{"_id": "d1", "text": "def writeBoolean(self, n):\n        \"\"\"\n        Writes a Boolean to the stream.\n        \"\"\"\n        t = TYPE_BOOL_TRUE\n\n        if n is False:\n            t = TYPE_BOOL_FALSE\n\n        self.stream.write(t)", "title": ""}
{"_id": "d2", "text": "def paste(xsel=False):\n    \"\"\"Returns system clipboard contents.\"\"\"\n    selection = \"primary\" if xsel else \"clipboard\"\n    try:\n        return subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"utf-8\")\n    except OSError as why:\n        raise XclipNotFound", "title": ""}
{"_id": "d3", "text": "def _format_json(data, theme):\n    \"\"\"Pretty print a dict as a JSON, with colors if pygments is present.\"\"\"\n    output = json.dumps(data, indent=2, sort_keys=True)\n\n    if pygments and sys.stdout.isatty():\n        style = get_style_by_name(theme)\n        formatter = Terminal256Formatter(style=style)\n        return pygments.highlight(output, JsonLexer(), formatter)\n\n    return output", "title": ""}
{"_id": "d4", "text": "def create_path(path):\n    \"\"\"Creates a absolute path in the file system.\n\n    :param path: The path to be created\n    \"\"\"\n    import os\n    if not os.path.exists(path):\n        os.makedirs(path)", "title": ""}
{"_id": "d5", "text": "def _vector_or_scalar(x, type='row'):\n    \"\"\"Convert an object to either a scalar or a row or column vector.\"\"\"\n    if isinstance(x, (list, tuple)):\n        x = np.array(x)\n    if isinstance(x, np.ndarray):\n        assert x.ndim == 1\n        if type == 'column':\n            x = x[:, None]\n    return x", "title": ""}
{"_id": "d6", "text": "def experiment_property(prop):\n    \"\"\"Get a property of the experiment by name.\"\"\"\n    exp = experiment(session)\n    p = getattr(exp, prop)\n    return success_response(field=prop, data=p, request_type=prop)", "title": ""}
{"_id": "d7", "text": "def data_from_file(file):\n    \"\"\"Return (first channel data, sample frequency, sample width) from a .wav\n    file.\"\"\"\n    fp = wave.open(file, 'r')\n    data = fp.readframes(fp.getnframes())\n    channels = fp.getnchannels()\n    freq = fp.getframerate()\n    bits = fp.getsampwidth()\n\n    # Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32\n    # bit not supported.\n    data = struct.unpack(('%sh' % fp.getnframes()) * channels, data)\n\n    # Only use first channel\n    channel1 = []\n    n = 0\n    for d in data:\n        if n % channels == 0:\n            channel1.append(d)\n        n += 1\n    fp.close()\n    return (channel1, freq, bits)", "title": ""}
{"_id": "d8", "text": "def source_range(start, end, nr_var_dict):\n    \"\"\"\n    Given a range of source numbers, as well as a dictionary\n    containing the numbers of each source, returns a dictionary\n    containing tuples of the start and end index\n    for each source variable type.\n    \"\"\"\n\n    return OrderedDict((k, e-s)\n        for k, (s, e)\n        in source_range_tuple(start, end, nr_var_dict).iteritems())", "title": ""}
{"_id": "d9", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d10", "text": "def _convert_to_array(array_like, dtype):\n        \"\"\"\n        Convert Matrix attributes which are array-like or buffer to array.\n        \"\"\"\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)", "title": ""}
{"_id": "d11", "text": "def get_uniques(l):\n    \"\"\" Returns a list with no repeated elements.\n    \"\"\"\n    result = []\n\n    for i in l:\n        if i not in result:\n            result.append(i)\n\n    return result", "title": ""}
{"_id": "d12", "text": "def interp(x, xp, *args, **kwargs):\n    \"\"\"Wrap interpolate_1d for deprecated interp.\"\"\"\n    return interpolate_1d(x, xp, *args, **kwargs)", "title": ""}
{"_id": "d13", "text": "def _array2cstr(arr):\n    \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())", "title": ""}
{"_id": "d14", "text": "def percentile(values, k):\n    \"\"\"Find the percentile of a list of values.\n\n    :param list values: The list of values to find the percentile of\n    :param int k: The percentile to find\n    :rtype: float or int\n\n    \"\"\"\n    if not values:\n        return None\n    values.sort()\n    index = (len(values) * (float(k) / 100)) - 1\n    return values[int(math.ceil(index))]", "title": ""}
{"_id": "d15", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d16", "text": "def transform_from_rot_trans(R, t):\n    \"\"\"Transforation matrix from rotation matrix and translation vector.\"\"\"\n    R = R.reshape(3, 3)\n    t = t.reshape(3, 1)\n    return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))", "title": ""}
{"_id": "d17", "text": "def _encode_bool(name, value, dummy0, dummy1):\n    \"\"\"Encode a python boolean (True/False).\"\"\"\n    return b\"\\x08\" + name + (value and b\"\\x01\" or b\"\\x00\")", "title": ""}
{"_id": "d18", "text": "def transform_to_3d(points,normal,z=0):\n    \"\"\"Project points into 3d from 2d points.\"\"\"\n    d = np.cross(normal, (0, 0, 1))\n    M = rotation_matrix(d)\n    transformed_points = M.dot(points.T).T + z\n    return transformed_points", "title": ""}
{"_id": "d19", "text": "def _not(condition=None, **kwargs):\n    \"\"\"\n    Return the opposite of input condition.\n\n    :param condition: condition to process.\n\n    :result: not condition.\n    :rtype: bool\n    \"\"\"\n\n    result = True\n\n    if condition is not None:\n        result = not run(condition, **kwargs)\n\n    return result", "title": ""}
{"_id": "d20", "text": "def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE,\ncontent=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for forbidden access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=403)", "title": ""}
{"_id": "d21", "text": "def items(self, section_name):\n        \"\"\":return: list((option, value), ...) pairs of all items in the given section\"\"\"\n        return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']", "title": ""}
{"_id": "d22", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d23", "text": "def config_parser_to_dict(config_parser):\n    \"\"\"\n    Convert a ConfigParser to a dictionary.\n    \"\"\"\n    response = {}\n\n    for section in config_parser.sections():\n        for option in config_parser.options(section):\n            response.setdefault(section, {})[option] = config_parser.get(section, option)\n\n    return response", "title": ""}
{"_id": "d24", "text": "def __add__(self, other):\n        \"\"\"Handle the `+` operator.\"\"\"\n        return self._handle_type(other)(self.value + other.value)", "title": ""}
{"_id": "d25", "text": "def connect_mysql(host, port, user, password, database):\n    \"\"\"Connect to MySQL with retries.\"\"\"\n    return pymysql.connect(\n        host=host, port=port,\n        user=user, passwd=password,\n        db=database\n    )", "title": ""}
{"_id": "d26", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d27", "text": "def connect(url, username, password):\n    \"\"\"\n    Return a connected Bitbucket session\n    \"\"\"\n\n    bb_session = stashy.connect(url, username, password)\n\n    logger.info('Connected to: %s as %s', url, username)\n\n    return bb_session", "title": ""}
{"_id": "d28", "text": "def add_blank_row(self, label):\n        \"\"\"\n        Add a blank row with only an index value to self.df.\n        This is done inplace.\n        \"\"\"\n        col_labels = self.df.columns\n        blank_item = pd.Series({}, index=col_labels, name=label)\n        # use .loc to add in place (append won't do that)\n        self.df.loc[blank_item.name] = blank_item\n        return self.df", "title": ""}
{"_id": "d29", "text": "def teardown(self):\n        \"\"\"\n        Stop and remove the container if it exists.\n        \"\"\"\n        while self._http_clients:\n            self._http_clients.pop().close()\n        if self.created:\n            self.halt()", "title": ""}
{"_id": "d30", "text": "def dumped(text, level, indent=2):\n    \"\"\"Put curly brackets round an indented text\"\"\"\n    return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "title": ""}
{"_id": "d31", "text": "def context(self):\n        \"\"\"\n        Create a context manager that ensures code runs within action's context.\n\n        The action does NOT finish when the context is exited.\n        \"\"\"\n        parent = _ACTION_CONTEXT.set(self)\n        try:\n            yield self\n        finally:\n            _ACTION_CONTEXT.reset(parent)", "title": ""}
{"_id": "d32", "text": "def pformat(object, indent=1, width=80, depth=None):\n    \"\"\"Format a Python object into a pretty-printed representation.\"\"\"\n    return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)", "title": ""}
{"_id": "d33", "text": "def replace_sys_args(new_args):\n    \"\"\"Temporarily replace sys.argv with current arguments\n\n    Restores sys.argv upon exit of the context manager.\n    \"\"\"\n    # Replace sys.argv arguments\n    # for module import\n    old_args = sys.argv\n    sys.argv = new_args\n    try:\n        yield\n    finally:\n        sys.argv = old_args", "title": ""}
{"_id": "d34", "text": "def serialize(obj):\n    \"\"\"Takes a object and produces a dict-like representation\n\n    :param obj: the object to serialize\n    \"\"\"\n    if isinstance(obj, list):\n        return [serialize(o) for o in obj]\n    return GenericSerializer(ModelProviderImpl()).serialize(obj)", "title": ""}
{"_id": "d35", "text": "def advance_one_line(self):\n    \"\"\"Advances to next line.\"\"\"\n\n    current_line = self._current_token.line_number\n    while current_line == self._current_token.line_number:\n      self._current_token = ConfigParser.Token(*next(self._token_generator))", "title": ""}
{"_id": "d36", "text": "def generate_swagger_html(swagger_static_root, swagger_json_url):\n    \"\"\"\n    given a root directory for the swagger statics, and\n    a swagger json path, return back a swagger html designed\n    to use those values.\n    \"\"\"\n    tmpl = _get_template(\"swagger.html\")\n    return tmpl.render(\n        swagger_root=swagger_static_root, swagger_json_url=swagger_json_url\n    )", "title": ""}
{"_id": "d37", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d38", "text": "def __add__(self,other):\n        \"\"\"\n            If the number of columns matches, we can concatenate two LabeldMatrices\n            with the + operator.\n        \"\"\"\n        assert self.matrix.shape[1] == other.matrix.shape[1]\n        return LabeledMatrix(np.concatenate([self.matrix,other.matrix],axis=0),self.labels)", "title": ""}
{"_id": "d39", "text": "def get_line_flux(line_wave, wave, flux, **kwargs):\n    \"\"\"Interpolated flux at a given wavelength (calls np.interp).\"\"\"\n    return np.interp(line_wave, wave, flux, **kwargs)", "title": ""}
{"_id": "d40", "text": "def send(message, request_context=None, binary=False):\n    \"\"\"Sends a message to websocket.\n\n    :param str message: data to send\n\n    :param request_context:\n\n    :raises IOError: If unable to send a message.\n    \"\"\"\n    if binary:\n        return uwsgi.websocket_send_binary(message, request_context)\n\n    return uwsgi.websocket_send(message, request_context)", "title": ""}
{"_id": "d41", "text": "def get_number(s, cast=int):\n    \"\"\"\n    Try to get a number out of a string, and cast it.\n    \"\"\"\n    import string\n    d = \"\".join(x for x in str(s) if x in string.digits)\n    return cast(d)", "title": ""}
{"_id": "d42", "text": "def get_hline():\n    \"\"\" gets a horiztonal line \"\"\"\n    return Window(\n        width=LayoutDimension.exact(1),\n        height=LayoutDimension.exact(1),\n        content=FillControl('-', token=Token.Line))", "title": ""}
{"_id": "d43", "text": "def parse_cookies_str(cookies):\n    \"\"\"\n    parse cookies str to dict\n    :param cookies: cookies str\n    :type cookies: str\n    :return: cookie dict\n    :rtype: dict\n    \"\"\"\n    cookie_dict = {}\n    for record in cookies.split(\";\"):\n        key, value = record.strip().split(\"=\", 1)\n        cookie_dict[key] = value\n    return cookie_dict", "title": ""}
{"_id": "d44", "text": "def to_snake_case(name):\n    \"\"\" Given a name in camelCase return in snake_case \"\"\"\n    s1 = FIRST_CAP_REGEX.sub(r'\\1_\\2', name)\n    return ALL_CAP_REGEX.sub(r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d45", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d46", "text": "def wordfreq(text, is_filename=False):\n    \"\"\"Return a dictionary of words and word counts in a string.\"\"\"\n    if is_filename:\n        with open(text) as f:\n            text = f.read()\n    freqs = {}\n    for word in text.split():\n        lword = word.lower()\n        freqs[lword] = freqs.get(lword, 0) + 1\n    return freqs", "title": ""}
{"_id": "d47", "text": "def copyFile(input, output, replace=None):\n    \"\"\"Copy a file whole from input to output.\"\"\"\n\n    _found = findFile(output)\n    if not _found or (_found and replace):\n        shutil.copy2(input, output)", "title": ""}
{"_id": "d48", "text": "def push(h, x):\n    \"\"\"Push a new value into heap.\"\"\"\n    h.push(x)\n    up(h, h.size()-1)", "title": ""}
{"_id": "d49", "text": "def yank(event):\n    \"\"\"\n    Paste before cursor.\n    \"\"\"\n    event.current_buffer.paste_clipboard_data(\n        event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)", "title": ""}
{"_id": "d50", "text": "def filter_contour(imageFile, opFile):\n    \"\"\" convert an image by applying a contour \"\"\"\n    im = Image.open(imageFile)\n    im1 = im.filter(ImageFilter.CONTOUR)\n    im1.save(opFile)", "title": ""}
{"_id": "d51", "text": "def count(lines):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  words = [w for l in lines for w in l.strip().split()]\n  return Counter(words)", "title": ""}
{"_id": "d52", "text": "def dictapply(d, fn):\n    \"\"\"\n    apply a function to all non-dict values in a dictionary\n    \"\"\"\n    for k, v in d.items():\n        if isinstance(v, dict):\n            v = dictapply(v, fn)\n        else:\n            d[k] = fn(v)\n    return d", "title": ""}
{"_id": "d53", "text": "def count_replica(self, partition):\n        \"\"\"Return count of replicas of given partition.\"\"\"\n        return sum(1 for b in partition.replicas if b in self.brokers)", "title": ""}
{"_id": "d54", "text": "def visit_Name(self, node):\n        \"\"\" Get range for parameters for examples or false branching. \"\"\"\n        return self.add(node, self.result[node.id])", "title": ""}
{"_id": "d55", "text": "def mkdir(dir, enter):\n    \"\"\"Create directory with template for topic of the current environment\n\n    \"\"\"\n\n    if not os.path.exists(dir):\n        os.makedirs(dir)", "title": ""}
{"_id": "d56", "text": "def qrot(vector, quaternion):\n    \"\"\"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\n\n    \"\"\"\n    t = 2 * np.cross(quaternion[1:], vector)\n    v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t)\n    return v_rot", "title": ""}
{"_id": "d57", "text": "def _numpy_char_to_bytes(arr):\n    \"\"\"Like netCDF4.chartostring, but faster and more flexible.\n    \"\"\"\n    # based on: http://stackoverflow.com/a/10984878/809705\n    arr = np.array(arr, copy=False, order='C')\n    dtype = 'S' + str(arr.shape[-1])\n    return arr.view(dtype).reshape(arr.shape[:-1])", "title": ""}
{"_id": "d58", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d59", "text": "def csv_to_dicts(file, header=None):\n    \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n    with open(file) as csvfile:\n        return [row for row in csv.DictReader(csvfile, fieldnames=header)]", "title": ""}
{"_id": "d60", "text": "def get_tri_area(pts):\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d61", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d62", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d63", "text": "def create_object(cls, members):\n    \"\"\"Promise an object of class `cls` with content `members`.\"\"\"\n    obj = cls.__new__(cls)\n    obj.__dict__ = members\n    return obj", "title": ""}
{"_id": "d64", "text": "def to_unicode_repr( _letter ):\n    \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n        in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n    # Python 2-3 compatible\n    return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"", "title": ""}
{"_id": "d65", "text": "def create_path(path):\n    \"\"\"Creates a absolute path in the file system.\n\n    :param path: The path to be created\n    \"\"\"\n    import os\n    if not os.path.exists(path):\n        os.makedirs(path)", "title": ""}
{"_id": "d66", "text": "def string_input(prompt=''):\n    \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n    v = sys.version[0]\n    if v == '3':\n        return input(prompt)\n    else:\n        return raw_input(prompt)", "title": ""}
{"_id": "d67", "text": "def cfloat64_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\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')", "title": ""}
{"_id": "d68", "text": "def yn_prompt(msg, default=True):\n    \"\"\"\n    Prompts the user for yes or no.\n    \"\"\"\n    ret = custom_prompt(msg, [\"y\", \"n\"], \"y\" if default else \"n\")\n    if ret == \"y\":\n        return True\n    return False", "title": ""}
{"_id": "d69", "text": "def _display(self, layout):\n        \"\"\"launch layouts display\"\"\"\n        print(file=self.out)\n        TextWriter().format(layout, self.out)", "title": ""}
{"_id": "d70", "text": "def assert_list(self, putative_list, expected_type=string_types, key_arg=None):\n    \"\"\"\n    :API: public\n    \"\"\"\n    return assert_list(putative_list, expected_type, key_arg=key_arg,\n                       raise_type=lambda msg: TargetDefinitionException(self, msg))", "title": ""}
{"_id": "d71", "text": "def _xxrange(self, start, end, step_count):\n        \"\"\"Generate n values between start and end.\"\"\"\n        _step = (end - start) / float(step_count)\n        return (start + (i * _step) for i in xrange(int(step_count)))", "title": ""}
{"_id": "d72", "text": "def assert_exactly_one_true(bool_list):\n    \"\"\"This method asserts that only one value of the provided list is True.\n\n    :param bool_list: List of booleans to check\n    :return: True if only one value is True, False otherwise\n    \"\"\"\n    assert isinstance(bool_list, list)\n    counter = 0\n    for item in bool_list:\n        if item:\n            counter += 1\n    return counter == 1", "title": ""}
{"_id": "d73", "text": "def _get_random_id():\n    \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n    symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(symbols) for _ in range(15))", "title": ""}
{"_id": "d74", "text": "async def list(source):\n    \"\"\"Generate a single list from an asynchronous sequence.\"\"\"\n    result = []\n    async with streamcontext(source) as streamer:\n        async for item in streamer:\n            result.append(item)\n    yield result", "title": ""}
{"_id": "d75", "text": "def csv_to_dicts(file, header=None):\n    \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n    with open(file) as csvfile:\n        return [row for row in csv.DictReader(csvfile, fieldnames=header)]", "title": ""}
{"_id": "d76", "text": "def _attrprint(d, delimiter=', '):\n    \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n    return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))", "title": ""}
{"_id": "d77", "text": "def get_next_scheduled_time(cron_string):\n    \"\"\"Calculate the next scheduled time by creating a crontab object\n    with a cron string\"\"\"\n    itr = croniter.croniter(cron_string, datetime.utcnow())\n    return itr.get_next(datetime)", "title": ""}
{"_id": "d78", "text": "def exit(exit_code=0):\n  r\"\"\"A function to support exiting from exit hooks.\n\n  Could also be used to exit from the calling scripts in a thread safe manner.\n  \"\"\"\n  core.processExitHooks()\n\n  if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook\n    sys.stderr.flush()\n    sys.stdout.flush()\n    os._exit(exit_code) #pylint: disable=W0212\n\n  sys.exit(exit_code)", "title": ""}
{"_id": "d79", "text": "def dot_product(self, other):\n        \"\"\" Return the dot product of the given vectors. \"\"\"\n        return self.x * other.x + self.y * other.y", "title": ""}
{"_id": "d80", "text": "def reloader_thread(softexit=False):\n    \"\"\"If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit``\n    will be used to end the process.\n    \"\"\"\n    while RUN_RELOADER:\n        if code_changed():\n            # force reload\n            if softexit:\n                sys.exit(3)\n            else:\n                os._exit(3)\n        time.sleep(1)", "title": ""}
{"_id": "d81", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d82", "text": "def average(iterator):\n    \"\"\"Iterative mean.\"\"\"\n    count = 0\n    total = 0\n    for num in iterator:\n        count += 1\n        total += num\n    return float(total)/count", "title": ""}
{"_id": "d83", "text": "def cint32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):\n        return np.fromiter(cptr, dtype=np.int32, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d84", "text": "def _aws_get_instance_by_tag(region, name, tag, raw):\n    \"\"\"Get all instances matching a tag.\"\"\"\n    client = boto3.session.Session().client('ec2', region)\n    matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', [])\n    instances = []\n    [[instances.append(_aws_instance_from_dict(region, instance, raw))  # pylint: disable=expression-not-assigned\n      for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation]\n    return instances", "title": ""}
{"_id": "d85", "text": "def cfloat64_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\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')", "title": ""}
{"_id": "d86", "text": "def loganalytics_data_plane_client(cli_ctx, _):\n    \"\"\"Initialize Log Analytics data client for use with CLI.\"\"\"\n    from .vendored_sdks.loganalytics import LogAnalyticsDataClient\n    from azure.cli.core._profile import Profile\n    profile = Profile(cli_ctx=cli_ctx)\n    cred, _, _ = profile.get_login_credentials(\n        resource=\"https://api.loganalytics.io\")\n    return LogAnalyticsDataClient(cred)", "title": ""}
{"_id": "d87", "text": "def cfloat32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n        return np.fromiter(cptr, dtype=np.float32, count=length)\n    else:\n        raise RuntimeError('Expected float pointer')", "title": ""}
{"_id": "d88", "text": "def underscore(text):\n    \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n    return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()", "title": ""}
{"_id": "d89", "text": "def cint8_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):\n        return np.fromiter(cptr, dtype=np.int8, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d90", "text": "def get_stoplist(language):\n    \"\"\"Returns an built-in stop-list for the language as a set of words.\"\"\"\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\n    return frozenset(w.decode(\"utf8\").lower() for w in stopwords.splitlines())", "title": ""}
{"_id": "d91", "text": "def add_str(window, line_num, str):\n    \"\"\" attempt to draw str on screen and ignore errors if they occur \"\"\"\n    try:\n        window.addstr(line_num, 0, str)\n    except curses.error:\n        pass", "title": ""}
{"_id": "d92", "text": "def relative_path(path):\n    \"\"\"\n    Return the given path relative to this file.\n    \"\"\"\n    return os.path.join(os.path.dirname(__file__), path)", "title": ""}
{"_id": "d93", "text": "def dictfetchall(cursor):\n    \"\"\"Returns all rows from a cursor as a dict (rather than a headerless table)\n\n    From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/\n    \"\"\"\n    desc = cursor.description\n    return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]", "title": ""}
{"_id": "d94", "text": "def xmltreefromfile(filename):\n    \"\"\"Internal function to read an XML file\"\"\"\n    try:\n        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n    except TypeError:\n        return ElementTree.parse(filename, ElementTree.XMLParser())", "title": ""}
{"_id": "d95", "text": "def _dictfetchall(self, cursor):\n        \"\"\" Return all rows from a cursor as a dict. \"\"\"\n        columns = [col[0] for col in cursor.description]\n        return [\n            dict(zip(columns, row))\n            for row in cursor.fetchall()\n        ]", "title": ""}
{"_id": "d96", "text": "def beta_pdf(x, a, b):\n  \"\"\"Beta distirbution probability density function.\"\"\"\n  bc = 1 / beta(a, b)\n  fc = x ** (a - 1)\n  sc = (1 - x) ** (b - 1)\n  return bc * fc * sc", "title": ""}
{"_id": "d97", "text": "def filter_out(queryset, setting_name):\n  \"\"\"\n  Remove unwanted results from queryset\n  \"\"\"\n  kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})\n  queryset = queryset.exclude(**kwargs)\n  return queryset", "title": ""}
{"_id": "d98", "text": "def intToBin(i):\n    \"\"\" Integer to two bytes \"\"\"\n    # divide in two parts (bytes)\n    i1 = i % 256\n    i2 = int(i / 256)\n    # make string (little endian)\n    return i.to_bytes(2, byteorder='little')", "title": ""}
{"_id": "d99", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d100", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d101", "text": "def pdf(x, mu, std):\n    \"\"\"Probability density function (normal distribution)\"\"\"\n    return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))", "title": ""}
{"_id": "d102", "text": "def bytes_to_c_array(data):\n    \"\"\"\n    Make a C array using the given string.\n    \"\"\"\n    chars = [\n        \"'{}'\".format(encode_escape(i))\n        for i in decode_escape(data)\n    ]\n    return ', '.join(chars) + ', 0'", "title": ""}
{"_id": "d103", "text": "def gray2bgr(img):\n    \"\"\"Convert a grayscale image to BGR image.\n\n    Args:\n        img (ndarray or str): The input image.\n\n    Returns:\n        ndarray: The converted BGR image.\n    \"\"\"\n    img = img[..., None] if img.ndim == 2 else img\n    out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n    return out_img", "title": ""}
{"_id": "d104", "text": "def mean_date(dt_list):\n    \"\"\"Calcuate mean datetime from datetime list\n    \"\"\"\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", "title": ""}
{"_id": "d105", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d106", "text": "def similarity(self, other):\n        \"\"\"Calculates the cosine similarity between this vector and another\n        vector.\"\"\"\n        if self.magnitude == 0 or other.magnitude == 0:\n            return 0\n\n        return self.dot(other) / self.magnitude", "title": ""}
{"_id": "d107", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d108", "text": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "title": ""}
{"_id": "d109", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d110", "text": "def direct2dDistance(self, point):\n        \"\"\"consider the distance between two mapPoints, ignoring all terrain, pathing issues\"\"\"\n        if not isinstance(point, MapPoint): return 0.0\n        return  ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula", "title": ""}
{"_id": "d111", "text": "def _model_unique(ins):\n    \"\"\" Get unique constraints info\n\n    :type ins: sqlalchemy.orm.mapper.Mapper\n    :rtype: list[tuple[str]]\n    \"\"\"\n    unique = []\n    for t in ins.tables:\n        for c in t.constraints:\n            if isinstance(c, UniqueConstraint):\n                unique.append(tuple(col.key for col in c.columns))\n    return unique", "title": ""}
{"_id": "d112", "text": "def horz_dpi(self):\n        \"\"\"\n        Integer dots per inch for the width of this image. Defaults to 72\n        when not present in the file, as is often the case.\n        \"\"\"\n        pHYs = self._chunks.pHYs\n        if pHYs is None:\n            return 72\n        return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)", "title": ""}
{"_id": "d113", "text": "def parse(self, s):\n        \"\"\"\n        Parses a date string formatted like ``YYYY-MM-DD``.\n        \"\"\"\n        return datetime.datetime.strptime(s, self.date_format).date()", "title": ""}
{"_id": "d114", "text": "def estimate_complexity(self, x,y,z,n):\n        \"\"\" \n        calculates a rough guess of runtime based on product of parameters \n        \"\"\"\n        num_calculations = x * y * z * n\n        run_time = num_calculations / 100000  # a 2014 PC does about 100k calcs in a second (guess based on prior logs)\n        return self.show_time_as_short_string(run_time)", "title": ""}
{"_id": "d115", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d116", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d117", "text": "def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):\n    \"\"\"Returns a generator which creates the next value in the range on demand\"\"\"\n    date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper)\n    current = start if start in date_interval else start + delta\n    while current in date_interval:\n        yield current\n        current = current + delta", "title": ""}
{"_id": "d118", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d119", "text": "def start_of_month(val):\n    \"\"\"\n    Return a new datetime.datetime object with values that represent\n    a start of a month.\n    :param val: Date to ...\n    :type val: datetime.datetime | datetime.date\n    :rtype: datetime.datetime\n    \"\"\"\n    if type(val) == date:\n        val = datetime.fromordinal(val.toordinal())\n    return start_of_day(val).replace(day=1)", "title": ""}
{"_id": "d120", "text": "def check_output(args, env=None, sp=subprocess):\n    \"\"\"Call an external binary and return its stdout.\"\"\"\n    log.debug('calling %s with env %s', args, env)\n    output = sp.check_output(args=args, env=env)\n    log.debug('output: %r', output)\n    return output", "title": ""}
{"_id": "d121", "text": "def datetime_to_ms(dt):\n    \"\"\"\n    Converts a datetime to a millisecond accuracy timestamp\n    \"\"\"\n    seconds = calendar.timegm(dt.utctimetuple())\n    return seconds * 1000 + int(dt.microsecond / 1000)", "title": ""}
{"_id": "d122", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d123", "text": "def datetime_to_timezone(date, tz=\"UTC\"):\n    \"\"\" convert naive datetime to timezone-aware datetime \"\"\"\n    if not date.tzinfo:\n        date = date.replace(tzinfo=timezone(get_timezone()))\n    return date.astimezone(timezone(tz))", "title": ""}
{"_id": "d124", "text": "def test(*args):\n    \"\"\"\n    Run unit tests.\n    \"\"\"\n    subprocess.call([\"py.test-2.7\"] + list(args))\n    subprocess.call([\"py.test-3.4\"] + list(args))", "title": ""}
{"_id": "d125", "text": "def ToDatetime(self):\n    \"\"\"Converts Timestamp to datetime.\"\"\"\n    return datetime.utcfromtimestamp(\n        self.seconds + self.nanos / float(_NANOS_PER_SECOND))", "title": ""}
{"_id": "d126", "text": "def sortable_title(instance):\n    \"\"\"Uses the default Plone sortable_text index lower-case\n    \"\"\"\n    title = plone_sortable_title(instance)\n    if safe_callable(title):\n        title = title()\n    return title.lower()", "title": ""}
{"_id": "d127", "text": "def localize(dt):\n    \"\"\"Localize a datetime object to local time.\"\"\"\n    if dt.tzinfo is UTC:\n        return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)\n    # No TZ info so not going to assume anything, return as-is.\n    return dt", "title": ""}
{"_id": "d128", "text": "def percent_cb(name, complete, total):\n    \"\"\" Callback for updating target progress \"\"\"\n    logger.debug(\n        \"{}: {} transferred out of {}\".format(\n            name, sizeof_fmt(complete), sizeof_fmt(total)\n        )\n    )\n    progress.update_target(name, complete, total)", "title": ""}
{"_id": "d129", "text": "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()", "title": ""}
{"_id": "d130", "text": "def to_pascal_case(s):\n    \"\"\"Transform underscore separated string to pascal case\n\n    \"\"\"\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())", "title": ""}
{"_id": "d131", "text": "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()", "title": ""}
{"_id": "d132", "text": "def _convert_date_to_dict(field_date):\n        \"\"\"\n        Convert native python ``datetime.date`` object  to a format supported by the API\n        \"\"\"\n        return {DAY: field_date.day, MONTH: field_date.month, YEAR: field_date.year}", "title": ""}
{"_id": "d133", "text": "def ToDatetime(self):\n    \"\"\"Converts Timestamp to datetime.\"\"\"\n    return datetime.utcfromtimestamp(\n        self.seconds + self.nanos / float(_NANOS_PER_SECOND))", "title": ""}
{"_id": "d134", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d135", "text": "def parse_timestamp(timestamp):\n    \"\"\"Parse ISO8601 timestamps given by github API.\"\"\"\n    dt = dateutil.parser.parse(timestamp)\n    return dt.astimezone(dateutil.tz.tzutc())", "title": ""}
{"_id": "d136", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d137", "text": "def fromtimestamp(cls, timestamp):\n    \"\"\"Returns a datetime object of a given timestamp (in local tz).\"\"\"\n    d = cls.utcfromtimestamp(timestamp)\n    return d.astimezone(localtz())", "title": ""}
{"_id": "d138", "text": "def print_latex(o):\n    \"\"\"A function to generate the latex representation of sympy\n    expressions.\"\"\"\n    if can_print_latex(o):\n        s = latex(o, mode='plain')\n        s = s.replace('\\\\dag','\\\\dagger')\n        s = s.strip('$')\n        return '$$%s$$' % s\n    # Fallback to the string printer\n    return None", "title": ""}
{"_id": "d139", "text": "def datetime64_to_datetime(dt):\n    \"\"\" convert numpy's datetime64 to datetime \"\"\"\n    dt64 = np.datetime64(dt)\n    ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')\n    return datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d140", "text": "def batch_tensor(self, name):\n        \"\"\" A buffer of a given value in a 'flat' (minibatch-indexed) format \"\"\"\n        if name in self.transition_tensors:\n            return tensor_util.merge_first_two_dims(self.transition_tensors[name])\n        else:\n            return self.rollout_tensors[name]", "title": ""}
{"_id": "d141", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d142", "text": "def create_symlink(source, link_name):\n    \"\"\"\n    Creates symbolic link for either operating system.\n\n    http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows\n    \"\"\"\n    os_symlink = getattr(os, \"symlink\", None)\n    if isinstance(os_symlink, collections.Callable):\n        os_symlink(source, link_name)\n    else:\n        import ctypes\n        csl = ctypes.windll.kernel32.CreateSymbolicLinkW\n        csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n        csl.restype = ctypes.c_ubyte\n        flags = 1 if os.path.isdir(source) else 0\n        if csl(link_name, source, flags) == 0:\n            raise ctypes.WinError()", "title": ""}
{"_id": "d143", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d144", "text": "def parse(source, remove_comments=True, **kw):\n    \"\"\"Thin wrapper around ElementTree.parse\"\"\"\n    return ElementTree.parse(source, SourceLineParser(), **kw)", "title": ""}
{"_id": "d145", "text": "def decorator(func):\n  r\"\"\"Makes the passed decorators to support optional args.\n  \"\"\"\n  def wrapper(__decorated__=None, *Args, **KwArgs):\n    if __decorated__ is None: # the decorator has some optional arguments.\n      return lambda _func: func(_func, *Args, **KwArgs)\n\n    else:\n      return func(__decorated__, *Args, **KwArgs)\n\n  return wrap(wrapper, func)", "title": ""}
{"_id": "d146", "text": "def show_image(self, key):\n        \"\"\"Show image (item is a PIL image)\"\"\"\n        data = self.model.get_data()\n        data[key].show()", "title": ""}
{"_id": "d147", "text": "def get_default_args(func):\n    \"\"\"\n    returns a dictionary of arg_name:default_values for the input function\n    \"\"\"\n    args, varargs, keywords, defaults = getargspec_no_self(func)\n    return dict(zip(args[-len(defaults):], defaults))", "title": ""}
{"_id": "d148", "text": "def _interval_to_bound_points(array):\n    \"\"\"\n    Helper function which returns an array\n    with the Intervals' boundaries.\n    \"\"\"\n\n    array_boundaries = np.array([x.left for x in array])\n    array_boundaries = np.concatenate(\n        (array_boundaries, np.array([array[-1].right])))\n\n    return array_boundaries", "title": ""}
{"_id": "d149", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d150", "text": "def test():        \n    \"\"\"Local test.\"\"\"\n    from spyder.utils.qthelpers import qapplication\n    app = qapplication()\n    dlg = ProjectDialog(None)\n    dlg.show()\n    sys.exit(app.exec_())", "title": ""}
{"_id": "d151", "text": "def del_label(self, name):\n        \"\"\"Delete a label by name.\"\"\"\n        labels_tag = self.root[0]\n        labels_tag.remove(self._find_label(name))", "title": ""}
{"_id": "d152", "text": "def mixedcase(path):\n    \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n    words = path.split('_')\n    return words[0] + ''.join(word.title() for word in words[1:])", "title": ""}
{"_id": "d153", "text": "def delete_all_eggs(self):\n        \"\"\" delete all the eggs in the directory specified \"\"\"\n        path_to_delete = os.path.join(self.egg_directory, \"lib\", \"python\")\n        if os.path.exists(path_to_delete):\n            shutil.rmtree(path_to_delete)", "title": ""}
{"_id": "d154", "text": "def get_system_cpu_times():\n    \"\"\"Return system CPU times as a namedtuple.\"\"\"\n    user, nice, system, idle = _psutil_osx.get_system_cpu_times()\n    return _cputimes_ntuple(user, nice, system, idle)", "title": ""}
{"_id": "d155", "text": "def remove(self, document_id, namespace, timestamp):\n        \"\"\"Removes documents from Solr\n\n        The input is a python dictionary that represents a mongo document.\n        \"\"\"\n        self.solr.delete(id=u(document_id),\n                         commit=(self.auto_commit_interval == 0))", "title": ""}
{"_id": "d156", "text": "def update_hash_from_str(hsh, str_input):\n    \"\"\"\n    Convert a str to object supporting buffer API and update a hash with it.\n    \"\"\"\n    byte_input = str(str_input).encode(\"UTF-8\")\n    hsh.update(byte_input)", "title": ""}
{"_id": "d157", "text": "def make_regex(separator):\n    \"\"\"Utility function to create regexp for matching escaped separators\n    in strings.\n\n    \"\"\"\n    return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +\n                      re.escape(separator) + r'\\\\]|\\\\.)+)')", "title": ""}
{"_id": "d158", "text": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "title": ""}
{"_id": "d159", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d160", "text": "def c_str(string):\n    \"\"\"\"Convert a python string to C string.\"\"\"\n    if not isinstance(string, str):\n        string = string.decode('ascii')\n    return ctypes.c_char_p(string.encode('utf-8'))", "title": ""}
{"_id": "d161", "text": "def endline_semicolon_check(self, original, loc, tokens):\n        \"\"\"Check for semicolons at the end of lines.\"\"\"\n        return self.check_strict(\"semicolon at end of line\", original, loc, tokens)", "title": ""}
{"_id": "d162", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d163", "text": "def get(self):\n        \"\"\"Get the highest priority Processing Block from the queue.\"\"\"\n        with self._mutex:\n            entry = self._queue.pop()\n            del self._block_map[entry[2]]\n            return entry[2]", "title": ""}
{"_id": "d164", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d165", "text": "def from_json(cls, json_str):\n        \"\"\"Deserialize the object from a JSON string.\"\"\"\n        d = json.loads(json_str)\n        return cls.from_dict(d)", "title": ""}
{"_id": "d166", "text": "def update(kernel=False):\n    \"\"\"\n    Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.\n\n    Exclude *kernel* upgrades by default.\n    \"\"\"\n    manager = MANAGER\n    cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}}\n    cmd = cmds[manager][kernel]\n    run_as_root(\"%(manager)s %(cmd)s\" % locals())", "title": ""}
{"_id": "d167", "text": "def guess_encoding(text, default=DEFAULT_ENCODING):\n    \"\"\"Guess string encoding.\n\n    Given a piece of text, apply character encoding detection to\n    guess the appropriate encoding of the text.\n    \"\"\"\n    result = chardet.detect(text)\n    return normalize_result(result, default=default)", "title": ""}
{"_id": "d168", "text": "def commajoin_as_strings(iterable):\n    \"\"\" Join the given iterable with ',' \"\"\"\n    return _(u',').join((six.text_type(i) for i in iterable))", "title": ""}
{"_id": "d169", "text": "def supports_color():\n    \"\"\"\n    Returns True if the running system's terminal supports color, and False\n    otherwise.\n    \"\"\"\n    unsupported_platform = (sys.platform in ('win32', 'Pocket PC'))\n    # isatty is not always implemented, #6223.\n    is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()\n    if unsupported_platform or not is_a_tty:\n        return False\n    return True", "title": ""}
{"_id": "d170", "text": "def seconds_to_hms(seconds):\n    \"\"\"\n    Converts seconds float to 'hh:mm:ss.ssssss' format.\n    \"\"\"\n    hours = int(seconds / 3600.0)\n    minutes = int((seconds / 60.0) % 60.0)\n    secs = float(seconds % 60.0)\n    return \"{0:02d}:{1:02d}:{2:02.6f}\".format(hours, minutes, secs)", "title": ""}
{"_id": "d171", "text": "def __contains__(self, key):\n        \"\"\"\n        Invoked when determining whether a specific key is in the dictionary\n        using `key in d`.\n\n        The key is looked up case-insensitively.\n        \"\"\"\n        k = self._real_key(key)\n        return k in self._data", "title": ""}
{"_id": "d172", "text": "def get_truetype(value):\n    \"\"\"Convert a string to a pythonized parameter.\"\"\"\n    if value in [\"true\", \"True\", \"y\", \"Y\", \"yes\"]:\n        return True\n    if value in [\"false\", \"False\", \"n\", \"N\", \"no\"]:\n        return False\n    if value.isdigit():\n        return int(value)\n    return str(value)", "title": ""}
{"_id": "d173", "text": "def Serializable(o):\n    \"\"\"Make sure an object is JSON-serializable\n    Use this to return errors and other info that does not need to be\n    deserialized or does not contain important app data. Best for returning\n    error info and such\"\"\"\n    if isinstance(o, (str, dict, int)):\n        return o\n    else:\n        try:\n            json.dumps(o)\n            return o\n        except Exception:\n            LOG.debug(\"Got a non-serilizeable object: %s\" % o)\n            return o.__repr__()", "title": ""}
{"_id": "d174", "text": "def timed_rotating_file_handler(name, logname, filename, when='h',\n                                interval=1, backupCount=0,\n                                encoding=None, delay=False, utc=False):\n    \"\"\"\n    A Bark logging handler logging output to a named file.  At\n    intervals specified by the 'when', the file will be rotated, under\n    control of 'backupCount'.\n\n    Similar to logging.handlers.TimedRotatingFileHandler.\n    \"\"\"\n\n    return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n        filename, when=when, interval=interval, backupCount=backupCount,\n        encoding=encoding, delay=delay, utc=utc))", "title": ""}
{"_id": "d175", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d176", "text": "def uniform_iterator(sequence):\n    \"\"\"Uniform (key, value) iteration on a `dict`,\n    or (idx, value) on a `list`.\"\"\"\n\n    if isinstance(sequence, abc.Mapping):\n        return six.iteritems(sequence)\n    else:\n        return enumerate(sequence)", "title": ""}
{"_id": "d177", "text": "def _guess_type(val):\n        \"\"\"Guess the input type of the parameter based off the default value, if unknown use text\"\"\"\n        if isinstance(val, bool):\n            return \"choice\"\n        elif isinstance(val, int):\n            return \"number\"\n        elif isinstance(val, float):\n            return \"number\"\n        elif isinstance(val, str):\n            return \"text\"\n        elif hasattr(val, 'read'):\n            return \"file\"\n        else:\n            return \"text\"", "title": ""}
{"_id": "d178", "text": "def _to_corrected_pandas_type(dt):\n    \"\"\"\n    When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n    This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n    \"\"\"\n    import numpy as np\n    if type(dt) == ByteType:\n        return np.int8\n    elif type(dt) == ShortType:\n        return np.int16\n    elif type(dt) == IntegerType:\n        return np.int32\n    elif type(dt) == FloatType:\n        return np.float32\n    else:\n        return None", "title": ""}
{"_id": "d179", "text": "def _platform_is_windows(platform=sys.platform):\n        \"\"\"Is the current OS a Windows?\"\"\"\n        matched = platform in ('cygwin', 'win32', 'win64')\n        if matched:\n            error_msg = \"Windows isn't supported yet\"\n            raise OSError(error_msg)\n        return matched", "title": ""}
{"_id": "d180", "text": "def _xls2col_widths(self, worksheet, tab):\n        \"\"\"Updates col_widths in code_array\"\"\"\n\n        for col in xrange(worksheet.ncols):\n            try:\n                xls_width = worksheet.colinfo_map[col].width\n                pys_width = self.xls_width2pys_width(xls_width)\n                self.code_array.col_widths[col, tab] = pys_width\n\n            except KeyError:\n                pass", "title": ""}
{"_id": "d181", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d182", "text": "def _bytes_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, bytes):\n        value = base64.standard_b64encode(value).decode(\"ascii\")\n    return value", "title": ""}
{"_id": "d183", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d184", "text": "def int_to_date(date):\n    \"\"\"\n    Convert an int of form yyyymmdd to a python date object.\n    \"\"\"\n\n    year = date // 10**4\n    month = date % 10**4 // 10**2\n    day = date % 10**2\n\n    return datetime.date(year, month, day)", "title": ""}
{"_id": "d185", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d186", "text": "def hasattrs(object, *names):\n    \"\"\"\n    Takes in an object and a variable length amount of named attributes,\n    and checks to see if the object has each property. If any of the\n    attributes are missing, this returns false.\n\n    :param object: an object that may or may not contain the listed attributes\n    :param names: a variable amount of attribute names to check for\n    :return: True if the object contains each named attribute, false otherwise\n    \"\"\"\n    for name in names:\n        if not hasattr(object, name):\n            return False\n    return True", "title": ""}
{"_id": "d187", "text": "def dict_update_newkeys(dict_, dict2):\n    \"\"\" Like dict.update, but does not overwrite items \"\"\"\n    for key, val in six.iteritems(dict2):\n        if key not in dict_:\n            dict_[key] = val", "title": ""}
{"_id": "d188", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d189", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d190", "text": "def _internet_on(address):\n    \"\"\"\n    Check to see if the internet is on by pinging a set address.\n    :param address: the IP or address to hit\n    :return: a boolean - true if can be reached, false if not.\n    \"\"\"\n    try:\n        urllib2.urlopen(address, timeout=1)\n        return True\n    except urllib2.URLError as err:\n        return False", "title": ""}
{"_id": "d191", "text": "def _defaultdict(dct, fallback=_illegal_character):\n    \"\"\"Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is\n    accessed.\n    \"\"\"\n    out = defaultdict(lambda: fallback)\n    for k, v in six.iteritems(dct):\n        out[k] = v\n    return out", "title": ""}
{"_id": "d192", "text": "def is_json_file(filename, show_warnings = False):\n    \"\"\"Check configuration file type is JSON\n    Return a boolean indicating wheather the file is JSON format or not\n    \"\"\"\n    try:\n        config_dict = load_config(filename, file_type = \"json\")\n        is_json = True\n    except:\n        is_json = False\n    return(is_json)", "title": ""}
{"_id": "d193", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d194", "text": "def post_commit_hook(argv):\n    \"\"\"Hook: for checking commit message.\"\"\"\n    _, stdout, _ = run(\"git log -1 --format=%B HEAD\")\n    message = \"\\n\".join(stdout)\n    options = {\"allow_empty\": True}\n\n    if not _check_message(message, options):\n        click.echo(\n            \"Commit message errors (fix with 'git commit --amend').\",\n            file=sys.stderr)\n        return 1  # it should not fail with exit\n    return 0", "title": ""}
{"_id": "d195", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d196", "text": "def is_image_file_valid(file_path_name):\n    \"\"\"\n    Indicate whether the specified image file is valid or not.\n\n\n    @param file_path_name: absolute path and file name of an image.\n\n\n    @return: ``True`` if the image file is valid, ``False`` if the file is\n        truncated or does not correspond to a supported image.\n    \"\"\"\n    # Image.verify is only implemented for PNG images, and it only verifies\n    # the CRC checksum in the image.  The only way to check from within\n    # Pillow is to load the image in a try/except and check the error.  If\n    # as much info as possible is from the image is needed,\n    # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it\n    # will attempt to parse as much as possible.\n    try:\n        with Image.open(file_path_name) as image:\n            image.load()\n    except IOError:\n        return False\n\n    return True", "title": ""}
{"_id": "d197", "text": "def dict_to_html_attrs(dict_):\n    \"\"\"\n    Banana banana\n    \"\"\"\n    res = ' '.join('%s=\"%s\"' % (k, v) for k, v in dict_.items())\n    return res", "title": ""}
{"_id": "d198", "text": "def is_binary(filename):\n    \"\"\" Returns True if the file is binary\n\n    \"\"\"\n    with open(filename, 'rb') as fp:\n        data = fp.read(1024)\n        if not data:\n            return False\n        if b'\\0' in data:\n            return True\n        return False", "title": ""}
{"_id": "d199", "text": "def dict_to_querystring(dictionary):\n    \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\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]", "title": ""}
{"_id": "d200", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d201", "text": "def dict_to_querystring(dictionary):\n    \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\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]", "title": ""}
{"_id": "d202", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d203", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d204", "text": "def is_element_present(driver, selector, by=By.CSS_SELECTOR):\n    \"\"\"\n    Returns whether the specified element selector is present 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 present)\n    \"\"\"\n    try:\n        driver.find_element(by=by, value=selector)\n        return True\n    except Exception:\n        return False", "title": ""}
{"_id": "d205", "text": "def updateFromKwargs(self, properties, kwargs, collector, **unused):\n        \"\"\"Primary entry point to turn 'kwargs' into 'properties'\"\"\"\n        properties[self.name] = self.getFromKwargs(kwargs)", "title": ""}
{"_id": "d206", "text": "def is_callable(*p):\n    \"\"\" True if all the args are functions and / or subroutines\n    \"\"\"\n    import symbols\n    return all(isinstance(x, symbols.FUNCTION) for x in p)", "title": ""}
{"_id": "d207", "text": "async def disconnect(self):\n        \"\"\" Disconnect from target. \"\"\"\n        if not self.connected:\n            return\n\n        self.writer.close()\n        self.reader = None\n        self.writer = None", "title": ""}
{"_id": "d208", "text": "def is_dataframe(obj):\n    \"\"\"\n    Returns True if the given object is a Pandas Data Frame.\n\n    Parameters\n    ----------\n    obj: instance\n        The object to test whether or not is a Pandas DataFrame.\n    \"\"\"\n    try:\n        # This is the best method of type checking\n        from pandas import DataFrame\n        return isinstance(obj, DataFrame)\n    except ImportError:\n        # Pandas is not a dependency, so this is scary\n        return obj.__class__.__name__ == \"DataFrame\"", "title": ""}
{"_id": "d209", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d210", "text": "def is_datetime_like(dtype):\n    \"\"\"Check if a dtype is a subclass of the numpy datetime types\n    \"\"\"\n    return (np.issubdtype(dtype, np.datetime64) or\n            np.issubdtype(dtype, np.timedelta64))", "title": ""}
{"_id": "d211", "text": "def serialize_json_string(self, value):\n        \"\"\"\n        Tries to load an encoded json string back into an object\n        :param json_string:\n        :return:\n        \"\"\"\n\n        # Check if the value might be a json string\n        if not isinstance(value, six.string_types):\n            return value\n\n        # Make sure it starts with a brace\n        if not value.startswith('{') or value.startswith('['):\n            return value\n\n        # Try to load the string\n        try:\n            return json.loads(value)\n        except:\n            return value", "title": ""}
{"_id": "d212", "text": "def is_defined(self, objtxt, force_import=False):\n        \"\"\"Return True if object is defined\"\"\"\n        return self.interpreter.is_defined(objtxt, force_import)", "title": ""}
{"_id": "d213", "text": "def get_hline():\n    \"\"\" gets a horiztonal line \"\"\"\n    return Window(\n        width=LayoutDimension.exact(1),\n        height=LayoutDimension.exact(1),\n        content=FillControl('-', token=Token.Line))", "title": ""}
{"_id": "d214", "text": "def group_exists(groupname):\n    \"\"\"Check if a group exists\"\"\"\n    try:\n        grp.getgrnam(groupname)\n        group_exists = True\n    except KeyError:\n        group_exists = False\n    return group_exists", "title": ""}
{"_id": "d215", "text": "def sync(self, recursive=False):\n        \"\"\"\n        Syncs the information from this item to the tree and view.\n        \"\"\"\n        self.syncTree(recursive=recursive)\n        self.syncView(recursive=recursive)", "title": ""}
{"_id": "d216", "text": "def is_same_shape(self, other_im, check_channels=False):\n        \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n        Parameters\n        ----------\n        other_im : :obj:`Image`\n            image to compare\n        check_channels : bool\n            whether or not to check equality of the channels\n\n        Returns\n        -------\n        bool\n            True if the images are the same shape, False otherwise\n        \"\"\"\n        if self.height == other_im.height and self.width == other_im.width:\n            if check_channels and self.channels != other_im.channels:\n                return False\n            return True\n        return False", "title": ""}
{"_id": "d217", "text": "def get_distance_between_two_points(self, one, two):\n        \"\"\"Returns the distance between two XYPoints.\"\"\"\n        dx = one.x - two.x\n        dy = one.y - two.y\n        return math.sqrt(dx * dx + dy * dy)", "title": ""}
{"_id": "d218", "text": "def is_same_shape(self, other_im, check_channels=False):\n        \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n        Parameters\n        ----------\n        other_im : :obj:`Image`\n            image to compare\n        check_channels : bool\n            whether or not to check equality of the channels\n\n        Returns\n        -------\n        bool\n            True if the images are the same shape, False otherwise\n        \"\"\"\n        if self.height == other_im.height and self.width == other_im.width:\n            if check_channels and self.channels != other_im.channels:\n                return False\n            return True\n        return False", "title": ""}
{"_id": "d219", "text": "def post_process(self):\n        \"\"\" Apply last 2D transforms\"\"\"\n        self.image.putdata(self.pixels)\n        self.image = self.image.transpose(Image.ROTATE_90)", "title": ""}
{"_id": "d220", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d221", "text": "def delete_all_from_db():\n    \"\"\"Clear the database.\n\n    Used for testing and debugging.\n\n    \"\"\"\n    # The models.CASCADE property is set on all ForeignKey fields, so tables can\n    # be deleted in any order without breaking constraints.\n    for model in django.apps.apps.get_models():\n        model.objects.all().delete()", "title": ""}
{"_id": "d222", "text": "def is_complex(dtype):\n  \"\"\"Returns whether this is a complex floating point type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_complex'):\n    return dtype.is_complex\n  return np.issubdtype(np.dtype(dtype), np.complex)", "title": ""}
{"_id": "d223", "text": "def delete(build_folder):\n    \"\"\"Delete build directory and all its contents.\n    \"\"\"\n    if _meta_.del_build in [\"on\", \"ON\"] and os.path.exists(build_folder):\n        shutil.rmtree(build_folder)", "title": ""}
{"_id": "d224", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d225", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d226", "text": "def _is_path(s):\n    \"\"\"Return whether an object is a path.\"\"\"\n    if isinstance(s, string_types):\n        try:\n            return op.exists(s)\n        except (OSError, ValueError):\n            return False\n    else:\n        return False", "title": ""}
{"_id": "d227", "text": "def see_doc(obj_with_doc):\n    \"\"\"Copy docstring from existing object to the decorated callable.\"\"\"\n    def decorator(fn):\n        fn.__doc__ = obj_with_doc.__doc__\n        return fn\n    return decorator", "title": ""}
{"_id": "d228", "text": "def isToneCal(self):\n        \"\"\"Whether the currently selected calibration stimulus type is the calibration curve\n\n        :returns: boolean -- if the current combo box selection is calibration curve\n        \"\"\"\n        return self.ui.calTypeCmbbx.currentIndex() == self.ui.calTypeCmbbx.count() -1", "title": ""}
{"_id": "d229", "text": "def hmsToDeg(h, m, s):\n    \"\"\"Convert RA hours, minutes, seconds into an angle in degrees.\"\"\"\n    return h * degPerHMSHour + m * degPerHMSMin + s * degPerHMSSec", "title": ""}
{"_id": "d230", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d231", "text": "def prepare(doc):\n    \"\"\"Sets the caption_found and plot_found variables to False.\"\"\"\n    doc.caption_found = False\n    doc.plot_found = False\n    doc.listings_counter = 0", "title": ""}
{"_id": "d232", "text": "def validate(key):\n    \"\"\"Check that the key is a string or bytestring.\n\n    That's the only valid type of key.\n    \"\"\"\n    if not isinstance(key, (str, bytes)):\n        raise KeyError('Key must be of type str or bytes, found type {}'.format(type(key)))", "title": ""}
{"_id": "d233", "text": "def _normal_prompt(self):\n        \"\"\"\n        Flushes the prompt before requesting the input\n\n        :return: The command line\n        \"\"\"\n        sys.stdout.write(self.__get_ps1())\n        sys.stdout.flush()\n        return safe_input()", "title": ""}
{"_id": "d234", "text": "def maxDepth(self, currentDepth=0):\n        \"\"\"Compute the depth of the longest branch of the tree\"\"\"\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", "title": ""}
{"_id": "d235", "text": "def from_rectangle(box):\n        \"\"\" Create a vector randomly within the given rectangle. \"\"\"\n        x = box.left + box.width * random.uniform(0, 1)\n        y = box.bottom + box.height * random.uniform(0, 1)\n        return Vector(x, y)", "title": ""}
{"_id": "d236", "text": "def launched():\n    \"\"\"Test whether the current python environment is the correct lore env.\n\n    :return:  :any:`True` if the environment is launched\n    :rtype: bool\n    \"\"\"\n    if not PREFIX:\n        return False\n\n    return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)", "title": ""}
{"_id": "d237", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d238", "text": "def is_sequence(obj):\n    \"\"\"Check if `obj` is a sequence, but not a string or bytes.\"\"\"\n    return isinstance(obj, Sequence) and not (\n        isinstance(obj, str) or BinaryClass.is_valid_type(obj))", "title": ""}
{"_id": "d239", "text": "def isnamedtuple(obj):\n    \"\"\"Heuristic check if an object is a namedtuple.\"\"\"\n    return isinstance(obj, tuple) \\\n           and hasattr(obj, \"_fields\") \\\n           and hasattr(obj, \"_asdict\") \\\n           and callable(obj._asdict)", "title": ""}
{"_id": "d240", "text": "def starts_with_prefix_in_list(text, prefixes):\n    \"\"\"\n    Return True if the given string starts with one of the prefixes in the given list, otherwise\n    return False.\n\n    Arguments:\n        text (str): Text to check for prefixes.\n        prefixes (list): List of prefixes to check for.\n\n    Returns:\n        bool: True if the given text starts with any of the given prefixes, otherwise False.\n    \"\"\"\n    for prefix in prefixes:\n        if text.startswith(prefix):\n            return True\n    return False", "title": ""}
{"_id": "d241", "text": "def print_yaml(o):\n    \"\"\"Pretty print an object as YAML.\"\"\"\n    print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))", "title": ""}
{"_id": "d242", "text": "def issuperset(self, other):\n        \"\"\"Report whether this RangeSet contains another set.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issuperset(self, other)", "title": ""}
{"_id": "d243", "text": "def deserialize_ndarray_npy(d):\n    \"\"\"\n    Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's\n    :obj:`save` function.\n\n    Args:\n        d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created\n            using :obj:`numpy.save`.\n\n    Returns:\n        An :obj:`ndarray` object.\n    \"\"\"\n    with io.BytesIO() as f:\n        f.write(json.loads(d['npy']).encode('latin-1'))\n        f.seek(0)\n        return np.load(f)", "title": ""}
{"_id": "d244", "text": "def check(text):\n    \"\"\"Check the text.\"\"\"\n    err = \"misc.currency\"\n    msg = u\"Incorrect use of symbols in {}.\"\n\n    symbols = [\n        \"\\$[\\d]* ?(?:dollars|usd|us dollars)\"\n    ]\n\n    return existence_check(text, symbols, err, msg)", "title": ""}
{"_id": "d245", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d246", "text": "def _map_table_name(self, model_names):\n        \"\"\"\n        Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,\n        tak si to namapujme\n        \"\"\"\n\n        for model in model_names:\n            if isinstance(model, tuple):\n                model = model[0]\n\n            try:\n                model_cls = getattr(self.models, model)\n                self.table_to_class[class_mapper(model_cls).tables[0].name] = model\n            except AttributeError:\n                pass", "title": ""}
{"_id": "d247", "text": "def service_available(service_name):\n    \"\"\"Determine whether a system service is available\"\"\"\n    try:\n        subprocess.check_output(\n            ['service', service_name, 'status'],\n            stderr=subprocess.STDOUT).decode('UTF-8')\n    except subprocess.CalledProcessError as e:\n        return b'unrecognized service' not in e.output\n    else:\n        return True", "title": ""}
{"_id": "d248", "text": "def keys(self):\n        \"\"\"Return a list of all keys in the dictionary.\n\n        Returns:\n            list of str: [key1,key2,...,keyN]\n        \"\"\"\n        all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]\n        return all_keys", "title": ""}
{"_id": "d249", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d250", "text": "def escape_tex(value):\n  \"\"\"\n  Make text tex safe\n  \"\"\"\n  newval = value\n  for pattern, replacement in LATEX_SUBS:\n    newval = pattern.sub(replacement, newval)\n  return newval", "title": ""}
{"_id": "d251", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d252", "text": "def update_index(index):\n    \"\"\"Re-index every document in a named index.\"\"\"\n    logger.info(\"Updating search index: '%s'\", index)\n    client = get_client()\n    responses = []\n    for model in get_index_models(index):\n        logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n        objects = model.objects.get_search_queryset(index).iterator()\n        actions = bulk_actions(objects, index=index, action=\"index\")\n        response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n        responses.append(response)\n    return responses", "title": ""}
{"_id": "d253", "text": "def is_datetime_like(dtype):\n    \"\"\"Check if a dtype is a subclass of the numpy datetime types\n    \"\"\"\n    return (np.issubdtype(dtype, np.datetime64) or\n            np.issubdtype(dtype, np.timedelta64))", "title": ""}
{"_id": "d254", "text": "def hidden_cursor(self):\n        \"\"\"Return a context manager that hides the cursor while inside it and\n        makes it visible on leaving.\"\"\"\n        self.stream.write(self.hide_cursor)\n        try:\n            yield\n        finally:\n            self.stream.write(self.normal_cursor)", "title": ""}
{"_id": "d255", "text": "def service_available(service_name):\n    \"\"\"Determine whether a system service is available\"\"\"\n    try:\n        subprocess.check_output(\n            ['service', service_name, 'status'],\n            stderr=subprocess.STDOUT).decode('UTF-8')\n    except subprocess.CalledProcessError as e:\n        return b'unrecognized service' not in e.output\n    else:\n        return True", "title": ""}
{"_id": "d256", "text": "def copy(doc, dest, src):\n    \"\"\"Copy element from sequence, member from mapping.\n\n    :param doc: the document base\n    :param dest: the destination\n    :type dest: Pointer\n    :param src: the source\n    :type src: Pointer\n    :return: the new object\n    \"\"\"\n\n    return Target(doc).copy(dest, src).document", "title": ""}
{"_id": "d257", "text": "def is_string(val):\n    \"\"\"Determines whether the passed value is a string, safe for 2/3.\"\"\"\n    try:\n        basestring\n    except NameError:\n        return isinstance(val, str)\n    return isinstance(val, basestring)", "title": ""}
{"_id": "d258", "text": "def read_from_file(file_path, encoding=\"utf-8\"):\n    \"\"\"\n    Read helper method\n\n    :type file_path: str|unicode\n    :type encoding: str|unicode\n    :rtype: str|unicode\n    \"\"\"\n    with codecs.open(file_path, \"r\", encoding) as f:\n        return f.read()", "title": ""}
{"_id": "d259", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d260", "text": "def _is_root():\n    \"\"\"Checks if the user is rooted.\"\"\"\n    import os\n    import ctypes\n    try:\n        return os.geteuid() == 0\n    except AttributeError:\n        return ctypes.windll.shell32.IsUserAnAdmin() != 0\n    return False", "title": ""}
{"_id": "d261", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d262", "text": "def describe_enum_value(enum_value):\n    \"\"\"Build descriptor for Enum instance.\n\n    Args:\n      enum_value: Enum value to provide descriptor for.\n\n    Returns:\n      Initialized EnumValueDescriptor instance describing the Enum instance.\n    \"\"\"\n    enum_value_descriptor = EnumValueDescriptor()\n    enum_value_descriptor.name = six.text_type(enum_value.name)\n    enum_value_descriptor.number = enum_value.number\n    return enum_value_descriptor", "title": ""}
{"_id": "d263", "text": "def user_in_all_groups(user, groups):\n    \"\"\"Returns True if the given user is in all given groups\"\"\"\n    return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)", "title": ""}
{"_id": "d264", "text": "def items(self):\n    \"\"\"Return a list of the (name, value) pairs of the enum.\n\n    These are returned in the order they were defined in the .proto file.\n    \"\"\"\n    return [(value_descriptor.name, value_descriptor.number)\n            for value_descriptor in self._enum_type.values]", "title": ""}
{"_id": "d265", "text": "def n_choose_k(n, k):\n    \"\"\" get the number of quartets as n-choose-k. This is used\n    in equal splits to decide whether a split should be exhaustively sampled\n    or randomly sampled. Edges near tips can be exhaustive while highly nested\n    edges probably have too many quartets\n    \"\"\"\n    return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1))", "title": ""}
{"_id": "d266", "text": "def items(cls):\n        \"\"\"\n        All values for this enum\n        :return: list of tuples\n\n        \"\"\"\n        return [\n            cls.PRECIPITATION,\n            cls.WIND,\n            cls.TEMPERATURE,\n            cls.PRESSURE\n        ]", "title": ""}
{"_id": "d267", "text": "def revnet_164_cifar():\n  \"\"\"Tiny hparams suitable for CIFAR/etc.\"\"\"\n  hparams = revnet_cifar_base()\n  hparams.bottleneck = True\n  hparams.num_channels = [16, 32, 64]\n  hparams.num_layers_per_block = [8, 8, 8]\n  return hparams", "title": ""}
{"_id": "d268", "text": "def items(cls):\n        \"\"\"\n        All values for this enum\n        :return: list of tuples\n\n        \"\"\"\n        return [\n            cls.PRECIPITATION,\n            cls.WIND,\n            cls.TEMPERATURE,\n            cls.PRESSURE\n        ]", "title": ""}
{"_id": "d269", "text": "def mtf_image_transformer_cifar_mp_4x():\n  \"\"\"Data parallel CIFAR parameters.\"\"\"\n  hparams = mtf_image_transformer_base_cifar()\n  hparams.mesh_shape = \"model:4;batch:8\"\n  hparams.layout = \"batch:batch;d_ff:model;heads:model\"\n  hparams.batch_size = 32\n  hparams.num_heads = 8\n  hparams.d_ff = 8192\n  return hparams", "title": ""}
{"_id": "d270", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d271", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d272", "text": "def _propagate_mean(mean, linop, dist):\n  \"\"\"Propagate a mean through linear Gaussian transformation.\"\"\"\n  return linop.matmul(mean) + dist.mean()[..., tf.newaxis]", "title": ""}
{"_id": "d273", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d274", "text": "def convertToBool():\n    \"\"\" Convert a byte value to boolean (0 or 1) if\n    the global flag strictBool is True\n    \"\"\"\n    if not OPTIONS.strictBool.value:\n        return []\n\n    REQUIRES.add('strictbool.asm')\n\n    result = []\n    result.append('pop af')\n    result.append('call __NORMALIZE_BOOLEAN')\n    result.append('push af')\n\n    return result", "title": ""}
{"_id": "d275", "text": "def normalize(x, min_value, max_value):\n    \"\"\"Normalize value between min and max values.\n    It also clips the values, so that you cannot have values higher or lower\n    than 0 - 1.\"\"\"\n    x = (x - min_value) / (max_value - min_value)\n    return clip(x, 0, 1)", "title": ""}
{"_id": "d276", "text": "def prepare_for_reraise(error, exc_info=None):\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d277", "text": "def close_all_but_this(self):\n        \"\"\"Close all files but the current one\"\"\"\n        self.close_all_right()\n        for i in range(0, self.get_stack_count()-1  ):\n            self.close_file(0)", "title": ""}
{"_id": "d278", "text": "def eval_in_system_namespace(self, exec_str):\n        \"\"\"\n            Get Callable for specified string (for GUI-based editing)\n        \"\"\"\n        ns = self.cmd_namespace\n        try:\n            return eval(exec_str, ns)\n        except Exception as e:\n            self.logger.warning('Could not execute %s, gave error %s', exec_str, e)\n            return None", "title": ""}
{"_id": "d279", "text": "def _close_socket(self):\n        \"\"\"Shutdown and close the Socket.\n\n        :return:\n        \"\"\"\n        try:\n            self.socket.shutdown(socket.SHUT_RDWR)\n        except (OSError, socket.error):\n            pass\n        self.socket.close()", "title": ""}
{"_id": "d280", "text": "def exec_function(ast, globals_map):\n    \"\"\"Execute a python code object in the given environment.\n\n    Args:\n      globals_map: Dictionary to use as the globals context.\n    Returns:\n      locals_map: Dictionary of locals from the environment after execution.\n    \"\"\"\n    locals_map = globals_map\n    exec ast in globals_map, locals_map\n    return locals_map", "title": ""}
{"_id": "d281", "text": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "title": ""}
{"_id": "d282", "text": "def get_unicode_str(obj):\n    \"\"\"Makes sure obj is a unicode string.\"\"\"\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)", "title": ""}
{"_id": "d283", "text": "def close_all_but_this(self):\n        \"\"\"Close all files but the current one\"\"\"\n        self.close_all_right()\n        for i in range(0, self.get_stack_count()-1  ):\n            self.close_file(0)", "title": ""}
{"_id": "d284", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d285", "text": "def _findNearest(arr, value):\n    \"\"\" Finds the value in arr that value is closest to\n    \"\"\"\n    arr = np.array(arr)\n    # find nearest value in array\n    idx = (abs(arr-value)).argmin()\n    return arr[idx]", "title": ""}
{"_id": "d286", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d287", "text": "def remove_examples_all():\n    \"\"\"remove arduino/examples/all directory.\n\n    :rtype: None\n\n    \"\"\"\n    d = examples_all_dir()\n    if d.exists():\n        log.debug('remove %s', d)\n        d.rmtree()\n    else:\n        log.debug('nothing to remove: %s', d)", "title": ""}
{"_id": "d288", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d289", "text": "def cli_command_quit(self, msg):\n        \"\"\"\\\n        kills the child and exits\n        \"\"\"\n        if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:\n            self.sprocess.proc.kill()\n        else:\n            sys.exit(0)", "title": ""}
{"_id": "d290", "text": "def dot(self, w):\n        \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n        return sum([x * y for x, y in zip(self, w)])", "title": ""}
{"_id": "d291", "text": "def printc(cls, txt, color=colors.red):\n        \"\"\"Print in color.\"\"\"\n        print(cls.color_txt(txt, color))", "title": ""}
{"_id": "d292", "text": "def need_update(a, b):\n    \"\"\"\n    Check if file a is newer than file b and decide whether or not to update\n    file b. Can generalize to two lists.\n    \"\"\"\n    a = listify(a)\n    b = listify(b)\n\n    return any((not op.exists(x)) for x in b) or \\\n           all((os.stat(x).st_size == 0 for x in b)) or \\\n           any(is_newer_file(x, y) for x in a for y in b)", "title": ""}
{"_id": "d293", "text": "def lengths( self ):\n        \"\"\"\n        The cell lengths.\n\n        Args:\n            None\n\n        Returns:\n            (np.array(a,b,c)): The cell lengths.\n        \"\"\"\n        return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) )", "title": ""}
{"_id": "d294", "text": "def random_str(size=10):\n    \"\"\"\n    create random string of selected size\n\n    :param size: int, length of the string\n    :return: the string\n    \"\"\"\n    return ''.join(random.choice(string.ascii_lowercase) for _ in range(size))", "title": ""}
{"_id": "d295", "text": "def get_table_columns(dbconn, tablename):\n    \"\"\"\n    Return a list of tuples specifying the column name and type\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n    info = cur.fetchall()\n    cols = [(i[1], i[2]) for i in info]\n    return cols", "title": ""}
{"_id": "d296", "text": "def remove_duplicates(lst):\n    \"\"\"\n    Emulate what a Python ``set()`` does, but keeping the element's order.\n    \"\"\"\n    dset = set()\n    return [l for l in lst if l not in dset and not dset.add(l)]", "title": ""}
{"_id": "d297", "text": "def _on_select(self, *args):\n        \"\"\"\n        Function bound to event of selection in the Combobox, calls callback if callable\n        \n        :param args: Tkinter event\n        \"\"\"\n        if callable(self.__callback):\n            self.__callback(self.selection)", "title": ""}
{"_id": "d298", "text": "def fft_spectrum(frames, fft_points=512):\n    \"\"\"This function computes the one-dimensional n-point discrete Fourier\n    Transform (DFT) of a real-valued array by means of an efficient algorithm\n    called the Fast Fourier Transform (FFT). Please refer to\n    https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft.html\n    for further details.\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 frame_len, the frames will be zero-padded.\n\n    Returns:\n            array: The fft spectrum.\n            If frames is an num_frames x sample_per_frame matrix, output\n            will be num_frames x FFT_LENGTH.\n    \"\"\"\n    SPECTRUM_VECTOR = np.fft.rfft(frames, n=fft_points, axis=-1, norm=None)\n    return np.absolute(SPECTRUM_VECTOR)", "title": ""}
{"_id": "d299", "text": "def isetdiff_flags(list1, list2):\n    \"\"\"\n    move to util_iter\n    \"\"\"\n    set2 = set(list2)\n    return (item not in set2 for item in list1)", "title": ""}
{"_id": "d300", "text": "def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None):\n    \"\"\" guess_file_class: determines what file the content is\n        Args:\n            filepath (str): filepath of file to check\n        Returns: string indicating file's class\n    \"\"\"\n    if youtube_id:\n        return FileTypes.YOUTUBE_VIDEO_FILE\n    elif web_url:\n        return FileTypes.WEB_VIDEO_FILE\n    elif encoding:\n        return FileTypes.BASE64_FILE\n    else:\n        ext = os.path.splitext(filepath)[1][1:].lower()\n        if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING[kind]:\n            return FILE_TYPE_MAPPING[kind][ext]\n    return None", "title": ""}
{"_id": "d301", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d302", "text": "def file_writelines_flush_sync(path, lines):\n    \"\"\"\n    Fill file at @path with @lines then flush all buffers\n    (Python and system buffers)\n    \"\"\"\n    fp = open(path, 'w')\n    try:\n        fp.writelines(lines)\n        flush_sync_file_object(fp)\n    finally:\n        fp.close()", "title": ""}
{"_id": "d303", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d304", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d305", "text": "def all_equal(arg1,arg2):\n    \"\"\"\n    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.\n    \"\"\"\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", "title": ""}
{"_id": "d306", "text": "def get_file_size(filename):\n    \"\"\"\n    Get the file size of a given file\n\n    :param filename: string: pathname of a file\n    :return: human readable filesize\n    \"\"\"\n    if os.path.isfile(filename):\n        return convert_size(os.path.getsize(filename))\n    return None", "title": ""}
{"_id": "d307", "text": "def _check_for_int(x):\n    \"\"\"\n    This is a compatibility function that takes a C{float} and converts it to an\n    C{int} if the values are equal.\n    \"\"\"\n    try:\n        y = int(x)\n    except (OverflowError, ValueError):\n        pass\n    else:\n        # There is no way in AMF0 to distinguish between integers and floats\n        if x == x and y == x:\n            return y\n\n    return x", "title": ""}
{"_id": "d308", "text": "def fill_form(form, data):\n    \"\"\"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.\n    \"\"\"\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", "title": ""}
{"_id": "d309", "text": "def check_clang_apply_replacements_binary(args):\n  \"\"\"Checks if invoking supplied clang-apply-replacements binary works.\"\"\"\n  try:\n    subprocess.check_call([args.clang_apply_replacements_binary, '--version'])\n  except:\n    print('Unable to run clang-apply-replacements. Is clang-apply-replacements '\n          'binary correctly specified?', file=sys.stderr)\n    traceback.print_exc()\n    sys.exit(1)", "title": ""}
{"_id": "d310", "text": "def _maybe_fill(arr, fill_value=np.nan):\n    \"\"\"\n    if we have a compatible fill_value and arr dtype, then fill\n    \"\"\"\n    if _isna_compat(arr, fill_value):\n        arr.fill(fill_value)\n    return arr", "title": ""}
{"_id": "d311", "text": "def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):\n    \"\"\"Extract a ALZIP archive.\"\"\"\n    return [cmd, '-d', outdir, archive]", "title": ""}
{"_id": "d312", "text": "def _maybe_fill(arr, fill_value=np.nan):\n    \"\"\"\n    if we have a compatible fill_value and arr dtype, then fill\n    \"\"\"\n    if _isna_compat(arr, fill_value):\n        arr.fill(fill_value)\n    return arr", "title": ""}
{"_id": "d313", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d314", "text": "def filter_(stream_spec, filter_name, *args, **kwargs):\n    \"\"\"Alternate name for ``filter``, so as to not collide with the\n    built-in python ``filter`` operator.\n    \"\"\"\n    return filter(stream_spec, filter_name, *args, **kwargs)", "title": ""}
{"_id": "d315", "text": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "title": ""}
{"_id": "d316", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x.\"\"\"\n    i = bs.bisect_left(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d317", "text": "def get_stationary_distribution(self):\n        \"\"\"Compute the stationary distribution of states.\n        \"\"\"\n        # The stationary distribution is proportional to the left-eigenvector\n        # associated with the largest eigenvalue (i.e., 1) of the transition\n        # matrix.\n        check_is_fitted(self, \"transmat_\")\n        eigvals, eigvecs = np.linalg.eig(self.transmat_.T)\n        eigvec = np.real_if_close(eigvecs[:, np.argmax(eigvals)])\n        return eigvec / eigvec.sum()", "title": ""}
{"_id": "d318", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d319", "text": "def _tf_squared_euclidean(X, Y):\n        \"\"\"Squared Euclidean distance between the rows of `X` and `Y`.\n        \"\"\"\n        return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1)", "title": ""}
{"_id": "d320", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d321", "text": "def euclidean(x, y):\n    \"\"\"Standard euclidean distance.\n\n    ..math::\n        D(x, y) = \\sqrt{\\sum_i (x_i - y_i)^2}\n    \"\"\"\n    result = 0.0\n    for i in range(x.shape[0]):\n        result += (x[i] - y[i]) ** 2\n    return np.sqrt(result)", "title": ""}
{"_id": "d322", "text": "def create_table_from_fits(fitsfile, hduname, colnames=None):\n    \"\"\"Memory efficient function for loading a table from a FITS\n    file.\"\"\"\n\n    if colnames is None:\n        return Table.read(fitsfile, hduname)\n\n    cols = []\n    with fits.open(fitsfile, memmap=True) as h:\n        for k in colnames:\n            data = h[hduname].data.field(k)\n            cols += [Column(name=k, data=data)]\n    return Table(cols)", "title": ""}
{"_id": "d323", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d324", "text": "def lint(args):\n    \"\"\"Run lint checks using flake8.\"\"\"\n    application = get_current_application()\n    if not args:\n        args = [application.name, 'tests']\n    args = ['flake8'] + list(args)\n    run.main(args, standalone_mode=False)", "title": ""}
{"_id": "d325", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d326", "text": "def _type_bool(label,default=False):\n    \"\"\"Shortcut fot boolean like fields\"\"\"\n    return label, abstractSearch.nothing, abstractRender.boolen, default", "title": ""}
{"_id": "d327", "text": "def join_cols(cols):\n    \"\"\"Join list of columns into a string for a SQL query\"\"\"\n    return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols", "title": ""}
{"_id": "d328", "text": "def parse_form(self, req, name, field):\n        \"\"\"Pull a form value from the request.\"\"\"\n        return core.get_value(req.POST, name, field)", "title": ""}
{"_id": "d329", "text": "def type_converter(text):\n    \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n    if text.isdigit():\n        return int(text), int\n\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE", "title": ""}
{"_id": "d330", "text": "def cors_header(func):\n    \"\"\" @cors_header decorator adds CORS headers \"\"\"\n\n    @wraps(func)\n    def wrapper(self, request, *args, **kwargs):\n        res = func(self, request, *args, **kwargs)\n        request.setHeader('Access-Control-Allow-Origin', '*')\n        request.setHeader('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With')\n        return res\n\n    return wrapper", "title": ""}
{"_id": "d331", "text": "def pdf(x, mu, std):\n    \"\"\"Probability density function (normal distribution)\"\"\"\n    return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))", "title": ""}
{"_id": "d332", "text": "def handleFlaskPostRequest(flaskRequest, endpoint):\n    \"\"\"\n    Handles the specified flask request for one of the POST URLS\n    Invokes the specified endpoint to generate a response.\n    \"\"\"\n    if flaskRequest.method == \"POST\":\n        return handleHttpPost(flaskRequest, endpoint)\n    elif flaskRequest.method == \"OPTIONS\":\n        return handleHttpOptions()\n    else:\n        raise exceptions.MethodNotAllowedException()", "title": ""}
{"_id": "d333", "text": "def pdf(x, mu, std):\n    \"\"\"Probability density function (normal distribution)\"\"\"\n    return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))", "title": ""}
{"_id": "d334", "text": "def python_mime(fn):\n    \"\"\"\n    Decorator, which adds correct MIME type for python source to the decorated\n    bottle API function.\n    \"\"\"\n    @wraps(fn)\n    def python_mime_decorator(*args, **kwargs):\n        response.content_type = \"text/x-python\"\n\n        return fn(*args, **kwargs)\n\n    return python_mime_decorator", "title": ""}
{"_id": "d335", "text": "def _spawn_kafka_consumer_thread(self):\n        \"\"\"Spawns a kafka continuous consumer thread\"\"\"\n        self.logger.debug(\"Spawn kafka consumer thread\"\"\")\n        self._consumer_thread = Thread(target=self._consumer_loop)\n        self._consumer_thread.setDaemon(True)\n        self._consumer_thread.start()", "title": ""}
{"_id": "d336", "text": "def flatpages_link_list(request):\n    \"\"\"\n    Returns a HttpResponse whose content is a Javascript file representing a\n    list of links to flatpages.\n    \"\"\"\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)", "title": ""}
{"_id": "d337", "text": "def values(self):\n        \"\"\"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\n        \"\"\"\n        lower = float(self.lowerSpnbx.value())\n        upper = float(self.upperSpnbx.value())\n        return (lower, upper)", "title": ""}
{"_id": "d338", "text": "def sqlmany(self, stringname, *args):\n        \"\"\"Wrapper for executing many SQL calls on my connection.\n\n        First arg is the name of a query, either a key in the\n        precompiled JSON or a method name in\n        ``allegedb.alchemy.Alchemist``. Remaining arguments should be\n        tuples of argument sequences to be passed to the query.\n\n        \"\"\"\n        if hasattr(self, 'alchemist'):\n            return getattr(self.alchemist.many, stringname)(*args)\n        s = self.strings[stringname]\n        return self.connection.cursor().executemany(s, args)", "title": ""}
{"_id": "d339", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d340", "text": "def render_template_string(source, **context):\n    \"\"\"Renders a template from the given template source string\n    with the given context.\n\n    :param source: the sourcecode of the template to be\n                   rendered\n    :param context: the variables that should be available in the\n                    context of the template.\n    \"\"\"\n    ctx = _app_ctx_stack.top\n    ctx.app.update_template_context(context)\n    return _render(ctx.app.jinja_env.from_string(source),\n                   context, ctx.app)", "title": ""}
{"_id": "d341", "text": "def asynchronous(function, event):\n    \"\"\"\n    Runs the function asynchronously taking care of exceptions.\n    \"\"\"\n    thread = Thread(target=synchronous, args=(function, event))\n    thread.daemon = True\n    thread.start()", "title": ""}
{"_id": "d342", "text": "def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE,\ncontent=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for forbidden access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=403)", "title": ""}
{"_id": "d343", "text": "def similarity(self, other):\n        \"\"\"Calculates the cosine similarity between this vector and another\n        vector.\"\"\"\n        if self.magnitude == 0 or other.magnitude == 0:\n            return 0\n\n        return self.dot(other) / self.magnitude", "title": ""}
{"_id": "d344", "text": "def default_static_path():\n    \"\"\"\n        Return the path to the javascript bundle\n    \"\"\"\n    fdir = os.path.dirname(__file__)\n    return os.path.abspath(os.path.join(fdir, '../assets/'))", "title": ""}
{"_id": "d345", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d346", "text": "def round_to_float(number, precision):\n    \"\"\"Round a float to a precision\"\"\"\n    rounded = Decimal(str(floor((number + precision / 2) // precision))\n                      ) * Decimal(str(precision))\n    return float(rounded)", "title": ""}
{"_id": "d347", "text": "def _calc_overlap_count(\n    markers1: dict,\n    markers2: dict,\n):\n    \"\"\"Calculate overlap count between the values of two dictionaries\n\n    Note: dict values must be sets\n    \"\"\"\n    overlaps=np.zeros((len(markers1), len(markers2)))\n\n    j=0\n    for marker_group in markers1:\n        tmp = [len(markers2[i].intersection(markers1[marker_group])) for i in markers2.keys()]\n        overlaps[j,:] = tmp\n        j += 1\n\n    return overlaps", "title": ""}
{"_id": "d348", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d349", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d350", "text": "def focusInEvent(self, event):\n        \"\"\"Reimplement Qt method to send focus change notification\"\"\"\n        self.focus_changed.emit()\n        return super(PageControlWidget, self).focusInEvent(event)", "title": ""}
{"_id": "d351", "text": "def mkdir(dir, enter):\n    \"\"\"Create directory with template for topic of the current environment\n\n    \"\"\"\n\n    if not os.path.exists(dir):\n        os.makedirs(dir)", "title": ""}
{"_id": "d352", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d353", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d354", "text": "def a2s(a):\n    \"\"\"\n     convert 3,3 a matrix to 6 element \"s\" list  (see Tauxe 1998)\n    \"\"\"\n    s = np.zeros((6,), 'f')  # make the a matrix\n    for i in range(3):\n        s[i] = a[i][i]\n    s[3] = a[0][1]\n    s[4] = a[1][2]\n    s[5] = a[0][2]\n    return s", "title": ""}
{"_id": "d355", "text": "def concat(cls, iterables):\n    \"\"\"\n    Similar to #itertools.chain.from_iterable().\n    \"\"\"\n\n    def generator():\n      for it in iterables:\n        for element in it:\n          yield element\n    return cls(generator())", "title": ""}
{"_id": "d356", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d357", "text": "def bulk_query(self, query, *multiparams):\n        \"\"\"Bulk insert or update.\"\"\"\n\n        with self.get_connection() as conn:\n            conn.bulk_query(query, *multiparams)", "title": ""}
{"_id": "d358", "text": "def Trie(S):\n    \"\"\"\n    :param S: set of words\n    :returns: trie containing all words from S\n    :complexity: linear in total word sizes from S\n    \"\"\"\n    T = None\n    for w in S:\n        T = add(T, w)\n    return T", "title": ""}
{"_id": "d359", "text": "def __set__(self, instance, value):\n        \"\"\" Set a related object for an instance. \"\"\"\n\n        self.map[id(instance)] = (weakref.ref(instance), value)", "title": ""}
{"_id": "d360", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d361", "text": "def go_to_background():\n    \"\"\" Daemonize the running process. \"\"\"\n    try:\n        if os.fork():\n            sys.exit()\n    except OSError as errmsg:\n        LOGGER.error('Fork failed: {0}'.format(errmsg))\n        sys.exit('Fork failed')", "title": ""}
{"_id": "d362", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d363", "text": "def compress(self, data_list):\n        \"\"\"\n        Return the cleaned_data of the form, everything should already be valid\n        \"\"\"\n        data = {}\n        if data_list:\n            return dict(\n                (f.name, data_list[i]) for i, f in enumerate(self.form))\n        return data", "title": ""}
{"_id": "d364", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d365", "text": "def safe_format(s, **kwargs):\n  \"\"\"\n  :type s str\n  \"\"\"\n  return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))", "title": ""}
{"_id": "d366", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d367", "text": "def straight_line_show(title, length=100, linestyle=\"=\", pad=0):\n        \"\"\"Print a formatted straight line.\n        \"\"\"\n        print(StrTemplate.straight_line(\n            title=title, length=length, linestyle=linestyle, pad=pad))", "title": ""}
{"_id": "d368", "text": "def make_executable(script_path):\n    \"\"\"Make `script_path` executable.\n\n    :param script_path: The file to change\n    \"\"\"\n    status = os.stat(script_path)\n    os.chmod(script_path, status.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d369", "text": "def  make_html_code( self, lines ):\n        \"\"\" convert a code sequence to HTML \"\"\"\n        line = code_header + '\\n'\n        for l in lines:\n            line = line + html_quote( l ) + '\\n'\n\n        return line + code_footer", "title": ""}
{"_id": "d370", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d371", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d372", "text": "def main(args=sys.argv):\n    \"\"\"\n    main entry point for the jardiff CLI\n    \"\"\"\n\n    parser = create_optparser(args[0])\n    return cli(parser.parse_args(args[1:]))", "title": ""}
{"_id": "d373", "text": "def free(self):\n        \"\"\"Free the underlying C array\"\"\"\n        if self._ptr is None:\n            return\n        Gauged.array_free(self.ptr)\n        FloatArray.ALLOCATIONS -= 1\n        self._ptr = None", "title": ""}
{"_id": "d374", "text": "def from_points(cls, list_of_lists):\n        \"\"\"\n        Creates a *Polygon* instance out of a list of lists, each sublist being populated with\n        `pyowm.utils.geo.Point` instances\n        :param list_of_lists: list\n        :type: list_of_lists: iterable_of_polygons\n        :returns:  a *Polygon* instance\n\n        \"\"\"\n        result = []\n        for l in list_of_lists:\n            curve = []\n            for point in l:\n                curve.append((point.lon, point.lat))\n            result.append(curve)\n        return Polygon(result)", "title": ""}
{"_id": "d375", "text": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "title": ""}
{"_id": "d376", "text": "def tmpfile(prefix, direc):\n    \"\"\"Returns the path to a newly created temporary file.\"\"\"\n    return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)", "title": ""}
{"_id": "d377", "text": "def connect(host, port, username, password):\n        \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n        # Instantiate ftplib client\n        session = ftplib.FTP()\n\n        # Connect to host without auth\n        session.connect(host, port)\n\n        # Authenticate connection\n        session.login(username, password)\n        return session", "title": ""}
{"_id": "d378", "text": "def unique_list(lst):\n    \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n    uniq = []\n    for item in lst:\n        if item not in uniq:\n            uniq.append(item)\n    return uniq", "title": ""}
{"_id": "d379", "text": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "title": ""}
{"_id": "d380", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d381", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d382", "text": "def zero_state(self, batch_size):\n        \"\"\" Initial state of the network \"\"\"\n        return torch.zeros(batch_size, self.state_dim, dtype=torch.float32)", "title": ""}
{"_id": "d383", "text": "def _fullname(o):\n    \"\"\"Return the fully-qualified name of a function.\"\"\"\n    return o.__module__ + \".\" + o.__name__ if o.__module__ else o.__name__", "title": ""}
{"_id": "d384", "text": "def create_index(config):\n    \"\"\"Create the root index.\"\"\"\n    filename = pathlib.Path(config.cache_path) / \"index.json\"\n    index = {\"version\": __version__}\n    with open(filename, \"w\") as out:\n        out.write(json.dumps(index, indent=2))", "title": ""}
{"_id": "d385", "text": "def issorted(list_, op=operator.le):\n    \"\"\"\n    Determines if a list is sorted\n\n    Args:\n        list_ (list):\n        op (func): sorted operation (default=operator.le)\n\n    Returns:\n        bool : True if the list is sorted\n    \"\"\"\n    return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))", "title": ""}
{"_id": "d386", "text": "def is_valid(number):\n    \"\"\"determines whether the card number is valid.\"\"\"\n    n = str(number)\n    if not n.isdigit():\n        return False\n    return int(n[-1]) == get_check_digit(n[:-1])", "title": ""}
{"_id": "d387", "text": "def us2mc(string):\n    \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)", "title": ""}
{"_id": "d388", "text": "def csv2yaml(in_file, out_file=None):\n    \"\"\"Convert a CSV SampleSheet to YAML run_info format.\n    \"\"\"\n    if out_file is None:\n        out_file = \"%s.yaml\" % os.path.splitext(in_file)[0]\n    barcode_ids = _generate_barcode_ids(_read_input_csv(in_file))\n    lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids)\n    with open(out_file, \"w\") as out_handle:\n        out_handle.write(yaml.safe_dump(lanes, default_flow_style=False))\n    return out_file", "title": ""}
{"_id": "d389", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d390", "text": "def cumsum(inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1, len(newlist)):\n        newlist[i] = newlist[i] + newlist[i - 1]\n    return newlist", "title": ""}
{"_id": "d391", "text": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d392", "text": "def move_to(self, ypos, xpos):\n        \"\"\"\n            move the cursor to the given co-ordinates.  Co-ordinates are 1\n            based, as listed in the status area of the terminal.\n        \"\"\"\n        # the screen's co-ordinates are 1 based, but the command is 0 based\n        xpos -= 1\n        ypos -= 1\n        self.exec_command(\"MoveCursor({0}, {1})\".format(ypos, xpos).encode(\"ascii\"))", "title": ""}
{"_id": "d393", "text": "def dict_from_object(obj: object):\n    \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n    # If object is a dict instance, no need to convert.\n    return (obj if isinstance(obj, dict)\n            else {attr: getattr(obj, attr)\n                  for attr in dir(obj) if not attr.startswith('_')})", "title": ""}
{"_id": "d394", "text": "def ensure_hbounds(self):\n        \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "title": ""}
{"_id": "d395", "text": "def strip_spaces(s):\n    \"\"\" Strip excess spaces from a string \"\"\"\n    return u\" \".join([c for c in s.split(u' ') if c])", "title": ""}
{"_id": "d396", "text": "def scatter(self, *args, **kwargs):\n        \"\"\"Add a scatter plot.\"\"\"\n        cls = _make_class(ScatterVisual,\n                          _default_marker=kwargs.pop('marker', None),\n                          )\n        return self._add_item(cls, *args, **kwargs)", "title": ""}
{"_id": "d397", "text": "def download_file_from_bucket(self, bucket, file_path, key):\n        \"\"\" Download file from S3 Bucket \"\"\"\n        with open(file_path, 'wb') as data:\n            self.__s3.download_fileobj(bucket, key, data)\n            return file_path", "title": ""}
{"_id": "d398", "text": "def imdecode(image_path):\n    \"\"\"Return BGR image read by opencv\"\"\"\n    import os\n    assert os.path.exists(image_path), image_path + ' not found'\n    im = cv2.imread(image_path)\n    return im", "title": ""}
{"_id": "d399", "text": "def ex(self, cmd):\n        \"\"\"Execute a normal python statement in user namespace.\"\"\"\n        with self.builtin_trap:\n            exec cmd in self.user_global_ns, self.user_ns", "title": ""}
{"_id": "d400", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d401", "text": "def dt2jd(dt):\n    \"\"\"Convert datetime to julian date\n    \"\"\"\n    a = (14 - dt.month)//12\n    y = dt.year + 4800 - a\n    m = dt.month + 12*a - 3\n    return dt.day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045", "title": ""}
{"_id": "d402", "text": "def smooth_gaussian(image, sigma=1):\n    \"\"\"Returns Gaussian smoothed image.\n\n    :param image: numpy array or :class:`jicimagelib.image.Image`\n    :param sigma: standard deviation\n    :returns: :class:`jicimagelib.image.Image`\n    \"\"\"\n    return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode=\"nearest\")", "title": ""}
{"_id": "d403", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d404", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d405", "text": "def convert_timestamp(timestamp):\n    \"\"\"\n    Converts bokehJS timestamp to datetime64.\n    \"\"\"\n    datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)\n    return np.datetime64(datetime.replace(tzinfo=None))", "title": ""}
{"_id": "d406", "text": "def _make_cmd_list(cmd_list):\n    \"\"\"\n    Helper function to easily create the proper json formated string from a list of strs\n    :param cmd_list: list of strings\n    :return: str json formatted\n    \"\"\"\n    cmd = ''\n    for i in cmd_list:\n        cmd = cmd + '\"' + i + '\",'\n    cmd = cmd[:-1]\n    return cmd", "title": ""}
{"_id": "d407", "text": "def accuracy(self):\n        \"\"\"\n        Calculates the accuracy of the tree by comparing\n        the model predictions to the dataset\n        (TP + TN) / (TP + TN + FP + FN) == (T / (T + F))\n        \"\"\"\n        sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr])\n        return float((self.model_predictions() == sub_observed).sum()) / self.data_size", "title": ""}
{"_id": "d408", "text": "def cli(yamlfile, format, context):\n    \"\"\" Generate JSONLD file from biolink schema \"\"\"\n    print(JSONLDGenerator(yamlfile, format).serialize(context=context))", "title": ""}
{"_id": "d409", "text": "def double_sha256(data):\n    \"\"\"A standard compound hash.\"\"\"\n    return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())", "title": ""}
{"_id": "d410", "text": "def get_cantons(self):\n        \"\"\"\n        Return the list of unique cantons, sorted by name.\n        \"\"\"\n        return sorted(list(set([\n            location.canton for location in self.get_locations().values()\n        ])))", "title": ""}
{"_id": "d411", "text": "def get_default_args(func):\n    \"\"\"\n    returns a dictionary of arg_name:default_values for the input function\n    \"\"\"\n    args, varargs, keywords, defaults = getargspec_no_self(func)\n    return dict(zip(args[-len(defaults):], defaults))", "title": ""}
{"_id": "d412", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d413", "text": "def _add_default_arguments(parser):\n    \"\"\"Add the default arguments to the parser.\n\n    :param argparse.ArgumentParser parser: The argument parser\n\n    \"\"\"\n    parser.add_argument('-c', '--config', action='store', dest='config',\n                        help='Path to the configuration file')\n    parser.add_argument('-f', '--foreground', action='store_true', dest='foreground',\n                        help='Run the application interactively')", "title": ""}
{"_id": "d414", "text": "def get_methods(*objs):\n    \"\"\" Return the names of all callable attributes of an object\"\"\"\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    )", "title": ""}
{"_id": "d415", "text": "def add_blank_row(self, label):\n        \"\"\"\n        Add a blank row with only an index value to self.df.\n        This is done inplace.\n        \"\"\"\n        col_labels = self.df.columns\n        blank_item = pd.Series({}, index=col_labels, name=label)\n        # use .loc to add in place (append won't do that)\n        self.df.loc[blank_item.name] = blank_item\n        return self.df", "title": ""}
{"_id": "d416", "text": "def items(self, section_name):\n        \"\"\":return: list((option, value), ...) pairs of all items in the given section\"\"\"\n        return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']", "title": ""}
{"_id": "d417", "text": "def computeDelaunayTriangulation(points):\n    \"\"\" Takes a list of point objects (which must have x and y fields).\n        Returns a list of 3-tuples: the indices of the points that form a\n        Delaunay triangle.\n    \"\"\"\n    siteList = SiteList(points)\n    context  = Context()\n    context.triangulate = True\n    voronoi(siteList,context)\n    return context.triangles", "title": ""}
{"_id": "d418", "text": "def get_keys_from_class(cc):\n    \"\"\"Return list of the key property names for a class \"\"\"\n    return [prop.name for prop in cc.properties.values() \\\n            if 'key' in prop.qualifiers]", "title": ""}
{"_id": "d419", "text": "def rm(venv_name):\n    \"\"\" Removes the venv by name \"\"\"\n    inenv = InenvManager()\n    venv = inenv.get_venv(venv_name)\n    click.confirm(\"Delete dir {}\".format(venv.path))\n    shutil.rmtree(venv.path)", "title": ""}
{"_id": "d420", "text": "def columns(self):\n        \"\"\"Return names of all the addressable columns (including foreign keys) referenced in user supplied model\"\"\"\n        res = [col['name'] for col in self.column_definitions]\n        res.extend([col['name'] for col in self.foreign_key_definitions])\n        return res", "title": ""}
{"_id": "d421", "text": "def remove_non_magic_cols(self):\n        \"\"\"\n        Remove all non-MagIC columns from all tables.\n        \"\"\"\n        for table_name in self.tables:\n            table = self.tables[table_name]\n            table.remove_non_magic_cols_from_table()", "title": ""}
{"_id": "d422", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d423", "text": "def _split_comma_separated(string):\n    \"\"\"Return a set of strings.\"\"\"\n    return set(text.strip() for text in string.split(',') if text.strip())", "title": ""}
{"_id": "d424", "text": "def angle(x0, y0, x1, y1):\n    \"\"\" Returns the angle between two points.\n    \"\"\"\n    return degrees(atan2(y1-y0, x1-x0))", "title": ""}
{"_id": "d425", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d426", "text": "def guess_extension(amimetype, normalize=False):\n    \"\"\"\n    Tries to guess extension for a mimetype.\n\n    @param amimetype: name of a mimetype\n    @time amimetype: string\n    @return: the extension\n    @rtype: string\n    \"\"\"\n    ext = _mimes.guess_extension(amimetype)\n    if ext and normalize:\n        # Normalize some common magic mis-interpreation\n        ext = {'.asc': '.txt', '.obj': '.bin'}.get(ext, ext)\n        from invenio.legacy.bibdocfile.api_normalizer import normalize_format\n        return normalize_format(ext)\n    return ext", "title": ""}
{"_id": "d427", "text": "def reset():\n    \"\"\"Delete the session and clear temporary directories\n\n    \"\"\"\n    shutil.rmtree(session['img_input_dir'])\n    shutil.rmtree(session['img_output_dir'])\n    session.clear()\n    return jsonify(ok='true')", "title": ""}
{"_id": "d428", "text": "def boolean(value):\n    \"\"\"\n    Configuration-friendly boolean type converter.\n\n    Supports both boolean-valued and string-valued inputs (e.g. from env vars).\n\n    \"\"\"\n    if isinstance(value, bool):\n        return value\n\n    if value == \"\":\n        return False\n\n    return strtobool(value)", "title": ""}
{"_id": "d429", "text": "def get_colors(img):\n    \"\"\"\n    Returns a list of all the image's colors.\n    \"\"\"\n    w, h = img.size\n    return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]", "title": ""}
{"_id": "d430", "text": "def pop(h):\n    \"\"\"Pop the heap value from the heap.\"\"\"\n    n = h.size() - 1\n    h.swap(0, n)\n    down(h, 0, n)\n    return h.pop()", "title": ""}
{"_id": "d431", "text": "def memory():\n    \"\"\"Determine memory specifications of the machine.\n\n    Returns\n    -------\n    mem_info : dictonary\n        Holds the current values for the total, free and used memory of the system.\n    \"\"\"\n\n    mem_info = dict()\n\n    for k, v in psutil.virtual_memory()._asdict().items():\n           mem_info[k] = int(v)\n           \n    return mem_info", "title": ""}
{"_id": "d432", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d433", "text": "def calculate_month(birth_date):\n    \"\"\"\n    Calculates and returns a month number basing on PESEL standard.\n    \"\"\"\n    year = int(birth_date.strftime('%Y'))\n    month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20\n\n    return month", "title": ""}
{"_id": "d434", "text": "def linedelimited (inlist,delimiter):\n    \"\"\"\nReturns a string composed of elements in inlist, with each element\nseparated by 'delimiter.'  Used by function writedelimited.  Use '\\t'\nfor tab-delimiting.\n\nUsage:   linedelimited (inlist,delimiter)\n\"\"\"\n    outstr = ''\n    for item in inlist:\n        if type(item) != StringType:\n            item = str(item)\n        outstr = outstr + item + delimiter\n    outstr = outstr[0:-1]\n    return outstr", "title": ""}
{"_id": "d435", "text": "def get_month_start_end_day():\n    \"\"\"\n    Get the month start date a nd end date\n    \"\"\"\n    t = date.today()\n    n = mdays[t.month]\n    return (date(t.year, t.month, 1), date(t.year, t.month, n))", "title": ""}
{"_id": "d436", "text": "def dequeue(self, block=True):\n        \"\"\"Dequeue a record and return item.\"\"\"\n        return self.queue.get(block, self.queue_get_timeout)", "title": ""}
{"_id": "d437", "text": "def return_value(self, *args, **kwargs):\n        \"\"\"Extracts the real value to be returned from the wrapping callable.\n\n        :return: The value the double should return when called.\n        \"\"\"\n\n        self._called()\n        return self._return_value(*args, **kwargs)", "title": ""}
{"_id": "d438", "text": "def get_best_encoding(stream):\n    \"\"\"Returns the default stream encoding if not found.\"\"\"\n    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n    if is_ascii_encoding(rv):\n        return 'utf-8'\n    return rv", "title": ""}
{"_id": "d439", "text": "def relpath(self):\n        \"\"\" Return this path as a relative path,\n        based from the current working directory.\n        \"\"\"\n        cwd = self.__class__(os.getcwdu())\n        return cwd.relpathto(self)", "title": ""}
{"_id": "d440", "text": "def we_are_in_lyon():\n    \"\"\"Check if we are on a Lyon machine\"\"\"\n    import socket\n    try:\n        hostname = socket.gethostname()\n        ip = socket.gethostbyname(hostname)\n    except socket.gaierror:\n        return False\n    return ip.startswith(\"134.158.\")", "title": ""}
{"_id": "d441", "text": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "title": ""}
{"_id": "d442", "text": "def is_callable(*p):\n    \"\"\" True if all the args are functions and / or subroutines\n    \"\"\"\n    import symbols\n    return all(isinstance(x, symbols.FUNCTION) for x in p)", "title": ""}
{"_id": "d443", "text": "def skip_connection_distance(a, b):\n    \"\"\"The distance between two skip-connections.\"\"\"\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))", "title": ""}
{"_id": "d444", "text": "def eqstr(a, b):\n    \"\"\"\n    Determine whether two strings are equivalent.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html\n\n    :param a: Arbitrary character string.\n    :type a: str\n    :param b: Arbitrary character string.\n    :type b: str\n    :return: True if A and B are equivalent.\n    :rtype: bool\n    \"\"\"\n    return bool(libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)))", "title": ""}
{"_id": "d445", "text": "def get_by(self, name):\n    \"\"\"get element by name\"\"\"\n    return next((item for item in self if item.name == name), None)", "title": ""}
{"_id": "d446", "text": "def validate(self, *args, **kwargs): # pylint: disable=arguments-differ\n        \"\"\"\n        Validate a parameter dict against a parameter schema from an ocrd-tool.json\n\n        Args:\n            obj (dict):\n            schema (dict):\n        \"\"\"\n        return super(ParameterValidator, self)._validate(*args, **kwargs)", "title": ""}
{"_id": "d447", "text": "def get_parent_dir(name):\n    \"\"\"Get the parent directory of a filename.\"\"\"\n    parent_dir = os.path.dirname(os.path.dirname(name))\n    if parent_dir:\n        return parent_dir\n    return os.path.abspath('.')", "title": ""}
{"_id": "d448", "text": "def me(self):\n        \"\"\"Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.\"\"\"\n        return self.guild.me if self.guild is not None else self.bot.user", "title": ""}
{"_id": "d449", "text": "def get_size_in_bytes(self, handle):\n        \"\"\"Return the size in bytes.\"\"\"\n        fpath = self._fpath_from_handle(handle)\n        return os.stat(fpath).st_size", "title": ""}
{"_id": "d450", "text": "def show_guestbook():\n    \"\"\"Returns all existing guestbook records.\"\"\"\n    cursor = flask.g.db.execute(\n        'SELECT name, message FROM entry ORDER BY id DESC;')\n    entries = [{'name': row[0], 'message': row[1]} for row in cursor.fetchall()]\n    return jinja2.Template(LAYOUT).render(entries=entries)", "title": ""}
{"_id": "d451", "text": "def get_month_start(day=None):\n    \"\"\"Returns the first day of the given month.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(day=1)", "title": ""}
{"_id": "d452", "text": "def rank(idx, dim):\n    \"\"\"Calculate the index rank according to Bertran's notation.\"\"\"\n    idxm = multi_index(idx, dim)\n    out = 0\n    while idxm[-1:] == (0,):\n        out += 1\n        idxm = idxm[:-1]\n    return out", "title": ""}
{"_id": "d453", "text": "def get_last_commit(git_path=None):\n    \"\"\"\n    Get the HEAD commit SHA1 of repository in current dir.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    line = get_last_commit_line(git_path)\n    revision_id = line.split()[1]\n    return revision_id", "title": ""}
{"_id": "d454", "text": "def csvpretty(csvfile: csvfile=sys.stdin):\n    \"\"\" Pretty print a CSV file. \"\"\"\n    shellish.tabulate(csv.reader(csvfile))", "title": ""}
{"_id": "d455", "text": "def array_dim(arr):\n    \"\"\"Return the size of a multidimansional array.\n    \"\"\"\n    dim = []\n    while True:\n        try:\n            dim.append(len(arr))\n            arr = arr[0]\n        except TypeError:\n            return dim", "title": ""}
{"_id": "d456", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d457", "text": "def qsize(self):\n        \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n        self.mutex.acquire()\n        n = self._qsize()\n        self.mutex.release()\n        return n", "title": ""}
{"_id": "d458", "text": "def is_static(self, filename):\n        \"\"\"Check if a file is a static file (which should be copied, rather\n        than compiled using Jinja2).\n\n        A file is considered static if it lives in any of the directories\n        specified in ``staticpaths``.\n\n        :param filename: the name of the file to check\n\n        \"\"\"\n        if self.staticpaths is None:\n            # We're not using static file support\n            return False\n\n        for path in self.staticpaths:\n            if filename.startswith(path):\n                return True\n        return False", "title": ""}
{"_id": "d459", "text": "def items(self):\n    \"\"\"Return a list of the (name, value) pairs of the enum.\n\n    These are returned in the order they were defined in the .proto file.\n    \"\"\"\n    return [(value_descriptor.name, value_descriptor.number)\n            for value_descriptor in self._enum_type.values]", "title": ""}
{"_id": "d460", "text": "def serve_static(request, path, insecure=False, **kwargs):\n    \"\"\"Collect and serve static files.\n\n    This view serves up static files, much like Django's\n    :py:func:`~django.views.static.serve` view, with the addition that it\n    collects static files first (if enabled). This allows images, fonts, and\n    other assets to be served up without first loading a page using the\n    ``{% javascript %}`` or ``{% stylesheet %}`` template tags.\n\n    You can use this view by adding the following to any :file:`urls.py`::\n\n        urlpatterns += static('static/', view='pipeline.views.serve_static')\n    \"\"\"\n    # Follow the same logic Django uses for determining access to the\n    # static-serving view.\n    if not django_settings.DEBUG and not insecure:\n        raise ImproperlyConfigured(\"The staticfiles view can only be used in \"\n                                   \"debug mode or if the --insecure \"\n                                   \"option of 'runserver' is used\")\n\n    if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED:\n        # Collect only the requested file, in order to serve the result as\n        # fast as possible. This won't interfere with the template tags in any\n        # way, as those will still cause Django to collect all media.\n        default_collector.collect(request, files=[path])\n\n    return serve(request, path, document_root=django_settings.STATIC_ROOT,\n                 **kwargs)", "title": ""}
{"_id": "d461", "text": "def items(cls):\n        \"\"\"\n        All values for this enum\n        :return: list of tuples\n\n        \"\"\"\n        return [\n            cls.PRECIPITATION,\n            cls.WIND,\n            cls.TEMPERATURE,\n            cls.PRESSURE\n        ]", "title": ""}
{"_id": "d462", "text": "def go_to_new_line(self):\n        \"\"\"Go to the end of the current line and create a new line\"\"\"\n        self.stdkey_end(False, False)\n        self.insert_text(self.get_line_separator())", "title": ""}
{"_id": "d463", "text": "def get_font_list():\n    \"\"\"Returns a sorted list of all system font names\"\"\"\n\n    font_map = pangocairo.cairo_font_map_get_default()\n    font_list = [f.get_name() for f in font_map.list_families()]\n    font_list.sort()\n\n    return font_list", "title": ""}
{"_id": "d464", "text": "def has_parent(self, term):\n        \"\"\"Return True if this GO object has a parent GO ID.\"\"\"\n        for parent in self.parents:\n            if parent.item_id == term or parent.has_parent(term):\n                return True\n        return False", "title": ""}
{"_id": "d465", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d466", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d467", "text": "def _get_local_ip():\n        \"\"\"\n        Get the local ip of this device\n\n        :return: Ip of this computer\n        :rtype: str\n        \"\"\"\n        return set([x[4][0] for x in socket.getaddrinfo(\n            socket.gethostname(),\n            80,\n            socket.AF_INET\n        )]).pop()", "title": ""}
{"_id": "d468", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d469", "text": "def get_public_members(obj):\n    \"\"\"\n    Retrieves a list of member-like objects (members or properties) that are\n    publically exposed.\n\n    :param obj: The object to probe.\n    :return:    A list of strings.\n    \"\"\"\n    return {attr: getattr(obj, attr) for attr in dir(obj)\n            if not attr.startswith(\"_\")\n            and not hasattr(getattr(obj, attr), '__call__')}", "title": ""}
{"_id": "d470", "text": "def timer():\n    \"\"\"\n    Timer used for calculate time elapsed\n    \"\"\"\n    if sys.platform == \"win32\":\n        default_timer = time.clock\n    else:\n        default_timer = time.time\n\n    return default_timer()", "title": ""}
{"_id": "d471", "text": "def last_day(year=_year, month=_month):\n    \"\"\"\n    get the current month's last day\n    :param year:  default to current year\n    :param month:  default to current month\n    :return: month's last day\n    \"\"\"\n    last_day = calendar.monthrange(year, month)[1]\n    return datetime.date(year=year, month=month, day=last_day)", "title": ""}
{"_id": "d472", "text": "def unit_tangent(self, t):\n        \"\"\"returns the unit tangent vector of the segment at t (centered at\n        the origin and expressed as a complex number).\"\"\"\n        dseg = self.derivative(t)\n        return dseg/abs(dseg)", "title": ""}
{"_id": "d473", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d474", "text": "def match_aspect_to_viewport(self):\n        \"\"\"Updates Camera.aspect to match the viewport's aspect ratio.\"\"\"\n        viewport = self.viewport\n        self.aspect = float(viewport.width) / viewport.height", "title": ""}
{"_id": "d475", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d476", "text": "def us2mc(string):\n    \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)", "title": ""}
{"_id": "d477", "text": "def _uniquify(_list):\n    \"\"\"Remove duplicates in a list.\"\"\"\n    seen = set()\n    result = []\n    for x in _list:\n        if x not in seen:\n            result.append(x)\n            seen.add(x)\n    return result", "title": ""}
{"_id": "d478", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d479", "text": "def get_module_path(modname):\n    \"\"\"Return module *modname* base path\"\"\"\n    return osp.abspath(osp.dirname(sys.modules[modname].__file__))", "title": ""}
{"_id": "d480", "text": "def np_hash(a):\n    \"\"\"Return a hash of a NumPy array.\"\"\"\n    if a is None:\n        return hash(None)\n    # Ensure that hashes are equal whatever the ordering in memory (C or\n    # Fortran)\n    a = np.ascontiguousarray(a)\n    # Compute the digest and return a decimal int\n    return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)", "title": ""}
{"_id": "d481", "text": "def get(s, delimiter='', format=\"diacritical\"):\n    \"\"\"Return pinyin of string, the string must be unicode\n    \"\"\"\n    return delimiter.join(_pinyin_generator(u(s), format=format))", "title": ""}
{"_id": "d482", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d483", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d484", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d485", "text": "def get_file_size(fileobj):\n    \"\"\"\n    Returns the size of a file-like object.\n    \"\"\"\n    currpos = fileobj.tell()\n    fileobj.seek(0, 2)\n    total_size = fileobj.tell()\n    fileobj.seek(currpos)\n    return total_size", "title": ""}
{"_id": "d486", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d487", "text": "def array_bytes(array):\n    \"\"\" Estimates the memory of the supplied array in bytes \"\"\"\n    return np.product(array.shape)*np.dtype(array.dtype).itemsize", "title": ""}
{"_id": "d488", "text": "def clear_es():\n        \"\"\"Clear all indexes in the es core\"\"\"\n        # TODO: should receive a catalog slug.\n        ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])\n        LOGGER.debug('Elasticsearch: Index cleared')", "title": ""}
{"_id": "d489", "text": "def get_idx_rect(index_list):\n    \"\"\"Extract the boundaries from a list of indexes\"\"\"\n    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\n    return ( min(rows), max(rows), min(cols), max(cols) )", "title": ""}
{"_id": "d490", "text": "def _get_node_parent(self, age, pos):\n        \"\"\"Get the parent node of node, whch is located in tree's node list.\n\n        Returns:\n            object: The parent node.\n        \"\"\"\n        return self.nodes[age][int(pos / self.comp)]", "title": ""}
{"_id": "d491", "text": "def __repr__(self):\n        \"\"\"Return list-lookalike of representation string of objects\"\"\"\n        strings = []\n        for currItem in self:\n            strings.append(\"%s\" % currItem)\n        return \"(%s)\" % (\", \".join(strings))", "title": ""}
{"_id": "d492", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d493", "text": "def tf2():\n  \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n  Returns:\n    The root module of a TF-2.0 API, if available.\n\n  Raises:\n    ImportError: if a TF-2.0 API is not available.\n  \"\"\"\n  # Import the `tf` compat API from this file and check if it's already TF 2.0.\n  if tf.__version__.startswith('2.'):\n    return tf\n  elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n    # As a fallback, try `tensorflow.compat.v2` if it's defined.\n    return tf.compat.v2\n  raise ImportError('cannot import tensorflow 2.0 API')", "title": ""}
{"_id": "d494", "text": "def split_addresses(email_string_list):\n    \"\"\"\n    Converts a string containing comma separated email addresses\n    into a list of email addresses.\n    \"\"\"\n    return [f for f in [s.strip() for s in email_string_list.split(\",\")] if f]", "title": ""}
{"_id": "d495", "text": "def size():\n    \"\"\"Determines the height and width of the console window\n\n        Returns:\n            tuple of int: The height in lines, then width in characters\n    \"\"\"\n    try:\n        assert os != 'nt' and sys.stdout.isatty()\n        rows, columns = os.popen('stty size', 'r').read().split()\n    except (AssertionError, AttributeError, ValueError):\n        # in case of failure, use dimensions of a full screen 13\" laptop\n        rows, columns = DEFAULT_HEIGHT, DEFAULT_WIDTH\n\n    return int(rows), int(columns)", "title": ""}
{"_id": "d496", "text": "def _encode_bool(name, value, dummy0, dummy1):\n    \"\"\"Encode a python boolean (True/False).\"\"\"\n    return b\"\\x08\" + name + (value and b\"\\x01\" or b\"\\x00\")", "title": ""}
{"_id": "d497", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d498", "text": "def write_enum(fo, datum, schema):\n    \"\"\"An enum is encoded by a int, representing the zero-based position of\n    the symbol in the schema.\"\"\"\n    index = schema['symbols'].index(datum)\n    write_int(fo, index)", "title": ""}
{"_id": "d499", "text": "def get_bottomrect_idx(self, pos):\n        \"\"\" Determine if cursor is on bottom right corner of a hot spot.\"\"\"\n        for i, r in enumerate(self.link_bottom_rects):\n            if r.Contains(pos):\n                return i\n        return -1", "title": ""}
{"_id": "d500", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d501", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d502", "text": "def plot_epsilon_residuals(self):\n        \"\"\"Plots the epsilon residuals for the variogram fit.\"\"\"\n        fig = plt.figure()\n        ax = fig.add_subplot(111)\n        ax.scatter(range(self.epsilon.size), self.epsilon, c='k', marker='*')\n        ax.axhline(y=0.0)\n        plt.show()", "title": ""}
{"_id": "d503", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d504", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d505", "text": "def forceupdate(self, *args, **kw):\n        \"\"\"Like a bulk :meth:`forceput`.\"\"\"\n        self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)", "title": ""}
{"_id": "d506", "text": "def get_nt_system_uid():\n    \"\"\"Get the MachineGuid from\n    HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Cryptography\\MachineGuid\n    \"\"\"\n    try:\n        import _winreg as winreg\n    except ImportError:\n        import winreg\n    lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\n    try:\n        key = winreg.OpenKey(lm, r\"Software\\Microsoft\\Cryptography\")\n        try:\n            return winreg.QueryValueEx(key, \"MachineGuid\")[0]\n        finally:\n            key.Close()\n    finally:\n        lm.Close()", "title": ""}
{"_id": "d507", "text": "def _escape(s):\n    \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n    e = s\n    e = e.replace('\\\\', '\\\\\\\\')\n    e = e.replace('\\n', '\\\\n')\n    e = e.replace('\\r', '\\\\r')\n    e = e.replace(\"'\", \"\\\\'\")\n    e = e.replace('\"', '\\\\\"')\n    return e", "title": ""}
{"_id": "d508", "text": "def get_element_with_id(self, id):\n        \"\"\"Return the element with the specified ID.\"\"\"\n        # Should we maintain a hashmap of ids to make this more efficient? Probably overkill.\n        # TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)\n        return next((el for el in self.elements if el.id == id), None)", "title": ""}
{"_id": "d509", "text": "def vector_distance(a, b):\n    \"\"\"The Euclidean distance between two vectors.\"\"\"\n    a = np.array(a)\n    b = np.array(b)\n    return np.linalg.norm(a - b)", "title": ""}
{"_id": "d510", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d511", "text": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "title": ""}
{"_id": "d512", "text": "def get_free_memory_win():\n    \"\"\"Return current free memory on the machine for windows.\n\n    Warning : this script is really not robust\n    Return in MB unit\n    \"\"\"\n    stat = MEMORYSTATUSEX()\n    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n    return int(stat.ullAvailPhys / 1024 / 1024)", "title": ""}
{"_id": "d513", "text": "def xpathEvalExpression(self, str):\n        \"\"\"Evaluate the XPath expression in the given context. \"\"\"\n        ret = libxml2mod.xmlXPathEvalExpression(str, self._o)\n        if ret is None:raise xpathError('xmlXPathEvalExpression() failed')\n        return xpathObjectRet(ret)", "title": ""}
{"_id": "d514", "text": "def EnumValueName(self, enum, value):\n    \"\"\"Returns the string name of an enum value.\n\n    This is just a small helper method to simplify a common operation.\n\n    Args:\n      enum: string name of the Enum.\n      value: int, value of the enum.\n\n    Returns:\n      string name of the enum value.\n\n    Raises:\n      KeyError if either the Enum doesn't exist or the value is not a valid\n        value for the enum.\n    \"\"\"\n    return self.enum_types_by_name[enum].values_by_number[value].name", "title": ""}
{"_id": "d515", "text": "def is_in(self, point_x, point_y):\n        \"\"\" Test if a point is within this polygonal region \"\"\"\n\n        point_array = array(((point_x, point_y),))\n        vertices = array(self.points)\n        winding = self.inside_rule == \"winding\"\n        result = points_in_polygon(point_array, vertices, winding)\n        return result[0]", "title": ""}
{"_id": "d516", "text": "def extent_count(self):\n        \"\"\"\n        Returns the volume group extent count.\n        \"\"\"\n        self.open()\n        count = lvm_vg_get_extent_count(self.handle)\n        self.close()\n        return count", "title": ""}
{"_id": "d517", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d518", "text": "def title(self):\n        \"\"\" The title of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.title", "title": ""}
{"_id": "d519", "text": "def visit_BoolOp(self, node):\n        \"\"\" Return type may come from any boolop operand. \"\"\"\n        return sum((self.visit(value) for value in node.values), [])", "title": ""}
{"_id": "d520", "text": "def __get_xml_text(root):\n    \"\"\" Return the text for the given root node (xml.dom.minidom). \"\"\"\n    txt = \"\"\n    for e in root.childNodes:\n        if (e.nodeType == e.TEXT_NODE):\n            txt += e.data\n    return txt", "title": ""}
{"_id": "d521", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d522", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d523", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d524", "text": "def equal(list1, list2):\n    \"\"\" takes flags returns indexes of True values \"\"\"\n    return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]", "title": ""}
{"_id": "d525", "text": "def select(self, cmd, *args, **kwargs):\n        \"\"\" Execute the SQL command and return the data rows as tuples\n        \"\"\"\n        self.cursor.execute(cmd, *args, **kwargs)\n        return self.cursor.fetchall()", "title": ""}
{"_id": "d526", "text": "def go_to_parent_directory(self):\n        \"\"\"Go to parent directory\"\"\"\n        self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))", "title": ""}
{"_id": "d527", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d528", "text": "def _top(self):\n        \"\"\" g \"\"\"\n        # Goto top of the list\n        self.top.body.focus_position = 2 if self.compact is False else 0\n        self.top.keypress(self.size, \"\")", "title": ""}
{"_id": "d529", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d530", "text": "def to_gtp(coord):\n    \"\"\"Converts from a Minigo coordinate to a GTP coordinate.\"\"\"\n    if coord is None:\n        return 'pass'\n    y, x = coord\n    return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)", "title": ""}
{"_id": "d531", "text": "def nb_to_python(nb_path):\n    \"\"\"convert notebook to python script\"\"\"\n    exporter = python.PythonExporter()\n    output, resources = exporter.from_filename(nb_path)\n    return output", "title": ""}
{"_id": "d532", "text": "def searchlast(self,n=10):\n        \"\"\"Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.\"\"\"            \n        solutions = deque([], n)\n        for solution in self:\n            solutions.append(solution)\n        return solutions", "title": ""}
{"_id": "d533", "text": "def to_json(df, state_index, color_index, fills):\n        \"\"\"Transforms dataframe to json response\"\"\"\n        records = {}\n        for i, row in df.iterrows():\n\n            records[row[state_index]] = {\n                \"fillKey\": row[color_index]\n            }\n\n        return {\n            \"data\": records,\n            \"fills\": fills\n        }", "title": ""}
{"_id": "d534", "text": "def _text_to_graphiz(self, text):\n        \"\"\"create a graphviz graph from text\"\"\"\n        dot = Source(text, format='svg')\n        return dot.pipe().decode('utf-8')", "title": ""}
{"_id": "d535", "text": "def get_colors(img):\n    \"\"\"\n    Returns a list of all the image's colors.\n    \"\"\"\n    w, h = img.size\n    return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]", "title": ""}
{"_id": "d536", "text": "def _round_half_hour(record):\n    \"\"\"\n    Round a time DOWN to half nearest half-hour.\n    \"\"\"\n    k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))\n    return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)", "title": ""}
{"_id": "d537", "text": "def get_X0(X):\n    \"\"\" Return zero-th element of a one-element data container.\n    \"\"\"\n    if pandas_available and isinstance(X, pd.DataFrame):\n        assert len(X) == 1\n        x = np.array(X.iloc[0])\n    else:\n        x, = X\n    return x", "title": ""}
{"_id": "d538", "text": "def threads_init(gtk=True):\n    \"\"\"Enables multithreading support in Xlib and PyGTK.\n    See the module docstring for more info.\n    \n    :Parameters:\n      gtk : bool\n        May be set to False to skip the PyGTK module.\n    \"\"\"\n    # enable X11 multithreading\n    x11.XInitThreads()\n    if gtk:\n        from gtk.gdk import threads_init\n        threads_init()", "title": ""}
{"_id": "d539", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d540", "text": "def enable_gtk3(self, app=None):\n        \"\"\"Enable event loop integration with Gtk3 (gir bindings).\n\n        Parameters\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        This methods sets the PyOS_InputHook for Gtk3, which allows\n        the Gtk3 to integrate with terminal based applications like\n        IPython.\n        \"\"\"\n        from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3\n        self.set_inputhook(create_inputhook_gtk3(self._stdin_file))\n        self._current_gui = GUI_GTK", "title": ""}
{"_id": "d541", "text": "def dot(a, b):\n    \"\"\"Take arrays `a` and `b` and form the dot product between the last axis\n    of `a` and the first of `b`.\n    \"\"\"\n    b = numpy.asarray(b)\n    return numpy.dot(a, b.reshape(b.shape[0], -1)).reshape(a.shape[:-1] + b.shape[1:])", "title": ""}
{"_id": "d542", "text": "def guess_encoding(text, default=DEFAULT_ENCODING):\n    \"\"\"Guess string encoding.\n\n    Given a piece of text, apply character encoding detection to\n    guess the appropriate encoding of the text.\n    \"\"\"\n    result = chardet.detect(text)\n    return normalize_result(result, default=default)", "title": ""}
{"_id": "d543", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d544", "text": "def __gzip(filename):\n\t\t\"\"\" Compress a file returning the new filename (.gz)\n\t\t\"\"\"\n\t\tzipname = filename + '.gz'\n\t\tfile_pointer = open(filename,'rb')\n\t\tzip_pointer = gzip.open(zipname,'wb')\n\t\tzip_pointer.writelines(file_pointer)\n\t\tfile_pointer.close()\n\t\tzip_pointer.close()\n\t\treturn zipname", "title": ""}
{"_id": "d545", "text": "def forceupdate(self, *args, **kw):\n        \"\"\"Like a bulk :meth:`forceput`.\"\"\"\n        self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)", "title": ""}
{"_id": "d546", "text": "def create_h5py_with_large_cache(filename, cache_size_mb):\n    \"\"\"\nAllows to open the hdf5 file with specified cache size\n    \"\"\"\n    # h5py does not allow to control the cache size from the high level\n    # we employ the workaround\n    # sources:\n    #http://stackoverflow.com/questions/14653259/how-to-set-cache-settings-while-using-h5py-high-level-interface\n    #https://groups.google.com/forum/#!msg/h5py/RVx1ZB6LpE4/KH57vq5yw2AJ\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", "title": ""}
{"_id": "d547", "text": "def rfft2d_freqs(h, w):\n    \"\"\"Computes 2D spectrum frequencies.\"\"\"\n\n    fy = np.fft.fftfreq(h)[:, None]\n    # when we have an odd input dimension we need to keep one additional\n    # frequency and later cut off 1 pixel\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)", "title": ""}
{"_id": "d548", "text": "def md5_hash_file(fh):\n    \"\"\"Return the md5 hash of the given file-object\"\"\"\n    md5 = hashlib.md5()\n    while True:\n        data = fh.read(8192)\n        if not data:\n            break\n        md5.update(data)\n    return md5.hexdigest()", "title": ""}
{"_id": "d549", "text": "def software_fibonacci(n):\n    \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n    a, b = 0, 1\n    for i in range(n):\n        a, b = b, a + b\n    return a", "title": ""}
{"_id": "d550", "text": "def h5ToDict(h5, readH5pyDataset=True):\n    \"\"\" Read a hdf5 file into a dictionary \"\"\"\n    h = h5py.File(h5, \"r\")\n    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n    if readH5pyDataset: h.close()\n    return ret", "title": ""}
{"_id": "d551", "text": "def current_zipfile():\n    \"\"\"A function to vend the current zipfile, if any\"\"\"\n    if zipfile.is_zipfile(sys.argv[0]):\n        fd = open(sys.argv[0], \"rb\")\n        return zipfile.ZipFile(fd)", "title": ""}
{"_id": "d552", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d553", "text": "def __init__(self, encoding='utf-8'):\n    \"\"\"Initializes an stdin input reader.\n\n    Args:\n      encoding (Optional[str]): input encoding.\n    \"\"\"\n    super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)", "title": ""}
{"_id": "d554", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d555", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d556", "text": "def double_sha256(data):\n    \"\"\"A standard compound hash.\"\"\"\n    return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())", "title": ""}
{"_id": "d557", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d558", "text": "def heappush_max(heap, item):\n    \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n    heap.append(item)\n    _siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d559", "text": "def split_addresses(email_string_list):\n    \"\"\"\n    Converts a string containing comma separated email addresses\n    into a list of email addresses.\n    \"\"\"\n    return [f for f in [s.strip() for s in email_string_list.split(\",\")] if f]", "title": ""}
{"_id": "d560", "text": "def _heappush_max(heap, item):\n    \"\"\" why is this not in heapq \"\"\"\n    heap.append(item)\n    heapq._siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d561", "text": "def _remove_keywords(d):\n    \"\"\"\n    copy the dict, filter_keywords\n\n    Parameters\n    ----------\n    d : dict\n    \"\"\"\n    return { k:v for k, v in iteritems(d) if k not in RESERVED }", "title": ""}
{"_id": "d562", "text": "def _heapify_max(x):\n    \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n    n = len(x)\n    for i in reversed(range(n//2)):\n        _siftup_max(x, i)", "title": ""}
{"_id": "d563", "text": "def uniq(seq):\n    \"\"\" Return a copy of seq without duplicates. \"\"\"\n    seen = set()\n    return [x for x in seq if str(x) not in seen and not seen.add(str(x))]", "title": ""}
{"_id": "d564", "text": "def pop(h):\n    \"\"\"Pop the heap value from the heap.\"\"\"\n    n = h.size() - 1\n    h.swap(0, n)\n    down(h, 0, n)\n    return h.pop()", "title": ""}
{"_id": "d565", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d566", "text": "def __call__(self, kind: Optional[str] = None, **kwargs):\n        \"\"\"Use the plotter as callable.\"\"\"\n        return plot(self.histogram, kind=kind, **kwargs)", "title": ""}
{"_id": "d567", "text": "def ci(a, which=95, axis=None):\n    \"\"\"Return a percentile range from an array of values.\"\"\"\n    p = 50 - which / 2, 50 + which / 2\n    return percentiles(a, p, axis)", "title": ""}
{"_id": "d568", "text": "def dtype(self):\n        \"\"\"Pixel data type.\"\"\"\n        try:\n            return self.data.dtype\n        except AttributeError:\n            return numpy.dtype('%s%d' % (self._sample_type, self._sample_bytes))", "title": ""}
{"_id": "d569", "text": "def tuple_search(t, i, v):\n    \"\"\"\n    Search tuple array by index and value\n    :param t: tuple array\n    :param i: index of the value in each tuple\n    :param v: value\n    :return: the first tuple in the array with the specific index / value\n    \"\"\"\n    for e in t:\n        if e[i] == v:\n            return e\n    return None", "title": ""}
{"_id": "d570", "text": "def from_pairs_to_array_values(pairs):\n    \"\"\"\n        Like from pairs but combines duplicate key values into arrays\n    :param pairs:\n    :return:\n    \"\"\"\n    result = {}\n    for pair in pairs:\n        result[pair[0]] = concat(prop_or([], pair[0], result), [pair[1]])\n    return result", "title": ""}
{"_id": "d571", "text": "def area(x,y):\n    \"\"\"\n    Calculate the area of a polygon given as x(...),y(...)\n    Implementation of Shoelace formula\n    \"\"\"\n    # http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates\n    return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))", "title": ""}
{"_id": "d572", "text": "def _getSuperFunc(self, s, func):\n        \"\"\"Return the the super function.\"\"\"\n\n        return getattr(super(self.cls(), s), func.__name__)", "title": ""}
{"_id": "d573", "text": "def val_to_bin(edges, x):\n    \"\"\"Convert axis coordinate to bin index.\"\"\"\n    ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n    return ibin", "title": ""}
{"_id": "d574", "text": "def val_to_bin(edges, x):\n    \"\"\"Convert axis coordinate to bin index.\"\"\"\n    ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n    return ibin", "title": ""}
{"_id": "d575", "text": "def compare(dicts):\n    \"\"\"Compare by iteration\"\"\"\n\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\n    return common_members", "title": ""}
{"_id": "d576", "text": "def convert_timestamp(timestamp):\n    \"\"\"\n    Converts bokehJS timestamp to datetime64.\n    \"\"\"\n    datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)\n    return np.datetime64(datetime.replace(tzinfo=None))", "title": ""}
{"_id": "d577", "text": "def _get_compiled_ext():\n    \"\"\"Official way to get the extension of compiled files (.pyc or .pyo)\"\"\"\n    for ext, mode, typ in imp.get_suffixes():\n        if typ == imp.PY_COMPILED:\n            return ext", "title": ""}
{"_id": "d578", "text": "def list_add_capitalize(l):\n    \"\"\"\n    @type l: list\n    @return: list\n    \"\"\"\n    nl = []\n\n    for i in l:\n        nl.append(i)\n\n        if hasattr(i, \"capitalize\"):\n            nl.append(i.capitalize())\n\n    return list(set(nl))", "title": ""}
{"_id": "d579", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d580", "text": "def to_camel_case(text):\n    \"\"\"Convert to camel case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    split = text.split('_')\n    return split[0] + \"\".join(x.title() for x in split[1:])", "title": ""}
{"_id": "d581", "text": "def median(lst):\n    \"\"\" Calcuates the median value in a @lst \"\"\"\n    #: http://stackoverflow.com/a/24101534\n    sortedLst = sorted(lst)\n    lstLen = len(lst)\n    index = (lstLen - 1) // 2\n    if (lstLen % 2):\n        return sortedLst[index]\n    else:\n        return (sortedLst[index] + sortedLst[index + 1])/2.0", "title": ""}
{"_id": "d582", "text": "def _IsRetryable(error):\n  \"\"\"Returns whether error is likely to be retryable.\"\"\"\n  if not isinstance(error, MySQLdb.OperationalError):\n    return False\n  if not error.args:\n    return False\n  code = error.args[0]\n  return code in _RETRYABLE_ERRORS", "title": ""}
{"_id": "d583", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d584", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d585", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d586", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d587", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x.\"\"\"\n    i = bs.bisect_left(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d588", "text": "def is_in(self, point_x, point_y):\n        \"\"\" Test if a point is within this polygonal region \"\"\"\n\n        point_array = array(((point_x, point_y),))\n        vertices = array(self.points)\n        winding = self.inside_rule == \"winding\"\n        result = points_in_polygon(point_array, vertices, winding)\n        return result[0]", "title": ""}
{"_id": "d589", "text": "def should_skip_logging(func):\n    \"\"\"\n    Should we skip logging for this handler?\n\n    \"\"\"\n    disabled = strtobool(request.headers.get(\"x-request-nolog\", \"false\"))\n    return disabled or getattr(func, SKIP_LOGGING, False)", "title": ""}
{"_id": "d590", "text": "def calc_cR(Q2, sigma):\n    \"\"\"Returns the cR statistic for the variogram fit (see [1]).\"\"\"\n    return Q2 * np.exp(np.sum(np.log(sigma**2))/sigma.shape[0])", "title": ""}
{"_id": "d591", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d592", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d593", "text": "def forget_coords(self):\n        \"\"\"Forget all loaded coordinates.\"\"\"\n        self.w.ntotal.set_text('0')\n        self.coords_dict.clear()\n        self.redo()", "title": ""}
{"_id": "d594", "text": "def flat_list(lst):\n    \"\"\"This function flatten given nested list.\n    Argument:\n        nested list\n    Returns:\n        flat list\n    \"\"\"\n    if isinstance(lst, list):\n        for item in lst:\n            for i in flat_list(item):\n                yield i\n    else:\n        yield lst", "title": ""}
{"_id": "d595", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d596", "text": "def imflip(img, direction='horizontal'):\n    \"\"\"Flip an image horizontally or vertically.\n\n    Args:\n        img (ndarray): Image to be flipped.\n        direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n    Returns:\n        ndarray: The flipped image.\n    \"\"\"\n    assert direction in ['horizontal', 'vertical']\n    if direction == 'horizontal':\n        return np.flip(img, axis=1)\n    else:\n        return np.flip(img, axis=0)", "title": ""}
{"_id": "d597", "text": "def get_order(self):\n        \"\"\"\n        Return a list of dicionaries. See `set_order`.\n        \"\"\"\n        return [dict(reverse=r[0], key=r[1]) for r in self.get_model()]", "title": ""}
{"_id": "d598", "text": "def hflip(img):\n    \"\"\"Horizontally flip the given PIL Image.\n\n    Args:\n        img (PIL Image): Image to be flipped.\n\n    Returns:\n        PIL Image:  Horizontall flipped image.\n    \"\"\"\n    if not _is_pil_image(img):\n        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n    return img.transpose(Image.FLIP_LEFT_RIGHT)", "title": ""}
{"_id": "d599", "text": "def mkdir(dir, enter):\n    \"\"\"Create directory with template for topic of the current environment\n\n    \"\"\"\n\n    if not os.path.exists(dir):\n        os.makedirs(dir)", "title": ""}
{"_id": "d600", "text": "def get_document_frequency(self, term):\n        \"\"\"\n        Returns the number of documents the specified term appears in.\n        \"\"\"\n        if term not in self._terms:\n            raise IndexError(TERM_DOES_NOT_EXIST)\n        else:\n            return len(self._terms[term])", "title": ""}
{"_id": "d601", "text": "def destroy(self):\n        \"\"\" Cleanup the activty lifecycle listener \"\"\"\n        if self.widget:\n            self.set_active(False)\n        super(AndroidBarcodeView, self).destroy()", "title": ""}
{"_id": "d602", "text": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "title": ""}
{"_id": "d603", "text": "def one_for_all(self, deps):\n        \"\"\"Because there are dependencies that depend on other\n        dependencies are created lists into other lists.\n        Thus creating this loop create one-dimensional list and\n        remove double packages from dependencies.\n        \"\"\"\n        requires, dependencies = [], []\n        deps.reverse()\n        # Inverting the list brings the\n        # dependencies in order to be installed.\n        requires = Utils().dimensional_list(deps)\n        dependencies = Utils().remove_dbs(requires)\n        return dependencies", "title": ""}
{"_id": "d604", "text": "def trigger_fullscreen_action(self, fullscreen):\n        \"\"\"\n        Toggle fullscreen from outside the GUI,\n        causes the GUI to updated and run all its actions.\n        \"\"\"\n        action = self.action_group.get_action('fullscreen')\n        action.set_active(fullscreen)", "title": ""}
{"_id": "d605", "text": "def download_json(local_filename, url, clobber=False):\n    \"\"\"Download the given JSON file, and pretty-print before we output it.\"\"\"\n    with open(local_filename, 'w') as json_file:\n        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))", "title": ""}
{"_id": "d606", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d607", "text": "def drag_and_drop(self, droppable):\n        \"\"\"\n        Performs drag a element to another elmenet.\n\n        Currently works only on Chrome driver.\n        \"\"\"\n        self.scroll_to()\n        ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()", "title": ""}
{"_id": "d608", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d609", "text": "def url_encode(url):\n    \"\"\"\n    Convert special characters using %xx escape.\n\n    :param url: str\n    :return: str - encoded url\n    \"\"\"\n    if isinstance(url, text_type):\n        url = url.encode('utf8')\n    return quote(url, ':/%?&=')", "title": ""}
{"_id": "d610", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d611", "text": "def go_to_new_line(self):\n        \"\"\"Go to the end of the current line and create a new line\"\"\"\n        self.stdkey_end(False, False)\n        self.insert_text(self.get_line_separator())", "title": ""}
{"_id": "d612", "text": "def ExecuteRaw(self, position, command):\n    \"\"\"Send a command string to gdb.\"\"\"\n    self.EnsureGdbPosition(position[0], None, None)\n    return gdb.execute(command, to_string=True)", "title": ""}
{"_id": "d613", "text": "def finish():\n    \"\"\"Print warning about interrupt and empty the job queue.\"\"\"\n    out.warn(\"Interrupted!\")\n    for t in threads:\n        t.stop()\n    jobs.clear()\n    out.warn(\"Waiting for download threads to finish.\")", "title": ""}
{"_id": "d614", "text": "def rlognormal(mu, tau, size=None):\n    \"\"\"\n    Return random lognormal variates.\n    \"\"\"\n\n    return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "title": ""}
{"_id": "d615", "text": "def calculate_boundingbox(lng, lat, miles):\n    \"\"\"\n    Given a latitude, longitude and a distance in miles, calculate\n    the co-ordinates of the bounding box 2*miles on long each side with the\n    given co-ordinates at the center.\n    \"\"\"\n\n    latChange = change_in_latitude(miles)\n    latSouth = lat - latChange\n    latNorth = lat + latChange\n    lngChange = change_in_longitude(lat, miles)\n    lngWest = lng + lngChange\n    lngEast = lng - lngChange\n    return (lngWest, latSouth, lngEast, latNorth)", "title": ""}
{"_id": "d616", "text": "def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"A quick and dirty way to get a unique string\"\"\"\n    return ''.join(random.choice(chars) for x in xrange(size))", "title": ""}
{"_id": "d617", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d618", "text": "def _generate_key_map(entity_list, key, entity_class):\n    \"\"\" 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.\n    \"\"\"\n\n    key_map = {}\n    for obj in entity_list:\n      key_map[obj[key]] = entity_class(**obj)\n\n    return key_map", "title": ""}
{"_id": "d619", "text": "def intersect(d1, d2):\n    \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n    return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "title": ""}
{"_id": "d620", "text": "def _rndPointDisposition(dx, dy):\n        \"\"\"Return random disposition point.\"\"\"\n        x = int(random.uniform(-dx, dx))\n        y = int(random.uniform(-dy, dy))\n        return (x, y)", "title": ""}
{"_id": "d621", "text": "def array_dim(arr):\n    \"\"\"Return the size of a multidimansional array.\n    \"\"\"\n    dim = []\n    while True:\n        try:\n            dim.append(len(arr))\n            arr = arr[0]\n        except TypeError:\n            return dim", "title": ""}
{"_id": "d622", "text": "def sine_wave(frequency):\n  \"\"\"Emit a sine wave at the given frequency.\"\"\"\n  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n  ts = xs / FLAGS.sample_rate\n  return tf.sin(2 * math.pi * frequency * ts)", "title": ""}
{"_id": "d623", "text": "def rank(idx, dim):\n    \"\"\"Calculate the index rank according to Bertran's notation.\"\"\"\n    idxm = multi_index(idx, dim)\n    out = 0\n    while idxm[-1:] == (0,):\n        out += 1\n        idxm = idxm[:-1]\n    return out", "title": ""}
{"_id": "d624", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d625", "text": "def find_nearest_index(arr, value):\n    \"\"\"For a given value, the function finds the nearest value\n    in the array and returns its index.\"\"\"\n    arr = np.array(arr)\n    index = (abs(arr-value)).argmin()\n    return index", "title": ""}
{"_id": "d626", "text": "def _get_random_id():\n    \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n    symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(symbols) for _ in range(15))", "title": ""}
{"_id": "d627", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d628", "text": "def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"A quick and dirty way to get a unique string\"\"\"\n    return ''.join(random.choice(chars) for x in xrange(size))", "title": ""}
{"_id": "d629", "text": "def make_file_read_only(file_path):\n    \"\"\"\n    Removes the write permissions for the given file for owner, groups and others.\n\n    :param file_path: The file whose privileges are revoked.\n    :raise FileNotFoundError: If the given file does not exist.\n    \"\"\"\n    old_permissions = os.stat(file_path).st_mode\n    os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)", "title": ""}
{"_id": "d630", "text": "def angle(x0, y0, x1, y1):\n    \"\"\" Returns the angle between two points.\n    \"\"\"\n    return degrees(atan2(y1-y0, x1-x0))", "title": ""}
{"_id": "d631", "text": "def copy(self):\n        \"\"\"\n        Return a copy of the dictionary.\n\n        This is a middle-deep copy; the copy is independent of the original in\n        all attributes that have mutable types except for:\n\n        * The values in the dictionary\n\n        Note that the Python functions :func:`py:copy.copy` and\n        :func:`py:copy.deepcopy` can be used to create completely shallow or\n        completely deep copies of objects of this class.\n        \"\"\"\n        result = NocaseDict()\n        result._data = self._data.copy()  # pylint: disable=protected-access\n        return result", "title": ""}
{"_id": "d632", "text": "def longest_run(da, dim='time'):\n    \"\"\"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\n        \"\"\"\n\n    d = rle(da, dim=dim)\n    rl_long = d.max(dim=dim)\n\n    return rl_long", "title": ""}
{"_id": "d633", "text": "def fopenat(base_fd, path):\n    \"\"\"\n    Does openat read-only, then does fdopen to get a file object\n    \"\"\"\n\n    return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')", "title": ""}
{"_id": "d634", "text": "def vars_class(cls):\n    \"\"\"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.\n    \"\"\"\n    return dict(chain.from_iterable(\n        vars(cls).items() for cls in reversed(cls.__mro__)))", "title": ""}
{"_id": "d635", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d636", "text": "def mean_date(dt_list):\n    \"\"\"Calcuate mean datetime from datetime list\n    \"\"\"\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", "title": ""}
{"_id": "d637", "text": "def _ensure_element(tup, elem):\n    \"\"\"\n    Create a tuple containing all elements of tup, plus elem.\n\n    Returns the new tuple and the index of elem in the new tuple.\n    \"\"\"\n    try:\n        return tup, tup.index(elem)\n    except ValueError:\n        return tuple(chain(tup, (elem,))), len(tup)", "title": ""}
{"_id": "d638", "text": "def bitdepth(self):\n        \"\"\"The number of bits per sample in the audio encoding (an int).\n        Only available for certain file formats (zero where\n        unavailable).\n        \"\"\"\n        if hasattr(self.mgfile.info, 'bits_per_sample'):\n            return self.mgfile.info.bits_per_sample\n        return 0", "title": ""}
{"_id": "d639", "text": "def to_python(self, value):\n        \"\"\"\n        Convert a string from a form into an Enum value.\n        \"\"\"\n        if value is None:\n            return value\n        if isinstance(value, self.enum):\n            return value\n        return self.enum[value]", "title": ""}
{"_id": "d640", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d641", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d642", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d643", "text": "def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx):\n        \"\"\"Merge all columns and place text string in widened cell.\"\"\"\n        hdridxval = len(self.hdrs) - 1\n        worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt)\n        return row_idx + 1", "title": ""}
{"_id": "d644", "text": "def dates_in_range(start_date, end_date):\n    \"\"\"Returns all dates between two dates.\n\n    Inclusive of the start date but not the end date.\n\n    Args:\n        start_date (datetime.date)\n        end_date (datetime.date)\n\n    Returns:\n        (list) of datetime.date objects\n    \"\"\"\n    return [\n        start_date + timedelta(n)\n        for n in range(int((end_date - start_date).days))\n    ]", "title": ""}
{"_id": "d645", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d646", "text": "def sort_fn_list(fn_list):\n    \"\"\"Sort input filename list by datetime\n    \"\"\"\n    dt_list = get_dt_list(fn_list)\n    fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]\n    return fn_list_sort", "title": ""}
{"_id": "d647", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d648", "text": "def Proxy(f):\n  \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n\n  return Wrapped", "title": ""}
{"_id": "d649", "text": "def metres2latlon(mx, my, origin_shift= 2 * pi * 6378137 / 2.0):\n    \"\"\"Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in\n    WGS84 Datum\"\"\"\n    lon = (mx / origin_shift) * 180.0\n    lat = (my / origin_shift) * 180.0\n\n    lat = 180 / pi * (2 * atan( exp( lat * pi / 180.0)) - pi / 2.0)\n    return lat, lon", "title": ""}
{"_id": "d650", "text": "def next (self):    # File-like object.\n\n        \"\"\"This is to support iterators over a file-like object.\n        \"\"\"\n\n        result = self.readline()\n        if result == self._empty_buffer:\n            raise StopIteration\n        return result", "title": ""}
{"_id": "d651", "text": "def _factor_generator(n):\n    \"\"\"\n    From a given natural integer, returns the prime factors and their multiplicity\n    :param n: Natural integer\n    :return:\n    \"\"\"\n    p = prime_factors(n)\n    factors = {}\n    for p1 in p:\n        try:\n            factors[p1] += 1\n        except KeyError:\n            factors[p1] = 1\n    return factors", "title": ""}
{"_id": "d652", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d653", "text": "def get_md5_for_file(file):\n    \"\"\"Get the md5 hash for a file.\n\n    :param file: the file to get the md5 hash for\n    \"\"\"\n    md5 = hashlib.md5()\n\n    while True:\n        data = file.read(md5.block_size)\n\n        if not data:\n            break\n\n        md5.update(data)\n\n    return md5.hexdigest()", "title": ""}
{"_id": "d654", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d655", "text": "def _rank(self, ranking, n):\n    \"\"\" return the first n sentences with highest ranking \"\"\"\n    return nlargest(n, ranking, key=ranking.get)", "title": ""}
{"_id": "d656", "text": "def drop_indexes(self):\n        \"\"\"Delete all indexes for the database\"\"\"\n        LOG.warning(\"Dropping all indexe\")\n        for collection_name in INDEXES:\n            LOG.warning(\"Dropping all indexes for collection name %s\", collection_name)\n            self.db[collection_name].drop_indexes()", "title": ""}
{"_id": "d657", "text": "def last(self):\n        \"\"\"Get the last object in file.\"\"\"\n        # End of file\n        self.__file.seek(0, 2)\n\n        # Get the last struct\n        data = self.get(self.length - 1)\n\n        return data", "title": ""}
{"_id": "d658", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d659", "text": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n    \"\"\"\n    Returns the last `n` rows in the table\n    \"\"\"\n    return fetch(dbconn, tablename, n, uuid, end=True)", "title": ""}
{"_id": "d660", "text": "def save(self, fname: str):\n        \"\"\"\n        Saves this training state to fname.\n        \"\"\"\n        with open(fname, \"wb\") as fp:\n            pickle.dump(self, fp)", "title": ""}
{"_id": "d661", "text": "def display_len(text):\n    \"\"\"\n    Get the display length of a string. This can differ from the character\n    length if the string contains wide characters.\n    \"\"\"\n    text = unicodedata.normalize('NFD', text)\n    return sum(char_width(char) for char in text)", "title": ""}
{"_id": "d662", "text": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "title": ""}
{"_id": "d663", "text": "def rel_path(filename):\n    \"\"\"\n    Function that gets relative path to the filename\n    \"\"\"\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)", "title": ""}
{"_id": "d664", "text": "def test():        \n    \"\"\"Local test.\"\"\"\n    from spyder.utils.qthelpers import qapplication\n    app = qapplication()\n    dlg = ProjectDialog(None)\n    dlg.show()\n    sys.exit(app.exec_())", "title": ""}
{"_id": "d665", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d666", "text": "def const_rand(size, seed=23980):\n    \"\"\" Generate a random array with a fixed seed.\n    \"\"\"\n    old_seed = np.random.seed()\n    np.random.seed(seed)\n    out = np.random.rand(size)\n    np.random.seed(old_seed)\n    return out", "title": ""}
{"_id": "d667", "text": "def get_action_methods(self):\n        \"\"\"\n        return a list of methods on this class for executing actions.\n        methods are return as a list of (name, func) tuples\n        \"\"\"\n        return [(name, getattr(self, name))\n                for name, _ in Action.get_command_types()]", "title": ""}
{"_id": "d668", "text": "def start():\n    \"\"\"Starts the web server.\"\"\"\n    global app\n    bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n               debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n               quiet=conf.WebQuiet)", "title": ""}
{"_id": "d669", "text": "async def sysinfo(dev: Device):\n    \"\"\"Print out system information (version, MAC addrs).\"\"\"\n    click.echo(await dev.get_system_info())\n    click.echo(await dev.get_interface_information())", "title": ""}
{"_id": "d670", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d671", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d672", "text": "def post_object_async(self, path, **kwds):\n    \"\"\"POST to an object.\"\"\"\n    return self.do_request_async(self.api_url + path, 'POST', **kwds)", "title": ""}
{"_id": "d673", "text": "def findfirst(f, coll):\n    \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n    result = list(dropwhile(f, coll))\n    return result[0] if result else None", "title": ""}
{"_id": "d674", "text": "def start(self):\n        \"\"\"Create a background thread for httpd and serve 'forever'\"\"\"\n        self._process = threading.Thread(target=self._background_runner)\n        self._process.start()", "title": ""}
{"_id": "d675", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d676", "text": "def start(self):\n        \"\"\"Create a background thread for httpd and serve 'forever'\"\"\"\n        self._process = threading.Thread(target=self._background_runner)\n        self._process.start()", "title": ""}
{"_id": "d677", "text": "def parse_querystring(self, req, name, field):\n        \"\"\"Pull a querystring value from the request.\"\"\"\n        return core.get_value(req.args, name, field)", "title": ""}
{"_id": "d678", "text": "def inject_into_urllib3():\n    \"\"\"\n    Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n    \"\"\"\n    util.ssl_.SSLContext = SecureTransportContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_SECURETRANSPORT = True\n    util.ssl_.IS_SECURETRANSPORT = True", "title": ""}
{"_id": "d679", "text": "def strip_spaces(x):\n    \"\"\"\n    Strips spaces\n    :param x:\n    :return:\n    \"\"\"\n    x = x.replace(b' ', b'')\n    x = x.replace(b'\\t', b'')\n    return x", "title": ""}
{"_id": "d680", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d681", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d682", "text": "def file_or_default(path, default, function = None):\n    \"\"\" Return a default value if a file does not exist \"\"\"\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", "title": ""}
{"_id": "d683", "text": "def this_quarter():\n        \"\"\" Return start and end date of this quarter. \"\"\"\n        since = TODAY + delta(day=1)\n        while since.month % 3 != 0:\n            since -= delta(months=1)\n        until = since + delta(months=3)\n        return Date(since), Date(until)", "title": ""}
{"_id": "d684", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d685", "text": "def get_month_start(day=None):\n    \"\"\"Returns the first day of the given month.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(day=1)", "title": ""}
{"_id": "d686", "text": "def clear_list_value(self, value):\n        \"\"\"\n        Clean the argument value to eliminate None or Falsy values if needed.\n        \"\"\"\n        # Don't go any further: this value is empty.\n        if not value:\n            return self.empty_value\n        # Clean empty items if wanted\n        if self.clean_empty:\n            value = [v for v in value if v]\n        return value or self.empty_value", "title": ""}
{"_id": "d687", "text": "def call_out(command):\n  \"\"\"\n  Run the given command (with shell=False) and return a tuple of\n  (int returncode, str output). Strip the output of enclosing whitespace.\n  \"\"\"\n  # start external command process\n  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n  # get outputs\n  out, _ = p.communicate()\n\n  return p.returncode, out.strip()", "title": ""}
{"_id": "d688", "text": "def run(self, value):\n        \"\"\" Determines if value value is empty.\n        Keyword arguments:\n        value str -- the value of the associated field to compare\n        \"\"\"\n        if self.pass_ and not value.strip():\n            return True\n\n        if not value:\n            return False\n        return True", "title": ""}
{"_id": "d689", "text": "def _string_width(self, s):\n        \"\"\"Get width of a string in the current font\"\"\"\n        s = str(s)\n        w = 0\n        for i in s:\n            w += self.character_widths[i]\n        return w * self.font_size / 1000.0", "title": ""}
{"_id": "d690", "text": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "title": ""}
{"_id": "d691", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d692", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d693", "text": "def datatype(dbtype, description, cursor):\n    \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n    dt = cursor.db.introspection.get_field_type(dbtype, description)\n    if type(dt) is tuple:\n        return dt[0]\n    else:\n        return dt", "title": ""}
{"_id": "d694", "text": "def normalize(im, invert=False, scale=None, dtype=np.float64):\n    \"\"\"\n    Normalize a field to a (min, max) exposure range, default is (0, 255).\n    (min, max) exposure values. Invert the image if requested.\n    \"\"\"\n    if dtype not in {np.float16, np.float32, np.float64}:\n        raise ValueError('dtype must be numpy.float16, float32, or float64.')\n    out = im.astype('float').copy()\n\n    scale = scale or (0.0, 255.0)\n    l, u = (float(i) for i in scale)\n    out = (out - l) / (u - l)\n    if invert:\n        out = -out + (out.max() + out.min())\n    return out.astype(dtype)", "title": ""}
{"_id": "d695", "text": "def end_index(self):\n        \"\"\"Return the 1-based index of the last item on this page.\"\"\"\n        paginator = self.paginator\n        # Special case for the last page because there can be orphans.\n        if self.number == paginator.num_pages:\n            return paginator.count\n        return (self.number - 1) * paginator.per_page + paginator.first_page", "title": ""}
{"_id": "d696", "text": "def filtered_image(self, im):\n        \"\"\"Returns a filtered image after applying the Fourier-space filters\"\"\"\n        q = np.fft.fftn(im)\n        for k,v in self.filters:\n            q[k] -= v\n        return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d697", "text": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n    \"\"\"\n    Returns the last `n` rows in the table\n    \"\"\"\n    return fetch(dbconn, tablename, n, uuid, end=True)", "title": ""}
{"_id": "d698", "text": "def get_buffer(self, data_np, header, format, output=None):\n        \"\"\"Get image as a buffer in (format).\n        Format should be 'jpeg', 'png', etc.\n        \"\"\"\n        if not have_pil:\n            raise Exception(\"Install PIL to use this method\")\n        image = PILimage.fromarray(data_np)\n        buf = output\n        if buf is None:\n            buf = BytesIO()\n        image.save(buf, format)\n        return buf", "title": ""}
{"_id": "d699", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d700", "text": "def uint32_to_uint8(cls, img):\n        \"\"\"\n        Cast uint32 RGB image to 4 uint8 channels.\n        \"\"\"\n        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))", "title": ""}
{"_id": "d701", "text": "def get_user_by_id(self, id):\n        \"\"\"Retrieve a User object by ID.\"\"\"\n        return self.db_adapter.get_object(self.UserClass, id=id)", "title": ""}
{"_id": "d702", "text": "def asynchronous(function, event):\n    \"\"\"\n    Runs the function asynchronously taking care of exceptions.\n    \"\"\"\n    thread = Thread(target=synchronous, args=(function, event))\n    thread.daemon = True\n    thread.start()", "title": ""}
{"_id": "d703", "text": "def reduce_fn(x):\n    \"\"\"\n    Aggregation function to get the first non-zero value.\n    \"\"\"\n    values = x.values if pd and isinstance(x, pd.Series) else x\n    for v in values:\n        if not is_nan(v):\n            return v\n    return np.NaN", "title": ""}
{"_id": "d704", "text": "def _EnforceProcessMemoryLimit(self, memory_limit):\n    \"\"\"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.\n    \"\"\"\n    # Resource is not supported on Windows.\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\n      resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))", "title": ""}
{"_id": "d705", "text": "def check_many(self, domains):\n        \"\"\"\n        Check availability for a number of domains. Returns a dictionary\n        mapping the domain names to their statuses as a string\n        (\"active\"/\"free\").\n        \"\"\"\n        return dict((item.domain, item.status) for item in self.check_domain_request(domains))", "title": ""}
{"_id": "d706", "text": "def end_block(self):\n        \"\"\"Ends an indentation block, leaving an empty line afterwards\"\"\"\n        self.current_indent -= 1\n\n        # If we did not add a new line automatically yet, now it's the time!\n        if not self.auto_added_line:\n            self.writeln()\n            self.auto_added_line = True", "title": ""}
{"_id": "d707", "text": "def get_weights_from_kmodel(kmodel):\n        \"\"\"\n        Convert kmodel's weights to bigdl format.\n        We are supposing the order is the same as the execution order.\n        :param kmodel: keras model\n        :return: list of ndarray\n        \"\"\"\n        layers_with_weights = [layer for layer in kmodel.layers if layer.weights]\n        bweights = []\n        for klayer in layers_with_weights:\n            # bws would be [weights, bias] or [weights]\n            bws = WeightsConverter.get_bigdl_weights_from_klayer(klayer)\n            for w in bws:\n                bweights.append(w)\n        return bweights", "title": ""}
{"_id": "d708", "text": "def MultiArgMax(x):\n  \"\"\"\n  Get tuple (actually a generator) of indices where the max value of\n  array x occurs. Requires that x have a max() method, as x.max()\n  (in the case of NumPy) is much faster than max(x).\n  For a simpler, faster argmax when there is only a single maximum entry,\n  or when knowing only the first index where the maximum occurs,\n  call argmax() on a NumPy array.\n\n  :param x: Any sequence that has a max() method.\n  :returns: Generator with the indices where the max value occurs.\n  \"\"\"\n  m = x.max()\n  return (i for i, v in enumerate(x) if v == m)", "title": ""}
{"_id": "d709", "text": "def get_nt_system_uid():\n    \"\"\"Get the MachineGuid from\n    HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Cryptography\\MachineGuid\n    \"\"\"\n    try:\n        import _winreg as winreg\n    except ImportError:\n        import winreg\n    lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\n    try:\n        key = winreg.OpenKey(lm, r\"Software\\Microsoft\\Cryptography\")\n        try:\n            return winreg.QueryValueEx(key, \"MachineGuid\")[0]\n        finally:\n            key.Close()\n    finally:\n        lm.Close()", "title": ""}
{"_id": "d710", "text": "def __init__(self, find, subcon):\n        \"\"\"Initialize.\"\"\"\n        Subconstruct.__init__(self, subcon)\n        self.find = find", "title": ""}
{"_id": "d711", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d712", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d713", "text": "def find_coord_vars(ncds):\n    \"\"\"\n    Finds all coordinate variables in a dataset.\n\n    A variable with the same name as a dimension is called a coordinate variable.\n    \"\"\"\n    coord_vars = []\n\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\n    return coord_vars", "title": ""}
{"_id": "d714", "text": "def get_func_posargs_name(f):\n    \"\"\"Returns the name of the function f's keyword argument parameter if it exists, otherwise None\"\"\"\n    sigparams = inspect.signature(f).parameters\n    for p in sigparams:\n        if sigparams[p].kind == inspect.Parameter.VAR_POSITIONAL:\n            return sigparams[p].name\n    return None", "title": ""}
{"_id": "d715", "text": "def check_git():\n    \"\"\"Check if git command is available.\"\"\"\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.\")", "title": ""}
{"_id": "d716", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d717", "text": "def positive_integer(anon, obj, field, val):\n    \"\"\"\n    Returns a random positive integer (for a Django PositiveIntegerField)\n    \"\"\"\n    return anon.faker.positive_integer(field=field)", "title": ""}
{"_id": "d718", "text": "def method(func):\n    \"\"\"Wrap a function as a method.\"\"\"\n    attr = abc.abstractmethod(func)\n    attr.__imethod__ = True\n    return attr", "title": ""}
{"_id": "d719", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d720", "text": "def type_converter(text):\n    \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n    if text.isdigit():\n        return int(text), int\n\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE", "title": ""}
{"_id": "d721", "text": "def create_path(path):\n    \"\"\"Creates a absolute path in the file system.\n\n    :param path: The path to be created\n    \"\"\"\n    import os\n    if not os.path.exists(path):\n        os.makedirs(path)", "title": ""}
{"_id": "d722", "text": "def is_int(value):\n    \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n    if isinstance(value, bool):\n        return False\n    try:\n        int(value)\n        return True\n    except (ValueError, TypeError):\n        return False", "title": ""}
{"_id": "d723", "text": "def h5ToDict(h5, readH5pyDataset=True):\n    \"\"\" Read a hdf5 file into a dictionary \"\"\"\n    h = h5py.File(h5, \"r\")\n    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n    if readH5pyDataset: h.close()\n    return ret", "title": ""}
{"_id": "d724", "text": "def int_to_date(date):\n    \"\"\"\n    Convert an int of form yyyymmdd to a python date object.\n    \"\"\"\n\n    year = date // 10**4\n    month = date % 10**4 // 10**2\n    day = date % 10**2\n\n    return datetime.date(year, month, day)", "title": ""}
{"_id": "d725", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d726", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d727", "text": "def add_noise(Y, sigma):\n    \"\"\"Adds noise to Y\"\"\"\n    return Y + np.random.normal(0, sigma, Y.shape)", "title": ""}
{"_id": "d728", "text": "def spline_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):\n    \"\"\"A datetime-version that takes datetime object list as x_axis\n    \"\"\"\n    numeric_datetime_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_axis\n    ]\n\n    numeric_datetime_new_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_new_axis\n    ]\n\n    return spline_interpolate(\n        numeric_datetime_axis, y_axis, numeric_datetime_new_axis)", "title": ""}
{"_id": "d729", "text": "def _load_data(filepath):\n  \"\"\"Loads the images and latent values into Numpy arrays.\"\"\"\n  with h5py.File(filepath, \"r\") as h5dataset:\n    image_array = np.array(h5dataset[\"images\"])\n    # The 'label' data set in the hdf5 file actually contains the float values\n    # and not the class labels.\n    values_array = np.array(h5dataset[\"labels\"])\n  return image_array, values_array", "title": ""}
{"_id": "d730", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d731", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d732", "text": "def is_valid_ip(ip_address):\n    \"\"\"\n    Check Validity of an IP address\n    \"\"\"\n    valid = True\n    try:\n        socket.inet_aton(ip_address.strip())\n    except:\n        valid = False\n    return valid", "title": ""}
{"_id": "d733", "text": "def main(idle):\n    \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n    while True:\n\n        LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n        time.sleep(idle)", "title": ""}
{"_id": "d734", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d735", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d736", "text": "def is_a_sequence(var, allow_none=False):\n    \"\"\" Returns True if var is a list or a tuple (but not a string!)\n    \"\"\"\n    return isinstance(var, (list, tuple)) or (var is None and allow_none)", "title": ""}
{"_id": "d737", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d738", "text": "def _notnull(expr):\n    \"\"\"\n    Return a sequence or scalar according to the input indicating if the values are not null.\n\n    :param expr: sequence or scalar\n    :return: sequence or scalar\n    \"\"\"\n\n    if isinstance(expr, SequenceExpr):\n        return NotNull(_input=expr, _data_type=types.boolean)\n    elif isinstance(expr, Scalar):\n        return NotNull(_input=expr, _value_type=types.boolean)", "title": ""}
{"_id": "d739", "text": "def conv_dict(self):\n        \"\"\"dictionary of conversion\"\"\"\n        return dict(integer=self.integer, real=self.real, no_type=self.no_type)", "title": ""}
{"_id": "d740", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d741", "text": "def get_hline():\n    \"\"\" gets a horiztonal line \"\"\"\n    return Window(\n        width=LayoutDimension.exact(1),\n        height=LayoutDimension.exact(1),\n        content=FillControl('-', token=Token.Line))", "title": ""}
{"_id": "d742", "text": "def _writable_dir(path):\n    \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n    return os.path.isdir(path) and os.access(path, os.W_OK)", "title": ""}
{"_id": "d743", "text": "def make_qs(n, m=None):\n    \"\"\"Make sympy symbols q0, q1, ...\n    \n    Args:\n        n(int), m(int, optional):\n            If specified both n and m, returns [qn, q(n+1), ..., qm],\n            Only n is specified, returns[q0, q1, ..., qn].\n\n    Return:\n        tuple(Symbol): Tuple of sympy symbols.\n    \"\"\"\n    try:\n        import sympy\n    except ImportError:\n        raise ImportError(\"This function requires sympy. Please install it.\")\n    if m is None:\n        syms = sympy.symbols(\" \".join(f\"q{i}\" for i in range(n)))\n        if isinstance(syms, tuple):\n            return syms\n        else:\n            return (syms,)\n    syms = sympy.symbols(\" \".join(f\"q{i}\" for i in range(n, m)))\n    if isinstance(syms, tuple):\n        return syms\n    else:\n        return (syms,)", "title": ""}
{"_id": "d744", "text": "def isdir(path, **kwargs):\n    \"\"\"Check if *path* is a directory\"\"\"\n    import os.path\n    return os.path.isdir(path, **kwargs)", "title": ""}
{"_id": "d745", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d746", "text": "def is_float_array(l):\n    r\"\"\"Checks if l is a numpy array of floats (any dimension\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.dtype.kind == 'f':\n            return True\n    return False", "title": ""}
{"_id": "d747", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d748", "text": "def is_iter_non_string(obj):\n    \"\"\"test if object is a list or tuple\"\"\"\n    if isinstance(obj, list) or isinstance(obj, tuple):\n        return True\n    return False", "title": ""}
{"_id": "d749", "text": "def round_to_x_digits(number, digits):\n    \"\"\"\n    Returns 'number' rounded to 'digits' digits.\n    \"\"\"\n    return round(number * math.pow(10, digits)) / math.pow(10, digits)", "title": ""}
{"_id": "d750", "text": "def __next__(self):\n    \"\"\"Pop the head off the iterator and return it.\"\"\"\n    res = self._head\n    self._fill()\n    if res is None:\n      raise StopIteration()\n    return res", "title": ""}
{"_id": "d751", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d752", "text": "def next (self):    # File-like object.\n\n        \"\"\"This is to support iterators over a file-like object.\n        \"\"\"\n\n        result = self.readline()\n        if result == self._empty_buffer:\n            raise StopIteration\n        return result", "title": ""}
{"_id": "d753", "text": "def as_tuple(self, value):\n        \"\"\"Utility function which converts lists to tuples.\"\"\"\n        if isinstance(value, list):\n            value = tuple(value)\n        return value", "title": ""}
{"_id": "d754", "text": "def __reversed__(self):\n        \"\"\"\n        Return a reversed iterable over the items in the dictionary. Items are\n        iterated over in their reverse sort order.\n\n        Iterating views while adding or deleting entries in the dictionary may\n        raise a RuntimeError or fail to iterate over all entries.\n        \"\"\"\n        _dict = self._dict\n        return iter((key, _dict[key]) for key in reversed(self._list))", "title": ""}
{"_id": "d755", "text": "def register_modele(self, modele: Modele):\n        \"\"\" Register a modele onto the lemmatizer\n\n        :param modele: Modele to register\n        \"\"\"\n        self.lemmatiseur._modeles[modele.gr()] = modele", "title": ""}
{"_id": "d756", "text": "def split_every(n, iterable):\n    \"\"\"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.\"\"\"\n    items = iter(iterable)\n    return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))", "title": ""}
{"_id": "d757", "text": "def flatten(l):\n    \"\"\"Flatten a nested list.\"\"\"\n    return sum(map(flatten, l), []) \\\n        if isinstance(l, list) or isinstance(l, tuple) else [l]", "title": ""}
{"_id": "d758", "text": "def directory_files(path):\n    \"\"\"Yield directory file names.\"\"\"\n\n    for entry in os.scandir(path):\n        if not entry.name.startswith('.') and entry.is_file():\n            yield entry.name", "title": ""}
{"_id": "d759", "text": "def read_array(path, mmap_mode=None):\n    \"\"\"Read a .npy array.\"\"\"\n    file_ext = op.splitext(path)[1]\n    if file_ext == '.npy':\n        return np.load(path, mmap_mode=mmap_mode)\n    raise NotImplementedError(\"The file extension `{}` \".format(file_ext) +\n                              \"is not currently supported.\")", "title": ""}
{"_id": "d760", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d761", "text": "def get_python():\n    \"\"\"Determine the path to the virtualenv 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", "title": ""}
{"_id": "d762", "text": "def render_template(template_name, **context):\n    \"\"\"Render a template into a response.\"\"\"\n    tmpl = jinja_env.get_template(template_name)\n    context[\"url_for\"] = url_for\n    return Response(tmpl.render(context), mimetype=\"text/html\")", "title": ""}
{"_id": "d763", "text": "def selectnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is `None`.\"\"\"\n\n    return select(table, field, lambda v: v is None, complement=complement)", "title": ""}
{"_id": "d764", "text": "def _join(verb):\n    \"\"\"\n    Join helper\n    \"\"\"\n    data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n    # Preserve x groups\n    if isinstance(verb.x, GroupedDataFrame):\n        data.plydata_groups = list(verb.x.plydata_groups)\n    return data", "title": ""}
{"_id": "d765", "text": "def stn(s, length, encoding, errors):\n    \"\"\"Convert a string to a null-terminated bytes object.\n    \"\"\"\n    s = s.encode(encoding, errors)\n    return s[:length] + (length - len(s)) * NUL", "title": ""}
{"_id": "d766", "text": "def join_images(img_files, out_file):\n    \"\"\"Join the list of images into the out file\"\"\"\n    images = [PIL.Image.open(f) for f in img_files]\n    joined = PIL.Image.new(\n        'RGB',\n        (sum(i.size[0] for i in images), max(i.size[1] for i in images))\n    )\n    left = 0\n    for img in images:\n        joined.paste(im=img, box=(left, 0))\n        left = left + img.size[0]\n    joined.save(out_file)", "title": ""}
{"_id": "d767", "text": "def _dict(content):\n    \"\"\"\n    Helper funcation that converts text-based get response\n    to a python dictionary for additional manipulation.\n    \"\"\"\n    if _has_pandas:\n        data = _data_frame(content).to_dict(orient='records')\n    else:\n        response = loads(content)\n        key = [x for x in response.keys() if x in c.response_data][0]\n        data = response[key]\n    return data", "title": ""}
{"_id": "d768", "text": "def get_join_cols(by_entry):\n  \"\"\" helper function used for joins\n  builds left and right join list for join function\n  \"\"\"\n  left_cols = []\n  right_cols = []\n  for col in by_entry:\n    if isinstance(col, str):\n      left_cols.append(col)\n      right_cols.append(col)\n    else:\n      left_cols.append(col[0])\n      right_cols.append(col[1])\n  return left_cols, right_cols", "title": ""}
{"_id": "d769", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d770", "text": "def flatten_dict_join_keys(dct, join_symbol=\" \"):\n    \"\"\" Flatten dict with defined key join symbol.\n\n    :param dct: dict to flatten\n    :param join_symbol: default value is \" \"\n    :return:\n    \"\"\"\n    return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )", "title": ""}
{"_id": "d771", "text": "def hash_iterable(it):\n\t\"\"\"Perform a O(1) memory hash of an iterable of arbitrary length.\n\n\thash(tuple(it)) creates a temporary tuple containing all values from it\n\twhich could be a problem if it is large.\n\n\tSee discussion at:\n\thttps://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ\n\t\"\"\"\n\thash_value = hash(type(it))\n\tfor value in it:\n\t\thash_value = hash((hash_value, value))\n\treturn hash_value", "title": ""}
{"_id": "d772", "text": "def get_join_cols(by_entry):\n  \"\"\" helper function used for joins\n  builds left and right join list for join function\n  \"\"\"\n  left_cols = []\n  right_cols = []\n  for col in by_entry:\n    if isinstance(col, str):\n      left_cols.append(col)\n      right_cols.append(col)\n    else:\n      left_cols.append(col[0])\n      right_cols.append(col[1])\n  return left_cols, right_cols", "title": ""}
{"_id": "d773", "text": "def _to_diagonally_dominant(mat):\n    \"\"\"Make matrix unweighted diagonally dominant using the Laplacian.\"\"\"\n    mat += np.diag(np.sum(mat != 0, axis=1) + 0.01)\n    return mat", "title": ""}
{"_id": "d774", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d775", "text": "def traverse_setter(obj, attribute, value):\n    \"\"\"\n    Traverses the object and sets the supplied attribute on the\n    object. Supports Dimensioned and DimensionedPlot types.\n    \"\"\"\n    obj.traverse(lambda x: setattr(x, attribute, value))", "title": ""}
{"_id": "d776", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d777", "text": "def read_key(self, key, bucket_name=None):\n        \"\"\"\n        Reads a key from S3\n\n        :param key: S3 key that will point to the file\n        :type key: str\n        :param bucket_name: Name of the bucket in which the file is stored\n        :type bucket_name: str\n        \"\"\"\n\n        obj = self.get_key(key, bucket_name)\n        return obj.get()['Body'].read().decode('utf-8')", "title": ""}
{"_id": "d778", "text": "def dump_json(obj):\n    \"\"\"Dump Python object as JSON string.\"\"\"\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)", "title": ""}
{"_id": "d779", "text": "def get_property(self, filename):\n        \"\"\"Opens the file and reads the value\"\"\"\n\n        with open(self.filepath(filename)) as f:\n            return f.read().strip()", "title": ""}
{"_id": "d780", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d781", "text": "def help_for_command(command):\n    \"\"\"Get the help text (signature + docstring) for a command (function).\"\"\"\n    help_text = pydoc.text.document(command)\n    # remove backspaces\n    return re.subn('.\\\\x08', '', help_text)[0]", "title": ""}
{"_id": "d782", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d783", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d784", "text": "def validate(raw_schema, target=None, **kwargs):\n    \"\"\"\n    Given the python representation of a JSONschema as defined in the swagger\n    spec, validate that the schema complies to spec.  If `target` is provided,\n    that target will be validated against the provided schema.\n    \"\"\"\n    schema = schema_validator(raw_schema, **kwargs)\n    if target is not None:\n        validate_object(target, schema=schema, **kwargs)", "title": ""}
{"_id": "d785", "text": "def build_output(self, fout):\n        \"\"\"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.\n        \"\"\"\n        fout.write('\\n'.join([s for s in self.out]))", "title": ""}
{"_id": "d786", "text": "def json_serial(obj):\n    \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n    if isinstance(obj, LegipyModel):\n        return obj.to_json()\n    elif isinstance(obj, (datetime.date, datetime.datetime)):\n        return obj.isoformat()\n    raise TypeError(\"Type {0} not serializable\".format(repr(type(obj))))", "title": ""}
{"_id": "d787", "text": "def generic_add(a, b):\n    \"\"\"Simple function to add two numbers\"\"\"\n    logger.debug('Called generic_add({}, {})'.format(a, b))\n    return a + b", "title": ""}
{"_id": "d788", "text": "def _unjsonify(x, isattributes=False):\n    \"\"\"Convert JSON string to an ordered defaultdict.\"\"\"\n    if isattributes:\n        obj = json.loads(x)\n        return dict_class(obj)\n    return json.loads(x)", "title": ""}
{"_id": "d789", "text": "def get_absolute_path(*args):\n    \"\"\"Transform relative pathnames into absolute pathnames.\"\"\"\n    directory = os.path.dirname(os.path.abspath(__file__))\n    return os.path.join(directory, *args)", "title": ""}
{"_id": "d790", "text": "def graphql_queries_to_json(*queries):\n    \"\"\"\n    Queries should be a list of GraphQL objects\n    \"\"\"\n    rtn = {}\n    for i, query in enumerate(queries):\n        rtn[\"q{}\".format(i)] = query.value\n    return json.dumps(rtn)", "title": ""}
{"_id": "d791", "text": "def synthesize(self, duration):\n        \"\"\"\n        Synthesize white noise\n\n        Args:\n            duration (numpy.timedelta64): The duration of the synthesized sound\n        \"\"\"\n        sr = self.samplerate.samples_per_second\n        seconds = duration / Seconds(1)\n        samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n        return AudioSamples(samples, self.samplerate)", "title": ""}
{"_id": "d792", "text": "def _clean_dict(target_dict, whitelist=None):\n    \"\"\" Convenience function that removes a dicts keys that have falsy values\n    \"\"\"\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    }", "title": ""}
{"_id": "d793", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d794", "text": "def calculate_embedding(self, batch_image_bytes):\n    \"\"\"Get the embeddings for a given JPEG image.\n\n    Args:\n      batch_image_bytes: As if returned from [ff.read() for ff in file_list].\n\n    Returns:\n      The Inception embeddings (bottleneck layer output)\n    \"\"\"\n    return self.tf_session.run(\n        self.embedding, feed_dict={self.input_jpeg: batch_image_bytes})", "title": ""}
{"_id": "d795", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d796", "text": "def timeout_thread_handler(timeout, stop_event):\n    \"\"\"A background thread to kill the process if it takes too long.\n\n    Args:\n        timeout (float): The number of seconds to wait before killing\n            the process.\n        stop_event (Event): An optional event to cleanly stop the background\n            thread if required during testing.\n    \"\"\"\n\n    stop_happened = stop_event.wait(timeout)\n    if stop_happened is False:\n        print(\"Killing program due to %f second timeout\" % timeout)\n\n    os._exit(2)", "title": ""}
{"_id": "d797", "text": "def copy_no_perm(src, dst):\n    \"\"\"\n    Copies a file from *src* to *dst* including meta data except for permission bits.\n    \"\"\"\n    shutil.copy(src, dst)\n    perm = os.stat(dst).st_mode\n    shutil.copystat(src, dst)\n    os.chmod(dst, perm)", "title": ""}
{"_id": "d798", "text": "def iter_with_last(iterable):\n    \"\"\"\n    :return: generator of tuples (isLastFlag, item)\n    \"\"\"\n    # Ensure it's an iterator and get the first field\n    iterable = iter(iterable)\n    prev = next(iterable)\n    for item in iterable:\n        # Lag by one item so I know I'm not at the end\n        yield False, prev\n        prev = item\n    # Last item\n    yield True, prev", "title": ""}
{"_id": "d799", "text": "def store_data(data):\n    \"\"\"Use this function to store data in a JSON file.\n\n    This function is used for loading up a JSON file and appending additional\n    data to the JSON file.\n\n    :param data: the data to add to the JSON file.\n    :type data: dict\n    \"\"\"\n    with open(url_json_path) as json_file:\n        try:\n            json_file_data = load(json_file)\n            json_file_data.update(data)\n        except (AttributeError, JSONDecodeError):\n            json_file_data = data\n    with open(url_json_path, 'w') as json_file:\n        dump(json_file_data, json_file, indent=4, sort_keys=True)", "title": ""}
{"_id": "d800", "text": "def flatten_dict_join_keys(dct, join_symbol=\" \"):\n    \"\"\" Flatten dict with defined key join symbol.\n\n    :param dct: dict to flatten\n    :param join_symbol: default value is \" \"\n    :return:\n    \"\"\"\n    return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )", "title": ""}
{"_id": "d801", "text": "def filename_addstring(filename, text):\n    \"\"\"\n    Add `text` to filename, keeping the extension in place\n    For example when adding a timestamp to the filename\n    \"\"\"\n    fn, ext = os.path.splitext(filename)\n    return fn + text + ext", "title": ""}
{"_id": "d802", "text": "def pop(self):\n        \"\"\"\n        return the last stack element and delete it from the list\n        \"\"\"\n        if not self.empty():\n            val = self.stack[-1]\n            del self.stack[-1]\n            return val", "title": ""}
{"_id": "d803", "text": "def interpolate_logscale_single(start, end, coefficient):\n    \"\"\" Cosine interpolation \"\"\"\n    return np.exp(np.log(start) + (np.log(end) - np.log(start)) * coefficient)", "title": ""}
{"_id": "d804", "text": "def get_last_modified_timestamp(self):\n        \"\"\"\n        Looks at the files in a git root directory and grabs the last modified timestamp\n        \"\"\"\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", "title": ""}
{"_id": "d805", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d806", "text": "def get_list_dimensions(_list):\n    \"\"\"\n    Takes a nested list and returns the size of each dimension followed\n    by the element type in the list\n    \"\"\"\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []", "title": ""}
{"_id": "d807", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d808", "text": "def levenshtein_distance_metric(a, b):\n    \"\"\" 1 - farthest apart (same number of words, all diff). 0 - same\"\"\"\n    return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1)))", "title": ""}
{"_id": "d809", "text": "def wait_until_exit(self):\n        \"\"\" Wait until thread exit\n\n            Used for testing purpose only\n        \"\"\"\n\n        if self._timeout is None:\n            raise Exception(\"Thread will never exit. Use stop or specify timeout when starting it!\")\n\n        self._thread.join()\n        self.stop()", "title": ""}
{"_id": "d810", "text": "def timed (log=sys.stderr, limit=2.0):\n    \"\"\"Decorator to run a function with timing info.\"\"\"\n    return lambda func: timeit(func, log, limit)", "title": ""}
{"_id": "d811", "text": "def dict_jsonp(param):\n    \"\"\"Convert the parameter into a dictionary before calling jsonp, if it's not already one\"\"\"\n    if not isinstance(param, dict):\n        param = dict(param)\n    return jsonp(param)", "title": ""}
{"_id": "d812", "text": "def txt_line_iterator(path):\n  \"\"\"Iterate through lines of file.\"\"\"\n  with tf.gfile.Open(path) as f:\n    for line in f:\n      yield line.strip()", "title": ""}
{"_id": "d813", "text": "def get_size(objects):\n    \"\"\"Compute the total size of all elements in objects.\"\"\"\n    res = 0\n    for o in objects:\n        try:\n            res += _getsizeof(o)\n        except AttributeError:\n            print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n    return res", "title": ""}
{"_id": "d814", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d815", "text": "def stderr(a):\n    \"\"\"\n    Calculate the standard error of a.\n    \"\"\"\n    return np.nanstd(a) / np.sqrt(sum(np.isfinite(a)))", "title": ""}
{"_id": "d816", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d817", "text": "def time(func, *args, **kwargs):\n    \"\"\"\n    Call the supplied function with the supplied arguments,\n    and return the total execution time as a float in seconds.\n\n    The precision of the returned value depends on the precision of\n    `time.time()` on your platform.\n\n    Arguments:\n        func: the function to run.\n        *args: positional arguments to pass into the function.\n        **kwargs: keyword arguments to pass into the function.\n    Returns:\n        Execution time of the function as a float in seconds.\n    \"\"\"\n    start_time = time_module.time()\n    func(*args, **kwargs)\n    end_time = time_module.time()\n    return end_time - start_time", "title": ""}
{"_id": "d818", "text": "def equal(list1, list2):\n    \"\"\" takes flags returns indexes of True values \"\"\"\n    return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]", "title": ""}
{"_id": "d819", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d820", "text": "def classnameify(s):\n  \"\"\"\n  Makes a classname\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))", "title": ""}
{"_id": "d821", "text": "def dedupe_list(l):\n    \"\"\"Remove duplicates from a list preserving the order.\n\n    We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n    the order, which hinders testability and does not work for lists with\n    unhashable elements.\n    \"\"\"\n    result = []\n\n    for el in l:\n        if el not in result:\n            result.append(el)\n\n    return result", "title": ""}
{"_id": "d822", "text": "def force_to_string(unknown):\n    \"\"\"\n    converts and unknown type to string for display purposes.\n    \n    \"\"\"\n    result = ''\n    if type(unknown) is str:\n        result = unknown\n    if type(unknown) is int:\n        result = str(unknown)\n    if type(unknown) is float:\n        result = str(unknown)\n    if type(unknown) is dict:\n        result = Dict2String(unknown)\n    if type(unknown) is list:\n        result = List2String(unknown)\n    return result", "title": ""}
{"_id": "d823", "text": "def nan_pixels(self):\n        \"\"\" Return an array of the NaN pixels.\n\n        Returns\n        -------\n        :obj:`numpy.ndarray`\n             Nx2 array of the NaN pixels\n        \"\"\"\n        nan_px = np.where(np.isnan(np.sum(self.raw_data, axis=2)))\n        nan_px = np.c_[nan_px[0], nan_px[1]]\n        return nan_px", "title": ""}
{"_id": "d824", "text": "def clean_error(err):\n    \"\"\"\n    Take stderr bytes returned from MicroPython and attempt to create a\n    non-verbose error message.\n    \"\"\"\n    if err:\n        decoded = err.decode('utf-8')\n        try:\n            return decoded.split('\\r\\n')[-2]\n        except Exception:\n            return decoded\n    return 'There was an error.'", "title": ""}
{"_id": "d825", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d826", "text": "def downcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n    return [ tt.lower() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d827", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d828", "text": "def arr_to_vector(arr):\n    \"\"\"Reshape a multidimensional array to a vector.\n    \"\"\"\n    dim = array_dim(arr)\n    tmp_arr = []\n    for n in range(len(dim) - 1):\n        for inner in arr:\n            for i in inner:\n                tmp_arr.append(i)\n        arr = tmp_arr\n        tmp_arr = []\n    return arr", "title": ""}
{"_id": "d829", "text": "def get_all_attributes(klass_or_instance):\n    \"\"\"Get all attribute members (attribute, property style method).\n    \"\"\"\n    pairs = list()\n    for attr, value in inspect.getmembers(\n            klass_or_instance, lambda x: not inspect.isroutine(x)):\n        if not (attr.startswith(\"__\") or attr.endswith(\"__\")):\n            pairs.append((attr, value))\n    return pairs", "title": ""}
{"_id": "d830", "text": "def session_to_epoch(timestamp):\n    \"\"\" converts Synergy Timestamp for session to UTC zone seconds since epoch \"\"\"\n    utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()\n    return calendar.timegm(utc_timetuple)", "title": ""}
{"_id": "d831", "text": "def zero_pixels(self):\n        \"\"\" Return an array of the zero pixels.\n\n        Returns\n        -------\n        :obj:`numpy.ndarray`\n             Nx2 array of the zero pixels\n        \"\"\"\n        zero_px = np.where(np.sum(self.raw_data, axis=2) == 0)\n        zero_px = np.c_[zero_px[0], zero_px[1]]\n        return zero_px", "title": ""}
{"_id": "d832", "text": "def end_table_header(self):\n        r\"\"\"End the table header which will appear on every page.\"\"\"\n\n        if self.header:\n            msg = \"Table already has a header\"\n            raise TableError(msg)\n\n        self.header = True\n\n        self.append(Command(r'endhead'))", "title": ""}
{"_id": "d833", "text": "def main(args=sys.argv):\n    \"\"\"\n    main entry point for the jardiff CLI\n    \"\"\"\n\n    parser = create_optparser(args[0])\n    return cli(parser.parse_args(args[1:]))", "title": ""}
{"_id": "d834", "text": "def raise_os_error(_errno, path=None):\n    \"\"\"\n    Helper for raising the correct exception under Python 3 while still\n    being able to raise the same common exception class in Python 2.7.\n    \"\"\"\n\n    msg = \"%s: '%s'\" % (strerror(_errno), path) if path else strerror(_errno)\n    raise OSError(_errno, msg)", "title": ""}
{"_id": "d835", "text": "def get_mnist(data_type=\"train\", location=\"/tmp/mnist\"):\n    \"\"\"\n    Get mnist dataset with features and label as ndarray.\n    Data would be downloaded automatically if it doesn't present at the specific location.\n\n    :param data_type: \"train\" for training data and \"test\" for testing data.\n    :param location: Location to store mnist dataset.\n    :return: (features: ndarray, label: ndarray)\n    \"\"\"\n    X, Y = mnist.read_data_sets(location, data_type)\n    return X, Y + 1", "title": ""}
{"_id": "d836", "text": "def _multiline_width(multiline_s, line_width_fn=len):\n    \"\"\"Visible width of a potentially multiline content.\"\"\"\n    return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "title": ""}
{"_id": "d837", "text": "def exec_function(ast, globals_map):\n    \"\"\"Execute a python code object in the given environment.\n\n    Args:\n      globals_map: Dictionary to use as the globals context.\n    Returns:\n      locals_map: Dictionary of locals from the environment after execution.\n    \"\"\"\n    locals_map = globals_map\n    exec ast in globals_map, locals_map\n    return locals_map", "title": ""}
{"_id": "d838", "text": "def col_rename(df,col_name,new_col_name):\n    \"\"\" Changes a column name in a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_name - string\n        Name of column to change\n    new_col_name - string\n        New name of column\n    \"\"\"\n    col_list = list(df.columns)\n    for index,value in enumerate(col_list):\n        if value == col_name:\n            col_list[index] = new_col_name\n            break\n    df.columns = col_list", "title": ""}
{"_id": "d839", "text": "def _include_yaml(loader, node):\n    \"\"\"Load another YAML file and embeds it using the !include tag.\n\n    Example:\n        device_tracker: !include device_tracker.yaml\n    \"\"\"\n    return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))", "title": ""}
{"_id": "d840", "text": "def comma_converter(float_string):\n    \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n    trans_table = maketrans(b',', b'.')\n    return float(float_string.translate(trans_table))", "title": ""}
{"_id": "d841", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d842", "text": "def to_identifier(s):\n  \"\"\"\n  Convert snake_case to camel_case.\n  \"\"\"\n  if s.startswith('GPS'):\n      s = 'Gps' + s[3:]\n  return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s", "title": ""}
{"_id": "d843", "text": "def tuple_search(t, i, v):\n    \"\"\"\n    Search tuple array by index and value\n    :param t: tuple array\n    :param i: index of the value in each tuple\n    :param v: value\n    :return: the first tuple in the array with the specific index / value\n    \"\"\"\n    for e in t:\n        if e[i] == v:\n            return e\n    return None", "title": ""}
{"_id": "d844", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d845", "text": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "title": ""}
{"_id": "d846", "text": "def _validate_pos(df):\n    \"\"\"Validates the returned positional object\n    \"\"\"\n    assert isinstance(df, pd.DataFrame)\n    assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n    assert df.position.dtype == np.dtype(\"int64\")\n    assert df.strand.dtype == np.dtype(\"O\")\n    assert df.seqname.dtype == np.dtype(\"O\")\n    return df", "title": ""}
{"_id": "d847", "text": "def autoconvert(string):\n    \"\"\"Try to convert variables into datatypes.\"\"\"\n    for fn in (boolify, int, float):\n        try:\n            return fn(string)\n        except ValueError:\n            pass\n    return string", "title": ""}
{"_id": "d848", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d849", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d850", "text": "def find_console_handler(logger):\n    \"\"\"Return a stream handler, if it exists.\"\"\"\n    for handler in logger.handlers:\n        if (isinstance(handler, logging.StreamHandler) and\n                handler.stream == sys.stderr):\n            return handler", "title": ""}
{"_id": "d851", "text": "def unicode_is_ascii(u_string):\n    \"\"\"Determine if unicode string only contains ASCII characters.\n\n    :param str u_string: unicode string to check. Must be unicode\n        and not Python 2 `str`.\n    :rtype: bool\n    \"\"\"\n    assert isinstance(u_string, str)\n    try:\n        u_string.encode('ascii')\n        return True\n    except UnicodeEncodeError:\n        return False", "title": ""}
{"_id": "d852", "text": "def clog(color):\n    \"\"\"Same to ``log``, but this one centralizes the message first.\"\"\"\n    logger = log(color)\n    return lambda msg: logger(centralize(msg).rstrip())", "title": ""}
{"_id": "d853", "text": "def is_defined(self, obj, force_import=False):\n        \"\"\"Return True if object is defined in current namespace\"\"\"\n        from spyder_kernels.utils.dochelpers import isdefined\n\n        ns = self._get_current_namespace(with_magics=True)\n        return isdefined(obj, force_import=force_import, namespace=ns)", "title": ""}
{"_id": "d854", "text": "def format(self, record, *args, **kwargs):\n        \"\"\"\n        Format a message in the log\n\n        Act like the normal format, but indent anything that is a\n        newline within the message.\n\n        \"\"\"\n        return logging.Formatter.format(\n            self, record, *args, **kwargs).replace('\\n', '\\n' + ' ' * 8)", "title": ""}
{"_id": "d855", "text": "def is_delimiter(line):\n    \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n    return bool(line) and line[0] in punctuation and line[0]*len(line) == line", "title": ""}
{"_id": "d856", "text": "def load_config(filename=\"logging.ini\", *args, **kwargs):\n    \"\"\"\n    Load logger config from file\n    \n    Keyword arguments:\n    filename -- configuration filename (Default: \"logging.ini\")\n    *args -- options passed to fileConfig\n    **kwargs -- options passed to fileConfigg\n    \n    \"\"\"\n    logging.config.fileConfig(filename, *args, **kwargs)", "title": ""}
{"_id": "d857", "text": "def is_parameter(self):\n        \"\"\"Whether this is a function parameter.\"\"\"\n        return (isinstance(self.scope, CodeFunction)\n                and self in self.scope.parameters)", "title": ""}
{"_id": "d858", "text": "def print_log(value_color=\"\", value_noncolor=\"\"):\n    \"\"\"set the colors for text.\"\"\"\n    HEADER = '\\033[92m'\n    ENDC = '\\033[0m'\n    print(HEADER + value_color + ENDC + str(value_noncolor))", "title": ""}
{"_id": "d859", "text": "def is_seq(obj):\n    \"\"\" Returns True if object is not a string but is iterable \"\"\"\n    if not hasattr(obj, '__iter__'):\n        return False\n    if isinstance(obj, basestring):\n        return False\n    return True", "title": ""}
{"_id": "d860", "text": "def logger(message, level=10):\n    \"\"\"Handle logging.\"\"\"\n    logging.getLogger(__name__).log(level, str(message))", "title": ""}
{"_id": "d861", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d862", "text": "def _convert_to_array(array_like, dtype):\n        \"\"\"\n        Convert Matrix attributes which are array-like or buffer to array.\n        \"\"\"\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)", "title": ""}
{"_id": "d863", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d864", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d865", "text": "def is_non_empty_string(input_string):\n    \"\"\"\n    Validate if non empty string\n\n    :param input_string: Input is a *str*.\n    :return: True if input is string and non empty.\n       Raise :exc:`Exception` otherwise.\n    \"\"\"\n    try:\n        if not input_string.strip():\n            raise ValueError()\n    except AttributeError as error:\n        raise TypeError(error)\n\n    return True", "title": ""}
{"_id": "d866", "text": "def get_naive(dt):\n  \"\"\"Gets a naive datetime from a datetime.\n\n  datetime_tz objects can't just have tzinfo replaced with None, you need to\n  call asdatetime.\n\n  Args:\n    dt: datetime object.\n\n  Returns:\n    datetime object without any timezone information.\n  \"\"\"\n  if not dt.tzinfo:\n    return dt\n  if hasattr(dt, \"asdatetime\"):\n    return dt.asdatetime()\n  return dt.replace(tzinfo=None)", "title": ""}
{"_id": "d867", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d868", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d869", "text": "def isnumber(*args):\n    \"\"\"Checks if value is an integer, long integer or float.\n\n    NOTE: Treats booleans as numbers, where True=1 and False=0.\n    \"\"\"\n    return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))", "title": ""}
{"_id": "d870", "text": "def relpath(path):\n    \"\"\"Path helper, gives you a path relative to this file\"\"\"\n    return os.path.normpath(\n        os.path.join(os.path.abspath(os.path.dirname(__file__)), path)\n    )", "title": ""}
{"_id": "d871", "text": "def cudaDriverGetVersion():\n    \"\"\"\n    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.\n\n    \"\"\"\n\n    version = ctypes.c_int()\n    status = _libcudart.cudaDriverGetVersion(ctypes.byref(version))\n    cudaCheckStatus(status)\n    return version.value", "title": ""}
{"_id": "d872", "text": "def israw(self, **kwargs):\n        \"\"\"\n        Returns True if the PTY should operate in raw mode.\n\n        If the container was not started with tty=True, this will return False.\n        \"\"\"\n\n        if self.raw is None:\n            info = self._container_info()\n            self.raw = self.stdout.isatty() and info['Config']['Tty']\n\n        return self.raw", "title": ""}
{"_id": "d873", "text": "def skip_connection_distance(a, b):\n    \"\"\"The distance between two skip-connections.\"\"\"\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))", "title": ""}
{"_id": "d874", "text": "def html(header_rows):\n    \"\"\"\n    Convert a list of tuples describing a table into a HTML string\n    \"\"\"\n    name = 'table%d' % next(tablecounter)\n    return HtmlTable([map(str, row) for row in header_rows], name).render()", "title": ""}
{"_id": "d875", "text": "def isSquare(matrix):\n    \"\"\"Check that ``matrix`` is square.\n\n    Returns\n    =======\n    is_square : bool\n        ``True`` if ``matrix`` is square, ``False`` otherwise.\n\n    \"\"\"\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", "title": ""}
{"_id": "d876", "text": "def ver_to_tuple(value):\n    \"\"\"\n    Convert version like string to a tuple of integers.\n    \"\"\"\n    return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "title": ""}
{"_id": "d877", "text": "def is_type(value):\n        \"\"\"Determine if value is an instance or subclass of the class Type.\"\"\"\n        if isinstance(value, type):\n            return issubclass(value, Type)\n        return isinstance(value, Type)", "title": ""}
{"_id": "d878", "text": "def _strvar(a, prec='{:G}'):\n    r\"\"\"Return variable as a string to print, with given precision.\"\"\"\n    return ' '.join([prec.format(i) for i in np.atleast_1d(a)])", "title": ""}
{"_id": "d879", "text": "def check_filename(filename):\n    \"\"\"\n    Returns a boolean stating if the filename is safe to use or not. Note that\n    this does not test for \"legal\" names accepted, but a more restricted set of:\n    Letters, numbers, spaces, hyphens, underscores and periods.\n\n    :param filename: name of a file as a string\n    :return: boolean if it is a safe file name\n    \"\"\"\n    if not isinstance(filename, str):\n        raise TypeError(\"filename must be a string\")\n    if regex.path.linux.filename.search(filename):\n        return True\n    return False", "title": ""}
{"_id": "d880", "text": "def GeneratePassphrase(length=20):\n  \"\"\"Create a 20 char passphrase with easily typeable chars.\"\"\"\n  valid_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  valid_chars += \"0123456789 ,-_&$#\"\n  return \"\".join(random.choice(valid_chars) for i in range(length))", "title": ""}
{"_id": "d881", "text": "def is_float(value):\n    \"\"\"must be a float\"\"\"\n    return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "title": ""}
{"_id": "d882", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d883", "text": "def on_source_directory_chooser_clicked(self):\n        \"\"\"Autoconnect slot activated when tbSourceDir is clicked.\"\"\"\n\n        title = self.tr('Set the source directory for script and scenario')\n        self.choose_directory(self.source_directory, title)", "title": ""}
{"_id": "d884", "text": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "title": ""}
{"_id": "d885", "text": "def clean_all(self, args):\n        \"\"\"Delete all build components; the package cache, package builds,\n        bootstrap builds and distributions.\"\"\"\n        self.clean_dists(args)\n        self.clean_builds(args)\n        self.clean_download_cache(args)", "title": ""}
{"_id": "d886", "text": "def _merge_maps(m1, m2):\n    \"\"\"merge two Mapping objects, keeping the type of the first mapping\"\"\"\n    return type(m1)(chain(m1.items(), m2.items()))", "title": ""}
{"_id": "d887", "text": "def strip(notebook):\n    \"\"\"Remove outputs from a notebook.\"\"\"\n    for cell in notebook.cells:\n        if cell.cell_type == 'code':\n            cell.outputs = []\n            cell.execution_count = None", "title": ""}
{"_id": "d888", "text": "def find_whole_word(w):\n    \"\"\"\n    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.\n    \"\"\"\n    return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search", "title": ""}
{"_id": "d889", "text": "def __delitem__(self, resource):\n        \"\"\"Remove resource instance from internal cache\"\"\"\n        self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None)", "title": ""}
{"_id": "d890", "text": "def autozoom(self, n=None):\n        \"\"\"\n        Auto-scales the axes to fit all the data in plot index n. If n == None,\n        auto-scale everyone.\n        \"\"\"\n        if n==None:\n            for p in self.plot_widgets: p.autoRange()\n        else:        self.plot_widgets[n].autoRange()\n\n        return self", "title": ""}
{"_id": "d891", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d892", "text": "def color_to_hex(color):\n    \"\"\"Convert matplotlib color code to hex color code\"\"\"\n    if color is None or colorConverter.to_rgba(color)[3] == 0:\n        return 'none'\n    else:\n        rgb = colorConverter.to_rgb(color)\n        return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))", "title": ""}
{"_id": "d893", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d894", "text": "def horizontal_line(ax, scale, i, **kwargs):\n    \"\"\"\n    Draws the i-th horizontal line parallel to the lower axis.\n\n    Parameters\n    ----------\n    ax: Matplotlib AxesSubplot\n        The subplot to draw on.\n    scale: float, 1.0\n        Simplex scale size.\n    i: float\n        The index of the line to draw\n    kwargs: Dictionary\n        Any kwargs to pass through to Matplotlib.\n    \"\"\"\n\n    p1 = (0, i, scale - i)\n    p2 = (scale - i, i, 0)\n    line(ax, p1, p2, **kwargs)", "title": ""}
{"_id": "d895", "text": "def terminate(self):\n        \"\"\"Terminate all workers and threads.\"\"\"\n        for t in self._threads:\n            t.quit()\n        self._thread = []\n        self._workers = []", "title": ""}
{"_id": "d896", "text": "def raise_figure_window(f=0):\n    \"\"\"\n    Raises the supplied figure number or figure window.\n    \"\"\"\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()", "title": ""}
{"_id": "d897", "text": "def linregress(x, y, return_stats=False):\n    \"\"\"linear regression calculation\n\n    Parameters\n    ----\n    x :         independent variable (series)\n    y :         dependent variable (series)\n    return_stats : returns statistical values as well if required (bool)\n    \n\n    Returns\n    ----\n    list of parameters (and statistics)\n    \"\"\"\n    a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y)\n\n    retval = a1, a0\n    if return_stats:\n        retval += r_value, p_value, stderr\n\n    return retval", "title": ""}
{"_id": "d898", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d899", "text": "def set_ylimits(self, row, column, min=None, max=None):\n        \"\"\"Set y-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_ylimits(min, max)", "title": ""}
{"_id": "d900", "text": "def _norm(self, x):\n    \"\"\"Compute the safe norm.\"\"\"\n    return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7)", "title": ""}
{"_id": "d901", "text": "def show(self, imgs, ax=None):\n        \"\"\" Visualize the persistence image\n\n        \"\"\"\n\n        ax = ax or plt.gca()\n\n        if type(imgs) is not list:\n            imgs = [imgs]\n\n        for i, img in enumerate(imgs):\n            ax.imshow(img, cmap=plt.get_cmap(\"plasma\"))\n            ax.axis(\"off\")", "title": ""}
{"_id": "d902", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d903", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d904", "text": "def cmp_contents(filename1, filename2):\n    \"\"\" Returns True if contents of the files are the same\n\n    Parameters\n    ----------\n    filename1 : str\n        filename of first file to compare\n    filename2 : str\n        filename of second file to compare\n\n    Returns\n    -------\n    tf : bool\n        True if binary contents of `filename1` is same as binary contents of\n        `filename2`, False otherwise.\n    \"\"\"\n    with open_readable(filename1, 'rb') as fobj:\n        contents1 = fobj.read()\n    with open_readable(filename2, 'rb') as fobj:\n        contents2 = fobj.read()\n    return contents1 == contents2", "title": ""}
{"_id": "d905", "text": "def _digits(minval, maxval):\n    \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n    if minval == maxval:\n        return 3\n    else:\n        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "title": ""}
{"_id": "d906", "text": "def compare(a, b):\n    \"\"\"\n     Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))\n    \"\"\"\n    s=0\n    for i in range(len(a)):\n        s=s+abs(a[i]-b[i])\n    return s", "title": ""}
{"_id": "d907", "text": "def compare(left, right):\n    \"\"\"\n    yields EVENT,ENTRY pairs describing the differences between left\n    and right, which are filenames for a pair of zip files\n    \"\"\"\n\n    with open_zip(left) as l:\n        with open_zip(right) as r:\n            return compare_zips(l, r)", "title": ""}
{"_id": "d908", "text": "def coverage():\n    \"\"\"Run coverage tests.\"\"\"\n    # Note: coverage options are controlled by .coveragerc file\n    install()\n    test_setup()\n    sh(\"%s -m coverage run %s\" % (PYTHON, TEST_SCRIPT))\n    sh(\"%s -m coverage report\" % PYTHON)\n    sh(\"%s -m coverage html\" % PYTHON)\n    sh(\"%s -m webbrowser -t htmlcov/index.html\" % PYTHON)", "title": ""}
{"_id": "d909", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d910", "text": "def m(name='', **kwargs):\n    \"\"\"\n    Print out memory usage at this point in time\n\n    http://docs.python.org/2/library/resource.html\n    http://stackoverflow.com/a/15448600/5006\n    http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended\n    \"\"\"\n    with Reflect.context(**kwargs) as r:\n        kwargs[\"name\"] = name\n        instance = M_CLASS(r, stream, **kwargs)\n        instance()", "title": ""}
{"_id": "d911", "text": "def cpp_prog_builder(build_context, target):\n    \"\"\"Build a C++ binary executable\"\"\"\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)", "title": ""}
{"_id": "d912", "text": "def dictmerge(x, y):\n    \"\"\"\n    merge two dictionaries\n    \"\"\"\n    z = x.copy()\n    z.update(y)\n    return z", "title": ""}
{"_id": "d913", "text": "def advance_one_line(self):\n    \"\"\"Advances to next line.\"\"\"\n\n    current_line = self._current_token.line_number\n    while current_line == self._current_token.line_number:\n      self._current_token = ConfigParser.Token(*next(self._token_generator))", "title": ""}
{"_id": "d914", "text": "def merge(self, other):\n        \"\"\" Merge another stats. \"\"\"\n        Stats.merge(self, other)\n        self.changes += other.changes", "title": ""}
{"_id": "d915", "text": "def display_len(text):\n    \"\"\"\n    Get the display length of a string. This can differ from the character\n    length if the string contains wide characters.\n    \"\"\"\n    text = unicodedata.normalize('NFD', text)\n    return sum(char_width(char) for char in text)", "title": ""}
{"_id": "d916", "text": "def Proxy(f):\n  \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n\n  return Wrapped", "title": ""}
{"_id": "d917", "text": "def _message_to_string(message, data=None):\n    \"\"\" Gives a string representation of a PB2 message. \"\"\"\n    if data is None:\n        data = _json_from_message(message)\n\n    return \"Message {} from {} to {}: {}\".format(\n        message.namespace, message.source_id, message.destination_id, data)", "title": ""}
{"_id": "d918", "text": "def fn_min(self, a, axis=None):\n        \"\"\"\n        Return the minimum of an array, ignoring any NaNs.\n\n        :param a: The array.\n        :return: The minimum value of the array.\n        \"\"\"\n\n        return numpy.nanmin(self._to_ndarray(a), axis=axis)", "title": ""}
{"_id": "d919", "text": "def arr_to_vector(arr):\n    \"\"\"Reshape a multidimensional array to a vector.\n    \"\"\"\n    dim = array_dim(arr)\n    tmp_arr = []\n    for n in range(len(dim) - 1):\n        for inner in arr:\n            for i in inner:\n                tmp_arr.append(i)\n        arr = tmp_arr\n        tmp_arr = []\n    return arr", "title": ""}
{"_id": "d920", "text": "def min_values(args):\n    \"\"\" Return possible range for min function. \"\"\"\n    return Interval(min(x.low for x in args), min(x.high for x in args))", "title": ""}
{"_id": "d921", "text": "def post_process(self):\n        \"\"\" Apply last 2D transforms\"\"\"\n        self.image.putdata(self.pixels)\n        self.image = self.image.transpose(Image.ROTATE_90)", "title": ""}
{"_id": "d922", "text": "def makedirs(path, mode=0o777, exist_ok=False):\n    \"\"\"A wrapper of os.makedirs().\"\"\"\n    os.makedirs(path, mode, exist_ok)", "title": ""}
{"_id": "d923", "text": "def autoconvert(string):\n    \"\"\"Try to convert variables into datatypes.\"\"\"\n    for fn in (boolify, int, float):\n        try:\n            return fn(string)\n        except ValueError:\n            pass\n    return string", "title": ""}
{"_id": "d924", "text": "def _from_dict(cls, _dict):\n        \"\"\"Initialize a ListCollectionsResponse object from a json dictionary.\"\"\"\n        args = {}\n        if 'collections' in _dict:\n            args['collections'] = [\n                Collection._from_dict(x) for x in (_dict.get('collections'))\n            ]\n        return cls(**args)", "title": ""}
{"_id": "d925", "text": "def most_common(items):\n    \"\"\"\n    Wanted functionality from Counters (new in Python 2.7).\n    \"\"\"\n    counts = {}\n    for i in items:\n        counts.setdefault(i, 0)\n        counts[i] += 1\n    return max(six.iteritems(counts), key=operator.itemgetter(1))", "title": ""}
{"_id": "d926", "text": "def find_one(cls, *args, **kwargs):\n        \"\"\"Run a find_one on this model's collection.  The arguments to\n        ``Model.find_one`` are the same as to ``pymongo.Collection.find_one``.\"\"\"\n        database, collection = cls._collection_key.split('.')\n        return current()[database][collection].find_one(*args, **kwargs)", "title": ""}
{"_id": "d927", "text": "def indentsize(line):\n    \"\"\"Return the indent size, in spaces, at the start of a line of text.\"\"\"\n    expline = string.expandtabs(line)\n    return len(expline) - len(string.lstrip(expline))", "title": ""}
{"_id": "d928", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d929", "text": "def make_env_key(app_name, key):\n    \"\"\"Creates an environment key-equivalent for the given key\"\"\"\n    key = key.replace('-', '_').replace(' ', '_')\n    return str(\"_\".join((x.upper() for x in (app_name, key))))", "title": ""}
{"_id": "d930", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d931", "text": "def touch():\n    \"\"\"Create new bucket.\"\"\"\n    from .models import Bucket\n    bucket = Bucket.create()\n    db.session.commit()\n    click.secho(str(bucket), fg='green')", "title": ""}
{"_id": "d932", "text": "def align_file_position(f, size):\n    \"\"\" Align the position in the file to the next block of specified size \"\"\"\n    align = (size - 1) - (f.tell() % size)\n    f.seek(align, 1)", "title": ""}
{"_id": "d933", "text": "def format_header_cell(val):\n    \"\"\"\n    Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and\n    all other '_' to spaces.\n    \"\"\"\n    return re.sub('_', ' ', re.sub(r'(_Px_)', '(', re.sub(r'(_xP_)', ')', str(val) )))", "title": ""}
{"_id": "d934", "text": "def go_to_line(self, line):\n        \"\"\"\n        Moves the text cursor to given line.\n\n        :param line: Line to go to.\n        :type line: int\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        cursor = self.textCursor()\n        cursor.setPosition(self.document().findBlockByNumber(line - 1).position())\n        self.setTextCursor(cursor)\n        return True", "title": ""}
{"_id": "d935", "text": "def copy(self):\n        \"\"\"Return a shallow copy of the sorted dictionary.\"\"\"\n        return self.__class__(self._key, self._load, self._iteritems())", "title": ""}
{"_id": "d936", "text": "def singleton(class_):\n    \"\"\"Singleton definition.\n\n    Method 1 from\n    https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n    \"\"\"\n    instances = {}\n\n    def get_instance(*args, **kwargs):\n        if class_ not in instances:\n            instances[class_] = class_(*args, **kwargs)\n        return instances[class_]\n    return get_instance", "title": ""}
{"_id": "d937", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d938", "text": "def _match_space_at_line(line):\n    \"\"\"Return a re.match object if an empty comment was found on line.\"\"\"\n    regex = re.compile(r\"^{0}$\".format(_MDL_COMMENT))\n    return regex.match(line)", "title": ""}
{"_id": "d939", "text": "def create_symlink(source, link_name):\n    \"\"\"\n    Creates symbolic link for either operating system.\n\n    http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows\n    \"\"\"\n    os_symlink = getattr(os, \"symlink\", None)\n    if isinstance(os_symlink, collections.Callable):\n        os_symlink(source, link_name)\n    else:\n        import ctypes\n        csl = ctypes.windll.kernel32.CreateSymbolicLinkW\n        csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n        csl.restype = ctypes.c_ubyte\n        flags = 1 if os.path.isdir(source) else 0\n        if csl(link_name, source, flags) == 0:\n            raise ctypes.WinError()", "title": ""}
{"_id": "d940", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d941", "text": "def count_generator(generator, memory_efficient=True):\n    \"\"\"Count number of item in generator.\n\n    memory_efficient=True, 3 times slower, but memory_efficient.\n    memory_efficient=False, faster, but cost more memory.\n    \"\"\"\n    if memory_efficient:\n        counter = 0\n        for _ in generator:\n            counter += 1\n        return counter\n    else:\n        return len(list(generator))", "title": ""}
{"_id": "d942", "text": "def replace_sys_args(new_args):\n    \"\"\"Temporarily replace sys.argv with current arguments\n\n    Restores sys.argv upon exit of the context manager.\n    \"\"\"\n    # Replace sys.argv arguments\n    # for module import\n    old_args = sys.argv\n    sys.argv = new_args\n    try:\n        yield\n    finally:\n        sys.argv = old_args", "title": ""}
{"_id": "d943", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d944", "text": "def export_context(cls, context):\n\t\t\"\"\" Export the specified context to be capable context transferring\n\n\t\t:param context: context to export\n\t\t:return: tuple\n\t\t\"\"\"\n\t\tif context is None:\n\t\t\treturn\n\t\tresult = [(x.context_name(), x.context_value()) for x in context]\n\t\tresult.reverse()\n\t\treturn tuple(result)", "title": ""}
{"_id": "d945", "text": "def generate_matrices(dim = 40):\n  \"\"\"\n  Generates the matrices that positive and negative samples are multiplied\n  with.  The matrix for positive samples is randomly drawn from a uniform\n  distribution, with elements in [-1, 1].  The matrix for negative examples\n  is the sum of the positive matrix with a matrix drawn from a normal\n  distribution with mean 0 variance 1.\n  \"\"\"\n  positive = numpy.random.uniform(-1, 1, (dim, dim))\n  negative = positive + numpy.random.normal(0, 1, (dim, dim))\n  return positive, negative", "title": ""}
{"_id": "d946", "text": "def qr(self,text):\n        \"\"\" Print QR Code for the provided string \"\"\"\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        # Convert the RGB image in printable image\n        self._convert_image(im)", "title": ""}
{"_id": "d947", "text": "def to_unicode_repr( _letter ):\n    \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n        in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n    # Python 2-3 compatible\n    return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"", "title": ""}
{"_id": "d948", "text": "def compute(args):\n    x, y, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot(x, y, params)", "title": ""}
{"_id": "d949", "text": "def clear_global(self):\n        \"\"\"Clear only any cached global data.\n\n        \"\"\"\n        vname = self.varname\n        logger.debug(f'global clearning {vname}')\n        if vname in globals():\n            logger.debug('removing global instance var: {}'.format(vname))\n            del globals()[vname]", "title": ""}
{"_id": "d950", "text": "def get(self):\n        \"\"\"retrieve a result from the pool\n\n        if nothing is already completed when this method is called, it will\n        block until something comes back\n\n        if the pool's function exited via exception, that will come back as\n        a result here as well, but will be re-raised in :meth:`get`.\n\n        .. note::\n            if there is nothing in the pool's output queue when this method is\n            called, it will block until something is ready\n\n        :returns:\n            a return value from one of the function's invocations if it exited\n            normally\n\n        :raises:\n            :class:`PoolClosed` if the pool was closed before a result could be\n            produced for thie call\n\n        :raises: any exception that was raised inside the worker function\n        \"\"\"\n        if self.closed:\n            raise PoolClosed()\n\n        while self._getcount not in self._cache:\n            counter, result = self.outq.get()\n            self._cache[counter] = result\n\n        result, succeeded = self._cache.pop(self._getcount)\n        self._getcount += 1\n\n        if not succeeded:\n            klass, exc, tb = result\n            raise klass, exc, tb\n        return result", "title": ""}
{"_id": "d951", "text": "def _release(self):\n        \"\"\"Destroy self since closures cannot be called again.\"\"\"\n        del self.funcs\n        del self.variables\n        del self.variable_values\n        del self.satisfied", "title": ""}
{"_id": "d952", "text": "def compute_capture(args):\n    x, y, w, h, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot_capture(x, y, w, h, params)", "title": ""}
{"_id": "d953", "text": "def __delitem__(self, key):\n        \"\"\"Remove a variable from this dataset.\n        \"\"\"\n        del self._variables[key]\n        self._coord_names.discard(key)", "title": ""}
{"_id": "d954", "text": "def get(self):\n        \"\"\"Get the highest priority Processing Block from the queue.\"\"\"\n        with self._mutex:\n            entry = self._queue.pop()\n            del self._block_map[entry[2]]\n            return entry[2]", "title": ""}
{"_id": "d955", "text": "def remove_columns(self, data, columns):\n        \"\"\" This method removes columns in data\n\n        :param data: original Pandas dataframe\n        :param columns: list of columns to remove\n        :type data: pandas.DataFrame\n        :type columns: list of strings\n\n        :returns: Pandas dataframe with removed columns\n        :rtype: pandas.DataFrame\n        \"\"\"\n\n        for column in columns:\n            if column in data.columns:\n                data = data.drop(column, axis=1)\n\n        return data", "title": ""}
{"_id": "d956", "text": "def _synced(method, self, args, kwargs):\n    \"\"\"Underlying synchronized wrapper.\"\"\"\n    with self._lock:\n        return method(*args, **kwargs)", "title": ""}
{"_id": "d957", "text": "def _delete_local(self, filename):\n        \"\"\"Deletes the specified file from the local filesystem.\"\"\"\n\n        if os.path.exists(filename):\n            os.remove(filename)", "title": ""}
{"_id": "d958", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d959", "text": "def remove_elements(target, indices):\n    \"\"\"Remove multiple elements from a list and return result.\n    This implementation is faster than the alternative below.\n    Also note the creation of a new list to avoid altering the\n    original. We don't have any current use for the original\n    intact list, but may in the future...\"\"\"\n\n    copied = list(target)\n\n    for index in reversed(indices):\n        del copied[index]\n    return copied", "title": ""}
{"_id": "d960", "text": "def get_window(self): \n        \"\"\"\n        Returns the object's parent window. Returns None if no window found.\n        \"\"\"\n        x = self\n        while not x._parent == None and \\\n              not isinstance(x._parent, Window): \n                  x = x._parent\n        return x._parent", "title": ""}
{"_id": "d961", "text": "def remove_bad(string):\n    \"\"\"\n    remove problem characters from string\n    \"\"\"\n    remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n    for c in remove:\n        string = string.replace(c, '_')\n    return string", "title": ""}
{"_id": "d962", "text": "def restore_scrollbar_position(self):\n        \"\"\"Restoring scrollbar position after main window is visible\"\"\"\n        scrollbar_pos = self.get_option('scrollbar_position', None)\n        if scrollbar_pos is not None:\n            self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)", "title": ""}
{"_id": "d963", "text": "def rm_empty_indices(*args):\n    \"\"\"\n    Remove unwanted list indices. First argument is the list\n    of indices to remove. Other elements are the lists\n    to trim.\n    \"\"\"\n    rm_inds = args[0]\n\n    if not rm_inds:\n        return args[1:]\n\n    keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n    return [[a[i] for i in keep_inds] for a in args[1:]]", "title": ""}
{"_id": "d964", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d965", "text": "def deprecate(func):\n  \"\"\" A deprecation warning emmiter as a decorator. \"\"\"\n  @wraps(func)\n  def wrapper(*args, **kwargs):\n    warn(\"Deprecated, this will be removed in the future\", DeprecationWarning)\n    return func(*args, **kwargs)\n  wrapper.__doc__ = \"Deprecated.\\n\" + (wrapper.__doc__ or \"\")\n  return wrapper", "title": ""}
{"_id": "d966", "text": "def remove_node(self, node):\n        \"\"\" Remove a node from this network. \"\"\"\n        if _debug: Network._debug(\"remove_node %r\", node)\n\n        self.nodes.remove(node)\n        node.lan = None", "title": ""}
{"_id": "d967", "text": "def deprecate(func):\n  \"\"\" A deprecation warning emmiter as a decorator. \"\"\"\n  @wraps(func)\n  def wrapper(*args, **kwargs):\n    warn(\"Deprecated, this will be removed in the future\", DeprecationWarning)\n    return func(*args, **kwargs)\n  wrapper.__doc__ = \"Deprecated.\\n\" + (wrapper.__doc__ or \"\")\n  return wrapper", "title": ""}
{"_id": "d968", "text": "def wordify(text):\n    \"\"\"Generate a list of words given text, removing punctuation.\n\n    Parameters\n    ----------\n    text : unicode\n        A piece of english text.\n\n    Returns\n    -------\n    words : list\n        List of words.\n    \"\"\"\n    stopset = set(nltk.corpus.stopwords.words('english'))\n    tokens = nltk.WordPunctTokenizer().tokenize(text)\n    return [w for w in tokens if w not in stopset]", "title": ""}
{"_id": "d969", "text": "def is_admin(self):\n        \"\"\"Is the user a system administrator\"\"\"\n        return self.role == self.roles.administrator.value and self.state == State.approved", "title": ""}
{"_id": "d970", "text": "def start_connect(self):\n    \"\"\"Tries to connect to the Heron Server\n\n    ``loop()`` method needs to be called after this.\n    \"\"\"\n    Log.debug(\"In start_connect() of %s\" % self._get_classname())\n    # TODO: specify buffer size, exception handling\n    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n\n    # when ready, handle_connect is called\n    self._connecting = True\n    self.connect(self.endpoint)", "title": ""}
{"_id": "d971", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d972", "text": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "title": ""}
{"_id": "d973", "text": "def lognorm(x, mu, sigma=1.0):\n    \"\"\" Log-normal function from scipy \"\"\"\n    return stats.lognorm(sigma, scale=mu).pdf(x)", "title": ""}
{"_id": "d974", "text": "def _api_type(self, value):\n        \"\"\"\n        Returns the API type of the given value based on its python type.\n\n        \"\"\"\n        if isinstance(value, six.string_types):\n            return 'string'\n        elif isinstance(value, six.integer_types):\n            return 'integer'\n        elif type(value) is datetime.datetime:\n            return 'date'", "title": ""}
{"_id": "d975", "text": "def denorm(self,arr):\n        \"\"\"Reverse the normalization done to a batch of images.\n\n        Arguments:\n            arr: of shape/size (N,3,sz,sz)\n        \"\"\"\n        if type(arr) is not np.ndarray: arr = to_np(arr)\n        if len(arr.shape)==3: arr = arr[None]\n        return self.transform.denorm(np.rollaxis(arr,1,4))", "title": ""}
{"_id": "d976", "text": "def is_seq(obj):\n    \"\"\"\n    Check if an object is a sequence.\n    \"\"\"\n    return (not is_str(obj) and not is_dict(obj) and\n            (hasattr(obj, \"__getitem__\") or hasattr(obj, \"__iter__\")))", "title": ""}
{"_id": "d977", "text": "def isTestCaseDisabled(test_case_class, method_name):\n    \"\"\"\n    I check to see if a method on a TestCase has been disabled via nose's\n    convention for disabling a TestCase.  This makes it so that users can\n    mix nose's parameterized tests with green as a runner.\n    \"\"\"\n    test_method = getattr(test_case_class, method_name)\n    return getattr(test_method, \"__test__\", 'not nose') is False", "title": ""}
{"_id": "d978", "text": "def _histplot_bins(column, bins=100):\n    \"\"\"Helper to get bins for histplot.\"\"\"\n    col_min = np.min(column)\n    col_max = np.max(column)\n    return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))", "title": ""}
{"_id": "d979", "text": "def prepare(doc):\n    \"\"\"Sets the caption_found and plot_found variables to False.\"\"\"\n    doc.caption_found = False\n    doc.plot_found = False\n    doc.listings_counter = 0", "title": ""}
{"_id": "d980", "text": "def path_for_import(name):\n    \"\"\"\n    Returns the directory path for the given package or module.\n    \"\"\"\n    return os.path.dirname(os.path.abspath(import_module(name).__file__))", "title": ""}
{"_id": "d981", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d982", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d983", "text": "def chunked(l, n):\n    \"\"\"Chunk one big list into few small lists.\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d984", "text": "def contains_all(self, array):\n        \"\"\"Test if `array` is an array of real numbers.\"\"\"\n        dtype = getattr(array, 'dtype', None)\n        if dtype is None:\n            dtype = np.result_type(*array)\n        return is_real_dtype(dtype)", "title": ""}
{"_id": "d985", "text": "def quit(self):\n        \"\"\" Exit the program due to user's choices.\n        \"\"\"\n        self.script.LOG.warn(\"Abort due to user choice!\")\n        sys.exit(self.QUIT_RC)", "title": ""}
{"_id": "d986", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d987", "text": "def print_images(self, *printable_images):\n        \"\"\"\n        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\n        \"\"\"\n        printable_image = reduce(lambda x, y: x.append(y), list(printable_images))\n        self.print_image(printable_image)", "title": ""}
{"_id": "d988", "text": "def ma(self):\n        \"\"\"Represent data as a masked array.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n        inf and nan are filtered via :func:`numpy.isfinite`.\n        \"\"\"\n        a = self.array\n        return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))", "title": ""}
{"_id": "d989", "text": "def _divide(self, x1, x2, out):\n        \"\"\"Raw pointwise multiplication of two elements.\"\"\"\n        self.tspace._divide(x1.tensor, x2.tensor, out.tensor)", "title": ""}
{"_id": "d990", "text": "def _to_json(self):\n        \"\"\" Gets a dict of this object's properties so that it can be used to send a dump to the client \"\"\"\n        return dict(( (k, v) for k, v in self.__dict__.iteritems() if k != 'server'))", "title": ""}
{"_id": "d991", "text": "def _user_yes_no_query(self, question):\n        \"\"\" Helper asking if the user want to download the file\n\n        Note:\n            Dowloading huge file can take a while\n\n        \"\"\"\n        sys.stdout.write('%s [y/n]\\n' % question)\n        while True:\n            try:\n                return strtobool(raw_input().lower())\n            except ValueError:\n                sys.stdout.write('Please respond with \\'y\\' or \\'n\\'.\\n')", "title": ""}
{"_id": "d992", "text": "def json_datetime_serial(obj):\n    \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n    if isinstance(obj, (datetime, date)):\n        serial = obj.isoformat()\n        return serial\n\n    if ObjectId is not None and isinstance(obj, ObjectId):\n        # TODO: try to use bson.json_util instead\n        return str(obj)\n\n    raise TypeError(\"Type not serializable\")", "title": ""}
{"_id": "d993", "text": "def downcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n    return [ tt.lower() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d994", "text": "def to_one_hot(dataY):\n    \"\"\"Convert the vector of labels dataY into one-hot encoding.\n\n    :param dataY: vector of labels\n    :return: one-hot encoded labels\n    \"\"\"\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", "title": ""}
{"_id": "d995", "text": "def matrix_at_check(self, original, loc, tokens):\n        \"\"\"Check for Python 3.5 matrix multiplication.\"\"\"\n        return self.check_py(\"35\", \"matrix multiplication\", original, loc, tokens)", "title": ""}
{"_id": "d996", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d997", "text": "def _fix_up(self, cls, code_name):\n    \"\"\"Internal helper called to tell the property its name.\n\n    This is called by _fix_up_properties() which is called by\n    MetaModel when finishing the construction of a Model subclass.\n    The name passed in is the name of the class attribute to which the\n    Property is assigned (a.k.a. the code name).  Note that this means\n    that each Property instance must be assigned to (at most) one\n    class attribute.  E.g. to declare three strings, you must call\n    StringProperty() three times, you cannot write\n\n      foo = bar = baz = StringProperty()\n    \"\"\"\n    self._code_name = code_name\n    if self._name is None:\n      self._name = code_name", "title": ""}
{"_id": "d998", "text": "def dot_v3(v, w):\n    \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n    return sum([x * y for x, y in zip(v, w)])", "title": ""}
{"_id": "d999", "text": "def dict_update_newkeys(dict_, dict2):\n    \"\"\" Like dict.update, but does not overwrite items \"\"\"\n    for key, val in six.iteritems(dict2):\n        if key not in dict_:\n            dict_[key] = val", "title": ""}
{"_id": "d1000", "text": "def download_json(local_filename, url, clobber=False):\n    \"\"\"Download the given JSON file, and pretty-print before we output it.\"\"\"\n    with open(local_filename, 'w') as json_file:\n        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))", "title": ""}
{"_id": "d1001", "text": "def read_img(path):\n    \"\"\" Reads image specified by path into numpy.ndarray\"\"\"\n    img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255\n    img = np.expand_dims(img.transpose(1, 0), 0)\n    return img", "title": ""}
{"_id": "d1002", "text": "def download_json(local_filename, url, clobber=False):\n    \"\"\"Download the given JSON file, and pretty-print before we output it.\"\"\"\n    with open(local_filename, 'w') as json_file:\n        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))", "title": ""}
{"_id": "d1003", "text": "def file_to_str(fname):\n    \"\"\"\n    Read a file into a string\n    PRE: fname is a small file (to avoid hogging memory and its discontents)\n    \"\"\"\n    data = None\n    # rU = read with Universal line terminator\n    with open(fname, 'rU') as fd:\n        data = fd.read()\n    return data", "title": ""}
{"_id": "d1004", "text": "def _download_py3(link, path, __hdr__):\n    \"\"\"Download a file from a link in Python 3.\"\"\"\n    try:\n        req = urllib.request.Request(link, headers=__hdr__)\n        u = urllib.request.urlopen(req)\n    except Exception as e:\n        raise Exception(' Download failed with the error:\\n{}'.format(e))\n\n    with open(path, 'wb') as outf:\n        for l in u:\n            outf.write(l)\n    u.close()", "title": ""}
{"_id": "d1005", "text": "def create_symlink(source, link_name):\n    \"\"\"\n    Creates symbolic link for either operating system.\n\n    http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows\n    \"\"\"\n    os_symlink = getattr(os, \"symlink\", None)\n    if isinstance(os_symlink, collections.Callable):\n        os_symlink(source, link_name)\n    else:\n        import ctypes\n        csl = ctypes.windll.kernel32.CreateSymbolicLinkW\n        csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n        csl.restype = ctypes.c_ubyte\n        flags = 1 if os.path.isdir(source) else 0\n        if csl(link_name, source, flags) == 0:\n            raise ctypes.WinError()", "title": ""}
{"_id": "d1006", "text": "def to_dotfile(self):\n        \"\"\" Writes a DOT graphviz file of the domain structure, and returns the filename\"\"\"\n        domain = self.get_domain()\n        filename = \"%s.dot\" % (self.__class__.__name__)\n        nx.write_dot(domain, filename)\n        return filename", "title": ""}
{"_id": "d1007", "text": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "title": ""}
{"_id": "d1008", "text": "def _drop_str_columns(df):\n    \"\"\"\n\n    Parameters\n    ----------\n    df : DataFrame\n\n    Returns\n    -------\n\n    \"\"\"\n    str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())\n    str_column_names = list(map(lambda pair: pair[0], str_columns))\n\n    return df.drop(str_column_names)", "title": ""}
{"_id": "d1009", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d1010", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d1011", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d1012", "text": "def remove_duplicates(lst):\n    \"\"\"\n    Emulate what a Python ``set()`` does, but keeping the element's order.\n    \"\"\"\n    dset = set()\n    return [l for l in lst if l not in dset and not dset.add(l)]", "title": ""}
{"_id": "d1013", "text": "def normalize_path(path):\n    \"\"\"\n    Convert a path to its canonical, case-normalized, absolute version.\n\n    \"\"\"\n    return os.path.normcase(os.path.realpath(os.path.expanduser(path)))", "title": ""}
{"_id": "d1014", "text": "def haversine(x):\n    \"\"\"Return the haversine of an angle\n\n    haversine(x) = sin(x/2)**2, where x is an angle in radians\n    \"\"\"\n    y = .5*x\n    y = np.sin(y)\n    return y*y", "title": ""}
{"_id": "d1015", "text": "def __get_float(section, name):\n    \"\"\"Get the forecasted float from json section.\"\"\"\n    try:\n        return float(section[name])\n    except (ValueError, TypeError, KeyError):\n        return float(0)", "title": ""}
{"_id": "d1016", "text": "def min_values(args):\n    \"\"\" Return possible range for min function. \"\"\"\n    return Interval(min(x.low for x in args), min(x.high for x in args))", "title": ""}
{"_id": "d1017", "text": "def write_color(string, name, style='normal', when='auto'):\n    \"\"\" Write the given colored string to standard out. \"\"\"\n    write(color(string, name, style, when))", "title": ""}
{"_id": "d1018", "text": "def close(self):\n        \"\"\"Close port.\"\"\"\n        os.close(self.in_d)\n        os.close(self.out_d)", "title": ""}
{"_id": "d1019", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d1020", "text": "def extract_keywords_from_text(self, text):\n        \"\"\"Method to extract keywords from the text provided.\n\n        :param text: Text to extract keywords from, provided as a string.\n        \"\"\"\n        sentences = nltk.tokenize.sent_tokenize(text)\n        self.extract_keywords_from_sentences(sentences)", "title": ""}
{"_id": "d1021", "text": "def deserialize_date(string):\n    \"\"\"\n    Deserializes string to date.\n\n    :param string: str.\n    :type string: str\n    :return: date.\n    :rtype: date\n    \"\"\"\n    try:\n        from dateutil.parser import parse\n        return parse(string).date()\n    except ImportError:\n        return string", "title": ""}
{"_id": "d1022", "text": "def get_soup(page=''):\n    \"\"\"\n    Returns a bs4 object of the page requested\n    \"\"\"\n    content = requests.get('%s/%s' % (BASE_URL, page)).text\n    return BeautifulSoup(content)", "title": ""}
{"_id": "d1023", "text": "def parse_date(s):\n    \"\"\"\n    Parse a date using dateutil.parser.parse if available,\n    falling back to datetime.datetime.strptime if not\n    \"\"\"\n    if isinstance(s, (datetime.datetime, datetime.date)):\n        return s\n    try:\n        from dateutil.parser import parse\n    except ImportError:\n        parse = lambda d: datetime.datetime.strptime(d, \"%Y-%m-%d\")\n    return parse(s)", "title": ""}
{"_id": "d1024", "text": "def clean_dataframe(df):\n    \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n    df = df.fillna(method='ffill')\n    df = df.fillna(0.0)\n    return df", "title": ""}
{"_id": "d1025", "text": "def _synced(method, self, args, kwargs):\n    \"\"\"Underlying synchronized wrapper.\"\"\"\n    with self._lock:\n        return method(*args, **kwargs)", "title": ""}
{"_id": "d1026", "text": "def fsliceafter(astr, sub):\n    \"\"\"Return the slice after at sub in string astr\"\"\"\n    findex = astr.find(sub)\n    return astr[findex + len(sub):]", "title": ""}
{"_id": "d1027", "text": "def map_wrap(f):\n    \"\"\"Wrap standard function to easily pass into 'map' processing.\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d1028", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d1029", "text": "def list_formatter(handler, item, value):\n    \"\"\"Format list.\"\"\"\n    return u', '.join(str(v) for v in value)", "title": ""}
{"_id": "d1030", "text": "def file_writelines_flush_sync(path, lines):\n    \"\"\"\n    Fill file at @path with @lines then flush all buffers\n    (Python and system buffers)\n    \"\"\"\n    fp = open(path, 'w')\n    try:\n        fp.writelines(lines)\n        flush_sync_file_object(fp)\n    finally:\n        fp.close()", "title": ""}
{"_id": "d1031", "text": "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d1032", "text": "def safe_int_conv(number):\n    \"\"\"Safely convert a single number to integer.\"\"\"\n    try:\n        return int(np.array(number).astype(int, casting='safe'))\n    except TypeError:\n        raise ValueError('cannot safely convert {} to integer'.format(number))", "title": ""}
{"_id": "d1033", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d1034", "text": "def safe_int_conv(number):\n    \"\"\"Safely convert a single number to integer.\"\"\"\n    try:\n        return int(np.array(number).astype(int, casting='safe'))\n    except TypeError:\n        raise ValueError('cannot safely convert {} to integer'.format(number))", "title": ""}
{"_id": "d1035", "text": "def create_path(path):\n    \"\"\"Creates a absolute path in the file system.\n\n    :param path: The path to be created\n    \"\"\"\n    import os\n    if not os.path.exists(path):\n        os.makedirs(path)", "title": ""}
{"_id": "d1036", "text": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d1037", "text": "def perform_pca(A):\n    \"\"\"\n    Computes eigenvalues and eigenvectors of covariance matrix of A.\n    The rows of a correspond to observations, the columns to variables.\n    \"\"\"\n    # First subtract the mean\n    M = (A-numpy.mean(A.T, axis=1)).T\n    # Get eigenvectors and values of covariance matrix\n    return numpy.linalg.eig(numpy.cov(M))", "title": ""}
{"_id": "d1038", "text": "def main_func(args=None):\n    \"\"\"Main funcion when executing this module as script\n\n    :param args: commandline arguments\n    :type args: list\n    :returns: None\n    :rtype: None\n    :raises: None\n    \"\"\"\n    # we have to initialize a gui even if we dont need one right now.\n    # as soon as you call maya.standalone.initialize(), a QApplication\n    # with type Tty is created. This is the type for conosle apps.\n    # Because i have not found a way to replace that, we just init the gui.\n    guimain.init_gui()\n\n    main.init()\n    launcher = Launcher()\n    parsed, unknown = launcher.parse_args(args)\n    parsed.func(parsed, unknown)", "title": ""}
{"_id": "d1039", "text": "def debug_on_error(type, value, tb):\n    \"\"\"Code due to Thomas Heller - published in Python Cookbook (O'Reilley)\"\"\"\n    traceback.print_exc(type, value, tb)\n    print()\n    pdb.pm()", "title": ""}
{"_id": "d1040", "text": "def from_rectangle(box):\n        \"\"\" Create a vector randomly within the given rectangle. \"\"\"\n        x = box.left + box.width * random.uniform(0, 1)\n        y = box.bottom + box.height * random.uniform(0, 1)\n        return Vector(x, y)", "title": ""}
{"_id": "d1041", "text": "def set_trace():\n    \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n    # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n    pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "title": ""}
{"_id": "d1042", "text": "def _remove_duplicates(objects):\n    \"\"\"Removes duplicate objects.\n\n    http://www.peterbe.com/plog/uniqifiers-benchmark.\n    \"\"\"\n    seen, uniq = set(), []\n    for obj in objects:\n        obj_id = id(obj)\n        if obj_id in seen:\n            continue\n        seen.add(obj_id)\n        uniq.append(obj)\n    return uniq", "title": ""}
{"_id": "d1043", "text": "def set_trace():\n    \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n    # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n    pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "title": ""}
{"_id": "d1044", "text": "def to_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case. For example, \"some_var\" would become \"someVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.lstrip('_').split('_')\n    return parts[0] + ''.join([i.title() for i in parts[1:]])", "title": ""}
{"_id": "d1045", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d1046", "text": "def do_history(self, line):\n        \"\"\"history Display a list of commands that have been entered.\"\"\"\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))", "title": ""}
{"_id": "d1047", "text": "def quote(s, unsafe='/'):\n    \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n    encoded value as the value.\"\"\"\n    res = s.replace('%', '%25')\n    for c in unsafe:\n        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n    return res", "title": ""}
{"_id": "d1048", "text": "def call_out(command):\n  \"\"\"\n  Run the given command (with shell=False) and return a tuple of\n  (int returncode, str output). Strip the output of enclosing whitespace.\n  \"\"\"\n  # start external command process\n  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n  # get outputs\n  out, _ = p.communicate()\n\n  return p.returncode, out.strip()", "title": ""}
{"_id": "d1049", "text": "def visit_BoolOp(self, node):\n        \"\"\" Return type may come from any boolop operand. \"\"\"\n        return sum((self.visit(value) for value in node.values), [])", "title": ""}
{"_id": "d1050", "text": "def linearRegressionAnalysis(series):\n    \"\"\"\n    Returns factor and offset of linear regression function by least\n    squares method.\n\n    \"\"\"\n    n = safeLen(series)\n    sumI = sum([i for i, v in enumerate(series) if v is not None])\n    sumV = sum([v for i, v in enumerate(series) if v is not None])\n    sumII = sum([i * i for i, v in enumerate(series) if v is not None])\n    sumIV = sum([i * v for i, v in enumerate(series) if v is not None])\n    denominator = float(n * sumII - sumI * sumI)\n    if denominator == 0:\n        return None\n    else:\n        factor = (n * sumIV - sumI * sumV) / denominator / series.step\n        offset = sumII * sumV - sumIV * sumI\n        offset = offset / denominator - factor * series.start\n        return factor, offset", "title": ""}
{"_id": "d1051", "text": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "title": ""}
{"_id": "d1052", "text": "def searchlast(self,n=10):\n        \"\"\"Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.\"\"\"            \n        solutions = deque([], n)\n        for solution in self:\n            solutions.append(solution)\n        return solutions", "title": ""}
{"_id": "d1053", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d1054", "text": "def _get_token(self, oauth_request, token_type='access'):\n        \"\"\"Try to find the token for the provided request token key.\"\"\"\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", "title": ""}
{"_id": "d1055", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d1056", "text": "def fn_min(self, a, axis=None):\n        \"\"\"\n        Return the minimum of an array, ignoring any NaNs.\n\n        :param a: The array.\n        :return: The minimum value of the array.\n        \"\"\"\n\n        return numpy.nanmin(self._to_ndarray(a), axis=axis)", "title": ""}
{"_id": "d1057", "text": "def draw_image(self, ax, image):\n        \"\"\"Process a matplotlib image object and call renderer.draw_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)", "title": ""}
{"_id": "d1058", "text": "def average(iterator):\n    \"\"\"Iterative mean.\"\"\"\n    count = 0\n    total = 0\n    for num in iterator:\n        count += 1\n        total += num\n    return float(total)/count", "title": ""}
{"_id": "d1059", "text": "def cart2pol(x, y):\n    \"\"\"Cartesian to Polar coordinates conversion.\"\"\"\n    theta = np.arctan2(y, x)\n    rho = np.hypot(x, y)\n    return theta, rho", "title": ""}
{"_id": "d1060", "text": "def get_column_keys_and_names(table):\n    \"\"\"\n    Return a generator of tuples k, c such that k is the name of the python attribute for\n    the column and c is the name of the column in the sql table.\n    \"\"\"\n    ins = inspect(table)\n    return ((k, c.name) for k, c in ins.mapper.c.items())", "title": ""}
{"_id": "d1061", "text": "def asyncStarCmap(asyncCallable, iterable):\n    \"\"\"itertools.starmap for deferred callables using cooperative multitasking\n    \"\"\"\n    results = []\n    yield coopStar(asyncCallable, results.append, iterable)\n    returnValue(results)", "title": ""}
{"_id": "d1062", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d1063", "text": "def _psutil_kill_pid(pid):\n    \"\"\"\n    http://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows\n    \"\"\"\n    try:\n        parent = Process(pid)\n        for child in parent.children(recursive=True):\n            child.kill()\n        parent.kill()\n    except NoSuchProcess:\n        return", "title": ""}
{"_id": "d1064", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d1065", "text": "def paint_cube(self, x, y):\n        \"\"\"\n        Paints a cube at a certain position a color.\n\n        Parameters\n        ----------\n        x: int\n            Horizontal position of the upper left corner of the cube.\n        y: int\n            Vertical position of the upper left corner of the cube.\n\n        \"\"\"\n        # get the color\n        color = self.next_color()\n        # calculate the position\n        cube_pos = [x, y, x + self.cube_size, y + self.cube_size]\n        # draw the cube\n        draw = ImageDraw.Draw(im=self.image)\n        draw.rectangle(xy=cube_pos, fill=color)", "title": ""}
{"_id": "d1066", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d1067", "text": "def p_postfix_expr(self, p):\n        \"\"\"postfix_expr : left_hand_side_expr\n                        | left_hand_side_expr PLUSPLUS\n                        | left_hand_side_expr MINUSMINUS\n        \"\"\"\n        if len(p) == 2:\n            p[0] = p[1]\n        else:\n            p[0] = ast.UnaryOp(op=p[2], value=p[1], postfix=True)", "title": ""}
{"_id": "d1068", "text": "def phantomjs_retrieve(url, data=None):\n    \"\"\"Retrieve the given URL using PhantomJS.\n    PhantomJS will evaluate all scripts and return the HTML after body.onload.\n    \n    url  - The page URL to retrieve\n    data - The form data. TODO: Currently ignored.\n\n    Returns a status code (e.g. 200) and the HTML as a unicode string.\n    \"\"\"\n    range_limit()\n    print \"pGET\", url\n    process = subprocess.Popen(['phantomjs', PHANTOM_SCRIPT, url], stdout=subprocess.PIPE)\n    out = process.communicate()\n    process.wait()\n    response = out[0].decode('utf-8', 'ignore')\n    status = response[:2]\n    body = response[3:] # After the 'ok ' part.\n    if status == 'ok':\n        return 200, body\n    else:\n        return 404, body", "title": ""}
{"_id": "d1069", "text": "def pprint_for_ordereddict():\n    \"\"\"\n    Context manager that causes pprint() to print OrderedDict objects as nicely\n    as standard Python dictionary objects.\n    \"\"\"\n    od_saved = OrderedDict.__repr__\n    try:\n        OrderedDict.__repr__ = dict.__repr__\n        yield\n    finally:\n        OrderedDict.__repr__ = od_saved", "title": ""}
{"_id": "d1070", "text": "def get_list_dimensions(_list):\n    \"\"\"\n    Takes a nested list and returns the size of each dimension followed\n    by the element type in the list\n    \"\"\"\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []", "title": ""}
{"_id": "d1071", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d1072", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d1073", "text": "def pformat(o, indent=1, width=80, depth=None):\n    \"\"\"Format a Python o into a pretty-printed representation.\"\"\"\n    return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(o)", "title": ""}
{"_id": "d1074", "text": "def this_quarter():\n        \"\"\" Return start and end date of this quarter. \"\"\"\n        since = TODAY + delta(day=1)\n        while since.month % 3 != 0:\n            since -= delta(months=1)\n        until = since + delta(months=3)\n        return Date(since), Date(until)", "title": ""}
{"_id": "d1075", "text": "def print_trace(self):\n        \"\"\"\n        Prints stack trace for current exceptions chain.\n        \"\"\"\n        traceback.print_exc()\n        for tb in self.tracebacks:\n            print tb,\n        print ''", "title": ""}
{"_id": "d1076", "text": "def help_for_command(command):\n    \"\"\"Get the help text (signature + docstring) for a command (function).\"\"\"\n    help_text = pydoc.text.document(command)\n    # remove backspaces\n    return re.subn('.\\\\x08', '', help_text)[0]", "title": ""}
{"_id": "d1077", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d1078", "text": "def check_git():\n    \"\"\"Check if git command is available.\"\"\"\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.\")", "title": ""}
{"_id": "d1079", "text": "def py(self, output):\n        \"\"\"Output data as a nicely-formatted python data structure\"\"\"\n        import pprint\n        pprint.pprint(output, stream=self.outfile)", "title": ""}
{"_id": "d1080", "text": "def get_column_keys_and_names(table):\n    \"\"\"\n    Return a generator of tuples k, c such that k is the name of the python attribute for\n    the column and c is the name of the column in the sql table.\n    \"\"\"\n    ins = inspect(table)\n    return ((k, c.name) for k, c in ins.mapper.c.items())", "title": ""}
{"_id": "d1081", "text": "def pretty(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Pretty print the object's representation.\n    \"\"\"\n    stream = StringIO()\n    printer = RepresentationPrinter(stream, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    return stream.getvalue()", "title": ""}
{"_id": "d1082", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d1083", "text": "def prnt(self):\n        \"\"\"\n        Prints DB data representation of the object.\n        \"\"\"\n        print(\"= = = =\\n\\n%s object key: \\033[32m%s\\033[0m\" % (self.__class__.__name__, self.key))\n        pprnt(self._data or self.clean_value())", "title": ""}
{"_id": "d1084", "text": "def timestamp_to_microseconds(timestamp):\n    \"\"\"Convert a timestamp string into a microseconds value\n    :param timestamp\n    :return time in microseconds\n    \"\"\"\n    timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX)\n    epoch_time_secs = calendar.timegm(timestamp_str.timetuple())\n    epoch_time_mus = epoch_time_secs * 1e6 + timestamp_str.microsecond\n    return epoch_time_mus", "title": ""}
{"_id": "d1085", "text": "def stdout_display():\n    \"\"\" Print results straight to stdout \"\"\"\n    if sys.version_info[0] == 2:\n        yield SmartBuffer(sys.stdout)\n    else:\n        yield SmartBuffer(sys.stdout.buffer)", "title": ""}
{"_id": "d1086", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d1087", "text": "def start(self, timeout=None):\n        \"\"\"\n        Startup of the node.\n        :param join: optionally wait for the process to end (default : True)\n        :return: None\n        \"\"\"\n\n        assert super(PyrosBase, self).start(timeout=timeout)\n        # Because we currently use this to setup connection\n        return self.name", "title": ""}
{"_id": "d1088", "text": "def filter_regex(names, regex):\n    \"\"\"\n    Return a tuple of strings that match the regular expression pattern.\n    \"\"\"\n    return tuple(name for name in names\n                 if regex.search(name) is not None)", "title": ""}
{"_id": "d1089", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d1090", "text": "def line_count(fn):\n    \"\"\" Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)\n    \"\"\"\n\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "title": ""}
{"_id": "d1091", "text": "def load(self):\n        \"\"\"Load proxy list from configured proxy source\"\"\"\n        self._list = self._source.load()\n        self._list_iter = itertools.cycle(self._list)", "title": ""}
{"_id": "d1092", "text": "def _get_points(self):\n        \"\"\"\n        Subclasses may override this method.\n        \"\"\"\n        return tuple([self._getitem__points(i)\n                     for i in range(self._len__points())])", "title": ""}
{"_id": "d1093", "text": "def format_pylint_disables(error_names, tag=True):\n    \"\"\"\n    Format a list of error_names into a 'pylint: disable=' line.\n    \"\"\"\n    tag_str = \"lint-amnesty, \" if tag else \"\"\n    if error_names:\n        return u\"  # {tag}pylint: disable={disabled}\".format(\n            disabled=\", \".join(sorted(error_names)),\n            tag=tag_str,\n        )\n    else:\n        return \"\"", "title": ""}
{"_id": "d1094", "text": "def qrandom(n):\n  \"\"\"\n  Creates an array of n true random numbers obtained from the quantum random\n  number generator at qrng.anu.edu.au\n\n  This function requires the package quantumrandom and an internet connection.\n\n  Args:\n    n (int):\n      length of the random array\n\n  Return:\n    array of ints:\n      array of truly random unsigned 16 bit int values\n  \"\"\"\n  import quantumrandom\n  return np.concatenate([\n    quantumrandom.get_data(data_type='uint16', array_length=1024)\n    for i in range(int(np.ceil(n/1024.0)))\n  ])[:n]", "title": ""}
{"_id": "d1095", "text": "def clear_table(dbconn, table_name):\n    \"\"\"\n    Delete all rows from a table\n    :param dbconn: data base connection\n    :param table_name: name of the table\n    :return:\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"DELETE FROM '{name}'\".format(name=table_name))\n    dbconn.commit()", "title": ""}
{"_id": "d1096", "text": "def lowstrip(term):\n    \"\"\"Convert to lowercase and strip spaces\"\"\"\n    term = re.sub('\\s+', ' ', term)\n    term = term.lower()\n    return term", "title": ""}
{"_id": "d1097", "text": "def chmod(self, mode):\n        \"\"\"\n        Change the mode (permissions) of this file.  The permissions are\n        unix-style and identical to those used by python's C{os.chmod}\n        function.\n\n        @param mode: new permissions\n        @type mode: int\n        \"\"\"\n        self.sftp._log(DEBUG, 'chmod(%s, %r)' % (hexlify(self.handle), mode))\n        attr = SFTPAttributes()\n        attr.st_mode = mode\n        self.sftp._request(CMD_FSETSTAT, self.handle, attr)", "title": ""}
{"_id": "d1098", "text": "def region_from_segment(image, segment):\n    \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n    x, y, w, h = segment\n    return image[y:y + h, x:x + w]", "title": ""}
{"_id": "d1099", "text": "def test(ctx, all=False, verbose=False):\n    \"\"\"Run the tests.\"\"\"\n    cmd = 'tox' if all else 'py.test'\n    if verbose:\n        cmd += ' -v'\n    return ctx.run(cmd, pty=True).return_code", "title": ""}
{"_id": "d1100", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d1101", "text": "def set_value(self, value):\n        \"\"\"Set value of the checkbox.\n\n        Parameters\n        ----------\n        value : bool\n            value for the checkbox\n\n        \"\"\"\n        if value:\n            self.setCheckState(Qt.Checked)\n        else:\n            self.setCheckState(Qt.Unchecked)", "title": ""}
{"_id": "d1102", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d1103", "text": "def resizeEvent(self, event):\n        \"\"\"Reimplement Qt method\"\"\"\n        if not self.isMaximized() and not self.fullscreen_flag:\n            self.window_size = self.size()\n        QMainWindow.resizeEvent(self, event)\n\n        # To be used by the tour to be able to resize\n        self.sig_resized.emit(event)", "title": ""}
{"_id": "d1104", "text": "def PrintSummaryTable(self):\n    \"\"\"Prints a summary table.\"\"\"\n    print(\"\"\"\n\nAs of {0:s} the repository contains:\n\n| **File paths covered** | **{1:d}** |\n| :------------------ | ------: |\n| **Registry keys covered** | **{2:d}** |\n| **Total artifacts** | **{3:d}** |\n\"\"\".format(\n    time.strftime('%Y-%m-%d'), self.path_count, self.reg_key_count,\n    self.total_count))", "title": ""}
{"_id": "d1105", "text": "def state(self):\n    \"\"\"Returns the current LED state by querying the remote controller.\"\"\"\n    ev = self._query_waiters.request(self.__do_query_state)\n    ev.wait(1.0)\n    return self._state", "title": ""}
{"_id": "d1106", "text": "def refresh_swagger(self):\n        \"\"\"\n        Manually refresh the swagger document. This can help resolve errors communicate with the API.\n        \"\"\"\n        try:\n            os.remove(self._get_swagger_filename(self.swagger_url))\n        except EnvironmentError as e:\n            logger.warn(os.strerror(e.errno))\n        else:\n            self.__init__()", "title": ""}
{"_id": "d1107", "text": "def full(self):\n        \"\"\"Return True if the queue is full\"\"\"\n        if not self.size: return False\n        return len(self.pq) == (self.size + self.removed_count)", "title": ""}
{"_id": "d1108", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d1109", "text": "def remove_duplicates(lst):\n    \"\"\"\n    Emulate what a Python ``set()`` does, but keeping the element's order.\n    \"\"\"\n    dset = set()\n    return [l for l in lst if l not in dset and not dset.add(l)]", "title": ""}
{"_id": "d1110", "text": "def rel_path(filename):\n    \"\"\"\n    Function that gets relative path to the filename\n    \"\"\"\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)", "title": ""}
{"_id": "d1111", "text": "def convert_timestamp(timestamp):\n    \"\"\"\n    Converts bokehJS timestamp to datetime64.\n    \"\"\"\n    datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)\n    return np.datetime64(datetime.replace(tzinfo=None))", "title": ""}
{"_id": "d1112", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d1113", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d1114", "text": "def sorted_index(values, x):\n    \"\"\"\n    For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n    :param values: list\n    :param x: item\n    :return: integer index\n    \"\"\"\n    i = bisect_left(values, x)\n    j = bisect_right(values, x)\n    return values[i:j].index(x) + i", "title": ""}
{"_id": "d1115", "text": "def prepare(self):\n        \"\"\"Prepare the handler, ensuring RabbitMQ is connected or start a new\n        connection attempt.\n\n        \"\"\"\n        super(RabbitMQRequestHandler, self).prepare()\n        if self._rabbitmq_is_closed:\n            self._connect_to_rabbitmq()", "title": ""}
{"_id": "d1116", "text": "def sorted_index(values, x):\n    \"\"\"\n    For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n    :param values: list\n    :param x: item\n    :return: integer index\n    \"\"\"\n    i = bisect_left(values, x)\n    j = bisect_right(values, x)\n    return values[i:j].index(x) + i", "title": ""}
{"_id": "d1117", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d1118", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d1119", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d1120", "text": "def _rndPointDisposition(dx, dy):\n        \"\"\"Return random disposition point.\"\"\"\n        x = int(random.uniform(-dx, dx))\n        y = int(random.uniform(-dy, dy))\n        return (x, y)", "title": ""}
{"_id": "d1121", "text": "def get_module_path(modname):\n    \"\"\"Return module *modname* base path\"\"\"\n    return osp.abspath(osp.dirname(sys.modules[modname].__file__))", "title": ""}
{"_id": "d1122", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d1123", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d1124", "text": "def read_string(buff, byteorder='big'):\n    \"\"\"Read a string from a file-like object.\"\"\"\n    length = read_numeric(USHORT, buff, byteorder)\n    return buff.read(length).decode('utf-8')", "title": ""}
{"_id": "d1125", "text": "def add_to_toolbar(self, toolbar, widget):\n        \"\"\"Add widget actions to toolbar\"\"\"\n        actions = widget.toolbar_actions\n        if actions is not None:\n            add_actions(toolbar, actions)", "title": ""}
{"_id": "d1126", "text": "def load_data(filename):\n    \"\"\"\n    :rtype : numpy matrix\n    \"\"\"\n    data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n    return data.as_matrix()", "title": ""}
{"_id": "d1127", "text": "def get_system_uid():\n    \"\"\"Get a (probably) unique ID to identify a system.\n    Used to differentiate votes.\n    \"\"\"\n    try:\n        if os.name == 'nt':\n            return get_nt_system_uid()\n        if sys.platform == 'darwin':\n            return get_osx_system_uid()\n    except Exception:\n        return get_mac_uid()\n    else:\n        return get_mac_uid()", "title": ""}
{"_id": "d1128", "text": "def lines(input):\n    \"\"\"Remove comments and empty lines\"\"\"\n    for raw_line in input:\n        line = raw_line.strip()\n        if line and not line.startswith('#'):\n            yield strip_comments(line)", "title": ""}
{"_id": "d1129", "text": "def get_user_name():\n    \"\"\"Get user name provide by operating system\n    \"\"\"\n\n    if sys.platform == 'win32':\n        #user = os.getenv('USERPROFILE')\n        user = os.getenv('USERNAME')\n    else:\n        user = os.getenv('LOGNAME')\n\n    return user", "title": ""}
{"_id": "d1130", "text": "def getlines(filename, module_globals=None):\n    \"\"\"Get the lines for a file from the cache.\n    Update the cache if it doesn't contain an entry for this file already.\"\"\"\n\n    if filename in cache:\n        return cache[filename][2]\n\n    try:\n        return updatecache(filename, module_globals)\n    except MemoryError:\n        clearcache()\n        return []", "title": ""}
{"_id": "d1131", "text": "def compute_y(self, coefficients, num_x):\n        \"\"\" Return calculated y-values for the domain of x-values in [1, num_x]. \"\"\"\n        y_vals = []\n\n        for x in range(1, num_x + 1):\n            y = sum([c * x ** i for i, c in enumerate(coefficients[::-1])])\n            y_vals.append(y)\n\n        return y_vals", "title": ""}
{"_id": "d1132", "text": "def _readuntil(f, end=_TYPE_END):\n\t\"\"\"Helper function to read bytes until a certain end byte is hit\"\"\"\n\tbuf = bytearray()\n\tbyte = f.read(1)\n\twhile byte != end:\n\t\tif byte == b'':\n\t\t\traise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))\n\t\tbuf += byte\n\t\tbyte = f.read(1)\n\treturn buf", "title": ""}
{"_id": "d1133", "text": "def _add_pos1(token):\n    \"\"\"\n    Adds a 'pos1' element to a frog token.\n    \"\"\"\n    result = token.copy()\n    result['pos1'] = _POSMAP[token['pos'].split(\"(\")[0]]\n    return result", "title": ""}
{"_id": "d1134", "text": "def read_string_from_file(path, encoding=\"utf8\"):\n  \"\"\"\n  Read entire contents of file into a string.\n  \"\"\"\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value", "title": ""}
{"_id": "d1135", "text": "def relative_path(path):\n    \"\"\"\n    Return the given path relative to this file.\n    \"\"\"\n    return os.path.join(os.path.dirname(__file__), path)", "title": ""}
{"_id": "d1136", "text": "def getfirstline(file, default):\n    \"\"\"\n    Returns the first line of a file.\n    \"\"\"\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\n    return default", "title": ""}
{"_id": "d1137", "text": "def page_guiref(arg_s=None):\n    \"\"\"Show a basic reference about the GUI Console.\"\"\"\n    from IPython.core import page\n    page.page(gui_reference, auto_html=True)", "title": ""}
{"_id": "d1138", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d1139", "text": "def save_excel(self, fd):\n        \"\"\" Saves the case as an Excel spreadsheet.\n        \"\"\"\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)", "title": ""}
{"_id": "d1140", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d1141", "text": "def set_font_size(self, size):\n        \"\"\"Convenience method for just changing font size.\"\"\"\n        if self.font.font_size == size:\n            pass\n        else:\n            self.font._set_size(size)", "title": ""}
{"_id": "d1142", "text": "def open_json(file_name):\n    \"\"\"\n    returns json contents as string\n    \"\"\"\n    with open(file_name, \"r\") as json_data:\n        data = json.load(json_data)\n        return data", "title": ""}
{"_id": "d1143", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d1144", "text": "def is_read_only(object):\n    \"\"\"\n    Returns if given object is read only ( built-in or extension ).\n\n    :param object: Object.\n    :type object: object\n    :return: Is object read only.\n    :rtype: bool\n    \"\"\"\n\n    try:\n        attribute = \"_trace__read__\"\n        setattr(object, attribute, True)\n        delattr(object, attribute)\n        return False\n    except (TypeError, AttributeError):\n        return True", "title": ""}
{"_id": "d1145", "text": "def draw_header(self, stream, header):\n        \"\"\"Draw header with underline\"\"\"\n        stream.writeln('=' * (len(header) + 4))\n        stream.writeln('| ' + header + ' |')\n        stream.writeln('=' * (len(header) + 4))\n        stream.writeln()", "title": ""}
{"_id": "d1146", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d1147", "text": "def get_xy_grids(ds, stride=1, getval=False):\n    \"\"\"Return 2D arrays of x and y map coordinates for input GDAL Dataset \n    \"\"\"\n    gt = ds.GetGeoTransform()\n    #stride = stride_m/gt[1]\n    pX = np.arange(0, ds.RasterXSize, stride)\n    pY = np.arange(0, ds.RasterYSize, stride)\n    psamp = np.meshgrid(pX, pY)\n    mX, mY = pixelToMap(psamp[0], psamp[1], gt)\n    return mX, mY", "title": ""}
{"_id": "d1148", "text": "def _parse_config(config_file_path):\n    \"\"\" Parse Config File from yaml file. \"\"\"\n    config_file = open(config_file_path, 'r')\n    config = yaml.load(config_file)\n    config_file.close()\n    return config", "title": ""}
{"_id": "d1149", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d1150", "text": "def is_non_empty_string(input_string):\n    \"\"\"\n    Validate if non empty string\n\n    :param input_string: Input is a *str*.\n    :return: True if input is string and non empty.\n       Raise :exc:`Exception` otherwise.\n    \"\"\"\n    try:\n        if not input_string.strip():\n            raise ValueError()\n    except AttributeError as error:\n        raise TypeError(error)\n\n    return True", "title": ""}
{"_id": "d1151", "text": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "title": ""}
{"_id": "d1152", "text": "def mouse_move_event(self, event):\n        \"\"\"\n        Forward mouse cursor position events to the example\n        \"\"\"\n        self.example.mouse_position_event(event.x(), event.y())", "title": ""}
{"_id": "d1153", "text": "def get_var_type(self, name):\n        \"\"\"\n        Return type string, compatible with numpy.\n        \"\"\"\n        name = create_string_buffer(name)\n        type_ = create_string_buffer(MAXSTRLEN)\n        self.library.get_var_type.argtypes = [c_char_p, c_char_p]\n        self.library.get_var_type(name, type_)\n        return type_.value", "title": ""}
{"_id": "d1154", "text": "def acquire_node(self, node):\n        \"\"\"\n        acquire a single redis node\n        \"\"\"\n        try:\n            return node.set(self.resource, self.lock_key, nx=True, px=self.ttl)\n        except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError):\n            return False", "title": ""}
{"_id": "d1155", "text": "def java_version():\n    \"\"\"Call java and return version information.\n\n    :return unicode: Java version string\n    \"\"\"\n    result = subprocess.check_output(\n        [c.JAVA, '-version'], stderr=subprocess.STDOUT\n    )\n    first_line = result.splitlines()[0]\n    return first_line.decode()", "title": ""}
{"_id": "d1156", "text": "def expireat(self, key, when):\n        \"\"\"Emulate expireat\"\"\"\n        expire_time = datetime.fromtimestamp(when)\n        key = self._encode(key)\n        if key in self.redis:\n            self.timeouts[key] = expire_time\n            return True\n        return False", "title": ""}
{"_id": "d1157", "text": "def init_checks_registry():\n    \"\"\"Register all globally visible functions.\n\n    The first argument name is either 'physical_line' or 'logical_line'.\n    \"\"\"\n    mod = inspect.getmodule(register_check)\n    for (name, function) in inspect.getmembers(mod, inspect.isfunction):\n        register_check(function)", "title": ""}
{"_id": "d1158", "text": "def find_root(self):\n        \"\"\" Traverse parent refs to top. \"\"\"\n        cmd = self\n        while cmd.parent:\n            cmd = cmd.parent\n        return cmd", "title": ""}
{"_id": "d1159", "text": "def _load_texture(file_name, resolver):\n    \"\"\"\n    Load a texture from a file into a PIL image.\n    \"\"\"\n    file_data = resolver.get(file_name)\n    image = PIL.Image.open(util.wrap_as_stream(file_data))\n    return image", "title": ""}
{"_id": "d1160", "text": "def _tuple_repr(data):\n    \"\"\"Return a repr() for a list/tuple\"\"\"\n    if len(data) == 1:\n        return \"(%s,)\" % rpr(data[0])\n    else:\n        return \"(%s)\" % \", \".join([rpr(x) for x in data])", "title": ""}
{"_id": "d1161", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d1162", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d1163", "text": "def make_bintree(levels):\n    \"\"\"Make a symmetrical binary tree with @levels\"\"\"\n    G = nx.DiGraph()\n    root = '0'\n    G.add_node(root)\n    add_children(G, root, levels, 2)\n    return G", "title": ""}
{"_id": "d1164", "text": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "title": ""}
{"_id": "d1165", "text": "def _makes_clone(_func, *args, **kw):\n    \"\"\"\n    A decorator that returns a clone of the current object so that\n    we can re-use the object for similar requests.\n    \"\"\"\n    self = args[0]._clone()\n    _func(self, *args[1:], **kw)\n    return self", "title": ""}
{"_id": "d1166", "text": "def linregress(x, y, return_stats=False):\n    \"\"\"linear regression calculation\n\n    Parameters\n    ----\n    x :         independent variable (series)\n    y :         dependent variable (series)\n    return_stats : returns statistical values as well if required (bool)\n    \n\n    Returns\n    ----\n    list of parameters (and statistics)\n    \"\"\"\n    a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y)\n\n    retval = a1, a0\n    if return_stats:\n        retval += r_value, p_value, stderr\n\n    return retval", "title": ""}
{"_id": "d1167", "text": "def linedelimited (inlist,delimiter):\n    \"\"\"\nReturns a string composed of elements in inlist, with each element\nseparated by 'delimiter.'  Used by function writedelimited.  Use '\\t'\nfor tab-delimiting.\n\nUsage:   linedelimited (inlist,delimiter)\n\"\"\"\n    outstr = ''\n    for item in inlist:\n        if type(item) != StringType:\n            item = str(item)\n        outstr = outstr + item + delimiter\n    outstr = outstr[0:-1]\n    return outstr", "title": ""}
{"_id": "d1168", "text": "def validate_multiindex(self, obj):\n        \"\"\"validate that we can store the multi-index; reset and return the\n        new object\n        \"\"\"\n        levels = [l if l is not None else \"level_{0}\".format(i)\n                  for i, l in enumerate(obj.index.names)]\n        try:\n            return obj.reset_index(), levels\n        except ValueError:\n            raise ValueError(\"duplicate names/columns in the multi-index when \"\n                             \"storing as a table\")", "title": ""}
{"_id": "d1169", "text": "def alert(text='', title='', button=OK_TEXT, root=None, timeout=None):\n    \"\"\"Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.\"\"\"\n    assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox'\n    return _buttonbox(msg=text, title=title, choices=[str(button)], root=root, timeout=timeout)", "title": ""}
{"_id": "d1170", "text": "def cmd_reindex():\n    \"\"\"Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.\n\n    The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until\n    the rename succeeds.\n    \"\"\"\n    db = connect(args.database)\n    for idx in args.indexes:\n        pg_reindex(db, idx)", "title": ""}
{"_id": "d1171", "text": "def list_add_capitalize(l):\n    \"\"\"\n    @type l: list\n    @return: list\n    \"\"\"\n    nl = []\n\n    for i in l:\n        nl.append(i)\n\n        if hasattr(i, \"capitalize\"):\n            nl.append(i.capitalize())\n\n    return list(set(nl))", "title": ""}
{"_id": "d1172", "text": "def update_redirect(self):\n        \"\"\"\n            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.\n        \"\"\"\n        page_history = Stack(session.get(\"page_history\", []))\n        page_history.push(request.url)\n        session[\"page_history\"] = page_history.to_json()", "title": ""}
{"_id": "d1173", "text": "def get_column_keys_and_names(table):\n    \"\"\"\n    Return a generator of tuples k, c such that k is the name of the python attribute for\n    the column and c is the name of the column in the sql table.\n    \"\"\"\n    ins = inspect(table)\n    return ((k, c.name) for k, c in ins.mapper.c.items())", "title": ""}
{"_id": "d1174", "text": "def filter_dict_by_key(d, keys):\n    \"\"\"Filter the dict *d* to remove keys not in *keys*.\"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d1175", "text": "def sent2features(sentence, template):\n    \"\"\" extract features in a sentence\n\n    :type sentence: list of token, each token is a list of tag\n    \"\"\"\n    return [word2features(sentence, i, template) for i in range(len(sentence))]", "title": ""}
{"_id": "d1176", "text": "def handle_whitespace(text):\n    r\"\"\"Handles whitespace cleanup.\n\n    Tabs are \"smartly\" retabbed (see sub_retab). Lines that contain\n    only whitespace are truncated to a single newline.\n    \"\"\"\n    text = re_retab.sub(sub_retab, text)\n    text = re_whitespace.sub('', text).strip()\n    return text", "title": ""}
{"_id": "d1177", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d1178", "text": "def _remove_blank(l):\n        \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n        ret = []\n        for i, _ in enumerate(l):\n            if l[i] == 0:\n                break\n            ret.append(l[i])\n        return ret", "title": ""}
{"_id": "d1179", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d1180", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d1181", "text": "def Fsphere(q, R):\n    \"\"\"Scattering form-factor amplitude of a sphere normalized to F(q=0)=V\n\n    Inputs:\n    -------\n        ``q``: independent variable\n        ``R``: sphere radius\n\n    Formula:\n    --------\n        ``4*pi/q^3 * (sin(qR) - qR*cos(qR))``\n    \"\"\"\n    return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R * np.cos(q * R))", "title": ""}
{"_id": "d1182", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d1183", "text": "def figsize(x=8, y=7., aspect=1.):\n    \"\"\" manually set the default figure size of plots\n    ::Arguments::\n        x (float): x-axis size\n        y (float): y-axis size\n        aspect (float): aspect ratio scalar\n    \"\"\"\n    # update rcparams with adjusted figsize params\n    mpl.rcParams.update({'figure.figsize': (x*aspect, y)})", "title": ""}
{"_id": "d1184", "text": "def to_identifier(s):\n  \"\"\"\n  Convert snake_case to camel_case.\n  \"\"\"\n  if s.startswith('GPS'):\n      s = 'Gps' + s[3:]\n  return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s", "title": ""}
{"_id": "d1185", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d1186", "text": "def vowels(self):\n        \"\"\"\n        Return a new IPAString, containing only the vowels in the current string.\n\n        :rtype: IPAString\n        \"\"\"\n        return IPAString(ipa_chars=[c for c in self.ipa_chars if c.is_vowel])", "title": ""}
{"_id": "d1187", "text": "def prune(self, n):\n        \"\"\"prune all but the first (=best) n items\"\"\"\n        if self.minimize:\n            self.data = self.data[:n]\n        else:\n            self.data = self.data[-1 * n:]", "title": ""}
{"_id": "d1188", "text": "def submitbutton(self, request, tag):\n        \"\"\"\n        Render an INPUT element of type SUBMIT which will post this form to the\n        server.\n        \"\"\"\n        return tags.input(type='submit',\n                          name='__submit__',\n                          value=self._getDescription())", "title": ""}
{"_id": "d1189", "text": "def rrmdir(directory):\n    \"\"\"\n    Recursivly delete a directory\n\n    :param directory: directory to remove\n    \"\"\"\n    for root, dirs, files in os.walk(directory, topdown=False):\n        for name in files:\n            os.remove(os.path.join(root, name))\n        for name in dirs:\n            os.rmdir(os.path.join(root, name))\n    os.rmdir(directory)", "title": ""}
{"_id": "d1190", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d1191", "text": "def rm_keys_from_dict(d, keys):\n    \"\"\"\n    Given a dictionary and a key list, remove any data in the dictionary with the given keys.\n\n    :param dict d: Metadata\n    :param list keys: Keys to be removed\n    :return dict d: Metadata\n    \"\"\"\n    # Loop for each key given\n    for key in keys:\n        # Is the key in the dictionary?\n        if key in d:\n            try:\n                d.pop(key, None)\n            except KeyError:\n                # Not concerned with an error. Keep going.\n                pass\n    return d", "title": ""}
{"_id": "d1192", "text": "def create_ellipse(width,height,angle):\n    \"\"\"Create parametric ellipse from 200 points.\"\"\"\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\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", "title": ""}
{"_id": "d1193", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d1194", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d1195", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d1196", "text": "def selecttrue(table, field, complement=False):\n    \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n    return select(table, field, lambda v: bool(v), complement=complement)", "title": ""}
{"_id": "d1197", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d1198", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d1199", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d1200", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d1201", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d1202", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d1203", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d1204", "text": "def configure_relation(graph, ns, mappings):\n    \"\"\"\n    Register relation endpoint(s) between two resources.\n\n    \"\"\"\n    convention = RelationConvention(graph)\n    convention.configure(ns, mappings)", "title": ""}
{"_id": "d1205", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d1206", "text": "def cprint(string, fg=None, bg=None, end='\\n', target=sys.stdout):\n    \"\"\"Print a colored string to the target handle.\n\n    fg and bg specify foreground- and background colors, respectively. The\n    remaining keyword arguments are the same as for Python's built-in print\n    function. Colors are returned to their defaults before the function\n    returns.\n\n    \"\"\"\n    _color_manager.set_color(fg, bg)\n    target.write(string + end)\n    target.flush()  # Needed for Python 3.x\n    _color_manager.set_defaults()", "title": ""}
{"_id": "d1207", "text": "def http_request_json(*args, **kwargs):\n    \"\"\"\n\n    See: http_request\n    \"\"\"\n    ret, status = http_request(*args, **kwargs)\n    return json.loads(ret), status", "title": ""}
{"_id": "d1208", "text": "def stdoutwriteline(*args):\n    \"\"\"\n    @type args: tuple\n    @return: None\n    \"\"\"\n    s = \"\"\n\n    for i in args:\n        s += str(i) + \" \"\n\n    s = s.strip()\n    sys.stdout.write(str(s) + \"\\n\")\n    sys.stdout.flush()\n\n    return s", "title": ""}
{"_id": "d1209", "text": "def copy_user_agent_from_driver(self):\n        \"\"\" 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.\n        \"\"\"\n        selenium_user_agent = self.driver.execute_script(\"return navigator.userAgent;\")\n        self.headers.update({\"user-agent\": selenium_user_agent})", "title": ""}
{"_id": "d1210", "text": "def _show(self, message, indent=0, enable_verbose=True):  # pragma: no cover\n        \"\"\"Message printer.\n        \"\"\"\n        if enable_verbose:\n            print(\"    \" * indent + message)", "title": ""}
{"_id": "d1211", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d1212", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d1213", "text": "def is_http_running_on(port):\n  \"\"\" Check if an http server runs on a given port.\n\n  Args:\n    The port to check.\n  Returns:\n    True if it is used by an http server. False otherwise.\n  \"\"\"\n  try:\n    conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n    conn.connect()\n    conn.close()\n    return True\n  except Exception:\n    return False", "title": ""}
{"_id": "d1214", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d1215", "text": "def download(url, encoding='utf-8'):\n    \"\"\"Returns the text fetched via http GET from URL, read as `encoding`\"\"\"\n    import requests\n    response = requests.get(url)\n    response.encoding = encoding\n    return response.text", "title": ""}
{"_id": "d1216", "text": "def sent2features(sentence, template):\n    \"\"\" extract features in a sentence\n\n    :type sentence: list of token, each token is a list of tag\n    \"\"\"\n    return [word2features(sentence, i, template) for i in range(len(sentence))]", "title": ""}
{"_id": "d1217", "text": "def clear(self):\n        \"\"\" clear plot \"\"\"\n        self.axes.cla()\n        self.conf.ntrace = 0\n        self.conf.xlabel = ''\n        self.conf.ylabel = ''\n        self.conf.title  = ''", "title": ""}
{"_id": "d1218", "text": "def __init__(self, pos, cell, motion, cellmotion):\n        self.pos = pos\n        \"\"\"(x, y) position of the mouse on the screen.\n        type: (int, int)\"\"\"\n        self.cell = cell\n        \"\"\"(x, y) position of the mouse snapped to a cell on the root console.\n        type: (int, int)\"\"\"\n        self.motion = motion\n        \"\"\"(x, y) motion of the mouse on the screen.\n        type: (int, int)\"\"\"\n        self.cellmotion = cellmotion\n        \"\"\"(x, y) mostion of the mouse moving over cells on the root console.\n        type: (int, int)\"\"\"", "title": ""}
{"_id": "d1219", "text": "def resize(self, size):\n\t\t\"\"\" Resize current array. If size is None, then array became nonfixed-length array. If new size is\n\t\tless then current size and value, then value will be truncated (lesser significant bits will be\n\t\ttruncated).\n\n\t\t:param size:\n\t\t:return:\n\t\t\"\"\"\n\t\tif size is not None:\n\t\t\tself.__value = int(WBinArray(self.__value)[:size])\n\t\tself.__size = size", "title": ""}
{"_id": "d1220", "text": "def print_out(self, *lst):\n      \"\"\" Print list of strings to the predefined stdout. \"\"\"\n      self.print2file(self.stdout, True, True, *lst)", "title": ""}
{"_id": "d1221", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d1222", "text": "def disable_busy_cursor():\n    \"\"\"Disable the hourglass cursor and listen for layer changes.\"\"\"\n    while QgsApplication.instance().overrideCursor() is not None and \\\n            QgsApplication.instance().overrideCursor().shape() == \\\n            QtCore.Qt.WaitCursor:\n        QgsApplication.instance().restoreOverrideCursor()", "title": ""}
{"_id": "d1223", "text": "async def json_or_text(response):\n    \"\"\"Turns response into a properly formatted json or text object\"\"\"\n    text = await response.text()\n    if response.headers['Content-Type'] == 'application/json; charset=utf-8':\n        return json.loads(text)\n    return text", "title": ""}
{"_id": "d1224", "text": "def get_auth():\n    \"\"\"Get authentication.\"\"\"\n    import getpass\n    user = input(\"User Name: \")  # noqa\n    pswd = getpass.getpass('Password: ')\n    return Github(user, pswd)", "title": ""}
{"_id": "d1225", "text": "def http(self, *args, **kwargs):\n        \"\"\"Starts the process of building a new HTTP route linked to this API instance\"\"\"\n        kwargs['api'] = self.api\n        return http(*args, **kwargs)", "title": ""}
{"_id": "d1226", "text": "def ILIKE(pattern):\n    \"\"\"Unix shell-style wildcards. Case-insensitive\"\"\"\n    return P(lambda x: fnmatch.fnmatch(x.lower(), pattern.lower()))", "title": ""}
{"_id": "d1227", "text": "def documentation(self):\n        \"\"\"\n        Get the documentation that the server sends for the API.\n        \"\"\"\n        newclient = self.__class__(self.session, self.root_url)\n        return newclient.get_raw('/')", "title": ""}
{"_id": "d1228", "text": "def _add_indent(string, indent):\n    \"\"\"Add indent of ``indent`` spaces to ``string.split(\"\\n\")[1:]``\n\n    Useful for formatting in strings to already indented blocks\n    \"\"\"\n    lines = string.split(\"\\n\")\n    first, lines = lines[0], lines[1:]\n    lines = [\"{indent}{s}\".format(indent=\" \" * indent, s=s)\n             for s in lines]\n    lines = [first] + lines\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d1229", "text": "def get_key_goids(self, goids):\n        \"\"\"Given GO IDs, return key GO IDs.\"\"\"\n        go2obj = self.go2obj\n        return set(go2obj[go].id for go in goids)", "title": ""}
{"_id": "d1230", "text": "def requests_post(url, data=None, json=None, **kwargs):\n    \"\"\"Requests-mock requests.post wrapper.\"\"\"\n    return requests_request('post', url, data=data, json=json, **kwargs)", "title": ""}
{"_id": "d1231", "text": "def get_idx_rect(index_list):\n    \"\"\"Extract the boundaries from a list of indexes\"\"\"\n    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\n    return ( min(rows), max(rows), min(cols), max(cols) )", "title": ""}
{"_id": "d1232", "text": "def _go_to_line(editor, line):\n    \"\"\"\n    Move cursor to this line in the current buffer.\n    \"\"\"\n    b = editor.application.current_buffer\n    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "title": ""}
{"_id": "d1233", "text": "def find_start_point(self):\n        \"\"\"\n        Find the first location in our array that is not empty\n        \"\"\"\n        for i, row in enumerate(self.data):\n            for j, _ in enumerate(row):\n                if self.data[i, j] != 0:  # or not np.isfinite(self.data[i,j]):\n                    return i, j", "title": ""}
{"_id": "d1234", "text": "def uniquify_list(L):\n    \"\"\"Same order unique list using only a list compression.\"\"\"\n    return [e for i, e in enumerate(L) if L.index(e) == i]", "title": ""}
{"_id": "d1235", "text": "def norm_vec(vector):\n    \"\"\"Normalize the length of a vector to one\"\"\"\n    assert len(vector) == 3\n    v = np.array(vector)\n    return v/np.sqrt(np.sum(v**2))", "title": ""}
{"_id": "d1236", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d1237", "text": "def filter_regex(names, regex):\n    \"\"\"\n    Return a tuple of strings that match the regular expression pattern.\n    \"\"\"\n    return tuple(name for name in names\n                 if regex.search(name) is not None)", "title": ""}
{"_id": "d1238", "text": "def _get_sql(filename):\n    \"\"\"Returns the contents of the sql file from the given ``filename``.\"\"\"\n    with open(os.path.join(SQL_DIR, filename), 'r') as f:\n        return f.read()", "title": ""}
{"_id": "d1239", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d1240", "text": "def parse_s3_url(url):\n    \"\"\"\n    Parses S3 URL.\n\n    Returns bucket (domain) and file (full path).\n    \"\"\"\n    bucket = ''\n    path = ''\n    if url:\n        result = urlparse(url)\n        bucket = result.netloc\n        path = result.path.strip('/')\n    return bucket, path", "title": ""}
{"_id": "d1241", "text": "def filter_regex(names, regex):\n    \"\"\"\n    Return a tuple of strings that match the regular expression pattern.\n    \"\"\"\n    return tuple(name for name in names\n                 if regex.search(name) is not None)", "title": ""}
{"_id": "d1242", "text": "def pickle_load(fname):\n    \"\"\"return the contents of a pickle file\"\"\"\n    assert type(fname) is str and os.path.exists(fname)\n    print(\"loaded\",fname)\n    return pickle.load(open(fname,\"rb\"))", "title": ""}
{"_id": "d1243", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d1244", "text": "def plot_dist_normal(s, mu, sigma):\n    \"\"\"\n    plot distribution\n    \"\"\"\n    import matplotlib.pyplot as plt\n    count, bins, ignored = plt.hist(s, 30, normed=True)\n    plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) \\\n            * np.exp( - (bins - mu)**2 / (2 * sigma**2) ), \\\n            linewidth = 2, color = 'r')\n    plt.show()", "title": ""}
{"_id": "d1245", "text": "def _pdf_at_peak(self):\n    \"\"\"Pdf evaluated at the peak.\"\"\"\n    return (self.peak - self.low) / (self.high - self.low)", "title": ""}
{"_id": "d1246", "text": "def _dict_to_proto(py_dict, proto):\n        \"\"\"\n        Converts a python dictionary to the proto supplied\n\n        :param py_dict: The dictionary to convert\n        :type py_dict: dict\n        :param proto: The proto object to merge with dictionary\n        :type proto: protobuf\n        :return: A parsed python dictionary in provided proto format\n        :raises:\n            ParseError: On JSON parsing problems.\n        \"\"\"\n        dict_json_str = json.dumps(py_dict)\n        return json_format.Parse(dict_json_str, proto)", "title": ""}
{"_id": "d1247", "text": "def round_to_n(x, n):\n    \"\"\"\n    Round to sig figs\n    \"\"\"\n    return round(x, -int(np.floor(np.log10(x))) + (n - 1))", "title": ""}
{"_id": "d1248", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d1249", "text": "def get_rounded(self, digits):\n        \"\"\" Return a vector with the elements rounded to the given number of digits. \"\"\"\n        result = self.copy()\n        result.round(digits)\n        return result", "title": ""}
{"_id": "d1250", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d1251", "text": "def call_and_exit(self, cmd, shell=True):\n        \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n        sys.exit(subprocess.call(cmd, shell=shell))", "title": ""}
{"_id": "d1252", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d1253", "text": "async def result_processor(tasks):\n    \"\"\"An async result aggregator that combines all the results\n       This gets executed in unsync.loop and unsync.thread\"\"\"\n    output = {}\n    for task in tasks:\n        num, res = await task\n        output[num] = res\n    return output", "title": ""}
{"_id": "d1254", "text": "def add_text(text, x=0.01, y=0.01, axes=\"gca\", draw=True, **kwargs):\n    \"\"\"\n    Adds text to the axes at the specified position.\n\n    **kwargs go to the axes.text() function.\n    \"\"\"\n    if axes==\"gca\": axes = _pylab.gca()\n    axes.text(x, y, text, transform=axes.transAxes, **kwargs)\n    if draw: _pylab.draw()", "title": ""}
{"_id": "d1255", "text": "def safe_quotes(text, escape_single_quotes=False):\n    \"\"\"htmlify string\"\"\"\n    if isinstance(text, str):\n        safe_text = text.replace('\"', \"&quot;\")\n        if escape_single_quotes:\n            safe_text = safe_text.replace(\"'\", \"&#92;'\")\n        return safe_text.replace('True', 'true')\n    return text", "title": ""}
{"_id": "d1256", "text": "def make_post_request(self, url, auth, json_payload):\n        \"\"\"This function executes the request with the provided\n        json payload and return the json response\"\"\"\n        response = requests.post(url, auth=auth, json=json_payload)\n        return response.json()", "title": ""}
{"_id": "d1257", "text": "def fig2x(figure, format):\n    \"\"\"Returns svg from matplotlib chart\"\"\"\n\n    # Save svg to file like object svg_io\n    io = StringIO()\n    figure.savefig(io, format=format)\n\n    # Rewind the file like object\n    io.seek(0)\n\n    data = io.getvalue()\n    io.close()\n\n    return data", "title": ""}
{"_id": "d1258", "text": "def error(*args):\n    \"\"\"Display error message via stderr or GUI.\"\"\"\n    if sys.stdin.isatty():\n        print('ERROR:', *args, file=sys.stderr)\n    else:\n        notify_error(*args)", "title": ""}
{"_id": "d1259", "text": "def close(*args, **kwargs):\n    r\"\"\"Close last created figure, alias to ``plt.close()``.\"\"\"\n    _, plt, _ = _import_plt()\n    plt.close(*args, **kwargs)", "title": ""}
{"_id": "d1260", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d1261", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d1262", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d1263", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d1264", "text": "def format_exc(limit=None):\n    \"\"\"Like print_exc() but return a string. Backport for Python 2.3.\"\"\"\n    try:\n        etype, value, tb = sys.exc_info()\n        return ''.join(traceback.format_exception(etype, value, tb, limit))\n    finally:\n        etype = value = tb = None", "title": ""}
{"_id": "d1265", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d1266", "text": "def _get_name(self, key):\n        \"\"\" get display name for a key, or mangle for display \"\"\"\n        if key in self.display_names:\n            return self.display_names[key]\n\n        return key.capitalize()", "title": ""}
{"_id": "d1267", "text": "def scipy_sparse_to_spmatrix(A):\n    \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP", "title": ""}
{"_id": "d1268", "text": "def _screen(self, s, newline=False):\n        \"\"\"Print something on screen when self.verbose == True\"\"\"\n        if self.verbose:\n            if newline:\n                print(s)\n            else:\n                print(s, end=' ')", "title": ""}
{"_id": "d1269", "text": "def scipy_sparse_to_spmatrix(A):\n    \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP", "title": ""}
{"_id": "d1270", "text": "def _stdout_raw(self, s):\n        \"\"\"Writes the string to stdout\"\"\"\n        print(s, end='', file=sys.stdout)\n        sys.stdout.flush()", "title": ""}
{"_id": "d1271", "text": "def write_wav(path, samples, sr=16000):\n    \"\"\"\n    Write to given samples to a wav file.\n    The samples are expected to be floating point numbers\n    in the range of -1.0 to 1.0.\n\n    Args:\n        path (str): The path to write the wav to.\n        samples (np.array): A float array .\n        sr (int): The sampling rate.\n    \"\"\"\n    max_value = np.abs(np.iinfo(np.int16).min)\n    data = (samples * max_value).astype(np.int16)\n    scipy.io.wavfile.write(path, sr, data)", "title": ""}
{"_id": "d1272", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d1273", "text": "def get_soup(page=''):\n    \"\"\"\n    Returns a bs4 object of the page requested\n    \"\"\"\n    content = requests.get('%s/%s' % (BASE_URL, page)).text\n    return BeautifulSoup(content)", "title": ""}
{"_id": "d1274", "text": "def init_checks_registry():\n    \"\"\"Register all globally visible functions.\n\n    The first argument name is either 'physical_line' or 'logical_line'.\n    \"\"\"\n    mod = inspect.getmodule(register_check)\n    for (name, function) in inspect.getmembers(mod, inspect.isfunction):\n        register_check(function)", "title": ""}
{"_id": "d1275", "text": "def mouse_out(self):\n        \"\"\"\n        Performs a mouse out the element.\n\n        Currently works only on Chrome driver.\n        \"\"\"\n        self.scroll_to()\n        ActionChains(self.parent.driver).move_by_offset(0, 0).click().perform()", "title": ""}
{"_id": "d1276", "text": "def push(h, x):\n    \"\"\"Push a new value into heap.\"\"\"\n    h.push(x)\n    up(h, h.size()-1)", "title": ""}
{"_id": "d1277", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d1278", "text": "def bash(filename):\n    \"\"\"Runs a bash script in the local directory\"\"\"\n    sys.stdout.flush()\n    subprocess.call(\"bash {}\".format(filename), shell=True)", "title": ""}
{"_id": "d1279", "text": "def stdin_readable():\n    \"\"\"Determine whether stdin has any data to read.\"\"\"\n    if not WINDOWS:\n        try:\n            return bool(select([sys.stdin], [], [], 0)[0])\n        except Exception:\n            logger.log_exc()\n    try:\n        return not sys.stdin.isatty()\n    except Exception:\n        logger.log_exc()\n    return False", "title": ""}
{"_id": "d1280", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d1281", "text": "def selecttrue(table, field, complement=False):\n    \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n    return select(table, field, lambda v: bool(v), complement=complement)", "title": ""}
{"_id": "d1282", "text": "def execute_in_background(self):\n        \"\"\"Executes a (shell) command in the background\n\n        :return: the process' pid\n        \"\"\"\n        # http://stackoverflow.com/questions/1605520\n        args = shlex.split(self.cmd)\n        p = Popen(args)\n        return p.pid", "title": ""}
{"_id": "d1283", "text": "def selecttrue(table, field, complement=False):\n    \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n    return select(table, field, lambda v: bool(v), complement=complement)", "title": ""}
{"_id": "d1284", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d1285", "text": "def selecttrue(table, field, complement=False):\n    \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n    return select(table, field, lambda v: bool(v), complement=complement)", "title": ""}
{"_id": "d1286", "text": "def ratio_and_percentage(current, total, time_remaining):\n    \"\"\"Returns the progress ratio and percentage.\"\"\"\n    return \"{} / {} ({}% completed)\".format(current, total, int(current / total * 100))", "title": ""}
{"_id": "d1287", "text": "def ask_dir(self):\n\t\t\"\"\"\n\t\tdialogue box for choosing directory\n\t\t\"\"\"\n\t\targs ['directory'] = askdirectory(**self.dir_opt) \n\t\tself.dir_text.set(args ['directory'])", "title": ""}
{"_id": "d1288", "text": "def numpy(self):\n        \"\"\" Grabs image data and converts it to a numpy array \"\"\"\n        # load GDCM's image reading functionality\n        image_reader = gdcm.ImageReader()\n        image_reader.SetFileName(self.fname)\n        if not image_reader.Read():\n            raise IOError(\"Could not read DICOM image\")\n        pixel_array = self._gdcm_to_numpy(image_reader.GetImage())\n        return pixel_array", "title": ""}
{"_id": "d1289", "text": "def selectgt(table, field, value, complement=False):\n    \"\"\"Select rows where the given field is greater than the given value.\"\"\"\n\n    value = Comparable(value)\n    return selectop(table, field, value, operator.gt, complement=complement)", "title": ""}
{"_id": "d1290", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d1291", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d1292", "text": "def ReadManyFromPath(filepath):\n  \"\"\"Reads a Python object stored in a specified YAML file.\n\n  Args:\n    filepath: A filepath to the YAML file.\n\n  Returns:\n    A Python data structure corresponding to the YAML in the given file.\n  \"\"\"\n  with io.open(filepath, mode=\"r\", encoding=\"utf-8\") as filedesc:\n    return ReadManyFromFile(filedesc)", "title": ""}
{"_id": "d1293", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d1294", "text": "def find_first_number(ll):\n    \"\"\" Returns nr of first entry parseable to float in ll, None otherwise\"\"\"\n    for nr, entry in enumerate(ll):\n        try:\n            float(entry)\n        except (ValueError, TypeError) as e:\n            pass\n        else:\n            return nr\n    return None", "title": ""}
{"_id": "d1295", "text": "def filter_by_ids(original_list, ids_to_filter):\n    \"\"\"Filter a list of dicts by IDs using an id key on each dict.\"\"\"\n    if not ids_to_filter:\n        return original_list\n\n    return [i for i in original_list if i['id'] in ids_to_filter]", "title": ""}
{"_id": "d1296", "text": "def load_yaml(filepath):\n    \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n    with open(filepath) as f:\n        txt = f.read()\n    return yaml.load(txt)", "title": ""}
{"_id": "d1297", "text": "def __init__(self):\n    \"\"\"Initializes an attribute container identifier.\"\"\"\n    super(AttributeContainerIdentifier, self).__init__()\n    self._identifier = id(self)", "title": ""}
{"_id": "d1298", "text": "def main_func(args=None):\n    \"\"\"Main funcion when executing this module as script\n\n    :param args: commandline arguments\n    :type args: list\n    :returns: None\n    :rtype: None\n    :raises: None\n    \"\"\"\n    # we have to initialize a gui even if we dont need one right now.\n    # as soon as you call maya.standalone.initialize(), a QApplication\n    # with type Tty is created. This is the type for conosle apps.\n    # Because i have not found a way to replace that, we just init the gui.\n    guimain.init_gui()\n\n    main.init()\n    launcher = Launcher()\n    parsed, unknown = launcher.parse_args(args)\n    parsed.func(parsed, unknown)", "title": ""}
{"_id": "d1299", "text": "async def readline(self):\n        \"\"\"\n        This is an asyncio adapted version of pyserial read.\n        It provides a non-blocking read and returns a line of data read.\n\n        :return: A line of data\n        \"\"\"\n        future = asyncio.Future()\n        data_available = False\n        while True:\n            if not data_available:\n                if not self.my_serial.inWaiting():\n                    await asyncio.sleep(self.sleep_tune)\n                else:\n                    data_available = True\n                    data = self.my_serial.readline()\n                    future.set_result(data)\n            else:\n                if not future.done():\n                    await asyncio.sleep(self.sleep_tune)\n                else:\n                    return future.result()", "title": ""}
{"_id": "d1300", "text": "def _trim(image):\n    \"\"\"Trim a PIL image and remove white space.\"\"\"\n    background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n    diff = PIL.ImageChops.difference(image, background)\n    diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n    bbox = diff.getbbox()\n    if bbox:\n        image = image.crop(bbox)\n    return image", "title": ""}
{"_id": "d1301", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d1302", "text": "def del_Unnamed(df):\n    \"\"\"\n    Deletes all the unnamed columns\n\n    :param df: pandas dataframe\n    \"\"\"\n    cols_del=[c for c in df.columns if 'Unnamed' in c]\n    return df.drop(cols_del,axis=1)", "title": ""}
{"_id": "d1303", "text": "def get_header(request, header_service):\n    \"\"\"Return request's 'X_POLYAXON_...:' header, as a bytestring.\n\n    Hide some test client ickyness where the header can be unicode.\n    \"\"\"\n    service = request.META.get('HTTP_{}'.format(header_service), b'')\n    if isinstance(service, str):\n        # Work around django test client oddness\n        service = service.encode(HTTP_HEADER_ENCODING)\n    return service", "title": ""}
{"_id": "d1304", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d1305", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d1306", "text": "def fix_datagrepper_message(message):\n    \"\"\"\n    See if a message is (probably) a datagrepper message and attempt to mutate\n    it to pass signature validation.\n\n    Datagrepper adds the 'source_name' and 'source_version' keys. If messages happen\n    to use those keys, they will fail message validation. Additionally, a 'headers'\n    dictionary is present on all responses, regardless of whether it was in the\n    original message or not. This is deleted if it's null, which won't be correct in\n    all cases. Finally, datagrepper turns the 'timestamp' field into a float, but it\n    might have been an integer when the message was signed.\n\n    A copy of the dictionary is made and returned if altering the message is necessary.\n\n    I'm so sorry.\n\n    Args:\n        message (dict): A message to clean up.\n\n    Returns:\n        dict: A copy of the provided message, with the datagrepper-related keys removed\n            if they were present.\n    \"\"\"\n    if not ('source_name' in message and 'source_version' in message):\n        return message\n\n    # Don't mutate the original message\n    message = message.copy()\n\n    del message['source_name']\n    del message['source_version']\n    # datanommer adds the headers field to the message in all cases.\n    # This is a huge problem because if the signature was generated with a 'headers'\n    # key set and we delete it here, messages will fail validation, but if we don't\n    # messages will fail validation if they didn't have a 'headers' key set.\n    #\n    # There's no way to know whether or not the headers field was part of the signed\n    # message or not. Generally, the problem is datanommer is mutating messages.\n    if 'headers' in message and not message['headers']:\n        del message['headers']\n    if 'timestamp' in message:\n        message['timestamp'] = int(message['timestamp'])\n\n    return message", "title": ""}
{"_id": "d1307", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d1308", "text": "def wordify(text):\n    \"\"\"Generate a list of words given text, removing punctuation.\n\n    Parameters\n    ----------\n    text : unicode\n        A piece of english text.\n\n    Returns\n    -------\n    words : list\n        List of words.\n    \"\"\"\n    stopset = set(nltk.corpus.stopwords.words('english'))\n    tokens = nltk.WordPunctTokenizer().tokenize(text)\n    return [w for w in tokens if w not in stopset]", "title": ""}
{"_id": "d1309", "text": "def get_var(name, factory=None):\n    \"\"\"Gets a global variable given its name.\n\n    If factory is not None and the variable is not set, factory\n    is a callable that will set the variable.\n\n    If not set, returns None.\n    \"\"\"\n    if name not in _VARS and factory is not None:\n        _VARS[name] = factory()\n    return _VARS.get(name)", "title": ""}
{"_id": "d1310", "text": "def remove_non_magic_cols(self):\n        \"\"\"\n        Remove all non-MagIC columns from all tables.\n        \"\"\"\n        for table_name in self.tables:\n            table = self.tables[table_name]\n            table.remove_non_magic_cols_from_table()", "title": ""}
{"_id": "d1311", "text": "def turn(self):\n        \"\"\"Turn the ring for a single position.\n        For example, [a, b, c, d] becomes [b, c, d, a].\"\"\"\n        first = self._data.pop(0)\n        self._data.append(first)", "title": ""}
{"_id": "d1312", "text": "def clean_axis(axis):\n    \"\"\"Remove ticks, tick labels, and frame from axis\"\"\"\n    axis.get_xaxis().set_ticks([])\n    axis.get_yaxis().set_ticks([])\n    for spine in list(axis.spines.values()):\n        spine.set_visible(False)", "title": ""}
{"_id": "d1313", "text": "def set_log_level(logger_name: str, log_level: str, propagate: bool = False):\n    \"\"\"Set the log level of the specified logger.\"\"\"\n    log = logging.getLogger(logger_name)\n    log.propagate = propagate\n    log.setLevel(log_level)", "title": ""}
{"_id": "d1314", "text": "def split_comma_argument(comma_sep_str):\n    \"\"\"Split a comma separated option into a list.\"\"\"\n    terms = []\n    for term in comma_sep_str.split(','):\n        if term:\n            terms.append(term)\n    return terms", "title": ""}
{"_id": "d1315", "text": "def python_mime(fn):\n    \"\"\"\n    Decorator, which adds correct MIME type for python source to the decorated\n    bottle API function.\n    \"\"\"\n    @wraps(fn)\n    def python_mime_decorator(*args, **kwargs):\n        response.content_type = \"text/x-python\"\n\n        return fn(*args, **kwargs)\n\n    return python_mime_decorator", "title": ""}
{"_id": "d1316", "text": "def set_pivot_keys(self, foreign_key, other_key):\n        \"\"\"\n        Set the key names for the pivot model instance\n        \"\"\"\n        self.__foreign_key = foreign_key\n        self.__other_key = other_key\n\n        return self", "title": ""}
{"_id": "d1317", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d1318", "text": "def fmt_subst(regex, subst):\n    \"\"\"Replace regex with string.\"\"\"\n    return lambda text: re.sub(regex, subst, text) if text else text", "title": ""}
{"_id": "d1319", "text": "def discard(self, element):\n        \"\"\"Remove element from the RangeSet if it is a member.\n\n        If the element is not a member, do nothing.\n        \"\"\"\n        try:\n            i = int(element)\n            set.discard(self, i)\n        except ValueError:\n            pass", "title": ""}
{"_id": "d1320", "text": "def median(self):\n        \"\"\"Computes the median of a log-normal distribution built with the stats data.\"\"\"\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", "title": ""}
{"_id": "d1321", "text": "def load_file(self, filename):\n        \"\"\"Read in file contents and set the current string.\"\"\"\n        with open(filename, 'r') as sourcefile:\n            self.set_string(sourcefile.read())", "title": ""}
{"_id": "d1322", "text": "def normalise_string(string):\n    \"\"\" Strips trailing whitespace from string, lowercases it and replaces\n        spaces with underscores\n    \"\"\"\n    string = (string.strip()).lower()\n    return re.sub(r'\\W+', '_', string)", "title": ""}
{"_id": "d1323", "text": "def to_utc(self, dt):\n        \"\"\"Convert any timestamp to UTC (with tzinfo).\"\"\"\n        if dt.tzinfo is None:\n            return dt.replace(tzinfo=self.utc)\n        return dt.astimezone(self.utc)", "title": ""}
{"_id": "d1324", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d1325", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d1326", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d1327", "text": "def check_str(obj):\n        \"\"\" Returns a string for various input types \"\"\"\n        if isinstance(obj, str):\n            return obj\n        if isinstance(obj, float):\n            return str(int(obj))\n        else:\n            return str(obj)", "title": ""}
{"_id": "d1328", "text": "async def restart(request):\n    \"\"\"\n    Returns OK, then waits approximately 1 second and restarts container\n    \"\"\"\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\"})", "title": ""}
{"_id": "d1329", "text": "def issuperset(self, other):\n        \"\"\"Report whether this RangeSet contains another set.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issuperset(self, other)", "title": ""}
{"_id": "d1330", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d1331", "text": "def feed_eof(self):\n        \"\"\"Send a potentially \"ragged\" EOF.\n\n        This method will raise an SSL_ERROR_EOF exception if the EOF is\n        unexpected.\n        \"\"\"\n        self._incoming.write_eof()\n        ssldata, appdata = self.feed_ssldata(b'')\n        assert appdata == [] or appdata == [b'']", "title": ""}
{"_id": "d1332", "text": "def maxDepth(self, currentDepth=0):\n        \"\"\"Compute the depth of the longest branch of the tree\"\"\"\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", "title": ""}
{"_id": "d1333", "text": "def bounds_to_poly(bounds):\n    \"\"\"\n    Constructs a shapely Polygon from the provided bounds tuple.\n\n    Parameters\n    ----------\n    bounds: tuple\n        Tuple representing the (left, bottom, right, top) coordinates\n\n    Returns\n    -------\n    polygon: shapely.geometry.Polygon\n        Shapely Polygon geometry of the bounds\n    \"\"\"\n    x0, y0, x1, y1 = bounds\n    return Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])", "title": ""}
{"_id": "d1334", "text": "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)", "title": ""}
{"_id": "d1335", "text": "def format_exc(*exc_info):\n    \"\"\"Show exception with traceback.\"\"\"\n    typ, exc, tb = exc_info or sys.exc_info()\n    error = traceback.format_exception(typ, exc, tb)\n    return \"\".join(error)", "title": ""}
{"_id": "d1336", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d1337", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d1338", "text": "def round_to_n(x, n):\n    \"\"\"\n    Round to sig figs\n    \"\"\"\n    return round(x, -int(np.floor(np.log10(x))) + (n - 1))", "title": ""}
{"_id": "d1339", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d1340", "text": "def round_to_n(x, n):\n    \"\"\"\n    Round to sig figs\n    \"\"\"\n    return round(x, -int(np.floor(np.log10(x))) + (n - 1))", "title": ""}
{"_id": "d1341", "text": "def lowPass(self, *args):\n        \"\"\"\n        Creates a copy of the signal with the low pass applied, args specifed are passed through to _butter. \n        :return: \n        \"\"\"\n        return Signal(self._butter(self.samples, 'low', *args), fs=self.fs)", "title": ""}
{"_id": "d1342", "text": "def begin_stream_loop(stream, poll_interval):\n    \"\"\"Start and maintain the streaming connection...\"\"\"\n    while should_continue():\n        try:\n            stream.start_polling(poll_interval)\n        except Exception as e:\n            # Infinite restart\n            logger.error(\"Exception while polling. Restarting in 1 second.\", exc_info=True)\n            time.sleep(1)", "title": ""}
{"_id": "d1343", "text": "def sine_wave(frequency):\n  \"\"\"Emit a sine wave at the given frequency.\"\"\"\n  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n  ts = xs / FLAGS.sample_rate\n  return tf.sin(2 * math.pi * frequency * ts)", "title": ""}
{"_id": "d1344", "text": "def lint(args):\n    \"\"\"Run lint checks using flake8.\"\"\"\n    application = get_current_application()\n    if not args:\n        args = [application.name, 'tests']\n    args = ['flake8'] + list(args)\n    run.main(args, standalone_mode=False)", "title": ""}
{"_id": "d1345", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d1346", "text": "def stub_main():\n    \"\"\"setuptools blah: it still can't run a module as a script entry_point\"\"\"\n    from google.apputils import run_script_module\n    import butcher.main\n    run_script_module.RunScriptModule(butcher.main)", "title": ""}
{"_id": "d1347", "text": "def _nbytes(buf):\n    \"\"\"Return byte-size of a memoryview or buffer.\"\"\"\n    if isinstance(buf, memoryview):\n        if PY3:\n            # py3 introduces nbytes attribute\n            return buf.nbytes\n        else:\n            # compute nbytes on py2\n            size = buf.itemsize\n            for dim in buf.shape:\n                size *= dim\n            return size\n    else:\n        # not a memoryview, raw bytes/ py2 buffer\n        return len(buf)", "title": ""}
{"_id": "d1348", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d1349", "text": "def _skip_frame(self):\n        \"\"\"Skip the next time frame\"\"\"\n        for line in self._f:\n            if line == 'ITEM: ATOMS\\n':\n                break\n        for i in range(self.num_atoms):\n            next(self._f)", "title": ""}
{"_id": "d1350", "text": "def save_excel(self, fd):\n        \"\"\" Saves the case as an Excel spreadsheet.\n        \"\"\"\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)", "title": ""}
{"_id": "d1351", "text": "def skip(self, n):\n        \"\"\"Skip the specified number of elements in the list.\n\n        If the number skipped is greater than the number of elements in\n        the list, hasNext() becomes false and available() returns zero\n        as there are no more elements to retrieve.\n\n        arg:    n (cardinal): the number of elements to skip\n        *compliance: mandatory -- This method must be implemented.*\n\n        \"\"\"\n        try:\n            self._iter_object.skip(n)\n        except AttributeError:\n            for i in range(0, n):\n                self.next()", "title": ""}
{"_id": "d1352", "text": "def getbyteslice(self, start, end):\n        \"\"\"Direct access to byte data.\"\"\"\n        c = self._rawarray[start:end]\n        return c", "title": ""}
{"_id": "d1353", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d1354", "text": "def is_full_slice(obj, l):\n    \"\"\"\n    We have a full length slice.\n    \"\"\"\n    return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and\n            obj.step is None)", "title": ""}
{"_id": "d1355", "text": "def resize_image(self, data, size):\n        \"\"\" Resizes the given image to fit inside a box of the given size. \"\"\"\n        from machina.core.compat import PILImage as Image\n        image = Image.open(BytesIO(data))\n\n        # Resize!\n        image.thumbnail(size, Image.ANTIALIAS)\n\n        string = BytesIO()\n        image.save(string, format='PNG')\n        return string.getvalue()", "title": ""}
{"_id": "d1356", "text": "def stop(self, dummy_signum=None, dummy_frame=None):\n        \"\"\" Shutdown process (this method is also a signal handler) \"\"\"\n        logging.info('Shutting down ...')\n        self.socket.close()\n        sys.exit(0)", "title": ""}
{"_id": "d1357", "text": "def stop(self):\n        \"\"\"Stops the background synchronization thread\"\"\"\n        with self.synclock:\n            if self.syncthread is not None:\n                self.syncthread.cancel()\n                self.syncthread = None", "title": ""}
{"_id": "d1358", "text": "def symlink_remove(link):\n    \"\"\"Remove a symlink. Used for model shortcut links.\n\n    link (unicode / Path): The path to the symlink.\n    \"\"\"\n    # https://stackoverflow.com/q/26554135/6400719\n    if os.path.isdir(path2str(link)) and is_windows:\n        # this should only be on Py2.7 and windows\n        os.rmdir(path2str(link))\n    else:\n        os.unlink(path2str(link))", "title": ""}
{"_id": "d1359", "text": "def _get_column_types(self, data):\n        \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n        columns = list(zip_longest(*data))\n        return [self._get_column_type(column) for column in columns]", "title": ""}
{"_id": "d1360", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d1361", "text": "def transcript_sort_key(transcript):\n    \"\"\"\n    Key function used to sort transcripts. Taking the negative of\n    protein sequence length and nucleotide sequence length so that\n    the transcripts with longest sequences come first in the list. This couldn't\n    be accomplished with `reverse=True` since we're also sorting by\n    transcript name (which places TP53-001 before TP53-002).\n    \"\"\"\n    return (\n        -len(transcript.protein_sequence),\n        -len(transcript.sequence),\n        transcript.name\n    )", "title": ""}
{"_id": "d1362", "text": "def getdefaultencoding():\n    \"\"\"Return IPython's guess for the default encoding for bytes as text.\n\n    Asks for stdin.encoding first, to match the calling Terminal, but that\n    is often None for subprocesses.  Fall back on locale.getpreferredencoding()\n    which should be a sensible platform default (that respects LANG environment),\n    and finally to sys.getdefaultencoding() which is the most conservative option,\n    and usually ASCII.\n    \"\"\"\n    enc = get_stream_enc(sys.stdin)\n    if not enc or enc=='ascii':\n        try:\n            # There are reports of getpreferredencoding raising errors\n            # in some cases, which may well be fixed, but let's be conservative here.\n            enc = locale.getpreferredencoding()\n        except Exception:\n            pass\n    return enc or sys.getdefaultencoding()", "title": ""}
{"_id": "d1363", "text": "def transcript_sort_key(transcript):\n    \"\"\"\n    Key function used to sort transcripts. Taking the negative of\n    protein sequence length and nucleotide sequence length so that\n    the transcripts with longest sequences come first in the list. This couldn't\n    be accomplished with `reverse=True` since we're also sorting by\n    transcript name (which places TP53-001 before TP53-002).\n    \"\"\"\n    return (\n        -len(transcript.protein_sequence),\n        -len(transcript.sequence),\n        transcript.name\n    )", "title": ""}
{"_id": "d1364", "text": "def _config_win32_domain(self, domain):\n        \"\"\"Configure a Domain registry entry.\"\"\"\n        # we call str() on domain to convert it from unicode to ascii\n        self.domain = dns.name.from_text(str(domain))", "title": ""}
{"_id": "d1365", "text": "def _dict_values_sorted_by_key(dictionary):\n    # This should be a yield from instead.\n    \"\"\"Internal helper to return the values of a dictionary, sorted by key.\n    \"\"\"\n    for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):\n        yield value", "title": ""}
{"_id": "d1366", "text": "def get_neg_infinity(dtype):\n    \"\"\"Return an appropriate positive infinity for this dtype.\n\n    Parameters\n    ----------\n    dtype : np.dtype\n\n    Returns\n    -------\n    fill_value : positive infinity value corresponding to this dtype.\n    \"\"\"\n    if issubclass(dtype.type, (np.floating, np.integer)):\n        return -np.inf\n\n    if issubclass(dtype.type, np.complexfloating):\n        return -np.inf - 1j * np.inf\n\n    return NINF", "title": ""}
{"_id": "d1367", "text": "def direct2dDistance(self, point):\n        \"\"\"consider the distance between two mapPoints, ignoring all terrain, pathing issues\"\"\"\n        if not isinstance(point, MapPoint): return 0.0\n        return  ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula", "title": ""}
{"_id": "d1368", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d1369", "text": "def _removeStopwords(text_list):\n    \"\"\"\n    Removes stopwords contained in a list of words.\n\n    :param text_string: A list of strings.\n    :type text_string: list.\n\n    :returns: The input ``text_list`` with stopwords removed.\n    :rtype: list\n    \"\"\"\n\n    output_list = []\n\n    for word in text_list:\n        if word.lower() not in _stopwords:\n            output_list.append(word)\n\n    return output_list", "title": ""}
{"_id": "d1370", "text": "def GetPythonLibraryDirectoryPath():\n  \"\"\"Retrieves the Python library directory path.\"\"\"\n  path = sysconfig.get_python_lib(True)\n  _, _, path = path.rpartition(sysconfig.PREFIX)\n\n  if path.startswith(os.sep):\n    path = path[1:]\n\n  return path", "title": ""}
{"_id": "d1371", "text": "def lspearmanr(x,y):\n    \"\"\"\nCalculates a Spearman rank-order correlation coefficient.  Taken\nfrom Heiman's Basic Statistics for the Behav. Sci (1st), p.192.\n\nUsage:   lspearmanr(x,y)      where x and y are equal-length lists\nReturns: Spearman's r, two-tailed p-value\n\"\"\"\n    TINY = 1e-30\n    if len(x) != len(y):\n        raise ValueError('Input values not paired in spearmanr.  Aborting.')\n    n = len(x)\n    rankx = rankdata(x)\n    ranky = rankdata(y)\n    dsq = sumdiffsquared(rankx,ranky)\n    rs = 1 - 6*dsq / float(n*(n**2-1))\n    t = rs * math.sqrt((n-2) / ((rs+1.0)*(1.0-rs)))\n    df = n-2\n    probrs = betai(0.5*df,0.5,df/(df+t*t))  # t already a float\n# probability values for rs are from part 2 of the spearman function in\n# Numerical Recipies, p.510.  They are close to tables, but not exact. (?)\n    return rs, probrs", "title": ""}
{"_id": "d1372", "text": "def _python_rpath(self):\n        \"\"\"The relative path (from environment root) to python.\"\"\"\n        # Windows virtualenv installation installs pip to the [Ss]cripts\n        # folder. Here's a simple check to support:\n        if sys.platform == 'win32':\n            return os.path.join('Scripts', 'python.exe')\n        return os.path.join('bin', 'python')", "title": ""}
{"_id": "d1373", "text": "def _not(condition=None, **kwargs):\n    \"\"\"\n    Return the opposite of input condition.\n\n    :param condition: condition to process.\n\n    :result: not condition.\n    :rtype: bool\n    \"\"\"\n\n    result = True\n\n    if condition is not None:\n        result = not run(condition, **kwargs)\n\n    return result", "title": ""}
{"_id": "d1374", "text": "def setValue(self, p_float):\n        \"\"\"Override method to set a value to show it as 0 to 100.\n\n        :param p_float: The float number that want to be set.\n        :type p_float: float\n        \"\"\"\n        p_float = p_float * 100\n\n        super(PercentageSpinBox, self).setValue(p_float)", "title": ""}
{"_id": "d1375", "text": "def expand_args(cmd_args):\n    \"\"\"split command args to args list\n    returns a list of args\n\n    :param cmd_args: command args, can be tuple, list or str\n    \"\"\"\n    if isinstance(cmd_args, (tuple, list)):\n        args_list = list(cmd_args)\n    else:\n        args_list = shlex.split(cmd_args)\n    return args_list", "title": ""}
{"_id": "d1376", "text": "def datetime_from_timestamp(timestamp, content):\n    \"\"\"\n    Helper function to add timezone information to datetime,\n    so that datetime is comparable to other datetime objects in recent versions\n    that now also have timezone information.\n    \"\"\"\n    return set_date_tzinfo(\n        datetime.fromtimestamp(timestamp),\n        tz_name=content.settings.get('TIMEZONE', None))", "title": ""}
{"_id": "d1377", "text": "def split_on(s, sep=\" \"):\n    \"\"\"Split s by sep, unless it's inside a quote.\"\"\"\n    pattern = '''((?:[^%s\"']|\"[^\"]*\"|'[^']*')+)''' % sep\n\n    return [_strip_speechmarks(t) for t in re.split(pattern, s)[1::2]]", "title": ""}
{"_id": "d1378", "text": "def SetValue(self, row, col, value):\n        \"\"\"\n        Set value in the pandas DataFrame\n        \"\"\"\n        self.dataframe.iloc[row, col] = value", "title": ""}
{"_id": "d1379", "text": "def extract_args(argv):\n    \"\"\"\n    take sys.argv that is used to call a command-line script and return a correctly split list of arguments\n    for example, this input: [\"eqarea.py\", \"-f\", \"infile\", \"-F\", \"outfile\", \"-A\"]\n    will return this output: [['f', 'infile'], ['F', 'outfile'], ['A']]\n    \"\"\"\n    string = \" \".join(argv)\n    string = string.split(' -')\n    program = string[0]\n    arguments = [s.split() for s in string[1:]]\n    return arguments", "title": ""}
{"_id": "d1380", "text": "def move_to(x, y):\n    \"\"\"Moves the brush to a particular position.\n\n    Arguments:\n        x - a number between -250 and 250.\n        y - a number between -180 and 180.\n    \"\"\"\n    _make_cnc_request(\"coord/{0}/{1}\".format(x, y))\n    state['turtle'].goto(x, y)", "title": ""}
{"_id": "d1381", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d1382", "text": "def stopwatch_now():\n    \"\"\"Get a timevalue for interval comparisons\n\n    When possible it is a monotonic clock to prevent backwards time issues.\n    \"\"\"\n    if six.PY2:\n        now = time.time()\n    else:\n        now = time.monotonic()\n    return now", "title": ""}
{"_id": "d1383", "text": "def case_us2mc(x):\n    \"\"\" underscore to mixed case notation \"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)", "title": ""}
{"_id": "d1384", "text": "def file_found(filename,force):\n    \"\"\"Check if a file exists\"\"\"\n    if os.path.exists(filename) and not force:\n        logger.info(\"Found %s; skipping...\"%filename)\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d1385", "text": "def restart(self, reset=False):\n        \"\"\"\n        Quit and Restart Spyder application.\n\n        If reset True it allows to reset spyder on restart.\n        \"\"\"\n        # Get start path to use in restart script\n        spyder_start_directory = get_module_path('spyder')\n        restart_script = osp.join(spyder_start_directory, 'app', 'restart.py')\n\n        # Get any initial argument passed when spyder was started\n        # Note: Variables defined in bootstrap.py and spyder/app/start.py\n        env = os.environ.copy()\n        bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)\n        spyder_args = env.pop('SPYDER_ARGS')\n\n        # Get current process and python running spyder\n        pid = os.getpid()\n        python = sys.executable\n\n        # Check if started with bootstrap.py\n        if bootstrap_args is not None:\n            spyder_args = bootstrap_args\n            is_bootstrap = True\n        else:\n            is_bootstrap = False\n\n        # Pass variables as environment variables (str) to restarter subprocess\n        env['SPYDER_ARGS'] = spyder_args\n        env['SPYDER_PID'] = str(pid)\n        env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)\n        env['SPYDER_RESET'] = str(reset)\n\n        if DEV:\n            if os.name == 'nt':\n                env['PYTHONPATH'] = ';'.join(sys.path)\n            else:\n                env['PYTHONPATH'] = ':'.join(sys.path)\n\n        # Build the command and popen arguments depending on the OS\n        if os.name == 'nt':\n            # Hide flashing command prompt\n            startupinfo = subprocess.STARTUPINFO()\n            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n            shell = False\n        else:\n            startupinfo = None\n            shell = True\n\n        command = '\"{0}\" \"{1}\"'\n        command = command.format(python, restart_script)\n\n        try:\n            if self.closing(True):\n                subprocess.Popen(command, shell=shell, env=env,\n                                 startupinfo=startupinfo)\n                self.console.quit()\n        except Exception as error:\n            # If there is an error with subprocess, Spyder should not quit and\n            # the error can be inspected in the internal console\n            print(error)  # spyder: test-skip\n            print(command)", "title": ""}
{"_id": "d1386", "text": "def MatrixSolve(a, rhs, adj):\n    \"\"\"\n    Matrix solve op.\n    \"\"\"\n    return np.linalg.solve(a if not adj else _adjoint(a), rhs),", "title": ""}
{"_id": "d1387", "text": "def _bindingsToDict(self, bindings):\n        \"\"\"\n        Given a binding from the sparql query result,\n        create a dict of plain text\n        \"\"\"\n        myDict = {}\n        for key, val in bindings.iteritems():\n            myDict[key.toPython().replace('?', '')] = val.toPython()\n        return myDict", "title": ""}
{"_id": "d1388", "text": "def MatrixSolve(a, rhs, adj):\n    \"\"\"\n    Matrix solve op.\n    \"\"\"\n    return np.linalg.solve(a if not adj else _adjoint(a), rhs),", "title": ""}
{"_id": "d1389", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d1390", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d1391", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d1392", "text": "def sort_dict(d, key=None, reverse=False):\n    \"\"\"\n    Sorts a dict by value.\n\n    Args:\n        d: Input dictionary\n        key: Function which takes an tuple (key, object) and returns a value to\n            compare and sort by. By default, the function compares the values\n            of the dict i.e. key = lambda t : t[1]\n        reverse: Allows to reverse sort order.\n\n    Returns:\n        OrderedDict object whose keys are ordered according to their value.\n    \"\"\"\n    kv_items = [kv for kv in d.items()]\n\n    # Sort kv_items according to key.\n    if key is None:\n        kv_items.sort(key=lambda t: t[1], reverse=reverse)\n    else:\n        kv_items.sort(key=key, reverse=reverse)\n\n    # Build ordered dict.\n    return collections.OrderedDict(kv_items)", "title": ""}
{"_id": "d1393", "text": "def commit(self, session=None):\n        \"\"\"Merge modified objects into parent transaction.\n\n        Once commited a transaction object is not usable anymore\n\n        :param:session: current sqlalchemy Session\n        \"\"\"\n        if self.__cleared:\n            return\n\n        if self._parent:\n            # nested transaction\n            self._commit_parent()\n        else:\n            self._commit_repository()\n        self._clear()", "title": ""}
{"_id": "d1394", "text": "def arglexsort(arrays):\n    \"\"\"\n    Returns the indices of the lexicographical sorting\n    order of the supplied arrays.\n    \"\"\"\n    dtypes = ','.join(array.dtype.str for array in arrays)\n    recarray = np.empty(len(arrays[0]), dtype=dtypes)\n    for i, array in enumerate(arrays):\n        recarray['f%s' % i] = array\n    return recarray.argsort()", "title": ""}
{"_id": "d1395", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d1396", "text": "def sort_dict(d, key=None, reverse=False):\n    \"\"\"\n    Sorts a dict by value.\n\n    Args:\n        d: Input dictionary\n        key: Function which takes an tuple (key, object) and returns a value to\n            compare and sort by. By default, the function compares the values\n            of the dict i.e. key = lambda t : t[1]\n        reverse: Allows to reverse sort order.\n\n    Returns:\n        OrderedDict object whose keys are ordered according to their value.\n    \"\"\"\n    kv_items = [kv for kv in d.items()]\n\n    # Sort kv_items according to key.\n    if key is None:\n        kv_items.sort(key=lambda t: t[1], reverse=reverse)\n    else:\n        kv_items.sort(key=key, reverse=reverse)\n\n    # Build ordered dict.\n    return collections.OrderedDict(kv_items)", "title": ""}
{"_id": "d1397", "text": "def __init__(self):\n    \"\"\"Initializes the database file object.\"\"\"\n    super(Sqlite3DatabaseFile, self).__init__()\n    self._connection = None\n    self._cursor = None\n    self.filename = None\n    self.read_only = None", "title": ""}
{"_id": "d1398", "text": "def arglexsort(arrays):\n    \"\"\"\n    Returns the indices of the lexicographical sorting\n    order of the supplied arrays.\n    \"\"\"\n    dtypes = ','.join(array.dtype.str for array in arrays)\n    recarray = np.empty(len(arrays[0]), dtype=dtypes)\n    for i, array in enumerate(arrays):\n        recarray['f%s' % i] = array\n    return recarray.argsort()", "title": ""}
{"_id": "d1399", "text": "def _shutdown_transport(self):\n        \"\"\"Unwrap a Python 2.6 SSL socket, so we can call shutdown()\"\"\"\n        if self.sock is not None:\n            try:\n                unwrap = self.sock.unwrap\n            except AttributeError:\n                return\n            try:\n                self.sock = unwrap()\n            except ValueError:\n                # Failure within SSL might mean unwrap exists but socket is not\n                # deemed wrapped\n                pass", "title": ""}
{"_id": "d1400", "text": "def sort_nicely(l):\n    \"\"\"Sort the given list in the way that humans expect.\"\"\"\n    convert = lambda text: int(text) if text.isdigit() else text\n    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]\n    l.sort(key=alphanum_key)", "title": ""}
{"_id": "d1401", "text": "def weighted_std(values, weights):\n    \"\"\" Calculate standard deviation weighted by errors \"\"\"\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)", "title": ""}
{"_id": "d1402", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d1403", "text": "def _std(self,x):\n        \"\"\"\n        Compute standard deviation with ddof degrees of freedom\n        \"\"\"\n        return np.nanstd(x.values,ddof=self._ddof)", "title": ""}
{"_id": "d1404", "text": "def asynchronous(function, event):\n    \"\"\"\n    Runs the function asynchronously taking care of exceptions.\n    \"\"\"\n    thread = Thread(target=synchronous, args=(function, event))\n    thread.daemon = True\n    thread.start()", "title": ""}
{"_id": "d1405", "text": "def get_function_class(function_name):\n    \"\"\"\n    Return the type for the requested function\n\n    :param function_name: the function to return\n    :return: the type for that function (i.e., this is a class, not an instance)\n    \"\"\"\n\n    if function_name in _known_functions:\n\n        return _known_functions[function_name]\n\n    else:\n\n        raise UnknownFunction(\"Function %s is not known. Known functions are: %s\" %\n                              (function_name, \",\".join(_known_functions.keys())))", "title": ""}
{"_id": "d1406", "text": "def safe_call(cls, method, *args):\n        \"\"\" Call a remote api method but don't raise if an error occurred.\"\"\"\n        return cls.call(method, *args, safe=True)", "title": ""}
{"_id": "d1407", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d1408", "text": "def is_static(*p):\n    \"\"\" A static value (does not change at runtime)\n    which is known at compile time\n    \"\"\"\n    return all(is_CONST(x) or\n               is_number(x) or\n               is_const(x)\n               for x in p)", "title": ""}
{"_id": "d1409", "text": "def incidence(boundary):\n    \"\"\"\n    given an Nxm matrix containing boundary info between simplices,\n    compute indidence info matrix\n    not very reusable; should probably not be in this lib\n    \"\"\"\n    return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1])", "title": ""}
{"_id": "d1410", "text": "def _update_staticmethod(self, oldsm, newsm):\n        \"\"\"Update a staticmethod update.\"\"\"\n        # While we can't modify the staticmethod object itself (it has no\n        # mutable attributes), we *can* extract the underlying function\n        # (by calling __get__(), which returns it) and update it in-place.\n        # We don't have the class available to pass to __get__() but any\n        # object except None will do.\n        self._update(None, None, oldsm.__get__(0), newsm.__get__(0))", "title": ""}
{"_id": "d1411", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d1412", "text": "def disconnect(self):\n        \"\"\"Gracefully close connection to stomp server.\"\"\"\n        if self._connected:\n            self._connected = False\n            self._conn.disconnect()", "title": ""}
{"_id": "d1413", "text": "def timeout_thread_handler(timeout, stop_event):\n    \"\"\"A background thread to kill the process if it takes too long.\n\n    Args:\n        timeout (float): The number of seconds to wait before killing\n            the process.\n        stop_event (Event): An optional event to cleanly stop the background\n            thread if required during testing.\n    \"\"\"\n\n    stop_happened = stop_event.wait(timeout)\n    if stop_happened is False:\n        print(\"Killing program due to %f second timeout\" % timeout)\n\n    os._exit(2)", "title": ""}
{"_id": "d1414", "text": "def _configure_logger():\n    \"\"\"Configure the logging module.\"\"\"\n    if not app.debug:\n        _configure_logger_for_production(logging.getLogger())\n    elif not app.testing:\n        _configure_logger_for_debugging(logging.getLogger())", "title": ""}
{"_id": "d1415", "text": "def _StopStatusUpdateThread(self):\n    \"\"\"Stops the status update thread.\"\"\"\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", "title": ""}
{"_id": "d1416", "text": "def to_binary(s, encoding='utf8'):\n    \"\"\"Portable cast function.\n\n    In python 2 the ``str`` function which is used to coerce objects to bytes does not\n    accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n    :param s: object to be converted to binary_type\n    :return: binary_type instance, representing s.\n    \"\"\"\n    if PY3:  # pragma: no cover\n        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n    return binary_type(s)", "title": ""}
{"_id": "d1417", "text": "def stop_button_click_handler(self):\n        \"\"\"Method to handle what to do when the stop button is pressed\"\"\"\n        self.stop_button.setDisabled(True)\n        # Interrupt computations or stop debugging\n        if not self.shellwidget._reading:\n            self.interrupt_kernel()\n        else:\n            self.shellwidget.write_to_stdin('exit')", "title": ""}
{"_id": "d1418", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d1419", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d1420", "text": "def _validate_date_str(str_):\n    \"\"\"Validate str as a date and return string version of date\"\"\"\n\n    if not str_:\n        return None\n\n    # Convert to datetime so we can validate it's a real date that exists then\n    # convert it back to the string.\n    try:\n        date = datetime.strptime(str_, DATE_FMT)\n    except ValueError:\n        msg = 'Invalid date format, should be YYYY-MM-DD'\n        raise argparse.ArgumentTypeError(msg)\n\n    return date.strftime(DATE_FMT)", "title": ""}
{"_id": "d1421", "text": "def magnitude(X):\n    \"\"\"Magnitude of a complex matrix.\"\"\"\n    r = np.real(X)\n    i = np.imag(X)\n    return np.sqrt(r * r + i * i);", "title": ""}
{"_id": "d1422", "text": "def loads(s, model=None, parser=None):\n    \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n    with StringIO(s) as f:\n        return load(f, model=model, parser=parser)", "title": ""}
{"_id": "d1423", "text": "def dot(self, w):\n        \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n        return sum([x * y for x, y in zip(self, w)])", "title": ""}
{"_id": "d1424", "text": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "title": ""}
{"_id": "d1425", "text": "def mean_date(dt_list):\n    \"\"\"Calcuate mean datetime from datetime list\n    \"\"\"\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", "title": ""}
{"_id": "d1426", "text": "def _serialize_json(obj, fp):\n    \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n    json.dump(obj, fp, indent=4, default=serialize)", "title": ""}
{"_id": "d1427", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d1428", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d1429", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d1430", "text": "def format_float(value): # not used\n    \"\"\"Modified form of the 'g' format specifier.\n    \"\"\"\n    string = \"{:g}\".format(value).replace(\"e+\", \"e\")\n    string = re.sub(\"e(-?)0*(\\d+)\", r\"e\\1\\2\", string)\n    return string", "title": ""}
{"_id": "d1431", "text": "def random_int(maximum_value):\n\t\"\"\" Random generator (PyCrypto getrandbits wrapper). The result is a non-negative value.\n\n\t:param maximum_value: maximum integer value\n\t:return: int\n\t\"\"\"\n\tif maximum_value == 0:\n\t\treturn 0\n\telif maximum_value == 1:\n\t\treturn random_bits(1)\n\n\tbits = math.floor(math.log2(maximum_value))\n\tresult = random_bits(bits) + random_int(maximum_value - ((2 ** bits) - 1))\n\treturn result", "title": ""}
{"_id": "d1432", "text": "def covstr(s):\n  \"\"\" convert string to int or float. \"\"\"\n  try:\n    ret = int(s)\n  except ValueError:\n    ret = float(s)\n  return ret", "title": ""}
{"_id": "d1433", "text": "def _system_parameters(**kwargs):\n    \"\"\"\n    Returns system keyword arguments removing Nones.\n\n    Args:\n        kwargs: system keyword arguments.\n\n    Returns:\n        dict: system keyword arguments.\n    \"\"\"\n    return {key: value for key, value in kwargs.items()\n            if (value is not None or value == {})}", "title": ""}
{"_id": "d1434", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d1435", "text": "def is_string(val):\n    \"\"\"Determines whether the passed value is a string, safe for 2/3.\"\"\"\n    try:\n        basestring\n    except NameError:\n        return isinstance(val, str)\n    return isinstance(val, basestring)", "title": ""}
{"_id": "d1436", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d1437", "text": "def lcumsum (inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1,len(newlist)):\n        newlist[i] = newlist[i] + newlist[i-1]\n    return newlist", "title": ""}
{"_id": "d1438", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d1439", "text": "def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model):\n    \"\"\" The how well do the features plus a constant base rate sum up to the model output.\n    \"\"\"\n\n    X_train, X_test = to_array(X_train, X_test)\n\n    # how many features to mask\n    assert X_train.shape[1] == X_test.shape[1]\n\n    # keep nkeep top features and re-train the model for each test explanation\n    yp_test = trained_model.predict(X_test)\n\n    return metric(yp_test, strip_list(attr_test).sum(1))", "title": ""}
{"_id": "d1440", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d1441", "text": "def doc_to_html(doc, doc_format=\"ROBOT\"):\n    \"\"\"Convert documentation to HTML\"\"\"\n    from robot.libdocpkg.htmlwriter import DocToHtml\n    return DocToHtml(doc_format)(doc)", "title": ""}
{"_id": "d1442", "text": "def replace(scope, strings, source, dest):\n    \"\"\"\n    Returns a copy of the given string (or list of strings) in which all\n    occurrences of the given source are replaced by the given dest.\n\n    :type  strings: string\n    :param strings: A string, or a list of strings.\n    :type  source: string\n    :param source: What to replace.\n    :type  dest: string\n    :param dest: What to replace it with.\n    :rtype:  string\n    :return: The resulting string, or list of strings.\n    \"\"\"\n    return [s.replace(source[0], dest[0]) for s in strings]", "title": ""}
{"_id": "d1443", "text": "def parse_datetime(dt_str):\n    \"\"\"Parse datetime.\"\"\"\n    date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n    dt_str = dt_str.replace(\"Z\", \" +0000\")\n    return datetime.datetime.strptime(dt_str, date_format)", "title": ""}
{"_id": "d1444", "text": "def c_str(string):\n    \"\"\"\"Convert a python string to C string.\"\"\"\n    if not isinstance(string, str):\n        string = string.decode('ascii')\n    return ctypes.c_char_p(string.encode('utf-8'))", "title": ""}
{"_id": "d1445", "text": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "title": ""}
{"_id": "d1446", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d1447", "text": "def str2bytes(x):\n  \"\"\"Convert input argument to bytes\"\"\"\n  if type(x) is bytes:\n    return x\n  elif type(x) is str:\n    return bytes([ ord(i) for i in x ])\n  else:\n    return str2bytes(str(x))", "title": ""}
{"_id": "d1448", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d1449", "text": "def visit_Str(self, node):\n        \"\"\" Set the pythonic string type. \"\"\"\n        self.result[node] = self.builder.NamedType(pytype_to_ctype(str))", "title": ""}
{"_id": "d1450", "text": "def string_list_to_array(l):\n    \"\"\"\n    Turns a Python unicode string list into a Java String array.\n\n    :param l: the string list\n    :type: list\n    :rtype: java string array\n    :return: JB_Object\n    \"\"\"\n    result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class(\"java/lang/String\"))\n    for i in range(len(l)):\n        javabridge.get_env().set_object_array_element(result, i, javabridge.get_env().new_string_utf(l[i]))\n    return result", "title": ""}
{"_id": "d1451", "text": "def coerce(self, value):\n        \"\"\"Convert from whatever is given to a list of scalars for the lookup_field.\"\"\"\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]", "title": ""}
{"_id": "d1452", "text": "def drop_bad_characters(text):\n    \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n    also any whitespace characters that aren't space.\n\n    :arg str text: the text to fix\n\n    :returns: text with all bad characters dropped\n\n    \"\"\"\n    # Strip all non-ascii and non-printable characters\n    text = ''.join([c for c in text if c in ALLOWED_CHARS])\n    return text", "title": ""}
{"_id": "d1453", "text": "def removeFromRegistery(obj) :\n\t\"\"\"Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory\n\ttaken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects,\n\tcascades to free the registeries of related rabalists also\"\"\"\n\t\n\tif isRabaObject(obj) :\n\t\t_unregisterRabaObjectInstance(obj)\n\telif isRabaList(obj) :\n\t\t_unregisterRabaListInstance(obj)", "title": ""}
{"_id": "d1454", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d1455", "text": "def _unzip_handle(handle):\n    \"\"\"Transparently unzip the file handle\"\"\"\n    if isinstance(handle, basestring):\n        handle = _gzip_open_filename(handle)\n    else:\n        handle = _gzip_open_handle(handle)\n    return handle", "title": ""}
{"_id": "d1456", "text": "def fsliceafter(astr, sub):\n    \"\"\"Return the slice after at sub in string astr\"\"\"\n    findex = astr.find(sub)\n    return astr[findex + len(sub):]", "title": ""}
{"_id": "d1457", "text": "def _update_texttuple(self, x, y, s, cs, d):\n        \"\"\"Update the text tuple at `x` and `y` with the given `s` and `d`\"\"\"\n        pos = (x, y, cs)\n        for i, (old_x, old_y, old_s, old_cs, old_d) in enumerate(self.value):\n            if (old_x, old_y, old_cs) == pos:\n                self.value[i] = (old_x, old_y, s, old_cs, d)\n                return\n        raise ValueError(\"No text tuple found at {0}!\".format(pos))", "title": ""}
{"_id": "d1458", "text": "def authenticate(self, transport, account_name, password=None):\n        \"\"\"\n        Authenticates account using soap method.\n        \"\"\"\n        Authenticator.authenticate(self, transport, account_name, password)\n\n        if password == None:\n            return self.pre_auth(transport, account_name)\n        else:\n            return self.auth(transport, account_name, password)", "title": ""}
{"_id": "d1459", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d1460", "text": "def _wait_for_response(self):\n\t\t\"\"\"\n\t\tWait until the user accepted or rejected the request\n\t\t\"\"\"\n\t\twhile not self.server.response_code:\n\t\t\ttime.sleep(2)\n\t\ttime.sleep(5)\n\t\tself.server.shutdown()", "title": ""}
{"_id": "d1461", "text": "def copy_and_update(dictionary, update):\n    \"\"\"Returns an updated copy of the dictionary without modifying the original\"\"\"\n    newdict = dictionary.copy()\n    newdict.update(update)\n    return newdict", "title": ""}
{"_id": "d1462", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d1463", "text": "def _do_auto_predict(machine, X, *args):\n    \"\"\"Performs an automatic prediction for the specified machine and returns\n    the predicted values.\n    \"\"\"\n    if auto_predict and hasattr(machine, \"predict\"):\n        return machine.predict(X)", "title": ""}
{"_id": "d1464", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d1465", "text": "def to_pascal_case(s):\n    \"\"\"Transform underscore separated string to pascal case\n\n    \"\"\"\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())", "title": ""}
{"_id": "d1466", "text": "def row_to_dict(row):\n    \"\"\"Convert a table row to a dictionary.\"\"\"\n    o = {}\n    for colname in row.colnames:\n\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\n    return o", "title": ""}
{"_id": "d1467", "text": "def color_string(color, string):\n    \"\"\"\n    Colorizes a given string, if coloring is available.\n    \"\"\"\n    if not color_available:\n        return string\n\n    return color + string + colorama.Fore.RESET", "title": ""}
{"_id": "d1468", "text": "def execute(self, env, args):\n        \"\"\" Starts a new task.\n\n            `env`\n                Runtime ``Environment`` instance.\n            `args`\n                Arguments object from arg parser.\n            \"\"\"\n\n        # start the task\n        if env.task.start(args.task_name):\n            env.io.success(u'Task Loaded.')", "title": ""}
{"_id": "d1469", "text": "def get_stoplist(language):\n    \"\"\"Returns an built-in stop-list for the language as a set of words.\"\"\"\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\n    return frozenset(w.decode(\"utf8\").lower() for w in stopwords.splitlines())", "title": ""}
{"_id": "d1470", "text": "def create_tmpfile(self, content):\n        \"\"\" Utility method to create temp files. These are cleaned at the end of the test \"\"\"\n        # Not using a context manager to avoid unneccessary identation in test code\n        tmpfile, tmpfilepath = tempfile.mkstemp()\n        self.tmpfiles.append(tmpfilepath)\n        with os.fdopen(tmpfile, \"w\") as f:\n            f.write(content)\n        return tmpfilepath", "title": ""}
{"_id": "d1471", "text": "def aandb(a, b):\n    \"\"\"Return a matrix of logic comparison of A or B\"\"\"\n    return matrix(np.logical_and(a, b).astype('float'), a.size)", "title": ""}
{"_id": "d1472", "text": "def json_template(data, template_name, template_context):\n    \"\"\"Old style, use JSONTemplateResponse instead of this.\n    \"\"\"\n    html = render_to_string(template_name, template_context)\n    data = data or {}\n    data['html'] = html\n    return HttpResponse(json_encode(data), content_type='application/json')", "title": ""}
{"_id": "d1473", "text": "def find(self, *args, **kwargs):\n        \"\"\"Same as :meth:`pymongo.collection.Collection.find`, except\n        it returns the right document class.\n        \"\"\"\n        return Cursor(self, *args, wrap=self.document_class, **kwargs)", "title": ""}
{"_id": "d1474", "text": "def unfolding(tens, i):\n    \"\"\"Compute the i-th unfolding of a tensor.\"\"\"\n    return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1))", "title": ""}
{"_id": "d1475", "text": "def members(self, uid=\"*\", objects=False):\n        \"\"\" members() issues an ldap query for all users, and returns a dict\n            for each matching entry. This can be quite slow, and takes roughly\n            3s to complete. You may optionally restrict the scope by specifying\n            a uid, which is roughly equivalent to a search(uid='foo')\n        \"\"\"\n        entries = self.search(uid='*')\n        if objects:\n            return self.memberObjects(entries)\n        result = []\n        for entry in entries:\n            result.append(entry[1])\n        return result", "title": ""}
{"_id": "d1476", "text": "def flatten_all_but_last(a):\n  \"\"\"Flatten all dimensions of a except the last.\"\"\"\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", "title": ""}
{"_id": "d1477", "text": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "title": ""}
{"_id": "d1478", "text": "def afx_small():\n  \"\"\"Small transformer model with small batch size for fast step times.\"\"\"\n  hparams = transformer.transformer_tpu()\n  hparams.filter_size = 1024\n  hparams.num_heads = 4\n  hparams.num_hidden_layers = 3\n  hparams.batch_size = 512\n  return hparams", "title": ""}
{"_id": "d1479", "text": "def get_span_char_width(span, column_widths):\n    \"\"\"\n    Sum the widths of the columns that make up the span, plus the extra.\n\n    Parameters\n    ----------\n    span : list of lists of int\n        list of [row, column] pairs that make up the span\n    column_widths : list of int\n        The widths of the columns that make up the table\n\n    Returns\n    -------\n    total_width : int\n        The total width of the span\n    \"\"\"\n\n    start_column = span[0][1]\n    column_count = get_span_column_count(span)\n    total_width = 0\n\n    for i in range(start_column, start_column + column_count):\n        total_width += column_widths[i]\n\n    total_width += column_count - 1\n\n    return total_width", "title": ""}
{"_id": "d1480", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d1481", "text": "def sort_genomic_ranges(rngs):\n  \"\"\"sort multiple ranges\"\"\"\n  return sorted(rngs, key=lambda x: (x.chr, x.start, x.end))", "title": ""}
{"_id": "d1482", "text": "def is_square_matrix(mat):\n    \"\"\"Test if an array is a square matrix.\"\"\"\n    mat = np.array(mat)\n    if mat.ndim != 2:\n        return False\n    shape = mat.shape\n    return shape[0] == shape[1]", "title": ""}
{"_id": "d1483", "text": "def save_session(self, sid, session, namespace=None):\n        \"\"\"Store the user session for a client.\n\n        The only difference with the :func:`socketio.Server.save_session`\n        method is that when the ``namespace`` argument is not given the\n        namespace associated with the class is used.\n        \"\"\"\n        return self.server.save_session(\n            sid, session, namespace=namespace or self.namespace)", "title": ""}
{"_id": "d1484", "text": "def is_connected(self):\n        \"\"\"\n        Return true if the socket managed by this connection is connected\n\n        :rtype: bool\n        \"\"\"\n        try:\n            return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)\n        except socket.error:\n            return False", "title": ""}
{"_id": "d1485", "text": "def show(config):\n    \"\"\"Show revision list\"\"\"\n    with open(config, 'r'):\n        main.show(yaml.load(open(config)))", "title": ""}
{"_id": "d1486", "text": "def txt_line_iterator(path):\n  \"\"\"Iterate through lines of file.\"\"\"\n  with tf.gfile.Open(path) as f:\n    for line in f:\n      yield line.strip()", "title": ""}
{"_id": "d1487", "text": "def _validate_type_scalar(self, value):\n        \"\"\" Is not a list or a dict \"\"\"\n        if isinstance(\n            value, _int_types + (_str_type, float, date, datetime, bool)\n        ):\n            return True", "title": ""}
{"_id": "d1488", "text": "def encode_dataset(dataset, vocabulary):\n  \"\"\"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\n  \"\"\"\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)", "title": ""}
{"_id": "d1489", "text": "def generate_write_yaml_to_file(file_name):\n    \"\"\" generate a method to write the configuration in yaml to the method desired \"\"\"\n    def write_yaml(config):\n        with open(file_name, 'w+') as fh:\n            fh.write(yaml.dump(config))\n    return write_yaml", "title": ""}
{"_id": "d1490", "text": "def Stop(self):\n    \"\"\"Stops the process status RPC server.\"\"\"\n    self._Close()\n\n    if self._rpc_thread.isAlive():\n      self._rpc_thread.join()\n    self._rpc_thread = None", "title": ""}
{"_id": "d1491", "text": "def is_valid_ipv6(ip_str):\n    \"\"\"\n    Check the validity of an IPv6 address\n    \"\"\"\n    try:\n        socket.inet_pton(socket.AF_INET6, ip_str)\n    except socket.error:\n        return False\n    return True", "title": ""}
{"_id": "d1492", "text": "def flush():\n    \"\"\"Try to flush all stdio buffers, both from python and from C.\"\"\"\n    try:\n        sys.stdout.flush()\n        sys.stderr.flush()\n    except (AttributeError, ValueError, IOError):\n        pass  # unsupported\n    try:\n        libc.fflush(None)\n    except (AttributeError, ValueError, IOError):\n        pass", "title": ""}
{"_id": "d1493", "text": "def get_list_representation(self):\n        \"\"\"Returns this subset's representation as a list of indices.\"\"\"\n        if self.is_list:\n            return self.list_or_slice\n        else:\n            return self[list(range(self.num_examples))]", "title": ""}
{"_id": "d1494", "text": "def terminate(self):\n        \"\"\"Terminate all workers and threads.\"\"\"\n        for t in self._threads:\n            t.quit()\n        self._thread = []\n        self._workers = []", "title": ""}
{"_id": "d1495", "text": "def post_process(self):\n        \"\"\" Apply last 2D transforms\"\"\"\n        self.image.putdata(self.pixels)\n        self.image = self.image.transpose(Image.ROTATE_90)", "title": ""}
{"_id": "d1496", "text": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "title": ""}
{"_id": "d1497", "text": "def write_tsv_line_from_list(linelist, outfp):\n    \"\"\"Utility method to convert list to tsv line with carriage return\"\"\"\n    line = '\\t'.join(linelist)\n    outfp.write(line)\n    outfp.write('\\n')", "title": ""}
{"_id": "d1498", "text": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "title": ""}
{"_id": "d1499", "text": "def _make_sentence(txt):\n    \"\"\"Make a sentence from a piece of text.\"\"\"\n    #Make sure first letter is capitalized\n    txt = txt.strip(' ')\n    txt = txt[0].upper() + txt[1:] + '.'\n    return txt", "title": ""}
{"_id": "d1500", "text": "def asyncStarCmap(asyncCallable, iterable):\n    \"\"\"itertools.starmap for deferred callables using cooperative multitasking\n    \"\"\"\n    results = []\n    yield coopStar(asyncCallable, results.append, iterable)\n    returnValue(results)", "title": ""}
{"_id": "d1501", "text": "def write_wav(path, samples, sr=16000):\n    \"\"\"\n    Write to given samples to a wav file.\n    The samples are expected to be floating point numbers\n    in the range of -1.0 to 1.0.\n\n    Args:\n        path (str): The path to write the wav to.\n        samples (np.array): A float array .\n        sr (int): The sampling rate.\n    \"\"\"\n    max_value = np.abs(np.iinfo(np.int16).min)\n    data = (samples * max_value).astype(np.int16)\n    scipy.io.wavfile.write(path, sr, data)", "title": ""}
{"_id": "d1502", "text": "def make_directory(path):\n    \"\"\"\n    Make a directory and any intermediate directories that don't already\n    exist. This function handles the case where two threads try to create\n    a directory at once.\n    \"\"\"\n    if not os.path.exists(path):\n        # concurrent writes that try to create the same dir can fail\n        try:\n            os.makedirs(path)\n\n        except OSError as e:\n            if e.errno == errno.EEXIST:\n                pass\n            else:\n                raise e", "title": ""}
{"_id": "d1503", "text": "def csv_matrix_print(classes, table):\n    \"\"\"\n    Return matrix as csv data.\n\n    :param classes: classes list\n    :type classes:list\n    :param table: table\n    :type table:dict\n    :return:\n    \"\"\"\n    result = \"\"\n    classes.sort()\n    for i in classes:\n        for j in classes:\n            result += str(table[i][j]) + \",\"\n        result = result[:-1] + \"\\n\"\n    return result[:-1]", "title": ""}
{"_id": "d1504", "text": "def quaternion_to_rotation_matrix(quaternion):\n    \"\"\"Compute the rotation matrix representated by the quaternion\"\"\"\n    c, x, y, z = quaternion\n    return np.array([\n        [c*c + x*x - y*y - z*z, 2*x*y - 2*c*z,         2*x*z + 2*c*y        ],\n        [2*x*y + 2*c*z,         c*c - x*x + y*y - z*z, 2*y*z - 2*c*x        ],\n        [2*x*z - 2*c*y,         2*y*z + 2*c*x,         c*c - x*x - y*y + z*z]\n    ], float)", "title": ""}
{"_id": "d1505", "text": "def write_file(filename, content):\n    \"\"\"Create the file with the given content\"\"\"\n    print 'Generating {0}'.format(filename)\n    with open(filename, 'wb') as out_f:\n        out_f.write(content)", "title": ""}
{"_id": "d1506", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d1507", "text": "def retry_test(func):\n    \"\"\"Retries the passed function 3 times before failing\"\"\"\n    success = False\n    ex = Exception(\"Unknown\")\n    for i in six.moves.range(3):\n        try:\n            result = func()\n        except Exception as e:\n            time.sleep(1)\n            ex = e\n        else:\n            success = True\n            break\n    if not success:\n        raise ex\n    assert success\n    return result", "title": ""}
{"_id": "d1508", "text": "def session_to_epoch(timestamp):\n    \"\"\" converts Synergy Timestamp for session to UTC zone seconds since epoch \"\"\"\n    utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()\n    return calendar.timegm(utc_timetuple)", "title": ""}
{"_id": "d1509", "text": "def get_own_ip():\n    \"\"\"Get the host's ip number.\n    \"\"\"\n    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    try:\n        sock.connect((\"8.8.8.8\", 80))\n    except socket.gaierror:\n        ip_ = \"127.0.0.1\"\n    else:\n        ip_ = sock.getsockname()[0]\n    finally:\n        sock.close()\n    return ip_", "title": ""}
{"_id": "d1510", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d1511", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d1512", "text": "def timestamp_to_datetime(timestamp):\n    \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n    from datetime import datetime, timedelta\n    obj = datetime.fromtimestamp(timestamp[0])\n    return obj + timedelta(microseconds=int(timestamp[1]))", "title": ""}
{"_id": "d1513", "text": "def str2bytes(x):\n  \"\"\"Convert input argument to bytes\"\"\"\n  if type(x) is bytes:\n    return x\n  elif type(x) is str:\n    return bytes([ ord(i) for i in x ])\n  else:\n    return str2bytes(str(x))", "title": ""}
{"_id": "d1514", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d1515", "text": "def html(header_rows):\n    \"\"\"\n    Convert a list of tuples describing a table into a HTML string\n    \"\"\"\n    name = 'table%d' % next(tablecounter)\n    return HtmlTable([map(str, row) for row in header_rows], name).render()", "title": ""}
{"_id": "d1516", "text": "def yview(self, *args):\n        \"\"\"Update inplace widgets position when doing vertical scroll\"\"\"\n        self.after_idle(self.__updateWnds)\n        ttk.Treeview.yview(self, *args)", "title": ""}
{"_id": "d1517", "text": "def is_gzipped_fastq(file_name):\n    \"\"\"\n    Determine whether indicated file appears to be a gzipped FASTQ.\n\n    :param str file_name: Name/path of file to check as gzipped FASTQ.\n    :return bool: Whether indicated file appears to be in gzipped FASTQ format.\n    \"\"\"\n    _, ext = os.path.splitext(file_name)\n    return file_name.endswith(\".fastq.gz\") or file_name.endswith(\".fq.gz\")", "title": ""}
{"_id": "d1518", "text": "def restore_scrollbar_position(self):\n        \"\"\"Restoring scrollbar position after main window is visible\"\"\"\n        scrollbar_pos = self.get_option('scrollbar_position', None)\n        if scrollbar_pos is not None:\n            self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)", "title": ""}
{"_id": "d1519", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d1520", "text": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d1521", "text": "def full(self):\n        \"\"\"Return True if the queue is full\"\"\"\n        if not self.size: return False\n        return len(self.pq) == (self.size + self.removed_count)", "title": ""}
{"_id": "d1522", "text": "def get_pg_connection(host, user, port, password, database, ssl={}):\n    \"\"\" PostgreSQL connection \"\"\"\n\n    return psycopg2.connect(host=host,\n                            user=user,\n                            port=port,\n                            password=password,\n                            dbname=database,\n                            sslmode=ssl.get('sslmode', None),\n                            sslcert=ssl.get('sslcert', None),\n                            sslkey=ssl.get('sslkey', None),\n                            sslrootcert=ssl.get('sslrootcert', None),\n                            )", "title": ""}
{"_id": "d1523", "text": "def defvalkey(js, key, default=None, take_none=True):\n    \"\"\"\n    Returns js[key] if set, otherwise default. Note js[key] can be None.\n    :param js:\n    :param key:\n    :param default:\n    :param take_none:\n    :return:\n    \"\"\"\n    if js is None:\n        return default\n    if key not in js:\n        return default\n    if js[key] is None and not take_none:\n        return default\n    return js[key]", "title": ""}
{"_id": "d1524", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d1525", "text": "def resize_image_to_fit_width(image, dest_w):\n    \"\"\"\n    Resize and image to fit the passed in width, keeping the aspect ratio the same\n\n    :param image: PIL.Image\n    :param dest_w: The desired width\n    \"\"\"\n    scale_factor = dest_w / image.size[0]\n    dest_h = image.size[1] * scale_factor\n    \n    scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)\n\n    return scaled_image", "title": ""}
{"_id": "d1526", "text": "def list(self):\n        \"\"\"position in 3d space\"\"\"\n        return [self._pos3d.x, self._pos3d.y, self._pos3d.z]", "title": ""}
{"_id": "d1527", "text": "def yn_prompt(msg, default=True):\n    \"\"\"\n    Prompts the user for yes or no.\n    \"\"\"\n    ret = custom_prompt(msg, [\"y\", \"n\"], \"y\" if default else \"n\")\n    if ret == \"y\":\n        return True\n    return False", "title": ""}
{"_id": "d1528", "text": "def GetAttributeNs(self, localName, namespaceURI):\n        \"\"\"Provides the value of the specified attribute \"\"\"\n        ret = libxml2mod.xmlTextReaderGetAttributeNs(self._o, localName, namespaceURI)\n        return ret", "title": ""}
{"_id": "d1529", "text": "def find_geom(geom, geoms):\n    \"\"\"\n    Returns the index of a geometry in a list of geometries avoiding\n    expensive equality checks of `in` operator.\n    \"\"\"\n    for i, g in enumerate(geoms):\n        if g is geom:\n            return i", "title": ""}
{"_id": "d1530", "text": "def _using_stdout(self):\n        \"\"\"\n        Return whether the handler is using sys.stdout.\n        \"\"\"\n        if WINDOWS and colorama:\n            # Then self.stream is an AnsiToWin32 object.\n            return self.stream.wrapped is sys.stdout\n\n        return self.stream is sys.stdout", "title": ""}
{"_id": "d1531", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d1532", "text": "def file_found(filename,force):\n    \"\"\"Check if a file exists\"\"\"\n    if os.path.exists(filename) and not force:\n        logger.info(\"Found %s; skipping...\"%filename)\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d1533", "text": "def _linearInterpolationTransformMatrix(matrix1, matrix2, value):\n    \"\"\" Linear, 'oldstyle' interpolation of the transform matrix.\"\"\"\n    return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))", "title": ""}
{"_id": "d1534", "text": "def is_unix_style(flags):\n    \"\"\"Check if we should use Unix style.\"\"\"\n\n    return (util.platform() != \"windows\" or (not bool(flags & REALPATH) and get_case(flags))) and not flags & _FORCEWIN", "title": ""}
{"_id": "d1535", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d1536", "text": "def start(args):\n    \"\"\"Run server with provided command line arguments.\n    \"\"\"\n    application = tornado.web.Application([(r\"/run\", run.get_handler(args)),\n                                           (r\"/status\", run.StatusHandler)])\n    application.runmonitor = RunMonitor()\n    application.listen(args.port)\n    tornado.ioloop.IOLoop.instance().start()", "title": ""}
{"_id": "d1537", "text": "def generic_div(a, b):\n    \"\"\"Simple function to divide two numbers\"\"\"\n    logger.debug('Called generic_div({}, {})'.format(a, b))\n    return a / b", "title": ""}
{"_id": "d1538", "text": "def scipy_sparse_to_spmatrix(A):\n    \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP", "title": ""}
{"_id": "d1539", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d1540", "text": "def _frombuffer(ptr, frames, channels, dtype):\n    \"\"\"Create NumPy array from a pointer to some memory.\"\"\"\n    framesize = channels * dtype.itemsize\n    data = np.frombuffer(ffi.buffer(ptr, frames * framesize), dtype=dtype)\n    data.shape = -1, channels\n    return data", "title": ""}
{"_id": "d1541", "text": "def _single_page_pdf(page):\n    \"\"\"Construct a single page PDF from the provided page in memory\"\"\"\n    pdf = Pdf.new()\n    pdf.pages.append(page)\n    bio = BytesIO()\n    pdf.save(bio)\n    bio.seek(0)\n    return bio.read()", "title": ""}
{"_id": "d1542", "text": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "title": ""}
{"_id": "d1543", "text": "def query_fetch_one(self, query, values):\n        \"\"\"\n        Executes a db query, gets the first value, and closes the connection.\n        \"\"\"\n        self.cursor.execute(query, values)\n        retval = self.cursor.fetchone()\n        self.__close_db()\n        return retval", "title": ""}
{"_id": "d1544", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d1545", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d1546", "text": "def strip_spaces(x):\n    \"\"\"\n    Strips spaces\n    :param x:\n    :return:\n    \"\"\"\n    x = x.replace(b' ', b'')\n    x = x.replace(b'\\t', b'')\n    return x", "title": ""}
{"_id": "d1547", "text": "def __consistent_isoformat_utc(datetime_val):\n        \"\"\"\n        Function that does what isoformat does but it actually does the same\n        every time instead of randomly doing different things on some systems\n        and also it represents that time as the equivalent UTC time.\n        \"\"\"\n        isotime = datetime_val.astimezone(pytz.utc).strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n        if isotime[-2] != \":\":\n            isotime = isotime[:-2] + \":\" + isotime[-2:]\n        return isotime", "title": ""}
{"_id": "d1548", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d1549", "text": "def __iter__(self):\n\t\t\"\"\"Iterate through all elements.\n\n\t\tMultiple copies will be returned if they exist.\n\t\t\"\"\"\n\t\tfor value, count in self.counts():\n\t\t\tfor _ in range(count):\n\t\t\t\tyield value", "title": ""}
{"_id": "d1550", "text": "def eintr_retry(exc_type, f, *args, **kwargs):\n    \"\"\"Calls a function.  If an error of the given exception type with\n    interrupted system call (EINTR) occurs calls the function again.\n    \"\"\"\n    while True:\n        try:\n            return f(*args, **kwargs)\n        except exc_type as exc:\n            if exc.errno != EINTR:\n                raise\n        else:\n            break", "title": ""}
{"_id": "d1551", "text": "def txt_line_iterator(path):\n  \"\"\"Iterate through lines of file.\"\"\"\n  with tf.gfile.Open(path) as f:\n    for line in f:\n      yield line.strip()", "title": ""}
{"_id": "d1552", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d1553", "text": "def itervalues(d, **kw):\n    \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n    if not PY2:\n        return iter(d.values(**kw))\n    return d.itervalues(**kw)", "title": ""}
{"_id": "d1554", "text": "def norm_slash(name):\n    \"\"\"Normalize path slashes.\"\"\"\n\n    if isinstance(name, str):\n        return name.replace('/', \"\\\\\") if not is_case_sensitive() else name\n    else:\n        return name.replace(b'/', b\"\\\\\") if not is_case_sensitive() else name", "title": ""}
{"_id": "d1555", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d1556", "text": "def Proxy(f):\n  \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n\n  return Wrapped", "title": ""}
{"_id": "d1557", "text": "def string_list_to_array(l):\n    \"\"\"\n    Turns a Python unicode string list into a Java String array.\n\n    :param l: the string list\n    :type: list\n    :rtype: java string array\n    :return: JB_Object\n    \"\"\"\n    result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class(\"java/lang/String\"))\n    for i in range(len(l)):\n        javabridge.get_env().set_object_array_element(result, i, javabridge.get_env().new_string_utf(l[i]))\n    return result", "title": ""}
{"_id": "d1558", "text": "def intToBin(i):\n    \"\"\" Integer to two bytes \"\"\"\n    # divide in two parts (bytes)\n    i1 = i % 256\n    i2 = int(i / 256)\n    # make string (little endian)\n    return i.to_bytes(2, byteorder='little')", "title": ""}
{"_id": "d1559", "text": "def get_java_path():\n  \"\"\"Get the path of java executable\"\"\"\n  java_home = os.environ.get(\"JAVA_HOME\")\n  return os.path.join(java_home, BIN_DIR, \"java\")", "title": ""}
{"_id": "d1560", "text": "def excel_key(index):\n    \"\"\"create a key for index by converting index into a base-26 number, using A-Z as the characters.\"\"\"\n    X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''\n    return X(int(index))", "title": ""}
{"_id": "d1561", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d1562", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d1563", "text": "def get_attributes(var):\n    \"\"\"\n    Given a varaible, return the list of attributes that are available inside\n    of a template\n    \"\"\"\n    is_valid = partial(is_valid_in_template, var)\n    return list(filter(is_valid, dir(var)))", "title": ""}
{"_id": "d1564", "text": "def _sim_fill(r1, r2, imsize):\n    \"\"\"\n        calculate the fill similarity over the image\n    \"\"\"\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", "title": ""}
{"_id": "d1565", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d1566", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d1567", "text": "def _timestamp_to_json_row(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\n\n    This version returns floating-point seconds value used in row data.\n    \"\"\"\n    if isinstance(value, datetime.datetime):\n        value = _microseconds_from_datetime(value) * 1e-6\n    return value", "title": ""}
{"_id": "d1568", "text": "def istype(obj, check):\n    \"\"\"Like isinstance(obj, check), but strict.\n\n    This won't catch subclasses.\n    \"\"\"\n    if isinstance(check, tuple):\n        for cls in check:\n            if type(obj) is cls:\n                return True\n        return False\n    else:\n        return type(obj) is check", "title": ""}
{"_id": "d1569", "text": "def parse_json_date(value):\n    \"\"\"\n    Parses an ISO8601 formatted datetime from a string value\n    \"\"\"\n    if not value:\n        return None\n\n    return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)", "title": ""}
{"_id": "d1570", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d1571", "text": "def read_json(location):\n    \"\"\"Open and load JSON from file.\n\n    location (Path): Path to JSON file.\n    RETURNS (dict): Loaded JSON content.\n    \"\"\"\n    location = ensure_path(location)\n    with location.open('r', encoding='utf8') as f:\n        return ujson.load(f)", "title": ""}
{"_id": "d1572", "text": "def check_str(obj):\n        \"\"\" Returns a string for various input types \"\"\"\n        if isinstance(obj, str):\n            return obj\n        if isinstance(obj, float):\n            return str(int(obj))\n        else:\n            return str(obj)", "title": ""}
{"_id": "d1573", "text": "def json_serialize(obj):\n    \"\"\"\n    Simple generic JSON serializer for common objects.\n    \"\"\"\n    if isinstance(obj, datetime):\n        return obj.isoformat()\n\n    if hasattr(obj, 'id'):\n        return jsonify(obj.id)\n\n    if hasattr(obj, 'name'):\n        return jsonify(obj.name)\n\n    raise TypeError('{0} is not JSON serializable'.format(obj))", "title": ""}
{"_id": "d1574", "text": "def to_pascal_case(s):\n    \"\"\"Transform underscore separated string to pascal case\n\n    \"\"\"\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())", "title": ""}
{"_id": "d1575", "text": "def load_schema(schema_path):\n    \"\"\"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\n    \"\"\"\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)", "title": ""}
{"_id": "d1576", "text": "def __init__(self, testnet=False, dryrun=False):\n        \"\"\"TODO doc string\"\"\"\n        self.testnet = testnet\n        self.dryrun = dryrun", "title": ""}
{"_id": "d1577", "text": "def unique(iterable):\n    \"\"\" Returns a list copy in which each item occurs only once (in-order).\n    \"\"\"\n    seen = set()\n    return [x for x in iterable if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d1578", "text": "def test():\n    \"\"\" Run all Tests [nose] \"\"\"\n\n    command = 'nosetests --with-coverage --cover-package=pwnurl'\n    status = subprocess.call(shlex.split(command))\n    sys.exit(status)", "title": ""}
{"_id": "d1579", "text": "def kill_process_children(pid):\n    \"\"\"Find and kill child processes of a process.\n\n    :param pid: PID of parent process (process ID)\n    :return: Nothing\n    \"\"\"\n    if sys.platform == \"darwin\":\n        kill_process_children_osx(pid)\n    elif sys.platform == \"linux\":\n        kill_process_children_unix(pid)\n    else:\n        pass", "title": ""}
{"_id": "d1580", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d1581", "text": "def sigterm(self, signum, frame):\n        \"\"\"\n        These actions will be done after SIGTERM.\n        \"\"\"\n        self.logger.warning(\"Caught signal %s. Stopping daemon.\" % signum)\n        sys.exit(0)", "title": ""}
{"_id": "d1582", "text": "def guess_url(url):\n    \"\"\"Guess if URL is a http or ftp URL.\n    @param url: the URL to check\n    @ptype url: unicode\n    @return: url with http:// or ftp:// prepended if it's detected as\n      a http respective ftp URL.\n    @rtype: unicode\n    \"\"\"\n    if url.lower().startswith(\"www.\"):\n        # syntactic sugar\n        return \"http://%s\" % url\n    elif url.lower().startswith(\"ftp.\"):\n        # syntactic sugar\n        return \"ftp://%s\" % url\n    return url", "title": ""}
{"_id": "d1583", "text": "def normalize(v, axis=None, eps=1e-10):\n  \"\"\"L2 Normalize along specified axes.\"\"\"\n  return v / max(anorm(v, axis=axis, keepdims=True), eps)", "title": ""}
{"_id": "d1584", "text": "def _unzip_handle(handle):\n    \"\"\"Transparently unzip the file handle\"\"\"\n    if isinstance(handle, basestring):\n        handle = _gzip_open_filename(handle)\n    else:\n        handle = _gzip_open_handle(handle)\n    return handle", "title": ""}
{"_id": "d1585", "text": "def finish_plot():\n    \"\"\"Helper for plotting.\"\"\"\n    plt.legend()\n    plt.grid(color='0.7')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.show()", "title": ""}
{"_id": "d1586", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d1587", "text": "def visit_BoolOp(self, node):\n        \"\"\" Return type may come from any boolop operand. \"\"\"\n        return sum((self.visit(value) for value in node.values), [])", "title": ""}
{"_id": "d1588", "text": "def download(url, encoding='utf-8'):\n    \"\"\"Returns the text fetched via http GET from URL, read as `encoding`\"\"\"\n    import requests\n    response = requests.get(url)\n    response.encoding = encoding\n    return response.text", "title": ""}
{"_id": "d1589", "text": "def s3(ctx, bucket_name, data_file, region):\n    \"\"\"Use the S3 SWAG backend.\"\"\"\n    if not ctx.data_file:\n        ctx.data_file = data_file\n\n    if not ctx.bucket_name:\n        ctx.bucket_name = bucket_name\n\n    if not ctx.region:\n        ctx.region = region\n\n    ctx.type = 's3'", "title": ""}
{"_id": "d1590", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d1591", "text": "def afx_small():\n  \"\"\"Small transformer model with small batch size for fast step times.\"\"\"\n  hparams = transformer.transformer_tpu()\n  hparams.filter_size = 1024\n  hparams.num_heads = 4\n  hparams.num_hidden_layers = 3\n  hparams.batch_size = 512\n  return hparams", "title": ""}
{"_id": "d1592", "text": "def is_safe_url(url, host=None):\n    \"\"\"Return ``True`` if the url is a safe redirection.\n\n    The safe redirection means that it doesn't point to a different host.\n    Always returns ``False`` on an empty url.\n    \"\"\"\n    if not url:\n        return False\n    netloc = urlparse.urlparse(url)[1]\n    return not netloc or netloc == host", "title": ""}
{"_id": "d1593", "text": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n    \"\"\"\n    Returns the last `n` rows in the table\n    \"\"\"\n    return fetch(dbconn, tablename, n, uuid, end=True)", "title": ""}
{"_id": "d1594", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d1595", "text": "def tail(self, n=10):\n        \"\"\"\n        Get an SArray that contains the last n elements in the SArray.\n\n        Parameters\n        ----------\n        n : int\n            The number of elements to fetch\n\n        Returns\n        -------\n        out : SArray\n            A new SArray which contains the last n rows of the current SArray.\n        \"\"\"\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.tail(n))", "title": ""}
{"_id": "d1596", "text": "def get_url_args(url):\n    \"\"\" Returns a dictionary from a URL params \"\"\"\n    url_data = urllib.parse.urlparse(url)\n    arg_dict = urllib.parse.parse_qs(url_data.query)\n    return arg_dict", "title": ""}
{"_id": "d1597", "text": "def print_latex(o):\n    \"\"\"A function to generate the latex representation of sympy\n    expressions.\"\"\"\n    if can_print_latex(o):\n        s = latex(o, mode='plain')\n        s = s.replace('\\\\dag','\\\\dagger')\n        s = s.strip('$')\n        return '$$%s$$' % s\n    # Fallback to the string printer\n    return None", "title": ""}
{"_id": "d1598", "text": "def colorbar(height, length, colormap):\n    \"\"\"Return the channels of a colorbar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.colorize(cbar)", "title": ""}
{"_id": "d1599", "text": "def set_empty(self, row, column):\n        \"\"\"Keep one of the subplots completely empty.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_empty()", "title": ""}
{"_id": "d1600", "text": "def fromDict(cls, _dict):\n        \"\"\" Builds instance from dictionary of properties. \"\"\"\n        obj = cls()\n        obj.__dict__.update(_dict)\n        return obj", "title": ""}
{"_id": "d1601", "text": "def _requiredSize(shape, dtype):\n\t\"\"\"\n\tDetermines the number of bytes required to store a NumPy array with\n\tthe specified shape and datatype.\n\t\"\"\"\n\treturn math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)", "title": ""}
{"_id": "d1602", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d1603", "text": "def normalized(vector):\n    \"\"\"\n    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.\n    \"\"\"\n    length = numpy.sum(vector * vector, axis=-1)\n    length = numpy.sqrt(length.reshape(length.shape + (1, )))\n    return vector / length", "title": ""}
{"_id": "d1604", "text": "def static_method(cls, f):\n        \"\"\"Decorator which dynamically binds static methods to the model for later use.\"\"\"\n        setattr(cls, f.__name__, staticmethod(f))\n        return f", "title": ""}
{"_id": "d1605", "text": "def align_to_mmap(num, round_up):\n    \"\"\"\n    Align the given integer number to the closest page offset, which usually is 4096 bytes.\n\n    :param round_up: if True, the next higher multiple of page size is used, otherwise\n        the lower page_size will be used (i.e. if True, 1 becomes 4096, otherwise it becomes 0)\n    :return: num rounded to closest page\"\"\"\n    res = (num // ALLOCATIONGRANULARITY) * ALLOCATIONGRANULARITY\n    if round_up and (res != num):\n        res += ALLOCATIONGRANULARITY\n    # END handle size\n    return res", "title": ""}
{"_id": "d1606", "text": "def set(self, f):\n        \"\"\"Call a function after a delay, unless another function is set\n        in the meantime.\"\"\"\n        self.stop()\n        self._create_timer(f)\n        self.start()", "title": ""}
{"_id": "d1607", "text": "def close(self):\n\t\t\"\"\"\n\t\tSend a terminate request and then disconnect from the serial device.\n\t\t\"\"\"\n\t\tif self._initialized:\n\t\t\tself.stop()\n\t\tself.logged_in = False\n\t\treturn self.serial_h.close()", "title": ""}
{"_id": "d1608", "text": "def test():\n    \"\"\"Interactive test run.\"\"\"\n    try:\n        while 1:\n            x, digs = input('Enter (x, digs): ')\n            print x, fix(x, digs), sci(x, digs)\n    except (EOFError, KeyboardInterrupt):\n        pass", "title": ""}
{"_id": "d1609", "text": "def dict_from_object(obj: object):\n    \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n    # If object is a dict instance, no need to convert.\n    return (obj if isinstance(obj, dict)\n            else {attr: getattr(obj, attr)\n                  for attr in dir(obj) if not attr.startswith('_')})", "title": ""}
{"_id": "d1610", "text": "def _normal_prompt(self):\n        \"\"\"\n        Flushes the prompt before requesting the input\n\n        :return: The command line\n        \"\"\"\n        sys.stdout.write(self.__get_ps1())\n        sys.stdout.flush()\n        return safe_input()", "title": ""}
{"_id": "d1611", "text": "def get_flat_size(self):\n        \"\"\"Returns the total length of all of the flattened variables.\n\n        Returns:\n            The length of all flattened variables concatenated.\n        \"\"\"\n        return sum(\n            np.prod(v.get_shape().as_list()) for v in self.variables.values())", "title": ""}
{"_id": "d1612", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d1613", "text": "def get_methods(*objs):\n    \"\"\" Return the names of all callable attributes of an object\"\"\"\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    )", "title": ""}
{"_id": "d1614", "text": "def b2u(string):\n    \"\"\" bytes to unicode \"\"\"\n    if (isinstance(string, bytes) or\n        (PY2 and isinstance(string, str))):\n        return string.decode('utf-8')\n    return string", "title": ""}
{"_id": "d1615", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d1616", "text": "def validate_int(value):\n    \"\"\" Integer validator \"\"\"\n\n    if value and not isinstance(value, int):\n        try:\n            int(str(value))\n        except (TypeError, ValueError):\n            raise ValidationError('not a valid number')\n    return value", "title": ""}
{"_id": "d1617", "text": "def list2dict(list_of_options):\n    \"\"\"Transforms a list of 2 element tuples to a dictionary\"\"\"\n    d = {}\n    for key, value in list_of_options:\n        d[key] = value\n    return d", "title": ""}
{"_id": "d1618", "text": "def is_valid_ipv6(ip_str):\n    \"\"\"\n    Check the validity of an IPv6 address\n    \"\"\"\n    try:\n        socket.inet_pton(socket.AF_INET6, ip_str)\n    except socket.error:\n        return False\n    return True", "title": ""}
{"_id": "d1619", "text": "def _values(self):\n        \"\"\"Getter for series values (flattened)\"\"\"\n        return [\n            val for serie in self.series for val in serie.values\n            if val is not None\n        ]", "title": ""}
{"_id": "d1620", "text": "def check_X_y(X, y):\n    \"\"\"\n    tool to ensure input and output data have the same number of samples\n\n    Parameters\n    ----------\n    X : array-like\n    y : array-like\n\n    Returns\n    -------\n    None\n    \"\"\"\n    if len(X) != len(y):\n        raise ValueError('Inconsistent input and output data shapes. '\\\n                         'found X: {} and y: {}'.format(X.shape, y.shape))", "title": ""}
{"_id": "d1621", "text": "def open_json(file_name):\n    \"\"\"\n    returns json contents as string\n    \"\"\"\n    with open(file_name, \"r\") as json_data:\n        data = json.load(json_data)\n        return data", "title": ""}
{"_id": "d1622", "text": "def AsPrimitiveProto(self):\n    \"\"\"Return an old style protocol buffer object.\"\"\"\n    if self.protobuf:\n      result = self.protobuf()\n      result.ParseFromString(self.SerializeToString())\n      return result", "title": ""}
{"_id": "d1623", "text": "def sav_to_pandas_rpy2(input_file):\n    \"\"\"\n    SPSS .sav files to Pandas DataFrame through Rpy2\n\n    :param input_file: string\n\n    :return:\n    \"\"\"\n    import pandas.rpy.common as com\n\n    w = com.robj.r('foreign::read.spss(\"%s\", to.data.frame=TRUE)' % input_file)\n    return com.convert_robj(w)", "title": ""}
{"_id": "d1624", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d1625", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d1626", "text": "def iter_except_top_row_tcs(self):\n        \"\"\"Generate each `a:tc` element in non-first rows of range.\"\"\"\n        for tr in self._tbl.tr_lst[self._top + 1:self._bottom]:\n            for tc in tr.tc_lst[self._left:self._right]:\n                yield tc", "title": ""}
{"_id": "d1627", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d1628", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d1629", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d1630", "text": "def get_type(self):\n        \"\"\"Get the type of the item.\n\n        :return: the type of the item.\n        :returntype: `unicode`\"\"\"\n        item_type = self.xmlnode.prop(\"type\")\n        if not item_type:\n            item_type = \"?\"\n        return item_type.decode(\"utf-8\")", "title": ""}
{"_id": "d1631", "text": "def _is_osx_107():\n    \"\"\"\n    :return:\n        A bool if the current machine is running OS X 10.7\n    \"\"\"\n\n    if sys.platform != 'darwin':\n        return False\n    version = platform.mac_ver()[0]\n    return tuple(map(int, version.split('.')))[0:2] == (10, 7)", "title": ""}
{"_id": "d1632", "text": "def close_other_windows(self):\n        \"\"\"\n        Closes all not current windows. Useful for tests - after each test you\n        can automatically close all windows.\n        \"\"\"\n        main_window_handle = self.current_window_handle\n        for window_handle in self.window_handles:\n            if window_handle == main_window_handle:\n                continue\n            self.switch_to_window(window_handle)\n            self.close()\n        self.switch_to_window(main_window_handle)", "title": ""}
{"_id": "d1633", "text": "def magnitude(X):\n    \"\"\"Magnitude of a complex matrix.\"\"\"\n    r = np.real(X)\n    i = np.imag(X)\n    return np.sqrt(r * r + i * i);", "title": ""}
{"_id": "d1634", "text": "def swap_memory():\n    \"\"\"Swap system memory as a (total, used, free, sin, sout) tuple.\"\"\"\n    mem = _psutil_mswindows.get_virtual_mem()\n    total = mem[2]\n    free = mem[3]\n    used = total - free\n    percent = usage_percent(used, total, _round=1)\n    return nt_swapmeminfo(total, used, free, percent, 0, 0)", "title": ""}
{"_id": "d1635", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d1636", "text": "def from_pb(cls, pb):\n        \"\"\"Instantiate the object from a protocol buffer.\n\n        Args:\n            pb (protobuf)\n\n        Save a reference to the protocol buffer on the object.\n        \"\"\"\n        obj = cls._from_pb(pb)\n        obj._pb = pb\n        return obj", "title": ""}
{"_id": "d1637", "text": "def make_executable(script_path):\n    \"\"\"Make `script_path` executable.\n\n    :param script_path: The file to change\n    \"\"\"\n    status = os.stat(script_path)\n    os.chmod(script_path, status.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d1638", "text": "def _write_json(file, contents):\n    \"\"\"Write a dict to a JSON file.\"\"\"\n    with open(file, 'w') as f:\n        return json.dump(contents, f, indent=2, sort_keys=True)", "title": ""}
{"_id": "d1639", "text": "def dedupe(items):\n    \"\"\"Remove duplicates from a sequence (of hashable items) while maintaining\n    order. NOTE: This only works if items in the list are hashable types.\n\n    Taken from the Python Cookbook, 3rd ed. Such a great book!\n\n    \"\"\"\n    seen = set()\n    for item in items:\n        if item not in seen:\n            yield item\n            seen.add(item)", "title": ""}
{"_id": "d1640", "text": "def set_property(self, key, value):\n        \"\"\"\n        Update only one property in the dict\n        \"\"\"\n        self.properties[key] = value\n        self.sync_properties()", "title": ""}
{"_id": "d1641", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d1642", "text": "def _write_color_colorama (fp, text, color):\n    \"\"\"Colorize text with given color.\"\"\"\n    foreground, background, style = get_win_color(color)\n    colorama.set_console(foreground=foreground, background=background,\n      style=style)\n    fp.write(text)\n    colorama.reset_console()", "title": ""}
{"_id": "d1643", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d1644", "text": "def save_dict_to_file(filename, dictionary):\n  \"\"\"Saves dictionary as CSV file.\"\"\"\n  with open(filename, 'w') as f:\n    writer = csv.writer(f)\n    for k, v in iteritems(dictionary):\n      writer.writerow([str(k), str(v)])", "title": ""}
{"_id": "d1645", "text": "def add_noise(Y, sigma):\n    \"\"\"Adds noise to Y\"\"\"\n    return Y + np.random.normal(0, sigma, Y.shape)", "title": ""}
{"_id": "d1646", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d1647", "text": "def stopwatch_now():\n    \"\"\"Get a timevalue for interval comparisons\n\n    When possible it is a monotonic clock to prevent backwards time issues.\n    \"\"\"\n    if six.PY2:\n        now = time.time()\n    else:\n        now = time.monotonic()\n    return now", "title": ""}
{"_id": "d1648", "text": "def safe_dump(data, stream=None, **kwds):\n    \"\"\"implementation of safe dumper using Ordered Dict Yaml Dumper\"\"\"\n    return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)", "title": ""}
{"_id": "d1649", "text": "def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs):\n    \"\"\"Add plots to an existing plot\"\"\"\n    if LATEX:\n        xl_data = xl[1]  # NOQA\n        yl_data = yl[1]\n    else:\n        xl_data = xl[0]  # NOQA\n        yl_data = yl[0]\n\n    for idx in range(len(y)):\n        ax.plot(x, y[idx], label=yl_data[idx], linestyle=linestyle)\n\n    ax.legend(loc='upper right')\n    ax.set_ylim(auto=True)", "title": ""}
{"_id": "d1650", "text": "def load_yaml_file(file_path: str):\n    \"\"\"Load a YAML file from path\"\"\"\n    with codecs.open(file_path, 'r') as f:\n        return yaml.safe_load(f)", "title": ""}
{"_id": "d1651", "text": "def safe_unicode(string):\n    \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n    if not PY3:\n        uni = string.replace(u'\\u2019', \"'\")\n        return uni.encode('utf-8')\n        \n    return string", "title": ""}
{"_id": "d1652", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d1653", "text": "def url_fix_common_typos (url):\n    \"\"\"Fix common typos in given URL like forgotten colon.\"\"\"\n    if url.startswith(\"http//\"):\n        url = \"http://\" + url[6:]\n    elif url.startswith(\"https//\"):\n        url = \"https://\" + url[7:]\n    return url", "title": ""}
{"_id": "d1654", "text": "def yaml(self):\n        \"\"\"\n        returns the yaml output of the dict.\n        \"\"\"\n        return ordered_dump(OrderedDict(self),\n                            Dumper=yaml.SafeDumper,\n                            default_flow_style=False)", "title": ""}
{"_id": "d1655", "text": "def matshow(*args, **kwargs):\n    \"\"\"\n    imshow without interpolation like as matshow\n    :param args:\n    :param kwargs:\n    :return:\n    \"\"\"\n    kwargs['interpolation'] = kwargs.pop('interpolation', 'none')\n    return plt.imshow(*args, **kwargs)", "title": ""}
{"_id": "d1656", "text": "def extract_all(zipfile, dest_folder):\n    \"\"\"\n    reads the zip file, determines compression\n    and unzips recursively until source files \n    are extracted \n    \"\"\"\n    z = ZipFile(zipfile)\n    print(z)\n    z.extract(dest_folder)", "title": ""}
{"_id": "d1657", "text": "def handle_m2m(self, sender, instance, **kwargs):\n    \"\"\" Handle many to many relationships \"\"\"\n    self.handle_save(instance.__class__, instance)", "title": ""}
{"_id": "d1658", "text": "def extract(self, destination):\n        \"\"\"Extract the archive.\"\"\"\n        with zipfile.ZipFile(self.archive, 'r') as zip_ref:\n            zip_ref.extractall(destination)", "title": ""}
{"_id": "d1659", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d1660", "text": "def compress(data, **kwargs):\n    \"\"\"zlib.compress(data, **kwargs)\n    \n    \"\"\" + zopfli.__COMPRESSOR_DOCSTRING__  + \"\"\"\n    Returns:\n      String containing a zlib container\n    \"\"\"\n    kwargs['gzip_mode'] = 0\n    return zopfli.zopfli.compress(data, **kwargs)", "title": ""}
{"_id": "d1661", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d1662", "text": "def init_mq(self):\n        \"\"\"Init connection and consumer with openstack mq.\"\"\"\n        mq = self.init_connection()\n        self.init_consumer(mq)\n        return mq.connection", "title": ""}
{"_id": "d1663", "text": "def dot_product(self, other):\n        \"\"\" Return the dot product of the given vectors. \"\"\"\n        return self.x * other.x + self.y * other.y", "title": ""}
{"_id": "d1664", "text": "def is_real_floating_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a real floating point type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.floating)", "title": ""}
{"_id": "d1665", "text": "def max(self):\n        \"\"\"\n        Returns the maximum value of the domain.\n\n        :rtype: `float` or `np.inf`\n        \"\"\"\n        return int(self._max) if not np.isinf(self._max) else self._max", "title": ""}
{"_id": "d1666", "text": "def bash(filename):\n    \"\"\"Runs a bash script in the local directory\"\"\"\n    sys.stdout.flush()\n    subprocess.call(\"bash {}\".format(filename), shell=True)", "title": ""}
{"_id": "d1667", "text": "def log_loss(preds, labels):\n    \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n    log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n    return -log_likelihood", "title": ""}
{"_id": "d1668", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d1669", "text": "def longest_run_1d(arr):\n    \"\"\"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.\n    \"\"\"\n    v, rl = rle_1d(arr)[:2]\n    return np.where(v, rl, 0).max()", "title": ""}
{"_id": "d1670", "text": "def list2dict(list_of_options):\n    \"\"\"Transforms a list of 2 element tuples to a dictionary\"\"\"\n    d = {}\n    for key, value in list_of_options:\n        d[key] = value\n    return d", "title": ""}
{"_id": "d1671", "text": "def simulate(self):\n        \"\"\"Generates a random integer in the available range.\"\"\"\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_)", "title": ""}
{"_id": "d1672", "text": "def in_directory(path):\n    \"\"\"Context manager (with statement) that changes the current directory\n    during the context.\n    \"\"\"\n    curdir = os.path.abspath(os.curdir)\n    os.chdir(path)\n    yield\n    os.chdir(curdir)", "title": ""}
{"_id": "d1673", "text": "def median(data):\n    \"\"\"Calculate the median of a list.\"\"\"\n    data.sort()\n    num_values = len(data)\n    half = num_values // 2\n    if num_values % 2:\n        return data[half]\n    return 0.5 * (data[half-1] + data[half])", "title": ""}
{"_id": "d1674", "text": "def filter_(stream_spec, filter_name, *args, **kwargs):\n    \"\"\"Alternate name for ``filter``, so as to not collide with the\n    built-in python ``filter`` operator.\n    \"\"\"\n    return filter(stream_spec, filter_name, *args, **kwargs)", "title": ""}
{"_id": "d1675", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d1676", "text": "def date_to_timestamp(date):\n    \"\"\"\n        date to unix timestamp in milliseconds\n    \"\"\"\n    date_tuple = date.timetuple()\n    timestamp = calendar.timegm(date_tuple) * 1000\n    return timestamp", "title": ""}
{"_id": "d1677", "text": "def python_mime(fn):\n    \"\"\"\n    Decorator, which adds correct MIME type for python source to the decorated\n    bottle API function.\n    \"\"\"\n    @wraps(fn)\n    def python_mime_decorator(*args, **kwargs):\n        response.content_type = \"text/x-python\"\n\n        return fn(*args, **kwargs)\n\n    return python_mime_decorator", "title": ""}
{"_id": "d1678", "text": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "title": ""}
{"_id": "d1679", "text": "def mock_decorator(*args, **kwargs):\n    \"\"\"Mocked decorator, needed in the case we need to mock a decorator\"\"\"\n    def _called_decorator(dec_func):\n        @wraps(dec_func)\n        def _decorator(*args, **kwargs):\n            return dec_func()\n        return _decorator\n    return _called_decorator", "title": ""}
{"_id": "d1680", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d1681", "text": "def add_matplotlib_cmap(cm, name=None):\n    \"\"\"Add a matplotlib colormap.\"\"\"\n    global cmaps\n    cmap = matplotlib_to_ginga_cmap(cm, name=name)\n    cmaps[cmap.name] = cmap", "title": ""}
{"_id": "d1682", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d1683", "text": "def find_one(self, query):\n        \"\"\"Find one wrapper with conversion to dictionary\n\n        :param dict query: A Mongo query\n        \"\"\"\n        mongo_response = yield self.collection.find_one(query)\n        raise Return(self._obj_cursor_to_dictionary(mongo_response))", "title": ""}
{"_id": "d1684", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d1685", "text": "def test_replace_colon():\n    \"\"\"py.test for replace_colon\"\"\"\n    data = ((\"zone:aap\", '@', \"zone@aap\"),# s, r, replaced\n    )    \n    for s, r, replaced in data:\n        result = replace_colon(s, r)\n        assert result == replaced", "title": ""}
{"_id": "d1686", "text": "def init_rotating_logger(level, logfile, max_files, max_bytes):\n  \"\"\"Initializes a rotating logger\n\n  It also makes sure that any StreamHandler is removed, so as to avoid stdout/stderr\n  constipation issues\n  \"\"\"\n  logging.basicConfig()\n\n  root_logger = logging.getLogger()\n  log_format = \"[%(asctime)s] [%(levelname)s] %(filename)s: %(message)s\"\n\n  root_logger.setLevel(level)\n  handler = RotatingFileHandler(logfile, maxBytes=max_bytes, backupCount=max_files)\n  handler.setFormatter(logging.Formatter(fmt=log_format, datefmt=date_format))\n  root_logger.addHandler(handler)\n\n  for handler in root_logger.handlers:\n    root_logger.debug(\"Associated handlers - \" + str(handler))\n    if isinstance(handler, logging.StreamHandler):\n      root_logger.debug(\"Removing StreamHandler: \" + str(handler))\n      root_logger.handlers.remove(handler)", "title": ""}
{"_id": "d1687", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d1688", "text": "def getfirstline(file, default):\n    \"\"\"\n    Returns the first line of a file.\n    \"\"\"\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\n    return default", "title": ""}
{"_id": "d1689", "text": "def maybeparens(lparen, item, rparen):\n    \"\"\"Wrap an item in optional parentheses, only applying them if necessary.\"\"\"\n    return item | lparen.suppress() + item + rparen.suppress()", "title": ""}
{"_id": "d1690", "text": "def now(timezone=None):\n    \"\"\"\n    Return a naive datetime object for the given ``timezone``. A ``timezone``\n    is any pytz- like or datetime.tzinfo-like timezone object. If no timezone\n    is given, then UTC is assumed.\n\n    This method is best used with pytz installed::\n\n        pip install pytz\n    \"\"\"\n    d = datetime.datetime.utcnow()\n    if not timezone:\n        return d\n\n    return to_timezone(d, timezone).replace(tzinfo=None)", "title": ""}
{"_id": "d1691", "text": "def matrixTimesVector(MM, aa):\n    \"\"\"\n\n    :param MM: A matrix of size 3x3\n    :param aa: A vector of size 3\n    :return: A vector of size 3 which is the product of the matrix by the vector\n    \"\"\"\n    bb = np.zeros(3, np.float)\n    for ii in range(3):\n        bb[ii] = np.sum(MM[ii, :] * aa)\n    return bb", "title": ""}
{"_id": "d1692", "text": "def redirect_stdout(new_stdout):\n    \"\"\"Redirect the stdout\n\n    Args:\n        new_stdout (io.StringIO): New stdout to use instead\n    \"\"\"\n    old_stdout, sys.stdout = sys.stdout, new_stdout\n    try:\n        yield None\n    finally:\n        sys.stdout = old_stdout", "title": ""}
{"_id": "d1693", "text": "def _check_and_convert_bools(self):\n        \"\"\"Replace boolean variables by the characters 'F'/'T'\n        \"\"\"\n        replacements = {\n            True: 'T',\n            False: 'F',\n        }\n\n        for key in self.bools:\n            if isinstance(self[key], bool):\n                self[key] = replacements[self[key]]", "title": ""}
{"_id": "d1694", "text": "def __exit__(self, *exc):\n        \"\"\"Exit the runtime context. This will end the transaction.\"\"\"\n        if exc[0] is None and exc[1] is None and exc[2] is None:\n            self.commit()\n        else:\n            self.rollback()", "title": ""}
{"_id": "d1695", "text": "def stringify_dict_contents(dct):\n    \"\"\"Turn dict keys and values into native strings.\"\"\"\n    return {\n        str_if_nested_or_str(k): str_if_nested_or_str(v)\n        for k, v in dct.items()\n    }", "title": ""}
{"_id": "d1696", "text": "def up(self):\n        \n        \"\"\"Moves the layer up in the stacking order.\n        \n        \"\"\"\n        \n        i = self.index()\n        if i != None:\n            del self.canvas.layers[i]\n            i = min(len(self.canvas.layers), i+1)\n            self.canvas.layers.insert(i, self)", "title": ""}
{"_id": "d1697", "text": "def pretty_dict_string(d, indent=0):\n    \"\"\"Pretty output of nested dictionaries.\n    \"\"\"\n    s = ''\n    for key, value in sorted(d.items()):\n        s += '    ' * indent + str(key)\n        if isinstance(value, dict):\n             s += '\\n' + pretty_dict_string(value, indent+1)\n        else:\n             s += '=' + str(value) + '\\n'\n    return s", "title": ""}
{"_id": "d1698", "text": "def set_locale(request):\n    \"\"\"Return locale from GET lang param or automatically.\"\"\"\n    return request.query.get('lang', app.ps.babel.select_locale_by_request(request))", "title": ""}
{"_id": "d1699", "text": "def is_power_of_2(num):\n    \"\"\"Return whether `num` is a power of two\"\"\"\n    log = math.log2(num)\n    return int(log) == float(log)", "title": ""}
{"_id": "d1700", "text": "def _qrcode_to_file(qrcode, out_filepath):\n    \"\"\" Save a `qrcode` object into `out_filepath`.\n    Parameters\n    ----------\n    qrcode: qrcode object\n\n    out_filepath: str\n        Path to the output file.\n    \"\"\"\n    try:\n        qrcode.save(out_filepath)\n    except Exception as exc:\n        raise IOError('Error trying to save QR code file {}.'.format(out_filepath)) from exc\n    else:\n        return qrcode", "title": ""}
{"_id": "d1701", "text": "def prepare(doc):\n    \"\"\"Sets the caption_found and plot_found variables to False.\"\"\"\n    doc.caption_found = False\n    doc.plot_found = False\n    doc.listings_counter = 0", "title": ""}
{"_id": "d1702", "text": "def copy(obj):\n    def copy(self):\n        \"\"\"\n        Copy self to a new object.\n        \"\"\"\n        from copy import deepcopy\n\n        return deepcopy(self)\n    obj.copy = copy\n    return obj", "title": ""}
{"_id": "d1703", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d1704", "text": "def positive_integer(anon, obj, field, val):\n    \"\"\"\n    Returns a random positive integer (for a Django PositiveIntegerField)\n    \"\"\"\n    return anon.faker.positive_integer(field=field)", "title": ""}
{"_id": "d1705", "text": "def _normalize(image):\n  \"\"\"Normalize the image to zero mean and unit variance.\"\"\"\n  offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])\n  image -= offset\n\n  scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])\n  image /= scale\n  return image", "title": ""}
{"_id": "d1706", "text": "def sometimesish(fn):\n    \"\"\"\n    Has a 50/50 chance of calling a function\n    \"\"\"\n    def wrapped(*args, **kwargs):\n        if random.randint(1, 2) == 1:\n            return fn(*args, **kwargs)\n\n    return wrapped", "title": ""}
{"_id": "d1707", "text": "def log_normalize(data):\n    \"\"\"Perform log transform log(x + 1).\n    \n    Parameters\n    ----------\n    data : array_like\n    \n    \"\"\"\n    if sp.issparse(data):\n        data = data.copy()\n        data.data = np.log2(data.data + 1)\n        return data\n\n    return np.log2(data.astype(np.float64) + 1)", "title": ""}
{"_id": "d1708", "text": "def runiform(lower, upper, size=None):\n    \"\"\"\n    Random uniform variates.\n    \"\"\"\n    return np.random.uniform(lower, upper, size)", "title": ""}
{"_id": "d1709", "text": "def decode_arr(data):\n    \"\"\"Extract a numpy array from a base64 buffer\"\"\"\n    data = data.encode('utf-8')\n    return frombuffer(base64.b64decode(data), float64)", "title": ""}
{"_id": "d1710", "text": "def get_idx_rect(index_list):\n    \"\"\"Extract the boundaries from a list of indexes\"\"\"\n    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\n    return ( min(rows), max(rows), min(cols), max(cols) )", "title": ""}
{"_id": "d1711", "text": "def _factor_generator(n):\n    \"\"\"\n    From a given natural integer, returns the prime factors and their multiplicity\n    :param n: Natural integer\n    :return:\n    \"\"\"\n    p = prime_factors(n)\n    factors = {}\n    for p1 in p:\n        try:\n            factors[p1] += 1\n        except KeyError:\n            factors[p1] = 1\n    return factors", "title": ""}
{"_id": "d1712", "text": "def input(self,pin):\n        \"\"\"Read the specified pin and return HIGH/true if the pin is pulled high,\n        or LOW/false if pulled low.\n        \"\"\"\n        return self.mraa_gpio.Gpio.read(self.mraa_gpio.Gpio(pin))", "title": ""}
{"_id": "d1713", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d1714", "text": "def _iter_keys(key):\n    \"\"\"! Iterate over subkeys of a key\n    \"\"\"\n    for i in range(winreg.QueryInfoKey(key)[0]):\n        yield winreg.OpenKey(key, winreg.EnumKey(key, i))", "title": ""}
{"_id": "d1715", "text": "def shape(self):\n        \"\"\"Compute the shape of the dataset as (rows, cols).\"\"\"\n        if not self.data:\n            return (0, 0)\n        return (len(self.data), len(self.dimensions))", "title": ""}
{"_id": "d1716", "text": "def _parse_config(config_file_path):\n    \"\"\" Parse Config File from yaml file. \"\"\"\n    config_file = open(config_file_path, 'r')\n    config = yaml.load(config_file)\n    config_file.close()\n    return config", "title": ""}
{"_id": "d1717", "text": "def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model):\n    \"\"\" The how well do the features plus a constant base rate sum up to the model output.\n    \"\"\"\n\n    X_train, X_test = to_array(X_train, X_test)\n\n    # how many features to mask\n    assert X_train.shape[1] == X_test.shape[1]\n\n    # keep nkeep top features and re-train the model for each test explanation\n    yp_test = trained_model.predict(X_test)\n\n    return metric(yp_test, strip_list(attr_test).sum(1))", "title": ""}
{"_id": "d1718", "text": "def load_data(filename):\n    \"\"\"\n    :rtype : numpy matrix\n    \"\"\"\n    data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n    return data.as_matrix()", "title": ""}
{"_id": "d1719", "text": "def one_hot2string(arr, vocab):\n    \"\"\"Convert a one-hot encoded array back to string\n    \"\"\"\n    tokens = one_hot2token(arr)\n    indexToLetter = _get_index_dict(vocab)\n\n    return [''.join([indexToLetter[x] for x in row]) for row in tokens]", "title": ""}
{"_id": "d1720", "text": "def lambda_from_file(python_file):\n    \"\"\"\n    Reads a python file and returns a awslambda.Code object\n    :param python_file:\n    :return:\n    \"\"\"\n    lambda_function = []\n    with open(python_file, 'r') as f:\n        lambda_function.extend(f.read().splitlines())\n\n    return awslambda.Code(ZipFile=(Join('\\n', lambda_function)))", "title": ""}
{"_id": "d1721", "text": "def reverse_code_map(self):\n        \"\"\"Return a map from a code ( usually a string ) to the  shorter numeric value\"\"\"\n\n        return {c.value: (c.ikey if c.ikey else c.key) for c in self.codes}", "title": ""}
{"_id": "d1722", "text": "def html_to_text(content):\n    \"\"\" Converts html content to plain text \"\"\"\n    text = None\n    h2t = html2text.HTML2Text()\n    h2t.ignore_links = False\n    text = h2t.handle(content)\n    return text", "title": ""}
{"_id": "d1723", "text": "def _loadfilepath(self, filepath, **kwargs):\n        \"\"\"This loads a geojson file into a geojson python\n        dictionary using the json module.\n        \n        Note: to load with a different text encoding use the encoding argument.\n        \"\"\"\n        with open(filepath, \"r\") as f:\n            data = json.load(f, **kwargs)\n        return data", "title": ""}
{"_id": "d1724", "text": "def get(url):\n    \"\"\"Recieving the JSON file from uulm\"\"\"\n    response = urllib.request.urlopen(url)\n    data = response.read()\n    data = data.decode(\"utf-8\")\n    data = json.loads(data)\n    return data", "title": ""}
{"_id": "d1725", "text": "def cli(yamlfile, root, format):\n    \"\"\" Generate CSV/TSV file from biolink model \"\"\"\n    print(CsvGenerator(yamlfile, format).serialize(classes=root))", "title": ""}
{"_id": "d1726", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d1727", "text": "def dimensions(path):\n    \"\"\"Get width and height of a PDF\"\"\"\n    pdf = PdfFileReader(path)\n    size = pdf.getPage(0).mediaBox\n    return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d1728", "text": "def list_apis(awsclient):\n    \"\"\"List APIs in account.\"\"\"\n    client_api = awsclient.get_client('apigateway')\n\n    apis = client_api.get_rest_apis()['items']\n\n    for api in apis:\n        print(json2table(api))", "title": ""}
{"_id": "d1729", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d1730", "text": "def get_code(module):\n    \"\"\"\n    Compile and return a Module's code object.\n    \"\"\"\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()", "title": ""}
{"_id": "d1731", "text": "def fopenat(base_fd, path):\n    \"\"\"\n    Does openat read-only, then does fdopen to get a file object\n    \"\"\"\n\n    return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')", "title": ""}
{"_id": "d1732", "text": "def aux_insertTree(childTree, parentTree):\n\t\"\"\"This a private (You shouldn't have to call it) recursive function that inserts a child tree into a parent tree.\"\"\"\n\tif childTree.x1 != None and childTree.x2 != None :\n\t\tparentTree.insert(childTree.x1, childTree.x2, childTree.name, childTree.referedObject)\n\n\tfor c in childTree.children:\n\t\taux_insertTree(c, parentTree)", "title": ""}
{"_id": "d1733", "text": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "title": ""}
{"_id": "d1734", "text": "def flat_list(lst):\n    \"\"\"This function flatten given nested list.\n    Argument:\n        nested list\n    Returns:\n        flat list\n    \"\"\"\n    if isinstance(lst, list):\n        for item in lst:\n            for i in flat_list(item):\n                yield i\n    else:\n        yield lst", "title": ""}
{"_id": "d1735", "text": "def get_feature_order(dataset, features):\n    \"\"\" Returns a list with the order that features requested appear in\n    dataset \"\"\"\n    all_features = dataset.get_feature_names()\n\n    i = [all_features.index(f) for f in features]\n\n    return i", "title": ""}
{"_id": "d1736", "text": "def circ_permutation(items):\n    \"\"\"Calculate the circular permutation for a given list of items.\"\"\"\n    permutations = []\n    for i in range(len(items)):\n        permutations.append(items[i:] + items[:i])\n    return permutations", "title": ""}
{"_id": "d1737", "text": "def _format_list(result):\n    \"\"\"Format list responses into a table.\"\"\"\n\n    if not result:\n        return result\n\n    if isinstance(result[0], dict):\n        return _format_list_objects(result)\n\n    table = Table(['value'])\n    for item in result:\n        table.add_row([iter_to_table(item)])\n    return table", "title": ""}
{"_id": "d1738", "text": "def redirect(view=None, url=None, **kwargs):\n    \"\"\"Redirects to the specified view or url\n    \"\"\"\n    if view:\n        if url:\n            kwargs[\"url\"] = url\n        url = flask.url_for(view, **kwargs)\n    current_context.exit(flask.redirect(url))", "title": ""}
{"_id": "d1739", "text": "def zero_pad(m, n=1):\n    \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n    return np.pad(m, (n, n), mode='constant', constant_values=[0])", "title": ""}
{"_id": "d1740", "text": "def get(self, key):  \n        \"\"\" get a set of keys from redis \"\"\"\n        res = self.connection.get(key)\n        print(res)\n        return res", "title": ""}
{"_id": "d1741", "text": "def zero_pad(m, n=1):\n    \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n    return np.pad(m, (n, n), mode='constant', constant_values=[0])", "title": ""}
{"_id": "d1742", "text": "def format_screen(strng):\n    \"\"\"Format a string for screen printing.\n\n    This removes some latex-type format codes.\"\"\"\n    # Paragraph continue\n    par_re = re.compile(r'\\\\$',re.MULTILINE)\n    strng = par_re.sub('',strng)\n    return strng", "title": ""}
{"_id": "d1743", "text": "def old_pad(s):\n    \"\"\"\n    Pads an input string to a given block size.\n    :param s: string\n    :returns: The padded string.\n    \"\"\"\n    if len(s) % OLD_BLOCK_SIZE == 0:\n        return s\n\n    return Padding.appendPadding(s, blocksize=OLD_BLOCK_SIZE)", "title": ""}
{"_id": "d1744", "text": "def path(self):\n        \"\"\"Return the project path (aka project root)\n\n        If ``package.__file__`` is ``/foo/foo/__init__.py``, then project.path\n        should be ``/foo``.\n        \"\"\"\n        return pathlib.Path(self.package.__file__).resolve().parent.parent", "title": ""}
{"_id": "d1745", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d1746", "text": "def case_us2mc(x):\n    \"\"\" underscore to mixed case notation \"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)", "title": ""}
{"_id": "d1747", "text": "def remove(self, path):\n        \"\"\"Remove remote file\n        Return:\n            bool: true or false\"\"\"\n        p = self.cmd('shell', 'rm', path)\n        stdout, stderr = p.communicate()\n        if stdout or stderr:\n            return False\n        else:\n            return True", "title": ""}
{"_id": "d1748", "text": "def endline_semicolon_check(self, original, loc, tokens):\n        \"\"\"Check for semicolons at the end of lines.\"\"\"\n        return self.check_strict(\"semicolon at end of line\", original, loc, tokens)", "title": ""}
{"_id": "d1749", "text": "def parse(self):\n        \"\"\"\n        Parse file specified by constructor.\n        \"\"\"\n        f = open(self.parse_log_path, \"r\")\n        self.parse2(f)\n        f.close()", "title": ""}
{"_id": "d1750", "text": "def get_absolute_path(*args):\n    \"\"\"Transform relative pathnames into absolute pathnames.\"\"\"\n    directory = os.path.dirname(os.path.abspath(__file__))\n    return os.path.join(directory, *args)", "title": ""}
{"_id": "d1751", "text": "def parse_obj(o):\n    \"\"\"\n    Parses a given dictionary with the key being the OBD PID and the value its\n    returned value by the OBD interface\n    :param dict o:\n    :return:\n    \"\"\"\n    r = {}\n    for k, v in o.items():\n        if is_unable_to_connect(v):\n            r[k] = None\n\n        try:\n            r[k] = parse_value(k, v)\n        except (ObdPidParserUnknownError, AttributeError, TypeError):\n            r[k] = None\n    return r", "title": ""}
{"_id": "d1752", "text": "def remove_list_duplicates(lista, unique=False):\n    \"\"\"\n    Remove duplicated elements in a list.\n    Args:\n        lista: List with elements to clean duplicates.\n    \"\"\"\n    result = []\n    allready = []\n\n    for elem in lista:\n        if elem not in result:\n            result.append(elem)\n        else:\n            allready.append(elem)\n\n    if unique:\n        for elem in allready:\n            result = list(filter((elem).__ne__, result))\n\n    return result", "title": ""}
{"_id": "d1753", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d1754", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d1755", "text": "def def_linear(fun):\n    \"\"\"Flags that a function is linear wrt all args\"\"\"\n    defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:\n                  fun(*subval(args, argnum, g), **kwargs))", "title": ""}
{"_id": "d1756", "text": "def add_to_parser(self, parser):\n        \"\"\"\n        Adds the argument to an argparse.ArgumentParser instance\n\n        @param parser An argparse.ArgumentParser instance\n        \"\"\"\n        kwargs = self._get_kwargs()\n        args = self._get_args()\n        parser.add_argument(*args, **kwargs)", "title": ""}
{"_id": "d1757", "text": "def random_choice(sequence):\n    \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n    return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)", "title": ""}
{"_id": "d1758", "text": "def unescape(str):\n    \"\"\"Undoes the effects of the escape() function.\"\"\"\n    out = ''\n    prev_backslash = False\n    for char in str:\n        if not prev_backslash and char == '\\\\':\n            prev_backslash = True\n            continue\n        out += char\n        prev_backslash = False\n    return out", "title": ""}
{"_id": "d1759", "text": "def hflip(img):\n    \"\"\"Horizontally flip the given PIL Image.\n\n    Args:\n        img (PIL Image): Image to be flipped.\n\n    Returns:\n        PIL Image:  Horizontall flipped image.\n    \"\"\"\n    if not _is_pil_image(img):\n        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n    return img.transpose(Image.FLIP_LEFT_RIGHT)", "title": ""}
{"_id": "d1760", "text": "def strip_columns(tab):\n    \"\"\"Strip whitespace from string columns.\"\"\"\n    for colname in tab.colnames:\n        if tab[colname].dtype.kind in ['S', 'U']:\n            tab[colname] = np.core.defchararray.strip(tab[colname])", "title": ""}
{"_id": "d1761", "text": "def export_all(self):\n\t\tquery = \"\"\"\n\t\t\tSELECT quote, library, logid\n\t\t\tfrom quotes\n\t\t\tleft outer join quote_log on quotes.quoteid = quote_log.quoteid\n\t\t\t\"\"\"\n\t\tfields = 'text', 'library', 'log_id'\n\t\treturn (dict(zip(fields, res)) for res in self.db.execute(query))", "title": ""}
{"_id": "d1762", "text": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "title": ""}
{"_id": "d1763", "text": "def _precision_recall(y_true, y_score, ax=None):\n    \"\"\"\n    Plot precision-recall 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]\n        Target scores (estimator predictions).\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    \"\"\"\n    precision, recall, _ = precision_recall_curve(y_true, y_score)\n    average_precision = average_precision_score(y_true, y_score)\n\n    if ax is None:\n        ax = plt.gca()\n\n    ax.plot(recall, precision, label=('Precision-Recall curve: AUC={0:0.2f}'\n                                      .format(average_precision)))\n    _set_ax_settings(ax)\n    return ax", "title": ""}
{"_id": "d1764", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d1765", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d1766", "text": "def remove_dups(seq):\n    \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d1767", "text": "def format_prettytable(table):\n    \"\"\"Converts SoftLayer.CLI.formatting.Table instance to a prettytable.\"\"\"\n    for i, row in enumerate(table.rows):\n        for j, item in enumerate(row):\n            table.rows[i][j] = format_output(item)\n\n    ptable = table.prettytable()\n    ptable.hrules = prettytable.FRAME\n    ptable.horizontal_char = '.'\n    ptable.vertical_char = ':'\n    ptable.junction_char = ':'\n    return ptable", "title": ""}
{"_id": "d1768", "text": "def _RemoveIllegalXMLCharacters(self, xml_string):\n    \"\"\"Removes illegal characters for XML.\n\n    If the input is not a string it will be returned unchanged.\n\n    Args:\n      xml_string (str): XML with possible illegal characters.\n\n    Returns:\n      str: XML where all illegal characters have been removed.\n    \"\"\"\n    if not isinstance(xml_string, py2to3.STRING_TYPES):\n      return xml_string\n\n    return self._ILLEGAL_XML_RE.sub('\\ufffd', xml_string)", "title": ""}
{"_id": "d1769", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d1770", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d1771", "text": "def pylog(self, *args, **kwargs):\n        \"\"\"Display all available logging information.\"\"\"\n        printerr(self.name, args, kwargs, traceback.format_exc())", "title": ""}
{"_id": "d1772", "text": "def strip_accents(s):\n    \"\"\"\n    Strip accents to prepare for slugification.\n    \"\"\"\n    nfkd = unicodedata.normalize('NFKD', unicode(s))\n    return u''.join(ch for ch in nfkd if not unicodedata.combining(ch))", "title": ""}
{"_id": "d1773", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d1774", "text": "def key_to_metric(self, key):\n        \"\"\"Replace all non-letter characters with underscores\"\"\"\n        return ''.join(l if l in string.letters else '_' for l in key)", "title": ""}
{"_id": "d1775", "text": "def get_ram(self, format_ = \"nl\"):\n\t\t\"\"\"\n\t\t\treturn a string representations of the ram\n\t\t\"\"\"\n\t\tram = [self.ram.read(i) for i in range(self.ram.size)]\n\t\treturn self._format_mem(ram, format_)", "title": ""}
{"_id": "d1776", "text": "def strip_querystring(url):\n    \"\"\"Remove the querystring from the end of a URL.\"\"\"\n    p = six.moves.urllib.parse.urlparse(url)\n    return p.scheme + \"://\" + p.netloc + p.path", "title": ""}
{"_id": "d1777", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d1778", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d1779", "text": "async def sysinfo(dev: Device):\n    \"\"\"Print out system information (version, MAC addrs).\"\"\"\n    click.echo(await dev.get_system_info())\n    click.echo(await dev.get_interface_information())", "title": ""}
{"_id": "d1780", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d1781", "text": "def _screen(self, s, newline=False):\n        \"\"\"Print something on screen when self.verbose == True\"\"\"\n        if self.verbose:\n            if newline:\n                print(s)\n            else:\n                print(s, end=' ')", "title": ""}
{"_id": "d1782", "text": "def lowstrip(term):\n    \"\"\"Convert to lowercase and strip spaces\"\"\"\n    term = re.sub('\\s+', ' ', term)\n    term = term.lower()\n    return term", "title": ""}
{"_id": "d1783", "text": "def _screen(self, s, newline=False):\n        \"\"\"Print something on screen when self.verbose == True\"\"\"\n        if self.verbose:\n            if newline:\n                print(s)\n            else:\n                print(s, end=' ')", "title": ""}
{"_id": "d1784", "text": "def to_str(s):\n    \"\"\"\n    Convert bytes and non-string into Python 3 str\n    \"\"\"\n    if isinstance(s, bytes):\n        s = s.decode('utf-8')\n    elif not isinstance(s, str):\n        s = str(s)\n    return s", "title": ""}
{"_id": "d1785", "text": "def printOut(value, end='\\n'):\n    \"\"\"\n    This function prints the given String immediately and flushes the output.\n    \"\"\"\n    sys.stdout.write(value)\n    sys.stdout.write(end)\n    sys.stdout.flush()", "title": ""}
{"_id": "d1786", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d1787", "text": "def IndexOfNth(s, value, n):\n    \"\"\"Gets the index of Nth occurance of a given character in a string\n\n    :param str s:\n        Input string\n    :param char value:\n        Input char to be searched.\n    :param int n:\n        Nth occurrence of char to be searched.\n\n    :return:\n        Index of the Nth occurrence in the string.\n    :rtype: int\n\n    \"\"\"\n    remaining = n\n    for i in xrange(0, len(s)):\n        if s[i] == value:\n            remaining -= 1\n            if remaining == 0:\n                return i\n    return -1", "title": ""}
{"_id": "d1788", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d1789", "text": "def get_trace_id_from_flask():\n    \"\"\"Get trace_id from flask request headers.\n\n    :rtype: str\n    :returns: TraceID in HTTP request headers.\n    \"\"\"\n    if flask is None or not flask.request:\n        return None\n\n    header = flask.request.headers.get(_FLASK_TRACE_HEADER)\n\n    if header is None:\n        return None\n\n    trace_id = header.split(\"/\", 1)[0]\n\n    return trace_id", "title": ""}
{"_id": "d1790", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d1791", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d1792", "text": "def _idx_col2rowm(d):\n    \"\"\"Generate indexes to change from col-major to row-major ordering\"\"\"\n    if 0 == len(d):\n        return 1\n    if 1 == len(d):\n        return np.arange(d[0])\n    # order='F' indicates column-major ordering\n    idx = np.array(np.arange(np.prod(d))).reshape(d, order='F').T\n    return idx.flatten(order='F')", "title": ""}
{"_id": "d1793", "text": "def get_memory_usage():\n    \"\"\"Gets RAM memory usage\n\n    :return: MB of memory used by this process\n    \"\"\"\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info().rss\n    return mem / (1024 * 1024)", "title": ""}
{"_id": "d1794", "text": "def _replace_token_range(tokens, start, end, replacement):\n    \"\"\"For a range indicated from start to end, replace with replacement.\"\"\"\n    tokens = tokens[:start] + replacement + tokens[end:]\n    return tokens", "title": ""}
{"_id": "d1795", "text": "def print_out(self, *lst):\n      \"\"\" Print list of strings to the predefined stdout. \"\"\"\n      self.print2file(self.stdout, True, True, *lst)", "title": ""}
{"_id": "d1796", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d1797", "text": "def parse(self):\n        \"\"\"Parses data in table\n\n        :return: List of list of values in table\n        \"\"\"\n        data = []  # add name of section\n\n        for row in self.soup.find_all(\"tr\"):  # cycle through all rows\n            parsed = self._parse_row(row)\n            if parsed:\n                data.append(parsed)\n\n        return data", "title": ""}
{"_id": "d1798", "text": "def stringify_col(df, col_name):\n    \"\"\"\n    Take a dataframe and string-i-fy a column of values.\n    Turn nan/None into \"\" and all other values into strings.\n\n    Parameters\n    ----------\n    df : dataframe\n    col_name : string\n    \"\"\"\n    df = df.copy()\n    df[col_name] = df[col_name].fillna(\"\")\n    df[col_name] = df[col_name].astype(str)\n    return df", "title": ""}
{"_id": "d1799", "text": "def add_0x(string):\n    \"\"\"Add 0x to string at start.\n    \"\"\"\n    if isinstance(string, bytes):\n        string = string.decode('utf-8')\n    return '0x' + str(string)", "title": ""}
{"_id": "d1800", "text": "def parse_form(self, req, name, field):\n        \"\"\"Pull a form value from the request.\"\"\"\n        return get_value(req.body_arguments, name, field)", "title": ""}
{"_id": "d1801", "text": "def warn_deprecated(message, stacklevel=2):  # pragma: no cover\n    \"\"\"Warn deprecated.\"\"\"\n\n    warnings.warn(\n        message,\n        category=DeprecationWarning,\n        stacklevel=stacklevel\n    )", "title": ""}
{"_id": "d1802", "text": "def resize_by_area(img, size):\n  \"\"\"image resize function used by quite a few image problems.\"\"\"\n  return tf.to_int64(\n      tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))", "title": ""}
{"_id": "d1803", "text": "def _get_points(self):\n        \"\"\"\n        Subclasses may override this method.\n        \"\"\"\n        return tuple([self._getitem__points(i)\n                     for i in range(self._len__points())])", "title": ""}
{"_id": "d1804", "text": "def validate_multiindex(self, obj):\n        \"\"\"validate that we can store the multi-index; reset and return the\n        new object\n        \"\"\"\n        levels = [l if l is not None else \"level_{0}\".format(i)\n                  for i, l in enumerate(obj.index.names)]\n        try:\n            return obj.reset_index(), levels\n        except ValueError:\n            raise ValueError(\"duplicate names/columns in the multi-index when \"\n                             \"storing as a table\")", "title": ""}
{"_id": "d1805", "text": "def raw_print(*args, **kw):\n    \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()", "title": ""}
{"_id": "d1806", "text": "def validate_multiindex(self, obj):\n        \"\"\"validate that we can store the multi-index; reset and return the\n        new object\n        \"\"\"\n        levels = [l if l is not None else \"level_{0}\".format(i)\n                  for i, l in enumerate(obj.index.names)]\n        try:\n            return obj.reset_index(), levels\n        except ValueError:\n            raise ValueError(\"duplicate names/columns in the multi-index when \"\n                             \"storing as a table\")", "title": ""}
{"_id": "d1807", "text": "def popup(self, title, callfn, initialdir=None):\n        \"\"\"Let user select a directory.\"\"\"\n        super(DirectorySelection, self).popup(title, callfn, initialdir)", "title": ""}
{"_id": "d1808", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d1809", "text": "def command_py2to3(args):\n    \"\"\"\n    Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n    \"\"\"\n    from lib2to3.main import main\n    sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "title": ""}
{"_id": "d1810", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d1811", "text": "def get_soup(page=''):\n    \"\"\"\n    Returns a bs4 object of the page requested\n    \"\"\"\n    content = requests.get('%s/%s' % (BASE_URL, page)).text\n    return BeautifulSoup(content)", "title": ""}
{"_id": "d1812", "text": "def make_file_read_only(file_path):\n    \"\"\"\n    Removes the write permissions for the given file for owner, groups and others.\n\n    :param file_path: The file whose privileges are revoked.\n    :raise FileNotFoundError: If the given file does not exist.\n    \"\"\"\n    old_permissions = os.stat(file_path).st_mode\n    os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)", "title": ""}
{"_id": "d1813", "text": "def __is_bound_method(method):\n    \"\"\"Return ``True`` if the `method` is a bound method (attached to an class\n    instance.\n\n    Args:\n        method: A method or function type object.\n    \"\"\"\n    if not(hasattr(method, \"__func__\") and hasattr(method, \"__self__\")):\n        return False\n\n    # Bound methods have a __self__ attribute pointing to the owner instance\n    return six.get_method_self(method) is not None", "title": ""}
{"_id": "d1814", "text": "def get_column_keys_and_names(table):\n    \"\"\"\n    Return a generator of tuples k, c such that k is the name of the python attribute for\n    the column and c is the name of the column in the sql table.\n    \"\"\"\n    ins = inspect(table)\n    return ((k, c.name) for k, c in ins.mapper.c.items())", "title": ""}
{"_id": "d1815", "text": "def clean_url(url):\n        \"\"\"URL Validation function\"\"\"\n        if not url.startswith(('http://', 'https://')):\n            url = f'http://{url}'\n\n        if not URL_RE.match(url):\n            raise BadURLException(f'{url} is not valid')\n\n        return url", "title": ""}
{"_id": "d1816", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d1817", "text": "def stft_magnitude(signal, fft_length,\n                   hop_length=None,\n                   window_length=None):\n  \"\"\"Calculate the short-time Fourier transform magnitude.\n\n  Args:\n    signal: 1D np.array of the input time-domain signal.\n    fft_length: Size of the FFT to apply.\n    hop_length: Advance (in samples) between each frame passed to FFT.\n    window_length: Length of each block of samples to pass to FFT.\n\n  Returns:\n    2D np.array where each row contains the magnitudes of the fft_length/2+1\n    unique values of the FFT for the corresponding frame of input samples.\n  \"\"\"\n  frames = frame(signal, window_length, hop_length)\n  # Apply frame window to each frame. We use a periodic Hann (cosine of period\n  # window_length) instead of the symmetric Hann of np.hanning (period\n  # window_length-1).\n  window = periodic_hann(window_length)\n  windowed_frames = frames * window\n  return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))", "title": ""}
{"_id": "d1818", "text": "def make_unique_ngrams(s, n):\n    \"\"\"Make a set of unique n-grams from a string.\"\"\"\n    return set(s[i:i + n] for i in range(len(s) - n + 1))", "title": ""}
{"_id": "d1819", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d1820", "text": "def vowels(self):\n        \"\"\"\n        Return a new IPAString, containing only the vowels in the current string.\n\n        :rtype: IPAString\n        \"\"\"\n        return IPAString(ipa_chars=[c for c in self.ipa_chars if c.is_vowel])", "title": ""}
{"_id": "d1821", "text": "def module_name(self):\n        \"\"\"\n        The module where this route's view function was defined.\n        \"\"\"\n        if not self.view_func:\n            return None\n        elif self._controller_cls:\n            rv = inspect.getmodule(self._controller_cls).__name__\n            return rv\n        return inspect.getmodule(self.view_func).__name__", "title": ""}
{"_id": "d1822", "text": "def _is_leap_year(year):\n    \"\"\"Determine if a year is leap year.\n\n    Parameters\n    ----------\n    year : numeric\n\n    Returns\n    -------\n    isleap : array of bools\n    \"\"\"\n    isleap = ((np.mod(year, 4) == 0) &\n              ((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0)))\n    return isleap", "title": ""}
{"_id": "d1823", "text": "def first_sunday(self, year, month):\n        \"\"\"Get the first sunday of a month.\"\"\"\n        date = datetime(year, month, 1, 0)\n        days_until_sunday = 6 - date.weekday()\n\n        return date + timedelta(days=days_until_sunday)", "title": ""}
{"_id": "d1824", "text": "def series_index(self, series):\n        \"\"\"\n        Return the integer index of *series* in this sequence.\n        \"\"\"\n        for idx, s in enumerate(self):\n            if series is s:\n                return idx\n        raise ValueError('series not in chart data object')", "title": ""}
{"_id": "d1825", "text": "def _remove_keywords(d):\n    \"\"\"\n    copy the dict, filter_keywords\n\n    Parameters\n    ----------\n    d : dict\n    \"\"\"\n    return { k:v for k, v in iteritems(d) if k not in RESERVED }", "title": ""}
{"_id": "d1826", "text": "def right_outer(self):\n        \"\"\"\n            Performs Right Outer Join\n            :return right_outer: dict\n        \"\"\"\n        self.get_collections_data()\n        right_outer_join = self.merge_join_docs(\n            set(self.collections_data['right'].keys()))\n        return right_outer_join", "title": ""}
{"_id": "d1827", "text": "def input_int_default(question=\"\", default=0):\n    \"\"\"A function that works for both, Python 2.x and Python 3.x.\n       It asks the user for input and returns it as a string.\n    \"\"\"\n    answer = input_string(question)\n    if answer == \"\" or answer == \"yes\":\n        return default\n    else:\n        return int(answer)", "title": ""}
{"_id": "d1828", "text": "async def result_processor(tasks):\n    \"\"\"An async result aggregator that combines all the results\n       This gets executed in unsync.loop and unsync.thread\"\"\"\n    output = {}\n    for task in tasks:\n        num, res = await task\n        output[num] = res\n    return output", "title": ""}
{"_id": "d1829", "text": "def to_dict(dictish):\n    \"\"\"\n    Given something that closely resembles a dictionary, we attempt\n    to coerce it into a propery dictionary.\n    \"\"\"\n    if hasattr(dictish, 'iterkeys'):\n        m = dictish.iterkeys\n    elif hasattr(dictish, 'keys'):\n        m = dictish.keys\n    else:\n        raise ValueError(dictish)\n\n    return dict((k, dictish[k]) for k in m())", "title": ""}
{"_id": "d1830", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d1831", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d1832", "text": "def shallow_reverse(g):\n    \"\"\"\n    Make a shallow copy of a directional graph and reverse the edges. This is a workaround to solve the issue that one\n    cannot easily make a shallow reversed copy of a graph in NetworkX 2, since networkx.reverse(copy=False) now returns\n    a GraphView, and GraphViews are always read-only.\n\n    :param networkx.DiGraph g:  The graph to reverse.\n    :return:                    A new networkx.DiGraph that has all nodes and all edges of the original graph, with\n                                edges reversed.\n    \"\"\"\n\n    new_g = networkx.DiGraph()\n\n    new_g.add_nodes_from(g.nodes())\n    for src, dst, data in g.edges(data=True):\n        new_g.add_edge(dst, src, **data)\n\n    return new_g", "title": ""}
{"_id": "d1833", "text": "def __matches(s1, s2, ngrams_fn, n=3):\n    \"\"\"\n        Returns the n-grams that match between two sequences\n\n        See also: SequenceMatcher.get_matching_blocks\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:\n    \"\"\"\n    ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n))\n    return ngrams1.intersection(ngrams2)", "title": ""}
{"_id": "d1834", "text": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "title": ""}
{"_id": "d1835", "text": "def parse_timestamp(timestamp):\n    \"\"\"Parse ISO8601 timestamps given by github API.\"\"\"\n    dt = dateutil.parser.parse(timestamp)\n    return dt.astimezone(dateutil.tz.tzutc())", "title": ""}
{"_id": "d1836", "text": "def _rotate(n, x, y, rx, ry):\n    \"\"\"Rotate and flip a quadrant appropriately\n\n    Based on the implementation here:\n        https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503\n\n    \"\"\"\n    if ry == 0:\n        if rx == 1:\n            x = n - 1 - x\n            y = n - 1 - y\n        return y, x\n    return x, y", "title": ""}
{"_id": "d1837", "text": "def redirect_output(fileobj):\n    \"\"\"Redirect standard out to file.\"\"\"\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old", "title": ""}
{"_id": "d1838", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d1839", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d1840", "text": "def paste(xsel=False):\n    \"\"\"Returns system clipboard contents.\"\"\"\n    selection = \"primary\" if xsel else \"clipboard\"\n    try:\n        return subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"utf-8\")\n    except OSError as why:\n        raise XclipNotFound", "title": ""}
{"_id": "d1841", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d1842", "text": "def normalize(self, string):\n        \"\"\"Normalize the string according to normalization list\"\"\"\n        return ''.join([self._normalize.get(x, x) for x in nfd(string)])", "title": ""}
{"_id": "d1843", "text": "def lower_ext(abspath):\n    \"\"\"Convert file extension to lowercase.\n    \"\"\"\n    fname, ext = os.path.splitext(abspath)\n    return fname + ext.lower()", "title": ""}
{"_id": "d1844", "text": "def _linear_interpolation(x, X, Y):\n    \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n    \"\"\"\n    return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "title": ""}
{"_id": "d1845", "text": "def __call__(self, func, *args, **kwargs):\n        \"\"\"Shorcut for self.run.\"\"\"\n        return self.run(func, *args, **kwargs)", "title": ""}
{"_id": "d1846", "text": "def abort(err):\n    \"\"\"Abort everything, everywhere.\"\"\"\n    if _debug: abort._debug(\"abort %r\", err)\n    global local_controllers\n\n    # tell all the local controllers to abort\n    for controller in local_controllers.values():\n        controller.abort(err)", "title": ""}
{"_id": "d1847", "text": "def test():  # pragma: no cover\n    \"\"\"Execute the unit tests on an installed copy of unyt.\n\n    Note that this function requires pytest to run. If pytest is not\n    installed this function will raise ImportError.\n    \"\"\"\n    import pytest\n    import os\n\n    pytest.main([os.path.dirname(os.path.abspath(__file__))])", "title": ""}
{"_id": "d1848", "text": "def storeByteArray(self, context, page, len, data, returnError):\n        \"\"\"please override\"\"\"\n        returnError.contents.value = self.IllegalStateError\n        raise NotImplementedError(\"You must override this method.\")", "title": ""}
{"_id": "d1849", "text": "def test(ctx, all=False, verbose=False):\n    \"\"\"Run the tests.\"\"\"\n    cmd = 'tox' if all else 'py.test'\n    if verbose:\n        cmd += ' -v'\n    return ctx.run(cmd, pty=True).return_code", "title": ""}
{"_id": "d1850", "text": "def array(self):\n        \"\"\"\n        return the underlying numpy array\n        \"\"\"\n        return np.arange(self.start, self.stop, self.step)", "title": ""}
{"_id": "d1851", "text": "def test(nose_argsuments):\n    \"\"\" Run application tests \"\"\"\n    from nose import run\n\n    params = ['__main__', '-c', 'nose.ini']\n    params.extend(nose_argsuments)\n    run(argv=params)", "title": ""}
{"_id": "d1852", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d1853", "text": "def _save_file(self, filename, contents):\n        \"\"\"write the html file contents to disk\"\"\"\n        with open(filename, 'w') as f:\n            f.write(contents)", "title": ""}
{"_id": "d1854", "text": "def requests_post(url, data=None, json=None, **kwargs):\n    \"\"\"Requests-mock requests.post wrapper.\"\"\"\n    return requests_request('post', url, data=data, json=json, **kwargs)", "title": ""}
{"_id": "d1855", "text": "def resetScale(self):\n        \"\"\"Resets the scale on this image. Correctly aligns time scale, undoes manual scaling\"\"\"\n        self.img.scale(1./self.imgScale[0], 1./self.imgScale[1])\n        self.imgScale = (1.,1.)", "title": ""}
{"_id": "d1856", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d1857", "text": "def compile_filter(bpf_filter, iface=None):\n    \"\"\"Asks Tcpdump to parse the filter, then build the matching\n    BPF bytecode using get_bpf_pointer.\n    \"\"\"\n    if not TCPDUMP:\n        raise Scapy_Exception(\"tcpdump is not available. Cannot use filter !\")\n    try:\n        process = subprocess.Popen([\n            conf.prog.tcpdump,\n            \"-p\",\n            \"-i\", (conf.iface if iface is None else iface),\n            \"-ddd\",\n            \"-s\", str(MTU),\n            bpf_filter],\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE\n        )\n    except OSError as ex:\n        raise Scapy_Exception(\"Failed to attach filter: %s\" % ex)\n    lines, err = process.communicate()\n    ret = process.returncode\n    if ret:\n        raise Scapy_Exception(\n            \"Failed to attach filter: tcpdump returned: %s\" % err\n        )\n    lines = lines.strip().split(b\"\\n\")\n    return get_bpf_pointer(lines)", "title": ""}
{"_id": "d1858", "text": "def plot_target(target, ax):\n    \"\"\"Ajoute la target au plot\"\"\"\n    ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)", "title": ""}
{"_id": "d1859", "text": "def append(self, item):\n        \"\"\" append item and print it to stdout \"\"\"\n        print(item)\n        super(MyList, self).append(item)", "title": ""}
{"_id": "d1860", "text": "def get_duckduckgo_links(limit, params, headers):\n\t\"\"\"\n\tfunction to fetch links equal to limit\n\n\tduckduckgo pagination is not static, so there is a limit on\n\tmaximum number of links that can be scraped\n\t\"\"\"\n\tresp = s.get('https://duckduckgo.com/html', params = params, headers = headers)\n\tlinks = scrape_links(resp.content, engine = 'd')\n\treturn links[:limit]", "title": ""}
{"_id": "d1861", "text": "def add_noise(Y, sigma):\n    \"\"\"Adds noise to Y\"\"\"\n    return Y + np.random.normal(0, sigma, Y.shape)", "title": ""}
{"_id": "d1862", "text": "def main_func(args=None):\n    \"\"\"Main funcion when executing this module as script\n\n    :param args: commandline arguments\n    :type args: list\n    :returns: None\n    :rtype: None\n    :raises: None\n    \"\"\"\n    # we have to initialize a gui even if we dont need one right now.\n    # as soon as you call maya.standalone.initialize(), a QApplication\n    # with type Tty is created. This is the type for conosle apps.\n    # Because i have not found a way to replace that, we just init the gui.\n    guimain.init_gui()\n\n    main.init()\n    launcher = Launcher()\n    parsed, unknown = launcher.parse_args(args)\n    parsed.func(parsed, unknown)", "title": ""}
{"_id": "d1863", "text": "def set_property(self, key, value):\n        \"\"\"\n        Update only one property in the dict\n        \"\"\"\n        self.properties[key] = value\n        self.sync_properties()", "title": ""}
{"_id": "d1864", "text": "def eqstr(a, b):\n    \"\"\"\n    Determine whether two strings are equivalent.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html\n\n    :param a: Arbitrary character string.\n    :type a: str\n    :param b: Arbitrary character string.\n    :type b: str\n    :return: True if A and B are equivalent.\n    :rtype: bool\n    \"\"\"\n    return bool(libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)))", "title": ""}
{"_id": "d1865", "text": "def __dir__(self):\n        u\"\"\"Returns a list of children and available helper methods.\"\"\"\n        return sorted(self.keys() | {m for m in dir(self.__class__) if m.startswith('to_')})", "title": ""}
{"_id": "d1866", "text": "def ask_dir(self):\n\t\t\"\"\"\n\t\tdialogue box for choosing directory\n\t\t\"\"\"\n\t\targs ['directory'] = askdirectory(**self.dir_opt) \n\t\tself.dir_text.set(args ['directory'])", "title": ""}
{"_id": "d1867", "text": "def add_argument(self, dest, nargs=1, obj=None):\n        \"\"\"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.\n        \"\"\"\n        if obj is None:\n            obj = dest\n        self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))", "title": ""}
{"_id": "d1868", "text": "def get_last(self, table=None):\n        \"\"\"Just the last entry.\"\"\"\n        if table is None: table = self.main_table\n        query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n        return self.own_cursor.execute(query).fetchone()", "title": ""}
{"_id": "d1869", "text": "def Min(a, axis, keep_dims):\n    \"\"\"\n    Min reduction op.\n    \"\"\"\n    return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d1870", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d1871", "text": "def build_parser():\n    \"\"\"Build argument parsers.\"\"\"\n\n    parser = argparse.ArgumentParser(\"Release packages to pypi\")\n    parser.add_argument('--check', '-c', action=\"store_true\", help=\"Do a dry run without uploading\")\n    parser.add_argument('component', help=\"The component to release as component-version\")\n    return parser", "title": ""}
{"_id": "d1872", "text": "def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):\n        \"\"\" Send email message via Flask-Sendmail.\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.\n        \"\"\"\n\n        if not current_app.testing:  # pragma: no cover\n\n            # Prepare email message\n            from flask_sendmail import Message\n            message = Message(\n                subject,\n                recipients=[recipient],\n                html=html_message,\n                body=text_message)\n\n            # Send email message\n            self.mail.send(message)", "title": ""}
{"_id": "d1873", "text": "def ma(self):\n        \"\"\"Represent data as a masked array.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n        inf and nan are filtered via :func:`numpy.isfinite`.\n        \"\"\"\n        a = self.array\n        return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))", "title": ""}
{"_id": "d1874", "text": "async def _send_plain_text(self, request: Request, stack: Stack):\n        \"\"\"\n        Sends plain text using `_send_text()`.\n        \"\"\"\n\n        await self._send_text(request, stack, None)", "title": ""}
{"_id": "d1875", "text": "def getbyteslice(self, start, end):\n        \"\"\"Direct access to byte data.\"\"\"\n        c = self._rawarray[start:end]\n        return c", "title": ""}
{"_id": "d1876", "text": "def strip_querystring(url):\n    \"\"\"Remove the querystring from the end of a URL.\"\"\"\n    p = six.moves.urllib.parse.urlparse(url)\n    return p.scheme + \"://\" + p.netloc + p.path", "title": ""}
{"_id": "d1877", "text": "def chunks(arr, size):\n    \"\"\"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`\n    \"\"\"\n    for i in _range(0, len(arr), size):\n        yield arr[i:i+size]", "title": ""}
{"_id": "d1878", "text": "def yield_connections(sock):\n    \"\"\"Run a server on the specified socket.\"\"\"\n    while True:\n        log.debug('waiting for connection on %s', sock.getsockname())\n        try:\n            conn, _ = sock.accept()\n        except KeyboardInterrupt:\n            return\n        conn.settimeout(None)\n        log.debug('accepted connection on %s', sock.getsockname())\n        yield conn", "title": ""}
{"_id": "d1879", "text": "def to_dicts(recarray):\n    \"\"\"convert record array to a dictionaries\"\"\"\n    for rec in recarray:\n        yield dict(zip(recarray.dtype.names, rec.tolist()))", "title": ""}
{"_id": "d1880", "text": "def set_if_empty(self, param, default):\n        \"\"\" Set the parameter to the default if it doesn't exist \"\"\"\n        if not self.has(param):\n            self.set(param, default)", "title": ""}
{"_id": "d1881", "text": "def is_scalar(value):\n    \"\"\"Test if the given value is a scalar.\n\n    This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n    Args:\n        value: the value to test for being a scalar value\n\n    Returns:\n        boolean: if the given value is a scalar or not\n    \"\"\"\n    return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))", "title": ""}
{"_id": "d1882", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d1883", "text": "def barray(iterlines):\n    \"\"\"\n    Array of bytes\n    \"\"\"\n    lst = [line.encode('utf-8') for line in iterlines]\n    arr = numpy.array(lst)\n    return arr", "title": ""}
{"_id": "d1884", "text": "def add_matplotlib_cmap(cm, name=None):\n    \"\"\"Add a matplotlib colormap.\"\"\"\n    global cmaps\n    cmap = matplotlib_to_ginga_cmap(cm, name=name)\n    cmaps[cmap.name] = cmap", "title": ""}
{"_id": "d1885", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d1886", "text": "def setPixel(self, x, y, color):\n        \"\"\"Set the pixel at (x,y) to the integers in sequence 'color'.\"\"\"\n        return _fitz.Pixmap_setPixel(self, x, y, color)", "title": ""}
{"_id": "d1887", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d1888", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d1889", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d1890", "text": "def get_hline():\n    \"\"\" gets a horiztonal line \"\"\"\n    return Window(\n        width=LayoutDimension.exact(1),\n        height=LayoutDimension.exact(1),\n        content=FillControl('-', token=Token.Line))", "title": ""}
{"_id": "d1891", "text": "def StringIO(*args, **kwargs):\n    \"\"\"StringIO constructor shim for the async wrapper.\"\"\"\n    raw = sync_io.StringIO(*args, **kwargs)\n    return AsyncStringIOWrapper(raw)", "title": ""}
{"_id": "d1892", "text": "def _zerosamestates(self, A):\n        \"\"\"\n        zeros out states that should be identical\n\n        REQUIRED ARGUMENTS\n\n        A: the matrix whose entries are to be zeroed.\n\n        \"\"\"\n\n        for pair in self.samestates:\n            A[pair[0], pair[1]] = 0\n            A[pair[1], pair[0]] = 0", "title": ""}
{"_id": "d1893", "text": "def get_attribute_name_id(attr):\n    \"\"\"\n    Return the attribute name identifier\n    \"\"\"\n    return attr.value.id if isinstance(attr.value, ast.Name) else None", "title": ""}
{"_id": "d1894", "text": "def __iand__(self, other):\n        \"\"\"Intersect this flag with ``other`` in-place.\n        \"\"\"\n        self.known &= other.known\n        self.active &= other.active\n        return self", "title": ""}
{"_id": "d1895", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d1896", "text": "def get_raw_input(description, default=False):\n    \"\"\"Get user input from the command line via raw_input / input.\n\n    description (unicode): Text to display before prompt.\n    default (unicode or False/None): Default value to display with prompt.\n    RETURNS (unicode): User input.\n    \"\"\"\n    additional = ' (default: %s)' % default if default else ''\n    prompt = '    %s%s: ' % (description, additional)\n    user_input = input_(prompt)\n    return user_input", "title": ""}
{"_id": "d1897", "text": "def setup(app):\n  \"\"\"\n  Just connects the docstring pre_processor and should_skip functions to be\n  applied on all docstrings.\n\n  \"\"\"\n  app.connect('autodoc-process-docstring',\n              lambda *args: pre_processor(*args, namer=audiolazy_namer))\n  app.connect('autodoc-skip-member', should_skip)", "title": ""}
{"_id": "d1898", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d1899", "text": "def convert_camel_case_to_snake_case(name):\n    \"\"\"Convert CamelCase to snake_case.\"\"\"\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()", "title": ""}
{"_id": "d1900", "text": "def array_size(x, axis):\n  \"\"\"Calculate the size of `x` along `axis` dimensions only.\"\"\"\n  axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)\n  return max(numpy.prod(axis_shape), 1)", "title": ""}
{"_id": "d1901", "text": "def _mean_dict(dict_list):\n    \"\"\"Compute the mean value across a list of dictionaries\n    \"\"\"\n    return {k: np.array([d[k] for d in dict_list]).mean()\n            for k in dict_list[0].keys()}", "title": ""}
{"_id": "d1902", "text": "def fsliceafter(astr, sub):\n    \"\"\"Return the slice after at sub in string astr\"\"\"\n    findex = astr.find(sub)\n    return astr[findex + len(sub):]", "title": ""}
{"_id": "d1903", "text": "def average(arr):\n  \"\"\"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\n\n  \"\"\"\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))", "title": ""}
{"_id": "d1904", "text": "def _aggr_mean(inList):\n  \"\"\" Returns mean of non-None elements of the list\n  \"\"\"\n  aggrSum = 0\n  nonNone = 0\n  for elem in inList:\n    if elem != SENTINEL_VALUE_FOR_MISSING_DATA:\n      aggrSum += elem\n      nonNone += 1\n  if nonNone != 0:\n    return aggrSum / nonNone\n  else:\n    return None", "title": ""}
{"_id": "d1905", "text": "def help(self):\n        \"\"\"Prints discovered resources and their associated methods. Nice when\n        noodling in the terminal to wrap your head around Magento's insanity.\n        \"\"\"\n\n        print('Resources:')\n        print('')\n        for name in sorted(self._resources.keys()):\n            methods = sorted(self._resources[name]._methods.keys())\n            print('{}: {}'.format(bold(name), ', '.join(methods)))", "title": ""}
{"_id": "d1906", "text": "def loganalytics_data_plane_client(cli_ctx, _):\n    \"\"\"Initialize Log Analytics data client for use with CLI.\"\"\"\n    from .vendored_sdks.loganalytics import LogAnalyticsDataClient\n    from azure.cli.core._profile import Profile\n    profile = Profile(cli_ctx=cli_ctx)\n    cred, _, _ = profile.get_login_credentials(\n        resource=\"https://api.loganalytics.io\")\n    return LogAnalyticsDataClient(cred)", "title": ""}
{"_id": "d1907", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d1908", "text": "def start(self):\n        \"\"\"Create a background thread for httpd and serve 'forever'\"\"\"\n        self._process = threading.Thread(target=self._background_runner)\n        self._process.start()", "title": ""}
{"_id": "d1909", "text": "def out(self, output, newline=True):\n        \"\"\"Outputs a string to the console (stdout).\"\"\"\n        click.echo(output, nl=newline)", "title": ""}
{"_id": "d1910", "text": "def decode_arr(data):\n    \"\"\"Extract a numpy array from a base64 buffer\"\"\"\n    data = data.encode('utf-8')\n    return frombuffer(base64.b64decode(data), float64)", "title": ""}
{"_id": "d1911", "text": "def csvpretty(csvfile: csvfile=sys.stdin):\n    \"\"\" Pretty print a CSV file. \"\"\"\n    shellish.tabulate(csv.reader(csvfile))", "title": ""}
{"_id": "d1912", "text": "def encode_batch(self, inputBatch):\n        \"\"\"Encodes a whole batch of input arrays, without learning.\"\"\"\n        X      = inputBatch\n        encode = self.encode\n        Y      = np.array([ encode(x) for x in X])\n        return Y", "title": ""}
{"_id": "d1913", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d1914", "text": "def parse(el, typ):\n    \"\"\"\n    Parse a ``BeautifulSoup`` element as the given type.\n    \"\"\"\n    if not el:\n        return typ()\n    txt = text(el)\n    if not txt:\n        return typ()\n    return typ(txt)", "title": ""}
{"_id": "d1915", "text": "def sine_wave(frequency):\n  \"\"\"Emit a sine wave at the given frequency.\"\"\"\n  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n  ts = xs / FLAGS.sample_rate\n  return tf.sin(2 * math.pi * frequency * ts)", "title": ""}
{"_id": "d1916", "text": "def as_tree(context):\n    \"\"\"Return info about an object's members as JSON\"\"\"\n\n    tree = _build_tree(context, 2, 1)\n    if type(tree) == dict:\n        tree = [tree] \n    \n    return Response(content_type='application/json', body=json.dumps(tree))", "title": ""}
{"_id": "d1917", "text": "def singleton(class_):\n    \"\"\"Singleton definition.\n\n    Method 1 from\n    https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n    \"\"\"\n    instances = {}\n\n    def get_instance(*args, **kwargs):\n        if class_ not in instances:\n            instances[class_] = class_(*args, **kwargs)\n        return instances[class_]\n    return get_instance", "title": ""}
{"_id": "d1918", "text": "def QA_util_datetime_to_strdate(dt):\n    \"\"\"\n    :param dt:  pythone datetime.datetime\n    :return:  1999-02-01 string type\n    \"\"\"\n    strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n    return strdate", "title": ""}
{"_id": "d1919", "text": "def filter_useless_pass(source):\n    \"\"\"Yield code with useless \"pass\" lines removed.\"\"\"\n    try:\n        marked_lines = frozenset(useless_pass_line_numbers(source))\n    except (SyntaxError, tokenize.TokenError):\n        marked_lines = frozenset()\n\n    sio = io.StringIO(source)\n    for line_number, line in enumerate(sio.readlines(), start=1):\n        if line_number not in marked_lines:\n            yield line", "title": ""}
{"_id": "d1920", "text": "def refresh_swagger(self):\n        \"\"\"\n        Manually refresh the swagger document. This can help resolve errors communicate with the API.\n        \"\"\"\n        try:\n            os.remove(self._get_swagger_filename(self.swagger_url))\n        except EnvironmentError as e:\n            logger.warn(os.strerror(e.errno))\n        else:\n            self.__init__()", "title": ""}
{"_id": "d1921", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d1922", "text": "def get_bin_indices(self, values):\n        \"\"\"Returns index tuple in histogram of bin which contains value\"\"\"\n        return tuple([self.get_axis_bin_index(values[ax_i], ax_i)\n                      for ax_i in range(self.dimensions)])", "title": ""}
{"_id": "d1923", "text": "def arglexsort(arrays):\n    \"\"\"\n    Returns the indices of the lexicographical sorting\n    order of the supplied arrays.\n    \"\"\"\n    dtypes = ','.join(array.dtype.str for array in arrays)\n    recarray = np.empty(len(arrays[0]), dtype=dtypes)\n    for i, array in enumerate(arrays):\n        recarray['f%s' % i] = array\n    return recarray.argsort()", "title": ""}
{"_id": "d1924", "text": "def register_view(self, view):\n        \"\"\"Register callbacks for button press events and selection changed\"\"\"\n        super(ListViewController, self).register_view(view)\n        self.tree_view.connect('button_press_event', self.mouse_click)", "title": ""}
{"_id": "d1925", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d1926", "text": "def Bernstein(n, k):\n    \"\"\"Bernstein polynomial.\n\n    \"\"\"\n    coeff = binom(n, k)\n\n    def _bpoly(x):\n        return coeff * x ** k * (1 - x) ** (n - k)\n\n    return _bpoly", "title": ""}
{"_id": "d1927", "text": "def abbreviate_dashed(s):\n    \"\"\"Abbreviates each part of string that is delimited by a '-'.\"\"\"\n    r = []\n    for part in s.split('-'):\n        r.append(abbreviate(part))\n    return '-'.join(r)", "title": ""}
{"_id": "d1928", "text": "def maskIndex(self):\n        \"\"\" 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.\n        \"\"\"\n        if isinstance(self.mask, bool):\n            return np.full(self.data.shape, self.mask, dtype=np.bool)\n        else:\n            return self.mask", "title": ""}
{"_id": "d1929", "text": "def _split(string, splitters):\n    \"\"\"Splits a string into parts at multiple characters\"\"\"\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", "title": ""}
{"_id": "d1930", "text": "def read_key(self, key, bucket_name=None):\n        \"\"\"\n        Reads a key from S3\n\n        :param key: S3 key that will point to the file\n        :type key: str\n        :param bucket_name: Name of the bucket in which the file is stored\n        :type bucket_name: str\n        \"\"\"\n\n        obj = self.get_key(key, bucket_name)\n        return obj.get()['Body'].read().decode('utf-8')", "title": ""}
{"_id": "d1931", "text": "def split_into_words(s):\n  \"\"\"Split a sentence into list of words.\"\"\"\n  s = re.sub(r\"\\W+\", \" \", s)\n  s = re.sub(r\"[_0-9]+\", \" \", s)\n  return s.split()", "title": ""}
{"_id": "d1932", "text": "def get_as_bytes(self, s3_path):\n        \"\"\"\n        Get the contents of an object stored in S3 as bytes\n\n        :param s3_path: URL for target S3 location\n        :return: File contents as pure bytes\n        \"\"\"\n        (bucket, key) = self._path_to_bucket_and_key(s3_path)\n        obj = self.s3.Object(bucket, key)\n        contents = obj.get()['Body'].read()\n        return contents", "title": ""}
{"_id": "d1933", "text": "def matrix_at_check(self, original, loc, tokens):\n        \"\"\"Check for Python 3.5 matrix multiplication.\"\"\"\n        return self.check_py(\"35\", \"matrix multiplication\", original, loc, tokens)", "title": ""}
{"_id": "d1934", "text": "def render_template(self, source, **kwargs_context):\n        r\"\"\"Render a template string using sandboxed environment.\n\n        :param source: A string containing the page source.\n        :param \\*\\*kwargs_context: The context associated with the page.\n        :returns: The rendered template.\n        \"\"\"\n        return self.jinja_env.from_string(source).render(kwargs_context)", "title": ""}
{"_id": "d1935", "text": "def emit_db_sequence_updates(engine):\n    \"\"\"Set database sequence objects to match the source db\n\n       Relevant only when generated from SQLAlchemy connection.\n       Needed to avoid subsequent unique key violations after DB build.\"\"\"\n\n    if engine and engine.name == 'postgresql':\n        # not implemented for other RDBMS; necessity unknown\n        conn = engine.connect()\n        qry = \"\"\"SELECT 'SELECT last_value FROM ' || n.nspname ||\n                         '.' || c.relname || ';' AS qry,\n                        n.nspname || '.' || c.relname AS qual_name\n                 FROM   pg_namespace n\n                 JOIN   pg_class c ON (n.oid = c.relnamespace)\n                 WHERE  c.relkind = 'S'\"\"\"\n        for (qry, qual_name) in list(conn.execute(qry)):\n            (lastval, ) = conn.execute(qry).first()\n            nextval = int(lastval) + 1\n            yield \"ALTER SEQUENCE %s RESTART WITH %s;\" % (qual_name, nextval)", "title": ""}
{"_id": "d1936", "text": "def method_double_for(self, method_name):\n        \"\"\"Returns the method double for the provided method name, creating one if necessary.\n\n        :param str method_name: The name of the method to retrieve a method double for.\n        :return: The mapped ``MethodDouble``.\n        :rtype: MethodDouble\n        \"\"\"\n\n        if method_name not in self._method_doubles:\n            self._method_doubles[method_name] = MethodDouble(method_name, self._target)\n\n        return self._method_doubles[method_name]", "title": ""}
{"_id": "d1937", "text": "def rgba_bytes_tuple(self, x):\n        \"\"\"Provides the color corresponding to value `x` in the\n        form of a tuple (R,G,B,A) with int values between 0 and 255.\n        \"\"\"\n        return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))", "title": ""}
{"_id": "d1938", "text": "def bulk_query(self, query, *multiparams):\n        \"\"\"Bulk insert or update.\"\"\"\n\n        with self.get_connection() as conn:\n            conn.bulk_query(query, *multiparams)", "title": ""}
{"_id": "d1939", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d1940", "text": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n    \"\"\"\n    http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n    \"\"\"\n    fft = np.fft.fft(data)\n    # n = len(data)\n    # timestep = 1.0 / fs\n    # freq = np.fft.fftfreq(n, d=timestep)\n    bp = fft.copy()\n\n    # Zero out fft coefficients\n    # bp[10:-10] = 0\n\n    # Normalise\n    # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n    bp *= fft.dot(fft) / bp.dot(bp)\n\n    # must multipy by 2 to get the correct amplitude\n    ibp = 12 * np.fft.ifft(bp)\n    return ibp", "title": ""}
{"_id": "d1941", "text": "def _std(self,x):\n        \"\"\"\n        Compute standard deviation with ddof degrees of freedom\n        \"\"\"\n        return np.nanstd(x.values,ddof=self._ddof)", "title": ""}
{"_id": "d1942", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d1943", "text": "def print_env_info(key, out=sys.stderr):\n    \"\"\"If given environment key is defined, print it out.\"\"\"\n    value = os.getenv(key)\n    if value is not None:\n        print(key, \"=\", repr(value), file=out)", "title": ""}
{"_id": "d1944", "text": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "title": ""}
{"_id": "d1945", "text": "def Stop(self):\n    \"\"\"Stops the process status RPC server.\"\"\"\n    self._Close()\n\n    if self._rpc_thread.isAlive():\n      self._rpc_thread.join()\n    self._rpc_thread = None", "title": ""}
{"_id": "d1946", "text": "def set_cache_max(self, cache_name, maxsize, **kwargs):\n        \"\"\"\n        Sets the maxsize attribute of the named cache\n        \"\"\"\n        cache = self._get_cache(cache_name)\n        cache.set_maxsize(maxsize, **kwargs)", "title": ""}
{"_id": "d1947", "text": "def _on_release(self, event):\n        \"\"\"Stop dragging.\"\"\"\n        if self._drag_cols or self._drag_rows:\n            self._visual_drag.place_forget()\n            self._dragged_col = None\n            self._dragged_row = None", "title": ""}
{"_id": "d1948", "text": "def update_cache(self, data):\n        \"\"\"Update a cached value.\"\"\"\n        UTILS.update(self._cache, data)\n        self._save_cache()", "title": ""}
{"_id": "d1949", "text": "def stop_button_click_handler(self):\n        \"\"\"Method to handle what to do when the stop button is pressed\"\"\"\n        self.stop_button.setDisabled(True)\n        # Interrupt computations or stop debugging\n        if not self.shellwidget._reading:\n            self.interrupt_kernel()\n        else:\n            self.shellwidget.write_to_stdin('exit')", "title": ""}
{"_id": "d1950", "text": "def angle(x, y):\n    \"\"\"Return the angle between vectors a and b in degrees.\"\"\"\n    return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi", "title": ""}
{"_id": "d1951", "text": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "title": ""}
{"_id": "d1952", "text": "def average(iterator):\n    \"\"\"Iterative mean.\"\"\"\n    count = 0\n    total = 0\n    for num in iterator:\n        count += 1\n        total += num\n    return float(total)/count", "title": ""}
{"_id": "d1953", "text": "def add_object(self, object):\n        \"\"\"Add object to db session. Only for session-centric object-database mappers.\"\"\"\n        if object.id is None:\n            object.get_id()\n        self.db.engine.save(object)", "title": ""}
{"_id": "d1954", "text": "def _cal_dist2center(X, center):\n    \"\"\" Calculate the SSE to the cluster center\n    \"\"\"\n    dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')\n    return(np.sum(dmemb2cen))", "title": ""}
{"_id": "d1955", "text": "def save_hdf5(X, y, path):\n    \"\"\"Save data as a HDF5 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 HDF5 file to save data.\n    \"\"\"\n\n    with h5py.File(path, 'w') as f:\n        is_sparse = 1 if sparse.issparse(X) else 0\n        f['issparse'] = is_sparse\n        f['target'] = y\n\n        if is_sparse:\n            if not sparse.isspmatrix_csr(X):\n                X = X.tocsr()\n\n            f['shape'] = np.array(X.shape)\n            f['data'] = X.data\n            f['indices'] = X.indices\n            f['indptr'] = X.indptr\n        else:\n            f['data'] = X", "title": ""}
{"_id": "d1956", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d1957", "text": "def get_gzipped_contents(input_file):\n    \"\"\"\n    Returns a gzipped version of a previously opened file's buffer.\n    \"\"\"\n    zbuf = StringIO()\n    zfile = GzipFile(mode=\"wb\", compresslevel=6, fileobj=zbuf)\n    zfile.write(input_file.read())\n    zfile.close()\n    return ContentFile(zbuf.getvalue())", "title": ""}
{"_id": "d1958", "text": "def vec_angle(a, b):\n    \"\"\"\n    Calculate angle between two vectors\n    \"\"\"\n    cosang = np.dot(a, b)\n    sinang = fast_norm(np.cross(a, b))\n    return np.arctan2(sinang, cosang)", "title": ""}
{"_id": "d1959", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d1960", "text": "def elapsed_time_from(start_time):\n    \"\"\"calculate time delta from latched time and current 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", "title": ""}
{"_id": "d1961", "text": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "title": ""}
{"_id": "d1962", "text": "def color_func(func_name):\n    \"\"\"\n    Call color function base on name\n    \"\"\"\n    if str(func_name).isdigit():\n        return term_color(int(func_name))\n    return globals()[func_name]", "title": ""}
{"_id": "d1963", "text": "def token_list_to_text(tokenlist):\n    \"\"\"\n    Concatenate all the text parts again.\n    \"\"\"\n    ZeroWidthEscape = Token.ZeroWidthEscape\n    return ''.join(item[1] for item in tokenlist if item[0] != ZeroWidthEscape)", "title": ""}
{"_id": "d1964", "text": "def sometimesish(fn):\n    \"\"\"\n    Has a 50/50 chance of calling a function\n    \"\"\"\n    def wrapped(*args, **kwargs):\n        if random.randint(1, 2) == 1:\n            return fn(*args, **kwargs)\n\n    return wrapped", "title": ""}
{"_id": "d1965", "text": "def help(self, level=0):\n        \"\"\"return the usage string for available options \"\"\"\n        self.cmdline_parser.formatter.output_level = level\n        with _patch_optparse():\n            return self.cmdline_parser.format_help()", "title": ""}
{"_id": "d1966", "text": "def next (self):    # File-like object.\n\n        \"\"\"This is to support iterators over a file-like object.\n        \"\"\"\n\n        result = self.readline()\n        if result == self._empty_buffer:\n            raise StopIteration\n        return result", "title": ""}
{"_id": "d1967", "text": "def get_request(self, request):\n        \"\"\"Sets token-based auth headers.\"\"\"\n        request.transport_user = self.username\n        request.transport_password = self.api_key\n        return request", "title": ""}
{"_id": "d1968", "text": "def min_or_none(val1, val2):\n    \"\"\"Returns min(val1, val2) returning None only if both values are None\"\"\"\n    return min(val1, val2, key=lambda x: sys.maxint if x is None else x)", "title": ""}
{"_id": "d1969", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d1970", "text": "def call_and_exit(self, cmd, shell=True):\n        \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n        sys.exit(subprocess.call(cmd, shell=shell))", "title": ""}
{"_id": "d1971", "text": "def average(arr):\n  \"\"\"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\n\n  \"\"\"\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))", "title": ""}
{"_id": "d1972", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d1973", "text": "def tf2():\n  \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n  Returns:\n    The root module of a TF-2.0 API, if available.\n\n  Raises:\n    ImportError: if a TF-2.0 API is not available.\n  \"\"\"\n  # Import the `tf` compat API from this file and check if it's already TF 2.0.\n  if tf.__version__.startswith('2.'):\n    return tf\n  elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n    # As a fallback, try `tensorflow.compat.v2` if it's defined.\n    return tf.compat.v2\n  raise ImportError('cannot import tensorflow 2.0 API')", "title": ""}
{"_id": "d1974", "text": "def _run_cmd_get_output(cmd):\n    \"\"\"Runs a shell command, returns console output.\n\n    Mimics python3's subprocess.getoutput\n    \"\"\"\n    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n    out, err = process.communicate()\n    return out or err", "title": ""}
{"_id": "d1975", "text": "def tf2():\n  \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n  Returns:\n    The root module of a TF-2.0 API, if available.\n\n  Raises:\n    ImportError: if a TF-2.0 API is not available.\n  \"\"\"\n  # Import the `tf` compat API from this file and check if it's already TF 2.0.\n  if tf.__version__.startswith('2.'):\n    return tf\n  elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n    # As a fallback, try `tensorflow.compat.v2` if it's defined.\n    return tf.compat.v2\n  raise ImportError('cannot import tensorflow 2.0 API')", "title": ""}
{"_id": "d1976", "text": "def cartesian_product(arrays, flat=True, copy=False):\n    \"\"\"\n    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.\n    \"\"\"\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)", "title": ""}
{"_id": "d1977", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d1978", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d1979", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d1980", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d1981", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d1982", "text": "def deserialize_date(string):\n    \"\"\"\n    Deserializes string to date.\n\n    :param string: str.\n    :type string: str\n    :return: date.\n    :rtype: date\n    \"\"\"\n    try:\n        from dateutil.parser import parse\n        return parse(string).date()\n    except ImportError:\n        return string", "title": ""}
{"_id": "d1983", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d1984", "text": "def compose(*funcs):\n    \"\"\"compose a list of functions\"\"\"\n    return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)", "title": ""}
{"_id": "d1985", "text": "def flatten_all_but_last(a):\n  \"\"\"Flatten all dimensions of a except the last.\"\"\"\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", "title": ""}
{"_id": "d1986", "text": "def concat(cls, iterables):\n    \"\"\"\n    Similar to #itertools.chain.from_iterable().\n    \"\"\"\n\n    def generator():\n      for it in iterables:\n        for element in it:\n          yield element\n    return cls(generator())", "title": ""}
{"_id": "d1987", "text": "def max(self):\n        \"\"\"\n        Returns the maximum value of the domain.\n\n        :rtype: `float` or `np.inf`\n        \"\"\"\n        return int(self._max) if not np.isinf(self._max) else self._max", "title": ""}
{"_id": "d1988", "text": "def OnCellBackgroundColor(self, event):\n        \"\"\"Cell background color event handler\"\"\"\n\n        with undo.group(_(\"Background color\")):\n            self.grid.actions.set_attr(\"bgcolor\", event.color)\n\n        self.grid.ForceRefresh()\n\n        self.grid.update_attribute_toolbar()\n\n        event.Skip()", "title": ""}
{"_id": "d1989", "text": "def longest_run(da, dim='time'):\n    \"\"\"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\n        \"\"\"\n\n    d = rle(da, dim=dim)\n    rl_long = d.max(dim=dim)\n\n    return rl_long", "title": ""}
{"_id": "d1990", "text": "def build_docs(directory):\n    \"\"\"Builds sphinx docs from a given directory.\"\"\"\n    os.chdir(directory)\n    process = subprocess.Popen([\"make\", \"html\"], cwd=directory)\n    process.communicate()", "title": ""}
{"_id": "d1991", "text": "def ex(self, cmd):\n        \"\"\"Execute a normal python statement in user namespace.\"\"\"\n        with self.builtin_trap:\n            exec cmd in self.user_global_ns, self.user_ns", "title": ""}
{"_id": "d1992", "text": "def _multiline_width(multiline_s, line_width_fn=len):\n    \"\"\"Visible width of a potentially multiline content.\"\"\"\n    return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "title": ""}
{"_id": "d1993", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d1994", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d1995", "text": "def convert_tstamp(response):\n\t\"\"\"\n\tConvert a Stripe API timestamp response (unix epoch) to a native datetime.\n\n\t:rtype: datetime\n\t\"\"\"\n\tif response is None:\n\t\t# Allow passing None to convert_tstamp()\n\t\treturn response\n\n\t# Overrides the set timezone to UTC - I think...\n\ttz = timezone.utc if settings.USE_TZ else None\n\n\treturn datetime.datetime.fromtimestamp(response, tz)", "title": ""}
{"_id": "d1996", "text": "def col_rename(df,col_name,new_col_name):\n    \"\"\" Changes a column name in a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_name - string\n        Name of column to change\n    new_col_name - string\n        New name of column\n    \"\"\"\n    col_list = list(df.columns)\n    for index,value in enumerate(col_list):\n        if value == col_name:\n            col_list[index] = new_col_name\n            break\n    df.columns = col_list", "title": ""}
{"_id": "d1997", "text": "def checkbox_uncheck(self, force_check=False):\n        \"\"\"\n        Wrapper to uncheck a checkbox\n        \"\"\"\n        if self.get_attribute('checked'):\n            self.click(force_click=force_check)", "title": ""}
{"_id": "d1998", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d1999", "text": "def adapt_array(arr):\n    \"\"\"\n    http://stackoverflow.com/a/31312102/190597 (SoulNibbler)\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr)\n    out.seek(0)\n    return sqlite3.Binary(out.read())", "title": ""}
{"_id": "d2000", "text": "def __set_token_expired(self, value):\n        \"\"\"Internal helper for oauth code\"\"\"\n        self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value)\n        return", "title": ""}
{"_id": "d2001", "text": "def check_attribute_exists(instance):\n    \"\"\" Additional check for the dimension model, to ensure that attributes\n    given as the key and label attribute on the dimension exist. \"\"\"\n    attributes = instance.get('attributes', {}).keys()\n    if instance.get('key_attribute') not in attributes:\n        return False\n    label_attr = instance.get('label_attribute')\n    if label_attr and label_attr not in attributes:\n        return False\n    return True", "title": ""}
{"_id": "d2002", "text": "def redirect_output(fileobj):\n    \"\"\"Redirect standard out to file.\"\"\"\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old", "title": ""}
{"_id": "d2003", "text": "def hasattrs(object, *names):\n    \"\"\"\n    Takes in an object and a variable length amount of named attributes,\n    and checks to see if the object has each property. If any of the\n    attributes are missing, this returns false.\n\n    :param object: an object that may or may not contain the listed attributes\n    :param names: a variable amount of attribute names to check for\n    :return: True if the object contains each named attribute, false otherwise\n    \"\"\"\n    for name in names:\n        if not hasattr(object, name):\n            return False\n    return True", "title": ""}
{"_id": "d2004", "text": "def dir_path(dir):\n    \"\"\"with dir_path(path) to change into a directory.\"\"\"\n    old_dir = os.getcwd()\n    os.chdir(dir)\n    yield\n    os.chdir(old_dir)", "title": ""}
{"_id": "d2005", "text": "def bisect_index(a, x):\n    \"\"\" Find the leftmost index of an element in a list using binary search.\n\n    Parameters\n    ----------\n    a: list\n        A sorted list.\n    x: arbitrary\n        The element.\n\n    Returns\n    -------\n    int\n        The index.\n\n    \"\"\"\n    i = bisect.bisect_left(a, x)\n    if i != len(a) and a[i] == x:\n        return i\n    raise ValueError", "title": ""}
{"_id": "d2006", "text": "def save_form(self, request, form, change):\n        \"\"\"\n        Super class ordering is important here - user must get saved first.\n        \"\"\"\n        OwnableAdmin.save_form(self, request, form, change)\n        return DisplayableAdmin.save_form(self, request, form, change)", "title": ""}
{"_id": "d2007", "text": "def check_str(obj):\n        \"\"\" Returns a string for various input types \"\"\"\n        if isinstance(obj, str):\n            return obj\n        if isinstance(obj, float):\n            return str(int(obj))\n        else:\n            return str(obj)", "title": ""}
{"_id": "d2008", "text": "def gaussian_variogram_model(m, d):\n    \"\"\"Gaussian model, m is [psill, range, nugget]\"\"\"\n    psill = float(m[0])\n    range_ = float(m[1])\n    nugget = float(m[2])\n    return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget", "title": ""}
{"_id": "d2009", "text": "def title(msg):\n    \"\"\"Sets the title of the console window.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "title": ""}
{"_id": "d2010", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d2011", "text": "def pprint(self, seconds):\n        \"\"\"\n        Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n        :param seconds:  The time in seconds.\n        \"\"\"\n        return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))", "title": ""}
{"_id": "d2012", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d2013", "text": "def _escape(s):\n    \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n    e = s\n    e = e.replace('\\\\', '\\\\\\\\')\n    e = e.replace('\\n', '\\\\n')\n    e = e.replace('\\r', '\\\\r')\n    e = e.replace(\"'\", \"\\\\'\")\n    e = e.replace('\"', '\\\\\"')\n    return e", "title": ""}
{"_id": "d2014", "text": "def normalize(data):\n    \"\"\"\n    Function to normalize data to have mean 0 and unity standard deviation\n    (also called z-transform)\n    \n    \n    Parameters\n    ----------\n    data : numpy.ndarray\n    \n    \n    Returns\n    -------\n    numpy.ndarray\n        z-transform of input array\n    \n    \"\"\"\n    data = data.astype(float)\n    data -= data.mean()\n    \n    return data / data.std()", "title": ""}
{"_id": "d2015", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d2016", "text": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "title": ""}
{"_id": "d2017", "text": "def isnumber(*args):\n    \"\"\"Checks if value is an integer, long integer or float.\n\n    NOTE: Treats booleans as numbers, where True=1 and False=0.\n    \"\"\"\n    return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))", "title": ""}
{"_id": "d2018", "text": "def print_tree(self, indent=2):\n        \"\"\" print_tree: prints out structure of tree\n            Args: indent (int): What level of indentation at which to start printing\n            Returns: None\n        \"\"\"\n        config.LOGGER.info(\"{indent}{data}\".format(indent=\"   \" * indent, data=str(self)))\n        for child in self.children:\n            child.print_tree(indent + 1)", "title": ""}
{"_id": "d2019", "text": "def is_readable(fp, size=1):\n    \"\"\"\n    Check if the file-like object is readable.\n\n    :param fp: file-like object\n    :param size: byte size\n    :return: bool\n    \"\"\"\n    read_size = len(fp.read(size))\n    fp.seek(-read_size, 1)\n    return read_size == size", "title": ""}
{"_id": "d2020", "text": "def strip_head(sequence, values):\n    \"\"\"Strips elements of `values` from the beginning of `sequence`.\"\"\"\n    values = set(values)\n    return list(itertools.dropwhile(lambda x: x in values, sequence))", "title": ""}
{"_id": "d2021", "text": "def check_create_folder(filename):\n    \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n    os.makedirs(os.path.dirname(filename), exist_ok=True)", "title": ""}
{"_id": "d2022", "text": "def to_dict(self):\n        \"\"\"Converts the table to a dict.\"\"\"\n        return {\"name\": self.table_name, \"kind\": self.table_kind, \"data\": [r.to_dict() for r in self]}", "title": ""}
{"_id": "d2023", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d2024", "text": "def _crop_list_to_size(l, size):\n    \"\"\"Make a list a certain size\"\"\"\n    for x in range(size - len(l)):\n        l.append(False)\n    for x in range(len(l) - size):\n        l.pop()\n    return l", "title": ""}
{"_id": "d2025", "text": "def isin_alone(elems, line):\n    \"\"\"Check if an element from a list is the only element of a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if line.strip().lower() == e.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d2026", "text": "def unit_key_from_name(name):\n  \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n  result = name\n\n  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n    result = result.replace(old, new)\n\n  # Collapse redundant underscores and convert to uppercase.\n  result = re.sub(r'_+', '_', result.upper())\n\n  return result", "title": ""}
{"_id": "d2027", "text": "def is_iter_non_string(obj):\n    \"\"\"test if object is a list or tuple\"\"\"\n    if isinstance(obj, list) or isinstance(obj, tuple):\n        return True\n    return False", "title": ""}
{"_id": "d2028", "text": "def string_to_int( s ):\n  \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n  result = 0\n  for c in s:\n    if not isinstance(c, int): c = ord( c )\n    result = 256 * result + c\n  return result", "title": ""}
{"_id": "d2029", "text": "def valid_uuid(value):\n    \"\"\" Check if value is a valid UUID. \"\"\"\n\n    try:\n        uuid.UUID(value, version=4)\n        return True\n    except (TypeError, ValueError, AttributeError):\n        return False", "title": ""}
{"_id": "d2030", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d2031", "text": "def _get_ipv4_from_binary(self, bin_addr):\n        \"\"\"Converts binary address to Ipv4 format.\"\"\"\n\n        return socket.inet_ntop(socket.AF_INET, struct.pack(\"!L\", bin_addr))", "title": ""}
{"_id": "d2032", "text": "def is_symlink(self):\n        \"\"\"\n        Whether this path is a symbolic link.\n        \"\"\"\n        try:\n            return S_ISLNK(self.lstat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            # Path doesn't exist\n            return False", "title": ""}
{"_id": "d2033", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d2034", "text": "def is_valid_folder(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.isdir(arg):\n        parser.error(\"The folder %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d2035", "text": "def abort(self):\n        \"\"\" ensure the master exit from Barrier \"\"\"\n        self.mutex.release()\n        self.turnstile.release()\n        self.mutex.release()\n        self.turnstile2.release()", "title": ""}
{"_id": "d2036", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d2037", "text": "def Gaussian(x, mu, sig):\n    \"\"\"\n    Gaussian pdf.\n    :param x: free variable.\n    :param mu: mean of the distribution.\n    :param sig: standard deviation of the distribution.\n    :return: sympy.Expr for a Gaussian pdf.\n    \"\"\"\n    return sympy.exp(-(x - mu)**2/(2*sig**2))/sympy.sqrt(2*sympy.pi*sig**2)", "title": ""}
{"_id": "d2038", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d2039", "text": "def angle_v2_rad(vec_a, vec_b):\n    \"\"\"Returns angle between vec_a and vec_b in range [0, PI].  This does not\n    distinguish if a is left of or right of b.\n    \"\"\"\n    # cos(x) = A * B / |A| * |B|\n    return math.acos(vec_a.dot(vec_b) / (vec_a.length() * vec_b.length()))", "title": ""}
{"_id": "d2040", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d2041", "text": "def txt_line_iterator(path):\n  \"\"\"Iterate through lines of file.\"\"\"\n  with tf.gfile.Open(path) as f:\n    for line in f:\n      yield line.strip()", "title": ""}
{"_id": "d2042", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d2043", "text": "def to_binary(s, encoding='utf8'):\n    \"\"\"Portable cast function.\n\n    In python 2 the ``str`` function which is used to coerce objects to bytes does not\n    accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n    :param s: object to be converted to binary_type\n    :return: binary_type instance, representing s.\n    \"\"\"\n    if PY3:  # pragma: no cover\n        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n    return binary_type(s)", "title": ""}
{"_id": "d2044", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d2045", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d2046", "text": "def is_valid_image_extension(file_path):\n    \"\"\"is_valid_image_extension.\"\"\"\n    valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']\n    _, extension = os.path.splitext(file_path)\n    return extension.lower() in valid_extensions", "title": ""}
{"_id": "d2047", "text": "def rollback(self):\n\t\t\"\"\"\n\t\tRollback MySQL Transaction to database.\n\t\tMySQLDB: If the database and tables support transactions, this rolls \n\t\tback (cancels) the current transaction; otherwise a \n\t\tNotSupportedError is raised.\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 5/12/2008\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif self.connection is not None:\n\t\t\t\tself.connection.rollback()\n\t\t\t\tself._updateCheckTime()\n\t\t\t\tself.release()\n\t\texcept Exception, e:\n\t\t\tpass", "title": ""}
{"_id": "d2048", "text": "def gevent_monkey_patch_report(self):\n        \"\"\"\n        Report effective gevent monkey patching on the logs.\n        \"\"\"\n        try:\n            import gevent.socket\n            import socket\n\n            if gevent.socket.socket is socket.socket:\n                self.log(\"gevent monkey patching is active\")\n                return True\n            else:\n                self.notify_user(\"gevent monkey patching failed.\")\n        except ImportError:\n            self.notify_user(\"gevent is not installed, monkey patching failed.\")\n        return False", "title": ""}
{"_id": "d2049", "text": "def underscore(text):\n    \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n    return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()", "title": ""}
{"_id": "d2050", "text": "def inside_softimage():\n    \"\"\"Returns a boolean indicating if the code is executed 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", "title": ""}
{"_id": "d2051", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d2052", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d2053", "text": "def test_kwargs_are_optional(self):\n        \"\"\"kwarg values always have defaults\"\"\"\n        with patch(\"sys.exit\") as mock_exit:\n            cli = MicroCLITestCase.T(\"script_name f3\".split()).run()\n            # kwargs are optional\n            mock_exit.assert_called_with(4)", "title": ""}
{"_id": "d2054", "text": "def is_valid_row(cls, row):\n        \"\"\"Indicates whether or not the given row contains valid data.\"\"\"\n        for k in row.keys():\n            if row[k] is None:\n                return False\n        return True", "title": ""}
{"_id": "d2055", "text": "def unixtime_to_datetime(ut):\n    \"\"\"Convert a unixtime timestamp to a datetime object.\n    The function converts a timestamp in Unix format to a\n    datetime object. UTC timezone will also be set.\n    :param ut: Unix timestamp to convert\n    :returns: a datetime object\n    :raises InvalidDateError: when the given timestamp cannot be\n        converted into a valid date\n    \"\"\"\n\n    dt = datetime.datetime.utcfromtimestamp(ut)\n    dt = dt.replace(tzinfo=tz.tzutc())\n    return dt", "title": ""}
{"_id": "d2056", "text": "def is_managed():\n    \"\"\"\n    Check if a Django project is being managed with ``manage.py`` or\n    ``django-admin`` scripts\n\n    :return: Check result\n    :rtype: bool\n    \"\"\"\n    for item in sys.argv:\n        if re.search(r'manage.py|django-admin|django', item) is not None:\n            return True\n    return False", "title": ""}
{"_id": "d2057", "text": "def __init__(self,operand,operator,**args):\n        \"\"\"\n        Accepts a NumberGenerator operand, an operator, and\n        optional arguments to be provided to the operator when calling\n        it on the operand.\n        \"\"\"\n        # Note that it's currently not possible to set\n        # parameters in the superclass when creating an instance,\n        # because **args is used by this class itself.\n        super(UnaryOperator,self).__init__()\n\n        self.operand=operand\n        self.operator=operator\n        self.args=args", "title": ""}
{"_id": "d2058", "text": "def _has_fileno(stream):\n    \"\"\"Returns whether the stream object seems to have a working fileno()\n\n    Tells whether _redirect_stderr is likely to work.\n\n    Parameters\n    ----------\n    stream : IO stream object\n\n    Returns\n    -------\n    has_fileno : bool\n        True if stream.fileno() exists and doesn't raise OSError or\n        UnsupportedOperation\n    \"\"\"\n    try:\n        stream.fileno()\n    except (AttributeError, OSError, IOError, io.UnsupportedOperation):\n        return False\n    return True", "title": ""}
{"_id": "d2059", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d2060", "text": "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n    \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n    return maybe_list and any(is_multiline(item) for item in maybe_list)", "title": ""}
{"_id": "d2061", "text": "def read(*args):\n    \"\"\"Reads complete file contents.\"\"\"\n    return io.open(os.path.join(HERE, *args), encoding=\"utf-8\").read()", "title": ""}
{"_id": "d2062", "text": "def table_exists(self, table):\n        \"\"\"Returns whether the given table exists.\n\n           :param table:\n           :type table: BQTable\n        \"\"\"\n        if not self.dataset_exists(table.dataset):\n            return False\n\n        try:\n            self.client.tables().get(projectId=table.project_id,\n                                     datasetId=table.dataset_id,\n                                     tableId=table.table_id).execute()\n        except http.HttpError as ex:\n            if ex.resp.status == 404:\n                return False\n            raise\n\n        return True", "title": ""}
{"_id": "d2063", "text": "def run_func(entry):\n    \"\"\"Runs the function associated with the given MenuEntry.\"\"\"\n    if entry.func:\n        if entry.args and entry.krgs:\n            return entry.func(*entry.args, **entry.krgs)\n        if entry.args:\n            return entry.func(*entry.args)\n        if entry.krgs:\n            return entry.func(**entry.krgs)\n        return entry.func()", "title": ""}
{"_id": "d2064", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d2065", "text": "def peekiter(iterable):\n    \"\"\"Return first row and also iterable with same items as original\"\"\"\n    it = iter(iterable)\n    one = next(it)\n\n    def gen():\n        \"\"\"Generator that returns first and proxy other items from source\"\"\"\n        yield one\n        while True:\n            yield next(it)\n    return (one, gen())", "title": ""}
{"_id": "d2066", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d2067", "text": "def str_ripper(self, text):\n        \"\"\"Got this code from here:\n        http://stackoverflow.com/questions/6116978/python-replace-multiple-strings\n\n        This method takes a set of strings, A, and removes all whole\n        elements of set A from string B.\n\n        Input: text string to strip based on instance attribute self.censor\n        Output: a stripped (censored) text string\n        \"\"\"\n        return self.pattern.sub(lambda m: self.rep[re.escape(m.group(0))], text)", "title": ""}
{"_id": "d2068", "text": "def is_local_url(target):\n    \"\"\"Determine if URL is safe to redirect to.\"\"\"\n    ref_url = urlparse(request.host_url)\n    test_url = urlparse(urljoin(request.host_url, target))\n    return test_url.scheme in ('http', 'https') and \\\n        ref_url.netloc == test_url.netloc", "title": ""}
{"_id": "d2069", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d2070", "text": "def valid_uuid(value):\n    \"\"\" Check if value is a valid UUID. \"\"\"\n\n    try:\n        uuid.UUID(value, version=4)\n        return True\n    except (TypeError, ValueError, AttributeError):\n        return False", "title": ""}
{"_id": "d2071", "text": "def getSystemVariable(self, remote, name):\n        \"\"\"Get single system variable from CCU / Homegear\"\"\"\n        if self._server is not None:\n            return self._server.getSystemVariable(remote, name)", "title": ""}
{"_id": "d2072", "text": "def _is_proper_sequence(seq):\n    \"\"\"Returns is seq is sequence and not string.\"\"\"\n    return (isinstance(seq, collections.abc.Sequence) and\n            not isinstance(seq, str))", "title": ""}
{"_id": "d2073", "text": "def get_data_table(filename):\n  \"\"\"Returns a DataTable instance built from either the filename, or STDIN if filename is None.\"\"\"\n  with get_file_object(filename, \"r\") as rf:\n    return DataTable(list(csv.reader(rf)))", "title": ""}
{"_id": "d2074", "text": "def _is_path(s):\n    \"\"\"Return whether an object is a path.\"\"\"\n    if isinstance(s, string_types):\n        try:\n            return op.exists(s)\n        except (OSError, ValueError):\n            return False\n    else:\n        return False", "title": ""}
{"_id": "d2075", "text": "def paste(xsel=False):\n    \"\"\"Returns system clipboard contents.\"\"\"\n    selection = \"primary\" if xsel else \"clipboard\"\n    try:\n        return subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"utf-8\")\n    except OSError as why:\n        raise XclipNotFound", "title": ""}
{"_id": "d2076", "text": "def is_image(filename):\n    \"\"\"Determine if given filename is an image.\"\"\"\n    # note: isfile() also accepts symlinks\n    return os.path.isfile(filename) and filename.lower().endswith(ImageExts)", "title": ""}
{"_id": "d2077", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d2078", "text": "def list_formatter(handler, item, value):\n    \"\"\"Format list.\"\"\"\n    return u', '.join(str(v) for v in value)", "title": ""}
{"_id": "d2079", "text": "def isnamedtuple(obj):\n    \"\"\"Heuristic check if an object is a namedtuple.\"\"\"\n    return isinstance(obj, tuple) \\\n           and hasattr(obj, \"_fields\") \\\n           and hasattr(obj, \"_asdict\") \\\n           and callable(obj._asdict)", "title": ""}
{"_id": "d2080", "text": "def _text_to_graphiz(self, text):\n        \"\"\"create a graphviz graph from text\"\"\"\n        dot = Source(text, format='svg')\n        return dot.pipe().decode('utf-8')", "title": ""}
{"_id": "d2081", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d2082", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d2083", "text": "def last_modified_date(filename):\n    \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n    mtime = os.path.getmtime(filename)\n    dt = datetime.datetime.utcfromtimestamp(mtime)\n    return dt.replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d2084", "text": "def Bernstein(n, k):\n    \"\"\"Bernstein polynomial.\n\n    \"\"\"\n    coeff = binom(n, k)\n\n    def _bpoly(x):\n        return coeff * x ** k * (1 - x) ** (n - k)\n\n    return _bpoly", "title": ""}
{"_id": "d2085", "text": "def _check_methods(self, methods):\n        \"\"\" @type methods: tuple \"\"\"\n        for method in methods:\n            if method not in self.ALLOWED_METHODS:\n                raise Exception('Invalid \\'%s\\' method' % method)", "title": ""}
{"_id": "d2086", "text": "def timestamp_to_datetime(cls, time_stamp, localized=True):\n        \"\"\" Converts a UTC timestamp to a datetime.datetime.\"\"\"\n        ret = datetime.datetime.utcfromtimestamp(time_stamp)\n        if localized:\n            ret = localize(ret, pytz.utc)\n        return ret", "title": ""}
{"_id": "d2087", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d2088", "text": "def validate(datum, schema, field=None, raise_errors=True):\n    \"\"\"\n    Determine if a python datum is an instance of a schema.\n\n    Parameters\n    ----------\n    datum: Any\n        Data being validated\n    schema: dict\n        Schema\n    field: str, optional\n        Record field being validated\n    raise_errors: bool, optional\n        If true, errors are raised for invalid data. If false, a simple\n        True (valid) or False (invalid) result is returned\n\n\n    Example::\n\n        from fastavro.validation import validate\n        schema = {...}\n        record = {...}\n        validate(record, schema)\n    \"\"\"\n    record_type = extract_record_type(schema)\n    result = None\n\n    validator = VALIDATORS.get(record_type)\n    if validator:\n        result = validator(datum, schema=schema,\n                           parent_ns=field,\n                           raise_errors=raise_errors)\n    elif record_type in SCHEMA_DEFS:\n        result = validate(datum,\n                          schema=SCHEMA_DEFS[record_type],\n                          field=field,\n                          raise_errors=raise_errors)\n    else:\n        raise UnknownType(record_type)\n\n    if raise_errors and result is False:\n        raise ValidationError(ValidationErrorData(datum, schema, field))\n\n    return result", "title": ""}
{"_id": "d2089", "text": "def memory_used(self):\n        \"\"\"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.\n        \"\"\"\n        if self._end_memory:\n            memory_used = self._end_memory - self._start_memory\n            return memory_used\n        else:\n            return None", "title": ""}
{"_id": "d2090", "text": "def __validate_email(self, email):\n        \"\"\"Checks if a string looks like an email address\"\"\"\n\n        e = re.match(self.EMAIL_ADDRESS_REGEX, email, re.UNICODE)\n        if e:\n            return email\n        else:\n            error = \"Invalid email address: \" + str(email)\n            msg = self.GRIMOIRELAB_INVALID_FORMAT % {'error': error}\n            raise InvalidFormatError(cause=msg)", "title": ""}
{"_id": "d2091", "text": "def is_readable_dir(path):\n  \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n  return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d2092", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d2093", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d2094", "text": "def SchemaValidate(self, xsd):\n        \"\"\"Use W3C XSD schema to validate the document as it is\n          processed. Activation is only possible before the first\n          Read(). If @xsd is None, then XML Schema validation is\n           deactivated. \"\"\"\n        ret = libxml2mod.xmlTextReaderSchemaValidate(self._o, xsd)\n        return ret", "title": ""}
{"_id": "d2095", "text": "def arg_bool(name, default=False):\n    \"\"\" Fetch a query argument, as a boolean. \"\"\"\n    v = request.args.get(name, '')\n    if not len(v):\n        return default\n    return v in BOOL_TRUISH", "title": ""}
{"_id": "d2096", "text": "def check_auth(username, pwd):\n    \"\"\"This function is called to check if a username /\n    password combination is valid.\n    \"\"\"\n    cfg = get_current_config()\n    return username == cfg[\"dashboard_httpauth\"].split(\n        \":\")[0] and pwd == cfg[\"dashboard_httpauth\"].split(\":\")[1]", "title": ""}
{"_id": "d2097", "text": "def is_rpm_package_installed(pkg):\n    \"\"\" checks if a particular rpm package is installed \"\"\"\n\n    with settings(hide('warnings', 'running', 'stdout', 'stderr'),\n                  warn_only=True, capture=True):\n\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:   # print error to user\n            print(result)\n            raise SystemExit()", "title": ""}
{"_id": "d2098", "text": "def json_template(data, template_name, template_context):\n    \"\"\"Old style, use JSONTemplateResponse instead of this.\n    \"\"\"\n    html = render_to_string(template_name, template_context)\n    data = data or {}\n    data['html'] = html\n    return HttpResponse(json_encode(data), content_type='application/json')", "title": ""}
{"_id": "d2099", "text": "def issuperset(self, other):\n        \"\"\"Report whether this RangeSet contains another set.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issuperset(self, other)", "title": ""}
{"_id": "d2100", "text": "def dumped(text, level, indent=2):\n    \"\"\"Put curly brackets round an indented text\"\"\"\n    return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "title": ""}
{"_id": "d2101", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d2102", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d2103", "text": "def is_valid_variable_name(string_to_check):\n    \"\"\"\n    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\n    \"\"\"\n\n    try:\n\n        parse('{} = None'.format(string_to_check))\n        return True\n\n    except (SyntaxError, ValueError, TypeError):\n\n        return False", "title": ""}
{"_id": "d2104", "text": "def dumped(text, level, indent=2):\n    \"\"\"Put curly brackets round an indented text\"\"\"\n    return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "title": ""}
{"_id": "d2105", "text": "def is_valid_variable_name(string_to_check):\n    \"\"\"\n    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\n    \"\"\"\n\n    try:\n\n        parse('{} = None'.format(string_to_check))\n        return True\n\n    except (SyntaxError, ValueError, TypeError):\n\n        return False", "title": ""}
{"_id": "d2106", "text": "def _clean_str(self, s):\n        \"\"\" Returns a lowercase string with punctuation and bad chars removed\n        :param s: string to clean\n        \"\"\"\n        return s.translate(str.maketrans('', '', punctuation)).replace('\\u200b', \" \").strip().lower()", "title": ""}
{"_id": "d2107", "text": "def assert_exactly_one_true(bool_list):\n    \"\"\"This method asserts that only one value of the provided list is True.\n\n    :param bool_list: List of booleans to check\n    :return: True if only one value is True, False otherwise\n    \"\"\"\n    assert isinstance(bool_list, list)\n    counter = 0\n    for item in bool_list:\n        if item:\n            counter += 1\n    return counter == 1", "title": ""}
{"_id": "d2108", "text": "def is_empty_object(n, last):\n    \"\"\"n may be the inside of block or object\"\"\"\n    if n.strip():\n        return False\n    # seems to be but can be empty code\n    last = last.strip()\n    markers = {\n        ')',\n        ';',\n    }\n    if not last or last[-1] in markers:\n        return False\n    return True", "title": ""}
{"_id": "d2109", "text": "def is_admin(self):\n        \"\"\"Is the user a system administrator\"\"\"\n        return self.role == self.roles.administrator.value and self.state == State.approved", "title": ""}
{"_id": "d2110", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d2111", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d2112", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d2113", "text": "def cart2pol(x, y):\n    \"\"\"Cartesian to Polar coordinates conversion.\"\"\"\n    theta = np.arctan2(y, x)\n    rho = np.hypot(x, y)\n    return theta, rho", "title": ""}
{"_id": "d2114", "text": "def set_value(self, value):\n        \"\"\"Set value of the checkbox.\n\n        Parameters\n        ----------\n        value : bool\n            value for the checkbox\n\n        \"\"\"\n        if value:\n            self.setChecked(Qt.Checked)\n        else:\n            self.setChecked(Qt.Unchecked)", "title": ""}
{"_id": "d2115", "text": "def install_handle_input(self):\n        \"\"\"Install the hook.\"\"\"\n        self.pointer = self.get_fptr()\n\n        self.hooked = ctypes.windll.user32.SetWindowsHookExA(\n            13,\n            self.pointer,\n            ctypes.windll.kernel32.GetModuleHandleW(None),\n            0\n        )\n        if not self.hooked:\n            return False\n        return True", "title": ""}
{"_id": "d2116", "text": "def __eq__(self, other):\n        \"\"\"Determine if two objects are equal.\"\"\"\n        return isinstance(other, self.__class__) \\\n            and self._freeze() == other._freeze()", "title": ""}
{"_id": "d2117", "text": "def map_wrap(f):\n    \"\"\"Wrap standard function to easily pass into 'map' processing.\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d2118", "text": "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n    \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n    return maybe_list and any(is_multiline(item) for item in maybe_list)", "title": ""}
{"_id": "d2119", "text": "def method(func):\n    \"\"\"Wrap a function as a method.\"\"\"\n    attr = abc.abstractmethod(func)\n    attr.__imethod__ = True\n    return attr", "title": ""}
{"_id": "d2120", "text": "def chmod(f):\n    \"\"\" change mod to writeable \"\"\"\n    try:\n        os.chmod(f, S_IWRITE)  # windows (cover all)\n    except Exception as e:\n        pass\n    try:\n        os.chmod(f, 0o777)  # *nix\n    except Exception as e:\n        pass", "title": ""}
{"_id": "d2121", "text": "def get_ctype(rtype, cfunc, *args):\n    \"\"\" 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\n    \"\"\"\n    val_p = backend.ffi.new(rtype)\n    args = args + (val_p,)\n    cfunc(*args)\n    return val_p[0]", "title": ""}
{"_id": "d2122", "text": "def clean_url(url):\n    \"\"\"\n    Remove params, query and fragment parts from URL so that `os.path.basename`\n    and `os.path.splitext` can work correctly.\n\n    @param url: URL to clean.\n    @type url: str\n\n    @return: Cleaned URL.\n    @rtype: str\n    \"\"\"\n    parsed = urlparse(url.strip())\n    reconstructed = ParseResult(\n        parsed.scheme, parsed.netloc, parsed.path,\n        params='', query='', fragment='')\n    return reconstructed.geturl()", "title": ""}
{"_id": "d2123", "text": "def wrap(string, length, indent):\n    \"\"\" Wrap a string at a line length \"\"\"\n    newline = \"\\n\" + \" \" * indent\n    return newline.join((string[i : i + length] for i in range(0, len(string), length)))", "title": ""}
{"_id": "d2124", "text": "def close_all():\n    \"\"\"Close all open/active plotters\"\"\"\n    for key, p in _ALL_PLOTTERS.items():\n        p.close()\n    _ALL_PLOTTERS.clear()\n    return True", "title": ""}
{"_id": "d2125", "text": "def write_float(self, number):\n        \"\"\" Writes a float to the underlying output file as a 4-byte value. \"\"\"\n        buf = pack(self.byte_order + \"f\", number)\n        self.write(buf)", "title": ""}
{"_id": "d2126", "text": "def _delete_whitespace(self):\n        \"\"\"Delete all whitespace from the end of the line.\"\"\"\n        while isinstance(self._lines[-1], (self._Space, self._LineBreak,\n                                           self._Indent)):\n            del self._lines[-1]", "title": ""}
{"_id": "d2127", "text": "def angle_between_vectors(x, y):\n    \"\"\" Compute the angle between vector x and y \"\"\"\n    dp = dot_product(x, y)\n    if dp == 0:\n        return 0\n    xm = magnitude(x)\n    ym = magnitude(y)\n    return math.acos(dp / (xm*ym)) * (180. / math.pi)", "title": ""}
{"_id": "d2128", "text": "def socket_close(self):\n        \"\"\"Close our socket.\"\"\"\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET", "title": ""}
{"_id": "d2129", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d2130", "text": "def _close_websocket(self):\n        \"\"\"Closes the websocket connection.\"\"\"\n        close_method = getattr(self._websocket, \"close\", None)\n        if callable(close_method):\n            asyncio.ensure_future(close_method(), loop=self._event_loop)\n        self._websocket = None\n        self._dispatch_event(event=\"close\")", "title": ""}
{"_id": "d2131", "text": "def pickle_data(data, picklefile):\n    \"\"\"Helper function to pickle `data` in `picklefile`.\"\"\"\n    with open(picklefile, 'wb') as f:\n        pickle.dump(data, f, protocol=2)", "title": ""}
{"_id": "d2132", "text": "def fit_select_best(X, y):\n    \"\"\"\n    Selects the best fit of the estimators already implemented by choosing the\n    model with the smallest mean square error metric for the trained values.\n    \"\"\"\n    models = [fit(X,y) for fit in [fit_linear, fit_quadratic]]\n    errors = map(lambda model: mse(y, model.predict(X)), models)\n\n    return min(zip(models, errors), key=itemgetter(1))[0]", "title": ""}
{"_id": "d2133", "text": "def softmax(attrs, inputs, proto_obj):\n    \"\"\"Softmax function.\"\"\"\n    if 'axis' not in attrs:\n        attrs = translation_utils._add_extra_attributes(attrs, {'axis': 1})\n    return 'softmax', attrs, inputs", "title": ""}
{"_id": "d2134", "text": "def filtered_image(self, im):\n        \"\"\"Returns a filtered image after applying the Fourier-space filters\"\"\"\n        q = np.fft.fftn(im)\n        for k,v in self.filters:\n            q[k] -= v\n        return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d2135", "text": "def disable_wx(self):\n        \"\"\"Disable event loop integration with wxPython.\n\n        This merely sets PyOS_InputHook to NULL.\n        \"\"\"\n        if self._apps.has_key(GUI_WX):\n            self._apps[GUI_WX]._in_event_loop = False\n        self.clear_inputhook()", "title": ""}
{"_id": "d2136", "text": "def underline(self, msg):\n        \"\"\"Underline the input\"\"\"\n        return click.style(msg, underline=True) if self.colorize else msg", "title": ""}
{"_id": "d2137", "text": "def on_close(self, evt):\n    \"\"\"\n    Pop-up menu and wx.EVT_CLOSE closing event\n    \"\"\"\n    self.stop() # DoseWatcher\n    if evt.EventObject is not self: # Avoid deadlocks\n      self.Close() # wx.Frame\n    evt.Skip()", "title": ""}
{"_id": "d2138", "text": "def afx_small():\n  \"\"\"Small transformer model with small batch size for fast step times.\"\"\"\n  hparams = transformer.transformer_tpu()\n  hparams.filter_size = 1024\n  hparams.num_heads = 4\n  hparams.num_hidden_layers = 3\n  hparams.batch_size = 512\n  return hparams", "title": ""}
{"_id": "d2139", "text": "def restore_scrollbar_position(self):\n        \"\"\"Restoring scrollbar position after main window is visible\"\"\"\n        scrollbar_pos = self.get_option('scrollbar_position', None)\n        if scrollbar_pos is not None:\n            self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)", "title": ""}
{"_id": "d2140", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d2141", "text": "def series_table_row_offset(self, series):\n        \"\"\"\n        Return the number of rows preceding the data table for *series* in\n        the Excel worksheet.\n        \"\"\"\n        title_and_spacer_rows = series.index * 2\n        data_point_rows = series.data_point_offset\n        return title_and_spacer_rows + data_point_rows", "title": ""}
{"_id": "d2142", "text": "def is_valid_image_extension(file_path):\n    \"\"\"is_valid_image_extension.\"\"\"\n    valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']\n    _, extension = os.path.splitext(file_path)\n    return extension.lower() in valid_extensions", "title": ""}
{"_id": "d2143", "text": "def getChildElementsByTagName(self, tagName):\n    \"\"\" Return child elements of type tagName if found, else [] \"\"\"\n    result = []\n    for child in self.childNodes:\n        if isinstance(child, Element):\n            if child.tagName == tagName:\n                result.append(child)\n    return result", "title": ""}
{"_id": "d2144", "text": "def mcc(y_true, y_pred, round=True):\n    \"\"\"Matthews correlation coefficient\n    \"\"\"\n    y_true, y_pred = _mask_value_nan(y_true, y_pred)\n    if round:\n        y_true = np.round(y_true)\n        y_pred = np.round(y_pred)\n    return skm.matthews_corrcoef(y_true, y_pred)", "title": ""}
{"_id": "d2145", "text": "def kernelDriverActive(self, interface):\n        \"\"\"\n        Tell whether a kernel driver is active on given interface number.\n        \"\"\"\n        result = libusb1.libusb_kernel_driver_active(self.__handle, interface)\n        if result == 0:\n            return False\n        elif result == 1:\n            return True\n        raiseUSBError(result)", "title": ""}
{"_id": "d2146", "text": "def schemaValidateFile(self, filename, options):\n        \"\"\"Do a schemas validation of the given resource, it will use\n           the SAX streamable validation internally. \"\"\"\n        ret = libxml2mod.xmlSchemaValidateFile(self._o, filename, options)\n        return ret", "title": ""}
{"_id": "d2147", "text": "def clear_globals_reload_modules(self):\n        \"\"\"Clears globals and reloads modules\"\"\"\n\n        self.code_array.clear_globals()\n        self.code_array.reload_modules()\n\n        # Clear result cache\n        self.code_array.result_cache.clear()", "title": ""}
{"_id": "d2148", "text": "def prox_zero(X, step):\n    \"\"\"Proximal operator to project onto zero\n    \"\"\"\n    return np.zeros(X.shape, dtype=X.dtype)", "title": ""}
{"_id": "d2149", "text": "def count_rows(self, table_name):\n        \"\"\"Return the number of entries in a table by counting them.\"\"\"\n        self.table_must_exist(table_name)\n        query = \"SELECT COUNT (*) FROM `%s`\" % table_name.lower()\n        self.own_cursor.execute(query)\n        return int(self.own_cursor.fetchone()[0])", "title": ""}
{"_id": "d2150", "text": "def mkdir(dir, enter):\n    \"\"\"Create directory with template for topic of the current environment\n\n    \"\"\"\n\n    if not os.path.exists(dir):\n        os.makedirs(dir)", "title": ""}
{"_id": "d2151", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d2152", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d2153", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d2154", "text": "def cleanup_lib(self):\n        \"\"\" unload the previously loaded shared library \"\"\"\n        if not self.using_openmp:\n            #this if statement is necessary because shared libraries that use\n            #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP\n            logging.debug('unloading shared library')\n            _ctypes.dlclose(self.lib._handle)", "title": ""}
{"_id": "d2155", "text": "def negate(self):\n        \"\"\"Reverse the range\"\"\"\n        self.from_value, self.to_value = self.to_value, self.from_value\n        self.include_lower, self.include_upper = self.include_upper, self.include_lower", "title": ""}
{"_id": "d2156", "text": "def cfloat32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n        return np.fromiter(cptr, dtype=np.float32, count=length)\n    else:\n        raise RuntimeError('Expected float pointer')", "title": ""}
{"_id": "d2157", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d2158", "text": "def cint8_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):\n        return np.fromiter(cptr, dtype=np.int8, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d2159", "text": "def get_resource_attribute(self, attr):\n        \"\"\"Gets the resource attribute if available\n\n        :param attr: Name of the attribute\n        :return: Value of the attribute, if set in the resource. None otherwise\n        \"\"\"\n        if attr not in self.resource_attributes:\n            raise KeyError(\"%s is not in resource attributes\" % attr)\n\n        return self.resource_attributes[attr]", "title": ""}
{"_id": "d2160", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d2161", "text": "def run(self):\n        \"\"\"Run the event loop.\"\"\"\n        self.signal_init()\n        self.listen_init()\n        self.logger.info('starting')\n        self.loop.start()", "title": ""}
{"_id": "d2162", "text": "def _ram_buffer(self):\n        \"\"\"Setup the RAM buffer from the C++ code.\"\"\"\n        # get the address of the RAM\n        address = _LIB.Memory(self._env)\n        # create a buffer from the contents of the address location\n        buffer_ = ctypes.cast(address, ctypes.POINTER(RAM_VECTOR)).contents\n        # create a NumPy array from the buffer\n        return np.frombuffer(buffer_, dtype='uint8')", "title": ""}
{"_id": "d2163", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d2164", "text": "def cumsum(inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1, len(newlist)):\n        newlist[i] = newlist[i] + newlist[i - 1]\n    return newlist", "title": ""}
{"_id": "d2165", "text": "def __consistent_isoformat_utc(datetime_val):\n        \"\"\"\n        Function that does what isoformat does but it actually does the same\n        every time instead of randomly doing different things on some systems\n        and also it represents that time as the equivalent UTC time.\n        \"\"\"\n        isotime = datetime_val.astimezone(pytz.utc).strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n        if isotime[-2] != \":\":\n            isotime = isotime[:-2] + \":\" + isotime[-2:]\n        return isotime", "title": ""}
{"_id": "d2166", "text": "def _swap_curly(string):\n    \"\"\"Swap single and double curly brackets\"\"\"\n    return (\n        string.replace('{{ ', '{{').replace('{{', '\\x00').replace('{', '{{')\n        .replace('\\x00', '{').replace(' }}', '}}').replace('}}', '\\x00')\n        .replace('}', '}}').replace('\\x00', '}')\n    )", "title": ""}
{"_id": "d2167", "text": "def _int64_feature(value):\n  \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))", "title": ""}
{"_id": "d2168", "text": "def now_time(str=False):\n    \"\"\"Get the current time.\"\"\"\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()", "title": ""}
{"_id": "d2169", "text": "def _do_auto_predict(machine, X, *args):\n    \"\"\"Performs an automatic prediction for the specified machine and returns\n    the predicted values.\n    \"\"\"\n    if auto_predict and hasattr(machine, \"predict\"):\n        return machine.predict(X)", "title": ""}
{"_id": "d2170", "text": "def home(self):\n        \"\"\"Set cursor to initial position and reset any shifting.\"\"\"\n        self.command(c.LCD_RETURNHOME)\n        self._cursor_pos = (0, 0)\n        c.msleep(2)", "title": ""}
{"_id": "d2171", "text": "def _getTypename(self, defn):\n        \"\"\" Returns the SQL typename required to store the given FieldDefinition \"\"\"\n        return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'", "title": ""}
{"_id": "d2172", "text": "def INIT_LIST_EXPR(self, cursor):\n        \"\"\"Returns a list of literal values.\"\"\"\n        values = [self.parse_cursor(child)\n                  for child in list(cursor.get_children())]\n        return values", "title": ""}
{"_id": "d2173", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d2174", "text": "def json_serial(obj):\n    \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n    if isinstance(obj, LegipyModel):\n        return obj.to_json()\n    elif isinstance(obj, (datetime.date, datetime.datetime)):\n        return obj.isoformat()\n    raise TypeError(\"Type {0} not serializable\".format(repr(type(obj))))", "title": ""}
{"_id": "d2175", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d2176", "text": "def cio_close(cio):\n    \"\"\"Wraps openjpeg library function cio_close.\n    \"\"\"\n    OPENJPEG.opj_cio_close.argtypes = [ctypes.POINTER(CioType)]\n    OPENJPEG.opj_cio_close(cio)", "title": ""}
{"_id": "d2177", "text": "def remove_trailing_string(content, trailing):\n    \"\"\"\n    Strip trailing component `trailing` from `content` if it exists.\n    Used when generating names from view classes.\n    \"\"\"\n    if content.endswith(trailing) and content != trailing:\n        return content[:-len(trailing)]\n    return content", "title": ""}
{"_id": "d2178", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d2179", "text": "def format_vars(args):\n    \"\"\"Format the given vars in the form: 'flag=value'\"\"\"\n    variables = []\n    for key, value in args.items():\n        if value:\n            variables += ['{0}={1}'.format(key, value)]\n    return variables", "title": ""}
{"_id": "d2180", "text": "def kill_dashboard(self, check_alive=True):\n        \"\"\"Kill the dashboard.\n\n        Args:\n            check_alive (bool): Raise an exception if the process was already\n                dead.\n        \"\"\"\n        self._kill_process_type(\n            ray_constants.PROCESS_TYPE_DASHBOARD, check_alive=check_alive)", "title": ""}
{"_id": "d2181", "text": "def cat_acc(y_true, y_pred):\n    \"\"\"Categorical accuracy\n    \"\"\"\n    return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))", "title": ""}
{"_id": "d2182", "text": "def string_to_date(value):\n    \"\"\"\n    Return a Python date that corresponds to the specified string\n    representation.\n\n    @param value: string representation of a date.\n\n    @return: an instance ``datetime.datetime`` represented by the string.\n    \"\"\"\n    if isinstance(value, datetime.date):\n        return value\n\n    return dateutil.parser.parse(value).date()", "title": ""}
{"_id": "d2183", "text": "def softplus(attrs, inputs, proto_obj):\n    \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs", "title": ""}
{"_id": "d2184", "text": "def isoformat(dt):\n    \"\"\"Return an ISO-8601 formatted string from the provided datetime object\"\"\"\n    if not isinstance(dt, datetime.datetime):\n        raise TypeError(\"Must provide datetime.datetime object to isoformat\")\n\n    if dt.tzinfo is None:\n        raise ValueError(\"naive datetime objects are not allowed beyond the library boundaries\")\n\n    return dt.isoformat().replace(\"+00:00\", \"Z\")", "title": ""}
{"_id": "d2185", "text": "def print_with_header(header, message, color, indent=0):\n    \"\"\"\n    Use one of the functions below for printing, not this one.\n    \"\"\"\n    print()\n    padding = ' ' * indent\n    print(padding + color + BOLD + header + ENDC + color + message + ENDC)", "title": ""}
{"_id": "d2186", "text": "def from_timestamp(microsecond_timestamp):\n    \"\"\"Convert a microsecond timestamp to a UTC datetime instance.\"\"\"\n    # Create datetime without losing precision from floating point (yes, this\n    # is actually needed):\n    return datetime.datetime.fromtimestamp(\n        microsecond_timestamp // 1000000, datetime.timezone.utc\n    ).replace(microsecond=(microsecond_timestamp % 1000000))", "title": ""}
{"_id": "d2187", "text": "def calculate_top_margin(self):\n\t\t\"\"\"\n\t\tCalculate the margin in pixels above the plot area, setting\n\t\tborder_top.\n\t\t\"\"\"\n\t\tself.border_top = 5\n\t\tif self.show_graph_title:\n\t\t\tself.border_top += self.title_font_size\n\t\tself.border_top += 5\n\t\tif self.show_graph_subtitle:\n\t\t\tself.border_top += self.subtitle_font_size", "title": ""}
{"_id": "d2188", "text": "def timestamp_from_datetime(dt):\n    \"\"\"\n    Compute timestamp from a datetime object that could be timezone aware\n    or unaware.\n    \"\"\"\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())", "title": ""}
{"_id": "d2189", "text": "def calculate_top_margin(self):\n\t\t\"\"\"\n\t\tCalculate the margin in pixels above the plot area, setting\n\t\tborder_top.\n\t\t\"\"\"\n\t\tself.border_top = 5\n\t\tif self.show_graph_title:\n\t\t\tself.border_top += self.title_font_size\n\t\tself.border_top += 5\n\t\tif self.show_graph_subtitle:\n\t\t\tself.border_top += self.subtitle_font_size", "title": ""}
{"_id": "d2190", "text": "def _DateToEpoch(date):\n  \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n  tz_zero = datetime.datetime.utcfromtimestamp(0)\n  diff_sec = int((date - tz_zero).total_seconds())\n  return diff_sec * 1000000", "title": ""}
{"_id": "d2191", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d2192", "text": "def created_today(self):\n        \"\"\"Return True if created today.\"\"\"\n        if self.datetime.date() == datetime.today().date():\n            return True\n        return False", "title": ""}
{"_id": "d2193", "text": "def monthly(date=datetime.date.today()):\n    \"\"\"\n    Take a date object and return the first day of the month.\n    \"\"\"\n    return datetime.date(date.year, date.month, 1)", "title": ""}
{"_id": "d2194", "text": "def update_dict(obj, dict, attributes):\n    \"\"\"Update dict with fields from obj.attributes.\n\n    :param obj: the object updated into dict\n    :param dict: the result dictionary\n    :param attributes: a list of attributes belonging to obj\n    \"\"\"\n    for attribute in attributes:\n        if hasattr(obj, attribute) and getattr(obj, attribute) is not None:\n            dict[attribute] = getattr(obj, attribute)", "title": ""}
{"_id": "d2195", "text": "def _default(self, obj):\n        \"\"\" return a serialized version of obj or raise a TypeError\n\n        :param obj:\n        :return: Serialized version of obj\n        \"\"\"\n        return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj)", "title": ""}
{"_id": "d2196", "text": "def getpackagepath():\n    \"\"\"\n     *Get the root path for this python package - used in unit testing code*\n    \"\"\"\n    moduleDirectory = os.path.dirname(__file__)\n    packagePath = os.path.dirname(__file__) + \"/../\"\n\n    return packagePath", "title": ""}
{"_id": "d2197", "text": "def print_args(output=sys.stdout):\n    \"\"\"Decorate a function so that print arguments before calling it.\n\n    Args:\n      output: writable to print args. (Default: sys.stdout)\n    \"\"\"\n    def decorator(func):\n        \"\"\"The decorator function.\n        \"\"\"\n        @wraps(func)\n        def _(*args, **kwargs):\n            \"\"\"The decorated function.\n            \"\"\"\n            output.write(\n                \"Args: {0}, KwArgs: {1}\\n\".format(str(args), str(kwargs)))\n            return func(*args, **kwargs)\n        return _\n    return decorator", "title": ""}
{"_id": "d2198", "text": "def __add__(self,other):\n        \"\"\"\n            If the number of columns matches, we can concatenate two LabeldMatrices\n            with the + operator.\n        \"\"\"\n        assert self.matrix.shape[1] == other.matrix.shape[1]\n        return LabeledMatrix(np.concatenate([self.matrix,other.matrix],axis=0),self.labels)", "title": ""}
{"_id": "d2199", "text": "def pretty_dict_string(d, indent=0):\n    \"\"\"Pretty output of nested dictionaries.\n    \"\"\"\n    s = ''\n    for key, value in sorted(d.items()):\n        s += '    ' * indent + str(key)\n        if isinstance(value, dict):\n             s += '\\n' + pretty_dict_string(value, indent+1)\n        else:\n             s += '=' + str(value) + '\\n'\n    return s", "title": ""}
{"_id": "d2200", "text": "def is_int(value):\n    \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n    if isinstance(value, bool):\n        return False\n    try:\n        int(value)\n        return True\n    except (ValueError, TypeError):\n        return False", "title": ""}
{"_id": "d2201", "text": "def generator_to_list(fn):\n    \"\"\"This decorator is for flat_list function.\n    It converts returned generator to list.\n    \"\"\"\n    def wrapper(*args, **kw):\n        return list(fn(*args, **kw))\n    return wrapper", "title": ""}
{"_id": "d2202", "text": "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig", "title": ""}
{"_id": "d2203", "text": "def Square(x, a, b, c):\n    \"\"\"Second order polynomial\n\n    Inputs:\n    -------\n        ``x``: independent variable\n        ``a``: coefficient of the second-order term\n        ``b``: coefficient of the first-order term\n        ``c``: additive constant\n\n    Formula:\n    --------\n        ``a*x^2 + b*x + c``\n    \"\"\"\n    return a * x ** 2 + b * x + c", "title": ""}
{"_id": "d2204", "text": "def vec_angle(a, b):\n    \"\"\"\n    Calculate angle between two vectors\n    \"\"\"\n    cosang = np.dot(a, b)\n    sinang = fast_norm(np.cross(a, b))\n    return np.arctan2(sinang, cosang)", "title": ""}
{"_id": "d2205", "text": "def parameter_vector(self):\n        \"\"\"An array of all parameters (including frozen parameters)\"\"\"\n        return np.array([getattr(self, k) for k in self.parameter_names])", "title": ""}
{"_id": "d2206", "text": "def position(self, x, y, text):\n        \"\"\"\n            ANSI Escape sequences\n            http://ascii-table.com/ansi-escape-sequences.php\n        \"\"\"\n        sys.stdout.write(\"\\x1b7\\x1b[%d;%df%s\\x1b8\" % (x, y, text))\n        sys.stdout.flush()", "title": ""}
{"_id": "d2207", "text": "def del_label(self, name):\n        \"\"\"Delete a label by name.\"\"\"\n        labels_tag = self.root[0]\n        labels_tag.remove(self._find_label(name))", "title": ""}
{"_id": "d2208", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d2209", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d2210", "text": "def transform(self, df):\n        \"\"\"\n        Transforms a DataFrame in place. Computes all outputs of the DataFrame.\n\n        Args:\n            df (pandas.DataFrame): DataFrame to transform.\n        \"\"\"\n        for name, function in self.outputs:\n            df[name] = function(df)", "title": ""}
{"_id": "d2211", "text": "def delete(self, name):\n        \"\"\"Delete object on remote\"\"\"\n        obj = self._get_object(name)\n        if obj:\n            return self.driver.delete_object(obj)", "title": ""}
{"_id": "d2212", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d2213", "text": "def desc(self):\n        \"\"\"Get a short description of the device.\"\"\"\n        return '{0} (ID: {1}) - {2} - {3}'.format(\n            self.name, self.device_id, self.type, self.status)", "title": ""}
{"_id": "d2214", "text": "def filter(self, obj, *args, **kwargs):\n        \"\"\"\n        Filter the given object through the filter chain.\n\n        :param obj: The object to filter\n        :param args: Additional arguments to pass to each filter function.\n        :param kwargs: Additional keyword arguments to pass to each filter\n                       function.\n        :return: The filtered object or :data:`None`\n\n        See the documentation of :class:`Filter` on how filtering operates.\n\n        Returns the object returned by the last function in the filter chain or\n        :data:`None` if any function returned :data:`None`.\n        \"\"\"\n        for _, _, func in self._filter_order:\n            obj = func(obj, *args, **kwargs)\n            if obj is None:\n                return None\n        return obj", "title": ""}
{"_id": "d2215", "text": "def fft(t, y, pow2=False, window=None, rescale=False):\n    \"\"\"\n    FFT of y, assuming complex or real-valued inputs. This goes through the \n    numpy fourier transform process, assembling and returning (frequencies, \n    complex fft) given time and signal data y.\n\n    Parameters\n    ----------\n    t,y\n        Time (t) and signal (y) arrays with which to perform the fft. Note the t\n        array is assumed to be evenly spaced.\n        \n    pow2 = False\n        Set this to true if you only want to keep the first 2^n data\n        points (speeds up the FFT substantially)\n\n    window = None\n        Can be set to any of the windowing functions in numpy that require only\n        the number of points as the argument, e.g. window='hanning'. \n        \n    rescale = False\n        If True, the FFT will be rescaled by the square root of the ratio of \n        variances before and after windowing, such that the sum of component \n        amplitudes squared is equal to the actual variance.\n    \"\"\"\n    # make sure they're numpy arrays, and make copies to avoid the referencing error\n    y = _n.array(y)\n    t = _n.array(t)\n\n    # if we're doing the power of 2, do it\n    if pow2:\n        keep  = 2**int(_n.log2(len(y)))\n\n        # now resize the data\n        y.resize(keep)\n        t.resize(keep)\n\n    # Window the data\n    if not window in [None, False, 0]:\n        try:\n            # Get the windowing array\n            w = eval(\"_n.\"+window, dict(_n=_n))(len(y))\n            \n            # Store the original variance\n            v0 = _n.average(abs(y)**2)\n            \n            # window the time domain data \n            y = y * w\n            \n            # Rescale by the variance ratio\n            if rescale: y = y * _n.sqrt(v0 / _n.average(abs(y)**2))\n            \n        except:\n            print(\"ERROR: Bad window!\")\n            return\n\n    # do the actual fft, and normalize\n    Y = _n.fft.fftshift( _n.fft.fft(y) / len(t) )\n    f = _n.fft.fftshift( _n.fft.fftfreq(len(t), t[1]-t[0]) )\n    \n    return f, Y", "title": ""}
{"_id": "d2216", "text": "def dictapply(d, fn):\n    \"\"\"\n    apply a function to all non-dict values in a dictionary\n    \"\"\"\n    for k, v in d.items():\n        if isinstance(v, dict):\n            v = dictapply(v, fn)\n        else:\n            d[k] = fn(v)\n    return d", "title": ""}
{"_id": "d2217", "text": "def _update_index_on_df(df, index_names):\n    \"\"\"Helper function to restore index information after collection. Doesn't\n    use self so we can serialize this.\"\"\"\n    if index_names:\n        df = df.set_index(index_names)\n        # Remove names from unnamed indexes\n        index_names = _denormalize_index_names(index_names)\n        df.index.names = index_names\n    return df", "title": ""}
{"_id": "d2218", "text": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "title": ""}
{"_id": "d2219", "text": "def guess_encoding(text, default=DEFAULT_ENCODING):\n    \"\"\"Guess string encoding.\n\n    Given a piece of text, apply character encoding detection to\n    guess the appropriate encoding of the text.\n    \"\"\"\n    result = chardet.detect(text)\n    return normalize_result(result, default=default)", "title": ""}
{"_id": "d2220", "text": "def guess_encoding(text, default=DEFAULT_ENCODING):\n    \"\"\"Guess string encoding.\n\n    Given a piece of text, apply character encoding detection to\n    guess the appropriate encoding of the text.\n    \"\"\"\n    result = chardet.detect(text)\n    return normalize_result(result, default=default)", "title": ""}
{"_id": "d2221", "text": "def build_and_start(query, directory):\n    \"\"\"This function will create and then start a new Async task with the\n    default callbacks argument defined in the decorator.\"\"\"\n\n    Async(target=grep, args=[query, directory]).start()", "title": ""}
{"_id": "d2222", "text": "def _string_width(self, s):\n        \"\"\"Get width of a string in the current font\"\"\"\n        s = str(s)\n        w = 0\n        for char in s:\n            char = ord(char)\n            w += self.character_widths[char]\n        return w * self.font_size / 1000.0", "title": ""}
{"_id": "d2223", "text": "def _mean_dict(dict_list):\n    \"\"\"Compute the mean value across a list of dictionaries\n    \"\"\"\n    return {k: np.array([d[k] for d in dict_list]).mean()\n            for k in dict_list[0].keys()}", "title": ""}
{"_id": "d2224", "text": "def _get_column_types(self, data):\n        \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n        columns = list(zip_longest(*data))\n        return [self._get_column_type(column) for column in columns]", "title": ""}
{"_id": "d2225", "text": "def lambda_from_file(python_file):\n    \"\"\"\n    Reads a python file and returns a awslambda.Code object\n    :param python_file:\n    :return:\n    \"\"\"\n    lambda_function = []\n    with open(python_file, 'r') as f:\n        lambda_function.extend(f.read().splitlines())\n\n    return awslambda.Code(ZipFile=(Join('\\n', lambda_function)))", "title": ""}
{"_id": "d2226", "text": "def __contains__(self, key):\n        \"\"\"\n        Invoked when determining whether a specific key is in the dictionary\n        using `key in d`.\n\n        The key is looked up case-insensitively.\n        \"\"\"\n        k = self._real_key(key)\n        return k in self._data", "title": ""}
{"_id": "d2227", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d2228", "text": "def is_subdir(a, b):\n    \"\"\"\n    Return true if a is a subdirectory of b\n    \"\"\"\n    a, b = map(os.path.abspath, [a, b])\n\n    return os.path.commonpath([a, b]) == b", "title": ""}
{"_id": "d2229", "text": "def seaborn_bar_(self, label=None, style=None, opts=None):\n        \"\"\"\n        Get a Seaborn bar chart\n        \"\"\"\n        try:\n            fig = sns.barplot(self.x, self.y, palette=\"BuGn_d\")\n            return fig\n        except Exception as e:\n            self.err(e, self.seaborn_bar_,\n                     \"Can not get Seaborn bar chart object\")", "title": ""}
{"_id": "d2230", "text": "def getFileDialogTitle(msg, title):\n    \"\"\"\n    Create nicely-formatted string based on arguments msg and title\n    :param msg: the msg to be displayed\n    :param title: the window title\n    :return: None\n    \"\"\"\n    if msg and title:\n        return \"%s - %s\" % (title, msg)\n    if msg and not title:\n        return str(msg)\n    if title and not msg:\n        return str(title)\n    return None", "title": ""}
{"_id": "d2231", "text": "def img_encode(arr, **kwargs):\n    \"\"\"Encode ndarray to base64 string image data\n    \n    Parameters\n    ----------\n    arr: ndarray (rows, cols, depth)\n    kwargs: passed directly to matplotlib.image.imsave\n    \"\"\"\n    sio = BytesIO()\n    imsave(sio, arr, **kwargs)\n    sio.seek(0)\n    img_format = kwargs['format'] if kwargs.get('format') else 'png'\n    img_str = base64.b64encode(sio.getvalue()).decode()\n\n    return 'data:image/{};base64,{}'.format(img_format, img_str)", "title": ""}
{"_id": "d2232", "text": "def _check_conversion(key, valid_dict):\n    \"\"\"Check for existence of key in dict, return value or raise error\"\"\"\n    if key not in valid_dict and key not in valid_dict.values():\n        # Only show users the nice string values\n        keys = [v for v in valid_dict.keys() if isinstance(v, string_types)]\n        raise ValueError('value must be one of %s, not %s' % (keys, key))\n    return valid_dict[key] if key in valid_dict else key", "title": ""}
{"_id": "d2233", "text": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d2234", "text": "def get_single_item(d):\n    \"\"\"Get an item from a dict which contains just one item.\"\"\"\n    assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)\n    return next(six.iteritems(d))", "title": ""}
{"_id": "d2235", "text": "def is_int(value):\n    \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n    if isinstance(value, bool):\n        return False\n    try:\n        int(value)\n        return True\n    except (ValueError, TypeError):\n        return False", "title": ""}
{"_id": "d2236", "text": "def dictmerge(x, y):\n    \"\"\"\n    merge two dictionaries\n    \"\"\"\n    z = x.copy()\n    z.update(y)\n    return z", "title": ""}
{"_id": "d2237", "text": "def bounding_box_from(points, i, i1, thr):\n    \"\"\"Creates bounding box for a line segment\n\n    Args:\n        points (:obj:`list` of :obj:`Point`)\n        i (int): Line segment start, index in points array\n        i1 (int): Line segment end, index in points array\n    Returns:\n        (float, float, float, float): with bounding box min x, min y, max x and max y\n    \"\"\"\n    pi = points[i]\n    pi1 = points[i1]\n\n    min_lat = min(pi.lat, pi1.lat)\n    min_lon = min(pi.lon, pi1.lon)\n    max_lat = max(pi.lat, pi1.lat)\n    max_lon = max(pi.lon, pi1.lon)\n\n    return min_lat-thr, min_lon-thr, max_lat+thr, max_lon+thr", "title": ""}
{"_id": "d2238", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d2239", "text": "def swap(self):\n        \"\"\"Return the box (for horizontal graphs)\"\"\"\n        self.xmin, self.ymin = self.ymin, self.xmin\n        self.xmax, self.ymax = self.ymax, self.xmax", "title": ""}
{"_id": "d2240", "text": "def itervalues(d, **kw):\n    \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n    if not PY2:\n        return iter(d.values(**kw))\n    return d.itervalues(**kw)", "title": ""}
{"_id": "d2241", "text": "def tob(data, enc='utf8'):\n    \"\"\" Convert anything to bytes \"\"\"\n    return data.encode(enc) if isinstance(data, six.text_type) else bytes(data)", "title": ""}
{"_id": "d2242", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d2243", "text": "def CleanseComments(line):\n  \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n  Args:\n    line: A line of C++ source.\n\n  Returns:\n    The line with single-line comments removed.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1 and not IsCppString(line[:commentpos]):\n    line = line[:commentpos].rstrip()\n  # get rid of /* ... */\n  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "title": ""}
{"_id": "d2244", "text": "def set_history_file(self, path):\n        \"\"\"Set path to history file. \"\" produces no file.\"\"\"\n        if path:\n            self.history = prompt_toolkit.history.FileHistory(fixpath(path))\n        else:\n            self.history = prompt_toolkit.history.InMemoryHistory()", "title": ""}
{"_id": "d2245", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d2246", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d2247", "text": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "title": ""}
{"_id": "d2248", "text": "def type_converter(text):\n    \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n    if text.isdigit():\n        return int(text), int\n\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE", "title": ""}
{"_id": "d2249", "text": "def array_bytes(array):\n    \"\"\" Estimates the memory of the supplied array in bytes \"\"\"\n    return np.product(array.shape)*np.dtype(array.dtype).itemsize", "title": ""}
{"_id": "d2250", "text": "def chunks(arr, size):\n    \"\"\"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`\n    \"\"\"\n    for i in _range(0, len(arr), size):\n        yield arr[i:i+size]", "title": ""}
{"_id": "d2251", "text": "def Distance(lat1, lon1, lat2, lon2):\n    \"\"\"Get distance between pairs of lat-lon points\"\"\"\n\n    az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)\n    return az21, dist", "title": ""}
{"_id": "d2252", "text": "def set_value(self, value):\n        \"\"\"Set value of the checkbox.\n\n        Parameters\n        ----------\n        value : bool\n            value for the checkbox\n\n        \"\"\"\n        if value:\n            self.setCheckState(Qt.Checked)\n        else:\n            self.setCheckState(Qt.Unchecked)", "title": ""}
{"_id": "d2253", "text": "def average(arr):\n  \"\"\"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\n\n  \"\"\"\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))", "title": ""}
{"_id": "d2254", "text": "def set_locale(request):\n    \"\"\"Return locale from GET lang param or automatically.\"\"\"\n    return request.query.get('lang', app.ps.babel.select_locale_by_request(request))", "title": ""}
{"_id": "d2255", "text": "def elapsed_time_from(start_time):\n    \"\"\"calculate time delta from latched time and current 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", "title": ""}
{"_id": "d2256", "text": "def getMaxAffiliationInstanceID():\n    \"\"\"\n\n    Returns\n    -------\n    maximum value of the Primary key from the table \"django-tethne_affiliation_instance\"\n    This is used to calculate the next id for primary key.\n\n    if the table is empty, 0 is returned\n\n    \"\"\"\n    dbconnectionhanlder = DBConnection()\n    dbconnectionhanlder.cursor.execute(\"SELECT max(id) from `django-tethne_affiliation_instance`\")\n    rows = dbconnectionhanlder.cursor.fetchall()\n    dbconnectionhanlder.conn.close()\n    if rows[0][0] is None:\n        return 0\n    else:\n        return rows[0][0]", "title": ""}
{"_id": "d2257", "text": "def var(series):\n    \"\"\"\n    Returns the variance of values in a series.\n\n    Args:\n        series (pandas.Series): column to summarize.\n    \"\"\"\n    if np.issubdtype(series.dtype, np.number):\n        return series.var()\n    else:\n        return np.nan", "title": ""}
{"_id": "d2258", "text": "def handle_m2m_user(self, sender, instance, **kwargs):\n    \"\"\" Handle many to many relationships for user field \"\"\"\n    self.handle_save(instance.user.__class__, instance.user)", "title": ""}
{"_id": "d2259", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d2260", "text": "def maxId(self):\n        \"\"\"int: current max id of objects\"\"\"\n        if len(self.model.db) == 0:\n            return 0\n\n        return max(map(lambda obj: obj[\"id\"], self.model.db))", "title": ""}
{"_id": "d2261", "text": "def lsem (inlist):\n    \"\"\"\nReturns the estimated standard error of the mean (sx-bar) of the\nvalues in the passed list.  sem = stdev / sqrt(n)\n\nUsage:   lsem(inlist)\n\"\"\"\n    sd = stdev(inlist)\n    n = len(inlist)\n    return sd/math.sqrt(n)", "title": ""}
{"_id": "d2262", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d2263", "text": "def import_js(path, lib_name, globals):\n    \"\"\"Imports from javascript source file.\n      globals is your globals()\"\"\"\n    with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:\n        js = f.read()\n    e = EvalJs()\n    e.execute(js)\n    var = e.context['var']\n    globals[lib_name] = var.to_python()", "title": ""}
{"_id": "d2264", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d2265", "text": "def parse_code(url):\n    \"\"\"\n    Parse the code parameter from the a URL\n\n    :param str url: URL to parse\n    :return: code query parameter\n    :rtype: str\n    \"\"\"\n    result = urlparse(url)\n    query = parse_qs(result.query)\n    return query['code']", "title": ""}
{"_id": "d2266", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d2267", "text": "def __call__(self, args):\n        \"\"\"Execute the user function.\"\"\"\n        window, ij = args\n        return self.user_func(srcs, window, ij, global_args), window", "title": ""}
{"_id": "d2268", "text": "def release(self):\n        \"\"\"\n        Releases this resource back to the pool it came from.\n        \"\"\"\n        if self.errored:\n            self.pool.delete_resource(self)\n        else:\n            self.pool.release(self)", "title": ""}
{"_id": "d2269", "text": "def _rm_name_match(s1, s2):\n  \"\"\"\n  determine whether two sequence names from a repeatmasker alignment match.\n\n  :return: True if they are the same string, or if one forms a substring of the\n           other, else False\n  \"\"\"\n  m_len = min(len(s1), len(s2))\n  return s1[:m_len] == s2[:m_len]", "title": ""}
{"_id": "d2270", "text": "def pull_stream(image):\n    \"\"\"\n    Return generator of pull status objects\n    \"\"\"\n    return (json.loads(s) for s in _get_docker().pull(image, stream=True))", "title": ""}
{"_id": "d2271", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d2272", "text": "def _composed_doc(fs):\n    \"\"\"\n    Generate a docstring for the composition of fs.\n    \"\"\"\n    if not fs:\n        # Argument name for the docstring.\n        return 'n'\n\n    return '{f}({g})'.format(f=fs[0].__name__, g=_composed_doc(fs[1:]))", "title": ""}
{"_id": "d2273", "text": "def date_to_datetime(x):\n    \"\"\"Convert a date into a datetime\"\"\"\n    if not isinstance(x, datetime) and isinstance(x, date):\n        return datetime.combine(x, time())\n    return x", "title": ""}
{"_id": "d2274", "text": "def Slice(a, begin, size):\n    \"\"\"\n    Slicing op.\n    \"\"\"\n    return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],", "title": ""}
{"_id": "d2275", "text": "def unpickle_file(picklefile, **kwargs):\n    \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)", "title": ""}
{"_id": "d2276", "text": "def dot(self, w):\n        \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n        return sum([x * y for x, y in zip(self, w)])", "title": ""}
{"_id": "d2277", "text": "def unpatch(obj, name):\n    \"\"\"\n    Undo the effects of patch(func, obj, name)\n    \"\"\"\n    setattr(obj, name, getattr(obj, name).original)", "title": ""}
{"_id": "d2278", "text": "def draw(graph, fname):\n    \"\"\"Draw a graph and save it into a file\"\"\"\n    ag = networkx.nx_agraph.to_agraph(graph)\n    ag.draw(fname, prog='dot')", "title": ""}
{"_id": "d2279", "text": "def items(iterable):\n    \"\"\"\n    Iterates over the items of a sequence. If the sequence supports the\n      dictionary protocol (iteritems/items) then we use that. Otherwise\n      we use the enumerate built-in function.\n    \"\"\"\n    if hasattr(iterable, 'iteritems'):\n        return (p for p in iterable.iteritems())\n    elif hasattr(iterable, 'items'):\n        return (p for p in iterable.items())\n    else:\n        return (p for p in enumerate(iterable))", "title": ""}
{"_id": "d2280", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d2281", "text": "def to_identifier(s):\n  \"\"\"\n  Convert snake_case to camel_case.\n  \"\"\"\n  if s.startswith('GPS'):\n      s = 'Gps' + s[3:]\n  return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s", "title": ""}
{"_id": "d2282", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d2283", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d2284", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d2285", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d2286", "text": "def _from_dict(cls, _dict):\n        \"\"\"Initialize a KeyValuePair object from a json dictionary.\"\"\"\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)", "title": ""}
{"_id": "d2287", "text": "def _cdf(self, xloc, dist, base, cache):\n        \"\"\"Cumulative distribution function.\"\"\"\n        return evaluation.evaluate_forward(dist, base**xloc, cache=cache)", "title": ""}
{"_id": "d2288", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d2289", "text": "def start_of_month(val):\n    \"\"\"\n    Return a new datetime.datetime object with values that represent\n    a start of a month.\n    :param val: Date to ...\n    :type val: datetime.datetime | datetime.date\n    :rtype: datetime.datetime\n    \"\"\"\n    if type(val) == date:\n        val = datetime.fromordinal(val.toordinal())\n    return start_of_day(val).replace(day=1)", "title": ""}
{"_id": "d2290", "text": "def _kw(keywords):\n    \"\"\"Turn list of keywords into dictionary.\"\"\"\n    r = {}\n    for k, v in keywords:\n        r[k] = v\n    return r", "title": ""}
{"_id": "d2291", "text": "def to_snake_case(text):\n    \"\"\"Convert to snake case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d2292", "text": "def update_index(index):\n    \"\"\"Re-index every document in a named index.\"\"\"\n    logger.info(\"Updating search index: '%s'\", index)\n    client = get_client()\n    responses = []\n    for model in get_index_models(index):\n        logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n        objects = model.objects.get_search_queryset(index).iterator()\n        actions = bulk_actions(objects, index=index, action=\"index\")\n        response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n        responses.append(response)\n    return responses", "title": ""}
{"_id": "d2293", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d2294", "text": "def add_index_alias(es, index_name, alias_name):\n    \"\"\"Add index alias to index_name\"\"\"\n\n    es.indices.put_alias(index=index_name, name=terms_alias)", "title": ""}
{"_id": "d2295", "text": "def _check_and_convert_bools(self):\n        \"\"\"Replace boolean variables by the characters 'F'/'T'\n        \"\"\"\n        replacements = {\n            True: 'T',\n            False: 'F',\n        }\n\n        for key in self.bools:\n            if isinstance(self[key], bool):\n                self[key] = replacements[self[key]]", "title": ""}
{"_id": "d2296", "text": "def index(obj, index=INDEX_NAME, doc_type=DOC_TYPE):\n    \"\"\"\n    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\n    \"\"\"\n    doc = to_dict(obj)\n\n    if doc is None:\n        return\n\n    id = doc.pop('id')\n\n    return es_conn.index(index, doc_type, doc, id=id)", "title": ""}
{"_id": "d2297", "text": "def as_tuple(self, value):\n        \"\"\"Utility function which converts lists to tuples.\"\"\"\n        if isinstance(value, list):\n            value = tuple(value)\n        return value", "title": ""}
{"_id": "d2298", "text": "def format_header_cell(val):\n    \"\"\"\n    Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and\n    all other '_' to spaces.\n    \"\"\"\n    return re.sub('_', ' ', re.sub(r'(_Px_)', '(', re.sub(r'(_xP_)', ')', str(val) )))", "title": ""}
{"_id": "d2299", "text": "def QA_util_datetime_to_strdate(dt):\n    \"\"\"\n    :param dt:  pythone datetime.datetime\n    :return:  1999-02-01 string type\n    \"\"\"\n    strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n    return strdate", "title": ""}
{"_id": "d2300", "text": "def iterparse(source, tag, clear=False, events=None):\n    \"\"\"\n    iterparse variant that supports 'tag' parameter (like lxml),\n    yields elements and clears nodes after parsing.\n    \"\"\"\n    for event, elem in ElementTree.iterparse(source, events=events):\n        if elem.tag == tag:\n            yield elem\n        if clear:\n            elem.clear()", "title": ""}
{"_id": "d2301", "text": "def command_py2to3(args):\n    \"\"\"\n    Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n    \"\"\"\n    from lib2to3.main import main\n    sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "title": ""}
{"_id": "d2302", "text": "def is_rfc2822(instance: str):\n    \"\"\"Validates RFC2822 format\"\"\"\n    if not isinstance(instance, str):\n        return True\n    return email.utils.parsedate(instance) is not None", "title": ""}
{"_id": "d2303", "text": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "title": ""}
{"_id": "d2304", "text": "def _check_color_dim(val):\n    \"\"\"Ensure val is Nx(n_col), usually Nx3\"\"\"\n    val = np.atleast_2d(val)\n    if val.shape[1] not in (3, 4):\n        raise RuntimeError('Value must have second dimension of size 3 or 4')\n    return val, val.shape[1]", "title": ""}
{"_id": "d2305", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d2306", "text": "def safe_unicode(string):\n    \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n    if not PY3:\n        uni = string.replace(u'\\u2019', \"'\")\n        return uni.encode('utf-8')\n        \n    return string", "title": ""}
{"_id": "d2307", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d2308", "text": "def items(self):\n    \"\"\"Return a list of the (name, value) pairs of the enum.\n\n    These are returned in the order they were defined in the .proto file.\n    \"\"\"\n    return [(value_descriptor.name, value_descriptor.number)\n            for value_descriptor in self._enum_type.values]", "title": ""}
{"_id": "d2309", "text": "def getpass(self, prompt, default=None):\n        \"\"\"Provide a password prompt.\"\"\"\n        return click.prompt(prompt, hide_input=True, default=default)", "title": ""}
{"_id": "d2310", "text": "def unpack_out(self, name):\n        return self.parse(\"\"\"\n            $enum = $enum_class($value.value)\n            \"\"\", enum_class=self._import_type(), value=name)[\"enum\"]", "title": ""}
{"_id": "d2311", "text": "def _set_widget_background_color(widget, color):\n        \"\"\"\n        Changes the base color of a widget (background).\n        :param widget: widget to modify\n        :param color: the color to apply\n        \"\"\"\n        pal = widget.palette()\n        pal.setColor(pal.Base, color)\n        widget.setPalette(pal)", "title": ""}
{"_id": "d2312", "text": "def get_mi_vec(slab):\n    \"\"\"\n    Convenience function which returns the unit vector aligned\n    with the miller index.\n    \"\"\"\n    mvec = np.cross(slab.lattice.matrix[0], slab.lattice.matrix[1])\n    return mvec / np.linalg.norm(mvec)", "title": ""}
{"_id": "d2313", "text": "def c2f(r, i, ctype_name):\n    \"\"\"\n    Convert strings to complex number instance with specified numpy type.\n    \"\"\"\n\n    ftype = c2f_dict[ctype_name]\n    return np.typeDict[ctype_name](ftype(r) + 1j * ftype(i))", "title": ""}
{"_id": "d2314", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d2315", "text": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "title": ""}
{"_id": "d2316", "text": "def exec_function(ast, globals_map):\n    \"\"\"Execute a python code object in the given environment.\n\n    Args:\n      globals_map: Dictionary to use as the globals context.\n    Returns:\n      locals_map: Dictionary of locals from the environment after execution.\n    \"\"\"\n    locals_map = globals_map\n    exec ast in globals_map, locals_map\n    return locals_map", "title": ""}
{"_id": "d2317", "text": "def is_collection(obj):\n    \"\"\"Tests if an object is a collection.\"\"\"\n\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n\n    if isinstance(obj, basestring):\n        val = False\n\n    return val", "title": ""}
{"_id": "d2318", "text": "def log_exception(exc_info=None, stream=None):\n    \"\"\"Log the 'exc_info' tuple in the server log.\"\"\"\n    exc_info = exc_info or sys.exc_info()\n    stream = stream or sys.stderr\n    try:\n        from traceback import print_exception\n        print_exception(exc_info[0], exc_info[1], exc_info[2], None, stream)\n        stream.flush()\n    finally:\n        exc_info = None", "title": ""}
{"_id": "d2319", "text": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "title": ""}
{"_id": "d2320", "text": "def __init__(self, filename, formatting_info=False, handle_ambiguous_date=None):\n    \"\"\"Initialize the ExcelWorkbook instance.\"\"\"\n    super().__init__(filename)\n    self.workbook = xlrd.open_workbook(self.filename, formatting_info=formatting_info)\n    self.handle_ambiguous_date = handle_ambiguous_date", "title": ""}
{"_id": "d2321", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d2322", "text": "def handle_exception(error):\n        \"\"\"Simple method for handling exceptions raised by `PyBankID`.\n\n        :param flask_pybankid.FlaskPyBankIDError error: The exception to handle.\n        :return: The exception represented as a dictionary.\n        :rtype: dict\n\n        \"\"\"\n        response = jsonify(error.to_dict())\n        response.status_code = error.status_code\n        return response", "title": ""}
{"_id": "d2323", "text": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "title": ""}
{"_id": "d2324", "text": "def timedcall(executable_function, *args):\n    \"\"\"!\n    @brief Executes specified method or function with measuring of execution time.\n    \n    @param[in] executable_function (pointer): Pointer to function or method.\n    @param[in] args (*): Arguments of called function or method.\n    \n    @return (tuple) Execution time and result of execution of function or method (execution_time, result_execution).\n    \n    \"\"\"\n    \n    time_start = time.clock();\n    result = executable_function(*args);\n    time_end = time.clock();\n    \n    return (time_end - time_start, result);", "title": ""}
{"_id": "d2325", "text": "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n    \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n    return maybe_list and any(is_multiline(item) for item in maybe_list)", "title": ""}
{"_id": "d2326", "text": "def exec_function(ast, globals_map):\n    \"\"\"Execute a python code object in the given environment.\n\n    Args:\n      globals_map: Dictionary to use as the globals context.\n    Returns:\n      locals_map: Dictionary of locals from the environment after execution.\n    \"\"\"\n    locals_map = globals_map\n    exec ast in globals_map, locals_map\n    return locals_map", "title": ""}
{"_id": "d2327", "text": "def is_connected(self):\n        \"\"\"\n        Return true if the socket managed by this connection is connected\n\n        :rtype: bool\n        \"\"\"\n        try:\n            return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)\n        except socket.error:\n            return False", "title": ""}
{"_id": "d2328", "text": "def call_and_exit(self, cmd, shell=True):\n        \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n        sys.exit(subprocess.call(cmd, shell=shell))", "title": ""}
{"_id": "d2329", "text": "def is_element_present(driver, selector, by=By.CSS_SELECTOR):\n    \"\"\"\n    Returns whether the specified element selector is present 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 present)\n    \"\"\"\n    try:\n        driver.find_element(by=by, value=selector)\n        return True\n    except Exception:\n        return False", "title": ""}
{"_id": "d2330", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d2331", "text": "def is_list_of_list(item):\n    \"\"\"\n    check whether the item is list (tuple)\n    and consist of list (tuple) elements\n    \"\"\"\n    if (\n        type(item) in (list, tuple)\n        and len(item)\n        and isinstance(item[0], (list, tuple))\n    ):\n        return True\n    return False", "title": ""}
{"_id": "d2332", "text": "def exit(exit_code=0):\n  r\"\"\"A function to support exiting from exit hooks.\n\n  Could also be used to exit from the calling scripts in a thread safe manner.\n  \"\"\"\n  core.processExitHooks()\n\n  if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook\n    sys.stderr.flush()\n    sys.stdout.flush()\n    os._exit(exit_code) #pylint: disable=W0212\n\n  sys.exit(exit_code)", "title": ""}
{"_id": "d2333", "text": "def is_nullable_list(val, vtype):\n    \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n    return (isinstance(val, list) and\n            any(isinstance(v, vtype) for v in val) and\n            all((isinstance(v, vtype) or v is None) for v in val))", "title": ""}
{"_id": "d2334", "text": "def _expand(self, str, local_vars={}):\n        \"\"\"Expand $vars in a string.\"\"\"\n        return ninja_syntax.expand(str, self.vars, local_vars)", "title": ""}
{"_id": "d2335", "text": "def task_property_present_predicate(service, task, prop):\n    \"\"\" True if the json_element passed is present for the task specified.\n    \"\"\"\n    try:\n        response = get_service_task(service, task)\n    except Exception as e:\n        pass\n\n    return (response is not None) and (prop in response)", "title": ""}
{"_id": "d2336", "text": "def _merge_args_with_kwargs(args_dict, kwargs_dict):\n    \"\"\"Merge args with kwargs.\"\"\"\n    ret = args_dict.copy()\n    ret.update(kwargs_dict)\n    return ret", "title": ""}
{"_id": "d2337", "text": "def inside_softimage():\n    \"\"\"Returns a boolean indicating if the code is executed 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", "title": ""}
{"_id": "d2338", "text": "def unique_everseen(seq):\n    \"\"\"Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d2339", "text": "def is_json_file(filename, show_warnings = False):\n    \"\"\"Check configuration file type is JSON\n    Return a boolean indicating wheather the file is JSON format or not\n    \"\"\"\n    try:\n        config_dict = load_config(filename, file_type = \"json\")\n        is_json = True\n    except:\n        is_json = False\n    return(is_json)", "title": ""}
{"_id": "d2340", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d2341", "text": "def _writable_dir(path):\n    \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n    return os.path.isdir(path) and os.access(path, os.W_OK)", "title": ""}
{"_id": "d2342", "text": "def get_url_args(url):\n    \"\"\" Returns a dictionary from a URL params \"\"\"\n    url_data = urllib.parse.urlparse(url)\n    arg_dict = urllib.parse.parse_qs(url_data.query)\n    return arg_dict", "title": ""}
{"_id": "d2343", "text": "def test_for_image(self, cat, img):\n        \"\"\"Tests if image img in category cat exists\"\"\"\n        return self.test_for_category(cat) and img in self.items[cat]", "title": ""}
{"_id": "d2344", "text": "def extract_all(zipfile, dest_folder):\n    \"\"\"\n    reads the zip file, determines compression\n    and unzips recursively until source files \n    are extracted \n    \"\"\"\n    z = ZipFile(zipfile)\n    print(z)\n    z.extract(dest_folder)", "title": ""}
{"_id": "d2345", "text": "def is_string(obj):\n    \"\"\"Is this a string.\n\n    :param object obj:\n    :rtype: bool\n    \"\"\"\n    if PYTHON3:\n        str_type = (bytes, str)\n    else:\n        str_type = (bytes, str, unicode)\n    return isinstance(obj, str_type)", "title": ""}
{"_id": "d2346", "text": "def parse_float_literal(ast, _variables=None):\n    \"\"\"Parse a float value node in the AST.\"\"\"\n    if isinstance(ast, (FloatValueNode, IntValueNode)):\n        return float(ast.value)\n    return INVALID", "title": ""}
{"_id": "d2347", "text": "def is_int(string):\n    \"\"\"\n    Checks if a string is an integer. If the string value is an integer\n    return True, otherwise return False. \n    \n    Args:\n        string: a string to test.\n\n    Returns: \n        boolean\n    \"\"\"\n    try:\n        a = float(string)\n        b = int(a)\n    except ValueError:\n        return False\n    else:\n        return a == b", "title": ""}
{"_id": "d2348", "text": "def stft(func=None, **kwparams):\n  \"\"\"\n  Short Time Fourier Transform for real data keeping the full FFT block.\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,\n              inverse_transform=lambda *args: numpy.fft.ifft(*args).real)\n\n  See ``stft.base`` docs for more.\n  \"\"\"\n  from numpy.fft import fft, ifft\n  ifft_r = lambda *args: ifft(*args).real\n  return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)", "title": ""}
{"_id": "d2349", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d2350", "text": "def stft(func=None, **kwparams):\n  \"\"\"\n  Short Time Fourier Transform for real data keeping the full FFT block.\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,\n              inverse_transform=lambda *args: numpy.fft.ifft(*args).real)\n\n  See ``stft.base`` docs for more.\n  \"\"\"\n  from numpy.fft import fft, ifft\n  ifft_r = lambda *args: ifft(*args).real\n  return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)", "title": ""}
{"_id": "d2351", "text": "def valid_uuid(value):\n    \"\"\" Check if value is a valid UUID. \"\"\"\n\n    try:\n        uuid.UUID(value, version=4)\n        return True\n    except (TypeError, ValueError, AttributeError):\n        return False", "title": ""}
{"_id": "d2352", "text": "def stft_magnitude(signal, fft_length,\n                   hop_length=None,\n                   window_length=None):\n  \"\"\"Calculate the short-time Fourier transform magnitude.\n\n  Args:\n    signal: 1D np.array of the input time-domain signal.\n    fft_length: Size of the FFT to apply.\n    hop_length: Advance (in samples) between each frame passed to FFT.\n    window_length: Length of each block of samples to pass to FFT.\n\n  Returns:\n    2D np.array where each row contains the magnitudes of the fft_length/2+1\n    unique values of the FFT for the corresponding frame of input samples.\n  \"\"\"\n  frames = frame(signal, window_length, hop_length)\n  # Apply frame window to each frame. We use a periodic Hann (cosine of period\n  # window_length) instead of the symmetric Hann of np.hanning (period\n  # window_length-1).\n  window = periodic_hann(window_length)\n  windowed_frames = frames * window\n  return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))", "title": ""}
{"_id": "d2353", "text": "def getvariable(name):\n    \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n    import inspect\n    fr = inspect.currentframe()\n    try:\n        while fr:\n            fr = fr.f_back\n            vars = fr.f_locals\n            if name in vars:\n                return vars[name]\n    except:\n        pass\n    return None", "title": ""}
{"_id": "d2354", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d2355", "text": "def check_empty_dict(GET_dict):\n    \"\"\"\n    Returns True if the GET querstring contains on values, but it can contain\n    empty keys.\n    This is better than doing not bool(request.GET) as an empty key will return\n    True\n    \"\"\"\n    empty = True\n    for k, v in GET_dict.items():\n        # Don't disable on p(age) or 'all' GET param\n        if v and k != 'p' and k != 'all':\n            empty = False\n    return empty", "title": ""}
{"_id": "d2356", "text": "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)", "title": ""}
{"_id": "d2357", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d2358", "text": "def rewindbody(self):\n        \"\"\"Rewind the file to the start of the body (if seekable).\"\"\"\n        if not self.seekable:\n            raise IOError, \"unseekable file\"\n        self.fp.seek(self.startofbody)", "title": ""}
{"_id": "d2359", "text": "def _check_2d_shape(X):\n    \"\"\"Check shape of array or sparse matrix.\n\n    Assure that X is always 2D: Unlike numpy we always deal with 2D arrays.\n    \"\"\"\n    if X.dtype.names is None and len(X.shape) != 2:\n        raise ValueError('X needs to be 2-dimensional, not '\n                         '{}-dimensional.'.format(len(X.shape)))", "title": ""}
{"_id": "d2360", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d2361", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d2362", "text": "def read(filename):\n    \"\"\"Read and return `filename` in root dir of project and return string\"\"\"\n    return codecs.open(os.path.join(__DIR__, filename), 'r').read()", "title": ""}
{"_id": "d2363", "text": "def instance_contains(container, item):\n    \"\"\"Search into instance attributes, properties and return values of no-args methods.\"\"\"\n    return item in (member for _, member in inspect.getmembers(container))", "title": ""}
{"_id": "d2364", "text": "def fill_nulls(self, col: str):\n        \"\"\"\n        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\")``\n        \"\"\"\n        n = [None, \"\"]\n        try:\n            self.df[col] = self.df[col].replace(n, nan)\n        except Exception as e:\n            self.err(e)", "title": ""}
{"_id": "d2365", "text": "def skewness(data):\n    \"\"\"\n    Returns the skewness of ``data``.\n    \"\"\"\n\n    if len(data) == 0:\n        return None\n\n    num = moment(data, 3)\n    denom = moment(data, 2) ** 1.5\n\n    return num / denom if denom != 0 else 0.", "title": ""}
{"_id": "d2366", "text": "def inpaint(self):\n        \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n        import inpaint\n        filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n        self.raster_data = np.ma.masked_invalid(filled)", "title": ""}
{"_id": "d2367", "text": "def _check_color_dim(val):\n    \"\"\"Ensure val is Nx(n_col), usually Nx3\"\"\"\n    val = np.atleast_2d(val)\n    if val.shape[1] not in (3, 4):\n        raise RuntimeError('Value must have second dimension of size 3 or 4')\n    return val, val.shape[1]", "title": ""}
{"_id": "d2368", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d2369", "text": "def available_gpus():\n  \"\"\"List of GPU device names detected by TensorFlow.\"\"\"\n  local_device_protos = device_lib.list_local_devices()\n  return [x.name for x in local_device_protos if x.device_type == 'GPU']", "title": ""}
{"_id": "d2370", "text": "def cleanLines(source, lineSep=os.linesep):\n    \"\"\"\n    :param source: some iterable source (list, file, etc)\n    :param lineSep: string of separators (chars) that must be removed\n    :return: list of non empty lines with removed separators\n    \"\"\"\n    stripped = (line.strip(lineSep) for line in source)\n    return (line for line in stripped if len(line) != 0)", "title": ""}
{"_id": "d2371", "text": "def allclose(a, b):\n    \"\"\"\n    Test that a and b are close and match in shape.\n\n    Parameters\n    ----------\n    a : ndarray\n        First array to check\n\n    b : ndarray\n        First array to check\n    \"\"\"\n    from numpy import allclose\n    return (a.shape == b.shape) and allclose(a, b)", "title": ""}
{"_id": "d2372", "text": "def camel_to_snake_case(name):\n    \"\"\"Takes a camelCased string and converts to snake_case.\"\"\"\n    pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])'\n    return '_'.join(map(str.lower, re.findall(pattern, name)))", "title": ""}
{"_id": "d2373", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d2374", "text": "def sorted_index(values, x):\n    \"\"\"\n    For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n    :param values: list\n    :param x: item\n    :return: integer index\n    \"\"\"\n    i = bisect_left(values, x)\n    j = bisect_right(values, x)\n    return values[i:j].index(x) + i", "title": ""}
{"_id": "d2375", "text": "def clear():\n    \"\"\"Clears the console.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        call(\"cls\", shell=True)\n    else:\n        call(\"clear\", shell=True)", "title": ""}
{"_id": "d2376", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x.\"\"\"\n    i = bs.bisect_left(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d2377", "text": "def logout(cache):\n    \"\"\"\n    Logs out the current session by removing it from the cache. This is\n    expected to only occur when a session has\n    \"\"\"\n    cache.set(flask.session['auth0_key'], None)\n    flask.session.clear()\n    return True", "title": ""}
{"_id": "d2378", "text": "def retrieve_asset(filename):\n    \"\"\" Retrieves a non-image asset associated with an entry \"\"\"\n\n    record = model.Image.get(asset_name=filename)\n    if not record:\n        raise http_error.NotFound(\"File not found\")\n    if not record.is_asset:\n        raise http_error.Forbidden()\n\n    return flask.send_file(record.file_path, conditional=True)", "title": ""}
{"_id": "d2379", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d2380", "text": "def json_template(data, template_name, template_context):\n    \"\"\"Old style, use JSONTemplateResponse instead of this.\n    \"\"\"\n    html = render_to_string(template_name, template_context)\n    data = data or {}\n    data['html'] = html\n    return HttpResponse(json_encode(data), content_type='application/json')", "title": ""}
{"_id": "d2381", "text": "def _closeResources(self):\n        \"\"\" Closes the root Dataset.\n        \"\"\"\n        logger.info(\"Closing: {}\".format(self._fileName))\n        self._h5Group.close()\n        self._h5Group = None", "title": ""}
{"_id": "d2382", "text": "def arg_bool(name, default=False):\n    \"\"\" Fetch a query argument, as a boolean. \"\"\"\n    v = request.args.get(name, '')\n    if not len(v):\n        return default\n    return v in BOOL_TRUISH", "title": ""}
{"_id": "d2383", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d2384", "text": "def view_500(request, url=None):\n    \"\"\"\n    it returns a 500 http response\n    \"\"\"\n    res = render_to_response(\"500.html\", context_instance=RequestContext(request))\n    res.status_code = 500\n    return res", "title": ""}
{"_id": "d2385", "text": "def stop(self, dummy_signum=None, dummy_frame=None):\n        \"\"\" Shutdown process (this method is also a signal handler) \"\"\"\n        logging.info('Shutting down ...')\n        self.socket.close()\n        sys.exit(0)", "title": ""}
{"_id": "d2386", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d2387", "text": "def logout(cache):\n    \"\"\"\n    Logs out the current session by removing it from the cache. This is\n    expected to only occur when a session has\n    \"\"\"\n    cache.set(flask.session['auth0_key'], None)\n    flask.session.clear()\n    return True", "title": ""}
{"_id": "d2388", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d2389", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d2390", "text": "def trim(self):\n        \"\"\"Clear not used counters\"\"\"\n        for key, value in list(iteritems(self.counters)):\n            if value.empty():\n                del self.counters[key]", "title": ""}
{"_id": "d2391", "text": "def filter(self, f, operator=\"and\"):\n        \"\"\"\n        Add a filter to the query\n\n        Takes a Filter object, or a filterable DSL object.\n        \"\"\"\n        if self._filtered:\n            self._filter_dsl.filter(f)\n        else:\n            self._build_filtered_query(f, operator)\n        return self", "title": ""}
{"_id": "d2392", "text": "def flatten(nested):\n    \"\"\" Return a flatten version of the nested argument \"\"\"\n    flat_return = list()\n\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\n    __inner_flat(nested,flat_return)\n\n    return flat_return", "title": ""}
{"_id": "d2393", "text": "def merge_pdfs(pdf_filepaths, out_filepath):\n    \"\"\" Merge all the PDF files in `pdf_filepaths` in a new PDF file `out_filepath`.\n\n    Parameters\n    ----------\n    pdf_filepaths: list of str\n        Paths to PDF files.\n\n    out_filepath: str\n        Path to the result PDF file.\n\n    Returns\n    -------\n    path: str\n        The output file path.\n    \"\"\"\n    merger = PdfFileMerger()\n    for pdf in pdf_filepaths:\n        merger.append(PdfFileReader(open(pdf, 'rb')))\n\n    merger.write(out_filepath)\n\n    return out_filepath", "title": ""}
{"_id": "d2394", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d2395", "text": "def merge_dict(data, *args):\n    \"\"\"Merge any number of dictionaries\n    \"\"\"\n    results = {}\n    for current in (data,) + args:\n        results.update(current)\n    return results", "title": ""}
{"_id": "d2396", "text": "def flatten(nested, containers=(list, tuple)):\n    \"\"\" Flatten a nested list by yielding its scalar items.\n    \"\"\"\n    for item in nested:\n        if hasattr(item, \"next\") or isinstance(item, containers):\n            for subitem in flatten(item):\n                yield subitem\n        else:\n            yield item", "title": ""}
{"_id": "d2397", "text": "def pprint(self, seconds):\n        \"\"\"\n        Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n        :param seconds:  The time in seconds.\n        \"\"\"\n        return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))", "title": ""}
{"_id": "d2398", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d2399", "text": "def version_jar(self):\n\t\t\"\"\"\n\t\tSpecial case of version() when the executable is a JAR file.\n\t\t\"\"\"\n\t\tcmd = config.get_command('java')\n\t\tcmd.append('-jar')\n\t\tcmd += self.cmd\n\t\tself.version(cmd=cmd, path=self.cmd[0])", "title": ""}
{"_id": "d2400", "text": "def flatten(lis):\n    \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n    new_lis = []\n    for item in lis:\n        if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n            new_lis.extend(flatten(item))\n        else:\n            new_lis.append(item)\n    return new_lis", "title": ""}
{"_id": "d2401", "text": "def clear():\n    \"\"\"Clears the console.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        call(\"cls\", shell=True)\n    else:\n        call(\"clear\", shell=True)", "title": ""}
{"_id": "d2402", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d2403", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d2404", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d2405", "text": "def count_string_diff(a,b):\n    \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n    shortest = min(len(a), len(b))\n    return sum(a[i] != b[i] for i in range(shortest))", "title": ""}
{"_id": "d2406", "text": "def flush():\n    \"\"\"Try to flush all stdio buffers, both from python and from C.\"\"\"\n    try:\n        sys.stdout.flush()\n        sys.stderr.flush()\n    except (AttributeError, ValueError, IOError):\n        pass  # unsupported\n    try:\n        libc.fflush(None)\n    except (AttributeError, ValueError, IOError):\n        pass", "title": ""}
{"_id": "d2407", "text": "def are_equal_xml(a_xml, b_xml):\n    \"\"\"Normalize and compare XML documents for equality. The document may or may not be\n    a DataONE type.\n\n    Args:\n      a_xml: str\n      b_xml: str\n        XML documents to compare for equality.\n\n    Returns:\n      bool: ``True`` if the XML documents are semantically equivalent.\n\n    \"\"\"\n    a_dom = xml.dom.minidom.parseString(a_xml)\n    b_dom = xml.dom.minidom.parseString(b_xml)\n    return are_equal_elements(a_dom.documentElement, b_dom.documentElement)", "title": ""}
{"_id": "d2408", "text": "def safe_int_conv(number):\n    \"\"\"Safely convert a single number to integer.\"\"\"\n    try:\n        return int(np.array(number).astype(int, casting='safe'))\n    except TypeError:\n        raise ValueError('cannot safely convert {} to integer'.format(number))", "title": ""}
{"_id": "d2409", "text": "def dedupe(items):\n    \"\"\"Remove duplicates from a sequence (of hashable items) while maintaining\n    order. NOTE: This only works if items in the list are hashable types.\n\n    Taken from the Python Cookbook, 3rd ed. Such a great book!\n\n    \"\"\"\n    seen = set()\n    for item in items:\n        if item not in seen:\n            yield item\n            seen.add(item)", "title": ""}
{"_id": "d2410", "text": "def go_to_background():\n    \"\"\" Daemonize the running process. \"\"\"\n    try:\n        if os.fork():\n            sys.exit()\n    except OSError as errmsg:\n        LOGGER.error('Fork failed: {0}'.format(errmsg))\n        sys.exit('Fork failed')", "title": ""}
{"_id": "d2411", "text": "def generate(env):\n    \"\"\"Add Builders and construction variables for SGI MIPS C++ to an Environment.\"\"\"\n\n    cplusplus.generate(env)\n\n    env['CXX']         = 'CC'\n    env['CXXFLAGS']    = SCons.Util.CLVar('-LANG:std')\n    env['SHCXX']       = '$CXX'\n    env['SHOBJSUFFIX'] = '.o'\n    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1", "title": ""}
{"_id": "d2412", "text": "def multis_2_mono(table):\n    \"\"\"\n    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\n    \"\"\"\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\n    return table", "title": ""}
{"_id": "d2413", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d2414", "text": "def safe_format(s, **kwargs):\n  \"\"\"\n  :type s str\n  \"\"\"\n  return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))", "title": ""}
{"_id": "d2415", "text": "def num_leaves(tree):\n    \"\"\"Determine the number of leaves in a tree\"\"\"\n    if tree.is_leaf:\n        return 1\n    else:\n        return num_leaves(tree.left_child) + num_leaves(tree.right_child)", "title": ""}
{"_id": "d2416", "text": "def print_latex(o):\n    \"\"\"A function to generate the latex representation of sympy\n    expressions.\"\"\"\n    if can_print_latex(o):\n        s = latex(o, mode='plain')\n        s = s.replace('\\\\dag','\\\\dagger')\n        s = s.strip('$')\n        return '$$%s$$' % s\n    # Fallback to the string printer\n    return None", "title": ""}
{"_id": "d2417", "text": "def xeval(source, optimize=True):\n    \"\"\"Compiles to native Python bytecode and runs program, returning the\n    topmost value on the stack.\n\n    Args:\n        optimize: Whether to optimize the code after parsing it.\n\n    Returns:\n        None: If the stack is empty\n        obj: If the stack contains a single value\n        [obj, obj, ...]: If the stack contains many values\n    \"\"\"\n    native = xcompile(source, optimize=optimize)\n    return native()", "title": ""}
{"_id": "d2418", "text": "def _tuple_repr(data):\n    \"\"\"Return a repr() for a list/tuple\"\"\"\n    if len(data) == 1:\n        return \"(%s,)\" % rpr(data[0])\n    else:\n        return \"(%s)\" % \", \".join([rpr(x) for x in data])", "title": ""}
{"_id": "d2419", "text": "def timestamp_to_datetime(timestamp):\n    \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n    from datetime import datetime, timedelta\n    obj = datetime.fromtimestamp(timestamp[0])\n    return obj + timedelta(microseconds=int(timestamp[1]))", "title": ""}
{"_id": "d2420", "text": "def fromtimestamp(cls, timestamp):\n    \"\"\"Returns a datetime object of a given timestamp (in local tz).\"\"\"\n    d = cls.utcfromtimestamp(timestamp)\n    return d.astimezone(localtz())", "title": ""}
{"_id": "d2421", "text": "def str2int(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n    return NumConv(radix, alphabet).str2int(num)", "title": ""}
{"_id": "d2422", "text": "def get_substring_idxs(substr, string):\n    \"\"\"\n    Return a list of indexes of substr. If substr not found, list is\n    empty.\n\n    Arguments:\n        substr (str): Substring to match.\n        string (str): String to match in.\n\n    Returns:\n        list of int: Start indices of substr.\n    \"\"\"\n    return [match.start() for match in re.finditer(substr, string)]", "title": ""}
{"_id": "d2423", "text": "def _concatenate_virtual_arrays(arrs, cols=None, scaling=None):\n    \"\"\"Return a virtual concatenate of several NumPy arrays.\"\"\"\n    return None if not len(arrs) else ConcatenatedArrays(arrs, cols,\n                                                         scaling=scaling)", "title": ""}
{"_id": "d2424", "text": "def short_description(func):\n    \"\"\"\n    Given an object with a docstring, return the first line of the docstring\n    \"\"\"\n\n    doc = inspect.getdoc(func)\n    if doc is not None:\n        doc = inspect.cleandoc(doc)\n        lines = doc.splitlines()\n        return lines[0]\n\n    return \"\"", "title": ""}
{"_id": "d2425", "text": "def _concatenate_virtual_arrays(arrs, cols=None, scaling=None):\n    \"\"\"Return a virtual concatenate of several NumPy arrays.\"\"\"\n    return None if not len(arrs) else ConcatenatedArrays(arrs, cols,\n                                                         scaling=scaling)", "title": ""}
{"_id": "d2426", "text": "def get_previous(self):\n        \"\"\"Get the billing cycle prior to this one. May return None\"\"\"\n        return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()", "title": ""}
{"_id": "d2427", "text": "def _concatenate_virtual_arrays(arrs, cols=None, scaling=None):\n    \"\"\"Return a virtual concatenate of several NumPy arrays.\"\"\"\n    return None if not len(arrs) else ConcatenatedArrays(arrs, cols,\n                                                         scaling=scaling)", "title": ""}
{"_id": "d2428", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d2429", "text": "def to_list(var):\n    \"\"\"Checks if given value is a list, tries to convert, if it is not.\"\"\"\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", "title": ""}
{"_id": "d2430", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d2431", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d2432", "text": "def get_decimal_quantum(precision):\n    \"\"\"Return minimal quantum of a number, as defined by precision.\"\"\"\n    assert isinstance(precision, (int, decimal.Decimal))\n    return decimal.Decimal(10) ** (-precision)", "title": ""}
{"_id": "d2433", "text": "def get_url(self, cmd, **args):\n        \"\"\"Expand the request URL for a request.\"\"\"\n        return self.http.base_url + self._mkurl(cmd, *args)", "title": ""}
{"_id": "d2434", "text": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "title": ""}
{"_id": "d2435", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d2436", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d2437", "text": "def double_sha256(data):\n    \"\"\"A standard compound hash.\"\"\"\n    return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())", "title": ""}
{"_id": "d2438", "text": "def command_py2to3(args):\n    \"\"\"\n    Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n    \"\"\"\n    from lib2to3.main import main\n    sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "title": ""}
{"_id": "d2439", "text": "def daterange(start_date, end_date):\n    \"\"\"\n    Yield one date per day from starting date to ending date.\n\n    Args:\n        start_date (date): starting date.\n        end_date (date): ending date.\n\n    Yields:\n        date: a date for each day within the range.\n    \"\"\"\n    for n in range(int((end_date - start_date).days)):\n        yield start_date + timedelta(n)", "title": ""}
{"_id": "d2440", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d2441", "text": "def render(template=None, ostr=None, **kwargs):\n    \"\"\"Generate report from a campaign\n\n    :param template: Jinja template to use, ``DEFAULT_TEMPLATE`` is used\n    if not specified\n    :param ostr: output file or filename. Default is standard output\n    \"\"\"\n    jinja_environment.filters['texscape'] = tex_escape\n    template = template or DEFAULT_TEMPLATE\n    ostr = ostr or sys.stdout\n    jinja_template = jinja_environment.get_template(template)\n    jinja_template.stream(**kwargs).dump(ostr)", "title": ""}
{"_id": "d2442", "text": "def abs_img(img):\n    \"\"\" Return an image with the binarised version of the data of `img`.\"\"\"\n    bool_img = np.abs(read_img(img).get_data())\n    return bool_img.astype(int)", "title": ""}
{"_id": "d2443", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d2444", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d2445", "text": "def get_remote_content(filepath):\n        \"\"\" A handy wrapper to get a remote file content \"\"\"\n        with hide('running'):\n            temp = BytesIO()\n            get(filepath, temp)\n            content = temp.getvalue().decode('utf-8')\n        return content.strip()", "title": ""}
{"_id": "d2446", "text": "def Slice(a, begin, size):\n    \"\"\"\n    Slicing op.\n    \"\"\"\n    return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],", "title": ""}
{"_id": "d2447", "text": "def get_by(self, name):\n    \"\"\"get element by name\"\"\"\n    return next((item for item in self if item.name == name), None)", "title": ""}
{"_id": "d2448", "text": "def angle(x, y):\n    \"\"\"Return the angle between vectors a and b in degrees.\"\"\"\n    return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi", "title": ""}
{"_id": "d2449", "text": "def object_as_dict(obj):\n    \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n    Based on https://stackoverflow.com/a/37350445/1579058\n    \"\"\"\n    return {c.key: getattr(obj, c.key)\n            for c in inspect(obj).mapper.column_attrs}", "title": ""}
{"_id": "d2450", "text": "def similarity(self, other):\n        \"\"\"Calculates the cosine similarity between this vector and another\n        vector.\"\"\"\n        if self.magnitude == 0 or other.magnitude == 0:\n            return 0\n\n        return self.dot(other) / self.magnitude", "title": ""}
{"_id": "d2451", "text": "def twitter_timeline(screen_name, since_id=None):\n    \"\"\" Return relevant twitter timeline \"\"\"\n    consumer_key = twitter_credential('consumer_key')\n    consumer_secret = twitter_credential('consumer_secret')\n    access_token = twitter_credential('access_token')\n    access_token_secret = twitter_credential('access_secret')\n    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n    auth.set_access_token(access_token, access_token_secret)\n    api = tweepy.API(auth)\n    return get_all_tweets(screen_name, api, since_id)", "title": ""}
{"_id": "d2452", "text": "def size(self):\n        \"\"\"\n        Recursively find size of a tree. Slow.\n        \"\"\"\n\n        if self is NULL:\n            return 0\n        return 1 + self.left.size() + self.right.size()", "title": ""}
{"_id": "d2453", "text": "def uniq(seq):\n    \"\"\" Return a copy of seq without duplicates. \"\"\"\n    seen = set()\n    return [x for x in seq if str(x) not in seen and not seen.add(str(x))]", "title": ""}
{"_id": "d2454", "text": "def size(self):\n        \"\"\"\n        Recursively find size of a tree. Slow.\n        \"\"\"\n\n        if self is NULL:\n            return 0\n        return 1 + self.left.size() + self.right.size()", "title": ""}
{"_id": "d2455", "text": "def data_directory():\n    \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")", "title": ""}
{"_id": "d2456", "text": "def num_leaves(tree):\n    \"\"\"Determine the number of leaves in a tree\"\"\"\n    if tree.is_leaf:\n        return 1\n    else:\n        return num_leaves(tree.left_child) + num_leaves(tree.right_child)", "title": ""}
{"_id": "d2457", "text": "def get_Callable_args_res(clb):\n    \"\"\"Python version independent function to obtain the parameters\n    of a typing.Callable object. Returns as tuple: args, result.\n    Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.\n    \"\"\"\n    try:\n        return clb.__args__, clb.__result__\n    except AttributeError:\n        # Python 3.6\n        return clb.__args__[:-1], clb.__args__[-1]", "title": ""}
{"_id": "d2458", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d2459", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d2460", "text": "def count_rows_with_nans(X):\n    \"\"\"Count the number of rows in 2D arrays that contain any nan values.\"\"\"\n    if X.ndim == 2:\n        return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()", "title": ""}
{"_id": "d2461", "text": "def similarity(self, other):\n        \"\"\"Calculates the cosine similarity between this vector and another\n        vector.\"\"\"\n        if self.magnitude == 0 or other.magnitude == 0:\n            return 0\n\n        return self.dot(other) / self.magnitude", "title": ""}
{"_id": "d2462", "text": "def min_depth(self, root):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: int\n    \"\"\"\n    if root is None:\n        return 0\n    if root.left is not None or root.right is not None:\n        return max(self.minDepth(root.left), self.minDepth(root.right))+1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1", "title": ""}
{"_id": "d2463", "text": "def get_language(self):\n        \"\"\"\n        Get the language parameter from the current request.\n        \"\"\"\n        return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object))", "title": ""}
{"_id": "d2464", "text": "def entropy(string):\n    \"\"\"Compute entropy on the string\"\"\"\n    p, lns = Counter(string), float(len(string))\n    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())", "title": ""}
{"_id": "d2465", "text": "def _get_str_columns(sf):\n    \"\"\"\n    Returns a list of names of columns that are string type.\n    \"\"\"\n    return [name for name in sf.column_names() if sf[name].dtype == str]", "title": ""}
{"_id": "d2466", "text": "def _count_leading_whitespace(text):\n  \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n  idx = 0\n  for idx, char in enumerate(text):\n    if not char.isspace():\n      return idx\n  return idx + 1", "title": ""}
{"_id": "d2467", "text": "def str2int(string_with_int):\n    \"\"\" Collect digits from a string \"\"\"\n    return int(\"\".join([char for char in string_with_int if char in string.digits]) or 0)", "title": ""}
{"_id": "d2468", "text": "def str2bytes(x):\n  \"\"\"Convert input argument to bytes\"\"\"\n  if type(x) is bytes:\n    return x\n  elif type(x) is str:\n    return bytes([ ord(i) for i in x ])\n  else:\n    return str2bytes(str(x))", "title": ""}
{"_id": "d2469", "text": "def get_image_dimension(self, url):\n        \"\"\"\n        Return a tuple that contains (width, height)\n        Pass in a url to an image and find out its size without loading the whole file\n        If the image wxh could not be found, the tuple will contain `None` values\n        \"\"\"\n        w_h = (None, None)\n        try:\n            if url.startswith('//'):\n                url = 'http:' + url\n            data = requests.get(url).content\n            im = Image.open(BytesIO(data))\n\n            w_h = im.size\n        except Exception:\n            logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n        return w_h", "title": ""}
{"_id": "d2470", "text": "def ident():\n    \"\"\"\n    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\n    \"\"\"\n    matrix = stypes.emptyDoubleMatrix()\n    libspice.ident_c(matrix)\n    return stypes.cMatrixToNumpy(matrix)", "title": ""}
{"_id": "d2471", "text": "def dir_modtime(dpath):\n    \"\"\"\n    Returns the latest modification time of all files/subdirectories in a\n    directory\n    \"\"\"\n    return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))", "title": ""}
{"_id": "d2472", "text": "def head_and_tail_print(self, n=5):\n        \"\"\"Display the first and last n elements of a DataFrame.\"\"\"\n        from IPython import display\n        display.display(display.HTML(self._head_and_tail_table(n)))", "title": ""}
{"_id": "d2473", "text": "def entropy(string):\n    \"\"\"Compute entropy on the string\"\"\"\n    p, lns = Counter(string), float(len(string))\n    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())", "title": ""}
{"_id": "d2474", "text": "def get_parent_dir(name):\n    \"\"\"Get the parent directory of a filename.\"\"\"\n    parent_dir = os.path.dirname(os.path.dirname(name))\n    if parent_dir:\n        return parent_dir\n    return os.path.abspath('.')", "title": ""}
{"_id": "d2475", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d2476", "text": "def findfirst(f, coll):\n    \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n    result = list(dropwhile(f, coll))\n    return result[0] if result else None", "title": ""}
{"_id": "d2477", "text": "def polyline(*points):\n    \"\"\"Converts a list of points to a Path composed of lines connecting those \n    points (i.e. a linear spline or polyline).  See also `polygon()`.\"\"\"\n    return Path(*[Line(points[i], points[i+1])\n                  for i in range(len(points) - 1)])", "title": ""}
{"_id": "d2478", "text": "def split_every(n, iterable):\n    \"\"\"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.\"\"\"\n    items = iter(iterable)\n    return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))", "title": ""}
{"_id": "d2479", "text": "def list2dict(list_of_options):\n    \"\"\"Transforms a list of 2 element tuples to a dictionary\"\"\"\n    d = {}\n    for key, value in list_of_options:\n        d[key] = value\n    return d", "title": ""}
{"_id": "d2480", "text": "def fft_freqs(n_fft, fs):\n    \"\"\"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.\n    \"\"\"\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)", "title": ""}
{"_id": "d2481", "text": "def concat(cls, iterables):\n    \"\"\"\n    Similar to #itertools.chain.from_iterable().\n    \"\"\"\n\n    def generator():\n      for it in iterables:\n        for element in it:\n          yield element\n    return cls(generator())", "title": ""}
{"_id": "d2482", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d2483", "text": "def symbol_pos_int(*args, **kwargs):\n    \"\"\"Create a sympy.Symbol with positive and integer assumptions.\"\"\"\n    kwargs.update({'positive': True,\n                   'integer': True})\n    return sympy.Symbol(*args, **kwargs)", "title": ""}
{"_id": "d2484", "text": "def _to_array(value):\n    \"\"\"As a convenience, turn Python lists and tuples into NumPy arrays.\"\"\"\n    if isinstance(value, (tuple, list)):\n        return array(value)\n    elif isinstance(value, (float, int)):\n        return np.float64(value)\n    else:\n        return value", "title": ""}
{"_id": "d2485", "text": "def getvariable(name):\n    \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n    import inspect\n    fr = inspect.currentframe()\n    try:\n        while fr:\n            fr = fr.f_back\n            vars = fr.f_locals\n            if name in vars:\n                return vars[name]\n    except:\n        pass\n    return None", "title": ""}
{"_id": "d2486", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d2487", "text": "def url_to_image(url):\n    \"\"\"\n    Fetch an image from url and convert it into a Pillow Image object\n    \"\"\"\n    r = requests.get(url)\n    image = StringIO(r.content)\n    return image", "title": ""}
{"_id": "d2488", "text": "def home():\n    \"\"\"Temporary helper function to link to the API routes\"\"\"\n    return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \\\n        HTTPStatus.OK", "title": ""}
{"_id": "d2489", "text": "def get(key, default=None):\n    \"\"\" return the key from the request\n    \"\"\"\n    data = get_form() or get_query_string()\n    return data.get(key, default)", "title": ""}
{"_id": "d2490", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d2491", "text": "def difference(ydata1, ydata2):\n    \"\"\"\n\n    Returns the number you should add to ydata1 to make it line up with ydata2\n\n    \"\"\"\n\n    y1 = _n.array(ydata1)\n    y2 = _n.array(ydata2)\n\n    return(sum(y2-y1)/len(ydata1))", "title": ""}
{"_id": "d2492", "text": "def to_simple_rdd(sc, features, labels):\n    \"\"\"Convert numpy arrays of features and labels into\n    an RDD of pairs.\n\n    :param sc: Spark context\n    :param features: numpy array with features\n    :param labels: numpy array with labels\n    :return: Spark RDD with feature-label pairs\n    \"\"\"\n    pairs = [(x, y) for x, y in zip(features, labels)]\n    return sc.parallelize(pairs)", "title": ""}
{"_id": "d2493", "text": "def get_available_gpus():\n  \"\"\"\n  Returns a list of string names of all available GPUs\n  \"\"\"\n  local_device_protos = device_lib.list_local_devices()\n  return [x.name for x in local_device_protos if x.device_type == 'GPU']", "title": ""}
{"_id": "d2494", "text": "def create_task(coro, loop):\n    # pragma: no cover\n    \"\"\"Compatibility wrapper for the loop.create_task() call introduced in\n    3.4.2.\"\"\"\n    if hasattr(loop, 'create_task'):\n        return loop.create_task(coro)\n    return asyncio.Task(coro, loop=loop)", "title": ""}
{"_id": "d2495", "text": "def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):\n  \"\"\"A block of standard 2d convolutions.\"\"\"\n  return conv_block_internal(conv, inputs, filters,\n                             dilation_rates_and_kernel_sizes, **kwargs)", "title": ""}
{"_id": "d2496", "text": "def extract_module_locals(depth=0):\n    \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n    f = sys._getframe(depth + 1)\n    global_ns = f.f_globals\n    module = sys.modules[global_ns['__name__']]\n    return (module, f.f_locals)", "title": ""}
{"_id": "d2497", "text": "def debug(sequence):\n    \"\"\"\n    adds information to the sequence for better debugging, currently only\n    an index property on each point in the sequence.\n    \"\"\"\n    points = []\n    for i, p in enumerate(sequence):\n        copy = Point(p)\n        copy['index'] = i\n        points.append(copy)\n    return sequence.__class__(points)", "title": ""}
{"_id": "d2498", "text": "def get_file_md5sum(path):\n    \"\"\"Calculate the MD5 hash for a file.\"\"\"\n    with open(path, 'rb') as fh:\n        h = str(hashlib.md5(fh.read()).hexdigest())\n    return h", "title": ""}
{"_id": "d2499", "text": "def voronoi(data, line_color=None, line_width=2, f_tooltip=None, cmap=None, max_area=1e4, alpha=220):\n    \"\"\"\n    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\n    \"\"\"\n    from geoplotlib.layers import VoronoiLayer\n    _global_config.layers.append(VoronoiLayer(data, line_color, line_width, f_tooltip, cmap, max_area, alpha))", "title": ""}
{"_id": "d2500", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d2501", "text": "def _elapsed_time(begin_time, end_time):\n    \"\"\"Assuming format YYYY-MM-DD hh:mm:ss\n\n    Returns the elapsed time in seconds\n    \"\"\"\n\n    bt = _str2datetime(begin_time)\n    et = _str2datetime(end_time)\n\n    return float((et - bt).seconds)", "title": ""}
{"_id": "d2502", "text": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "title": ""}
{"_id": "d2503", "text": "def get_var(self, name):\n        \"\"\" Returns the variable set with the given name.\n        \"\"\"\n        for var in self.vars:\n            if var.name == name:\n                return var\n        else:\n            raise ValueError", "title": ""}
{"_id": "d2504", "text": "def c_array(ctype, values):\n    \"\"\"Convert a python string to c array.\"\"\"\n    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):\n        return (ctype * len(values)).from_buffer_copy(values)\n    return (ctype * len(values))(*values)", "title": ""}
{"_id": "d2505", "text": "def node__name__(self):\n        \"\"\"Return the name of this node or its class name.\"\"\"\n\n        return self.node.__name__ \\\n            if self.node.__name__ is not None else self.node.__class__.__name__", "title": ""}
{"_id": "d2506", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d2507", "text": "def load_object_by_name(object_name):\n    \"\"\"Load an object from a module by name\"\"\"\n    mod_name, attr = object_name.rsplit('.', 1)\n    mod = import_module(mod_name)\n    return getattr(mod, attr)", "title": ""}
{"_id": "d2508", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d2509", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d2510", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d2511", "text": "def gray2bgr(img):\n    \"\"\"Convert a grayscale image to BGR image.\n\n    Args:\n        img (ndarray or str): The input image.\n\n    Returns:\n        ndarray: The converted BGR image.\n    \"\"\"\n    img = img[..., None] if img.ndim == 2 else img\n    out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n    return out_img", "title": ""}
{"_id": "d2512", "text": "def matrix_to_gl(matrix):\n    \"\"\"\n    Convert a numpy row- major homogenous transformation matrix\n    to a flat column- major GLfloat transformation.\n\n    Parameters\n    -------------\n    matrix : (4,4) float\n      Row- major homogenous transform\n\n    Returns\n    -------------\n    glmatrix : (16,) gl.GLfloat\n      Transform in pyglet format\n    \"\"\"\n    matrix = np.asanyarray(matrix, dtype=np.float64)\n    if matrix.shape != (4, 4):\n        raise ValueError('matrix must be (4,4)!')\n\n    # switch to column major and flatten to (16,)\n    column = matrix.T.flatten()\n    # convert to GLfloat\n    glmatrix = (gl.GLfloat * 16)(*column)\n\n    return glmatrix", "title": ""}
{"_id": "d2513", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d2514", "text": "def check_output(args):\n    \"\"\"Runs command and returns the output as string.\"\"\"\n    log.debug('run: %s', args)\n    out = subprocess.check_output(args=args).decode('utf-8')\n    log.debug('out: %r', out)\n    return out", "title": ""}
{"_id": "d2515", "text": "def format_timestamp(timestamp):\n        \"\"\"\n        Format the UTC timestamp for Elasticsearch\n        eg. 2014-07-09T08:37:18.000Z\n\n        @see https://docs.python.org/2/library/time.html#time.strftime\n\n        :type timestamp int\n        :rtype: str\n        \"\"\"\n        tz_info = tz.tzutc()\n        return datetime.fromtimestamp(timestamp, tz=tz_info).strftime(\"%Y-%m-%dT%H:%M:%S.000Z\")", "title": ""}
{"_id": "d2516", "text": "def get_page_text(self, page):\n        \"\"\"\n        Downloads and returns the full text of a particular page\n        in the document.\n        \"\"\"\n        url = self.get_page_text_url(page)\n        return self._get_url(url)", "title": ""}
{"_id": "d2517", "text": "def localize(dt):\n    \"\"\"Localize a datetime object to local time.\"\"\"\n    if dt.tzinfo is UTC:\n        return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)\n    # No TZ info so not going to assume anything, return as-is.\n    return dt", "title": ""}
{"_id": "d2518", "text": "def get_parent_dir(name):\n    \"\"\"Get the parent directory of a filename.\"\"\"\n    parent_dir = os.path.dirname(os.path.dirname(name))\n    if parent_dir:\n        return parent_dir\n    return os.path.abspath('.')", "title": ""}
{"_id": "d2519", "text": "def convert_2_utc(self, datetime_, timezone):\n        \"\"\"convert to datetime to UTC offset.\"\"\"\n\n        datetime_ = self.tz_mapper[timezone].localize(datetime_)\n        return datetime_.astimezone(pytz.UTC)", "title": ""}
{"_id": "d2520", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d2521", "text": "def _DateToEpoch(date):\n  \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n  tz_zero = datetime.datetime.utcfromtimestamp(0)\n  diff_sec = int((date - tz_zero).total_seconds())\n  return diff_sec * 1000000", "title": ""}
{"_id": "d2522", "text": "def read(filename):\n    \"\"\"Read and return `filename` in root dir of project and return string\"\"\"\n    return codecs.open(os.path.join(__DIR__, filename), 'r').read()", "title": ""}
{"_id": "d2523", "text": "def convert_timestamp(timestamp):\n    \"\"\"\n    Converts bokehJS timestamp to datetime64.\n    \"\"\"\n    datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)\n    return np.datetime64(datetime.replace(tzinfo=None))", "title": ""}
{"_id": "d2524", "text": "def family_directory(fonts):\n  \"\"\"Get the path of font project directory.\"\"\"\n  if fonts:\n    dirname = os.path.dirname(fonts[0])\n    if dirname == '':\n      dirname = '.'\n    return dirname", "title": ""}
{"_id": "d2525", "text": "def decode_bytes(string):\n    \"\"\" Decodes a given base64 string into bytes.\n\n    :param str string: The string to decode\n    :return: The decoded bytes\n    :rtype: bytes\n    \"\"\"\n\n    if is_string_type(type(string)):\n        string = bytes(string, \"utf-8\")\n    return base64.decodebytes(string)", "title": ""}
{"_id": "d2526", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d2527", "text": "def intToBin(i):\n    \"\"\" Integer to two bytes \"\"\"\n    # devide in two parts (bytes)\n    i1 = i % 256\n    i2 = int(i / 256)\n    # make string (little endian)\n    return chr(i1) + chr(i2)", "title": ""}
{"_id": "d2528", "text": "def p(self):\n        \"\"\"\n        Helper property containing the percentage this slider is \"filled\".\n        \n        This property is read-only.\n        \"\"\"\n        return (self.n-self.nmin)/max((self.nmax-self.nmin),1)", "title": ""}
{"_id": "d2529", "text": "def isbinary(*args):\n    \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n    return all(map(lambda c: isnumber(c) or isbool(c), args))", "title": ""}
{"_id": "d2530", "text": "def extra_funcs(*funcs):\n  \"\"\"Decorator which adds extra functions to be downloaded to the pyboard.\"\"\"\n  def extra_funcs_decorator(real_func):\n    def wrapper(*args, **kwargs):\n      return real_func(*args, **kwargs)\n    wrapper.extra_funcs = list(funcs)\n    wrapper.source = inspect.getsource(real_func)\n    wrapper.name = real_func.__name__\n    return wrapper\n  return extra_funcs_decorator", "title": ""}
{"_id": "d2531", "text": "def csv_to_dicts(file, header=None):\n    \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n    with open(file) as csvfile:\n        return [row for row in csv.DictReader(csvfile, fieldnames=header)]", "title": ""}
{"_id": "d2532", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d2533", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d2534", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d2535", "text": "def remove(parent, idx):\n  \"\"\"Remove a value from a dict.\"\"\"\n  if isinstance(parent, dict):\n    del parent[idx]\n  elif isinstance(parent, list):\n    del parent[int(idx)]\n  else:\n    raise JSONPathError(\"Invalid path for operation\")", "title": ""}
{"_id": "d2536", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d2537", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d2538", "text": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "title": ""}
{"_id": "d2539", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d2540", "text": "def option2tuple(opt):\n    \"\"\"Return a tuple of option, taking possible presence of level into account\"\"\"\n\n    if isinstance(opt[0], int):\n        tup = opt[1], opt[2:]\n    else:\n        tup = opt[0], opt[1:]\n\n    return tup", "title": ""}
{"_id": "d2541", "text": "def remove_list_duplicates(lista, unique=False):\n    \"\"\"\n    Remove duplicated elements in a list.\n    Args:\n        lista: List with elements to clean duplicates.\n    \"\"\"\n    result = []\n    allready = []\n\n    for elem in lista:\n        if elem not in result:\n            result.append(elem)\n        else:\n            allready.append(elem)\n\n    if unique:\n        for elem in allready:\n            result = list(filter((elem).__ne__, result))\n\n    return result", "title": ""}
{"_id": "d2542", "text": "def _run_cmd_get_output(cmd):\n    \"\"\"Runs a shell command, returns console output.\n\n    Mimics python3's subprocess.getoutput\n    \"\"\"\n    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n    out, err = process.communicate()\n    return out or err", "title": ""}
{"_id": "d2543", "text": "def clean_out_dir(directory):\n    \"\"\"\n    Delete all the files and subdirectories in a directory.\n    \"\"\"\n    if not isinstance(directory, path):\n        directory = path(directory)\n    for file_path in directory.files():\n        file_path.remove()\n    for dir_path in directory.dirs():\n        dir_path.rmtree()", "title": ""}
{"_id": "d2544", "text": "def get_width():\n    \"\"\"Get terminal width\"\"\"\n    # Get terminal size\n    ws = struct.pack(\"HHHH\", 0, 0, 0, 0)\n    ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)\n    lines, columns, x, y = struct.unpack(\"HHHH\", ws)\n    width = min(columns * 39 // 40, columns - 2)\n    return width", "title": ""}
{"_id": "d2545", "text": "def _normalize_abmn(abmn):\n    \"\"\"return a normalized version of abmn\n    \"\"\"\n    abmn_2d = np.atleast_2d(abmn)\n    abmn_normalized = np.hstack((\n        np.sort(abmn_2d[:, 0:2], axis=1),\n        np.sort(abmn_2d[:, 2:4], axis=1),\n    ))\n    return abmn_normalized", "title": ""}
{"_id": "d2546", "text": "def size(dtype):\n  \"\"\"Returns the number of bytes to represent this `dtype`.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'size'):\n    return dtype.size\n  return np.dtype(dtype).itemsize", "title": ""}
{"_id": "d2547", "text": "def make_bintree(levels):\n    \"\"\"Make a symmetrical binary tree with @levels\"\"\"\n    G = nx.DiGraph()\n    root = '0'\n    G.add_node(root)\n    add_children(G, root, levels, 2)\n    return G", "title": ""}
{"_id": "d2548", "text": "def index(self, value):\n\t\t\"\"\"\n\t\tReturn the smallest index of the row(s) with this column\n\t\tequal to value.\n\t\t\"\"\"\n\t\tfor i in xrange(len(self.parentNode)):\n\t\t\tif getattr(self.parentNode[i], self.Name) == value:\n\t\t\t\treturn i\n\t\traise ValueError(value)", "title": ""}
{"_id": "d2549", "text": "def refresh(self, document):\n\t\t\"\"\" Load a new copy of a document from the database.  does not\n\t\t\treplace the old one \"\"\"\n\t\ttry:\n\t\t\told_cache_size = self.cache_size\n\t\t\tself.cache_size = 0\n\t\t\tobj = self.query(type(document)).filter_by(mongo_id=document.mongo_id).one()\n\t\tfinally:\n\t\t\tself.cache_size = old_cache_size\n\t\tself.cache_write(obj)\n\t\treturn obj", "title": ""}
{"_id": "d2550", "text": "def __getitem__(self, index):\n    \"\"\"Get the item at the given index.\n\n    Index is a tuple of (row, col)\n    \"\"\"\n    row, col = index\n    return self.rows[row][col]", "title": ""}
{"_id": "d2551", "text": "def update_screen(self):\n        \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n        self.clock.tick(self.FPS)\n        pygame.display.update()", "title": ""}
{"_id": "d2552", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d2553", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d2554", "text": "def _get_local_ip(self):\n        \"\"\"Try to determine the local IP address of the machine.\"\"\"\n        try:\n            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n            # Use Google Public DNS server to determine own IP\n            sock.connect(('8.8.8.8', 80))\n\n            return sock.getsockname()[0]\n        except socket.error:\n            try:\n                return socket.gethostbyname(socket.gethostname())\n            except socket.gaierror:\n                return '127.0.0.1'\n        finally:\n            sock.close()", "title": ""}
{"_id": "d2555", "text": "def round_to_float(number, precision):\n    \"\"\"Round a float to a precision\"\"\"\n    rounded = Decimal(str(floor((number + precision / 2) // precision))\n                      ) * Decimal(str(precision))\n    return float(rounded)", "title": ""}
{"_id": "d2556", "text": "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location", "title": ""}
{"_id": "d2557", "text": "def series_table_row_offset(self, series):\n        \"\"\"\n        Return the number of rows preceding the data table for *series* in\n        the Excel worksheet.\n        \"\"\"\n        title_and_spacer_rows = series.index * 2\n        data_point_rows = series.data_point_offset\n        return title_and_spacer_rows + data_point_rows", "title": ""}
{"_id": "d2558", "text": "def class_name(obj):\n    \"\"\"\n    Get the name of an object, including the module name if available.\n    \"\"\"\n\n    name = obj.__name__\n    module = getattr(obj, '__module__')\n\n    if module:\n        name = f'{module}.{name}'\n    return name", "title": ""}
{"_id": "d2559", "text": "def initialize_api(flask_app):\n    \"\"\"Initialize an API.\"\"\"\n    if not flask_restplus:\n        return\n\n    api = flask_restplus.Api(version=\"1.0\", title=\"My Example API\")\n    api.add_resource(HelloWorld, \"/hello\")\n\n    blueprint = flask.Blueprint(\"api\", __name__, url_prefix=\"/api\")\n    api.init_app(blueprint)\n    flask_app.register_blueprint(blueprint)", "title": ""}
{"_id": "d2560", "text": "def class_name(obj):\n    \"\"\"\n    Get the name of an object, including the module name if available.\n    \"\"\"\n\n    name = obj.__name__\n    module = getattr(obj, '__module__')\n\n    if module:\n        name = f'{module}.{name}'\n    return name", "title": ""}
{"_id": "d2561", "text": "def register_extension_class(ext, base, *args, **kwargs):\n    \"\"\"Instantiate the given extension class and register as a public attribute of the given base.\n\n    README: The expected protocol here is to instantiate the given extension and pass the base\n    object as the first positional argument, then unpack args and kwargs as additional arguments to\n    the extension's constructor.\n    \"\"\"\n    ext_instance = ext.plugin(base, *args, **kwargs)\n    setattr(base, ext.name.lstrip('_'), ext_instance)", "title": ""}
{"_id": "d2562", "text": "def dir_modtime(dpath):\n    \"\"\"\n    Returns the latest modification time of all files/subdirectories in a\n    directory\n    \"\"\"\n    return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))", "title": ""}
{"_id": "d2563", "text": "def array_dim(arr):\n    \"\"\"Return the size of a multidimansional array.\n    \"\"\"\n    dim = []\n    while True:\n        try:\n            dim.append(len(arr))\n            arr = arr[0]\n        except TypeError:\n            return dim", "title": ""}
{"_id": "d2564", "text": "def get_top(self, *args, **kwargs):\n        \"\"\"Return a get_content generator for top submissions.\n\n        Corresponds to the submissions provided by\n        ``https://www.reddit.com/top/`` for the session.\n\n        The additional parameters are passed directly into\n        :meth:`.get_content`. Note: the `url` parameter cannot be altered.\n\n        \"\"\"\n        return self.get_content(self.config['top'], *args, **kwargs)", "title": ""}
{"_id": "d2565", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d2566", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d2567", "text": "def size(self):\n        \"\"\"The size of this parameter, equivalent to self.value.size\"\"\"\n        return np.multiply.reduce(self.shape, dtype=np.int32)", "title": ""}
{"_id": "d2568", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d2569", "text": "def length(self):\n        \"\"\"Array of vector lengths\"\"\"\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "title": ""}
{"_id": "d2570", "text": "def get_user_by_id(self, id):\n        \"\"\"Retrieve a User object by ID.\"\"\"\n        return self.db_adapter.get_object(self.UserClass, id=id)", "title": ""}
{"_id": "d2571", "text": "async def join(self, ctx, *, channel: discord.VoiceChannel):\n        \"\"\"Joins a voice channel\"\"\"\n\n        if ctx.voice_client is not None:\n            return await ctx.voice_client.move_to(channel)\n\n        await channel.connect()", "title": ""}
{"_id": "d2572", "text": "def load_object_by_name(object_name):\n    \"\"\"Load an object from a module by name\"\"\"\n    mod_name, attr = object_name.rsplit('.', 1)\n    mod = import_module(mod_name)\n    return getattr(mod, attr)", "title": ""}
{"_id": "d2573", "text": "async def join(self, ctx, *, channel: discord.VoiceChannel):\n        \"\"\"Joins a voice channel\"\"\"\n\n        if ctx.voice_client is not None:\n            return await ctx.voice_client.move_to(channel)\n\n        await channel.connect()", "title": ""}
{"_id": "d2574", "text": "def OnMove(self, event):\n        \"\"\"Main window move event\"\"\"\n\n        # Store window position in config\n        position = self.main_window.GetScreenPositionTuple()\n\n        config[\"window_position\"] = repr(position)", "title": ""}
{"_id": "d2575", "text": "def _handle_chat_name(self, data):\n        \"\"\"Handle user name changes\"\"\"\n\n        self.room.user.nick = data\n        self.conn.enqueue_data(\"user\", self.room.user)", "title": ""}
{"_id": "d2576", "text": "def size():\n    \"\"\"Determines the height and width of the console window\n\n        Returns:\n            tuple of int: The height in lines, then width in characters\n    \"\"\"\n    try:\n        assert os != 'nt' and sys.stdout.isatty()\n        rows, columns = os.popen('stty size', 'r').read().split()\n    except (AssertionError, AttributeError, ValueError):\n        # in case of failure, use dimensions of a full screen 13\" laptop\n        rows, columns = DEFAULT_HEIGHT, DEFAULT_WIDTH\n\n    return int(rows), int(columns)", "title": ""}
{"_id": "d2577", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d2578", "text": "def auth_request(self, url, headers, body):\n        \"\"\"Perform auth request for token.\"\"\"\n\n        return self.req.post(url, headers, body=body)", "title": ""}
{"_id": "d2579", "text": "def get_plain_image_as_widget(self):\n        \"\"\"Used for generating thumbnails.  Does not include overlaid\n        graphics.\n        \"\"\"\n        arr = self.getwin_array(order=self.rgb_order)\n        image = self._get_qimage(arr, self.qimg_fmt)\n        return image", "title": ""}
{"_id": "d2580", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d2581", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d2582", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d2583", "text": "def copy(self):\n        \"\"\"\n        Creates a copy of model\n        \"\"\"\n        return self.__class__(field_type=self.get_field_type(), data=self.export_data())", "title": ""}
{"_id": "d2584", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d2585", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d2586", "text": "def ffmpeg_works():\n  \"\"\"Tries to encode images with ffmpeg to check if it 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", "title": ""}
{"_id": "d2587", "text": "def managepy(cmd, extra=None):\n    \"\"\"Run manage.py using this component's specific Django settings\"\"\"\n\n    extra = extra.split() if extra else []\n    run_django_cli(['invoke', cmd] + extra)", "title": ""}
{"_id": "d2588", "text": "def branches(self):\n        \"\"\"All branches in a list\"\"\"\n        result = self.git(self.default + ['branch', '-a', '--no-color'])\n        return [l.strip(' *\\n') for l in result.split('\\n') if l.strip(' *\\n')]", "title": ""}
{"_id": "d2589", "text": "def get_qualified_name(_object):\n    \"\"\"Return the Fully Qualified Name from an instance or class.\"\"\"\n    module = _object.__module__\n    if hasattr(_object, '__name__'):\n        _class = _object.__name__\n\n    else:\n        _class = _object.__class__.__name__\n\n    return module + '.' + _class", "title": ""}
{"_id": "d2590", "text": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "title": ""}
{"_id": "d2591", "text": "def __init__(self, form_post_data=None, *args, **kwargs):\n        \"\"\"\n        Overriding init so we can set the post vars like a normal form and generate\n        the form the same way Django does.\n        \"\"\"\n        kwargs.update({'form_post_data': form_post_data})\n        super(MongoModelForm, self).__init__(*args, **kwargs)", "title": ""}
{"_id": "d2592", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d2593", "text": "def object_to_json(obj, indent=2):\n    \"\"\"\n        transform object to json\n    \"\"\"\n    instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder)\n    return instance_json", "title": ""}
{"_id": "d2594", "text": "def _text_to_graphiz(self, text):\n        \"\"\"create a graphviz graph from text\"\"\"\n        dot = Source(text, format='svg')\n        return dot.pipe().decode('utf-8')", "title": ""}
{"_id": "d2595", "text": "def full_like(array, value, dtype=None):\n    \"\"\" Create a shared memory array with the same shape and type as a given array, filled with `value`.\n    \"\"\"\n    shared = empty_like(array, dtype)\n    shared[:] = value\n    return shared", "title": ""}
{"_id": "d2596", "text": "def weighted_std(values, weights):\n    \"\"\" Calculate standard deviation weighted by errors \"\"\"\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)", "title": ""}
{"_id": "d2597", "text": "def _check_conversion(key, valid_dict):\n    \"\"\"Check for existence of key in dict, return value or raise error\"\"\"\n    if key not in valid_dict and key not in valid_dict.values():\n        # Only show users the nice string values\n        keys = [v for v in valid_dict.keys() if isinstance(v, string_types)]\n        raise ValueError('value must be one of %s, not %s' % (keys, key))\n    return valid_dict[key] if key in valid_dict else key", "title": ""}
{"_id": "d2598", "text": "def __del__(self):\n        \"\"\"Frees all resources.\n        \"\"\"\n        if hasattr(self, '_Api'):\n            self._Api.close()\n\n        self._Logger.info('object destroyed')", "title": ""}
{"_id": "d2599", "text": "def fill_document(doc):\n    \"\"\"Add a section, a subsection and some text to the document.\n\n    :param doc: the document\n    :type doc: :class:`pylatex.document.Document` instance\n    \"\"\"\n    with doc.create(Section('A section')):\n        doc.append('Some regular text and some ')\n        doc.append(italic('italic text. '))\n\n        with doc.create(Subsection('A subsection')):\n            doc.append('Also some crazy characters: $&#{}')", "title": ""}
{"_id": "d2600", "text": "def hex_to_hsv(color):\n    \"\"\"\n    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')\n    \"\"\"\n    color = normalize(color)\n    color = color[1:]\n    # color=tuple(ord(c)/255.0 for c in color.decode('hex'))\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)", "title": ""}
{"_id": "d2601", "text": "def polite_string(a_string):\n    \"\"\"Returns a \"proper\" string that should work in both Py3/Py2\"\"\"\n    if is_py3() and hasattr(a_string, 'decode'):\n        try:\n            return a_string.decode('utf-8')\n        except UnicodeDecodeError:\n            return a_string\n\n    return a_string", "title": ""}
{"_id": "d2602", "text": "def isfunc(x):\n    \"\"\"\n    Returns `True` if the given value is a function or method object.\n\n    Arguments:\n        x (mixed): value to check.\n\n    Returns:\n        bool\n    \"\"\"\n    return any([\n        inspect.isfunction(x) and not asyncio.iscoroutinefunction(x),\n        inspect.ismethod(x) and not asyncio.iscoroutinefunction(x)\n    ])", "title": ""}
{"_id": "d2603", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d2604", "text": "def action(self):\n        \"\"\"\n        This class overrides this method\n        \"\"\"\n        self.return_value = self.function(*self.args, **self.kwargs)", "title": ""}
{"_id": "d2605", "text": "def _open_url(url):\n    \"\"\"Open a HTTP connection to the URL and return a file-like object.\"\"\"\n    response = requests.get(url, stream=True)\n    if response.status_code != 200:\n        raise IOError(\"Unable to download {}, HTTP {}\".format(url, response.status_code))\n    return response", "title": ""}
{"_id": "d2606", "text": "def set_parent_path(self, value):\n        \"\"\"\n        Set the parent path and the path from the new parent path.\n\n        :param value: The path to the object's parent\n        \"\"\"\n\n        self._parent_path = value\n        self.path = value + r'/' + self.name\n        self._update_childrens_parent_path()", "title": ""}
{"_id": "d2607", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d2608", "text": "def normalize_time(timestamp):\n    \"\"\"Normalize time in arbitrary timezone to UTC naive object.\"\"\"\n    offset = timestamp.utcoffset()\n    if offset is None:\n        return timestamp\n    return timestamp.replace(tzinfo=None) - offset", "title": ""}
{"_id": "d2609", "text": "def _get_all_constants():\n    \"\"\"\n    Get list of all uppercase, non-private globals (doesn't start with ``_``).\n\n    Returns:\n        list: Uppercase names defined in `globals()` (variables from this \\\n              module).\n    \"\"\"\n    return [\n        key for key in globals().keys()\n        if all([\n            not key.startswith(\"_\"),          # publicly accesible\n            key.upper() == key,               # uppercase\n            type(globals()[key]) in _ALLOWED  # and with type from _ALLOWED\n        ])\n    ]", "title": ""}
{"_id": "d2610", "text": "def inverse_transform(self, X):\n        \"\"\"Undo the scaling of X according to feature_range.\n\n        Note that if truncate is true, any truncated points will not\n        be restored exactly.\n\n        Parameters\n        ----------\n        X : array-like with shape [n_samples, n_features]\n            Input data that will be transformed.\n        \"\"\"\n        X = check_array(X, copy=self.copy)\n        X -= self.min_\n        X /= self.scale_\n        return X", "title": ""}
{"_id": "d2611", "text": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "title": ""}
{"_id": "d2612", "text": "def closeEvent(self, e):\n        \"\"\"Qt slot when the window is closed.\"\"\"\n        self.emit('close_widget')\n        super(DockWidget, self).closeEvent(e)", "title": ""}
{"_id": "d2613", "text": "def wipe(self):\n        \"\"\" Wipe the store\n        \"\"\"\n        keys = list(self.keys()).copy()\n        for key in keys:\n            self.delete(key)", "title": ""}
{"_id": "d2614", "text": "def datetime_to_timezone(date, tz=\"UTC\"):\n    \"\"\" convert naive datetime to timezone-aware datetime \"\"\"\n    if not date.tzinfo:\n        date = date.replace(tzinfo=timezone(get_timezone()))\n    return date.astimezone(timezone(tz))", "title": ""}
{"_id": "d2615", "text": "def unit_key_from_name(name):\n  \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n  result = name\n\n  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n    result = result.replace(old, new)\n\n  # Collapse redundant underscores and convert to uppercase.\n  result = re.sub(r'_+', '_', result.upper())\n\n  return result", "title": ""}
{"_id": "d2616", "text": "def geodetic_to_ecef(latitude, longitude, altitude):\n    \"\"\"Convert WGS84 geodetic coordinates into ECEF\n    \n    Parameters\n    ----------\n    latitude : float or array_like\n        Geodetic latitude (degrees)\n    longitude : float or array_like\n        Geodetic longitude (degrees)\n    altitude : float or array_like\n        Geodetic Height (km) above WGS84 reference ellipsoid.\n        \n    Returns\n    -------\n    x, y, z\n        numpy arrays of x, y, z locations in km\n        \n    \"\"\"\n\n\n    ellip = np.sqrt(1. - earth_b ** 2 / earth_a ** 2)\n    r_n = earth_a / np.sqrt(1. - ellip ** 2 * np.sin(np.deg2rad(latitude)) ** 2)\n\n    # colatitude = 90. - latitude\n    x = (r_n + altitude) * np.cos(np.deg2rad(latitude)) * np.cos(np.deg2rad(longitude))\n    y = (r_n + altitude) * np.cos(np.deg2rad(latitude)) * np.sin(np.deg2rad(longitude))\n    z = (r_n * (1. - ellip ** 2) + altitude) * np.sin(np.deg2rad(latitude))\n\n    return x, y, z", "title": ""}
{"_id": "d2617", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d2618", "text": "def scan(client, query=None, scroll='5m', raise_on_error=True,\n         preserve_order=False, size=1000, **kwargs):\n    \"\"\"\n    Simple abstraction on top of the\n    :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that\n    yields all hits as returned by underlining scroll requests.\n    By default scan does not return results in any pre-determined order. To\n    have a standard order in the returned documents (either by score or\n    explicit sort definition) when scrolling, use ``preserve_order=True``. This\n    may be an expensive operation and will negate the performance benefits of\n    using ``scan``.\n    :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n    :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api\n    :arg scroll: Specify how long a consistent view of the index should be\n        maintained for scrolled search\n    :arg raise_on_error: raises an exception (``ScanError``) if an error is\n        encountered (some shards fail to execute). By default we raise.\n    :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will\n        cause the scroll to paginate with preserving the order. Note that this\n        can be an extremely expensive operation and can easily lead to\n        unpredictable results, use with caution.\n    :arg size: size (per shard) of the batch send at each iteration.\n    Any additional keyword arguments will be passed to the initial\n    :meth:`~elasticsearch.Elasticsearch.search` call::\n        scan(es,\n            query={\"query\": {\"match\": {\"title\": \"python\"}}},\n            index=\"orders-*\",\n            doc_type=\"books\"\n        )\n    \"\"\"\n    if not preserve_order:\n        kwargs['search_type'] = 'scan'\n    # initial search\n    resp = client.search(body=query, scroll=scroll, size=size, **kwargs)\n\n    scroll_id = resp.get('_scroll_id')\n    if scroll_id is None:\n        return\n\n    first_run = True\n    while True:\n        # if we didn't set search_type to scan initial search contains data\n        if preserve_order and first_run:\n            first_run = False\n        else:\n            resp = client.scroll(scroll_id, scroll=scroll)\n\n        for hit in resp['hits']['hits']:\n            yield hit\n\n        # check if we have any errrors\n        if resp[\"_shards\"][\"failed\"]:\n            logger.warning(\n                'Scroll request has failed on %d shards out of %d.',\n                resp['_shards']['failed'], resp['_shards']['total']\n            )\n            if raise_on_error:\n                raise ScanError(\n                    'Scroll request has failed on %d shards out of %d.' %\n                    (resp['_shards']['failed'], resp['_shards']['total'])\n                )\n\n        scroll_id = resp.get('_scroll_id')\n        # end of scroll\n        if scroll_id is None or not resp['hits']['hits']:\n            break", "title": ""}
{"_id": "d2619", "text": "def get_file_size(filename):\n    \"\"\"\n    Get the file size of a given file\n\n    :param filename: string: pathname of a file\n    :return: human readable filesize\n    \"\"\"\n    if os.path.isfile(filename):\n        return convert_size(os.path.getsize(filename))\n    return None", "title": ""}
{"_id": "d2620", "text": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "title": ""}
{"_id": "d2621", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d2622", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d2623", "text": "def is_valid_regex(regex):\n    \"\"\"Function for checking a valid regex.\"\"\"\n    if len(regex) == 0:\n        return False\n    try:\n        re.compile(regex)\n        return True\n    except sre_constants.error:\n        return False", "title": ""}
{"_id": "d2624", "text": "def requests_post(url, data=None, json=None, **kwargs):\n    \"\"\"Requests-mock requests.post wrapper.\"\"\"\n    return requests_request('post', url, data=data, json=json, **kwargs)", "title": ""}
{"_id": "d2625", "text": "def check_length(value, length):\n    \"\"\"\n    Checks length of value\n\n    @param value: value to check\n    @type value: C{str}\n\n    @param length: length checking for\n    @type length: C{int}\n\n    @return: None when check successful\n\n    @raise ValueError: check failed\n    \"\"\"\n    _length = len(value)\n    if _length != length:\n        raise ValueError(\"length must be %d, not %d\" % \\\n                         (length, _length))", "title": ""}
{"_id": "d2626", "text": "def session_to_epoch(timestamp):\n    \"\"\" converts Synergy Timestamp for session to UTC zone seconds since epoch \"\"\"\n    utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()\n    return calendar.timegm(utc_timetuple)", "title": ""}
{"_id": "d2627", "text": "def is_type(value):\n        \"\"\"Determine if value is an instance or subclass of the class Type.\"\"\"\n        if isinstance(value, type):\n            return issubclass(value, Type)\n        return isinstance(value, Type)", "title": ""}
{"_id": "d2628", "text": "def session_to_epoch(timestamp):\n    \"\"\" converts Synergy Timestamp for session to UTC zone seconds since epoch \"\"\"\n    utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()\n    return calendar.timegm(utc_timetuple)", "title": ""}
{"_id": "d2629", "text": "def rm_empty_indices(*args):\n    \"\"\"\n    Remove unwanted list indices. First argument is the list\n    of indices to remove. Other elements are the lists\n    to trim.\n    \"\"\"\n    rm_inds = args[0]\n\n    if not rm_inds:\n        return args[1:]\n\n    keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n    return [[a[i] for i in keep_inds] for a in args[1:]]", "title": ""}
{"_id": "d2630", "text": "def line_line_collide(line1, line2):\n    \"\"\"Determine if two line segments meet.\n\n    This is a helper for :func:`convex_hull_collide` in the\n    special case that the two convex hulls are actually\n    just line segments. (Even in this case, this is only\n    problematic if both segments are on a single line.)\n\n    Args:\n        line1 (numpy.ndarray): ``2 x 2`` array of start and end nodes.\n        line2 (numpy.ndarray): ``2 x 2`` array of start and end nodes.\n\n    Returns:\n        bool: Indicating if the line segments collide.\n    \"\"\"\n    s, t, success = segment_intersection(\n        line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1]\n    )\n    if success:\n        return _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval(\n            t, 0.0, 1.0\n        )\n\n    else:\n        disjoint, _ = parallel_lines_parameters(\n            line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1]\n        )\n        return not disjoint", "title": ""}
{"_id": "d2631", "text": "def is_type(value):\n        \"\"\"Determine if value is an instance or subclass of the class Type.\"\"\"\n        if isinstance(value, type):\n            return issubclass(value, Type)\n        return isinstance(value, Type)", "title": ""}
{"_id": "d2632", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d2633", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d2634", "text": "def _escape(self, s):\n        \"\"\"Escape bad characters for regular expressions.\n\n        Similar to `re.escape` but allows '%' to pass through.\n\n        \"\"\"\n        for ch, r_ch in self.ESCAPE_SETS:\n            s = s.replace(ch, r_ch)\n        return s", "title": ""}
{"_id": "d2635", "text": "def copy(string, **kwargs):\n    \"\"\"Copy given string into system clipboard.\"\"\"\n    window = Tk()\n    window.withdraw()\n    window.clipboard_clear()\n    window.clipboard_append(string)\n    window.destroy()\n    return", "title": ""}
{"_id": "d2636", "text": "def quote(s, unsafe='/'):\n    \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n    encoded value as the value.\"\"\"\n    res = s.replace('%', '%25')\n    for c in unsafe:\n        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n    return res", "title": ""}
{"_id": "d2637", "text": "def __call__(self, xy):\n        \"\"\"Project x and y\"\"\"\n        x, y = xy\n        return (self.x(x), self.y(y))", "title": ""}
{"_id": "d2638", "text": "def fast_exit(code):\n    \"\"\"Exit without garbage collection, this speeds up exit by about 10ms for\n    things like bash completion.\n    \"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(code)", "title": ""}
{"_id": "d2639", "text": "def __init__(self, ba=None):\n        \"\"\"Constructor.\"\"\"\n        self.bytearray = ba or (bytearray(b'\\0') * self.SIZEOF)", "title": ""}
{"_id": "d2640", "text": "def relative_path(path):\n    \"\"\"\n    Return the given path relative to this file.\n    \"\"\"\n    return os.path.join(os.path.dirname(__file__), path)", "title": ""}
{"_id": "d2641", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d2642", "text": "def double_exponential_moving_average(data, period):\n    \"\"\"\n    Double Exponential Moving Average.\n\n    Formula:\n    DEMA = 2*EMA - EMA(EMA)\n    \"\"\"\n    catch_errors.check_for_period_error(data, period)\n\n    dema = (2 * ema(data, period)) - ema(ema(data, period), period)\n    return dema", "title": ""}
{"_id": "d2643", "text": "def is_file_url(url):\n    \"\"\"Returns true if the given url is a file url\"\"\"\n    from .misc import to_text\n\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\"", "title": ""}
{"_id": "d2644", "text": "def save_image(pdf_path, img_path, page_num):\n    \"\"\"\n\n    Creates images for a page of the input pdf document and saves it\n    at img_path.\n\n    :param pdf_path: path to pdf to create images for.\n    :param img_path: path where to save the images.\n    :param page_num: page number to create image from in the pdf file.\n    :return:\n    \"\"\"\n    pdf_img = Image(filename=\"{}[{}]\".format(pdf_path, page_num))\n    with pdf_img.convert(\"png\") as converted:\n        # Set white background.\n        converted.background_color = Color(\"white\")\n        converted.alpha_channel = \"remove\"\n        converted.save(filename=img_path)", "title": ""}
{"_id": "d2645", "text": "def go_to_new_line(self):\n        \"\"\"Go to the end of the current line and create a new line\"\"\"\n        self.stdkey_end(False, False)\n        self.insert_text(self.get_line_separator())", "title": ""}
{"_id": "d2646", "text": "def version_triple(tag):\n    \"\"\"\n    returns: a triple of integers from a version tag\n    \"\"\"\n    groups = re.match(r'v?(\\d+)\\.(\\d+)\\.(\\d+)', tag).groups()\n    return tuple(int(n) for n in groups)", "title": ""}
{"_id": "d2647", "text": "def __next__(self, reward, ask_id, lbl):\n        \"\"\"For Python3 compatibility of generator.\"\"\"\n        return self.next(reward, ask_id, lbl)", "title": ""}
{"_id": "d2648", "text": "def contains_extractor(document):\n    \"\"\"A basic document feature extractor that returns a dict of words that the\n    document contains.\"\"\"\n    tokens = _get_document_tokens(document)\n    features = dict((u'contains({0})'.format(w), True) for w in tokens)\n    return features", "title": ""}
{"_id": "d2649", "text": "def download_json(local_filename, url, clobber=False):\n    \"\"\"Download the given JSON file, and pretty-print before we output it.\"\"\"\n    with open(local_filename, 'w') as json_file:\n        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))", "title": ""}
{"_id": "d2650", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d2651", "text": "def clean_tmpdir(path):\n    \"\"\"Invoked atexit, this removes our tmpdir\"\"\"\n    if os.path.exists(path) and \\\n       os.path.isdir(path):\n        rmtree(path)", "title": ""}
{"_id": "d2652", "text": "def _heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "title": ""}
{"_id": "d2653", "text": "def get_method_names(obj):\n        \"\"\"\n        Gets names of all methods implemented in specified object.\n\n        :param obj: an object to introspect.\n\n        :return: a list with method names.\n        \"\"\"\n        method_names = []\n        \n        for method_name in dir(obj):\n\n            method = getattr(obj, method_name)\n\n            if MethodReflector._is_method(method, method_name):\n                method_names.append(method_name)\n\n        return method_names", "title": ""}
{"_id": "d2654", "text": "def iterate(obj):\n\t\"\"\"Loop over an iterable and track progress, including first and last state.\n\t\n\tOn each iteration yield an Iteration named tuple with the first and last flags, current element index, total\n\titerable length (if possible to acquire), and value, in that order.\n\t\n\t\tfor iteration in iterate(something):\n\t\t\titeration.value  # Do something.\n\t\n\tYou can unpack these safely:\n\t\n\t\tfor first, last, index, total, value in iterate(something):\n\t\t\tpass\n\t\n\tIf you want to unpack the values you are iterating across, you can by wrapping the nested unpacking in parenthesis:\n\t\n\t\tfor first, last, index, total, (foo, bar, baz) in iterate(something):\n\t\t\tpass\n\t\n\tEven if the length of the iterable can't be reliably determined this function will still capture the \"last\" state\n\tof the final loop iteration.  (Basically: this works with generators.)\n\t\n\tThis process is about 10x slower than simple enumeration on CPython 3.4, so only use it where you actually need to\n\ttrack state.  Use `enumerate()` elsewhere.\n\t\"\"\"\n\t\n\tglobal next, Iteration\n\tnext = next\n\tIteration = Iteration\n\t\n\ttotal = len(obj) if isinstance(obj, Sized) else None\n\titerator = iter(obj)\n\tfirst = True\n\tlast = False\n\ti = 0\n\t\n\ttry:\n\t\tvalue = next(iterator)\n\texcept StopIteration:\n\t\treturn\n\t\n\twhile True:\n\t\ttry:\n\t\t\tnext_value = next(iterator)\n\t\texcept StopIteration:\n\t\t\tlast = True\n\t\t\n\t\tyield Iteration(first, last, i, total, value)\n\t\tif last: return\n\t\t\n\t\tvalue = next_value\n\t\ti += 1\n\t\tfirst = False", "title": ""}
{"_id": "d2655", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d2656", "text": "def _select_features(example, feature_list=None):\n  \"\"\"Select a subset of features from the example dict.\"\"\"\n  feature_list = feature_list or [\"inputs\", \"targets\"]\n  return {f: example[f] for f in feature_list}", "title": ""}
{"_id": "d2657", "text": "def datatype(dbtype, description, cursor):\n    \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n    dt = cursor.db.introspection.get_field_type(dbtype, description)\n    if type(dt) is tuple:\n        return dt[0]\n    else:\n        return dt", "title": ""}
{"_id": "d2658", "text": "def get_last(self, table=None):\n        \"\"\"Just the last entry.\"\"\"\n        if table is None: table = self.main_table\n        query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n        return self.own_cursor.execute(query).fetchone()", "title": ""}
{"_id": "d2659", "text": "def get_list_dimensions(_list):\n    \"\"\"\n    Takes a nested list and returns the size of each dimension followed\n    by the element type in the list\n    \"\"\"\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []", "title": ""}
{"_id": "d2660", "text": "def stft_magnitude(signal, fft_length,\n                   hop_length=None,\n                   window_length=None):\n  \"\"\"Calculate the short-time Fourier transform magnitude.\n\n  Args:\n    signal: 1D np.array of the input time-domain signal.\n    fft_length: Size of the FFT to apply.\n    hop_length: Advance (in samples) between each frame passed to FFT.\n    window_length: Length of each block of samples to pass to FFT.\n\n  Returns:\n    2D np.array where each row contains the magnitudes of the fft_length/2+1\n    unique values of the FFT for the corresponding frame of input samples.\n  \"\"\"\n  frames = frame(signal, window_length, hop_length)\n  # Apply frame window to each frame. We use a periodic Hann (cosine of period\n  # window_length) instead of the symmetric Hann of np.hanning (period\n  # window_length-1).\n  window = periodic_hann(window_length)\n  windowed_frames = frames * window\n  return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))", "title": ""}
{"_id": "d2661", "text": "def wget(url):\n    \"\"\"\n    Download the page into a string\n    \"\"\"\n    import urllib.parse\n    request = urllib.request.urlopen(url)\n    filestring = request.read()\n    return filestring", "title": ""}
{"_id": "d2662", "text": "def _read_text(self, filename):\n        \"\"\"\n        Helper that reads the UTF-8 content of the specified file, or\n        None if the file doesn't exist. This returns a unicode string.\n        \"\"\"\n        with io.open(filename, 'rt', encoding='utf-8') as f:\n            return f.read()", "title": ""}
{"_id": "d2663", "text": "def pods(self):\n        \"\"\" A list of kubernetes pods corresponding to current workers\n\n        See Also\n        --------\n        KubeCluster.logs\n        \"\"\"\n        return self.core_api.list_namespaced_pod(\n            self.namespace,\n            label_selector=format_labels(self.pod_template.metadata.labels)\n        ).items", "title": ""}
{"_id": "d2664", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d2665", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d2666", "text": "def fill_nulls(self, col: str):\n        \"\"\"\n        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\")``\n        \"\"\"\n        n = [None, \"\"]\n        try:\n            self.df[col] = self.df[col].replace(n, nan)\n        except Exception as e:\n            self.err(e)", "title": ""}
{"_id": "d2667", "text": "def display_len(text):\n    \"\"\"\n    Get the display length of a string. This can differ from the character\n    length if the string contains wide characters.\n    \"\"\"\n    text = unicodedata.normalize('NFD', text)\n    return sum(char_width(char) for char in text)", "title": ""}
{"_id": "d2668", "text": "def inpaint(self):\n        \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n        import inpaint\n        filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n        self.raster_data = np.ma.masked_invalid(filled)", "title": ""}
{"_id": "d2669", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d2670", "text": "def clean_dataframe(df):\n    \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n    df = df.fillna(method='ffill')\n    df = df.fillna(0.0)\n    return df", "title": ""}
{"_id": "d2671", "text": "def count_rows(self, table_name):\n        \"\"\"Return the number of entries in a table by counting them.\"\"\"\n        self.table_must_exist(table_name)\n        query = \"SELECT COUNT (*) FROM `%s`\" % table_name.lower()\n        self.own_cursor.execute(query)\n        return int(self.own_cursor.fetchone()[0])", "title": ""}
{"_id": "d2672", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d2673", "text": "def _hide_tick_lines_and_labels(axis):\n    \"\"\"\n    Set visible property of ticklines and ticklabels of an axis to False\n    \"\"\"\n    for item in axis.get_ticklines() + axis.get_ticklabels():\n        item.set_visible(False)", "title": ""}
{"_id": "d2674", "text": "def _drop_str_columns(df):\n    \"\"\"\n\n    Parameters\n    ----------\n    df : DataFrame\n\n    Returns\n    -------\n\n    \"\"\"\n    str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())\n    str_column_names = list(map(lambda pair: pair[0], str_columns))\n\n    return df.drop(str_column_names)", "title": ""}
{"_id": "d2675", "text": "def getpass(self, prompt, default=None):\n        \"\"\"Provide a password prompt.\"\"\"\n        return click.prompt(prompt, hide_input=True, default=default)", "title": ""}
{"_id": "d2676", "text": "def median_high(data):\n    \"\"\"Return the high median of data.\n\n    When the number of data points is odd, the middle value is returned.\n    When it is even, the larger of the two middle values is returned.\n\n    \"\"\"\n    data = sorted(data)\n    n = len(data)\n    if n == 0:\n        raise StatisticsError(\"no median for empty data\")\n    return data[n // 2]", "title": ""}
{"_id": "d2677", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d2678", "text": "def vec_angle(a, b):\n    \"\"\"\n    Calculate angle between two vectors\n    \"\"\"\n    cosang = np.dot(a, b)\n    sinang = fast_norm(np.cross(a, b))\n    return np.arctan2(sinang, cosang)", "title": ""}
{"_id": "d2679", "text": "def finish():\n    \"\"\"Print warning about interrupt and empty the job queue.\"\"\"\n    out.warn(\"Interrupted!\")\n    for t in threads:\n        t.stop()\n    jobs.clear()\n    out.warn(\"Waiting for download threads to finish.\")", "title": ""}
{"_id": "d2680", "text": "def _to_corrected_pandas_type(dt):\n    \"\"\"\n    When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n    This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n    \"\"\"\n    import numpy as np\n    if type(dt) == ByteType:\n        return np.int8\n    elif type(dt) == ShortType:\n        return np.int16\n    elif type(dt) == IntegerType:\n        return np.int32\n    elif type(dt) == FloatType:\n        return np.float32\n    else:\n        return None", "title": ""}
{"_id": "d2681", "text": "def kill_process_children(pid):\n    \"\"\"Find and kill child processes of a process.\n\n    :param pid: PID of parent process (process ID)\n    :return: Nothing\n    \"\"\"\n    if sys.platform == \"darwin\":\n        kill_process_children_osx(pid)\n    elif sys.platform == \"linux\":\n        kill_process_children_unix(pid)\n    else:\n        pass", "title": ""}
{"_id": "d2682", "text": "def search_overlap(self, point_list):\n        \"\"\"\n        Returns all intervals that overlap the point_list.\n        \"\"\"\n        result = set()\n        for j in point_list:\n            self.search_point(j, result)\n        return result", "title": ""}
{"_id": "d2683", "text": "def guess_encoding(text, default=DEFAULT_ENCODING):\n    \"\"\"Guess string encoding.\n\n    Given a piece of text, apply character encoding detection to\n    guess the appropriate encoding of the text.\n    \"\"\"\n    result = chardet.detect(text)\n    return normalize_result(result, default=default)", "title": ""}
{"_id": "d2684", "text": "def findMax(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMax(arr, out)\n    return out", "title": ""}
{"_id": "d2685", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d2686", "text": "def maxDepth(self, currentDepth=0):\n        \"\"\"Compute the depth of the longest branch of the tree\"\"\"\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", "title": ""}
{"_id": "d2687", "text": "def pout(msg, log=None):\n    \"\"\"Print 'msg' to stdout, and option 'log' at info level.\"\"\"\n    _print(msg, sys.stdout, log_func=log.info if log else None)", "title": ""}
{"_id": "d2688", "text": "def argmax(l,f=None):\n    \"\"\"http://stackoverflow.com/questions/5098580/implementing-argmax-in-python\"\"\"\n    if f:\n        l = [f(i) for i in l]\n    return max(enumerate(l), key=lambda x:x[1])[0]", "title": ""}
{"_id": "d2689", "text": "def mkdir(dir, enter):\n    \"\"\"Create directory with template for topic of the current environment\n\n    \"\"\"\n\n    if not os.path.exists(dir):\n        os.makedirs(dir)", "title": ""}
{"_id": "d2690", "text": "def min_depth(self, root):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: int\n    \"\"\"\n    if root is None:\n        return 0\n    if root.left is not None or root.right is not None:\n        return max(self.minDepth(root.left), self.minDepth(root.right))+1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1", "title": ""}
{"_id": "d2691", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d2692", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d2693", "text": "def OnMove(self, event):\n        \"\"\"Main window move event\"\"\"\n\n        # Store window position in config\n        position = self.main_window.GetScreenPositionTuple()\n\n        config[\"window_position\"] = repr(position)", "title": ""}
{"_id": "d2694", "text": "def find(self, name):\n        \"\"\"Return the index of the toc entry with name NAME.\n\n           Return -1 for failure.\"\"\"\n        for i, nm in enumerate(self.data):\n            if nm[-1] == name:\n                return i\n        return -1", "title": ""}
{"_id": "d2695", "text": "def multiply(self, number):\n        \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n        return self.from_list([x * number for x in self.to_list()])", "title": ""}
{"_id": "d2696", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d2697", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d2698", "text": "def get_image_dimension(self, url):\n        \"\"\"\n        Return a tuple that contains (width, height)\n        Pass in a url to an image and find out its size without loading the whole file\n        If the image wxh could not be found, the tuple will contain `None` values\n        \"\"\"\n        w_h = (None, None)\n        try:\n            if url.startswith('//'):\n                url = 'http:' + url\n            data = requests.get(url).content\n            im = Image.open(BytesIO(data))\n\n            w_h = im.size\n        except Exception:\n            logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n        return w_h", "title": ""}
{"_id": "d2699", "text": "def read_stdin():\n    \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n    if sys.stdin.isatty() and sys.stdout.isatty():\n        print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n    return sys.stdin.read()", "title": ""}
{"_id": "d2700", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d2701", "text": "def read_key(suppress=False):\n    \"\"\"\n    Blocks until a keyboard event happens, then returns that event's name or,\n    if missing, its scan code.\n    \"\"\"\n    event = read_event(suppress)\n    return event.name or event.scan_code", "title": ""}
{"_id": "d2702", "text": "def fit_transform(self, raw_documents, y=None):\n        \"\"\"Learn vocabulary and idf, return term-document matrix.\n        This is equivalent to fit followed by transform, but more efficiently\n        implemented.\n        Parameters\n        ----------\n        raw_documents : iterable\n            an iterable which yields either str, unicode or file objects\n        Returns\n        -------\n        X : sparse matrix, [n_samples, n_features]\n            Tf-idf-weighted document-term matrix.\n        \"\"\"\n        documents = super(TfidfVectorizer, self).fit_transform(\n            raw_documents=raw_documents, y=y)\n        count = CountVectorizer(encoding=self.encoding,\n                                decode_error=self.decode_error,\n                                strip_accents=self.strip_accents,\n                                lowercase=self.lowercase,\n                                preprocessor=self.preprocessor,\n                                tokenizer=self.tokenizer,\n                                stop_words=self.stop_words,\n                                token_pattern=self.token_pattern,\n                                ngram_range=self.ngram_range,\n                                analyzer=self.analyzer,\n                                max_df=self.max_df,\n                                min_df=self.min_df,\n                                max_features=self.max_features,\n                                vocabulary=self.vocabulary_,\n                                binary=self.binary,\n                                dtype=self.dtype)\n        count.fit_transform(raw_documents=raw_documents, y=y)\n        self.period_ = count.period_\n        self.df_ = count.df_\n        self.n = count.n\n        return documents", "title": ""}
{"_id": "d2703", "text": "def call_out(command):\n  \"\"\"\n  Run the given command (with shell=False) and return a tuple of\n  (int returncode, str output). Strip the output of enclosing whitespace.\n  \"\"\"\n  # start external command process\n  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n  # get outputs\n  out, _ = p.communicate()\n\n  return p.returncode, out.strip()", "title": ""}
{"_id": "d2704", "text": "def inject_into_urllib3():\n    \"\"\"\n    Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n    \"\"\"\n    util.ssl_.SSLContext = SecureTransportContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_SECURETRANSPORT = True\n    util.ssl_.IS_SECURETRANSPORT = True", "title": ""}
{"_id": "d2705", "text": "def report_stdout(host, stdout):\n    \"\"\"Take a stdout 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 stdout: the std out of that process\n    :type stdout: paramiko.channel.Channel\n    \"\"\"\n    lines = stdout.readlines()\n    if lines:\n        print(\"STDOUT from {host}:\".format(host=host))\n        for line in lines:\n            print(line.rstrip(), file=sys.stdout)", "title": ""}
{"_id": "d2706", "text": "def is_local_url(target):\n    \"\"\"Determine if URL is safe to redirect to.\"\"\"\n    ref_url = urlparse(request.host_url)\n    test_url = urlparse(urljoin(request.host_url, target))\n    return test_url.scheme in ('http', 'https') and \\\n        ref_url.netloc == test_url.netloc", "title": ""}
{"_id": "d2707", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d2708", "text": "def export_all(self):\n\t\tquery = \"\"\"\n\t\t\tSELECT quote, library, logid\n\t\t\tfrom quotes\n\t\t\tleft outer join quote_log on quotes.quoteid = quote_log.quoteid\n\t\t\t\"\"\"\n\t\tfields = 'text', 'library', 'log_id'\n\t\treturn (dict(zip(fields, res)) for res in self.db.execute(query))", "title": ""}
{"_id": "d2709", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d2710", "text": "def rotateImage(image, angle):\n    \"\"\"\n        rotates a 2d array to a multiple of 90 deg.\n        0 = default\n        1 = 90 deg. cw\n        2 = 180 deg.\n        3 = 90 deg. ccw\n    \"\"\"\n    image = [list(row) for row in image]\n\n    for n in range(angle % 4):\n        image = list(zip(*image[::-1]))\n\n    return image", "title": ""}
{"_id": "d2711", "text": "def flatten(lis):\n    \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n    new_lis = []\n    for item in lis:\n        if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n            new_lis.extend(flatten(item))\n        else:\n            new_lis.append(item)\n    return new_lis", "title": ""}
{"_id": "d2712", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d2713", "text": "def hflip(img):\n    \"\"\"Horizontally flip the given PIL Image.\n\n    Args:\n        img (PIL Image): Image to be flipped.\n\n    Returns:\n        PIL Image:  Horizontall flipped image.\n    \"\"\"\n    if not _is_pil_image(img):\n        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n    return img.transpose(Image.FLIP_LEFT_RIGHT)", "title": ""}
{"_id": "d2714", "text": "def generate_seed(seed):\n    \"\"\"Generate seed for random number generator\"\"\"\n    if seed is None:\n        random.seed()\n        seed = random.randint(0, sys.maxsize)\n    random.seed(a=seed)\n\n    return seed", "title": ""}
{"_id": "d2715", "text": "def __clear_buffers(self):\n        \"\"\"Clears the input and output buffers\"\"\"\n        try:\n            self._port.reset_input_buffer()\n            self._port.reset_output_buffer()\n        except AttributeError:\n            #pySerial 2.7\n            self._port.flushInput()\n            self._port.flushOutput()", "title": ""}
{"_id": "d2716", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d2717", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d2718", "text": "def is_symlink(self):\n        \"\"\"\n        Whether this path is a symbolic link.\n        \"\"\"\n        try:\n            return S_ISLNK(self.lstat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            # Path doesn't exist\n            return False", "title": ""}
{"_id": "d2719", "text": "def flatten_all_but_last(a):\n  \"\"\"Flatten all dimensions of a except the last.\"\"\"\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", "title": ""}
{"_id": "d2720", "text": "def is_collection(obj):\n    \"\"\"Tests if an object is a collection.\"\"\"\n\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n\n    if isinstance(obj, basestring):\n        val = False\n\n    return val", "title": ""}
{"_id": "d2721", "text": "async def terminate(self):\n        \"\"\"Terminate a running script.\"\"\"\n        self.proc.terminate()\n\n        await asyncio.wait_for(self.proc.wait(), self.kill_delay)\n        if self.proc.returncode is None:\n            self.proc.kill()\n        await self.proc.wait()\n\n        await super().terminate()", "title": ""}
{"_id": "d2722", "text": "def is_string(val):\n    \"\"\"Determines whether the passed value is a string, safe for 2/3.\"\"\"\n    try:\n        basestring\n    except NameError:\n        return isinstance(val, str)\n    return isinstance(val, basestring)", "title": ""}
{"_id": "d2723", "text": "def go_to_background():\n    \"\"\" Daemonize the running process. \"\"\"\n    try:\n        if os.fork():\n            sys.exit()\n    except OSError as errmsg:\n        LOGGER.error('Fork failed: {0}'.format(errmsg))\n        sys.exit('Fork failed')", "title": ""}
{"_id": "d2724", "text": "def _wait_for_response(self):\n\t\t\"\"\"\n\t\tWait until the user accepted or rejected the request\n\t\t\"\"\"\n\t\twhile not self.server.response_code:\n\t\t\ttime.sleep(2)\n\t\ttime.sleep(5)\n\t\tself.server.shutdown()", "title": ""}
{"_id": "d2725", "text": "def reportMemory(k, options, field=None, isBytes=False):\n    \"\"\" Given k kilobytes, report back the correct format as string.\n    \"\"\"\n    if options.pretty:\n        return prettyMemory(int(k), field=field, isBytes=isBytes)\n    else:\n        if isBytes:\n            k /= 1024.\n        if field is not None:\n            return \"%*dK\" % (field - 1, k)  # -1 for the \"K\"\n        else:\n            return \"%dK\" % int(k)", "title": ""}
{"_id": "d2726", "text": "def OnUpdateFigurePanel(self, event):\n        \"\"\"Redraw event handler for the figure panel\"\"\"\n\n        if self.updating:\n            return\n\n        self.updating = True\n        self.figure_panel.update(self.get_figure(self.code))\n        self.updating = False", "title": ""}
{"_id": "d2727", "text": "def format_line(data, linestyle):\n    \"\"\"Formats a list of elements using the given line style\"\"\"\n    return linestyle.begin + linestyle.sep.join(data) + linestyle.end", "title": ""}
{"_id": "d2728", "text": "def format_screen(strng):\n    \"\"\"Format a string for screen printing.\n\n    This removes some latex-type format codes.\"\"\"\n    # Paragraph continue\n    par_re = re.compile(r'\\\\$',re.MULTILINE)\n    strng = par_re.sub('',strng)\n    return strng", "title": ""}
{"_id": "d2729", "text": "def to_percentage(number, rounding=2):\n    \"\"\"Creates a percentage string representation from the given `number`. The\n    number is multiplied by 100 before adding a '%' character.\n\n    Raises `ValueError` if `number` cannot be converted to a number.\n    \"\"\"\n    number = float(number) * 100\n    number_as_int = int(number)\n    rounded = round(number, rounding)\n\n    return '{}%'.format(number_as_int if number_as_int == rounded else rounded)", "title": ""}
{"_id": "d2730", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d2731", "text": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "title": ""}
{"_id": "d2732", "text": "def start(self):\n        \"\"\"Create a background thread for httpd and serve 'forever'\"\"\"\n        self._process = threading.Thread(target=self._background_runner)\n        self._process.start()", "title": ""}
{"_id": "d2733", "text": "def irfftn(a, s, axes=None):\n    \"\"\"\n    Compute the inverse of the multi-dimensional discrete Fourier transform\n    for real input. This function is a wrapper for\n    :func:`pyfftw.interfaces.numpy_fft.irfftn`, with an interface similar to\n    that of :func:`numpy.fft.irfftn`.\n\n    Parameters\n    ----------\n    a : array_like\n      Input array\n    s : sequence of ints\n      Shape of the output along each transformed axis (input is cropped or\n      zero-padded to match). This parameter is not optional because, unlike\n      :func:`ifftn`, the output shape cannot be uniquely determined from\n      the input shape.\n    axes : sequence of ints, optional (default None)\n      Axes over which to compute the inverse DFT.\n\n    Returns\n    -------\n    af : ndarray\n      Inverse DFT of input array\n    \"\"\"\n\n    return pyfftw.interfaces.numpy_fft.irfftn(\n        a, s=s, axes=axes, overwrite_input=False,\n        planner_effort='FFTW_MEASURE', threads=pyfftw_threads)", "title": ""}
{"_id": "d2734", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d2735", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d2736", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d2737", "text": "def to_snake_case(s):\n    \"\"\"Converts camel-case identifiers to snake-case.\"\"\"\n    return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)", "title": ""}
{"_id": "d2738", "text": "def dereference_url(url):\n    \"\"\"\n    Makes a HEAD request to find the final destination of a URL after\n    following any redirects\n    \"\"\"\n    res = open_url(url, method='HEAD')\n    res.close()\n    return res.url", "title": ""}
{"_id": "d2739", "text": "def speedtest(func, *args, **kwargs):\n    \"\"\" Test the speed of a function. \"\"\"\n    n = 100\n    start = time.time()\n    for i in range(n): func(*args,**kwargs)\n    end = time.time()\n    return (end-start)/n", "title": ""}
{"_id": "d2740", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d2741", "text": "def ver_to_tuple(value):\n    \"\"\"\n    Convert version like string to a tuple of integers.\n    \"\"\"\n    return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "title": ""}
{"_id": "d2742", "text": "def is_delimiter(line):\n    \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n    return bool(line) and line[0] in punctuation and line[0]*len(line) == line", "title": ""}
{"_id": "d2743", "text": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "title": ""}
{"_id": "d2744", "text": "def clean_float(v):\n    \"\"\"Remove commas from a float\"\"\"\n\n    if v is None or not str(v).strip():\n        return None\n\n    return float(str(v).replace(',', ''))", "title": ""}
{"_id": "d2745", "text": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "title": ""}
{"_id": "d2746", "text": "def remove_examples_all():\n    \"\"\"remove arduino/examples/all directory.\n\n    :rtype: None\n\n    \"\"\"\n    d = examples_all_dir()\n    if d.exists():\n        log.debug('remove %s', d)\n        d.rmtree()\n    else:\n        log.debug('nothing to remove: %s', d)", "title": ""}
{"_id": "d2747", "text": "def random_letters(n):\n    \"\"\"\n    Generate a random string from a-zA-Z\n    :param n: length of the string\n    :return: the random string\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(n))", "title": ""}
{"_id": "d2748", "text": "def _maybe_fill(arr, fill_value=np.nan):\n    \"\"\"\n    if we have a compatible fill_value and arr dtype, then fill\n    \"\"\"\n    if _isna_compat(arr, fill_value):\n        arr.fill(fill_value)\n    return arr", "title": ""}
{"_id": "d2749", "text": "def sine_wave(frequency):\n  \"\"\"Emit a sine wave at the given frequency.\"\"\"\n  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n  ts = xs / FLAGS.sample_rate\n  return tf.sin(2 * math.pi * frequency * ts)", "title": ""}
{"_id": "d2750", "text": "def _file_and_exists(val, input_files):\n    \"\"\"Check if an input is a file and exists.\n\n    Checks both locally (staged) and from input files (re-passed but never localized).\n    \"\"\"\n    return ((os.path.exists(val) and os.path.isfile(val)) or\n            val in input_files)", "title": ""}
{"_id": "d2751", "text": "def read_uint(data, start, length):\n    \"\"\"Extract a uint from a position in a sequence.\"\"\"\n    return int.from_bytes(data[start:start+length], byteorder='big')", "title": ""}
{"_id": "d2752", "text": "def example_write_file_to_disk_if_changed():\n    \"\"\" Try to remove all comments from a file, and save it if changes were made. \"\"\"\n    my_file = FileAsObj('/tmp/example_file.txt')\n    my_file.rm(my_file.egrep('^#'))\n    if my_file.changed:\n        my_file.save()", "title": ""}
{"_id": "d2753", "text": "def rel_path(filename):\n    \"\"\"\n    Function that gets relative path to the filename\n    \"\"\"\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)", "title": ""}
{"_id": "d2754", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d2755", "text": "def dates_in_range(start_date, end_date):\n    \"\"\"Returns all dates between two dates.\n\n    Inclusive of the start date but not the end date.\n\n    Args:\n        start_date (datetime.date)\n        end_date (datetime.date)\n\n    Returns:\n        (list) of datetime.date objects\n    \"\"\"\n    return [\n        start_date + timedelta(n)\n        for n in range(int((end_date - start_date).days))\n    ]", "title": ""}
{"_id": "d2756", "text": "def chkstr(s, v):\n    \"\"\"\n    Small routine for checking whether a string is empty\n    even a string\n\n    :param s: the string in question\n    :param v: variable name\n    \"\"\"\n    if type(s) != str:\n        raise TypeError(\"{var} must be str\".format(var=v))\n    if not s:\n        raise ValueError(\"{var} cannot be empty\".format(var=v))", "title": ""}
{"_id": "d2757", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d2758", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d2759", "text": "def get_url_file_name(url):\n    \"\"\"Get the file name from an url\n    \n    Parameters\n    ----------\n    url : str\n\n    Returns\n    -------\n    str\n        The file name \n    \"\"\"\n\n    assert isinstance(url, (str, _oldstr))\n    return urlparse.urlparse(url).path.split('/')[-1]", "title": ""}
{"_id": "d2760", "text": "def extent(self):\n        \"\"\"Helper for matplotlib imshow\"\"\"\n        return (\n            self.intervals[1].pix1 - 0.5,\n            self.intervals[1].pix2 - 0.5,\n            self.intervals[0].pix1 - 0.5,\n            self.intervals[0].pix2 - 0.5,\n        )", "title": ""}
{"_id": "d2761", "text": "def _get_background_color(self):\n        \"\"\"Returns background color rgb tuple of right line\"\"\"\n\n        color = self.cell_attributes[self.key][\"bgcolor\"]\n        return tuple(c / 255.0 for c in color_pack2rgb(color))", "title": ""}
{"_id": "d2762", "text": "def resize(self, size):\n        \"\"\"Return a new Image instance with the given size.\"\"\"\n        return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))", "title": ""}
{"_id": "d2763", "text": "def now_time(str=False):\n    \"\"\"Get the current time.\"\"\"\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()", "title": ""}
{"_id": "d2764", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d2765", "text": "def get_date(date):\n    \"\"\"\n    Get the date from a value that could be a date object or a string.\n\n    :param date: The date object or string.\n\n    :returns: The date object.\n    \"\"\"\n    if type(date) is str:\n        return datetime.strptime(date, '%Y-%m-%d').date()\n    else:\n        return date", "title": ""}
{"_id": "d2766", "text": "def get_shape(img):\n    \"\"\"Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple\n    \"\"\"\n    if hasattr(img, 'shape'):\n        shape = img.shape\n    else:\n        shape = img.get_data().shape\n    return shape", "title": ""}
{"_id": "d2767", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d2768", "text": "def monthly(date=datetime.date.today()):\n    \"\"\"\n    Take a date object and return the first day of the month.\n    \"\"\"\n    return datetime.date(date.year, date.month, 1)", "title": ""}
{"_id": "d2769", "text": "def write_padding(fp, size, divisor=2):\n    \"\"\"\n    Writes padding bytes given the currently written size.\n\n    :param fp: file-like object\n    :param divisor: divisor of the byte alignment\n    :return: written byte size\n    \"\"\"\n    remainder = size % divisor\n    if remainder:\n        return write_bytes(fp, struct.pack('%dx' % (divisor - remainder)))\n    return 0", "title": ""}
{"_id": "d2770", "text": "def findfirst(f, coll):\n    \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n    result = list(dropwhile(f, coll))\n    return result[0] if result else None", "title": ""}
{"_id": "d2771", "text": "def incr(self, key, incr_by=1):\n        \"\"\"Increment the key by the given amount.\"\"\"\n        return self.database.hincrby(self.key, key, incr_by)", "title": ""}
{"_id": "d2772", "text": "def fit_linear(X, y):\n    \"\"\"\n    Uses OLS to fit the regression.\n    \"\"\"\n    model = linear_model.LinearRegression()\n    model.fit(X, y)\n    return model", "title": ""}
{"_id": "d2773", "text": "def idx(df, index):\n    \"\"\"Universal indexing for numpy and pandas objects.\"\"\"\n    if isinstance(df, (pd.DataFrame, pd.Series)):\n        return df.iloc[index]\n    else:\n        return df[index, :]", "title": ""}
{"_id": "d2774", "text": "def col_frequencies(col, weights=None, gap_chars='-.'):\n    \"\"\"Frequencies of each residue type (totaling 1.0) in a single column.\"\"\"\n    counts = col_counts(col, weights, gap_chars)\n    # Reduce to frequencies\n    scale = 1.0 / sum(counts.values())\n    return dict((aa, cnt * scale) for aa, cnt in counts.iteritems())", "title": ""}
{"_id": "d2775", "text": "def ServerLoggingStartupInit():\n  \"\"\"Initialize the server logging configuration.\"\"\"\n  global LOGGER\n  if local_log:\n    logging.debug(\"Using local LogInit from %s\", local_log)\n    local_log.LogInit()\n    logging.debug(\"Using local AppLogInit from %s\", local_log)\n    LOGGER = local_log.AppLogInit()\n  else:\n    LogInit()\n    LOGGER = AppLogInit()", "title": ""}
{"_id": "d2776", "text": "def matrix_to_gl(matrix):\n    \"\"\"\n    Convert a numpy row- major homogenous transformation matrix\n    to a flat column- major GLfloat transformation.\n\n    Parameters\n    -------------\n    matrix : (4,4) float\n      Row- major homogenous transform\n\n    Returns\n    -------------\n    glmatrix : (16,) gl.GLfloat\n      Transform in pyglet format\n    \"\"\"\n    matrix = np.asanyarray(matrix, dtype=np.float64)\n    if matrix.shape != (4, 4):\n        raise ValueError('matrix must be (4,4)!')\n\n    # switch to column major and flatten to (16,)\n    column = matrix.T.flatten()\n    # convert to GLfloat\n    glmatrix = (gl.GLfloat * 16)(*column)\n\n    return glmatrix", "title": ""}
{"_id": "d2777", "text": "def _join(verb):\n    \"\"\"\n    Join helper\n    \"\"\"\n    data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n    # Preserve x groups\n    if isinstance(verb.x, GroupedDataFrame):\n        data.plydata_groups = list(verb.x.plydata_groups)\n    return data", "title": ""}
{"_id": "d2778", "text": "def get_trace_id_from_flask():\n    \"\"\"Get trace_id from flask request headers.\n\n    :rtype: str\n    :returns: TraceID in HTTP request headers.\n    \"\"\"\n    if flask is None or not flask.request:\n        return None\n\n    header = flask.request.headers.get(_FLASK_TRACE_HEADER)\n\n    if header is None:\n        return None\n\n    trace_id = header.split(\"/\", 1)[0]\n\n    return trace_id", "title": ""}
{"_id": "d2779", "text": "def intty(cls):\n        \"\"\" Check if we are in a tty. \"\"\"\n        # XXX: temporary hack until we can detect if we are in a pipe or not\n        return True\n\n        if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():\n            return True\n\n        return False", "title": ""}
{"_id": "d2780", "text": "def wrap_key(self, key):\n        \"\"\"Translate the key into the central cell\n\n           This method is only applicable in case of a periodic system.\n        \"\"\"\n        return tuple(np.round(\n            self.integer_cell.shortest_vector(key)\n        ).astype(int))", "title": ""}
{"_id": "d2781", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d2782", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d2783", "text": "def linedelimited (inlist,delimiter):\n    \"\"\"\nReturns a string composed of elements in inlist, with each element\nseparated by 'delimiter.'  Used by function writedelimited.  Use '\\t'\nfor tab-delimiting.\n\nUsage:   linedelimited (inlist,delimiter)\n\"\"\"\n    outstr = ''\n    for item in inlist:\n        if type(item) != StringType:\n            item = str(item)\n        outstr = outstr + item + delimiter\n    outstr = outstr[0:-1]\n    return outstr", "title": ""}
{"_id": "d2784", "text": "def get_inputs_from_cm(index, cm):\n    \"\"\"Return indices of inputs to the node with the given index.\"\"\"\n    return tuple(i for i in range(cm.shape[0]) if cm[i][index])", "title": ""}
{"_id": "d2785", "text": "def main(filename):\n    \"\"\"\n    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.\n    \"\"\"\n\n    # Prepare font.\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\n    # Initialize PDF document on a stream.\n    with Document('output.pdf') as document:\n\n        # Initialize a new page and begin its context.\n        with document.Page() as ctx:\n\n            # Open the image to embed.\n            with Image(filename) as embed:\n\n                # Set the media box for the page to the same as the\n                # image to embed.\n                ctx.box = embed.box\n\n                # Embed the image.\n                ctx.embed(embed)\n\n            # Write some text.\n            ctx.add(Text('Hello World', font, size=14, x=100, y=60))", "title": ""}
{"_id": "d2786", "text": "def _index_ordering(redshift_list):\n        \"\"\"\n\n        :param redshift_list: list of redshifts\n        :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n        \"\"\"\n        redshift_list = np.array(redshift_list)\n        sort_index = np.argsort(redshift_list)\n        return sort_index", "title": ""}
{"_id": "d2787", "text": "def __mul__(self, other):\n        \"\"\"Handle the `*` operator.\"\"\"\n        return self._handle_type(other)(self.value * other.value)", "title": ""}
{"_id": "d2788", "text": "def get_own_ip():\n    \"\"\"Get the host's ip number.\n    \"\"\"\n    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    try:\n        sock.connect((\"8.8.8.8\", 80))\n    except socket.gaierror:\n        ip_ = \"127.0.0.1\"\n    else:\n        ip_ = sock.getsockname()[0]\n    finally:\n        sock.close()\n    return ip_", "title": ""}
{"_id": "d2789", "text": "def bin_to_int(string):\n    \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n    if isinstance(string, str):\n        return struct.unpack(\"b\", string)[0]\n    else:\n        return struct.unpack(\"b\", bytes([string]))[0]", "title": ""}
{"_id": "d2790", "text": "def end_index(self):\n        \"\"\"\n        Returns the 1-based index of the last object on this page,\n        relative to total objects found (hits).\n        \"\"\"\n        return ((self.number - 1) * self.paginator.per_page +\n            len(self.object_list))", "title": ""}
{"_id": "d2791", "text": "def str2int(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n    return NumConv(radix, alphabet).str2int(num)", "title": ""}
{"_id": "d2792", "text": "def prevmonday(num):\n    \"\"\"\n    Return unix SECOND timestamp of \"num\" mondays ago\n    \"\"\"\n    today = get_today()\n    lastmonday = today - timedelta(days=today.weekday(), weeks=num)\n    return lastmonday", "title": ""}
{"_id": "d2793", "text": "def intToBin(i):\n    \"\"\" Integer to two bytes \"\"\"\n    # devide in two parts (bytes)\n    i1 = i % 256\n    i2 = int(i / 256)\n    # make string (little endian)\n    return chr(i1) + chr(i2)", "title": ""}
{"_id": "d2794", "text": "def qsize(self):\n        \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n        self.mutex.acquire()\n        n = self._qsize()\n        self.mutex.release()\n        return n", "title": ""}
{"_id": "d2795", "text": "def max(self):\n        \"\"\"\n        Returns the maximum value of the domain.\n\n        :rtype: `float` or `np.inf`\n        \"\"\"\n        return int(self._max) if not np.isinf(self._max) else self._max", "title": ""}
{"_id": "d2796", "text": "def get_line_ending(line):\n    \"\"\"Return line ending.\"\"\"\n    non_whitespace_index = len(line.rstrip()) - len(line)\n    if not non_whitespace_index:\n        return ''\n    else:\n        return line[non_whitespace_index:]", "title": ""}
{"_id": "d2797", "text": "def subkey(dct, keys):\n    \"\"\"Get an entry from a dict of dicts by the list of keys to 'follow'\n    \"\"\"\n    key = keys[0]\n    if len(keys) == 1:\n        return dct[key]\n    return subkey(dct[key], keys[1:])", "title": ""}
{"_id": "d2798", "text": "def all_collections(db):\n\t\"\"\"\n\tYield all non-sytem collections in db.\n\t\"\"\"\n\tinclude_pattern = r'(?!system\\.)'\n\treturn (\n\t\tdb[name]\n\t\tfor name in db.list_collection_names()\n\t\tif re.match(include_pattern, name)\n\t)", "title": ""}
{"_id": "d2799", "text": "def lin_interp(x, rangeX, rangeY):\n    \"\"\"\n    Interpolate linearly variable x in rangeX onto rangeY.\n    \"\"\"\n    s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])\n    y = rangeY[0] * (1 - s) + rangeY[1] * s\n    return y", "title": ""}
{"_id": "d2800", "text": "def _get_local_ip():\n        \"\"\"\n        Get the local ip of this device\n\n        :return: Ip of this computer\n        :rtype: str\n        \"\"\"\n        return set([x[4][0] for x in socket.getaddrinfo(\n            socket.gethostname(),\n            80,\n            socket.AF_INET\n        )]).pop()", "title": ""}
{"_id": "d2801", "text": "def spline_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):\n    \"\"\"A datetime-version that takes datetime object list as x_axis\n    \"\"\"\n    numeric_datetime_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_axis\n    ]\n\n    numeric_datetime_new_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_new_axis\n    ]\n\n    return spline_interpolate(\n        numeric_datetime_axis, y_axis, numeric_datetime_new_axis)", "title": ""}
{"_id": "d2802", "text": "def get_last_modified_timestamp(self):\n        \"\"\"\n        Looks at the files in a git root directory and grabs the last modified timestamp\n        \"\"\"\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", "title": ""}
{"_id": "d2803", "text": "def intersect_3d(p1, p2):\n    \"\"\"Find the closes point for a given set of lines in 3D.\n\n    Parameters\n    ----------\n    p1 : (M, N) array_like\n        Starting points\n    p2 : (M, N) array_like\n        End points.\n\n    Returns\n    -------\n    x : (N,) ndarray\n        Least-squares solution - the closest point of the intersections.\n\n    Raises\n    ------\n    numpy.linalg.LinAlgError\n        If computation does not converge.\n\n    \"\"\"\n    v = p2 - p1\n    normed_v = unit_vector(v)\n    nx = normed_v[:, 0]\n    ny = normed_v[:, 1]\n    nz = normed_v[:, 2]\n    xx = np.sum(nx**2 - 1)\n    yy = np.sum(ny**2 - 1)\n    zz = np.sum(nz**2 - 1)\n    xy = np.sum(nx * ny)\n    xz = np.sum(nx * nz)\n    yz = np.sum(ny * nz)\n    M = np.array([(xx, xy, xz), (xy, yy, yz), (xz, yz, zz)])\n    x = np.sum(\n        p1[:, 0] * (nx**2 - 1) + p1[:, 1] * (nx * ny) + p1[:, 2] * (nx * nz)\n    )\n    y = np.sum(\n        p1[:, 0] * (nx * ny) + p1[:, 1] * (ny * ny - 1) + p1[:, 2] * (ny * nz)\n    )\n    z = np.sum(\n        p1[:, 0] * (nx * nz) + p1[:, 1] * (ny * nz) + p1[:, 2] * (nz**2 - 1)\n    )\n    return np.linalg.lstsq(M, np.array((x, y, z)), rcond=None)[0]", "title": ""}
{"_id": "d2804", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d2805", "text": "def is_sequence(obj):\n    \"\"\"Check if `obj` is a sequence, but not a string or bytes.\"\"\"\n    return isinstance(obj, Sequence) and not (\n        isinstance(obj, str) or BinaryClass.is_valid_type(obj))", "title": ""}
{"_id": "d2806", "text": "def gday_of_year(self):\n        \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n        return (self.date - dt.date(self.date.year, 1, 1)).days", "title": ""}
{"_id": "d2807", "text": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "title": ""}
{"_id": "d2808", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d2809", "text": "def runiform(lower, upper, size=None):\n    \"\"\"\n    Random uniform variates.\n    \"\"\"\n    return np.random.uniform(lower, upper, size)", "title": ""}
{"_id": "d2810", "text": "def _run_cmd_get_output(cmd):\n    \"\"\"Runs a shell command, returns console output.\n\n    Mimics python3's subprocess.getoutput\n    \"\"\"\n    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n    out, err = process.communicate()\n    return out or err", "title": ""}
{"_id": "d2811", "text": "def split_every(n, iterable):\n    \"\"\"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.\"\"\"\n    items = iter(iterable)\n    return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))", "title": ""}
{"_id": "d2812", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d2813", "text": "def stop_at(iterable, idx):\n    \"\"\"Stops iterating before yielding the specified idx.\"\"\"\n    for i, item in enumerate(iterable):\n        if i == idx: return\n        yield item", "title": ""}
{"_id": "d2814", "text": "def get(s, delimiter='', format=\"diacritical\"):\n    \"\"\"Return pinyin of string, the string must be unicode\n    \"\"\"\n    return delimiter.join(_pinyin_generator(u(s), format=format))", "title": ""}
{"_id": "d2815", "text": "def _dict_values_sorted_by_key(dictionary):\n    # This should be a yield from instead.\n    \"\"\"Internal helper to return the values of a dictionary, sorted by key.\n    \"\"\"\n    for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):\n        yield value", "title": ""}
{"_id": "d2816", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d2817", "text": "def links(cls, page):\n    \"\"\"return all links on a page, including potentially rel= links.\"\"\"\n    for match in cls.HREF_RE.finditer(page):\n      yield cls.href_match_to_url(match)", "title": ""}
{"_id": "d2818", "text": "def get_size(path):\n    \"\"\" Returns the size in bytes if `path` is a file,\n        or the size of all files in `path` if it's a directory.\n        Analogous to `du -s`.\n    \"\"\"\n    if os.path.isfile(path):\n        return os.path.getsize(path)\n    return sum(get_size(os.path.join(path, f)) for f in os.listdir(path))", "title": ""}
{"_id": "d2819", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d2820", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d2821", "text": "def memsize(self):\n        \"\"\" Total array cell + indexes size\n        \"\"\"\n        return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds)", "title": ""}
{"_id": "d2822", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d2823", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d2824", "text": "def load(raw_bytes):\n        \"\"\"\n        given a bytes object, should return a base python data\n        structure that represents the object.\n        \"\"\"\n        try:\n            if not isinstance(raw_bytes, string_type):\n                raw_bytes = raw_bytes.decode()\n            return json.loads(raw_bytes)\n        except ValueError as e:\n            raise SerializationException(str(e))", "title": ""}
{"_id": "d2825", "text": "def _extract_node_text(node):\n    \"\"\"Extract text from a given lxml node.\"\"\"\n\n    texts = map(\n        six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n    )\n    return \" \".join(text for text in texts if text)", "title": ""}
{"_id": "d2826", "text": "def compose_all(tups):\n  \"\"\"Compose all given tuples together.\"\"\"\n  from . import ast  # I weep for humanity\n  return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))", "title": ""}
{"_id": "d2827", "text": "def first_sunday(self, year, month):\n        \"\"\"Get the first sunday of a month.\"\"\"\n        date = datetime(year, month, 1, 0)\n        days_until_sunday = 6 - date.weekday()\n\n        return date + timedelta(days=days_until_sunday)", "title": ""}
{"_id": "d2828", "text": "def json(body, charset='utf-8', **kwargs):\n    \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n    return json_converter.loads(text(body, charset=charset))", "title": ""}
{"_id": "d2829", "text": "def _get_background_color(self):\n        \"\"\"Returns background color rgb tuple of right line\"\"\"\n\n        color = self.cell_attributes[self.key][\"bgcolor\"]\n        return tuple(c / 255.0 for c in color_pack2rgb(color))", "title": ""}
{"_id": "d2830", "text": "def parse_json_date(value):\n    \"\"\"\n    Parses an ISO8601 formatted datetime from a string value\n    \"\"\"\n    if not value:\n        return None\n\n    return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)", "title": ""}
{"_id": "d2831", "text": "def _get_compiled_ext():\n    \"\"\"Official way to get the extension of compiled files (.pyc or .pyo)\"\"\"\n    for ext, mode, typ in imp.get_suffixes():\n        if typ == imp.PY_COMPILED:\n            return ext", "title": ""}
{"_id": "d2832", "text": "def dump_json(obj):\n    \"\"\"Dump Python object as JSON string.\"\"\"\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)", "title": ""}
{"_id": "d2833", "text": "def get_abi3_suffix():\n    \"\"\"Return the file extension for an abi3-compliant Extension()\"\"\"\n    for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION):\n        if '.abi3' in suffix:  # Unix\n            return suffix\n        elif suffix == '.pyd':  # Windows\n            return suffix", "title": ""}
{"_id": "d2834", "text": "def dump_json(obj):\n    \"\"\"Dump Python object as JSON string.\"\"\"\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)", "title": ""}
{"_id": "d2835", "text": "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location", "title": ""}
{"_id": "d2836", "text": "def json_dumps(self, obj):\n        \"\"\"Serializer for consistency\"\"\"\n        return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))", "title": ""}
{"_id": "d2837", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d2838", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d2839", "text": "def _cumprod(l):\n  \"\"\"Cumulative product of a list.\n\n  Args:\n    l: a list of integers\n  Returns:\n    a list with one more element (starting with 1)\n  \"\"\"\n  ret = [1]\n  for item in l:\n    ret.append(ret[-1] * item)\n  return ret", "title": ""}
{"_id": "d2840", "text": "def json_dumps(self, obj):\n        \"\"\"Serializer for consistency\"\"\"\n        return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))", "title": ""}
{"_id": "d2841", "text": "def typename(obj):\n    \"\"\"Returns the type of obj as a string. More descriptive and specific than\n    type(obj), and safe for any object, unlike __class__.\"\"\"\n    if hasattr(obj, '__class__'):\n        return getattr(obj, '__class__').__name__\n    else:\n        return type(obj).__name__", "title": ""}
{"_id": "d2842", "text": "def json_decode(data):\n    \"\"\"\n    Decodes the given JSON as primitives\n    \"\"\"\n    if isinstance(data, six.binary_type):\n        data = data.decode('utf-8')\n\n    return json.loads(data)", "title": ""}
{"_id": "d2843", "text": "def uniq(seq):\n    \"\"\" Return a copy of seq without duplicates. \"\"\"\n    seen = set()\n    return [x for x in seq if str(x) not in seen and not seen.add(str(x))]", "title": ""}
{"_id": "d2844", "text": "def is_collection(obj):\n    \"\"\"Tests if an object is a collection.\"\"\"\n\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n\n    if isinstance(obj, basestring):\n        val = False\n\n    return val", "title": ""}
{"_id": "d2845", "text": "def itervalues(d, **kw):\n    \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n    if not PY2:\n        return iter(d.values(**kw))\n    return d.itervalues(**kw)", "title": ""}
{"_id": "d2846", "text": "def transcript_sort_key(transcript):\n    \"\"\"\n    Key function used to sort transcripts. Taking the negative of\n    protein sequence length and nucleotide sequence length so that\n    the transcripts with longest sequences come first in the list. This couldn't\n    be accomplished with `reverse=True` since we're also sorting by\n    transcript name (which places TP53-001 before TP53-002).\n    \"\"\"\n    return (\n        -len(transcript.protein_sequence),\n        -len(transcript.sequence),\n        transcript.name\n    )", "title": ""}
{"_id": "d2847", "text": "def getSystemVariable(self, remote, name):\n        \"\"\"Get single system variable from CCU / Homegear\"\"\"\n        if self._server is not None:\n            return self._server.getSystemVariable(remote, name)", "title": ""}
{"_id": "d2848", "text": "def extract_keywords_from_text(self, text):\n        \"\"\"Method to extract keywords from the text provided.\n\n        :param text: Text to extract keywords from, provided as a string.\n        \"\"\"\n        sentences = nltk.tokenize.sent_tokenize(text)\n        self.extract_keywords_from_sentences(sentences)", "title": ""}
{"_id": "d2849", "text": "def prettify(elem):\n    \"\"\"Return a pretty-printed XML string for the Element.\n    \"\"\"\n    rough_string = ET.tostring(elem, 'utf-8')\n    reparsed = minidom.parseString(rough_string)\n    return reparsed.toprettyxml(indent=\"\\t\")", "title": ""}
{"_id": "d2850", "text": "def kill_process_children(pid):\n    \"\"\"Find and kill child processes of a process.\n\n    :param pid: PID of parent process (process ID)\n    :return: Nothing\n    \"\"\"\n    if sys.platform == \"darwin\":\n        kill_process_children_osx(pid)\n    elif sys.platform == \"linux\":\n        kill_process_children_unix(pid)\n    else:\n        pass", "title": ""}
{"_id": "d2851", "text": "def __get_xml_text(root):\n    \"\"\" Return the text for the given root node (xml.dom.minidom). \"\"\"\n    txt = \"\"\n    for e in root.childNodes:\n        if (e.nodeType == e.TEXT_NODE):\n            txt += e.data\n    return txt", "title": ""}
{"_id": "d2852", "text": "def classify_clusters(points, n=10):\n    \"\"\"\n    Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects.\n    \"\"\"\n    arr = [[p.x, p.y] for p in points.values]\n    clf = KMeans(n_clusters=n)\n    clf.fit(arr)\n    classes = clf.predict(arr)\n    return classes", "title": ""}
{"_id": "d2853", "text": "def getSystemVariable(self, remote, name):\n        \"\"\"Get single system variable from CCU / Homegear\"\"\"\n        if self._server is not None:\n            return self._server.getSystemVariable(remote, name)", "title": ""}
{"_id": "d2854", "text": "def _sourced_dict(self, source=None, **kwargs):\n        \"\"\"Like ``dict(**kwargs)``, but where the ``source`` key is special.\n        \"\"\"\n        if source:\n            kwargs['source'] = source\n        elif self.source:\n            kwargs['source'] = self.source\n        return kwargs", "title": ""}
{"_id": "d2855", "text": "def get_element_attribute_or_empty(element, attribute_name):\n    \"\"\"\n\n    Args:\n        element (element): The xib's element.\n        attribute_name (str): The desired attribute's name.\n\n    Returns:\n        The attribute's value, or an empty str if none exists.\n\n    \"\"\"\n    return element.attributes[attribute_name].value if element.hasAttribute(attribute_name) else \"\"", "title": ""}
{"_id": "d2856", "text": "def make_lambda(call):\n    \"\"\"Wrap an AST Call node to lambda expression node.\n    call: ast.Call node\n    \"\"\"\n    empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n    return ast.Lambda(args=empty_args, body=call)", "title": ""}
{"_id": "d2857", "text": "def is_changed():\n    \"\"\" Checks if current project has any noncommited changes. \"\"\"\n    executed, changed_lines = execute_git('status --porcelain', output=False)\n    merge_not_finished = mod_path.exists('.git/MERGE_HEAD')\n    return changed_lines.strip() or merge_not_finished", "title": ""}
{"_id": "d2858", "text": "def apply_kwargs(func, **kwargs):\n    \"\"\"Call *func* with kwargs, but only those kwargs that it accepts.\n    \"\"\"\n    new_kwargs = {}\n    params = signature(func).parameters\n    for param_name in params.keys():\n        if param_name in kwargs:\n            new_kwargs[param_name] = kwargs[param_name]\n    return func(**new_kwargs)", "title": ""}
{"_id": "d2859", "text": "def color_func(func_name):\n    \"\"\"\n    Call color function base on name\n    \"\"\"\n    if str(func_name).isdigit():\n        return term_color(int(func_name))\n    return globals()[func_name]", "title": ""}
{"_id": "d2860", "text": "def last_modified_date(filename):\n    \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n    mtime = os.path.getmtime(filename)\n    dt = datetime.datetime.utcfromtimestamp(mtime)\n    return dt.replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d2861", "text": "def run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv. Return result code.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tresult_code = __import__('pytest').main()\n\t\t\tif result_code:\n\t\t\t\traise SystemExit(result_code)", "title": ""}
{"_id": "d2862", "text": "def copy_user_agent_from_driver(self):\n        \"\"\" 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.\n        \"\"\"\n        selenium_user_agent = self.driver.execute_script(\"return navigator.userAgent;\")\n        self.headers.update({\"user-agent\": selenium_user_agent})", "title": ""}
{"_id": "d2863", "text": "def print_matrix(X, decimals=1):\n    \"\"\"Pretty printing for numpy matrix X\"\"\"\n    for row in np.round(X, decimals=decimals):\n        print(row)", "title": ""}
{"_id": "d2864", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d2865", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d2866", "text": "def open01(x, limit=1.e-6):\n    \"\"\"Constrain numbers to (0,1) interval\"\"\"\n    try:\n        return np.array([min(max(y, limit), 1. - limit) for y in x])\n    except TypeError:\n        return min(max(x, limit), 1. - limit)", "title": ""}
{"_id": "d2867", "text": "def _check_graphviz_available(output_format):\n    \"\"\"check if we need graphviz for different output format\"\"\"\n    try:\n        subprocess.call([\"dot\", \"-V\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    except OSError:\n        print(\n            \"The output format '%s' is currently not available.\\n\"\n            \"Please install 'Graphviz' to have other output formats \"\n            \"than 'dot' or 'vcg'.\" % output_format\n        )\n        sys.exit(32)", "title": ""}
{"_id": "d2868", "text": "def _linear_interpolation(x, X, Y):\n    \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n    \"\"\"\n    return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "title": ""}
{"_id": "d2869", "text": "def _text_to_graphiz(self, text):\n        \"\"\"create a graphviz graph from text\"\"\"\n        dot = Source(text, format='svg')\n        return dot.pipe().decode('utf-8')", "title": ""}
{"_id": "d2870", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d2871", "text": "def selectgt(table, field, value, complement=False):\n    \"\"\"Select rows where the given field is greater than the given value.\"\"\"\n\n    value = Comparable(value)\n    return selectop(table, field, value, operator.gt, complement=complement)", "title": ""}
{"_id": "d2872", "text": "def index(m, val):\n    \"\"\"\n    Return the indices of all the ``val`` in ``m``\n    \"\"\"\n    mm = np.array(m)\n    idx_tuple = np.where(mm == val)\n    idx = idx_tuple[0].tolist()\n\n    return idx", "title": ""}
{"_id": "d2873", "text": "def page_guiref(arg_s=None):\n    \"\"\"Show a basic reference about the GUI Console.\"\"\"\n    from IPython.core import page\n    page.page(gui_reference, auto_html=True)", "title": ""}
{"_id": "d2874", "text": "def _unique_rows_numpy(a):\n    \"\"\"return unique rows\"\"\"\n    a = np.ascontiguousarray(a)\n    unique_a = np.unique(a.view([('', a.dtype)] * a.shape[1]))\n    return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))", "title": ""}
{"_id": "d2875", "text": "def executable_exists(executable):\n    \"\"\"Test if an executable is available on the system.\"\"\"\n    for directory in os.getenv(\"PATH\").split(\":\"):\n        if os.path.exists(os.path.join(directory, executable)):\n            return True\n    return False", "title": ""}
{"_id": "d2876", "text": "def values(self):\n        \"\"\"return a list of all state values\"\"\"\n        values = []\n        for __, data in self.items():\n            values.append(data)\n        return values", "title": ""}
{"_id": "d2877", "text": "def btc_make_p2sh_address( script_hex ):\n    \"\"\"\n    Make a P2SH address from a hex script\n    \"\"\"\n    h = hashing.bin_hash160(binascii.unhexlify(script_hex))\n    addr = bin_hash160_to_address(h, version_byte=multisig_version_byte)\n    return addr", "title": ""}
{"_id": "d2878", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d2879", "text": "def colorbar(height, length, colormap):\n    \"\"\"Return the channels of a colorbar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.colorize(cbar)", "title": ""}
{"_id": "d2880", "text": "def get_dt_list(fn_list):\n    \"\"\"Get list of datetime objects, extracted from a filename\n    \"\"\"\n    dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])\n    return dt_list", "title": ""}
{"_id": "d2881", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d2882", "text": "def index(m, val):\n    \"\"\"\n    Return the indices of all the ``val`` in ``m``\n    \"\"\"\n    mm = np.array(m)\n    idx_tuple = np.where(mm == val)\n    idx = idx_tuple[0].tolist()\n\n    return idx", "title": ""}
{"_id": "d2883", "text": "def poke_array(self, store, name, elemtype, elements, container, visited, _stack):\n        \"\"\"abstract method\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d2884", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d2885", "text": "def is_valid(email):\n        \"\"\"Email address validation method.\n\n        :param email: Email address to be saved.\n        :type email: basestring\n        :returns: True if email address is correct, False otherwise.\n        :rtype: bool\n        \"\"\"\n        if isinstance(email, basestring) and EMAIL_RE.match(email):\n            return True\n        return False", "title": ""}
{"_id": "d2886", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d2887", "text": "def update_screen(self):\n        \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n        self.clock.tick(self.FPS)\n        pygame.display.update()", "title": ""}
{"_id": "d2888", "text": "def loadmat(filename):\n    \"\"\"This function should be called instead of direct spio.loadmat\n    as it cures the problem of not properly recovering python dictionaries\n    from mat files. It calls the function check keys to cure all entries\n    which are still mat-objects\n    \"\"\"\n    data = sploadmat(filename, struct_as_record=False, squeeze_me=True)\n    return _check_keys(data)", "title": ""}
{"_id": "d2889", "text": "def add_matplotlib_cmap(cm, name=None):\n    \"\"\"Add a matplotlib colormap.\"\"\"\n    global cmaps\n    cmap = matplotlib_to_ginga_cmap(cm, name=name)\n    cmaps[cmap.name] = cmap", "title": ""}
{"_id": "d2890", "text": "def loads(s, model=None, parser=None):\n    \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n    with StringIO(s) as f:\n        return load(f, model=model, parser=parser)", "title": ""}
{"_id": "d2891", "text": "def _float_almost_equal(float1, float2, places=7):\n    \"\"\"Return True if two numbers are equal up to the\n    specified number of \"places\" after the decimal point.\n    \"\"\"\n\n    if round(abs(float2 - float1), places) == 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d2892", "text": "def getFunction(self):\n        \"\"\"Called by remote workers. Useful to populate main module globals()\n        for interactive shells. Retrieves the serialized function.\"\"\"\n        return functionFactory(\n            self.code,\n            self.name,\n            self.defaults,\n            self.globals,\n            self.imports,\n        )", "title": ""}
{"_id": "d2893", "text": "def is_text(obj, name=None):\n    \"\"\"\n    returns True if object is text-like\n    \"\"\"\n    try:  # python2\n        ans = isinstance(obj, basestring)\n    except NameError:  # python3\n        ans = isinstance(obj, str)\n    if name:\n        print(\"is_text: (%s) %s = %s\" % (ans, name, obj.__class__),\n              file=sys.stderr)\n    return ans", "title": ""}
{"_id": "d2894", "text": "def _get_or_create_stack(name):\n  \"\"\"Returns a thread local stack uniquified by the given name.\"\"\"\n  stack = getattr(_LOCAL_STACKS, name, None)\n  if stack is None:\n    stack = []\n    setattr(_LOCAL_STACKS, name, stack)\n  return stack", "title": ""}
{"_id": "d2895", "text": "def forget_coords(self):\n        \"\"\"Forget all loaded coordinates.\"\"\"\n        self.w.ntotal.set_text('0')\n        self.coords_dict.clear()\n        self.redo()", "title": ""}
{"_id": "d2896", "text": "def localize(dt):\n    \"\"\"Localize a datetime object to local time.\"\"\"\n    if dt.tzinfo is UTC:\n        return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)\n    # No TZ info so not going to assume anything, return as-is.\n    return dt", "title": ""}
{"_id": "d2897", "text": "def unlock(self):\n    \"\"\"Closes the session to the database.\"\"\"\n    if not hasattr(self, 'session'):\n      raise RuntimeError('Error detected! The session that you want to close does not exist any more!')\n    logger.debug(\"Closed database session of '%s'\" % self._database)\n    self.session.close()\n    del self.session", "title": ""}
{"_id": "d2898", "text": "def lognorm(x, mu, sigma=1.0):\n    \"\"\" Log-normal function from scipy \"\"\"\n    return stats.lognorm(sigma, scale=mu).pdf(x)", "title": ""}
{"_id": "d2899", "text": "def find_frequencies(data, freq=44100, bits=16):\n    \"\"\"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.\n    \"\"\"\n    # Fast fourier transform\n    n = len(data)\n    p = _fft(data)\n    uniquePts = numpy.ceil((n + 1) / 2.0)\n\n    # Scale by the length (n) and square the value to get the amplitude\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\n    # Generate the frequencies and zip with the amplitudes\n    s = freq / float(n)\n    freqArray = numpy.arange(0, uniquePts * s, s)\n    return zip(freqArray, p)", "title": ""}
{"_id": "d2900", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d2901", "text": "def to_python(self, value):\n        \"\"\"\n        Convert a string from a form into an Enum value.\n        \"\"\"\n        if value is None:\n            return value\n        if isinstance(value, self.enum):\n            return value\n        return self.enum[value]", "title": ""}
{"_id": "d2902", "text": "def pylog(self, *args, **kwargs):\n        \"\"\"Display all available logging information.\"\"\"\n        printerr(self.name, args, kwargs, traceback.format_exc())", "title": ""}
{"_id": "d2903", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d2904", "text": "def close_log(log, verbose=True):\n    \"\"\"Close log\n\n    This method closes and active logging.Logger instance.\n\n    Parameters\n    ----------\n    log : logging.Logger\n        Logging instance\n\n    \"\"\"\n\n    if verbose:\n        print('Closing log file:', log.name)\n\n    # Send closing message.\n    log.info('The log file has been closed.')\n\n    # Remove all handlers from log.\n    [log.removeHandler(handler) for handler in log.handlers]", "title": ""}
{"_id": "d2905", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d2906", "text": "def load_config(filename=\"logging.ini\", *args, **kwargs):\n    \"\"\"\n    Load logger config from file\n    \n    Keyword arguments:\n    filename -- configuration filename (Default: \"logging.ini\")\n    *args -- options passed to fileConfig\n    **kwargs -- options passed to fileConfigg\n    \n    \"\"\"\n    logging.config.fileConfig(filename, *args, **kwargs)", "title": ""}
{"_id": "d2907", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d2908", "text": "def setLoggerAll(self, mthd):\n        \"\"\" Sends all messages to ``logger.[mthd]()`` for handling \"\"\"\n        for key in self._logger_methods:\n            self._logger_methods[key] = mthd", "title": ""}
{"_id": "d2909", "text": "def time_range(from_=None, to=None):  # todo datetime conversion\n    \"\"\"\n    :param str from_:\n    :param str to:\n\n    :return: dict\n    \"\"\"\n    args = locals()\n    return {\n        k.replace('_', ''): v for k, v in args.items()\n    }", "title": ""}
{"_id": "d2910", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d2911", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d2912", "text": "def timed_rotating_file_handler(name, logname, filename, when='h',\n                                interval=1, backupCount=0,\n                                encoding=None, delay=False, utc=False):\n    \"\"\"\n    A Bark logging handler logging output to a named file.  At\n    intervals specified by the 'when', the file will be rotated, under\n    control of 'backupCount'.\n\n    Similar to logging.handlers.TimedRotatingFileHandler.\n    \"\"\"\n\n    return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n        filename, when=when, interval=interval, backupCount=backupCount,\n        encoding=encoding, delay=delay, utc=utc))", "title": ""}
{"_id": "d2913", "text": "def path_to_list(pathstr):\n    \"\"\"Conver a path string to a list of path elements.\"\"\"\n    return [elem for elem in pathstr.split(os.path.pathsep) if elem]", "title": ""}
{"_id": "d2914", "text": "def logger(message, level=10):\n    \"\"\"Handle logging.\"\"\"\n    logging.getLogger(__name__).log(level, str(message))", "title": ""}
{"_id": "d2915", "text": "def relative_path(path):\n    \"\"\"\n    Return the given path relative to this file.\n    \"\"\"\n    return os.path.join(os.path.dirname(__file__), path)", "title": ""}
{"_id": "d2916", "text": "def pylog(self, *args, **kwargs):\n        \"\"\"Display all available logging information.\"\"\"\n        printerr(self.name, args, kwargs, traceback.format_exc())", "title": ""}
{"_id": "d2917", "text": "def fast_exit(code):\n    \"\"\"Exit without garbage collection, this speeds up exit by about 10ms for\n    things like bash completion.\n    \"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(code)", "title": ""}
{"_id": "d2918", "text": "def write(self, text):\n        \"\"\"Write text. An additional attribute terminator with a value of\n           None is added to the logging record to indicate that StreamHandler\n           should not add a newline.\"\"\"\n        self.logger.log(self.loglevel, text, extra={'terminator': None})", "title": ""}
{"_id": "d2919", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d2920", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d2921", "text": "def validate_multiindex(self, obj):\n        \"\"\"validate that we can store the multi-index; reset and return the\n        new object\n        \"\"\"\n        levels = [l if l is not None else \"level_{0}\".format(i)\n                  for i, l in enumerate(obj.index.names)]\n        try:\n            return obj.reset_index(), levels\n        except ValueError:\n            raise ValueError(\"duplicate names/columns in the multi-index when \"\n                             \"storing as a table\")", "title": ""}
{"_id": "d2922", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d2923", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d2924", "text": "def compare(a, b):\n    \"\"\"\n     Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))\n    \"\"\"\n    s=0\n    for i in range(len(a)):\n        s=s+abs(a[i]-b[i])\n    return s", "title": ""}
{"_id": "d2925", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d2926", "text": "def camelcase_to_slash(name):\n    \"\"\" Converts CamelCase to camel/case\n\n    code ripped from http://stackoverflow.com/questions/1175208/does-the-python-standard-library-have-function-to-convert-camelcase-to-camel-cas\n    \"\"\"\n\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()", "title": ""}
{"_id": "d2927", "text": "def clean_error(err):\n    \"\"\"\n    Take stderr bytes returned from MicroPython and attempt to create a\n    non-verbose error message.\n    \"\"\"\n    if err:\n        decoded = err.decode('utf-8')\n        try:\n            return decoded.split('\\r\\n')[-2]\n        except Exception:\n            return decoded\n    return 'There was an error.'", "title": ""}
{"_id": "d2928", "text": "def _extract_node_text(node):\n    \"\"\"Extract text from a given lxml node.\"\"\"\n\n    texts = map(\n        six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n    )\n    return \" \".join(text for text in texts if text)", "title": ""}
{"_id": "d2929", "text": "def main(argv=None):\n  \"\"\"Run a Tensorflow model on the Iris dataset.\"\"\"\n  args = parse_arguments(sys.argv if argv is None else argv)\n\n  tf.logging.set_verbosity(tf.logging.INFO)\n  learn_runner.run(\n      experiment_fn=get_experiment_fn(args),\n      output_dir=args.job_dir)", "title": ""}
{"_id": "d2930", "text": "def _extract_node_text(node):\n    \"\"\"Extract text from a given lxml node.\"\"\"\n\n    texts = map(\n        six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n    )\n    return \" \".join(text for text in texts if text)", "title": ""}
{"_id": "d2931", "text": "def add_suffix(fullname, suffix):\n    \"\"\" Add suffix to a full file name\"\"\"\n    name, ext = os.path.splitext(fullname)\n    return name + '_' + suffix + ext", "title": ""}
{"_id": "d2932", "text": "def from_file(filename, mime=False):\n    \"\"\" Opens file, attempts to identify content based\n    off magic number and will return the file extension.\n    If mime is True it will return the mime type instead.\n\n    :param filename: path to file\n    :param mime: Return mime, not extension\n    :return: guessed extension or mime\n    \"\"\"\n\n    head, foot = _file_details(filename)\n    return _magic(head, foot, mime, ext_from_filename(filename))", "title": ""}
{"_id": "d2933", "text": "def process_instance(self, instance):\n        self.log.debug(\"e = mc^2\")\n        self.log.info(\"About to fail..\")\n        self.log.warning(\"Failing.. soooon..\")\n        self.log.critical(\"Ok, you're done.\")\n        assert False, \"\"\"ValidateFailureMock was destined to fail..\n\nHere's some extended information about what went wrong.\n\nIt has quite the long string associated with it, including\na few newlines and a list.\n\n- Item 1\n- Item 2\n\n\"\"\"", "title": ""}
{"_id": "d2934", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d2935", "text": "def markdown_media_css():\n    \"\"\" Add css requirements to HTML.\n\n    :returns: Editor template context.\n\n    \"\"\"\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    )", "title": ""}
{"_id": "d2936", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d2937", "text": "def smooth_gaussian(image, sigma=1):\n    \"\"\"Returns Gaussian smoothed image.\n\n    :param image: numpy array or :class:`jicimagelib.image.Image`\n    :param sigma: standard deviation\n    :returns: :class:`jicimagelib.image.Image`\n    \"\"\"\n    return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode=\"nearest\")", "title": ""}
{"_id": "d2938", "text": "def cross_list(*sequences):\n  \"\"\"\n  From: http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-19-sect-9.html\n  \"\"\"\n  result = [[ ]]\n  for seq in sequences:\n    result = [sublist+[item] for sublist in result for item in seq]\n  return result", "title": ""}
{"_id": "d2939", "text": "def default_static_path():\n    \"\"\"\n        Return the path to the javascript bundle\n    \"\"\"\n    fdir = os.path.dirname(__file__)\n    return os.path.abspath(os.path.join(fdir, '../assets/'))", "title": ""}
{"_id": "d2940", "text": "def safe_quotes(text, escape_single_quotes=False):\n    \"\"\"htmlify string\"\"\"\n    if isinstance(text, str):\n        safe_text = text.replace('\"', \"&quot;\")\n        if escape_single_quotes:\n            safe_text = safe_text.replace(\"'\", \"&#92;'\")\n        return safe_text.replace('True', 'true')\n    return text", "title": ""}
{"_id": "d2941", "text": "def clean_dataframe(df):\n    \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n    df = df.fillna(method='ffill')\n    df = df.fillna(0.0)\n    return df", "title": ""}
{"_id": "d2942", "text": "def get_filename_safe_string(string):\n    \"\"\"\n    Converts a string to a string that is safe for a filename\n    Args:\n        string (str): A string to make safe for a filename\n\n    Returns:\n        str: A string safe for a filename\n    \"\"\"\n    invalid_filename_chars = ['\\\\', '/', ':', '\"', '*', '?', '|', '\\n',\n                              '\\r']\n    if string is None:\n        string = \"None\"\n    for char in invalid_filename_chars:\n        string = string.replace(char, \"\")\n    string = string.rstrip(\".\")\n\n    return string", "title": ""}
{"_id": "d2943", "text": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "title": ""}
{"_id": "d2944", "text": "def date_to_datetime(x):\n    \"\"\"Convert a date into a datetime\"\"\"\n    if not isinstance(x, datetime) and isinstance(x, date):\n        return datetime.combine(x, time())\n    return x", "title": ""}
{"_id": "d2945", "text": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "title": ""}
{"_id": "d2946", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d2947", "text": "def aggregate(d, y_size, x_size):\n        \"\"\"Average every 4 elements (2x2) in a 2D array\"\"\"\n        if d.ndim != 2:\n            # we can't guarantee what blocks we are getting and how\n            # it should be reshaped to do the averaging.\n            raise ValueError(\"Can't aggregrate (reduce) data arrays with \"\n                             \"more than 2 dimensions.\")\n        if not (x_size.is_integer() and y_size.is_integer()):\n            raise ValueError(\"Aggregation factors are not integers\")\n        for agg_size, chunks in zip([y_size, x_size], d.chunks):\n            for chunk_size in chunks:\n                if chunk_size % agg_size != 0:\n                    raise ValueError(\"Aggregation requires arrays with \"\n                                     \"shapes and chunks divisible by the \"\n                                     \"factor\")\n\n        new_chunks = (tuple(int(x / y_size) for x in d.chunks[0]),\n                      tuple(int(x / x_size) for x in d.chunks[1]))\n        return da.core.map_blocks(_mean, d, y_size, x_size, dtype=d.dtype, chunks=new_chunks)", "title": ""}
{"_id": "d2948", "text": "def make_regex(separator):\n    \"\"\"Utility function to create regexp for matching escaped separators\n    in strings.\n\n    \"\"\"\n    return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +\n                      re.escape(separator) + r'\\\\]|\\\\.)+)')", "title": ""}
{"_id": "d2949", "text": "def rollback(self):\n\t\t\"\"\"\n\t\tRollback MySQL Transaction to database.\n\t\tMySQLDB: If the database and tables support transactions, this rolls \n\t\tback (cancels) the current transaction; otherwise a \n\t\tNotSupportedError is raised.\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 5/12/2008\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif self.connection is not None:\n\t\t\t\tself.connection.rollback()\n\t\t\t\tself._updateCheckTime()\n\t\t\t\tself.release()\n\t\texcept Exception, e:\n\t\t\tpass", "title": ""}
{"_id": "d2950", "text": "def to_dicts(recarray):\n    \"\"\"convert record array to a dictionaries\"\"\"\n    for rec in recarray:\n        yield dict(zip(recarray.dtype.names, rec.tolist()))", "title": ""}
{"_id": "d2951", "text": "def Softsign(a):\n    \"\"\"\n    Softsign op.\n    \"\"\"\n    return np.divide(a, np.add(np.abs(a), 1)),", "title": ""}
{"_id": "d2952", "text": "def find_whole_word(w):\n    \"\"\"\n    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.\n    \"\"\"\n    return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search", "title": ""}
{"_id": "d2953", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d2954", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d2955", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d2956", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d2957", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d2958", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d2959", "text": "def to_camel_case(snake_case_name):\n    \"\"\"\n    Converts snake_cased_names to CamelCaseNames.\n\n    :param snake_case_name: The name you'd like to convert from.\n    :type snake_case_name: string\n\n    :returns: A converted string\n    :rtype: string\n    \"\"\"\n    bits = snake_case_name.split('_')\n    return ''.join([bit.capitalize() for bit in bits])", "title": ""}
{"_id": "d2960", "text": "def figsize(x=8, y=7., aspect=1.):\n    \"\"\" manually set the default figure size of plots\n    ::Arguments::\n        x (float): x-axis size\n        y (float): y-axis size\n        aspect (float): aspect ratio scalar\n    \"\"\"\n    # update rcparams with adjusted figsize params\n    mpl.rcParams.update({'figure.figsize': (x*aspect, y)})", "title": ""}
{"_id": "d2961", "text": "def get_last(self, table=None):\n        \"\"\"Just the last entry.\"\"\"\n        if table is None: table = self.main_table\n        query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n        return self.own_cursor.execute(query).fetchone()", "title": ""}
{"_id": "d2962", "text": "def rgb2gray(img):\n    \"\"\"Converts an RGB image to grayscale using matlab's algorithm.\"\"\"\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", "title": ""}
{"_id": "d2963", "text": "def jac(x,a):\n    \"\"\" Jacobian matrix given Christophe's suggestion of f \"\"\"\n    return (x-a) / np.sqrt(((x-a)**2).sum(1))[:,np.newaxis]", "title": ""}
{"_id": "d2964", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d2965", "text": "def test(*args):\n    \"\"\"\n    Run unit tests.\n    \"\"\"\n    subprocess.call([\"py.test-2.7\"] + list(args))\n    subprocess.call([\"py.test-3.4\"] + list(args))", "title": ""}
{"_id": "d2966", "text": "def _heapify_max(x):\n    \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n    n = len(x)\n    for i in reversed(range(n//2)):\n        _siftup_max(x, i)", "title": ""}
{"_id": "d2967", "text": "def commajoin_as_strings(iterable):\n    \"\"\" Join the given iterable with ',' \"\"\"\n    return _(u',').join((six.text_type(i) for i in iterable))", "title": ""}
{"_id": "d2968", "text": "def SegmentMax(a, ids):\n    \"\"\"\n    Segmented max op.\n    \"\"\"\n    func = lambda idxs: np.amax(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d2969", "text": "def as_tuple(self, value):\n        \"\"\"Utility function which converts lists to tuples.\"\"\"\n        if isinstance(value, list):\n            value = tuple(value)\n        return value", "title": ""}
{"_id": "d2970", "text": "def min_values(args):\n    \"\"\" Return possible range for min function. \"\"\"\n    return Interval(min(x.low for x in args), min(x.high for x in args))", "title": ""}
{"_id": "d2971", "text": "def md5_hash_file(fh):\n    \"\"\"Return the md5 hash of the given file-object\"\"\"\n    md5 = hashlib.md5()\n    while True:\n        data = fh.read(8192)\n        if not data:\n            break\n        md5.update(data)\n    return md5.hexdigest()", "title": ""}
{"_id": "d2972", "text": "def change_cell(self, x, y, ch, fg, bg):\n        \"\"\"Change cell in position (x;y).\n        \"\"\"\n        self.console.draw_char(x, y, ch, fg, bg)", "title": ""}
{"_id": "d2973", "text": "def memory_usage(method):\n  \"\"\"Log memory usage before and after a method.\"\"\"\n  def wrapper(*args, **kwargs):\n    logging.info('Memory before method %s is %s.',\n                 method.__name__, runtime.memory_usage().current())\n    result = method(*args, **kwargs)\n    logging.info('Memory after method %s is %s',\n                 method.__name__, runtime.memory_usage().current())\n    return result\n  return wrapper", "title": ""}
{"_id": "d2974", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d2975", "text": "def _rendered_size(text, point_size, font_file):\n    \"\"\"\n    Return a (width, height) pair representing the size of *text* in English\n    Metric Units (EMU) when rendered at *point_size* in the font defined in\n    *font_file*.\n    \"\"\"\n    emu_per_inch = 914400\n    px_per_inch = 72.0\n\n    font = _Fonts.font(font_file, point_size)\n    px_width, px_height = font.getsize(text)\n\n    emu_width = int(px_width / px_per_inch * emu_per_inch)\n    emu_height = int(px_height / px_per_inch * emu_per_inch)\n\n    return emu_width, emu_height", "title": ""}
{"_id": "d2976", "text": "def col_rename(df,col_name,new_col_name):\n    \"\"\" Changes a column name in a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_name - string\n        Name of column to change\n    new_col_name - string\n        New name of column\n    \"\"\"\n    col_list = list(df.columns)\n    for index,value in enumerate(col_list):\n        if value == col_name:\n            col_list[index] = new_col_name\n            break\n    df.columns = col_list", "title": ""}
{"_id": "d2977", "text": "def submit_form_id(step, id):\n    \"\"\"\n    Submit the form having given id.\n    \"\"\"\n    form = world.browser.find_element_by_xpath(str('id(\"{id}\")'.format(id=id)))\n    form.submit()", "title": ""}
{"_id": "d2978", "text": "def _tofloat(obj):\n    \"\"\"Convert to float if object is a float string.\"\"\"\n    if \"inf\" in obj.lower().strip():\n        return obj\n    try:\n        return int(obj)\n    except ValueError:\n        try:\n            return float(obj)\n        except ValueError:\n            return obj", "title": ""}
{"_id": "d2979", "text": "def get_subject(self, msg):\n        \"\"\"Extracts the subject line from an EmailMessage object.\"\"\"\n\n        text, encoding = decode_header(msg['subject'])[-1]\n\n        try:\n            text = text.decode(encoding)\n\n        # If it's already decoded, ignore error\n        except AttributeError:\n            pass\n\n        return text", "title": ""}
{"_id": "d2980", "text": "def update(packages, env=None, user=None):\n    \"\"\"\n    Update conda packages in a conda env\n\n    Attributes\n    ----------\n        packages: list of packages comma delimited\n    \"\"\"\n    packages = ' '.join(packages.split(','))\n    cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user)\n    return _execcmd(cmd, user=user)", "title": ""}
{"_id": "d2981", "text": "def downcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n    return [ tt.lower() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d2982", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d2983", "text": "def makedirs(path, mode=0o777, exist_ok=False):\n    \"\"\"A wrapper of os.makedirs().\"\"\"\n    os.makedirs(path, mode, exist_ok)", "title": ""}
{"_id": "d2984", "text": "def _check_fpos(self, fp_, fpos, offset, block):\n        \"\"\"Check file position matches blocksize\"\"\"\n        if (fp_.tell() + offset != fpos):\n            warnings.warn(\"Actual \"+block+\" header size does not match expected\")\n        return", "title": ""}
{"_id": "d2985", "text": "def assert_any_call(self, *args, **kwargs):\n        \"\"\"assert the mock has been called with the specified arguments.\n\n        The assert passes if the mock has *ever* been called, unlike\n        `assert_called_with` and `assert_called_once_with` that only pass if\n        the call is the most recent one.\"\"\"\n        kall = call(*args, **kwargs)\n        if kall not in self.call_args_list:\n            expected_string = self._format_mock_call_signature(args, kwargs)\n            raise AssertionError(\n                '%s call not found' % expected_string\n            )", "title": ""}
{"_id": "d2986", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d2987", "text": "def assert_any_call(self, *args, **kwargs):\n        \"\"\"assert the mock has been called with the specified arguments.\n\n        The assert passes if the mock has *ever* been called, unlike\n        `assert_called_with` and `assert_called_once_with` that only pass if\n        the call is the most recent one.\"\"\"\n        kall = call(*args, **kwargs)\n        if kall not in self.call_args_list:\n            expected_string = self._format_mock_call_signature(args, kwargs)\n            raise AssertionError(\n                '%s call not found' % expected_string\n            )", "title": ""}
{"_id": "d2988", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d2989", "text": "def update(self, *args, **kwargs):\n        \"\"\" A handy update() method which returns self :)\n\n        :rtype: DictProxy\n        \"\"\"\n        super(DictProxy, self).update(*args, **kwargs)\n        return self", "title": ""}
{"_id": "d2990", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d2991", "text": "def install():\n        \"\"\"\n        Installs ScoutApm SQL Instrumentation by monkeypatching the `cursor`\n        method of BaseDatabaseWrapper, to return a wrapper that instruments any\n        calls going through it.\n        \"\"\"\n\n        @monkeypatch_method(BaseDatabaseWrapper)\n        def cursor(original, self, *args, **kwargs):\n            result = original(*args, **kwargs)\n            return _DetailedTracingCursorWrapper(result, self)\n\n        logger.debug(\"Monkey patched SQL\")", "title": ""}
{"_id": "d2992", "text": "def is_integer(obj):\n    \"\"\"Is this an integer.\n\n    :param object obj:\n    :return:\n    \"\"\"\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))", "title": ""}
{"_id": "d2993", "text": "def move_up(lines=1, file=sys.stdout):\n    \"\"\" Move the cursor up a number of lines.\n\n        Esc[ValueA:\n        Moves the cursor up by the specified number of lines without changing\n        columns. If the cursor is already on the top line, ANSI.SYS ignores\n        this sequence.\n    \"\"\"\n    move.up(lines).write(file=file)", "title": ""}
{"_id": "d2994", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d2995", "text": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "title": ""}
{"_id": "d2996", "text": "def is_square_matrix(mat):\n    \"\"\"Test if an array is a square matrix.\"\"\"\n    mat = np.array(mat)\n    if mat.ndim != 2:\n        return False\n    shape = mat.shape\n    return shape[0] == shape[1]", "title": ""}
{"_id": "d2997", "text": "def align_file_position(f, size):\n    \"\"\" Align the position in the file to the next block of specified size \"\"\"\n    align = (size - 1) - (f.tell() % size)\n    f.seek(align, 1)", "title": ""}
{"_id": "d2998", "text": "def filter_regex(names, regex):\n    \"\"\"\n    Return a tuple of strings that match the regular expression pattern.\n    \"\"\"\n    return tuple(name for name in names\n                 if regex.search(name) is not None)", "title": ""}
{"_id": "d2999", "text": "def gmove(pattern, destination):\n    \"\"\"Move all file found by glob.glob(pattern) to destination directory.\n\n    Args:\n        pattern (str): Glob pattern\n        destination (str): Path to the destination directory.\n\n    Returns:\n        bool: True if the operation is successful, False otherwise.\n    \"\"\"\n    for item in glob.glob(pattern):\n        if not move(item, destination):\n            return False\n    return True", "title": ""}
{"_id": "d3000", "text": "def is_sparse_vector(x):\n    \"\"\" x is a 2D sparse matrix with it's first shape equal to 1.\n    \"\"\"\n    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1", "title": ""}
{"_id": "d3001", "text": "def movingaverage(arr, window):\n    \"\"\"\n    Calculates the moving average (\"rolling mean\") of an array\n    of a certain window size.\n    \"\"\"\n    m = np.ones(int(window)) / int(window)\n    return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')", "title": ""}
{"_id": "d3002", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d3003", "text": "def validate_multiindex(self, obj):\n        \"\"\"validate that we can store the multi-index; reset and return the\n        new object\n        \"\"\"\n        levels = [l if l is not None else \"level_{0}\".format(i)\n                  for i, l in enumerate(obj.index.names)]\n        try:\n            return obj.reset_index(), levels\n        except ValueError:\n            raise ValueError(\"duplicate names/columns in the multi-index when \"\n                             \"storing as a table\")", "title": ""}
{"_id": "d3004", "text": "def me(self):\n        \"\"\"Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.\"\"\"\n        return self.guild.me if self.guild is not None else self.bot.user", "title": ""}
{"_id": "d3005", "text": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "title": ""}
{"_id": "d3006", "text": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "title": ""}
{"_id": "d3007", "text": "def graphql_queries_to_json(*queries):\n    \"\"\"\n    Queries should be a list of GraphQL objects\n    \"\"\"\n    rtn = {}\n    for i, query in enumerate(queries):\n        rtn[\"q{}\".format(i)] = query.value\n    return json.dumps(rtn)", "title": ""}
{"_id": "d3008", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d3009", "text": "def linregress(x, y, return_stats=False):\n    \"\"\"linear regression calculation\n\n    Parameters\n    ----\n    x :         independent variable (series)\n    y :         dependent variable (series)\n    return_stats : returns statistical values as well if required (bool)\n    \n\n    Returns\n    ----\n    list of parameters (and statistics)\n    \"\"\"\n    a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y)\n\n    retval = a1, a0\n    if return_stats:\n        retval += r_value, p_value, stderr\n\n    return retval", "title": ""}
{"_id": "d3010", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d3011", "text": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "title": ""}
{"_id": "d3012", "text": "def allsame(list_, strict=True):\n    \"\"\"\n    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\n    \"\"\"\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)", "title": ""}
{"_id": "d3013", "text": "def ncores_reserved(self):\n        \"\"\"\n        Returns the number of cores reserved in this moment.\n        A core is reserved if it's still not running but\n        we have submitted the task to the queue manager.\n        \"\"\"\n        return sum(task.manager.num_cores for task in self if task.status == task.S_SUB)", "title": ""}
{"_id": "d3014", "text": "def is_list_of_list(item):\n    \"\"\"\n    check whether the item is list (tuple)\n    and consist of list (tuple) elements\n    \"\"\"\n    if (\n        type(item) in (list, tuple)\n        and len(item)\n        and isinstance(item[0], (list, tuple))\n    ):\n        return True\n    return False", "title": ""}
{"_id": "d3015", "text": "def ncores_reserved(self):\n        \"\"\"\n        Returns the number of cores reserved in this moment.\n        A core is reserved if it's still not running but\n        we have submitted the task to the queue manager.\n        \"\"\"\n        return sum(task.manager.num_cores for task in self if task.status == task.S_SUB)", "title": ""}
{"_id": "d3016", "text": "def is_dataframe(obj):\n    \"\"\"\n    Returns True if the given object is a Pandas Data Frame.\n\n    Parameters\n    ----------\n    obj: instance\n        The object to test whether or not is a Pandas DataFrame.\n    \"\"\"\n    try:\n        # This is the best method of type checking\n        from pandas import DataFrame\n        return isinstance(obj, DataFrame)\n    except ImportError:\n        # Pandas is not a dependency, so this is scary\n        return obj.__class__.__name__ == \"DataFrame\"", "title": ""}
{"_id": "d3017", "text": "def stop(self):\n        \"\"\"stop server\"\"\"\n        try:\n            self.shutdown()\n        except (PyMongoError, ServersError) as exc:\n            logger.info(\"Killing %s with signal, shutdown command failed: %r\",\n                        self.name, exc)\n            return process.kill_mprocess(self.proc)", "title": ""}
{"_id": "d3018", "text": "def build_list_type_validator(item_validator):\n    \"\"\"Return a function which validates that the value is a list of items\n    which are validated using item_validator.\n    \"\"\"\n    def validate_list_of_type(value):\n        return [item_validator(item) for item in validate_list(value)]\n    return validate_list_of_type", "title": ""}
{"_id": "d3019", "text": "def compute(args):\n    x, y, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot(x, y, params)", "title": ""}
{"_id": "d3020", "text": "def allZero(buffer):\n    \"\"\"\n    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.\n    \"\"\"\n    allZero = True\n    for byte in buffer:\n        if byte != \"\\x00\":\n            allZero = False\n            break\n    return allZero", "title": ""}
{"_id": "d3021", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d3022", "text": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "title": ""}
{"_id": "d3023", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d3024", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d3025", "text": "def connect_mysql(host, port, user, password, database):\n    \"\"\"Connect to MySQL with retries.\"\"\"\n    return pymysql.connect(\n        host=host, port=port,\n        user=user, passwd=password,\n        db=database\n    )", "title": ""}
{"_id": "d3026", "text": "def isstring(value):\n    \"\"\"Report whether the given value is a byte or unicode string.\"\"\"\n    classes = (str, bytes) if pyutils.PY3 else basestring  # noqa: F821\n    return isinstance(value, classes)", "title": ""}
{"_id": "d3027", "text": "async def scalar(self, query, as_tuple=False):\n        \"\"\"Get single value from ``select()`` query, i.e. for aggregation.\n\n        :return: result is the same as after sync ``query.scalar()`` call\n        \"\"\"\n        query = self._swap_database(query)\n        return (await scalar(query, as_tuple=as_tuple))", "title": ""}
{"_id": "d3028", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d3029", "text": "def executemany(self, sql, *params):\n        \"\"\"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.\n        \"\"\"\n        fut = self._run_operation(self._impl.executemany, sql, *params)\n        return fut", "title": ""}
{"_id": "d3030", "text": "def _internet_on(address):\n    \"\"\"\n    Check to see if the internet is on by pinging a set address.\n    :param address: the IP or address to hit\n    :return: a boolean - true if can be reached, false if not.\n    \"\"\"\n    try:\n        urllib2.urlopen(address, timeout=1)\n        return True\n    except urllib2.URLError as err:\n        return False", "title": ""}
{"_id": "d3031", "text": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "title": ""}
{"_id": "d3032", "text": "def information(filename):\n    \"\"\"Returns the file exif\"\"\"\n    check_if_this_file_exist(filename)\n    filename = os.path.abspath(filename)\n    result = get_json(filename)\n    result = result[0]\n    return result", "title": ""}
{"_id": "d3033", "text": "def _Enum(docstring, *names):\n  \"\"\"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.\n  \"\"\"\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)", "title": ""}
{"_id": "d3034", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d3035", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d3036", "text": "def is_exe(fpath):\n    \"\"\"\n    Path references an executable file.\n    \"\"\"\n    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)", "title": ""}
{"_id": "d3037", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d3038", "text": "def get_adjacent_matrix(self):\n        \"\"\"Get adjacency matrix.\n\n        Returns:\n            :param adj: adjacency matrix\n            :type adj: np.ndarray\n        \"\"\"\n        edges = self.edges\n        num_edges = len(edges) + 1\n        adj = np.zeros([num_edges, num_edges])\n\n        for k in range(num_edges - 1):\n            adj[edges[k].L, edges[k].R] = 1\n            adj[edges[k].R, edges[k].L] = 1\n\n        return adj", "title": ""}
{"_id": "d3039", "text": "def get_shared_memory_bytes():\n    \"\"\"Get the size of the shared memory file system.\n\n    Returns:\n        The size of the shared memory file system in bytes.\n    \"\"\"\n    # Make sure this is only called on Linux.\n    assert sys.platform == \"linux\" or sys.platform == \"linux2\"\n\n    shm_fd = os.open(\"/dev/shm\", os.O_RDONLY)\n    try:\n        shm_fs_stats = os.fstatvfs(shm_fd)\n        # The value shm_fs_stats.f_bsize is the block size and the\n        # value shm_fs_stats.f_bavail is the number of available\n        # blocks.\n        shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail\n    finally:\n        os.close(shm_fd)\n\n    return shm_avail", "title": ""}
{"_id": "d3040", "text": "def from_json_str(cls, json_str):\n    \"\"\"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.\n    \"\"\"\n    return cls.from_json(json.loads(json_str, cls=JsonDecoder))", "title": ""}
{"_id": "d3041", "text": "def is_timestamp(obj):\n    \"\"\"\n    Yaml either have automatically converted it to a datetime object\n    or it is a string that will be validated later.\n    \"\"\"\n    return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)", "title": ""}
{"_id": "d3042", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d3043", "text": "def launched():\n    \"\"\"Test whether the current python environment is the correct lore env.\n\n    :return:  :any:`True` if the environment is launched\n    :rtype: bool\n    \"\"\"\n    if not PREFIX:\n        return False\n\n    return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)", "title": ""}
{"_id": "d3044", "text": "def ner_chunk(args):\n  \"\"\"Chunk named entities.\"\"\"\n  chunker = NEChunker(lang=args.lang)\n  tag(chunker, args)", "title": ""}
{"_id": "d3045", "text": "def cell_ends_with_code(lines):\n    \"\"\"Is the last line of the cell a line with code?\"\"\"\n    if not lines:\n        return False\n    if not lines[-1].strip():\n        return False\n    if lines[-1].startswith('#'):\n        return False\n    return True", "title": ""}
{"_id": "d3046", "text": "def get_prep_value(self, value):\n        \"\"\"Convert JSON object to a string\"\"\"\n        if self.null and value is None:\n            return None\n        return json.dumps(value, **self.dump_kwargs)", "title": ""}
{"_id": "d3047", "text": "def reset(self):\n        \"\"\"Reset analyzer state\n        \"\"\"\n        self.prevframe = None\n        self.wasmoving = False\n        self.t0 = 0\n        self.ismoving = False", "title": ""}
{"_id": "d3048", "text": "def _get_non_empty_list(cls, iter):\n        \"\"\"Return a list of the input, excluding all ``None`` values.\"\"\"\n        res = []\n        for value in iter:\n            if hasattr(value, 'items'):\n                value = cls._get_non_empty_dict(value) or None\n            if value is not None:\n                res.append(value)\n        return res", "title": ""}
{"_id": "d3049", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d3050", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d3051", "text": "def __exit__(self, *args):\n        \"\"\"\n        Cleanup any necessary opened files\n        \"\"\"\n\n        if self._output_file_handle:\n            self._output_file_handle.close()\n            self._output_file_handle = None", "title": ""}
{"_id": "d3052", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d3053", "text": "def get_selected_values(self, selection):\n        \"\"\"Return a list of values for the given selection.\"\"\"\n        return [v for b, v in self._choices if b & selection]", "title": ""}
{"_id": "d3054", "text": "def isTestCaseDisabled(test_case_class, method_name):\n    \"\"\"\n    I check to see if a method on a TestCase has been disabled via nose's\n    convention for disabling a TestCase.  This makes it so that users can\n    mix nose's parameterized tests with green as a runner.\n    \"\"\"\n    test_method = getattr(test_case_class, method_name)\n    return getattr(test_method, \"__test__\", 'not nose') is False", "title": ""}
{"_id": "d3055", "text": "def compare(a, b):\n    \"\"\"\n     Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))\n    \"\"\"\n    s=0\n    for i in range(len(a)):\n        s=s+abs(a[i]-b[i])\n    return s", "title": ""}
{"_id": "d3056", "text": "def call_and_exit(self, cmd, shell=True):\n        \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n        sys.exit(subprocess.call(cmd, shell=shell))", "title": ""}
{"_id": "d3057", "text": "def equal(obj1, obj2):\n    \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n    Comparable.log(obj1, obj2, '==')\n    equality = obj1.equality(obj2)\n    Comparable.log(obj1, obj2, '==', result=equality)\n    return equality", "title": ""}
{"_id": "d3058", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d3059", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d3060", "text": "def check_exists(filename, oappend=False):\n    \"\"\"\n    Avoid overwriting some files accidentally.\n    \"\"\"\n    if op.exists(filename):\n        if oappend:\n            return oappend\n        logging.error(\"`{0}` found, overwrite (Y/N)?\".format(filename))\n        overwrite = (raw_input() == 'Y')\n    else:\n        overwrite = True\n\n    return overwrite", "title": ""}
{"_id": "d3061", "text": "def _pooling_output_shape(input_shape, pool_size=(2, 2),\n                          strides=None, padding='VALID'):\n  \"\"\"Helper: compute the output shape for the pooling layer.\"\"\"\n  dims = (1,) + pool_size + (1,)  # NHWC\n  spatial_strides = strides or (1,) * len(pool_size)\n  strides = (1,) + spatial_strides + (1,)\n  pads = padtype_to_pads(input_shape, dims, strides, padding)\n  operand_padded = onp.add(input_shape, onp.add(*zip(*pads)))\n  t = onp.floor_divide(onp.subtract(operand_padded, dims), strides) + 1\n  return tuple(t)", "title": ""}
{"_id": "d3062", "text": "def other_ind(self):\n        \"\"\"last row or column of square A\"\"\"\n        return np.full(self.n_min, self.size - 1, dtype=np.int)", "title": ""}
{"_id": "d3063", "text": "def encode(strs):\n    \"\"\"Encodes a list of strings to a single string.\n    :type strs: List[str]\n    :rtype: str\n    \"\"\"\n    res = ''\n    for string in strs.split():\n        res += str(len(string)) + \":\" + string\n    return res", "title": ""}
{"_id": "d3064", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d3065", "text": "def __connect():\n    \"\"\"\n    Connect to a redis instance.\n    \"\"\"\n    global redis_instance\n    if use_tcp_socket:\n        redis_instance = redis.StrictRedis(host=hostname, port=port)\n    else:\n        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "title": ""}
{"_id": "d3066", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d3067", "text": "def from_dict(cls, d):\n        \"\"\"Create an instance from a dictionary.\"\"\"\n        return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})", "title": ""}
{"_id": "d3068", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d3069", "text": "def num_leaves(tree):\n    \"\"\"Determine the number of leaves in a tree\"\"\"\n    if tree.is_leaf:\n        return 1\n    else:\n        return num_leaves(tree.left_child) + num_leaves(tree.right_child)", "title": ""}
{"_id": "d3070", "text": "def _std(self,x):\n        \"\"\"\n        Compute standard deviation with ddof degrees of freedom\n        \"\"\"\n        return np.nanstd(x.values,ddof=self._ddof)", "title": ""}
{"_id": "d3071", "text": "def objectcount(data, key):\n    \"\"\"return the count of objects of key\"\"\"\n    objkey = key.upper()\n    return len(data.dt[objkey])", "title": ""}
{"_id": "d3072", "text": "def iterexpand(arry, extra):\n    \"\"\"\n    Expand dimensions by iteratively append empty axes.\n\n    Parameters\n    ----------\n    arry : ndarray\n        The original array\n\n    extra : int\n        The number of empty axes to append\n    \"\"\"\n    for d in range(arry.ndim, arry.ndim+extra):\n        arry = expand_dims(arry, axis=d)\n    return arry", "title": ""}
{"_id": "d3073", "text": "def aws_to_unix_id(aws_key_id):\n    \"\"\"Converts a AWS Key ID into a UID\"\"\"\n    uid_bytes = hashlib.sha256(aws_key_id.encode()).digest()[-2:]\n    if USING_PYTHON2:\n        return 2000 + int(from_bytes(uid_bytes) // 2)\n    else:\n        return 2000 + (int.from_bytes(uid_bytes, byteorder=sys.byteorder) // 2)", "title": ""}
{"_id": "d3074", "text": "def imflip(img, direction='horizontal'):\n    \"\"\"Flip an image horizontally or vertically.\n\n    Args:\n        img (ndarray): Image to be flipped.\n        direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n    Returns:\n        ndarray: The flipped image.\n    \"\"\"\n    assert direction in ['horizontal', 'vertical']\n    if direction == 'horizontal':\n        return np.flip(img, axis=1)\n    else:\n        return np.flip(img, axis=0)", "title": ""}
{"_id": "d3075", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d3076", "text": "def _linear_interpolation(x, X, Y):\n    \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n    \"\"\"\n    return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "title": ""}
{"_id": "d3077", "text": "def flattened_nested_key_indices(nested_dict):\n    \"\"\"\n    Combine the outer and inner keys of nested dictionaries into a single\n    ordering.\n    \"\"\"\n    outer_keys, inner_keys = collect_nested_keys(nested_dict)\n    combined_keys = list(sorted(set(outer_keys + inner_keys)))\n    return {k: i for (i, k) in enumerate(combined_keys)}", "title": ""}
{"_id": "d3078", "text": "def movingaverage(arr, window):\n    \"\"\"\n    Calculates the moving average (\"rolling mean\") of an array\n    of a certain window size.\n    \"\"\"\n    m = np.ones(int(window)) / int(window)\n    return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')", "title": ""}
{"_id": "d3079", "text": "def run(self, *args, **kwargs):\n        \"\"\" Connect and run bot in event loop. \"\"\"\n        self.eventloop.run_until_complete(self.connect(*args, **kwargs))\n        try:\n            self.eventloop.run_forever()\n        finally:\n            self.eventloop.stop()", "title": ""}
{"_id": "d3080", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d3081", "text": "def ensure_dir_exists(directory):\n    \"\"\"Se asegura de que un directorio exista.\"\"\"\n    if directory and not os.path.exists(directory):\n        os.makedirs(directory)", "title": ""}
{"_id": "d3082", "text": "def ReadTif(tifFile):\n        \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n        img = Image.open(tifFile)\n        img = np.array(img)\n        return img", "title": ""}
{"_id": "d3083", "text": "def append_scope(self):\n        \"\"\"Create a new scope in the current frame.\"\"\"\n        self.stack.current.append(Scope(self.stack.current.current))", "title": ""}
{"_id": "d3084", "text": "def _isnan(self):\n        \"\"\"\n        Return if each value is NaN.\n        \"\"\"\n        if self._can_hold_na:\n            return isna(self)\n        else:\n            # shouldn't reach to this condition by checking hasnans beforehand\n            values = np.empty(len(self), dtype=np.bool_)\n            values.fill(False)\n            return values", "title": ""}
{"_id": "d3085", "text": "def write_color(string, name, style='normal', when='auto'):\n    \"\"\" Write the given colored string to standard out. \"\"\"\n    write(color(string, name, style, when))", "title": ""}
{"_id": "d3086", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d3087", "text": "def send_dir(self, local_path, remote_path, user='root'):\n        \"\"\"Upload a directory on the remote host.\n        \"\"\"\n        self.enable_user(user)\n        return self.ssh_pool.send_dir(user, local_path, remote_path)", "title": ""}
{"_id": "d3088", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d3089", "text": "def symlink(source, destination):\n    \"\"\"Create a symbolic link\"\"\"\n    log(\"Symlinking {} as {}\".format(source, destination))\n    cmd = [\n        'ln',\n        '-sf',\n        source,\n        destination,\n    ]\n    subprocess.check_call(cmd)", "title": ""}
{"_id": "d3090", "text": "def _array2cstr(arr):\n    \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())", "title": ""}
{"_id": "d3091", "text": "def set_header(self, key, value):\n    \"\"\" Sets a HTTP header for future requests. \"\"\"\n    self.conn.issue_command(\"Header\", _normalize_header(key), value)", "title": ""}
{"_id": "d3092", "text": "def rank(self):\n        \"\"\"how high in sorted list each key is. inverse permutation of sorter, such that sorted[rank]==keys\"\"\"\n        r = np.empty(self.size, np.int)\n        r[self.sorter] = np.arange(self.size)\n        return r", "title": ""}
{"_id": "d3093", "text": "def batchify(data, batch_size):\n    \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n    nbatch = data.shape[0] // batch_size\n    data = data[:nbatch * batch_size]\n    data = data.reshape((batch_size, nbatch)).T\n    return data", "title": ""}
{"_id": "d3094", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d3095", "text": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "title": ""}
{"_id": "d3096", "text": "def load_object_by_name(object_name):\n    \"\"\"Load an object from a module by name\"\"\"\n    mod_name, attr = object_name.rsplit('.', 1)\n    mod = import_module(mod_name)\n    return getattr(mod, attr)", "title": ""}
{"_id": "d3097", "text": "def safe_setattr(obj, name, value):\n    \"\"\"Attempt to setattr but catch AttributeErrors.\"\"\"\n    try:\n        setattr(obj, name, value)\n        return True\n    except AttributeError:\n        return False", "title": ""}
{"_id": "d3098", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d3099", "text": "def _Enum(docstring, *names):\n  \"\"\"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.\n  \"\"\"\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)", "title": ""}
{"_id": "d3100", "text": "def object_as_dict(obj):\n    \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n    Based on https://stackoverflow.com/a/37350445/1579058\n    \"\"\"\n    return {c.key: getattr(obj, c.key)\n            for c in inspect(obj).mapper.column_attrs}", "title": ""}
{"_id": "d3101", "text": "def return_value(self, *args, **kwargs):\n        \"\"\"Extracts the real value to be returned from the wrapping callable.\n\n        :return: The value the double should return when called.\n        \"\"\"\n\n        self._called()\n        return self._return_value(*args, **kwargs)", "title": ""}
{"_id": "d3102", "text": "def fit_linear(X, y):\n    \"\"\"\n    Uses OLS to fit the regression.\n    \"\"\"\n    model = linear_model.LinearRegression()\n    model.fit(X, y)\n    return model", "title": ""}
{"_id": "d3103", "text": "def remover(file_path):\n    \"\"\"Delete a file or directory path only if it exists.\"\"\"\n    if os.path.isfile(file_path):\n        os.remove(file_path)\n        return True\n    elif os.path.isdir(file_path):\n        shutil.rmtree(file_path)\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d3104", "text": "def reduce_fn(x):\n    \"\"\"\n    Aggregation function to get the first non-zero value.\n    \"\"\"\n    values = x.values if pd and isinstance(x, pd.Series) else x\n    for v in values:\n        if not is_nan(v):\n            return v\n    return np.NaN", "title": ""}
{"_id": "d3105", "text": "def del_label(self, name):\n        \"\"\"Delete a label by name.\"\"\"\n        labels_tag = self.root[0]\n        labels_tag.remove(self._find_label(name))", "title": ""}
{"_id": "d3106", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d3107", "text": "def safe_delete(filename):\n  \"\"\"Delete a file safely. If it's not present, no-op.\"\"\"\n  try:\n    os.unlink(filename)\n  except OSError as e:\n    if e.errno != errno.ENOENT:\n      raise", "title": ""}
{"_id": "d3108", "text": "def read(filename):\n    \"\"\"Read and return `filename` in root dir of project and return string\"\"\"\n    return codecs.open(os.path.join(__DIR__, filename), 'r').read()", "title": ""}
{"_id": "d3109", "text": "def cli(env, identifier):\n    \"\"\"Delete an image.\"\"\"\n\n    image_mgr = SoftLayer.ImageManager(env.client)\n    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')\n\n    image_mgr.delete_image(image_id)", "title": ""}
{"_id": "d3110", "text": "def read_string_from_file(path, encoding=\"utf8\"):\n  \"\"\"\n  Read entire contents of file into a string.\n  \"\"\"\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value", "title": ""}
{"_id": "d3111", "text": "def remove_examples_all():\n    \"\"\"remove arduino/examples/all directory.\n\n    :rtype: None\n\n    \"\"\"\n    d = examples_all_dir()\n    if d.exists():\n        log.debug('remove %s', d)\n        d.rmtree()\n    else:\n        log.debug('nothing to remove: %s', d)", "title": ""}
{"_id": "d3112", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d3113", "text": "def make_bintree(levels):\n    \"\"\"Make a symmetrical binary tree with @levels\"\"\"\n    G = nx.DiGraph()\n    root = '0'\n    G.add_node(root)\n    add_children(G, root, levels, 2)\n    return G", "title": ""}
{"_id": "d3114", "text": "def read_string_from_file(path, encoding=\"utf8\"):\n  \"\"\"\n  Read entire contents of file into a string.\n  \"\"\"\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value", "title": ""}
{"_id": "d3115", "text": "def str2int(string_with_int):\n    \"\"\" Collect digits from a string \"\"\"\n    return int(\"\".join([char for char in string_with_int if char in string.digits]) or 0)", "title": ""}
{"_id": "d3116", "text": "def imdecode(image_path):\n    \"\"\"Return BGR image read by opencv\"\"\"\n    import os\n    assert os.path.exists(image_path), image_path + ' not found'\n    im = cv2.imread(image_path)\n    return im", "title": ""}
{"_id": "d3117", "text": "def _match_space_at_line(line):\n    \"\"\"Return a re.match object if an empty comment was found on line.\"\"\"\n    regex = re.compile(r\"^{0}$\".format(_MDL_COMMENT))\n    return regex.match(line)", "title": ""}
{"_id": "d3118", "text": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "title": ""}
{"_id": "d3119", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d3120", "text": "def set_rate(rate):\n    \"\"\"Defines the ideal rate at which computation is to be performed\n\n    :arg rate: the frequency in Hertz \n    :type rate: int or float\n\n    :raises: TypeError: if argument 'rate' is not int or float\n    \"\"\"\n    if not (isinstance(rate, int) or isinstance(rate, float)):\n        raise TypeError(\"argument to set_rate is expected to be int or float\")\n    global loop_duration\n    loop_duration = 1.0/rate", "title": ""}
{"_id": "d3121", "text": "def _platform_pylib_exts():  # nocover\n    \"\"\"\n    Returns .so, .pyd, or .dylib depending on linux, win or mac.\n    On python3 return the previous with and without abi (e.g.\n    .cpython-35m-x86_64-linux-gnu) flags. On python2 returns with\n    and without multiarch.\n    \"\"\"\n    import sysconfig\n    valid_exts = []\n    if six.PY2:\n        # see also 'SHLIB_EXT'\n        base_ext = '.' + sysconfig.get_config_var('SO').split('.')[-1]\n    else:\n        # return with and without API flags\n        # handle PEP 3149 -- ABI version tagged .so files\n        base_ext = '.' + sysconfig.get_config_var('EXT_SUFFIX').split('.')[-1]\n    for tag in _extension_module_tags():\n        valid_exts.append('.' + tag + base_ext)\n    valid_exts.append(base_ext)\n    return tuple(valid_exts)", "title": ""}
{"_id": "d3122", "text": "def apply_argument_parser(argumentsParser, options=None):\n    \"\"\" Apply the argument parser. \"\"\"\n    if options is not None:\n        args = argumentsParser.parse_args(options)\n    else:\n        args = argumentsParser.parse_args()\n    return args", "title": ""}
{"_id": "d3123", "text": "def _visual_width(line):\n    \"\"\"Get the the number of columns required to display a string\"\"\"\n\n    return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, \"\", line))", "title": ""}
{"_id": "d3124", "text": "def help(self, level=0):\n        \"\"\"return the usage string for available options \"\"\"\n        self.cmdline_parser.formatter.output_level = level\n        with _patch_optparse():\n            return self.cmdline_parser.format_help()", "title": ""}
{"_id": "d3125", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d3126", "text": "def check_create_folder(filename):\n    \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n    os.makedirs(os.path.dirname(filename), exist_ok=True)", "title": ""}
{"_id": "d3127", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d3128", "text": "def zero_pad(m, n=1):\n    \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n    return np.pad(m, (n, n), mode='constant', constant_values=[0])", "title": ""}
{"_id": "d3129", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d3130", "text": "def zero_pad(m, n=1):\n    \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n    return np.pad(m, (n, n), mode='constant', constant_values=[0])", "title": ""}
{"_id": "d3131", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d3132", "text": "def column_exists(cr, table, column):\n    \"\"\" Check whether a certain column exists \"\"\"\n    cr.execute(\n        'SELECT count(attname) FROM pg_attribute '\n        'WHERE attrelid = '\n        '( SELECT oid FROM pg_class WHERE relname = %s ) '\n        'AND attname = %s',\n        (table, column))\n    return cr.fetchone()[0] == 1", "title": ""}
{"_id": "d3133", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d3134", "text": "def query_sum(queryset, field):\n    \"\"\"\n    Let the DBMS perform a sum on a queryset\n    \"\"\"\n    return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']", "title": ""}
{"_id": "d3135", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d3136", "text": "def user_parse(data):\n        \"\"\"Parse information from the provider.\"\"\"\n        _user = data.get('response', {}).get('user', {})\n        yield 'id', _user.get('name')\n        yield 'username', _user.get('name')\n        yield 'link', _user.get('blogs', [{}])[0].get('url')", "title": ""}
{"_id": "d3137", "text": "def clip_image(image, clip_min, clip_max):\n  \"\"\" Clip an image, or an image batch, with upper and lower threshold. \"\"\"\n  return np.minimum(np.maximum(clip_min, image), clip_max)", "title": ""}
{"_id": "d3138", "text": "def clean_time(time_string):\n    \"\"\"Return a datetime from the Amazon-provided datetime string\"\"\"\n    # Get a timezone-aware datetime object from the string\n    time = dateutil.parser.parse(time_string)\n    if not settings.USE_TZ:\n        # If timezone support is not active, convert the time to UTC and\n        # remove the timezone field\n        time = time.astimezone(timezone.utc).replace(tzinfo=None)\n    return time", "title": ""}
{"_id": "d3139", "text": "def updateFromKwargs(self, properties, kwargs, collector, **unused):\n        \"\"\"Primary entry point to turn 'kwargs' into 'properties'\"\"\"\n        properties[self.name] = self.getFromKwargs(kwargs)", "title": ""}
{"_id": "d3140", "text": "def string_to_float_list(string_var):\n        \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n        try:\n            return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n        except:\n            return [float(s) for s in string_var.strip('[').strip(']').split(',')]", "title": ""}
{"_id": "d3141", "text": "def wget(url):\n    \"\"\"\n    Download the page into a string\n    \"\"\"\n    import urllib.parse\n    request = urllib.request.urlopen(url)\n    filestring = request.read()\n    return filestring", "title": ""}
{"_id": "d3142", "text": "def parse_json_date(value):\n    \"\"\"\n    Parses an ISO8601 formatted datetime from a string value\n    \"\"\"\n    if not value:\n        return None\n\n    return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)", "title": ""}
{"_id": "d3143", "text": "def dedupe_list(l):\n    \"\"\"Remove duplicates from a list preserving the order.\n\n    We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n    the order, which hinders testability and does not work for lists with\n    unhashable elements.\n    \"\"\"\n    result = []\n\n    for el in l:\n        if el not in result:\n            result.append(el)\n\n    return result", "title": ""}
{"_id": "d3144", "text": "def parse_query_string(query):\n    \"\"\"\n    parse_query_string:\n    very simplistic. won't do the right thing with list values\n    \"\"\"\n    result = {}\n    qparts = query.split('&')\n    for item in qparts:\n        key, value = item.split('=')\n        key = key.strip()\n        value = value.strip()\n        result[key] = unquote_plus(value)\n    return result", "title": ""}
{"_id": "d3145", "text": "def get_dict_for_attrs(obj, attrs):\n    \"\"\"\n    Returns dictionary for each attribute from given ``obj``.\n    \"\"\"\n    data = {}\n    for attr in attrs:\n        data[attr] = getattr(obj, attr)\n    return data", "title": ""}
{"_id": "d3146", "text": "def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):\n    \"\"\" Transforms the output of parse() into a Text object.\n        The token parameter lists the order of tags in each token in the input string.\n    \"\"\"\n    return Text(string, token)", "title": ""}
{"_id": "d3147", "text": "def map_wrap(f):\n    \"\"\"Wrap standard function to easily pass into 'map' processing.\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d3148", "text": "def parse(source, remove_comments=True, **kw):\n    \"\"\"Thin wrapper around ElementTree.parse\"\"\"\n    return ElementTree.parse(source, SourceLineParser(), **kw)", "title": ""}
{"_id": "d3149", "text": "def dropna(self, subset=None):\n        \"\"\"Remove missing values according to Baloo's convention.\n\n        Parameters\n        ----------\n        subset : list of str, optional\n            Which columns to check for missing values in.\n\n        Returns\n        -------\n        DataFrame\n            DataFrame with no null values in columns.\n\n        \"\"\"\n        subset = check_and_obtain_subset_columns(subset, self)\n        not_nas = [v.notna() for v in self[subset]._iter()]\n        and_filter = reduce(lambda x, y: x & y, not_nas)\n\n        return self[and_filter]", "title": ""}
{"_id": "d3150", "text": "def updateFromKwargs(self, properties, kwargs, collector, **unused):\n        \"\"\"Primary entry point to turn 'kwargs' into 'properties'\"\"\"\n        properties[self.name] = self.getFromKwargs(kwargs)", "title": ""}
{"_id": "d3151", "text": "def clean_dict_keys(d):\n    \"\"\"Convert all keys of the dict 'd' to (ascii-)strings.\n\n    :Raises: UnicodeEncodeError\n    \"\"\"\n    new_d = {}\n    for (k, v) in d.iteritems():\n        new_d[str(k)] = v\n    return new_d", "title": ""}
{"_id": "d3152", "text": "def def_linear(fun):\n    \"\"\"Flags that a function is linear wrt all args\"\"\"\n    defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:\n                  fun(*subval(args, argnum, g), **kwargs))", "title": ""}
{"_id": "d3153", "text": "def test3():\n    \"\"\"Test the multiprocess\n    \"\"\"\n    import time\n    \n    p = MVisionProcess()\n    p.start()\n    time.sleep(5)\n    p.stop()", "title": ""}
{"_id": "d3154", "text": "def reprkwargs(kwargs, sep=', ', fmt=\"{0!s}={1!r}\"):\n    \"\"\"Display kwargs.\"\"\"\n    return sep.join(fmt.format(k, v) for k, v in kwargs.iteritems())", "title": ""}
{"_id": "d3155", "text": "def remove_punctuation(text, exceptions=[]):\n    \"\"\"\n    Return a string with punctuation removed.\n\n    Parameters:\n        text (str): The text to remove punctuation from.\n        exceptions (list): List of symbols to keep in the given text.\n\n    Return:\n        str: The input text without the punctuation.\n    \"\"\"\n\n    all_but = [\n        r'\\w',\n        r'\\s'\n    ]\n\n    all_but.extend(exceptions)\n\n    pattern = '[^{}]'.format(''.join(all_but))\n\n    return re.sub(pattern, '', text)", "title": ""}
{"_id": "d3156", "text": "def is_file(path):\n    \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n    try:\n        return path.expanduser().absolute().is_file()\n    except AttributeError:\n        return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))", "title": ""}
{"_id": "d3157", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d3158", "text": "def dir_path(dir):\n    \"\"\"with dir_path(path) to change into a directory.\"\"\"\n    old_dir = os.getcwd()\n    os.chdir(dir)\n    yield\n    os.chdir(old_dir)", "title": ""}
{"_id": "d3159", "text": "def exit_and_fail(self, msg=None, out=None):\n    \"\"\"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)\n    \"\"\"\n    self.exit(result=PANTS_FAILED_EXIT_CODE, msg=msg, out=out)", "title": ""}
{"_id": "d3160", "text": "def palettebar(height, length, colormap):\n    \"\"\"Return the channels of a palettebar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.palettize(cbar)", "title": ""}
{"_id": "d3161", "text": "def do_exit(self, arg):\n        \"\"\"Exit the shell session.\"\"\"\n\n        if self.current:\n            self.current.close()\n        self.resource_manager.close()\n        del self.resource_manager\n        return True", "title": ""}
{"_id": "d3162", "text": "def user_return(self, frame, return_value):\n        \"\"\"This function is called when a return trap is set here.\"\"\"\n        pdb.Pdb.user_return(self, frame, return_value)", "title": ""}
{"_id": "d3163", "text": "def unzip_file_to_dir(path_to_zip, output_directory):\n    \"\"\"\n    Extract a ZIP archive to a directory\n    \"\"\"\n    z = ZipFile(path_to_zip, 'r')\n    z.extractall(output_directory)\n    z.close()", "title": ""}
{"_id": "d3164", "text": "def _single_page_pdf(page):\n    \"\"\"Construct a single page PDF from the provided page in memory\"\"\"\n    pdf = Pdf.new()\n    pdf.pages.append(page)\n    bio = BytesIO()\n    pdf.save(bio)\n    bio.seek(0)\n    return bio.read()", "title": ""}
{"_id": "d3165", "text": "def _basic_field_data(field, obj):\n    \"\"\"Returns ``obj.field`` data as a dict\"\"\"\n    value = field.value_from_object(obj)\n    return {Field.TYPE: FieldType.VAL, Field.VALUE: value}", "title": ""}
{"_id": "d3166", "text": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d3167", "text": "def get_remote_content(filepath):\n        \"\"\" A handy wrapper to get a remote file content \"\"\"\n        with hide('running'):\n            temp = BytesIO()\n            get(filepath, temp)\n            content = temp.getvalue().decode('utf-8')\n        return content.strip()", "title": ""}
{"_id": "d3168", "text": "def random_choice(sequence):\n    \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n    return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)", "title": ""}
{"_id": "d3169", "text": "def translate_v3(vec, amount):\n    \"\"\"Return a new Vec3 that is translated version of vec.\"\"\"\n\n    return Vec3(vec.x+amount, vec.y+amount, vec.z+amount)", "title": ""}
{"_id": "d3170", "text": "def _parallel_compare_helper(class_obj, pairs, x, x_link=None):\n    \"\"\"Internal function to overcome pickling problem in python2.\"\"\"\n    return class_obj._compute(pairs, x, x_link)", "title": ""}
{"_id": "d3171", "text": "def imdecode(image_path):\n    \"\"\"Return BGR image read by opencv\"\"\"\n    import os\n    assert os.path.exists(image_path), image_path + ' not found'\n    im = cv2.imread(image_path)\n    return im", "title": ""}
{"_id": "d3172", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d3173", "text": "def get_keys_from_class(cc):\n    \"\"\"Return list of the key property names for a class \"\"\"\n    return [prop.name for prop in cc.properties.values() \\\n            if 'key' in prop.qualifiers]", "title": ""}
{"_id": "d3174", "text": "def resize(self, size):\n        \"\"\"Return a new Image instance with the given size.\"\"\"\n        return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))", "title": ""}
{"_id": "d3175", "text": "def datetime_created(self):\n        \"\"\"Returns file group's create aware *datetime* in UTC format.\"\"\"\n        if self.info().get('datetime_created'):\n            return dateutil.parser.parse(self.info()['datetime_created'])", "title": ""}
{"_id": "d3176", "text": "def context(self):\n        \"\"\" Convenient access to shared context \"\"\"\n        if self._context is not None:\n            return self._context\n        else:\n            logger.warning(\"Using shared context without a lock\")\n            return self._executor._shared_context", "title": ""}
{"_id": "d3177", "text": "def counter(items):\n    \"\"\"\n    Simplest required implementation of collections.Counter. Required as 2.6\n    does not have Counter in collections.\n    \"\"\"\n    results = {}\n    for item in items:\n        results[item] = results.get(item, 0) + 1\n    return results", "title": ""}
{"_id": "d3178", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d3179", "text": "def filter_bolts(table, header):\n  \"\"\" filter to keep bolts \"\"\"\n  bolts_info = []\n  for row in table:\n    if row[0] == 'bolt':\n      bolts_info.append(row)\n  return bolts_info, header", "title": ""}
{"_id": "d3180", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d3181", "text": "def pylint_raw(options):\n    \"\"\"\n    Use check_output to run pylint.\n    Because pylint changes the exit code based on the code score,\n    we have to wrap it in a try/except block.\n\n    :param options:\n    :return:\n    \"\"\"\n    command = ['pylint']\n    command.extend(options)\n\n    proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    outs, __ = proc.communicate()\n\n    return outs.decode()", "title": ""}
{"_id": "d3182", "text": "def print_param_values(self_):\n        \"\"\"Print the values of all this object's Parameters.\"\"\"\n        self = self_.self\n        for name,val in self.param.get_param_values():\n            print('%s.%s = %s' % (self.name,name,val))", "title": ""}
{"_id": "d3183", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d3184", "text": "def print_env_info(key, out=sys.stderr):\n    \"\"\"If given environment key is defined, print it out.\"\"\"\n    value = os.getenv(key)\n    if value is not None:\n        print(key, \"=\", repr(value), file=out)", "title": ""}
{"_id": "d3185", "text": "def random_letters(n):\n    \"\"\"\n    Generate a random string from a-zA-Z\n    :param n: length of the string\n    :return: the random string\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(n))", "title": ""}
{"_id": "d3186", "text": "def info(txt):\n    \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d3187", "text": "def GeneratePassphrase(length=20):\n  \"\"\"Create a 20 char passphrase with easily typeable chars.\"\"\"\n  valid_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  valid_chars += \"0123456789 ,-_&$#\"\n  return \"\".join(random.choice(valid_chars) for i in range(length))", "title": ""}
{"_id": "d3188", "text": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Like `pretty` but print to stdout.\n    \"\"\"\n    printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    sys.stdout.write(newline)\n    sys.stdout.flush()", "title": ""}
{"_id": "d3189", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d3190", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d3191", "text": "def pytest_runtest_logreport(self, report):\n        \"\"\"Store all test reports for evaluation on finish\"\"\"\n        rep = report\n        res = self.config.hook.pytest_report_teststatus(report=rep)\n        cat, letter, word = res\n        self.stats.setdefault(cat, []).append(rep)", "title": ""}
{"_id": "d3192", "text": "def prettyprint(d):\n        \"\"\"Print dicttree in Json-like format. keys are sorted\n        \"\"\"\n        print(json.dumps(d, sort_keys=True, \n                         indent=4, separators=(\",\" , \": \")))", "title": ""}
{"_id": "d3193", "text": "def generate_write_yaml_to_file(file_name):\n    \"\"\" generate a method to write the configuration in yaml to the method desired \"\"\"\n    def write_yaml(config):\n        with open(file_name, 'w+') as fh:\n            fh.write(yaml.dump(config))\n    return write_yaml", "title": ""}
{"_id": "d3194", "text": "def printdict(adict):\n    \"\"\"printdict\"\"\"\n    dlist = list(adict.keys())\n    dlist.sort()\n    for i in range(0, len(dlist)):\n        print(dlist[i], adict[dlist[i]])", "title": ""}
{"_id": "d3195", "text": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n    \"\"\"\n    Returns the last `n` rows in the table\n    \"\"\"\n    return fetch(dbconn, tablename, n, uuid, end=True)", "title": ""}
{"_id": "d3196", "text": "def show_progress(self):\n        \"\"\"If we are in a progress scope, and no log messages have been\n        shown, write out another '.'\"\"\"\n        if self.in_progress_hanging:\n            sys.stdout.write('.')\n            sys.stdout.flush()", "title": ""}
{"_id": "d3197", "text": "def get_tri_area(pts):\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d3198", "text": "def pprint(o, stream=None, indent=1, width=80, depth=None):\n    \"\"\"Pretty-print a Python o to a stream [default is sys.stdout].\"\"\"\n    printer = PrettyPrinter(\n        stream=stream, indent=indent, width=width, depth=depth)\n    printer.pprint(o)", "title": ""}
{"_id": "d3199", "text": "def call_out(command):\n  \"\"\"\n  Run the given command (with shell=False) and return a tuple of\n  (int returncode, str output). Strip the output of enclosing whitespace.\n  \"\"\"\n  # start external command process\n  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n  # get outputs\n  out, _ = p.communicate()\n\n  return p.returncode, out.strip()", "title": ""}
{"_id": "d3200", "text": "def get_table_columns(dbconn, tablename):\n    \"\"\"\n    Return a list of tuples specifying the column name and type\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n    info = cur.fetchall()\n    cols = [(i[1], i[2]) for i in info]\n    return cols", "title": ""}
{"_id": "d3201", "text": "def get(cls):\n    \"\"\"Subsystems used outside of any task.\"\"\"\n    return {\n      SourceRootConfig,\n      Reporting,\n      Reproducer,\n      RunTracker,\n      Changed,\n      BinaryUtil.Factory,\n      Subprocess.Factory\n    }", "title": ""}
{"_id": "d3202", "text": "def _stdout_raw(self, s):\n        \"\"\"Writes the string to stdout\"\"\"\n        print(s, end='', file=sys.stdout)\n        sys.stdout.flush()", "title": ""}
{"_id": "d3203", "text": "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()", "title": ""}
{"_id": "d3204", "text": "def ss(*args, **kwargs):\n    \"\"\"\n    exactly like s, but doesn't return variable names or file positions (useful for logging)\n\n    since -- 10-15-2015\n    return -- str\n    \"\"\"\n    if not args:\n        raise ValueError(\"you didn't pass any arguments to print out\")\n\n    with Reflect.context(args, **kwargs) as r:\n        instance = V_CLASS(r, stream, **kwargs)\n        return instance.value().strip()", "title": ""}
{"_id": "d3205", "text": "def _shape(self, df):\n        \"\"\"\n        Calculate table chape considering index levels.\n        \"\"\"\n\n        row, col = df.shape\n        return row + df.columns.nlevels, col + df.index.nlevels", "title": ""}
{"_id": "d3206", "text": "def get_encoding(binary):\n    \"\"\"Return the encoding type.\"\"\"\n\n    try:\n        from chardet import detect\n    except ImportError:\n        LOGGER.error(\"Please install the 'chardet' module\")\n        sys.exit(1)\n\n    encoding = detect(binary).get('encoding')\n\n    return 'iso-8859-1' if encoding == 'CP949' else encoding", "title": ""}
{"_id": "d3207", "text": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Like `pretty` but print to stdout.\n    \"\"\"\n    printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    sys.stdout.write(newline)\n    sys.stdout.flush()", "title": ""}
{"_id": "d3208", "text": "def _get_os_environ_dict(keys):\n  \"\"\"Return a dictionary of key/values from os.environ.\"\"\"\n  return {k: os.environ.get(k, _UNDEFINED) for k in keys}", "title": ""}
{"_id": "d3209", "text": "def to_json(data):\n    \"\"\"Return data as a JSON string.\"\"\"\n    return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)", "title": ""}
{"_id": "d3210", "text": "def getfield(f):\n    \"\"\"convert values from cgi.Field objects to plain values.\"\"\"\n    if isinstance(f, list):\n        return [getfield(x) for x in f]\n    else:\n        return f.value", "title": ""}
{"_id": "d3211", "text": "def time_string(seconds):\n    \"\"\"Returns time in seconds as a string formatted HHHH:MM:SS.\"\"\"\n    s = int(round(seconds))  # round to nearest second\n    h, s = divmod(s, 3600)  # get hours and remainder\n    m, s = divmod(s, 60)  # split remainder into minutes and seconds\n    return \"%2i:%02i:%02i\" % (h, m, s)", "title": ""}
{"_id": "d3212", "text": "def fields(self):\n        \"\"\"Returns the list of field names of the model.\"\"\"\n        return (self.attributes.values() + self.lists.values()\n                + self.references.values())", "title": ""}
{"_id": "d3213", "text": "def _normal_prompt(self):\n        \"\"\"\n        Flushes the prompt before requesting the input\n\n        :return: The command line\n        \"\"\"\n        sys.stdout.write(self.__get_ps1())\n        sys.stdout.flush()\n        return safe_input()", "title": ""}
{"_id": "d3214", "text": "def translate_index_to_position(self, index):\n        \"\"\"\n        Given an index for the text, return the corresponding (row, col) tuple.\n        (0-based. Returns (0, 0) for index=0.)\n        \"\"\"\n        # Find start of this line.\n        row, row_index = self._find_line_start_index(index)\n        col = index - row_index\n\n        return row, col", "title": ""}
{"_id": "d3215", "text": "def _set_property(self, val, *args):\n        \"\"\"Private method that sets the value currently of the property\"\"\"\n        val = UserClassAdapter._set_property(self, val, *args)\n        if val:\n            Adapter._set_property(self, val, *args)\n        return val", "title": ""}
{"_id": "d3216", "text": "def get_inputs_from_cm(index, cm):\n    \"\"\"Return indices of inputs to the node with the given index.\"\"\"\n    return tuple(i for i in range(cm.shape[0]) if cm[i][index])", "title": ""}
{"_id": "d3217", "text": "def metadata(self):\n        \"\"\"google.protobuf.Message: the current operation metadata.\"\"\"\n        if not self._operation.HasField(\"metadata\"):\n            return None\n\n        return protobuf_helpers.from_any_pb(\n            self._metadata_type, self._operation.metadata\n        )", "title": ""}
{"_id": "d3218", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d3219", "text": "def stop(pid):\n    \"\"\"Shut down a specific process.\n\n    Args:\n      pid: the pid of the process to shutdown.\n    \"\"\"\n    if psutil.pid_exists(pid):\n      try:\n        p = psutil.Process(pid)\n        p.kill()\n      except Exception:\n        pass", "title": ""}
{"_id": "d3220", "text": "def get_all_items(obj):\n    \"\"\"\n    dict.items() but with a separate row for each value in a MultiValueDict\n    \"\"\"\n    if hasattr(obj, 'getlist'):\n        items = []\n        for key in obj:\n            for value in obj.getlist(key):\n                items.append((key, value))\n        return items\n    else:\n        return obj.items()", "title": ""}
{"_id": "d3221", "text": "def download_json(local_filename, url, clobber=False):\n    \"\"\"Download the given JSON file, and pretty-print before we output it.\"\"\"\n    with open(local_filename, 'w') as json_file:\n        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))", "title": ""}
{"_id": "d3222", "text": "def get_size(objects):\n    \"\"\"Compute the total size of all elements in objects.\"\"\"\n    res = 0\n    for o in objects:\n        try:\n            res += _getsizeof(o)\n        except AttributeError:\n            print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n    return res", "title": ""}
{"_id": "d3223", "text": "def get_translucent_cmap(r, g, b):\n\n    class TranslucentCmap(BaseColormap):\n        glsl_map = \"\"\"\n        vec4 translucent_fire(float t) {{\n            return vec4({0}, {1}, {2}, t);\n        }}\n        \"\"\".format(r, g, b)\n\n    return TranslucentCmap()", "title": ""}
{"_id": "d3224", "text": "def get_qualified_name(_object):\n    \"\"\"Return the Fully Qualified Name from an instance or class.\"\"\"\n    module = _object.__module__\n    if hasattr(_object, '__name__'):\n        _class = _object.__name__\n\n    else:\n        _class = _object.__class__.__name__\n\n    return module + '.' + _class", "title": ""}
{"_id": "d3225", "text": "def execute(self, sql, params=None):\n        \"\"\"Just a pointer to engine.execute\n        \"\"\"\n        # wrap in a transaction to ensure things are committed\n        # https://github.com/smnorris/pgdata/issues/3\n        with self.engine.begin() as conn:\n            result = conn.execute(sql, params)\n        return result", "title": ""}
{"_id": "d3226", "text": "def get_qualified_name(_object):\n    \"\"\"Return the Fully Qualified Name from an instance or class.\"\"\"\n    module = _object.__module__\n    if hasattr(_object, '__name__'):\n        _class = _object.__name__\n\n    else:\n        _class = _object.__class__.__name__\n\n    return module + '.' + _class", "title": ""}
{"_id": "d3227", "text": "def set_ylimits(self, row, column, min=None, max=None):\n        \"\"\"Set y-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_ylimits(min, max)", "title": ""}
{"_id": "d3228", "text": "def _shutdown_transport(self):\n        \"\"\"Unwrap a Python 2.6 SSL socket, so we can call shutdown()\"\"\"\n        if self.sock is not None:\n            try:\n                unwrap = self.sock.unwrap\n            except AttributeError:\n                return\n            try:\n                self.sock = unwrap()\n            except ValueError:\n                # Failure within SSL might mean unwrap exists but socket is not\n                # deemed wrapped\n                pass", "title": ""}
{"_id": "d3229", "text": "def run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv. Return result code.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tresult_code = __import__('pytest').main()\n\t\t\tif result_code:\n\t\t\t\traise SystemExit(result_code)", "title": ""}
{"_id": "d3230", "text": "def each_img(dir_path):\n    \"\"\"\n    Iterates through each image in the given directory. (not recursive)\n    :param dir_path: Directory path where images files are present\n    :return: Iterator to iterate through image files\n    \"\"\"\n    for fname in os.listdir(dir_path):\n        if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'):\n            yield fname", "title": ""}
{"_id": "d3231", "text": "def now(timezone=None):\n    \"\"\"\n    Return a naive datetime object for the given ``timezone``. A ``timezone``\n    is any pytz- like or datetime.tzinfo-like timezone object. If no timezone\n    is given, then UTC is assumed.\n\n    This method is best used with pytz installed::\n\n        pip install pytz\n    \"\"\"\n    d = datetime.datetime.utcnow()\n    if not timezone:\n        return d\n\n    return to_timezone(d, timezone).replace(tzinfo=None)", "title": ""}
{"_id": "d3232", "text": "def clean_axis(axis):\n    \"\"\"Remove ticks, tick labels, and frame from axis\"\"\"\n    axis.get_xaxis().set_ticks([])\n    axis.get_yaxis().set_ticks([])\n    for spine in list(axis.spines.values()):\n        spine.set_visible(False)", "title": ""}
{"_id": "d3233", "text": "def get(self):\n        \"\"\"Get the highest priority Processing Block from the queue.\"\"\"\n        with self._mutex:\n            entry = self._queue.pop()\n            del self._block_map[entry[2]]\n            return entry[2]", "title": ""}
{"_id": "d3234", "text": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "title": ""}
{"_id": "d3235", "text": "async def delete(self):\n        \"\"\"\n        Delete task (in any state) permanently.\n\n        Returns `True` is task is deleted.\n        \"\"\"\n        the_tuple = await self.queue.delete(self.tube, self.task_id)\n\n        self.update_from_tuple(the_tuple)\n\n        return bool(self.state == DONE)", "title": ""}
{"_id": "d3236", "text": "def get_line_ending(line):\n    \"\"\"Return line ending.\"\"\"\n    non_whitespace_index = len(line.rstrip()) - len(line)\n    if not non_whitespace_index:\n        return ''\n    else:\n        return line[non_whitespace_index:]", "title": ""}
{"_id": "d3237", "text": "def rndstr(size=16):\n    \"\"\"\n    Returns a string of random ascii characters or digits\n\n    :param size: The length of the string\n    :return: string\n    \"\"\"\n    _basech = string.ascii_letters + string.digits\n    return \"\".join([rnd.choice(_basech) for _ in range(size)])", "title": ""}
{"_id": "d3238", "text": "def column(self):\n        \"\"\"\n        Returns a zero-based column number of the beginning of this range.\n        \"\"\"\n        line, column = self.source_buffer.decompose_position(self.begin_pos)\n        return column", "title": ""}
{"_id": "d3239", "text": "def min_values(args):\n    \"\"\" Return possible range for min function. \"\"\"\n    return Interval(min(x.low for x in args), min(x.high for x in args))", "title": ""}
{"_id": "d3240", "text": "def get_object_attrs(obj):\n    \"\"\"\n    Get the attributes of an object using dir.\n\n    This filters protected attributes\n    \"\"\"\n    attrs = [k for k in dir(obj) if not k.startswith('__')]\n    if not attrs:\n        attrs = dir(obj)\n    return attrs", "title": ""}
{"_id": "d3241", "text": "def zrank(self, name, value):\n        \"\"\"\n        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\n        \"\"\"\n        with self.pipe as pipe:\n            value = self.valueparse.encode(value)\n            return pipe.zrank(self.redis_key(name), value)", "title": ""}
{"_id": "d3242", "text": "def data_directory():\n    \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")", "title": ""}
{"_id": "d3243", "text": "def _readuntil(f, end=_TYPE_END):\n\t\"\"\"Helper function to read bytes until a certain end byte is hit\"\"\"\n\tbuf = bytearray()\n\tbyte = f.read(1)\n\twhile byte != end:\n\t\tif byte == b'':\n\t\t\traise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))\n\t\tbuf += byte\n\t\tbyte = f.read(1)\n\treturn buf", "title": ""}
{"_id": "d3244", "text": "def view_extreme_groups(token, dstore):\n    \"\"\"\n    Show the source groups contributing the most to the highest IML\n    \"\"\"\n    data = dstore['disagg_by_grp'].value\n    data.sort(order='extreme_poe')\n    return rst_table(data[::-1])", "title": ""}
{"_id": "d3245", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d3246", "text": "def str2int(string_with_int):\n    \"\"\" Collect digits from a string \"\"\"\n    return int(\"\".join([char for char in string_with_int if char in string.digits]) or 0)", "title": ""}
{"_id": "d3247", "text": "def read(fname):\n    \"\"\"Quick way to read a file content.\"\"\"\n    content = None\n    with open(os.path.join(here, fname)) as f:\n        content = f.read()\n    return content", "title": ""}
{"_id": "d3248", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d3249", "text": "def read_string_from_file(path, encoding=\"utf8\"):\n  \"\"\"\n  Read entire contents of file into a string.\n  \"\"\"\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value", "title": ""}
{"_id": "d3250", "text": "def OnRootView(self, event):\n        \"\"\"Reset view to the root of the tree\"\"\"\n        self.adapter, tree, rows = self.RootNode()\n        self.squareMap.SetModel(tree, self.adapter)\n        self.RecordHistory()\n        self.ConfigureViewTypeChoices()", "title": ""}
{"_id": "d3251", "text": "def read_folder(directory):\n    \"\"\"read text files in directory and returns them as array\n\n    Args:\n        directory: where the text files are\n\n    Returns:\n        Array of text\n    \"\"\"\n    res = []\n    for filename in os.listdir(directory):\n        with io.open(os.path.join(directory, filename), encoding=\"utf-8\") as f:\n            content = f.read()\n            res.append(content)\n    return res", "title": ""}
{"_id": "d3252", "text": "def size(dtype):\n  \"\"\"Returns the number of bytes to represent this `dtype`.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'size'):\n    return dtype.size\n  return np.dtype(dtype).itemsize", "title": ""}
{"_id": "d3253", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d3254", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x\"\"\"\n    i = bisect.bisect_left(a, x)\n    if i:\n        return a[i-1]\n    raise ValueError", "title": ""}
{"_id": "d3255", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d3256", "text": "def yticks(self):\n        \"\"\"Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular\"\"\"\n        return np.linspace(np.min(self[:, 0]), np.max(self[:, 0]), 4)", "title": ""}
{"_id": "d3257", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d3258", "text": "def _model_unique(ins):\n    \"\"\" Get unique constraints info\n\n    :type ins: sqlalchemy.orm.mapper.Mapper\n    :rtype: list[tuple[str]]\n    \"\"\"\n    unique = []\n    for t in ins.tables:\n        for c in t.constraints:\n            if isinstance(c, UniqueConstraint):\n                unique.append(tuple(col.key for col in c.columns))\n    return unique", "title": ""}
{"_id": "d3259", "text": "def read_string(buff, byteorder='big'):\n    \"\"\"Read a string from a file-like object.\"\"\"\n    length = read_numeric(USHORT, buff, byteorder)\n    return buff.read(length).decode('utf-8')", "title": ""}
{"_id": "d3260", "text": "def get_url_args(url):\n    \"\"\" Returns a dictionary from a URL params \"\"\"\n    url_data = urllib.parse.urlparse(url)\n    arg_dict = urllib.parse.parse_qs(url_data.query)\n    return arg_dict", "title": ""}
{"_id": "d3261", "text": "def ReadTif(tifFile):\n        \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n        img = Image.open(tifFile)\n        img = np.array(img)\n        return img", "title": ""}
{"_id": "d3262", "text": "def return_type(type_name, formatter=None):\n    \"\"\"Specify that this function returns a typed value.\n\n    Args:\n        type_name (str): A type name known to the global typedargs type system\n        formatter (str): An optional name of a formatting function specified\n            for the type given in type_name.\n    \"\"\"\n\n    def _returns(func):\n        annotated(func)\n        func.metadata.typed_returnvalue(type_name, formatter)\n        return func\n\n    return _returns", "title": ""}
{"_id": "d3263", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d3264", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d3265", "text": "def from_pb(cls, pb):\n        \"\"\"Instantiate the object from a protocol buffer.\n\n        Args:\n            pb (protobuf)\n\n        Save a reference to the protocol buffer on the object.\n        \"\"\"\n        obj = cls._from_pb(pb)\n        obj._pb = pb\n        return obj", "title": ""}
{"_id": "d3266", "text": "def extract_words(lines):\n    \"\"\"\n    Extract from the given iterable of lines the list of words.\n\n    :param lines: an iterable of lines;\n    :return: a generator of words of lines.\n    \"\"\"\n    for line in lines:\n        for word in re.findall(r\"\\w+\", line):\n            yield word", "title": ""}
{"_id": "d3267", "text": "def ReadTif(tifFile):\n        \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n        img = Image.open(tifFile)\n        img = np.array(img)\n        return img", "title": ""}
{"_id": "d3268", "text": "def _check_for_int(x):\n    \"\"\"\n    This is a compatibility function that takes a C{float} and converts it to an\n    C{int} if the values are equal.\n    \"\"\"\n    try:\n        y = int(x)\n    except (OverflowError, ValueError):\n        pass\n    else:\n        # There is no way in AMF0 to distinguish between integers and floats\n        if x == x and y == x:\n            return y\n\n    return x", "title": ""}
{"_id": "d3269", "text": "def r_num(obj):\n    \"\"\"Read list of numbers.\"\"\"\n    if isinstance(obj, (list, tuple)):\n        it = iter\n    else:\n        it = LinesIterator\n    dataset = Dataset([Dataset.FLOAT])\n    return dataset.load(it(obj))", "title": ""}
{"_id": "d3270", "text": "def process_module(self, module):\n        \"\"\"inspect the source file to find encoding problem\"\"\"\n        if module.file_encoding:\n            encoding = module.file_encoding\n        else:\n            encoding = \"ascii\"\n\n        with module.stream() as stream:\n            for lineno, line in enumerate(stream):\n                self._check_encoding(lineno + 1, line, encoding)", "title": ""}
{"_id": "d3271", "text": "def map_keys_deep(f, dct):\n    \"\"\"\n    Implementation of map that recurses. This tests the same keys at every level of dict and in lists\n    :param f: 2-ary function expecting a key and value and returns a modified key\n    :param dct: Dict for deep processing\n    :return: Modified dct with matching props mapped\n    \"\"\"\n    return _map_deep(lambda k, v: [f(k, v), v], dct)", "title": ""}
{"_id": "d3272", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d3273", "text": "def redirect_std():\n    \"\"\"\n    Connect stdin/stdout to controlling terminal even if the scripts input and output\n    were redirected. This is useful in utilities based on termenu.\n    \"\"\"\n    stdin = sys.stdin\n    stdout = sys.stdout\n    if not sys.stdin.isatty():\n        sys.stdin = open_raw(\"/dev/tty\", \"r\", 0)\n    if not sys.stdout.isatty():\n        sys.stdout = open_raw(\"/dev/tty\", \"w\", 0)\n\n    return stdin, stdout", "title": ""}
{"_id": "d3274", "text": "def _help():\n    \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n    statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n    print statement.strip()", "title": ""}
{"_id": "d3275", "text": "def __setitem__(self, field, value):\n        \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n        return self._client.hset(self.key_prefix, field, self._dumps(value))", "title": ""}
{"_id": "d3276", "text": "def send(message, request_context=None, binary=False):\n    \"\"\"Sends a message to websocket.\n\n    :param str message: data to send\n\n    :param request_context:\n\n    :raises IOError: If unable to send a message.\n    \"\"\"\n    if binary:\n        return uwsgi.websocket_send_binary(message, request_context)\n\n    return uwsgi.websocket_send(message, request_context)", "title": ""}
{"_id": "d3277", "text": "def __connect():\n    \"\"\"\n    Connect to a redis instance.\n    \"\"\"\n    global redis_instance\n    if use_tcp_socket:\n        redis_instance = redis.StrictRedis(host=hostname, port=port)\n    else:\n        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "title": ""}
{"_id": "d3278", "text": "def mark(self, n=1):\n        \"\"\"Mark the occurrence of a given number of events.\"\"\"\n        self.tick_if_necessary()\n        self.count += n\n        self.m1_rate.update(n)\n        self.m5_rate.update(n)\n        self.m15_rate.update(n)", "title": ""}
{"_id": "d3279", "text": "def exit(self):\n        \"\"\"\n        Closes the connection\n        \"\"\"\n        self.pubsub.unsubscribe()\n        self.client.connection_pool.disconnect()\n\n        logger.info(\"Connection to Redis closed\")", "title": ""}
{"_id": "d3280", "text": "def _post(self, url, params, uploads=None):\n        \"\"\" Wrapper method for POST calls. \"\"\"\n        self._call(self.POST, url, params, uploads)", "title": ""}
{"_id": "d3281", "text": "def prep_regex(patterns):\n    \"\"\"Compile regex patterns.\"\"\"\n\n    flags = 0 if Config.options.case_sensitive else re.I\n\n    return [re.compile(pattern, flags) for pattern in patterns]", "title": ""}
{"_id": "d3282", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d3283", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d3284", "text": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "title": ""}
{"_id": "d3285", "text": "def unmatched(match):\n    \"\"\"Return unmatched part of re.Match object.\"\"\"\n    start, end = match.span(0)\n    return match.string[:start]+match.string[end:]", "title": ""}
{"_id": "d3286", "text": "def seq():\n    \"\"\"\n    Counts up sequentially from a number based on the current time\n\n    :rtype int:\n    \"\"\"\n    current_frame     = inspect.currentframe().f_back\n    trace_string      = \"\"\n    while current_frame.f_back:\n      trace_string = trace_string + current_frame.f_back.f_code.co_name\n      current_frame = current_frame.f_back\n    return counter.get_from_trace(trace_string)", "title": ""}
{"_id": "d3287", "text": "def is_valid_email(email):\n    \"\"\"\n    Check if email is valid\n    \"\"\"\n    pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n    return bool(pattern.match(email))", "title": ""}
{"_id": "d3288", "text": "def _Members(self, group):\n    \"\"\"Unify members of a group and accounts with the group as primary gid.\"\"\"\n    group.members = set(group.members).union(self.gids.get(group.gid, []))\n    return group", "title": ""}
{"_id": "d3289", "text": "def version_triple(tag):\n    \"\"\"\n    returns: a triple of integers from a version tag\n    \"\"\"\n    groups = re.match(r'v?(\\d+)\\.(\\d+)\\.(\\d+)', tag).groups()\n    return tuple(int(n) for n in groups)", "title": ""}
{"_id": "d3290", "text": "def kill(self):\n        \"\"\"Kill the browser.\n\n        This is useful when the browser is stuck.\n        \"\"\"\n        if self.process:\n            self.process.kill()\n            self.process.wait()", "title": ""}
{"_id": "d3291", "text": "def data_directory():\n    \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")", "title": ""}
{"_id": "d3292", "text": "def kill_process_children(pid):\n    \"\"\"Find and kill child processes of a process.\n\n    :param pid: PID of parent process (process ID)\n    :return: Nothing\n    \"\"\"\n    if sys.platform == \"darwin\":\n        kill_process_children_osx(pid)\n    elif sys.platform == \"linux\":\n        kill_process_children_unix(pid)\n    else:\n        pass", "title": ""}
{"_id": "d3293", "text": "def f(x, a, c):\n    \"\"\" Objective function (sum of squared residuals) \"\"\"\n    v = g(x, a, c)\n    return v.dot(v)", "title": ""}
{"_id": "d3294", "text": "def stop(pid):\n    \"\"\"Shut down a specific process.\n\n    Args:\n      pid: the pid of the process to shutdown.\n    \"\"\"\n    if psutil.pid_exists(pid):\n      try:\n        p = psutil.Process(pid)\n        p.kill()\n      except Exception:\n        pass", "title": ""}
{"_id": "d3295", "text": "def clean():\n    \"\"\"clean - remove build artifacts.\"\"\"\n    run('rm -rf build/')\n    run('rm -rf dist/')\n    run('rm -rf puzzle.egg-info')\n    run('find . -name __pycache__ -delete')\n    run('find . -name *.pyc -delete')\n    run('find . -name *.pyo -delete')\n    run('find . -name *~ -delete')\n\n    log.info('cleaned up')", "title": ""}
{"_id": "d3296", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d3297", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d3298", "text": "def check_version():\n    \"\"\"Sanity check version information for corrupt virtualenv symlinks\n    \"\"\"\n    if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]:\n        return\n\n    sys.exit(\n        ansi.error() + ' your virtual env points to the wrong python version. '\n                       'This is likely because you used a python installer that clobbered '\n                       'the system installation, which breaks virtualenv creation. '\n                       'To fix, check this symlink, and delete the installation of python '\n                       'that it is brokenly pointing to, then delete the virtual env itself '\n                       'and rerun lore install: ' + os.linesep + os.linesep + BIN_PYTHON +\n        os.linesep\n    )", "title": ""}
{"_id": "d3299", "text": "def _remove_none_values(dictionary):\n    \"\"\" Remove dictionary keys whose value is None \"\"\"\n    return list(map(dictionary.pop,\n                    [i for i in dictionary if dictionary[i] is None]))", "title": ""}
{"_id": "d3300", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d3301", "text": "def CleanseComments(line):\n  \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n  Args:\n    line: A line of C++ source.\n\n  Returns:\n    The line with single-line comments removed.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1 and not IsCppString(line[:commentpos]):\n    line = line[:commentpos].rstrip()\n  # get rid of /* ... */\n  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "title": ""}
{"_id": "d3302", "text": "def join(self, room):\n        \"\"\"Lets a user join a room on a specific Namespace.\"\"\"\n        self.socket.rooms.add(self._get_room_name(room))", "title": ""}
{"_id": "d3303", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d3304", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d3305", "text": "def _remove_duplicate_files(xs):\n    \"\"\"Remove files specified multiple times in a list.\n    \"\"\"\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", "title": ""}
{"_id": "d3306", "text": "def on_error(e):  # pragma: no cover\n    \"\"\"Error handler\n\n    RuntimeError or ValueError exceptions raised by commands will be handled\n    by this function.\n    \"\"\"\n    exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'}\n    sys.stderr.write('{}: {}\\n'.format(exname[e.__class__.__name__], str(e)))\n    sys.stderr.write('See file slam_error.log for additional details.\\n')\n    sys.exit(1)", "title": ""}
{"_id": "d3307", "text": "def _delete_local(self, filename):\n        \"\"\"Deletes the specified file from the local filesystem.\"\"\"\n\n        if os.path.exists(filename):\n            os.remove(filename)", "title": ""}
{"_id": "d3308", "text": "def __copy__(self):\n        \"\"\"A magic method to implement shallow copy behavior.\"\"\"\n        return self.__class__.load(self.dump(), context=self.context)", "title": ""}
{"_id": "d3309", "text": "def PopTask(self):\n    \"\"\"Retrieves and removes the first task from the heap.\n\n    Returns:\n      Task: the task or None if the heap is empty.\n    \"\"\"\n    try:\n      _, task = heapq.heappop(self._heap)\n\n    except IndexError:\n      return None\n    self._task_identifiers.remove(task.identifier)\n    return task", "title": ""}
{"_id": "d3310", "text": "def _curve(x1, y1, x2, y2, hunit = HUNIT, vunit = VUNIT):\n    \"\"\"\n    Return a PyX curved path from (x1, y1) to (x2, y2),\n    such that the slope at either end is zero.\n    \"\"\"\n    ax1, ax2, axm = x1 * hunit, x2 * hunit, (x1 + x2) * hunit / 2\n    ay1, ay2 = y1 * vunit, y2 * vunit\n    return pyx.path.curve(ax1, ay1, axm, ay1, axm, ay2, ax2, ay2)", "title": ""}
{"_id": "d3311", "text": "def drop_bad_characters(text):\n    \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n    also any whitespace characters that aren't space.\n\n    :arg str text: the text to fix\n\n    :returns: text with all bad characters dropped\n\n    \"\"\"\n    # Strip all non-ascii and non-printable characters\n    text = ''.join([c for c in text if c in ALLOWED_CHARS])\n    return text", "title": ""}
{"_id": "d3312", "text": "def once(func):\n    \"\"\"Runs a thing once and once only.\"\"\"\n    lock = threading.Lock()\n\n    def new_func(*args, **kwargs):\n        if new_func.called:\n            return\n        with lock:\n            if new_func.called:\n                return\n            rv = func(*args, **kwargs)\n            new_func.called = True\n            return rv\n\n    new_func = update_wrapper(new_func, func)\n    new_func.called = False\n    return new_func", "title": ""}
{"_id": "d3313", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d3314", "text": "def unique(iterable):\n    \"\"\" Returns a list copy in which each item occurs only once (in-order).\n    \"\"\"\n    seen = set()\n    return [x for x in iterable if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d3315", "text": "def union_overlapping(intervals):\n    \"\"\"Union any overlapping intervals in the given set.\"\"\"\n    disjoint_intervals = []\n\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\n    return disjoint_intervals", "title": ""}
{"_id": "d3316", "text": "def _generate_phrases(self, sentences):\n        \"\"\"Method to generate contender phrases given the sentences of the text\n        document.\n\n        :param sentences: List of strings where each string represents a\n                          sentence which forms the text.\n        :return: Set of string tuples where each tuple is a collection\n                 of words forming a contender phrase.\n        \"\"\"\n        phrase_list = set()\n        # Create contender phrases from sentences.\n        for sentence in sentences:\n            word_list = [word.lower() for word in wordpunct_tokenize(sentence)]\n            phrase_list.update(self._get_phrase_list_from_words(word_list))\n        return phrase_list", "title": ""}
{"_id": "d3317", "text": "def unapostrophe(text):\n    \"\"\"Strip apostrophe and 's' from the end of a string.\"\"\"\n    text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)\n    return text", "title": ""}
{"_id": "d3318", "text": "def indentsize(line):\n    \"\"\"Return the indent size, in spaces, at the start of a line of text.\"\"\"\n    expline = string.expandtabs(line)\n    return len(expline) - len(string.lstrip(expline))", "title": ""}
{"_id": "d3319", "text": "def _do_remove_prefix(name):\n    \"\"\"Strip the possible prefix 'Table: ' from a table name.\"\"\"\n    res = name\n    if isinstance(res, str):\n        if (res.find('Table: ') == 0):\n            res = res.replace('Table: ', '', 1)\n    return res", "title": ""}
{"_id": "d3320", "text": "def distinct(l):\n    \"\"\"\n    Return a list where the duplicates have been removed.\n\n    Args:\n        l (list): the list to filter.\n\n    Returns:\n        list: the same list without duplicates.\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return (_ for _ in l if not (_ in seen or seen_add(_)))", "title": ""}
{"_id": "d3321", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d3322", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d3323", "text": "def fixpath(path):\n    \"\"\"Uniformly format a path.\"\"\"\n    return os.path.normpath(os.path.realpath(os.path.expanduser(path)))", "title": ""}
{"_id": "d3324", "text": "def drop_trailing_zeros_decimal(num):\n    \"\"\" Drops the trailinz zeros from decimal value.\n        Returns a string\n    \"\"\"\n    out = str(num)\n    return out.rstrip('0').rstrip('.') if '.' in out else out", "title": ""}
{"_id": "d3325", "text": "def symlink(source, destination):\n    \"\"\"Create a symbolic link\"\"\"\n    log(\"Symlinking {} as {}\".format(source, destination))\n    cmd = [\n        'ln',\n        '-sf',\n        source,\n        destination,\n    ]\n    subprocess.check_call(cmd)", "title": ""}
{"_id": "d3326", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d3327", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d3328", "text": "def conf(self):\n        \"\"\"Generate the Sphinx `conf.py` configuration file\n\n        Returns:\n            (str): the contents of the `conf.py` file.\n        \"\"\"\n        return self.env.get_template('conf.py.j2').render(\n            metadata=self.metadata,\n            package=self.package)", "title": ""}
{"_id": "d3329", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d3330", "text": "def render_to_json(templates, context, request):\n    \"\"\"\n    Generate a JSON HttpResponse with rendered template HTML.\n    \"\"\"\n    html = render_to_string(\n        templates,\n        context=context,\n        request=request\n    )\n    _json = json.dumps({\n        \"html\": html\n    })\n    return HttpResponse(_json)", "title": ""}
{"_id": "d3331", "text": "def to_unicode_repr( _letter ):\n    \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n        in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n    # Python 2-3 compatible\n    return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"", "title": ""}
{"_id": "d3332", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d3333", "text": "def join_cols(cols):\n    \"\"\"Join list of columns into a string for a SQL query\"\"\"\n    return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols", "title": ""}
{"_id": "d3334", "text": "def to_snake_case(name):\n    \"\"\" Given a name in camelCase return in snake_case \"\"\"\n    s1 = FIRST_CAP_REGEX.sub(r'\\1_\\2', name)\n    return ALL_CAP_REGEX.sub(r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d3335", "text": "def initialize_api(flask_app):\n    \"\"\"Initialize an API.\"\"\"\n    if not flask_restplus:\n        return\n\n    api = flask_restplus.Api(version=\"1.0\", title=\"My Example API\")\n    api.add_resource(HelloWorld, \"/hello\")\n\n    blueprint = flask.Blueprint(\"api\", __name__, url_prefix=\"/api\")\n    api.init_app(blueprint)\n    flask_app.register_blueprint(blueprint)", "title": ""}
{"_id": "d3336", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d3337", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d3338", "text": "def _replace_token_range(tokens, start, end, replacement):\n    \"\"\"For a range indicated from start to end, replace with replacement.\"\"\"\n    tokens = tokens[:start] + replacement + tokens[end:]\n    return tokens", "title": ""}
{"_id": "d3339", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d3340", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d3341", "text": "def specialRound(number, rounding):\n    \"\"\"A method used to round a number in the way that UsefulUtils rounds.\"\"\"\n    temp = 0\n    if rounding == 0:\n        temp = number\n    else:\n        temp =  round(number, rounding)\n    if temp % 1 == 0:\n        return int(temp)\n    else:\n        return float(temp)", "title": ""}
{"_id": "d3342", "text": "def requests_request(method, url, **kwargs):\n    \"\"\"Requests-mock requests.request wrapper.\"\"\"\n    session = local_sessions.session\n    response = session.request(method=method, url=url, **kwargs)\n    session.close()\n    return response", "title": ""}
{"_id": "d3343", "text": "def unique(self, name):\n    \"\"\"Make a variable name unique by appending a number if needed.\"\"\"\n    # Make sure the name is valid\n    name = self.valid(name)\n    # Make sure it's not too long\n    name = self.trim(name)\n    # Now make sure it's unique\n    unique_name = name\n    i = 2\n    while unique_name in self.names:\n      unique_name = name + str(i)\n      i += 1\n    self.names.add(unique_name)\n    return unique_name", "title": ""}
{"_id": "d3344", "text": "def auth_request(self, url, headers, body):\n        \"\"\"Perform auth request for token.\"\"\"\n\n        return self.req.post(url, headers, body=body)", "title": ""}
{"_id": "d3345", "text": "def check_type_and_size_of_param_list(param_list, expected_length):\n    \"\"\"\n    Ensure that param_list is a list with the expected length. Raises a helpful\n    ValueError if this is not the case.\n    \"\"\"\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\n    return None", "title": ""}
{"_id": "d3346", "text": "def _request_limit_reached(exception):\n    \"\"\" Checks if exception was raised because of too many executed requests. (This is a temporal solution and\n    will be changed in later package versions.)\n\n    :param exception: Exception raised during download\n    :type exception: Exception\n    :return: True if exception is caused because too many requests were executed at once and False otherwise\n    :rtype: bool\n    \"\"\"\n    return isinstance(exception, requests.HTTPError) and \\\n        exception.response.status_code == requests.status_codes.codes.TOO_MANY_REQUESTS", "title": ""}
{"_id": "d3347", "text": "def is_float_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy float array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy float array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.floating)", "title": ""}
{"_id": "d3348", "text": "def dict_to_querystring(dictionary):\n    \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\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]", "title": ""}
{"_id": "d3349", "text": "def init_rotating_logger(level, logfile, max_files, max_bytes):\n  \"\"\"Initializes a rotating logger\n\n  It also makes sure that any StreamHandler is removed, so as to avoid stdout/stderr\n  constipation issues\n  \"\"\"\n  logging.basicConfig()\n\n  root_logger = logging.getLogger()\n  log_format = \"[%(asctime)s] [%(levelname)s] %(filename)s: %(message)s\"\n\n  root_logger.setLevel(level)\n  handler = RotatingFileHandler(logfile, maxBytes=max_bytes, backupCount=max_files)\n  handler.setFormatter(logging.Formatter(fmt=log_format, datefmt=date_format))\n  root_logger.addHandler(handler)\n\n  for handler in root_logger.handlers:\n    root_logger.debug(\"Associated handlers - \" + str(handler))\n    if isinstance(handler, logging.StreamHandler):\n      root_logger.debug(\"Removing StreamHandler: \" + str(handler))\n      root_logger.handlers.remove(handler)", "title": ""}
{"_id": "d3350", "text": "def _log_disconnect(self):\n        \"\"\" Decrement connection count \"\"\"\n        if self.logged:\n            self.server.stats.connectionClosed()\n            self.logged = False", "title": ""}
{"_id": "d3351", "text": "def display_len(text):\n    \"\"\"\n    Get the display length of a string. This can differ from the character\n    length if the string contains wide characters.\n    \"\"\"\n    text = unicodedata.normalize('NFD', text)\n    return sum(char_width(char) for char in text)", "title": ""}
{"_id": "d3352", "text": "def download_sdk(url):\n    \"\"\"Downloads the SDK and returns a file-like object for the zip content.\"\"\"\n    r = requests.get(url)\n    r.raise_for_status()\n    return StringIO(r.content)", "title": ""}
{"_id": "d3353", "text": "def merge_dict(data, *args):\n    \"\"\"Merge any number of dictionaries\n    \"\"\"\n    results = {}\n    for current in (data,) + args:\n        results.update(current)\n    return results", "title": ""}
{"_id": "d3354", "text": "def normalise_string(string):\n    \"\"\" Strips trailing whitespace from string, lowercases it and replaces\n        spaces with underscores\n    \"\"\"\n    string = (string.strip()).lower()\n    return re.sub(r'\\W+', '_', string)", "title": ""}
{"_id": "d3355", "text": "def gmove(pattern, destination):\n    \"\"\"Move all file found by glob.glob(pattern) to destination directory.\n\n    Args:\n        pattern (str): Glob pattern\n        destination (str): Path to the destination directory.\n\n    Returns:\n        bool: True if the operation is successful, False otherwise.\n    \"\"\"\n    for item in glob.glob(pattern):\n        if not move(item, destination):\n            return False\n    return True", "title": ""}
{"_id": "d3356", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d3357", "text": "def ensure_hbounds(self):\n        \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "title": ""}
{"_id": "d3358", "text": "def url_encode(url):\n    \"\"\"\n    Convert special characters using %xx escape.\n\n    :param url: str\n    :return: str - encoded url\n    \"\"\"\n    if isinstance(url, text_type):\n        url = url.encode('utf8')\n    return quote(url, ':/%?&=')", "title": ""}
{"_id": "d3359", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d3360", "text": "def _normalize_abmn(abmn):\n    \"\"\"return a normalized version of abmn\n    \"\"\"\n    abmn_2d = np.atleast_2d(abmn)\n    abmn_normalized = np.hstack((\n        np.sort(abmn_2d[:, 0:2], axis=1),\n        np.sort(abmn_2d[:, 2:4], axis=1),\n    ))\n    return abmn_normalized", "title": ""}
{"_id": "d3361", "text": "def resize_image_to_fit_width(image, dest_w):\n    \"\"\"\n    Resize and image to fit the passed in width, keeping the aspect ratio the same\n\n    :param image: PIL.Image\n    :param dest_w: The desired width\n    \"\"\"\n    scale_factor = dest_w / image.size[0]\n    dest_h = image.size[1] * scale_factor\n    \n    scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)\n\n    return scaled_image", "title": ""}
{"_id": "d3362", "text": "def price_rounding(price, decimals=2):\n    \"\"\"Takes a decimal price and rounds to a number of decimal places\"\"\"\n    try:\n        exponent = D('.' + decimals * '0')\n    except InvalidOperation:\n        # Currencies with no decimal places, ex. JPY, HUF\n        exponent = D()\n    return price.quantize(exponent, rounding=ROUND_UP)", "title": ""}
{"_id": "d3363", "text": "def resize_image_to_fit_width(image, dest_w):\n    \"\"\"\n    Resize and image to fit the passed in width, keeping the aspect ratio the same\n\n    :param image: PIL.Image\n    :param dest_w: The desired width\n    \"\"\"\n    scale_factor = dest_w / image.size[0]\n    dest_h = image.size[1] * scale_factor\n    \n    scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)\n\n    return scaled_image", "title": ""}
{"_id": "d3364", "text": "def get_feature_order(dataset, features):\n    \"\"\" Returns a list with the order that features requested appear in\n    dataset \"\"\"\n    all_features = dataset.get_feature_names()\n\n    i = [all_features.index(f) for f in features]\n\n    return i", "title": ""}
{"_id": "d3365", "text": "def process_response(self, response):\n        \"\"\"\n        Load a JSON response.\n\n        :param Response response: The HTTP response.\n        :return dict: The JSON-loaded content.\n        \"\"\"\n        if response.status_code != 200:\n            raise TwilioException('Unable to fetch page', response)\n\n        return json.loads(response.text)", "title": ""}
{"_id": "d3366", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d3367", "text": "def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE,\ncontent=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for forbidden access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=403)", "title": ""}
{"_id": "d3368", "text": "def run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv. Return result code.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tresult_code = __import__('pytest').main()\n\t\t\tif result_code:\n\t\t\t\traise SystemExit(result_code)", "title": ""}
{"_id": "d3369", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d3370", "text": "def encode_dataset(dataset, vocabulary):\n  \"\"\"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\n  \"\"\"\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)", "title": ""}
{"_id": "d3371", "text": "def __get__(self, obj, objtype):\n        if not self.is_method:\n            self.is_method = True\n        \"\"\"Support instance methods.\"\"\"\n        return functools.partial(self.__call__, obj)", "title": ""}
{"_id": "d3372", "text": "def matrixTimesVector(MM, aa):\n    \"\"\"\n\n    :param MM: A matrix of size 3x3\n    :param aa: A vector of size 3\n    :return: A vector of size 3 which is the product of the matrix by the vector\n    \"\"\"\n    bb = np.zeros(3, np.float)\n    for ii in range(3):\n        bb[ii] = np.sum(MM[ii, :] * aa)\n    return bb", "title": ""}
{"_id": "d3373", "text": "def get_own_ip():\n    \"\"\"Get the host's ip number.\n    \"\"\"\n    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    try:\n        sock.connect((\"8.8.8.8\", 80))\n    except socket.gaierror:\n        ip_ = \"127.0.0.1\"\n    else:\n        ip_ = sock.getsockname()[0]\n    finally:\n        sock.close()\n    return ip_", "title": ""}
{"_id": "d3374", "text": "def execute_only_once():\n    \"\"\"\n    Each called in the code to this function is guaranteed to return True the\n    first time and False afterwards.\n\n    Returns:\n        bool: whether this is the first time this function gets called from this line of code.\n\n    Example:\n        .. code-block:: python\n\n            if execute_only_once():\n                # do something only once\n    \"\"\"\n    f = inspect.currentframe().f_back\n    ident = (f.f_code.co_filename, f.f_lineno)\n    if ident in _EXECUTE_HISTORY:\n        return False\n    _EXECUTE_HISTORY.add(ident)\n    return True", "title": ""}
{"_id": "d3375", "text": "def where_is(strings, pattern, n=1, lookup_func=re.match):\n    \"\"\"Return index of the nth match found of pattern in strings\n\n    Parameters\n    ----------\n    strings: list of str\n        List of strings\n\n    pattern: str\n        Pattern to be matched\n\n    nth: int\n        Number of times the match must happen to return the item index.\n\n    lookup_func: callable\n        Function to match each item in strings to the pattern, e.g., re.match or re.search.\n\n    Returns\n    -------\n    index: int\n        Index of the nth item that matches the pattern.\n        If there are no n matches will return -1\n    \"\"\"\n    count = 0\n    for idx, item in enumerate(strings):\n        if lookup_func(pattern, item):\n            count += 1\n            if count == n:\n                return idx\n    return -1", "title": ""}
{"_id": "d3376", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d3377", "text": "def conv_dict(self):\n        \"\"\"dictionary of conversion\"\"\"\n        return dict(integer=self.integer, real=self.real, no_type=self.no_type)", "title": ""}
{"_id": "d3378", "text": "def sem(inlist):\n    \"\"\"\nReturns the estimated standard error of the mean (sx-bar) of the\nvalues in the passed list.  sem = stdev / sqrt(n)\n\nUsage:   lsem(inlist)\n\"\"\"\n    sd = stdev(inlist)\n    n = len(inlist)\n    return sd / math.sqrt(n)", "title": ""}
{"_id": "d3379", "text": "def unwind(self):\n        \"\"\" Get a list of all ancestors in descending order of level, including a new instance  of self\n        \"\"\"\n        return [ QuadKey(self.key[:l+1]) for l in reversed(range(len(self.key))) ]", "title": ""}
{"_id": "d3380", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d3381", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d3382", "text": "def polyline(self, arr):\n        \"\"\"Draw a set of lines\"\"\"\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])", "title": ""}
{"_id": "d3383", "text": "def series_index(self, series):\n        \"\"\"\n        Return the integer index of *series* in this sequence.\n        \"\"\"\n        for idx, s in enumerate(self):\n            if series is s:\n                return idx\n        raise ValueError('series not in chart data object')", "title": ""}
{"_id": "d3384", "text": "def make_post_request(self, url, auth, json_payload):\n        \"\"\"This function executes the request with the provided\n        json payload and return the json response\"\"\"\n        response = requests.post(url, auth=auth, json=json_payload)\n        return response.json()", "title": ""}
{"_id": "d3385", "text": "def bisect_index(a, x):\n    \"\"\" Find the leftmost index of an element in a list using binary search.\n\n    Parameters\n    ----------\n    a: list\n        A sorted list.\n    x: arbitrary\n        The element.\n\n    Returns\n    -------\n    int\n        The index.\n\n    \"\"\"\n    i = bisect.bisect_left(a, x)\n    if i != len(a) and a[i] == x:\n        return i\n    raise ValueError", "title": ""}
{"_id": "d3386", "text": "def prettyprint(d):\n        \"\"\"Print dicttree in Json-like format. keys are sorted\n        \"\"\"\n        print(json.dumps(d, sort_keys=True, \n                         indent=4, separators=(\",\" , \": \")))", "title": ""}
{"_id": "d3387", "text": "def print(*a):\n    \"\"\" print just one that returns what you give it instead of None \"\"\"\n    try:\n        _print(*a)\n        return a[0] if len(a) == 1 else a\n    except:\n        _print(*a)", "title": ""}
{"_id": "d3388", "text": "def clear(self):\n        \"\"\"\n        Clear screen and go to 0,0\n        \"\"\"\n        # Erase current output first.\n        self.erase()\n\n        # Send \"Erase Screen\" command and go to (0, 0).\n        output = self.output\n\n        output.erase_screen()\n        output.cursor_goto(0, 0)\n        output.flush()\n\n        self.request_absolute_cursor_position()", "title": ""}
{"_id": "d3389", "text": "def _days_in_month(date):\n    \"\"\"The number of days in the month of the given 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", "title": ""}
{"_id": "d3390", "text": "def pprint(self, seconds):\n        \"\"\"\n        Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n        :param seconds:  The time in seconds.\n        \"\"\"\n        return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))", "title": ""}
{"_id": "d3391", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d3392", "text": "def error(*args):\n    \"\"\"Display error message via stderr or GUI.\"\"\"\n    if sys.stdin.isatty():\n        print('ERROR:', *args, file=sys.stderr)\n    else:\n        notify_error(*args)", "title": ""}
{"_id": "d3393", "text": "def roc_auc(y_true, y_score):\n    \"\"\"\n    Returns are under the ROC curve\n    \"\"\"\n    notnull = ~np.isnan(y_true)\n    fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true[notnull], y_score[notnull])\n    return sklearn.metrics.auc(fpr, tpr)", "title": ""}
{"_id": "d3394", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d3395", "text": "def rotateImage(image, angle):\n    \"\"\"\n        rotates a 2d array to a multiple of 90 deg.\n        0 = default\n        1 = 90 deg. cw\n        2 = 180 deg.\n        3 = 90 deg. ccw\n    \"\"\"\n    image = [list(row) for row in image]\n\n    for n in range(angle % 4):\n        image = list(zip(*image[::-1]))\n\n    return image", "title": ""}
{"_id": "d3396", "text": "def printc(cls, txt, color=colors.red):\n        \"\"\"Print in color.\"\"\"\n        print(cls.color_txt(txt, color))", "title": ""}
{"_id": "d3397", "text": "def get_rounded(self, digits):\n        \"\"\" Return a vector with the elements rounded to the given number of digits. \"\"\"\n        result = self.copy()\n        result.round(digits)\n        return result", "title": ""}
{"_id": "d3398", "text": "def clean_error(err):\n    \"\"\"\n    Take stderr bytes returned from MicroPython and attempt to create a\n    non-verbose error message.\n    \"\"\"\n    if err:\n        decoded = err.decode('utf-8')\n        try:\n            return decoded.split('\\r\\n')[-2]\n        except Exception:\n            return decoded\n    return 'There was an error.'", "title": ""}
{"_id": "d3399", "text": "def parse_response(self, resp):\n        \"\"\"\n        Parse the xmlrpc response.\n        \"\"\"\n        p, u = self.getparser()\n        p.feed(resp.content)\n        p.close()\n        return u.close()", "title": ""}
{"_id": "d3400", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d3401", "text": "def setup_detect_python2():\n        \"\"\"\n        Call this before using the refactoring tools to create them on demand\n        if needed.\n        \"\"\"\n        if None in [RTs._rt_py2_detect, RTs._rtp_py2_detect]:\n            RTs._rt_py2_detect = RefactoringTool(py2_detect_fixers)\n            RTs._rtp_py2_detect = RefactoringTool(py2_detect_fixers,\n                                                  {'print_function': True})", "title": ""}
{"_id": "d3402", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d3403", "text": "def s3(ctx, bucket_name, data_file, region):\n    \"\"\"Use the S3 SWAG backend.\"\"\"\n    if not ctx.data_file:\n        ctx.data_file = data_file\n\n    if not ctx.bucket_name:\n        ctx.bucket_name = bucket_name\n\n    if not ctx.region:\n        ctx.region = region\n\n    ctx.type = 's3'", "title": ""}
{"_id": "d3404", "text": "def select_fields_as_sql(self):\n        \"\"\"\n        Returns the selected fields or expressions as a SQL string.\n        \"\"\"\n        return comma_join(list(self._fields) + ['%s AS %s' % (v, k) for k, v in self._calculated_fields.items()])", "title": ""}
{"_id": "d3405", "text": "def kill_mprocess(process):\n    \"\"\"kill process\n    Args:\n        process - Popen object for process\n    \"\"\"\n    if process and proc_alive(process):\n        process.terminate()\n        process.communicate()\n    return not proc_alive(process)", "title": ""}
{"_id": "d3406", "text": "def sent2features(sentence, template):\n    \"\"\" extract features in a sentence\n\n    :type sentence: list of token, each token is a list of tag\n    \"\"\"\n    return [word2features(sentence, i, template) for i in range(len(sentence))]", "title": ""}
{"_id": "d3407", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d3408", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d3409", "text": "def write_image(filename, image):\n    \"\"\" Write image data to PNG, JPG file\n\n    :param filename: name of PNG or JPG file to write data to\n    :type filename: str\n    :param image: image data to write to file\n    :type image: numpy array\n    \"\"\"\n    data_format = get_data_format(filename)\n    if data_format is MimeType.JPG:\n        LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.')\n    return Image.fromarray(image).save(filename)", "title": ""}
{"_id": "d3410", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d3411", "text": "def plot_and_save(self, **kwargs):\n        \"\"\"Used when the plot method defined does not create a figure nor calls save_plot\n        Then the plot method has to use self.fig\"\"\"\n        self.fig = pyplot.figure()\n        self.plot()\n        self.axes = pyplot.gca()\n        self.save_plot(self.fig, self.axes, **kwargs)\n        pyplot.close(self.fig)", "title": ""}
{"_id": "d3412", "text": "def get(url):\n    \"\"\"Recieving the JSON file from uulm\"\"\"\n    response = urllib.request.urlopen(url)\n    data = response.read()\n    data = data.decode(\"utf-8\")\n    data = json.loads(data)\n    return data", "title": ""}
{"_id": "d3413", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d3414", "text": "def iterate_chunks(file, chunk_size):\n    \"\"\"\n    Iterate chunks of size chunk_size from a file-like object\n    \"\"\"\n    chunk = file.read(chunk_size)\n    while chunk:\n        yield chunk\n        chunk = file.read(chunk_size)", "title": ""}
{"_id": "d3415", "text": "def fig2x(figure, format):\n    \"\"\"Returns svg from matplotlib chart\"\"\"\n\n    # Save svg to file like object svg_io\n    io = StringIO()\n    figure.savefig(io, format=format)\n\n    # Rewind the file like object\n    io.seek(0)\n\n    data = io.getvalue()\n    io.close()\n\n    return data", "title": ""}
{"_id": "d3416", "text": "def clean_error(err):\n    \"\"\"\n    Take stderr bytes returned from MicroPython and attempt to create a\n    non-verbose error message.\n    \"\"\"\n    if err:\n        decoded = err.decode('utf-8')\n        try:\n            return decoded.split('\\r\\n')[-2]\n        except Exception:\n            return decoded\n    return 'There was an error.'", "title": ""}
{"_id": "d3417", "text": "def validate_string_list(lst):\n    \"\"\"Validate that the input is a list of strings.\n\n    Raises ValueError if not.\"\"\"\n    if not isinstance(lst, list):\n        raise ValueError('input %r must be a list' % lst)\n    for x in lst:\n        if not isinstance(x, basestring):\n            raise ValueError('element %r in list must be a string' % x)", "title": ""}
{"_id": "d3418", "text": "def cmd_reindex():\n    \"\"\"Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.\n\n    The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until\n    the rename succeeds.\n    \"\"\"\n    db = connect(args.database)\n    for idx in args.indexes:\n        pg_reindex(db, idx)", "title": ""}
{"_id": "d3419", "text": "def is_valid_folder(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.isdir(arg):\n        parser.error(\"The folder %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d3420", "text": "def unapostrophe(text):\n    \"\"\"Strip apostrophe and 's' from the end of a string.\"\"\"\n    text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)\n    return text", "title": ""}
{"_id": "d3421", "text": "def QA_util_datetime_to_strdate(dt):\n    \"\"\"\n    :param dt:  pythone datetime.datetime\n    :return:  1999-02-01 string type\n    \"\"\"\n    strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n    return strdate", "title": ""}
{"_id": "d3422", "text": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n    \"\"\"Clean a pandas dataframe by:\n        1. Filling empty values with Nan\n        2. Dropping columns with all empty values\n\n    Args:\n        df: Pandas DataFrame\n        fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n        drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n    Returns:\n        DataFrame: cleaned DataFrame\n\n    \"\"\"\n    if fill_nan:\n        df = df.fillna(value=np.nan)\n    if drop_empty_columns:\n        df = df.dropna(axis=1, how='all')\n    return df.sort_index()", "title": ""}
{"_id": "d3423", "text": "def extract(self):\n        \"\"\"\n        Creates a copy of this tabarray in the form of a numpy ndarray.\n\n        Useful if you want to do math on array elements, e.g. if you have a \n        subset of the columns that are all numerical, you can construct a \n        numerical matrix and do matrix operations.\n\n        \"\"\"\n        return np.vstack([self[r] for r in self.dtype.names]).T.squeeze()", "title": ""}
{"_id": "d3424", "text": "def delete_entry(self, key):\n        \"\"\"Delete an object from the redis table\"\"\"\n        pipe = self.client.pipeline()\n        pipe.srem(self.keys_container, key)\n        pipe.delete(key)\n        pipe.execute()", "title": ""}
{"_id": "d3425", "text": "def match_files(files, pattern: Pattern):\n    \"\"\"Yields file name if matches a regular expression pattern.\"\"\"\n\n    for name in files:\n        if re.match(pattern, name):\n            yield name", "title": ""}
{"_id": "d3426", "text": "def ma(self):\n        \"\"\"Represent data as a masked array.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n        inf and nan are filtered via :func:`numpy.isfinite`.\n        \"\"\"\n        a = self.array\n        return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))", "title": ""}
{"_id": "d3427", "text": "def _selectItem(self, index):\n        \"\"\"Select item in the list\n        \"\"\"\n        self._selectedIndex = index\n        self.setCurrentIndex(self.model().createIndex(index, 0))", "title": ""}
{"_id": "d3428", "text": "def remove_punctuation(text, exceptions=[]):\n    \"\"\"\n    Return a string with punctuation removed.\n\n    Parameters:\n        text (str): The text to remove punctuation from.\n        exceptions (list): List of symbols to keep in the given text.\n\n    Return:\n        str: The input text without the punctuation.\n    \"\"\"\n\n    all_but = [\n        r'\\w',\n        r'\\s'\n    ]\n\n    all_but.extend(exceptions)\n\n    pattern = '[^{}]'.format(''.join(all_but))\n\n    return re.sub(pattern, '', text)", "title": ""}
{"_id": "d3429", "text": "def percentile_index(a, q):\n    \"\"\"\n    Returns the index of the value at the Qth percentile in array a.\n    \"\"\"\n    return np.where(\n        a==np.percentile(a, q, interpolation='nearest')\n    )[0][0]", "title": ""}
{"_id": "d3430", "text": "def _clean_str(self, s):\n        \"\"\" Returns a lowercase string with punctuation and bad chars removed\n        :param s: string to clean\n        \"\"\"\n        return s.translate(str.maketrans('', '', punctuation)).replace('\\u200b', \" \").strip().lower()", "title": ""}
{"_id": "d3431", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d3432", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d3433", "text": "def _attach_files(filepaths, email_):\n    \"\"\"Take a list of filepaths and attach the files to a MIMEMultipart.\n\n    Args:\n        filepaths (list(str)): A list of filepaths.\n        email_ (email.MIMEMultipart): A MIMEMultipart email_.\n    \"\"\"\n    for filepath in filepaths:\n        base = os.path.basename(filepath)\n        with open(filepath, \"rb\") as file:\n            part = MIMEApplication(file.read(), Name=base)\n            part[\"Content-Disposition\"] = 'attachment; filename=\"%s\"' % base\n            email_.attach(part)", "title": ""}
{"_id": "d3434", "text": "def send(r, stream=False):\n    \"\"\"Just sends the request using its send method and returns its response.  \"\"\"\n    r.send(stream=stream)\n    return r.response", "title": ""}
{"_id": "d3435", "text": "def handle_data(self, data):\n        \"\"\"\n        Djeffify data between tags\n        \"\"\"\n        if data.strip():\n            data = djeffify_string(data)\n        self.djhtml += data", "title": ""}
{"_id": "d3436", "text": "def splitext_no_dot(filename):\n    \"\"\"\n    Wrap os.path.splitext to return the name and the extension\n    without the '.' (e.g., csv instead of .csv)\n    \"\"\"\n    name, ext = os.path.splitext(filename)\n    ext = ext.lower()\n    return name, ext.strip('.')", "title": ""}
{"_id": "d3437", "text": "def boolean(flag):\n    \"\"\"\n    Convert string in boolean\n    \"\"\"\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)", "title": ""}
{"_id": "d3438", "text": "def autoscan():\n    \"\"\"autoscan will check all of the serial ports to see if they have\n       a matching VID:PID for a MicroPython board.\n    \"\"\"\n    for port in serial.tools.list_ports.comports():\n        if is_micropython_usb_device(port):\n            connect_serial(port[0])", "title": ""}
{"_id": "d3439", "text": "def format_float(value): # not used\n    \"\"\"Modified form of the 'g' format specifier.\n    \"\"\"\n    string = \"{:g}\".format(value).replace(\"e+\", \"e\")\n    string = re.sub(\"e(-?)0*(\\d+)\", r\"e\\1\\2\", string)\n    return string", "title": ""}
{"_id": "d3440", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d3441", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d3442", "text": "def internal_reset(self):\n        \"\"\"\n        internal state reset.\n        used e.g. in unittests\n        \"\"\"\n        log.critical(\"PIA internal_reset()\")\n        self.empty_key_toggle = True\n        self.current_input_char = None\n        self.input_repead = 0", "title": ""}
{"_id": "d3443", "text": "def get_rounded(self, digits):\n        \"\"\" Return a vector with the elements rounded to the given number of digits. \"\"\"\n        result = self.copy()\n        result.round(digits)\n        return result", "title": ""}
{"_id": "d3444", "text": "def get_member(thing_obj, member_string):\n    \"\"\"Get a member from an object by (string) name\"\"\"\n    mems = {x[0]: x[1] for x in inspect.getmembers(thing_obj)}\n    if member_string in mems:\n        return mems[member_string]", "title": ""}
{"_id": "d3445", "text": "def _replace_service_arg(self, name, index, args):\n        \"\"\" Replace index in list with service \"\"\"\n        args[index] = self.get_instantiated_service(name)", "title": ""}
{"_id": "d3446", "text": "def isbinary(*args):\n    \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n    return all(map(lambda c: isnumber(c) or isbool(c), args))", "title": ""}
{"_id": "d3447", "text": "def _synced(method, self, args, kwargs):\n    \"\"\"Underlying synchronized wrapper.\"\"\"\n    with self._lock:\n        return method(*args, **kwargs)", "title": ""}
{"_id": "d3448", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d3449", "text": "def is_set(self, key):\n        \"\"\"Return True if variable is a set\"\"\"\n        data = self.model.get_data()\n        return isinstance(data[key], set)", "title": ""}
{"_id": "d3450", "text": "def dropna(self):\n        \"\"\"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.\n\n        \"\"\"\n        not_nas = [v.notna() for v in self.values]\n        and_filter = reduce(lambda x, y: x & y, not_nas)\n\n        return self[and_filter]", "title": ""}
{"_id": "d3451", "text": "def getdefaultencoding():\n    \"\"\"Return IPython's guess for the default encoding for bytes as text.\n\n    Asks for stdin.encoding first, to match the calling Terminal, but that\n    is often None for subprocesses.  Fall back on locale.getpreferredencoding()\n    which should be a sensible platform default (that respects LANG environment),\n    and finally to sys.getdefaultencoding() which is the most conservative option,\n    and usually ASCII.\n    \"\"\"\n    enc = get_stream_enc(sys.stdin)\n    if not enc or enc=='ascii':\n        try:\n            # There are reports of getpreferredencoding raising errors\n            # in some cases, which may well be fixed, but let's be conservative here.\n            enc = locale.getpreferredencoding()\n        except Exception:\n            pass\n    return enc or sys.getdefaultencoding()", "title": ""}
{"_id": "d3452", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d3453", "text": "def reset_default_logger():\n    \"\"\"\n    Resets the internal default logger to the initial configuration\n    \"\"\"\n    global logger\n    global _loglevel\n    global _logfile\n    global _formatter\n    _loglevel = logging.DEBUG\n    _logfile = None\n    _formatter = None\n    logger = setup_logger(name=LOGZERO_DEFAULT_LOGGER, logfile=_logfile, level=_loglevel, formatter=_formatter)", "title": ""}
{"_id": "d3454", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d3455", "text": "def discard(self, element):\n        \"\"\"Remove element from the RangeSet if it is a member.\n\n        If the element is not a member, do nothing.\n        \"\"\"\n        try:\n            i = int(element)\n            set.discard(self, i)\n        except ValueError:\n            pass", "title": ""}
{"_id": "d3456", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d3457", "text": "def _config_win32_domain(self, domain):\n        \"\"\"Configure a Domain registry entry.\"\"\"\n        # we call str() on domain to convert it from unicode to ascii\n        self.domain = dns.name.from_text(str(domain))", "title": ""}
{"_id": "d3458", "text": "def save_pdf(path):\n  \"\"\"\n  Saves a pdf of the current matplotlib figure.\n\n  :param path: str, filepath to save to\n  \"\"\"\n\n  pp = PdfPages(path)\n  pp.savefig(pyplot.gcf())\n  pp.close()", "title": ""}
{"_id": "d3459", "text": "def generate_id():\n    \"\"\"Generate new UUID\"\"\"\n    # TODO: Use six.string_type to Py3 compat\n    try:\n        return unicode(uuid1()).replace(u\"-\", u\"\")\n    except NameError:\n        return str(uuid1()).replace(u\"-\", u\"\")", "title": ""}
{"_id": "d3460", "text": "def _save_file(self, filename, contents):\n        \"\"\"write the html file contents to disk\"\"\"\n        with open(filename, 'w') as f:\n            f.write(contents)", "title": ""}
{"_id": "d3461", "text": "def is_set(self, key):\n        \"\"\"Return True if variable is a set\"\"\"\n        data = self.model.get_data()\n        return isinstance(data[key], set)", "title": ""}
{"_id": "d3462", "text": "def get_all_attributes(klass_or_instance):\n    \"\"\"Get all attribute members (attribute, property style method).\n    \"\"\"\n    pairs = list()\n    for attr, value in inspect.getmembers(\n            klass_or_instance, lambda x: not inspect.isroutine(x)):\n        if not (attr.startswith(\"__\") or attr.endswith(\"__\")):\n            pairs.append((attr, value))\n    return pairs", "title": ""}
{"_id": "d3463", "text": "def unique_everseen(seq):\n    \"\"\"Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d3464", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d3465", "text": "def traverse_setter(obj, attribute, value):\n    \"\"\"\n    Traverses the object and sets the supplied attribute on the\n    object. Supports Dimensioned and DimensionedPlot types.\n    \"\"\"\n    obj.traverse(lambda x: setattr(x, attribute, value))", "title": ""}
{"_id": "d3466", "text": "def is_valid_varname(varname):\n    \"\"\" Checks syntax and validity of a variable name \"\"\"\n    if not isinstance(varname, six.string_types):\n        return False\n    match_obj = re.match(varname_regex, varname)\n    valid_syntax = match_obj is not None\n    valid_name = not keyword.iskeyword(varname)\n    isvalid = valid_syntax and valid_name\n    return isvalid", "title": ""}
{"_id": "d3467", "text": "def setAutoRangeOn(self, axisNumber):\n        \"\"\" Sets the auto-range of the axis on.\n\n            :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).\n        \"\"\"\n        setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)", "title": ""}
{"_id": "d3468", "text": "def unique_element(ll):\n    \"\"\" returns unique elements from a list preserving the original order \"\"\"\n    seen = {}\n    result = []\n    for item in ll:\n        if item in seen:\n            continue\n        seen[item] = 1\n        result.append(item)\n    return result", "title": ""}
{"_id": "d3469", "text": "def wait_on_rate_limit(self, value):\n        \"\"\"Enable or disable automatic rate-limit handling.\"\"\"\n        check_type(value, bool, may_be_none=False)\n        self._wait_on_rate_limit = value", "title": ""}
{"_id": "d3470", "text": "def get_last(self, table=None):\n        \"\"\"Just the last entry.\"\"\"\n        if table is None: table = self.main_table\n        query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n        return self.own_cursor.execute(query).fetchone()", "title": ""}
{"_id": "d3471", "text": "def discard(self, element):\n        \"\"\"Remove element from the RangeSet if it is a member.\n\n        If the element is not a member, do nothing.\n        \"\"\"\n        try:\n            i = int(element)\n            set.discard(self, i)\n        except ValueError:\n            pass", "title": ""}
{"_id": "d3472", "text": "def _send_file(self, filename):\n        \"\"\"\n        Sends a file via FTP.\n        \"\"\"\n        # pylint: disable=E1101\n        ftp = ftplib.FTP(host=self.host)\n        ftp.login(user=self.user, passwd=self.password)\n        ftp.set_pasv(True)\n        ftp.storbinary(\"STOR %s\" % os.path.basename(filename),\n            file(filename, 'rb'))", "title": ""}
{"_id": "d3473", "text": "def get_trace_id_from_flask():\n    \"\"\"Get trace_id from flask request headers.\n\n    :rtype: str\n    :returns: TraceID in HTTP request headers.\n    \"\"\"\n    if flask is None or not flask.request:\n        return None\n\n    header = flask.request.headers.get(_FLASK_TRACE_HEADER)\n\n    if header is None:\n        return None\n\n    trace_id = header.split(\"/\", 1)[0]\n\n    return trace_id", "title": ""}
{"_id": "d3474", "text": "def send_photo(self, photo: str, caption: str=None, reply: Message=None, on_success: callable=None,\n                   reply_markup: botapi.ReplyMarkup=None):\n        \"\"\"\n        Send photo to this peer.\n        :param photo: File path to photo to send.\n        :param caption: Caption for photo\n        :param reply: Message object or message_id to reply to.\n        :param on_success: Callback to call when call is complete.\n\n        :type reply: int or Message\n        \"\"\"\n        self.twx.send_photo(peer=self, photo=photo, caption=caption, reply=reply, reply_markup=reply_markup,\n                            on_success=on_success)", "title": ""}
{"_id": "d3475", "text": "def sys_pipes_forever(encoding=_default_encoding):\n    \"\"\"Redirect all C output to sys.stdout/err\n    \n    This is not a context manager; it turns on C-forwarding permanently.\n    \"\"\"\n    global _mighty_wurlitzer\n    if _mighty_wurlitzer is None:\n        _mighty_wurlitzer = sys_pipes(encoding)\n    _mighty_wurlitzer.__enter__()", "title": ""}
{"_id": "d3476", "text": "def _check_for_errors(etree: ET.ElementTree):\n    \"\"\"Check AniDB response XML tree for errors.\"\"\"\n    if etree.getroot().tag == 'error':\n        raise APIError(etree.getroot().text)", "title": ""}
{"_id": "d3477", "text": "def previous_friday(dt):\n    \"\"\"\n    If holiday falls on Saturday or Sunday, use previous Friday instead.\n    \"\"\"\n    if dt.weekday() == 5:\n        return dt - timedelta(1)\n    elif dt.weekday() == 6:\n        return dt - timedelta(2)\n    return dt", "title": ""}
{"_id": "d3478", "text": "def save_model(self, request, obj, form, change):\n        \"\"\"\n        Set currently authenticated user as the author of the gallery.\n        \"\"\"\n        obj.author = request.user\n        obj.save()", "title": ""}
{"_id": "d3479", "text": "def set_position(self, x, y, width, height):\n        \"\"\"Set window top-left corner position and size\"\"\"\n        SetWindowPos(self._hwnd, None, x, y, width, height, ctypes.c_uint(0))", "title": ""}
{"_id": "d3480", "text": "def set_constraint_bound(self, name, value):\n        \"\"\"Set the upper bound of a constraint.\"\"\"\n        index = self._get_constraint_index(name)\n        self.upper_bounds[index] = value\n        self._reset_solution()", "title": ""}
{"_id": "d3481", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d3482", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d3483", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d3484", "text": "def set_axis_options(self, row, column, text):\n        \"\"\"Set additionnal options as plain text.\"\"\"\n\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_axis_options(text)", "title": ""}
{"_id": "d3485", "text": "def set_default(self, key, value):\n        \"\"\"Set the default value for this key.\n        Default only used when no value is provided by the user via\n        arg, config or env.\n        \"\"\"\n        k = self._real_key(key.lower())\n        self._defaults[k] = value", "title": ""}
{"_id": "d3486", "text": "def batchify(data, batch_size):\n    \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n    nbatch = data.shape[0] // batch_size\n    data = data[:nbatch * batch_size]\n    data = data.reshape((batch_size, nbatch)).T\n    return data", "title": ""}
{"_id": "d3487", "text": "def stringc(text, color):\n    \"\"\"\n    Return a string with terminal colors.\n    \"\"\"\n    if has_colors:\n        text = str(text)\n\n        return \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"\n    else:\n        return text", "title": ""}
{"_id": "d3488", "text": "def extent(self):\n        \"\"\"Helper for matplotlib imshow\"\"\"\n        return (\n            self.intervals[1].pix1 - 0.5,\n            self.intervals[1].pix2 - 0.5,\n            self.intervals[0].pix1 - 0.5,\n            self.intervals[0].pix2 - 0.5,\n        )", "title": ""}
{"_id": "d3489", "text": "def _match_space_at_line(line):\n    \"\"\"Return a re.match object if an empty comment was found on line.\"\"\"\n    regex = re.compile(r\"^{0}$\".format(_MDL_COMMENT))\n    return regex.match(line)", "title": ""}
{"_id": "d3490", "text": "def chunks(iterable, chunk):\n    \"\"\"Yield successive n-sized chunks from an iterable.\"\"\"\n    for i in range(0, len(iterable), chunk):\n        yield iterable[i:i + chunk]", "title": ""}
{"_id": "d3491", "text": "def _print_memory(self, memory):\n        \"\"\"Print memory.\n        \"\"\"\n        for addr, value in memory.items():\n            print(\"    0x%08x : 0x%08x (%d)\" % (addr, value, value))", "title": ""}
{"_id": "d3492", "text": "def Slice(a, begin, size):\n    \"\"\"\n    Slicing op.\n    \"\"\"\n    return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],", "title": ""}
{"_id": "d3493", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d3494", "text": "def sort_by_name(self):\n        \"\"\"Sort list elements by name.\"\"\"\n        super(JSSObjectList, self).sort(key=lambda k: k.name)", "title": ""}
{"_id": "d3495", "text": "def cached_query(qs, timeout=None):\n    \"\"\" Auto cached queryset and generate results.\n    \"\"\"\n    cache_key = generate_cache_key(qs)\n    return get_cached(cache_key, list, args=(qs,), timeout=None)", "title": ""}
{"_id": "d3496", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d3497", "text": "def lin_interp(x, rangeX, rangeY):\n    \"\"\"\n    Interpolate linearly variable x in rangeX onto rangeY.\n    \"\"\"\n    s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])\n    y = rangeY[0] * (1 - s) + rangeY[1] * s\n    return y", "title": ""}
{"_id": "d3498", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d3499", "text": "def is_full_slice(obj, l):\n    \"\"\"\n    We have a full length slice.\n    \"\"\"\n    return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and\n            obj.step is None)", "title": ""}
{"_id": "d3500", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d3501", "text": "def is_full_slice(obj, l):\n    \"\"\"\n    We have a full length slice.\n    \"\"\"\n    return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and\n            obj.step is None)", "title": ""}
{"_id": "d3502", "text": "def fsliceafter(astr, sub):\n    \"\"\"Return the slice after at sub in string astr\"\"\"\n    findex = astr.find(sub)\n    return astr[findex + len(sub):]", "title": ""}
{"_id": "d3503", "text": "def validate_type(self, type_):\n        \"\"\"Take an str/unicode `type_` and raise a ValueError if it's not \n        a valid type for the object.\n        \n        A valid type for a field is a value from the types_set attribute of \n        that field's class. \n        \n        \"\"\"\n        if type_ is not None and type_ not in self.types_set:\n            raise ValueError('Invalid type for %s:%s' % (self.__class__, type_))", "title": ""}
{"_id": "d3504", "text": "def movingaverage(arr, window):\n    \"\"\"\n    Calculates the moving average (\"rolling mean\") of an array\n    of a certain window size.\n    \"\"\"\n    m = np.ones(int(window)) / int(window)\n    return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')", "title": ""}
{"_id": "d3505", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d3506", "text": "def smooth_array(array, amount=1):\n    \"\"\"\n\n    Returns the nearest-neighbor (+/- amount) smoothed array.\n    This does not modify the array or slice off the funny end points.\n\n    \"\"\"\n    if amount==0: return array\n\n    # we have to store the old values in a temp array to keep the\n    # smoothing from affecting the smoothing\n    new_array = _n.array(array)\n\n    for n in range(len(array)):\n        new_array[n] = smooth(array, n, amount)\n\n    return new_array", "title": ""}
{"_id": "d3507", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d3508", "text": "def pick_unused_port(self):\n    \"\"\" Pick an unused port. There is a slight chance that this wont work. \"\"\"\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.bind(('127.0.0.1', 0))\n    _, port = s.getsockname()\n    s.close()\n    return port", "title": ""}
{"_id": "d3509", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d3510", "text": "def run(context, port):\n    \"\"\" Run the Webserver/SocketIO and app\n    \"\"\"\n    global ctx\n    ctx = context\n    app.run(port=port)", "title": ""}
{"_id": "d3511", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d3512", "text": "def enter_room(self, sid, room, namespace=None):\n        \"\"\"Enter a room.\n\n        The only difference with the :func:`socketio.Server.enter_room` method\n        is that when the ``namespace`` argument is not given the namespace\n        associated with the class is used.\n        \"\"\"\n        return self.server.enter_room(sid, room,\n                                      namespace=namespace or self.namespace)", "title": ""}
{"_id": "d3513", "text": "def end(self):\n        \"\"\"End of the Glances server session.\"\"\"\n        if not self.args.disable_autodiscover:\n            self.autodiscover_client.close()\n        self.server.end()", "title": ""}
{"_id": "d3514", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d3515", "text": "def delistify(x):\n    \"\"\" A basic slug version of a given parameter list. \"\"\"\n    if isinstance(x, list):\n        x = [e.replace(\"'\", \"\") for e in x]\n        return '-'.join(sorted(x))\n    return x", "title": ""}
{"_id": "d3516", "text": "def transcript_sort_key(transcript):\n    \"\"\"\n    Key function used to sort transcripts. Taking the negative of\n    protein sequence length and nucleotide sequence length so that\n    the transcripts with longest sequences come first in the list. This couldn't\n    be accomplished with `reverse=True` since we're also sorting by\n    transcript name (which places TP53-001 before TP53-002).\n    \"\"\"\n    return (\n        -len(transcript.protein_sequence),\n        -len(transcript.sequence),\n        transcript.name\n    )", "title": ""}
{"_id": "d3517", "text": "def access_to_sympy(self, var_name, access):\n        \"\"\"\n        Transform a (multidimensional) variable access to a flattend sympy expression.\n\n        Also works with flat array accesses.\n        \"\"\"\n        base_sizes = self.variables[var_name][1]\n\n        expr = sympy.Number(0)\n\n        for dimension, a in enumerate(access):\n            base_size = reduce(operator.mul, base_sizes[dimension+1:], sympy.Integer(1))\n\n            expr += base_size*a\n\n        return expr", "title": ""}
{"_id": "d3518", "text": "def _dict_values_sorted_by_key(dictionary):\n    # This should be a yield from instead.\n    \"\"\"Internal helper to return the values of a dictionary, sorted by key.\n    \"\"\"\n    for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):\n        yield value", "title": ""}
{"_id": "d3519", "text": "def query_sum(queryset, field):\n    \"\"\"\n    Let the DBMS perform a sum on a queryset\n    \"\"\"\n    return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']", "title": ""}
{"_id": "d3520", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d3521", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d3522", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d3523", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d3524", "text": "def sort_by_name(self):\n        \"\"\"Sort list elements by name.\"\"\"\n        super(JSSObjectList, self).sort(key=lambda k: k.name)", "title": ""}
{"_id": "d3525", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d3526", "text": "def get_py_source(file):\n    \"\"\"\n    Retrieves and returns the source code for any Python\n    files requested by the UI via the host agent\n\n    @param file [String] The fully qualified path to a file\n    \"\"\"\n    try:\n        response = None\n        pysource = \"\"\n\n        if regexp_py.search(file) is None:\n            response = {\"error\": \"Only Python source files are allowed. (*.py)\"}\n        else:\n            with open(file, 'r') as pyfile:\n                pysource = pyfile.read()\n\n            response = {\"data\": pysource}\n\n    except Exception as e:\n        response = {\"error\": str(e)}\n    finally:\n        return response", "title": ""}
{"_id": "d3527", "text": "def _root_mean_square_error(y, y_pred, w):\n    \"\"\"Calculate the root mean square error.\"\"\"\n    return np.sqrt(np.average(((y_pred - y) ** 2), weights=w))", "title": ""}
{"_id": "d3528", "text": "def replace(scope, strings, source, dest):\n    \"\"\"\n    Returns a copy of the given string (or list of strings) in which all\n    occurrences of the given source are replaced by the given dest.\n\n    :type  strings: string\n    :param strings: A string, or a list of strings.\n    :type  source: string\n    :param source: What to replace.\n    :type  dest: string\n    :param dest: What to replace it with.\n    :rtype:  string\n    :return: The resulting string, or list of strings.\n    \"\"\"\n    return [s.replace(source[0], dest[0]) for s in strings]", "title": ""}
{"_id": "d3529", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d3530", "text": "def toArray(self):\n        \"\"\"\n        Returns a copy of this SparseVector as a 1-dimensional NumPy array.\n        \"\"\"\n        arr = np.zeros((self.size,), dtype=np.float64)\n        arr[self.indices] = self.values\n        return arr", "title": ""}
{"_id": "d3531", "text": "def unicode_is_ascii(u_string):\n    \"\"\"Determine if unicode string only contains ASCII characters.\n\n    :param str u_string: unicode string to check. Must be unicode\n        and not Python 2 `str`.\n    :rtype: bool\n    \"\"\"\n    assert isinstance(u_string, str)\n    try:\n        u_string.encode('ascii')\n        return True\n    except UnicodeEncodeError:\n        return False", "title": ""}
{"_id": "d3532", "text": "def step_next_line(self):\n        \"\"\"Sets cursor as beginning of next line.\"\"\"\n        self._eol.append(self.position)\n        self._lineno += 1\n        self._col_offset = 0", "title": ""}
{"_id": "d3533", "text": "def datatype(dbtype, description, cursor):\n    \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n    dt = cursor.db.introspection.get_field_type(dbtype, description)\n    if type(dt) is tuple:\n        return dt[0]\n    else:\n        return dt", "title": ""}
{"_id": "d3534", "text": "def read_sphinx_environment(pth):\n    \"\"\"Read the sphinx environment.pickle file at path `pth`.\"\"\"\n\n    with open(pth, 'rb') as fo:\n        env = pickle.load(fo)\n    return env", "title": ""}
{"_id": "d3535", "text": "def _is_image_sequenced(image):\n    \"\"\"Determine if the image is a sequenced image.\"\"\"\n    try:\n        image.seek(1)\n        image.seek(0)\n        result = True\n    except EOFError:\n        result = False\n\n    return result", "title": ""}
{"_id": "d3536", "text": "def consecutive(data, stepsize=1):\n    \"\"\"Converts array into chunks with consecutive elements of given step size.\n    http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy\n    \"\"\"\n    return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)", "title": ""}
{"_id": "d3537", "text": "def go_to_line(self, line):\n        \"\"\"\n        Moves the text cursor to given line.\n\n        :param line: Line to go to.\n        :type line: int\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        cursor = self.textCursor()\n        cursor.setPosition(self.document().findBlockByNumber(line - 1).position())\n        self.setTextCursor(cursor)\n        return True", "title": ""}
{"_id": "d3538", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d3539", "text": "def is_image_file_valid(file_path_name):\n    \"\"\"\n    Indicate whether the specified image file is valid or not.\n\n\n    @param file_path_name: absolute path and file name of an image.\n\n\n    @return: ``True`` if the image file is valid, ``False`` if the file is\n        truncated or does not correspond to a supported image.\n    \"\"\"\n    # Image.verify is only implemented for PNG images, and it only verifies\n    # the CRC checksum in the image.  The only way to check from within\n    # Pillow is to load the image in a try/except and check the error.  If\n    # as much info as possible is from the image is needed,\n    # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it\n    # will attempt to parse as much as possible.\n    try:\n        with Image.open(file_path_name) as image:\n            image.load()\n    except IOError:\n        return False\n\n    return True", "title": ""}
{"_id": "d3540", "text": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "title": ""}
{"_id": "d3541", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d3542", "text": "def cleanLines(source, lineSep=os.linesep):\n    \"\"\"\n    :param source: some iterable source (list, file, etc)\n    :param lineSep: string of separators (chars) that must be removed\n    :return: list of non empty lines with removed separators\n    \"\"\"\n    stripped = (line.strip(lineSep) for line in source)\n    return (line for line in stripped if len(line) != 0)", "title": ""}
{"_id": "d3543", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d3544", "text": "def reindent(s, numspaces):\n    \"\"\" reinidents a string (s) by the given number of spaces (numspaces) \"\"\"\n    leading_space = numspaces * ' '\n    lines = [leading_space + line.strip()for line in s.splitlines()]\n    return '\\n'.join(lines)", "title": ""}
{"_id": "d3545", "text": "def wrap_count(method):\n    \"\"\"\n    Returns number of wraps around given method.\n    \"\"\"\n    number = 0\n    while hasattr(method, '__aspects_orig'):\n        number += 1\n        method = method.__aspects_orig\n    return number", "title": ""}
{"_id": "d3546", "text": "def restart(self, reset=False):\n        \"\"\"\n        Quit and Restart Spyder application.\n\n        If reset True it allows to reset spyder on restart.\n        \"\"\"\n        # Get start path to use in restart script\n        spyder_start_directory = get_module_path('spyder')\n        restart_script = osp.join(spyder_start_directory, 'app', 'restart.py')\n\n        # Get any initial argument passed when spyder was started\n        # Note: Variables defined in bootstrap.py and spyder/app/start.py\n        env = os.environ.copy()\n        bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)\n        spyder_args = env.pop('SPYDER_ARGS')\n\n        # Get current process and python running spyder\n        pid = os.getpid()\n        python = sys.executable\n\n        # Check if started with bootstrap.py\n        if bootstrap_args is not None:\n            spyder_args = bootstrap_args\n            is_bootstrap = True\n        else:\n            is_bootstrap = False\n\n        # Pass variables as environment variables (str) to restarter subprocess\n        env['SPYDER_ARGS'] = spyder_args\n        env['SPYDER_PID'] = str(pid)\n        env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)\n        env['SPYDER_RESET'] = str(reset)\n\n        if DEV:\n            if os.name == 'nt':\n                env['PYTHONPATH'] = ';'.join(sys.path)\n            else:\n                env['PYTHONPATH'] = ':'.join(sys.path)\n\n        # Build the command and popen arguments depending on the OS\n        if os.name == 'nt':\n            # Hide flashing command prompt\n            startupinfo = subprocess.STARTUPINFO()\n            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n            shell = False\n        else:\n            startupinfo = None\n            shell = True\n\n        command = '\"{0}\" \"{1}\"'\n        command = command.format(python, restart_script)\n\n        try:\n            if self.closing(True):\n                subprocess.Popen(command, shell=shell, env=env,\n                                 startupinfo=startupinfo)\n                self.console.quit()\n        except Exception as error:\n            # If there is an error with subprocess, Spyder should not quit and\n            # the error can be inspected in the internal console\n            print(error)  # spyder: test-skip\n            print(command)", "title": ""}
{"_id": "d3547", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d3548", "text": "def restart(self, reset=False):\n        \"\"\"\n        Quit and Restart Spyder application.\n\n        If reset True it allows to reset spyder on restart.\n        \"\"\"\n        # Get start path to use in restart script\n        spyder_start_directory = get_module_path('spyder')\n        restart_script = osp.join(spyder_start_directory, 'app', 'restart.py')\n\n        # Get any initial argument passed when spyder was started\n        # Note: Variables defined in bootstrap.py and spyder/app/start.py\n        env = os.environ.copy()\n        bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)\n        spyder_args = env.pop('SPYDER_ARGS')\n\n        # Get current process and python running spyder\n        pid = os.getpid()\n        python = sys.executable\n\n        # Check if started with bootstrap.py\n        if bootstrap_args is not None:\n            spyder_args = bootstrap_args\n            is_bootstrap = True\n        else:\n            is_bootstrap = False\n\n        # Pass variables as environment variables (str) to restarter subprocess\n        env['SPYDER_ARGS'] = spyder_args\n        env['SPYDER_PID'] = str(pid)\n        env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)\n        env['SPYDER_RESET'] = str(reset)\n\n        if DEV:\n            if os.name == 'nt':\n                env['PYTHONPATH'] = ';'.join(sys.path)\n            else:\n                env['PYTHONPATH'] = ':'.join(sys.path)\n\n        # Build the command and popen arguments depending on the OS\n        if os.name == 'nt':\n            # Hide flashing command prompt\n            startupinfo = subprocess.STARTUPINFO()\n            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n            shell = False\n        else:\n            startupinfo = None\n            shell = True\n\n        command = '\"{0}\" \"{1}\"'\n        command = command.format(python, restart_script)\n\n        try:\n            if self.closing(True):\n                subprocess.Popen(command, shell=shell, env=env,\n                                 startupinfo=startupinfo)\n                self.console.quit()\n        except Exception as error:\n            # If there is an error with subprocess, Spyder should not quit and\n            # the error can be inspected in the internal console\n            print(error)  # spyder: test-skip\n            print(command)", "title": ""}
{"_id": "d3549", "text": "def length(self):\n        \"\"\"Array of vector lengths\"\"\"\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "title": ""}
{"_id": "d3550", "text": "def _bindingsToDict(self, bindings):\n        \"\"\"\n        Given a binding from the sparql query result,\n        create a dict of plain text\n        \"\"\"\n        myDict = {}\n        for key, val in bindings.iteritems():\n            myDict[key.toPython().replace('?', '')] = val.toPython()\n        return myDict", "title": ""}
{"_id": "d3551", "text": "def compose_all(tups):\n  \"\"\"Compose all given tuples together.\"\"\"\n  from . import ast  # I weep for humanity\n  return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))", "title": ""}
{"_id": "d3552", "text": "def insert_many(self, items):\n    \"\"\"\n    Insert many items at once into a temporary table.\n\n    \"\"\"\n    return SessionContext.session.execute(\n        self.insert(values=[\n            to_dict(item, self.c)\n            for item in items\n        ]),\n    ).rowcount", "title": ""}
{"_id": "d3553", "text": "def visit_Str(self, node):\n        \"\"\" Set the pythonic string type. \"\"\"\n        self.result[node] = self.builder.NamedType(pytype_to_ctype(str))", "title": ""}
{"_id": "d3554", "text": "def get_count(self, query):\n        \"\"\"\n        Returns a number of query results. This is faster than .count() on the query\n        \"\"\"\n        count_q = query.statement.with_only_columns(\n            [func.count()]).order_by(None)\n        count = query.session.execute(count_q).scalar()\n        return count", "title": ""}
{"_id": "d3555", "text": "def downgrade(directory, sql, tag, x_arg, revision):\n    \"\"\"Revert to a previous version\"\"\"\n    _downgrade(directory, revision, sql, tag, x_arg)", "title": ""}
{"_id": "d3556", "text": "def unlock(self):\n    \"\"\"Closes the session to the database.\"\"\"\n    if not hasattr(self, 'session'):\n      raise RuntimeError('Error detected! The session that you want to close does not exist any more!')\n    logger.debug(\"Closed database session of '%s'\" % self._database)\n    self.session.close()\n    del self.session", "title": ""}
{"_id": "d3557", "text": "def cpp_prog_builder(build_context, target):\n    \"\"\"Build a C++ binary executable\"\"\"\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)", "title": ""}
{"_id": "d3558", "text": "def column_exists(cr, table, column):\n    \"\"\" Check whether a certain column exists \"\"\"\n    cr.execute(\n        'SELECT count(attname) FROM pg_attribute '\n        'WHERE attrelid = '\n        '( SELECT oid FROM pg_class WHERE relname = %s ) '\n        'AND attname = %s',\n        (table, column))\n    return cr.fetchone()[0] == 1", "title": ""}
{"_id": "d3559", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d3560", "text": "def sqliteRowsToDicts(sqliteRows):\n    \"\"\"\n    Unpacks sqlite rows as returned by fetchall\n    into an array of simple dicts.\n\n    :param sqliteRows: array of rows returned from fetchall DB call\n    :return:  array of dicts, keyed by the column names.\n    \"\"\"\n    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "title": ""}
{"_id": "d3561", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d3562", "text": "def get_type_len(self):\n        \"\"\"Retrieve the type and length for a data record.\"\"\"\n        # Check types and set type/len\n        self.get_sql()\n        return self.type, self.len, self.len_decimal", "title": ""}
{"_id": "d3563", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d3564", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d3565", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d3566", "text": "def exists(self, filepath):\n        \"\"\"Determines if the specified file/folder exists, even if it\n        is on a remote server.\"\"\"\n        if self.is_ssh(filepath):\n            self._check_ftp()\n            remotepath = self._get_remote(filepath)\n            try:\n                self.ftp.stat(remotepath)\n            except IOError as e:\n                if e.errno == errno.ENOENT:\n                    return False\n            else:\n                return True\n        else:\n            return os.path.exists(filepath)", "title": ""}
{"_id": "d3567", "text": "def ensure_tuple(obj):\n    \"\"\"Try and make the given argument into a tuple.\"\"\"\n    if obj is None:\n        return tuple()\n    if isinstance(obj, Iterable) and not isinstance(obj, six.string_types):\n        return tuple(obj)\n    return obj,", "title": ""}
{"_id": "d3568", "text": "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig", "title": ""}
{"_id": "d3569", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d3570", "text": "def weighted_std(values, weights):\n    \"\"\" Calculate standard deviation weighted by errors \"\"\"\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)", "title": ""}
{"_id": "d3571", "text": "def calculate_bounding_box(data):\n    \"\"\"\n    Returns a 2 x m array indicating the min and max along each\n    dimension.\n    \"\"\"\n    mins = data.min(0)\n    maxes = data.max(0)\n    return mins, maxes", "title": ""}
{"_id": "d3572", "text": "def is_static(*p):\n    \"\"\" A static value (does not change at runtime)\n    which is known at compile time\n    \"\"\"\n    return all(is_CONST(x) or\n               is_number(x) or\n               is_const(x)\n               for x in p)", "title": ""}
{"_id": "d3573", "text": "def _create_complete_graph(node_ids):\n    \"\"\"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)\n    \"\"\"\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", "title": ""}
{"_id": "d3574", "text": "def static_method(cls, f):\n        \"\"\"Decorator which dynamically binds static methods to the model for later use.\"\"\"\n        setattr(cls, f.__name__, staticmethod(f))\n        return f", "title": ""}
{"_id": "d3575", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d3576", "text": "def glr_path_static():\n    \"\"\"Returns path to packaged static files\"\"\"\n    return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))", "title": ""}
{"_id": "d3577", "text": "def __connect():\n    \"\"\"\n    Connect to a redis instance.\n    \"\"\"\n    global redis_instance\n    if use_tcp_socket:\n        redis_instance = redis.StrictRedis(host=hostname, port=port)\n    else:\n        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "title": ""}
{"_id": "d3578", "text": "def _update_staticmethod(self, oldsm, newsm):\n        \"\"\"Update a staticmethod update.\"\"\"\n        # While we can't modify the staticmethod object itself (it has no\n        # mutable attributes), we *can* extract the underlying function\n        # (by calling __get__(), which returns it) and update it in-place.\n        # We don't have the class available to pass to __get__() but any\n        # object except None will do.\n        self._update(None, None, oldsm.__get__(0), newsm.__get__(0))", "title": ""}
{"_id": "d3579", "text": "def image_format(value):\n    \"\"\"\n    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\n\n    \"\"\"\n\n    if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS:\n        raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)", "title": ""}
{"_id": "d3580", "text": "def _update_staticmethod(self, oldsm, newsm):\n        \"\"\"Update a staticmethod update.\"\"\"\n        # While we can't modify the staticmethod object itself (it has no\n        # mutable attributes), we *can* extract the underlying function\n        # (by calling __get__(), which returns it) and update it in-place.\n        # We don't have the class available to pass to __get__() but any\n        # object except None will do.\n        self._update(None, None, oldsm.__get__(0), newsm.__get__(0))", "title": ""}
{"_id": "d3581", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d3582", "text": "def standard_deviation(numbers):\n    \"\"\"Return standard deviation.\"\"\"\n    numbers = list(numbers)\n    if not numbers:\n        return 0\n    mean = sum(numbers) / len(numbers)\n    return (sum((n - mean) ** 2 for n in numbers) /\n            len(numbers)) ** .5", "title": ""}
{"_id": "d3583", "text": "def norm_vec(vector):\n    \"\"\"Normalize the length of a vector to one\"\"\"\n    assert len(vector) == 3\n    v = np.array(vector)\n    return v/np.sqrt(np.sum(v**2))", "title": ""}
{"_id": "d3584", "text": "async def restart(request):\n    \"\"\"\n    Returns OK, then waits approximately 1 second and restarts container\n    \"\"\"\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\"})", "title": ""}
{"_id": "d3585", "text": "def length(self):\n        \"\"\"Array of vector lengths\"\"\"\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "title": ""}
{"_id": "d3586", "text": "def parse_json_date(value):\n    \"\"\"\n    Parses an ISO8601 formatted datetime from a string value\n    \"\"\"\n    if not value:\n        return None\n\n    return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)", "title": ""}
{"_id": "d3587", "text": "def fetch_header(self):\n        \"\"\"Make a header request to the endpoint.\"\"\"\n        query = self.query().add_query_parameter(req='header')\n        return self._parse_messages(self.get_query(query).content)[0]", "title": ""}
{"_id": "d3588", "text": "def dt2str(dt, flagSeconds=True):\n    \"\"\"Converts datetime object to str if not yet an str.\"\"\"\n    if isinstance(dt, str):\n        return dt\n    return dt.strftime(_FMTS if flagSeconds else _FMT)", "title": ""}
{"_id": "d3589", "text": "def add_device_callback(self, callback):\n        \"\"\"Register a callback to be invoked when a new device appears.\"\"\"\n        _LOGGER.debug('Added new callback %s ', callback)\n        self._cb_new_device.append(callback)", "title": ""}
{"_id": "d3590", "text": "def any_contains_any(strings, candidates):\n    \"\"\"Whether any of the strings contains any of the candidates.\"\"\"\n    for string in strings:\n        for c in candidates:\n            if c in string:\n                return True", "title": ""}
{"_id": "d3591", "text": "def load(cls, fname):\n        \"\"\"\n        Loads the flow from a JSON file.\n\n        :param fname: the file to load\n        :type fname: str\n        :return: the flow\n        :rtype: Flow\n        \"\"\"\n        with open(fname) as f:\n            content = f.readlines()\n        return Flow.from_json(''.join(content))", "title": ""}
{"_id": "d3592", "text": "def safe_format(s, **kwargs):\n  \"\"\"\n  :type s str\n  \"\"\"\n  return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))", "title": ""}
{"_id": "d3593", "text": "def build_output(self, fout):\n        \"\"\"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.\n        \"\"\"\n        fout.write('\\n'.join([s for s in self.out]))", "title": ""}
{"_id": "d3594", "text": "def format_line(data, linestyle):\n    \"\"\"Formats a list of elements using the given line style\"\"\"\n    return linestyle.begin + linestyle.sep.join(data) + linestyle.end", "title": ""}
{"_id": "d3595", "text": "def _write_config(config, cfg_file):\n    \"\"\"\n    Write a config object to the settings.cfg file.\n\n    :param config: A ConfigParser object to write to the settings.cfg file.\n    \"\"\"\n    directory = os.path.dirname(cfg_file)\n    if not os.path.exists(directory):\n        os.makedirs(directory)\n    with open(cfg_file, \"w+\") as output_file:\n        config.write(output_file)", "title": ""}
{"_id": "d3596", "text": "def _strvar(a, prec='{:G}'):\n    r\"\"\"Return variable as a string to print, with given precision.\"\"\"\n    return ' '.join([prec.format(i) for i in np.atleast_1d(a)])", "title": ""}
{"_id": "d3597", "text": "def entropy(string):\n    \"\"\"Compute entropy on the string\"\"\"\n    p, lns = Counter(string), float(len(string))\n    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())", "title": ""}
{"_id": "d3598", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d3599", "text": "def dump_stmt_strings(stmts, fname):\n    \"\"\"Save printed statements in a file.\n\n    Parameters\n    ----------\n    stmts_in : list[indra.statements.Statement]\n        A list of statements to save in a text file.\n    fname : Optional[str]\n        The name of a text file to save the printed statements into.\n    \"\"\"\n    with open(fname, 'wb') as fh:\n        for st in stmts:\n            fh.write(('%s\\n' % st).encode('utf-8'))", "title": ""}
{"_id": "d3600", "text": "def validate_stringlist(s):\n    \"\"\"Validate a list of strings\n\n    Parameters\n    ----------\n    val: iterable of strings\n\n    Returns\n    -------\n    list\n        list of str\n\n    Raises\n    ------\n    ValueError\"\"\"\n    if isinstance(s, six.string_types):\n        return [six.text_type(v.strip()) for v in s.split(',') if v.strip()]\n    else:\n        try:\n            return list(map(validate_str, s))\n        except TypeError as e:\n            raise ValueError(e.message)", "title": ""}
{"_id": "d3601", "text": "def write_line(self, line, count=1):\n        \"\"\"writes the line and count newlines after the line\"\"\"\n        self.write(line)\n        self.write_newlines(count)", "title": ""}
{"_id": "d3602", "text": "def make_strslice(lineno, s, lower, upper):\n    \"\"\" Wrapper: returns String Slice node\n    \"\"\"\n    return symbols.STRSLICE.make_node(lineno, s, lower, upper)", "title": ""}
{"_id": "d3603", "text": "def filedata(self):\n        \"\"\"Property providing access to the :class:`.FileDataAPI`\"\"\"\n        if self._filedata_api is None:\n            self._filedata_api = self.get_filedata_api()\n        return self._filedata_api", "title": ""}
{"_id": "d3604", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d3605", "text": "def backward_char(self, e): # (C-b)\n        u\"\"\"Move back a character. \"\"\"\n        self.l_buffer.backward_char(self.argument_reset)\n        self.finalize()", "title": ""}
{"_id": "d3606", "text": "def top(n, width=WIDTH, style=STYLE):\n    \"\"\"Prints the top row of a table\"\"\"\n    return hrule(n, width, linestyle=STYLES[style].top)", "title": ""}
{"_id": "d3607", "text": "def _repr_strip(mystring):\n    \"\"\"\n    Returns the string without any initial or final quotes.\n    \"\"\"\n    r = repr(mystring)\n    if r.startswith(\"'\") and r.endswith(\"'\"):\n        return r[1:-1]\n    else:\n        return r", "title": ""}
{"_id": "d3608", "text": "def html_to_text(content):\n    \"\"\" Converts html content to plain text \"\"\"\n    text = None\n    h2t = html2text.HTML2Text()\n    h2t.ignore_links = False\n    text = h2t.handle(content)\n    return text", "title": ""}
{"_id": "d3609", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d3610", "text": "def pretty(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Pretty print the object's representation.\n    \"\"\"\n    stream = StringIO()\n    printer = RepresentationPrinter(stream, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    return stream.getvalue()", "title": ""}
{"_id": "d3611", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d3612", "text": "def chmod(scope, filename, mode):\n    \"\"\"\n    Changes the permissions of the given file (or list of files)\n    to the given mode. You probably want to use an octal representation\n    for the integer, e.g. \"chmod(myfile, 0644)\".\n\n    :type  filename: string\n    :param filename: A filename.\n    :type  mode: int\n    :param mode: The access permissions.\n    \"\"\"\n    for file in filename:\n        os.chmod(file, mode[0])\n    return True", "title": ""}
{"_id": "d3613", "text": "def lines(input):\n    \"\"\"Remove comments and empty lines\"\"\"\n    for raw_line in input:\n        line = raw_line.strip()\n        if line and not line.startswith('#'):\n            yield strip_comments(line)", "title": ""}
{"_id": "d3614", "text": "def get_shape(img):\n    \"\"\"Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple\n    \"\"\"\n    if hasattr(img, 'shape'):\n        shape = img.shape\n    else:\n        shape = img.get_data().shape\n    return shape", "title": ""}
{"_id": "d3615", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d3616", "text": "def set_title(self, title, **kwargs):\n        \"\"\"Sets the title on the underlying matplotlib AxesSubplot.\"\"\"\n        ax = self.get_axes()\n        ax.set_title(title, **kwargs)", "title": ""}
{"_id": "d3617", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d3618", "text": "def show_yticklabels(self, row, column):\n        \"\"\"Show the y-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_yticklabels()", "title": ""}
{"_id": "d3619", "text": "def _replace_file(path, content):\n  \"\"\"Writes a file if it doesn't already exist with the same content.\n\n  This is useful because cargo uses timestamps to decide whether to compile things.\"\"\"\n  if os.path.exists(path):\n    with open(path, 'r') as f:\n      if content == f.read():\n        print(\"Not overwriting {} because it is unchanged\".format(path), file=sys.stderr)\n        return\n\n  with open(path, 'w') as f:\n    f.write(content)", "title": ""}
{"_id": "d3620", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d3621", "text": "def numberp(v):\n    \"\"\"Return true iff 'v' is a number.\"\"\"\n    return (not(isinstance(v, bool)) and\n            (isinstance(v, int) or isinstance(v, float)))", "title": ""}
{"_id": "d3622", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d3623", "text": "def is_float(value):\n    \"\"\"must be a float\"\"\"\n    return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "title": ""}
{"_id": "d3624", "text": "def query_sum(queryset, field):\n    \"\"\"\n    Let the DBMS perform a sum on a queryset\n    \"\"\"\n    return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']", "title": ""}
{"_id": "d3625", "text": "def replace_variable_node(node, annotation):\n    \"\"\"Replace a node annotated by `nni.variable`.\n    node: the AST node to replace\n    annotation: annotation string\n    \"\"\"\n    assert type(node) is ast.Assign, 'nni.variable is not annotating assignment expression'\n    assert len(node.targets) == 1, 'Annotated assignment has more than one left-hand value'\n    name, expr = parse_nni_variable(annotation)\n    assert test_variable_equal(node.targets[0], name), 'Annotated variable has wrong name'\n    node.value = expr\n    return node", "title": ""}
{"_id": "d3626", "text": "def _swap_rows(self, i, j):\n        \"\"\"Swap i and j rows\n\n        As the side effect, determinant flips.\n\n        \"\"\"\n\n        L = np.eye(3, dtype='intc')\n        L[i, i] = 0\n        L[j, j] = 0\n        L[i, j] = 1\n        L[j, i] = 1\n        self._L.append(L.copy())\n        self._A = np.dot(L, self._A)", "title": ""}
{"_id": "d3627", "text": "def transformer(data, label):\n    \"\"\" data preparation \"\"\"\n    data = mx.image.imresize(data, IMAGE_SIZE, IMAGE_SIZE)\n    data = mx.nd.transpose(data, (2, 0, 1))\n    data = data.astype(np.float32) / 128.0 - 1\n    return data, label", "title": ""}
{"_id": "d3628", "text": "def purge_duplicates(list_in):\n    \"\"\"Remove duplicates from list while preserving order.\n\n    Parameters\n    ----------\n    list_in: Iterable\n\n    Returns\n    -------\n    list\n        List of first occurences in order\n    \"\"\"\n    _list = []\n    for item in list_in:\n        if item not in _list:\n            _list.append(item)\n    return _list", "title": ""}
{"_id": "d3629", "text": "def resetScale(self):\n        \"\"\"Resets the scale on this image. Correctly aligns time scale, undoes manual scaling\"\"\"\n        self.img.scale(1./self.imgScale[0], 1./self.imgScale[1])\n        self.imgScale = (1.,1.)", "title": ""}
{"_id": "d3630", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d3631", "text": "def get_point_hash(self, point):\n        \"\"\"\n        return geohash for given point with self.precision\n        :param point: GeoPoint instance\n        :return: string\n        \"\"\"\n        return geohash.encode(point.latitude, point.longitude, self.precision)", "title": ""}
{"_id": "d3632", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d3633", "text": "def __eq__(self, anotherset):\n        \"\"\"Tests on itemlist equality\"\"\"\n        if not isinstance(anotherset, LR0ItemSet):\n            raise TypeError\n        if len(self.itemlist) != len(anotherset.itemlist):\n            return False\n        for element in self.itemlist:\n            if element not in anotherset.itemlist:\n                return False\n        return True", "title": ""}
{"_id": "d3634", "text": "def paint(self, tbl):\n        \"\"\"\n        Paint the table on terminal\n        Currently only print out basic string format\n        \"\"\"\n        if not isinstance(tbl, Table):\n            logging.error(\"unable to paint table: invalid object\")\n            return False\n\n        self.term.stream.write(self.term.clear)\n\n        self.term.stream.write(str(tbl))\n        return True", "title": ""}
{"_id": "d3635", "text": "def check_int(integer):\n    \"\"\"\n    Check if number is integer or not.\n\n    :param integer: Number as str\n    :return: Boolean\n    \"\"\"\n    if not isinstance(integer, str):\n        return False\n    if integer[0] in ('-', '+'):\n        return integer[1:].isdigit()\n    return integer.isdigit()", "title": ""}
{"_id": "d3636", "text": "def timedelta2millisecond(td):\n    \"\"\"Get milliseconds from a timedelta.\"\"\"\n    milliseconds = td.days * 24 * 60 * 60 * 1000\n    milliseconds += td.seconds * 1000\n    milliseconds += td.microseconds / 1000\n    return milliseconds", "title": ""}
{"_id": "d3637", "text": "def get_truetype(value):\n    \"\"\"Convert a string to a pythonized parameter.\"\"\"\n    if value in [\"true\", \"True\", \"y\", \"Y\", \"yes\"]:\n        return True\n    if value in [\"false\", \"False\", \"n\", \"N\", \"no\"]:\n        return False\n    if value.isdigit():\n        return int(value)\n    return str(value)", "title": ""}
{"_id": "d3638", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d3639", "text": "def __getitem__(self, name):\n        \"\"\"\n        A pymongo-like behavior for dynamically obtaining a collection of documents\n        \"\"\"\n        if name not in self._collections:\n            self._collections[name] = Collection(self.db, name)\n        return self._collections[name]", "title": ""}
{"_id": "d3640", "text": "def line_line_collide(line1, line2):\n    \"\"\"Determine if two line segments meet.\n\n    This is a helper for :func:`convex_hull_collide` in the\n    special case that the two convex hulls are actually\n    just line segments. (Even in this case, this is only\n    problematic if both segments are on a single line.)\n\n    Args:\n        line1 (numpy.ndarray): ``2 x 2`` array of start and end nodes.\n        line2 (numpy.ndarray): ``2 x 2`` array of start and end nodes.\n\n    Returns:\n        bool: Indicating if the line segments collide.\n    \"\"\"\n    s, t, success = segment_intersection(\n        line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1]\n    )\n    if success:\n        return _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval(\n            t, 0.0, 1.0\n        )\n\n    else:\n        disjoint, _ = parallel_lines_parameters(\n            line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1]\n        )\n        return not disjoint", "title": ""}
{"_id": "d3641", "text": "def zero_pad(m, n=1):\n    \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n    return np.pad(m, (n, n), mode='constant', constant_values=[0])", "title": ""}
{"_id": "d3642", "text": "def logger(message, level=10):\n    \"\"\"Handle logging.\"\"\"\n    logging.getLogger(__name__).log(level, str(message))", "title": ""}
{"_id": "d3643", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d3644", "text": "def _get_example_length(example):\n  \"\"\"Returns the maximum length between the example inputs and targets.\"\"\"\n  length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0])\n  return length", "title": ""}
{"_id": "d3645", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d3646", "text": "def flatten4d3d(x):\n  \"\"\"Flatten a 4d-tensor into a 3d-tensor by joining width and height.\"\"\"\n  xshape = shape_list(x)\n  result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]])\n  return result", "title": ""}
{"_id": "d3647", "text": "def previous_friday(dt):\n    \"\"\"\n    If holiday falls on Saturday or Sunday, use previous Friday instead.\n    \"\"\"\n    if dt.weekday() == 5:\n        return dt - timedelta(1)\n    elif dt.weekday() == 6:\n        return dt - timedelta(2)\n    return dt", "title": ""}
{"_id": "d3648", "text": "def is_complex(dtype):\n  \"\"\"Returns whether this is a complex floating point type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_complex'):\n    return dtype.is_complex\n  return np.issubdtype(np.dtype(dtype), np.complex)", "title": ""}
{"_id": "d3649", "text": "def get_indent(text):\n    \"\"\"Get indent of text.\n\n    https://stackoverflow.com/questions/2268532/grab-a-lines-whitespace-\n    indention-with-python\n    \"\"\"\n    indent = ''\n\n    ret = re.match(r'(\\s*)', text)\n    if ret:\n        indent = ret.group(1)\n\n    return indent", "title": ""}
{"_id": "d3650", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d3651", "text": "def tuple_search(t, i, v):\n    \"\"\"\n    Search tuple array by index and value\n    :param t: tuple array\n    :param i: index of the value in each tuple\n    :param v: value\n    :return: the first tuple in the array with the specific index / value\n    \"\"\"\n    for e in t:\n        if e[i] == v:\n            return e\n    return None", "title": ""}
{"_id": "d3652", "text": "def is_lazy_iterable(obj):\n    \"\"\"\n    Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n    \"\"\"\n    return isinstance(obj,\n        (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))", "title": ""}
{"_id": "d3653", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d3654", "text": "def is_readable(filename):\n    \"\"\"Check if file is a regular file and is readable.\"\"\"\n    return os.path.isfile(filename) and os.access(filename, os.R_OK)", "title": ""}
{"_id": "d3655", "text": "def find_nearest_index(arr, value):\n    \"\"\"For a given value, the function finds the nearest value\n    in the array and returns its index.\"\"\"\n    arr = np.array(arr)\n    index = (abs(arr-value)).argmin()\n    return index", "title": ""}
{"_id": "d3656", "text": "def starts_with_prefix_in_list(text, prefixes):\n    \"\"\"\n    Return True if the given string starts with one of the prefixes in the given list, otherwise\n    return False.\n\n    Arguments:\n        text (str): Text to check for prefixes.\n        prefixes (list): List of prefixes to check for.\n\n    Returns:\n        bool: True if the given text starts with any of the given prefixes, otherwise False.\n    \"\"\"\n    for prefix in prefixes:\n        if text.startswith(prefix):\n            return True\n    return False", "title": ""}
{"_id": "d3657", "text": "def index(m, val):\n    \"\"\"\n    Return the indices of all the ``val`` in ``m``\n    \"\"\"\n    mm = np.array(m)\n    idx_tuple = np.where(mm == val)\n    idx = idx_tuple[0].tolist()\n\n    return idx", "title": ""}
{"_id": "d3658", "text": "def requests_post(url, data=None, json=None, **kwargs):\n    \"\"\"Requests-mock requests.post wrapper.\"\"\"\n    return requests_request('post', url, data=data, json=json, **kwargs)", "title": ""}
{"_id": "d3659", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d3660", "text": "def _genTex2D(self):\n        \"\"\"Generate an empty texture in OpenGL\"\"\"\n        for face in range(6):\n            gl.glTexImage2D(self.target0 + face, 0, self.internal_fmt, self.width, self.height, 0,\n                            self.pixel_fmt, gl.GL_UNSIGNED_BYTE, 0)", "title": ""}
{"_id": "d3661", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d3662", "text": "def ci(a, which=95, axis=None):\n    \"\"\"Return a percentile range from an array of values.\"\"\"\n    p = 50 - which / 2, 50 + which / 2\n    return percentiles(a, p, axis)", "title": ""}
{"_id": "d3663", "text": "def int2str(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from integers to strings\"\"\"\n    return NumConv(radix, alphabet).int2str(num)", "title": ""}
{"_id": "d3664", "text": "def run(self):\n        \"\"\"Run the event loop.\"\"\"\n        self.signal_init()\n        self.listen_init()\n        self.logger.info('starting')\n        self.loop.start()", "title": ""}
{"_id": "d3665", "text": "def int_to_date(date):\n    \"\"\"\n    Convert an int of form yyyymmdd to a python date object.\n    \"\"\"\n\n    year = date // 10**4\n    month = date % 10**4 // 10**2\n    day = date % 10**2\n\n    return datetime.date(year, month, day)", "title": ""}
{"_id": "d3666", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d3667", "text": "def _linearInterpolationTransformMatrix(matrix1, matrix2, value):\n    \"\"\" Linear, 'oldstyle' interpolation of the transform matrix.\"\"\"\n    return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))", "title": ""}
{"_id": "d3668", "text": "def start(self):\n        \"\"\"Start the receiver.\n        \"\"\"\n        if not self._is_running:\n            self._do_run = True\n            self._thread.start()\n        return self", "title": ""}
{"_id": "d3669", "text": "def is_valid_uid(uid):\n    \"\"\"\n    :return: True if it is a valid DHIS2 UID, False if not\n    \"\"\"\n    pattern = r'^[A-Za-z][A-Za-z0-9]{10}$'\n    if not isinstance(uid, string_types):\n        return False\n    return bool(re.compile(pattern).match(uid))", "title": ""}
{"_id": "d3670", "text": "def _synced(method, self, args, kwargs):\n    \"\"\"Underlying synchronized wrapper.\"\"\"\n    with self._lock:\n        return method(*args, **kwargs)", "title": ""}
{"_id": "d3671", "text": "def _check_color_dim(val):\n    \"\"\"Ensure val is Nx(n_col), usually Nx3\"\"\"\n    val = np.atleast_2d(val)\n    if val.shape[1] not in (3, 4):\n        raise RuntimeError('Value must have second dimension of size 3 or 4')\n    return val, val.shape[1]", "title": ""}
{"_id": "d3672", "text": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "title": ""}
{"_id": "d3673", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d3674", "text": "def format_time(time):\n    \"\"\" Formats the given time into HH:MM:SS \"\"\"\n    h, r = divmod(time / 1000, 3600)\n    m, s = divmod(r, 60)\n\n    return \"%02d:%02d:%02d\" % (h, m, s)", "title": ""}
{"_id": "d3675", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d3676", "text": "def fileModifiedTimestamp(fname):\n    \"\"\"return \"YYYY-MM-DD\" when the file was modified.\"\"\"\n    modifiedTime=os.path.getmtime(fname)\n    stamp=time.strftime('%Y-%m-%d', time.localtime(modifiedTime))\n    return stamp", "title": ""}
{"_id": "d3677", "text": "def start(self):\n        \"\"\"Activate the TypingStream on stdout\"\"\"\n        self.streams.append(sys.stdout)\n        sys.stdout = self.stream", "title": ""}
{"_id": "d3678", "text": "def localize(dt):\n    \"\"\"Localize a datetime object to local time.\"\"\"\n    if dt.tzinfo is UTC:\n        return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)\n    # No TZ info so not going to assume anything, return as-is.\n    return dt", "title": ""}
{"_id": "d3679", "text": "def as_tuple(self, value):\n        \"\"\"Utility function which converts lists to tuples.\"\"\"\n        if isinstance(value, list):\n            value = tuple(value)\n        return value", "title": ""}
{"_id": "d3680", "text": "def current_offset(local_tz=None):\n    \"\"\"\n    Returns current utcoffset for a timezone. Uses\n    DEFAULT_LOCAL_TZ by default. That value can be\n    changed at runtime using the func below.\n    \"\"\"\n    if local_tz is None:\n        local_tz = DEFAULT_LOCAL_TZ\n    dt = local_tz.localize(datetime.now())\n    return dt.utcoffset()", "title": ""}
{"_id": "d3681", "text": "def __hash__(self):\n        \"\"\"Return ``hash(self)``.\"\"\"\n        return hash((type(self), self.domain, self.range, self.partition))", "title": ""}
{"_id": "d3682", "text": "def set_cursor_position(self, position):\n        \"\"\"Set cursor position\"\"\"\n        position = self.get_position(position)\n        cursor = self.textCursor()\n        cursor.setPosition(position)\n        self.setTextCursor(cursor)\n        self.ensureCursorVisible()", "title": ""}
{"_id": "d3683", "text": "def downcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n    return [ tt.lower() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d3684", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d3685", "text": "def gaussian_variogram_model(m, d):\n    \"\"\"Gaussian model, m is [psill, range, nugget]\"\"\"\n    psill = float(m[0])\n    range_ = float(m[1])\n    nugget = float(m[2])\n    return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget", "title": ""}
{"_id": "d3686", "text": "def clear_timeline(self):\n        \"\"\"\n        Clear the contents of the TimeLine Canvas\n\n        Does not modify the actual markers dictionary and thus after\n        redrawing all markers are visible again.\n        \"\"\"\n        self._timeline.delete(tk.ALL)\n        self._canvas_ticks.delete(tk.ALL)", "title": ""}
{"_id": "d3687", "text": "def remove_list_duplicates(lista, unique=False):\n    \"\"\"\n    Remove duplicated elements in a list.\n    Args:\n        lista: List with elements to clean duplicates.\n    \"\"\"\n    result = []\n    allready = []\n\n    for elem in lista:\n        if elem not in result:\n            result.append(elem)\n        else:\n            allready.append(elem)\n\n    if unique:\n        for elem in allready:\n            result = list(filter((elem).__ne__, result))\n\n    return result", "title": ""}
{"_id": "d3688", "text": "def yview(self, *args):\n        \"\"\"Update inplace widgets position when doing vertical scroll\"\"\"\n        self.after_idle(self.__updateWnds)\n        ttk.Treeview.yview(self, *args)", "title": ""}
{"_id": "d3689", "text": "async def iso(self, source):\n        \"\"\"Convert to timestamp.\"\"\"\n        from datetime import datetime\n        unix_timestamp = int(source)\n        return datetime.fromtimestamp(unix_timestamp).isoformat()", "title": ""}
{"_id": "d3690", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d3691", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d3692", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d3693", "text": "def listfolderpath(p):\n    \"\"\"\n    generator of list folder in the path.\n    folders only\n    \"\"\"\n    for entry in scandir.scandir(p):\n        if entry.is_dir():\n            yield entry.path", "title": ""}
{"_id": "d3694", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d3695", "text": "def render_template(env, filename, values=None):\n    \"\"\"\n    Render a jinja template\n    \"\"\"\n    if not values:\n        values = {}\n    tmpl = env.get_template(filename)\n    return tmpl.render(values)", "title": ""}
{"_id": "d3696", "text": "def listified_tokenizer(source):\n    \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n    io_obj = io.StringIO(source)\n    return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]", "title": ""}
{"_id": "d3697", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d3698", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d3699", "text": "def save_notebook(work_notebook, write_file):\n    \"\"\"Saves the Jupyter work_notebook to write_file\"\"\"\n    with open(write_file, 'w') as out_nb:\n        json.dump(work_notebook, out_nb, indent=2)", "title": ""}
{"_id": "d3700", "text": "def conv3x3(in_channels, out_channels, stride=1):\n    \"\"\"\n    3x3 convolution with padding.\n    Original code has had bias turned off, because Batch Norm would remove the bias either way\n    \"\"\"\n    return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)", "title": ""}
{"_id": "d3701", "text": "def _unjsonify(x, isattributes=False):\n    \"\"\"Convert JSON string to an ordered defaultdict.\"\"\"\n    if isattributes:\n        obj = json.loads(x)\n        return dict_class(obj)\n    return json.loads(x)", "title": ""}
{"_id": "d3702", "text": "def camel_to_(s):\n    \"\"\"\n    Convert CamelCase to camel_case\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', s)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d3703", "text": "def toJson(protoObject, indent=None):\n    \"\"\"\n    Serialises a protobuf object as json\n    \"\"\"\n    # Using the internal method because this way we can reformat the JSON\n    js = json_format.MessageToDict(protoObject, False)\n    return json.dumps(js, indent=indent)", "title": ""}
{"_id": "d3704", "text": "def normalize_time(timestamp):\n    \"\"\"Normalize time in arbitrary timezone to UTC naive object.\"\"\"\n    offset = timestamp.utcoffset()\n    if offset is None:\n        return timestamp\n    return timestamp.replace(tzinfo=None) - offset", "title": ""}
{"_id": "d3705", "text": "def angle_v2_rad(vec_a, vec_b):\n    \"\"\"Returns angle between vec_a and vec_b in range [0, PI].  This does not\n    distinguish if a is left of or right of b.\n    \"\"\"\n    # cos(x) = A * B / |A| * |B|\n    return math.acos(vec_a.dot(vec_b) / (vec_a.length() * vec_b.length()))", "title": ""}
{"_id": "d3706", "text": "def toListInt(value):\n        \"\"\"\n        Convert a value to list of ints, if possible.\n        \"\"\"\n        if TypeConverters._can_convert_to_list(value):\n            value = TypeConverters.toList(value)\n            if all(map(lambda v: TypeConverters._is_integer(v), value)):\n                return [int(v) for v in value]\n        raise TypeError(\"Could not convert %s to list of ints\" % value)", "title": ""}
{"_id": "d3707", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d3708", "text": "def cmd_dns_lookup_reverse(ip_address, verbose):\n    \"\"\"Perform a reverse lookup of a given IP address.\n\n    Example:\n\n    \\b\n    $ $ habu.dns.lookup.reverse 8.8.8.8\n    {\n        \"hostname\": \"google-public-dns-a.google.com\"\n    }\n    \"\"\"\n    if verbose:\n        logging.basicConfig(level=logging.INFO, format='%(message)s')\n        print(\"Looking up %s...\" % ip_address, file=sys.stderr)\n\n    answer = lookup_reverse(ip_address)\n\n    if answer:\n        print(json.dumps(answer, indent=4))\n    else:\n        print(\"[X] %s is not valid IPv4/IPV6 address\" % ip_address)\n\n    return True", "title": ""}
{"_id": "d3709", "text": "def stop_process(self):\n        \"\"\"\n        Stops the child process.\n        \"\"\"\n        self._process.terminate()\n        if not self._process.waitForFinished(100):\n            self._process.kill()", "title": ""}
{"_id": "d3710", "text": "def yview(self, *args):\n        \"\"\"Update inplace widgets position when doing vertical scroll\"\"\"\n        self.after_idle(self.__updateWnds)\n        ttk.Treeview.yview(self, *args)", "title": ""}
{"_id": "d3711", "text": "def stop(self):\n        \"\"\"\n        Stop this server so that the calling process can exit\n        \"\"\"\n        # unsetup_fuse()\n        self.fuse_process.teardown()\n        for uuid in self.processes:\n            self.processes[uuid].terminate()", "title": ""}
{"_id": "d3712", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d3713", "text": "def get_methods(*objs):\n    \"\"\" Return the names of all callable attributes of an object\"\"\"\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    )", "title": ""}
{"_id": "d3714", "text": "def forward(self, step):\n        \"\"\"Move the turtle forward.\n\n        :param step: Integer. Distance to move forward.\n        \"\"\"\n        x = self.pos_x + math.cos(math.radians(self.rotation)) * step\n        y = self.pos_y + math.sin(math.radians(self.rotation)) * step\n        prev_brush_state = self.brush_on\n        self.brush_on = True\n        self.move(x, y)\n        self.brush_on = prev_brush_state", "title": ""}
{"_id": "d3715", "text": "def l2_norm(arr):\n    \"\"\"\n    The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n    dot product of the vector.\n    \"\"\"\n    arr = np.asarray(arr)\n    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "title": ""}
{"_id": "d3716", "text": "def default_strlen(strlen=None):\n    \"\"\"Sets the default string length for lstring and ilwd:char, if they are\n    treated as strings. Default is 50.\n    \"\"\"\n    if strlen is not None:\n        _default_types_status['default_strlen'] = strlen\n        # update the typeDicts as needed\n        lstring_as_obj(_default_types_status['lstring_as_obj'])\n        ilwd_as_int(_default_types_status['ilwd_as_int'])\n    return _default_types_status['default_strlen']", "title": ""}
{"_id": "d3717", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d3718", "text": "def generate_id():\n    \"\"\"Generate new UUID\"\"\"\n    # TODO: Use six.string_type to Py3 compat\n    try:\n        return unicode(uuid1()).replace(u\"-\", u\"\")\n    except NameError:\n        return str(uuid1()).replace(u\"-\", u\"\")", "title": ""}
{"_id": "d3719", "text": "def end_index(self):\n        \"\"\"\n        Returns the 1-based index of the last object on this page,\n        relative to total objects found (hits).\n        \"\"\"\n        return ((self.number - 1) * self.paginator.per_page +\n            len(self.object_list))", "title": ""}
{"_id": "d3720", "text": "def to_pascal_case(s):\n    \"\"\"Transform underscore separated string to pascal case\n\n    \"\"\"\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())", "title": ""}
{"_id": "d3721", "text": "def onLeftDown(self, event=None):\n        \"\"\" left button down: report x,y coords, start zooming mode\"\"\"\n        if event is None:\n            return\n        self.cursor_mode_action('leftdown', event=event)\n        self.ForwardEvent(event=event.guiEvent)", "title": ""}
{"_id": "d3722", "text": "def omnihash(obj):\n    \"\"\" recursively hash unhashable objects \"\"\"\n    if isinstance(obj, set):\n        return hash(frozenset(omnihash(e) for e in obj))\n    elif isinstance(obj, (tuple, list)):\n        return hash(tuple(omnihash(e) for e in obj))\n    elif isinstance(obj, dict):\n        return hash(frozenset((k, omnihash(v)) for k, v in obj.items()))\n    else:\n        return hash(obj)", "title": ""}
{"_id": "d3723", "text": "def norm_vec(vector):\n    \"\"\"Normalize the length of a vector to one\"\"\"\n    assert len(vector) == 3\n    v = np.array(vector)\n    return v/np.sqrt(np.sum(v**2))", "title": ""}
{"_id": "d3724", "text": "def test(ctx, all=False, verbose=False):\n    \"\"\"Run the tests.\"\"\"\n    cmd = 'tox' if all else 'py.test'\n    if verbose:\n        cmd += ' -v'\n    return ctx.run(cmd, pty=True).return_code", "title": ""}
{"_id": "d3725", "text": "def txt_line_iterator(path):\n  \"\"\"Iterate through lines of file.\"\"\"\n  with tf.gfile.Open(path) as f:\n    for line in f:\n      yield line.strip()", "title": ""}
{"_id": "d3726", "text": "def cover(session):\n    \"\"\"Run the final coverage report.\n    This outputs the coverage report aggregating coverage from the unit\n    test runs (not system test runs), and then erases coverage data.\n    \"\"\"\n    session.interpreter = 'python3.6'\n    session.install('coverage', 'pytest-cov')\n    session.run('coverage', 'report', '--show-missing', '--fail-under=100')\n    session.run('coverage', 'erase')", "title": ""}
{"_id": "d3727", "text": "def find_one(line, lookup):\n        \"\"\"\n        regexp search with one value to return.\n\n        :param line: Line\n        :param lookup: regexp\n        :return: Match group or False\n        \"\"\"\n        match = re.search(lookup, line)\n        if match:\n            if match.group(1):\n                return match.group(1)\n        return False", "title": ""}
{"_id": "d3728", "text": "def teardown_test(self, context):\n        \"\"\"\n        Tears down the Django test\n        \"\"\"\n        context.test.tearDownClass()\n        context.test._post_teardown(run=True)\n        del context.test", "title": ""}
{"_id": "d3729", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d3730", "text": "def __init__(self,operand,operator,**args):\n        \"\"\"\n        Accepts a NumberGenerator operand, an operator, and\n        optional arguments to be provided to the operator when calling\n        it on the operand.\n        \"\"\"\n        # Note that it's currently not possible to set\n        # parameters in the superclass when creating an instance,\n        # because **args is used by this class itself.\n        super(UnaryOperator,self).__init__()\n\n        self.operand=operand\n        self.operator=operator\n        self.args=args", "title": ""}
{"_id": "d3731", "text": "def _ioctl (self, func, args):\n        \"\"\"Call ioctl() with given parameters.\"\"\"\n        import fcntl\n        return fcntl.ioctl(self.sockfd.fileno(), func, args)", "title": ""}
{"_id": "d3732", "text": "def dict_update_newkeys(dict_, dict2):\n    \"\"\" Like dict.update, but does not overwrite items \"\"\"\n    for key, val in six.iteritems(dict2):\n        if key not in dict_:\n            dict_[key] = val", "title": ""}
{"_id": "d3733", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d3734", "text": "def inheritdoc(method):\n    \"\"\"Set __doc__ of *method* to __doc__ of *method* in its parent class.\n\n    Since this is used on :class:`.StringMixIn`, the \"parent class\" used is\n    ``str``. This function can be used as a decorator.\n    \"\"\"\n    method.__doc__ = getattr(str, method.__name__).__doc__\n    return method", "title": ""}
{"_id": "d3735", "text": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    l = [v.strip() for v in value.split(',')]\n    if len(l) == 1:\n        l = value.split()\n    return l", "title": ""}
{"_id": "d3736", "text": "def _remove_from_index(index, obj):\n    \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n    try:\n        index.value_map[indexed_value(index, obj)].remove(obj.id)\n    except KeyError:\n        pass", "title": ""}
{"_id": "d3737", "text": "def keys(self, index=None):\n        \"\"\"Returns a list of keys in the database\n        \"\"\"\n        with self._lmdb.begin() as txn:\n            return [key.decode() for key, _ in txn.cursor()]", "title": ""}
{"_id": "d3738", "text": "def make_bound(lower, upper, lineno):\n    \"\"\" Wrapper: Creates an array bound\n    \"\"\"\n    return symbols.BOUND.make_node(lower, upper, lineno)", "title": ""}
{"_id": "d3739", "text": "def load_image(fname):\n    \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n    with open(fname, \"rb\") as f:\n        i = Image.open(fname)\n        #i.load()\n        return i", "title": ""}
{"_id": "d3740", "text": "def get_dict_to_encoded_url(data):\n    \"\"\"\n    Converts a dict to an encoded URL.\n    Example: given  data = {'a': 1, 'b': 2}, it returns 'a=1&b=2'\n    \"\"\"\n    unicode_data = dict([(k, smart_str(v)) for k, v in data.items()])\n    encoded = urllib.urlencode(unicode_data)\n    return encoded", "title": ""}
{"_id": "d3741", "text": "def load(self, filename='classifier.dump'):\n        \"\"\"\n        Unpickles the classifier used\n        \"\"\"\n        ifile = open(filename, 'r+')\n        self.classifier = pickle.load(ifile)\n        ifile.close()", "title": ""}
{"_id": "d3742", "text": "def get_body_size(params, boundary):\n    \"\"\"Returns the number of bytes that the multipart/form-data encoding\n    of ``params`` will be.\"\"\"\n    size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))\n    return size + len(boundary) + 6", "title": ""}
{"_id": "d3743", "text": "def load_graph_from_rdf(fname):\n    \"\"\" reads an RDF file into a graph \"\"\"\n    print(\"reading RDF from \" + fname + \"....\")\n    store = Graph()\n    store.parse(fname, format=\"n3\")\n    print(\"Loaded \" + str(len(store)) + \" tuples\")\n    return store", "title": ""}
{"_id": "d3744", "text": "def __init__(self, usb):\n    \"\"\"Constructs a FastbootCommands instance.\n\n    Arguments:\n      usb: UsbHandle instance.\n    \"\"\"\n    self._usb = usb\n    self._protocol = self.protocol_handler(usb)", "title": ""}
{"_id": "d3745", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d3746", "text": "def _if(ctx, logical_test, value_if_true=0, value_if_false=False):\n    \"\"\"\n    Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE\n    \"\"\"\n    return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false", "title": ""}
{"_id": "d3747", "text": "def _find(string, sub_string, start_index):\n    \"\"\"Return index of sub_string in string.\n\n    Raise TokenError if sub_string is not found.\n    \"\"\"\n    result = string.find(sub_string, start_index)\n    if result == -1:\n        raise TokenError(\"expected '{0}'\".format(sub_string))\n    return result", "title": ""}
{"_id": "d3748", "text": "def b2u(string):\n    \"\"\" bytes to unicode \"\"\"\n    if (isinstance(string, bytes) or\n        (PY2 and isinstance(string, str))):\n        return string.decode('utf-8')\n    return string", "title": ""}
{"_id": "d3749", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d3750", "text": "def human_uuid():\n    \"\"\"Returns a good UUID for using as a human readable string.\"\"\"\n    return base64.b32encode(\n        hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip('=')", "title": ""}
{"_id": "d3751", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d3752", "text": "def safe_int(val, default=None):\n    \"\"\"\n    Returns int() of val if val is not convertable to int use default\n    instead\n\n    :param val:\n    :param default:\n    \"\"\"\n\n    try:\n        val = int(val)\n    except (ValueError, TypeError):\n        val = default\n\n    return val", "title": ""}
{"_id": "d3753", "text": "def normal_log_q(self,z):\n        \"\"\"\n        The unnormalized log posterior components for mean-field normal family (the quantity we want to approximate)\n        RAO-BLACKWELLIZED!\n        \"\"\"             \n        means, scale = self.get_means_and_scales()\n        return ss.norm.logpdf(z,loc=means,scale=scale)", "title": ""}
{"_id": "d3754", "text": "def gaussian_variogram_model(m, d):\n    \"\"\"Gaussian model, m is [psill, range, nugget]\"\"\"\n    psill = float(m[0])\n    range_ = float(m[1])\n    nugget = float(m[2])\n    return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget", "title": ""}
{"_id": "d3755", "text": "def process_request(self, request, response):\n        \"\"\"Logs the basic endpoint requested\"\"\"\n        self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))", "title": ""}
{"_id": "d3756", "text": "def val_to_bin(edges, x):\n    \"\"\"Convert axis coordinate to bin index.\"\"\"\n    ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n    return ibin", "title": ""}
{"_id": "d3757", "text": "def log_loss(preds, labels):\n    \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n    log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n    return -log_likelihood", "title": ""}
{"_id": "d3758", "text": "def dot_v3(v, w):\n    \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n    return sum([x * y for x, y in zip(v, w)])", "title": ""}
{"_id": "d3759", "text": "def close_log(log, verbose=True):\n    \"\"\"Close log\n\n    This method closes and active logging.Logger instance.\n\n    Parameters\n    ----------\n    log : logging.Logger\n        Logging instance\n\n    \"\"\"\n\n    if verbose:\n        print('Closing log file:', log.name)\n\n    # Send closing message.\n    log.info('The log file has been closed.')\n\n    # Remove all handlers from log.\n    [log.removeHandler(handler) for handler in log.handlers]", "title": ""}
{"_id": "d3760", "text": "def v_normalize(v):\n    \"\"\"\n    Normalizes the given vector.\n    \n    The vector given may have any number of dimensions.\n    \"\"\"\n    vmag = v_magnitude(v)\n    return [ v[i]/vmag  for i in range(len(v)) ]", "title": ""}
{"_id": "d3761", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d3762", "text": "def v_normalize(v):\n    \"\"\"\n    Normalizes the given vector.\n    \n    The vector given may have any number of dimensions.\n    \"\"\"\n    vmag = v_magnitude(v)\n    return [ v[i]/vmag  for i in range(len(v)) ]", "title": ""}
{"_id": "d3763", "text": "def map(cls, iterable, func, *a, **kw):\n    \"\"\"\n    Iterable-first replacement of Python's built-in `map()` function.\n    \"\"\"\n\n    return cls(func(x, *a, **kw) for x in iterable)", "title": ""}
{"_id": "d3764", "text": "def OnTogglePlay(self, event):\n        \"\"\"Toggles the video status between play and hold\"\"\"\n\n        if self.player.get_state() == vlc.State.Playing:\n            self.player.pause()\n        else:\n            self.player.play()\n\n        event.Skip()", "title": ""}
{"_id": "d3765", "text": "def clean_with_zeros(self,x):\n        \"\"\" set nan and inf rows from x to zero\"\"\"\n        x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0\n        return x", "title": ""}
{"_id": "d3766", "text": "def movingaverage(arr, window):\n    \"\"\"\n    Calculates the moving average (\"rolling mean\") of an array\n    of a certain window size.\n    \"\"\"\n    m = np.ones(int(window)) / int(window)\n    return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')", "title": ""}
{"_id": "d3767", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d3768", "text": "def get_process_handle(self):\n        \"\"\"\n        @rtype:  L{ProcessHandle}\n        @return: Process handle received from the system.\n            Returns C{None} if the handle is not available.\n        \"\"\"\n        # The handle doesn't need to be closed.\n        # See http://msdn.microsoft.com/en-us/library/ms681423(VS.85).aspx\n        hProcess = self.raw.u.CreateProcessInfo.hProcess\n        if hProcess in (0, win32.NULL, win32.INVALID_HANDLE_VALUE):\n            hProcess = None\n        else:\n            hProcess = ProcessHandle(hProcess, False, win32.PROCESS_ALL_ACCESS)\n        return hProcess", "title": ""}
{"_id": "d3769", "text": "def make_regex(separator):\n    \"\"\"Utility function to create regexp for matching escaped separators\n    in strings.\n\n    \"\"\"\n    return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +\n                      re.escape(separator) + r'\\\\]|\\\\.)+)')", "title": ""}
{"_id": "d3770", "text": "def _position():\n    \"\"\"Returns the current xy coordinates of the mouse cursor as a two-integer\n    tuple by calling the GetCursorPos() win32 function.\n\n    Returns:\n      (x, y) tuple of the current xy coordinates of the mouse cursor.\n    \"\"\"\n\n    cursor = POINT()\n    ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))\n    return (cursor.x, cursor.y)", "title": ""}
{"_id": "d3771", "text": "def comment (self, s, **args):\n        \"\"\"Write DOT comment.\"\"\"\n        self.write(u\"// \")\n        self.writeln(s=s, **args)", "title": ""}
{"_id": "d3772", "text": "def kill_process_children(pid):\n    \"\"\"Find and kill child processes of a process.\n\n    :param pid: PID of parent process (process ID)\n    :return: Nothing\n    \"\"\"\n    if sys.platform == \"darwin\":\n        kill_process_children_osx(pid)\n    elif sys.platform == \"linux\":\n        kill_process_children_unix(pid)\n    else:\n        pass", "title": ""}
{"_id": "d3773", "text": "def _psutil_kill_pid(pid):\n    \"\"\"\n    http://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows\n    \"\"\"\n    try:\n        parent = Process(pid)\n        for child in parent.children(recursive=True):\n            child.kill()\n        parent.kill()\n    except NoSuchProcess:\n        return", "title": ""}
{"_id": "d3774", "text": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "title": ""}
{"_id": "d3775", "text": "def top_1_tpu(inputs):\n  \"\"\"find max and argmax over the last dimension.\n\n  Works well on TPU\n\n  Args:\n    inputs: A tensor with shape [..., depth]\n\n  Returns:\n    values: a Tensor with shape [...]\n    indices: a Tensor with shape [...]\n  \"\"\"\n  inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True)\n  mask = tf.to_int32(tf.equal(inputs_max, inputs))\n  index = tf.range(tf.shape(inputs)[-1]) * mask\n  return tf.squeeze(inputs_max, -1), tf.reduce_max(index, axis=-1)", "title": ""}
{"_id": "d3776", "text": "def close(self):\n        \"\"\"Closes this response.\"\"\"\n        if self._connection:\n            self._connection.close()\n        self._response.close()", "title": ""}
{"_id": "d3777", "text": "def retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n\t\"\"\"\n\tGiven a callable func, trap the indicated exceptions\n\tfor up to 'retries' times, invoking cleanup on the\n\texception. On the final attempt, allow any exceptions\n\tto propagate.\n\t\"\"\"\n\tattempts = count() if retries == float('inf') else range(retries)\n\tfor attempt in attempts:\n\t\ttry:\n\t\t\treturn func()\n\t\texcept trap:\n\t\t\tcleanup()\n\n\treturn func()", "title": ""}
{"_id": "d3778", "text": "def reduce_json(data):\n    \"\"\"Reduce a JSON object\"\"\"\n    return reduce(lambda x, y: int(x) + int(y), data.values())", "title": ""}
{"_id": "d3779", "text": "def convert_value(bind, value):\n    \"\"\" Type casting. \"\"\"\n    type_name = get_type(bind)\n    try:\n        return typecast.cast(type_name, value)\n    except typecast.ConverterError:\n        return value", "title": ""}
{"_id": "d3780", "text": "def chop(seq, size):\n    \"\"\"Chop a sequence into chunks of the given size.\"\"\"\n    chunk = lambda i: seq[i:i+size]\n    return map(chunk,xrange(0,len(seq),size))", "title": ""}
{"_id": "d3781", "text": "def write_str2file(pathname, astr):\n    \"\"\"writes a string to file\"\"\"\n    fname = pathname\n    fhandle = open(fname, 'wb')\n    fhandle.write(astr)\n    fhandle.close()", "title": ""}
{"_id": "d3782", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d3783", "text": "def csv_matrix_print(classes, table):\n    \"\"\"\n    Return matrix as csv data.\n\n    :param classes: classes list\n    :type classes:list\n    :param table: table\n    :type table:dict\n    :return:\n    \"\"\"\n    result = \"\"\n    classes.sort()\n    for i in classes:\n        for j in classes:\n            result += str(table[i][j]) + \",\"\n        result = result[:-1] + \"\\n\"\n    return result[:-1]", "title": ""}
{"_id": "d3784", "text": "def MatrixInverse(a, adj):\n    \"\"\"\n    Matrix inversion op.\n    \"\"\"\n    return np.linalg.inv(a if not adj else _adjoint(a)),", "title": ""}
{"_id": "d3785", "text": "def _write_color_ansi (fp, text, color):\n    \"\"\"Colorize text with given color.\"\"\"\n    fp.write(esc_ansicolor(color))\n    fp.write(text)\n    fp.write(AnsiReset)", "title": ""}
{"_id": "d3786", "text": "def indentsize(line):\n    \"\"\"Return the indent size, in spaces, at the start of a line of text.\"\"\"\n    expline = string.expandtabs(line)\n    return len(expline) - len(string.lstrip(expline))", "title": ""}
{"_id": "d3787", "text": "def write_line(self, line, count=1):\n        \"\"\"writes the line and count newlines after the line\"\"\"\n        self.write(line)\n        self.write_newlines(count)", "title": ""}
{"_id": "d3788", "text": "def _show_traceback(method):\n    \"\"\"decorator for showing tracebacks in IPython\"\"\"\n    def m(self, *args, **kwargs):\n        try:\n            return(method(self, *args, **kwargs))\n        except Exception as e:\n            ip = get_ipython()\n            if ip is None:\n                self.log.warning(\"Exception in widget method %s: %s\", method, e, exc_info=True)\n            else:\n                ip.showtraceback()\n    return m", "title": ""}
{"_id": "d3789", "text": "def _write_pidfile(pidfile):\n    \"\"\" Write file with current process ID.\n    \"\"\"\n    pid = str(os.getpid())\n    handle = open(pidfile, 'w')\n    try:\n        handle.write(\"%s\\n\" % pid)\n    finally:\n        handle.close()", "title": ""}
{"_id": "d3790", "text": "def random_color(_min=MIN_COLOR, _max=MAX_COLOR):\n    \"\"\"Returns a random color between min and max.\"\"\"\n    return color(random.randint(_min, _max))", "title": ""}
{"_id": "d3791", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d3792", "text": "def SegmentMin(a, ids):\n    \"\"\"\n    Segmented min op.\n    \"\"\"\n    func = lambda idxs: np.amin(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d3793", "text": "def save_dot(self, fd):\n        \"\"\" Saves a representation of the case in the Graphviz DOT language.\n        \"\"\"\n        from pylon.io import DotWriter\n        DotWriter(self).write(fd)", "title": ""}
{"_id": "d3794", "text": "def _prepare_proxy(self, conn):\n        \"\"\"\n        Establish tunnel connection early, because otherwise httplib\n        would improperly set Host: header to proxy's IP:port.\n        \"\"\"\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n        conn.connect()", "title": ""}
{"_id": "d3795", "text": "def cleanup_nodes(doc):\n    \"\"\"\n    Remove text nodes containing only whitespace\n    \"\"\"\n    for node in doc.documentElement.childNodes:\n        if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():\n            doc.documentElement.removeChild(node)\n    return doc", "title": ""}
{"_id": "d3796", "text": "def mock_decorator(*args, **kwargs):\n    \"\"\"Mocked decorator, needed in the case we need to mock a decorator\"\"\"\n    def _called_decorator(dec_func):\n        @wraps(dec_func)\n        def _decorator(*args, **kwargs):\n            return dec_func()\n        return _decorator\n    return _called_decorator", "title": ""}
{"_id": "d3797", "text": "def __get_xml_text(root):\n    \"\"\" Return the text for the given root node (xml.dom.minidom). \"\"\"\n    txt = \"\"\n    for e in root.childNodes:\n        if (e.nodeType == e.TEXT_NODE):\n            txt += e.data\n    return txt", "title": ""}
{"_id": "d3798", "text": "def cat_acc(y_true, y_pred):\n    \"\"\"Categorical accuracy\n    \"\"\"\n    return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))", "title": ""}
{"_id": "d3799", "text": "def _xxrange(self, start, end, step_count):\n        \"\"\"Generate n values between start and end.\"\"\"\n        _step = (end - start) / float(step_count)\n        return (start + (i * _step) for i in xrange(int(step_count)))", "title": ""}
{"_id": "d3800", "text": "def forceupdate(self, *args, **kw):\n        \"\"\"Like a bulk :meth:`forceput`.\"\"\"\n        self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)", "title": ""}
{"_id": "d3801", "text": "def load_yaml(filepath):\n    \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n    with open(filepath) as f:\n        txt = f.read()\n    return yaml.load(txt)", "title": ""}
{"_id": "d3802", "text": "def start_of_month(val):\n    \"\"\"\n    Return a new datetime.datetime object with values that represent\n    a start of a month.\n    :param val: Date to ...\n    :type val: datetime.datetime | datetime.date\n    :rtype: datetime.datetime\n    \"\"\"\n    if type(val) == date:\n        val = datetime.fromordinal(val.toordinal())\n    return start_of_day(val).replace(day=1)", "title": ""}
{"_id": "d3803", "text": "def chunks(iterable, chunk):\n    \"\"\"Yield successive n-sized chunks from an iterable.\"\"\"\n    for i in range(0, len(iterable), chunk):\n        yield iterable[i:i + chunk]", "title": ""}
{"_id": "d3804", "text": "def most_common(items):\n    \"\"\"\n    Wanted functionality from Counters (new in Python 2.7).\n    \"\"\"\n    counts = {}\n    for i in items:\n        counts.setdefault(i, 0)\n        counts[i] += 1\n    return max(six.iteritems(counts), key=operator.itemgetter(1))", "title": ""}
{"_id": "d3805", "text": "def _run_asyncio(loop, zmq_context):\n    \"\"\"\n    Run asyncio (should be called in a thread) and close the loop and the zmq context when the thread ends\n    :param loop:\n    :param zmq_context:\n    :return:\n    \"\"\"\n    try:\n        asyncio.set_event_loop(loop)\n        loop.run_forever()\n    except:\n        pass\n    finally:\n        loop.close()\n        zmq_context.destroy(1000)", "title": ""}
{"_id": "d3806", "text": "def most_common(items):\n    \"\"\"\n    Wanted functionality from Counters (new in Python 2.7).\n    \"\"\"\n    counts = {}\n    for i in items:\n        counts.setdefault(i, 0)\n        counts[i] += 1\n    return max(six.iteritems(counts), key=operator.itemgetter(1))", "title": ""}
{"_id": "d3807", "text": "def _is_iterable(item):\n    \"\"\" Checks if an item is iterable (list, tuple, generator), but not string \"\"\"\n    return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)", "title": ""}
{"_id": "d3808", "text": "def _position():\n    \"\"\"Returns the current xy coordinates of the mouse cursor as a two-integer\n    tuple by calling the GetCursorPos() win32 function.\n\n    Returns:\n      (x, y) tuple of the current xy coordinates of the mouse cursor.\n    \"\"\"\n\n    cursor = POINT()\n    ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))\n    return (cursor.x, cursor.y)", "title": ""}
{"_id": "d3809", "text": "def _parse(self, date_str, format='%Y-%m-%d'):\n        \"\"\"\n        helper function for parsing FRED date string into datetime\n        \"\"\"\n        rv = pd.to_datetime(date_str, format=format)\n        if hasattr(rv, 'to_pydatetime'):\n            rv = rv.to_pydatetime()\n        return rv", "title": ""}
{"_id": "d3810", "text": "def normalize_text(text, line_len=80, indent=\"\"):\n    \"\"\"Wrap the text on the given line length.\"\"\"\n    return \"\\n\".join(\n        textwrap.wrap(\n            text, width=line_len, initial_indent=indent, subsequent_indent=indent\n        )\n    )", "title": ""}
{"_id": "d3811", "text": "def threadid(self):\n        \"\"\"\n        Current thread ident. If current thread is main thread then it returns ``None``.\n\n        :type: int or None\n        \"\"\"\n        current = self.thread.ident\n        main = get_main_thread()\n        if main is None:\n            return current\n        else:\n            return current if current != main.ident else None", "title": ""}
{"_id": "d3812", "text": "def format_vars(args):\n    \"\"\"Format the given vars in the form: 'flag=value'\"\"\"\n    variables = []\n    for key, value in args.items():\n        if value:\n            variables += ['{0}={1}'.format(key, value)]\n    return variables", "title": ""}
{"_id": "d3813", "text": "def remove_examples_all():\n    \"\"\"remove arduino/examples/all directory.\n\n    :rtype: None\n\n    \"\"\"\n    d = examples_all_dir()\n    if d.exists():\n        log.debug('remove %s', d)\n        d.rmtree()\n    else:\n        log.debug('nothing to remove: %s', d)", "title": ""}
{"_id": "d3814", "text": "def transform_from_rot_trans(R, t):\n    \"\"\"Transforation matrix from rotation matrix and translation vector.\"\"\"\n    R = R.reshape(3, 3)\n    t = t.reshape(3, 1)\n    return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))", "title": ""}
{"_id": "d3815", "text": "def is_iter_non_string(obj):\n    \"\"\"test if object is a list or tuple\"\"\"\n    if isinstance(obj, list) or isinstance(obj, tuple):\n        return True\n    return False", "title": ""}
{"_id": "d3816", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d3817", "text": "def trans_from_matrix(matrix):\n    \"\"\" Convert a vtk matrix to a numpy.ndarray \"\"\"\n    t = np.zeros((4, 4))\n    for i in range(4):\n        for j in range(4):\n            t[i, j] = matrix.GetElement(i, j)\n    return t", "title": ""}
{"_id": "d3818", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d3819", "text": "def get_file_extension_type(filename):\n    \"\"\"\n    Return the group associated to the file\n    :param filename:\n    :return: str\n    \"\"\"\n    ext = get_file_extension(filename)\n    if ext:\n        for name, group in EXTENSIONS.items():\n            if ext in group:\n                return name\n    return \"OTHER\"", "title": ""}
{"_id": "d3820", "text": "def inspect_cuda():\n    \"\"\" Return cuda device information and nvcc/cuda setup \"\"\"\n    nvcc_settings = nvcc_compiler_settings()\n    sysconfig.get_config_vars()\n    nvcc_compiler = ccompiler.new_compiler()\n    sysconfig.customize_compiler(nvcc_compiler)\n    customize_compiler_for_nvcc(nvcc_compiler, nvcc_settings)\n\n    output = inspect_cuda_version_and_devices(nvcc_compiler, nvcc_settings)\n\n    return json.loads(output), nvcc_settings", "title": ""}
{"_id": "d3821", "text": "def iteritems(data, **kwargs):\n    \"\"\"Iterate over dict items.\"\"\"\n    return iter(data.items(**kwargs)) if IS_PY3 else data.iteritems(**kwargs)", "title": ""}
{"_id": "d3822", "text": "def _array2cstr(arr):\n    \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())", "title": ""}
{"_id": "d3823", "text": "def default_static_path():\n    \"\"\"\n        Return the path to the javascript bundle\n    \"\"\"\n    fdir = os.path.dirname(__file__)\n    return os.path.abspath(os.path.join(fdir, '../assets/'))", "title": ""}
{"_id": "d3824", "text": "def list_add_capitalize(l):\n    \"\"\"\n    @type l: list\n    @return: list\n    \"\"\"\n    nl = []\n\n    for i in l:\n        nl.append(i)\n\n        if hasattr(i, \"capitalize\"):\n            nl.append(i.capitalize())\n\n    return list(set(nl))", "title": ""}
{"_id": "d3825", "text": "def random_id(size=8, chars=string.ascii_letters + string.digits):\n\t\"\"\"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.\n\t\"\"\"\n\treturn ''.join(random.choice(chars) for _ in range(size))", "title": ""}
{"_id": "d3826", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d3827", "text": "def threadid(self):\n        \"\"\"\n        Current thread ident. If current thread is main thread then it returns ``None``.\n\n        :type: int or None\n        \"\"\"\n        current = self.thread.ident\n        main = get_main_thread()\n        if main is None:\n            return current\n        else:\n            return current if current != main.ident else None", "title": ""}
{"_id": "d3828", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d3829", "text": "def get_best_encoding(stream):\n    \"\"\"Returns the default stream encoding if not found.\"\"\"\n    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n    if is_ascii_encoding(rv):\n        return 'utf-8'\n    return rv", "title": ""}
{"_id": "d3830", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d3831", "text": "def require_root(fn):\n    \"\"\"\n    Decorator to make sure, that user is root.\n    \"\"\"\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\n    return xex", "title": ""}
{"_id": "d3832", "text": "def normalize(self):\n        \"\"\" Normalize data. \"\"\"\n\n        if self.preprocessed_data.empty:\n            data = self.original_data\n        else:\n            data = self.preprocessed_data\n\n        data = pd.DataFrame(preprocessing.normalize(data), columns=data.columns, index=data.index)\n        self.preprocessed_data = data", "title": ""}
{"_id": "d3833", "text": "def m(name='', **kwargs):\n    \"\"\"\n    Print out memory usage at this point in time\n\n    http://docs.python.org/2/library/resource.html\n    http://stackoverflow.com/a/15448600/5006\n    http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended\n    \"\"\"\n    with Reflect.context(**kwargs) as r:\n        kwargs[\"name\"] = name\n        instance = M_CLASS(r, stream, **kwargs)\n        instance()", "title": ""}
{"_id": "d3834", "text": "def normalize(df, style = 'mean'):\n    \"\"\" Returns a normalized version of a DataFrame or Series\n    Parameters:\n    df - DataFrame or Series\n        The data to normalize\n    style - function or string, default 'mean'\n        The style to use when computing the norms. Takes 'mean' or 'minmax' to\n        do mean or min-max normalization respectively. User-defined functions that take\n        a pandas Series as input and return a normalized pandas Series are also accepted\n    \"\"\"\n    if style == 'mean':\n        df_mean,df_std = df.mean(),df.std()\n        return (df-df_mean)/df_std\n    elif style == 'minmax':\n        col_min,col_max = df.min(),df.max()\n        return (df-col_min)/(col_max-col_min)\n    else:\n        return style(df)", "title": ""}
{"_id": "d3835", "text": "def get_qapp():\n    \"\"\"Return an instance of QApplication. Creates one if neccessary.\n\n    :returns: a QApplication instance\n    :rtype: QApplication\n    :raises: None\n    \"\"\"\n    global app\n    app = QtGui.QApplication.instance()\n    if app is None:\n        app = QtGui.QApplication([], QtGui.QApplication.GuiClient)\n    return app", "title": ""}
{"_id": "d3836", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d3837", "text": "def column_names(self, table):\n      \"\"\"An iterable of column names, for a particular table or\n      view.\"\"\"\n\n      table_info = self.execute(\n        u'PRAGMA table_info(%s)' % quote(table))\n      return (column['name'] for column in table_info)", "title": ""}
{"_id": "d3838", "text": "def _normalize_abmn(abmn):\n    \"\"\"return a normalized version of abmn\n    \"\"\"\n    abmn_2d = np.atleast_2d(abmn)\n    abmn_normalized = np.hstack((\n        np.sort(abmn_2d[:, 0:2], axis=1),\n        np.sort(abmn_2d[:, 2:4], axis=1),\n    ))\n    return abmn_normalized", "title": ""}
{"_id": "d3839", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d3840", "text": "def _count_leading_whitespace(text):\n  \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n  idx = 0\n  for idx, char in enumerate(text):\n    if not char.isspace():\n      return idx\n  return idx + 1", "title": ""}
{"_id": "d3841", "text": "def __str__(self):\n        \"\"\"Executes self.function to convert LazyString instance to a real\n        str.\"\"\"\n        if not hasattr(self, '_str'):\n            self._str=self.function(*self.args, **self.kwargs)\n        return self._str", "title": ""}
{"_id": "d3842", "text": "def get_size(objects):\n    \"\"\"Compute the total size of all elements in objects.\"\"\"\n    res = 0\n    for o in objects:\n        try:\n            res += _getsizeof(o)\n        except AttributeError:\n            print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n    return res", "title": ""}
{"_id": "d3843", "text": "def to_string(s, encoding='utf-8'):\n    \"\"\"\n    Accept unicode(py2) or bytes(py3)\n\n    Returns:\n        py2 type: str\n        py3 type: str\n    \"\"\"\n    if six.PY2:\n        return s.encode(encoding)\n    if isinstance(s, bytes):\n        return s.decode(encoding)\n    return s", "title": ""}
{"_id": "d3844", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d3845", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d3846", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d3847", "text": "def format_line(data, linestyle):\n    \"\"\"Formats a list of elements using the given line style\"\"\"\n    return linestyle.begin + linestyle.sep.join(data) + linestyle.end", "title": ""}
{"_id": "d3848", "text": "def get_tweepy_auth(twitter_api_key,\n                    twitter_api_secret,\n                    twitter_access_token,\n                    twitter_access_token_secret):\n    \"\"\"Make a tweepy auth object\"\"\"\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", "title": ""}
{"_id": "d3849", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d3850", "text": "def aloha_to_html(html_source):\n    \"\"\"Converts HTML5 from Aloha to a more structured HTML5\"\"\"\n    xml = aloha_to_etree(html_source)\n    return etree.tostring(xml, pretty_print=True)", "title": ""}
{"_id": "d3851", "text": "def exit(self):\n        \"\"\"Handle interactive exit.\n\n        This method calls the ask_exit callback.\"\"\"\n        if self.confirm_exit:\n            if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):\n                self.ask_exit()\n        else:\n            self.ask_exit()", "title": ""}
{"_id": "d3852", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d3853", "text": "def __del__(self):\n        \"\"\"Cleanup the session if it was created here\"\"\"\n        if self._cleanup_session:\n            self._session.loop.run_until_complete(self._session.close())", "title": ""}
{"_id": "d3854", "text": "def get_just_date(self):\n        \"\"\"Parses just date from date-time\n\n        :return: Just day, month and year (setting hours to 00:00:00)\n        \"\"\"\n        return datetime.datetime(\n            self.date_time.year,\n            self.date_time.month,\n            self.date_time.day\n        )", "title": ""}
{"_id": "d3855", "text": "def format_screen(strng):\n    \"\"\"Format a string for screen printing.\n\n    This removes some latex-type format codes.\"\"\"\n    # Paragraph continue\n    par_re = re.compile(r'\\\\$',re.MULTILINE)\n    strng = par_re.sub('',strng)\n    return strng", "title": ""}
{"_id": "d3856", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d3857", "text": "def to_camel_case(snake_case_name):\n    \"\"\"\n    Converts snake_cased_names to CamelCaseNames.\n\n    :param snake_case_name: The name you'd like to convert from.\n    :type snake_case_name: string\n\n    :returns: A converted string\n    :rtype: string\n    \"\"\"\n    bits = snake_case_name.split('_')\n    return ''.join([bit.capitalize() for bit in bits])", "title": ""}
{"_id": "d3858", "text": "def load_image(fname):\n    \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n    with open(fname, \"rb\") as f:\n        i = Image.open(fname)\n        #i.load()\n        return i", "title": ""}
{"_id": "d3859", "text": "def random_choice(sequence):\n    \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n    return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)", "title": ""}
{"_id": "d3860", "text": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "title": ""}
{"_id": "d3861", "text": "def other_ind(self):\n        \"\"\"last row or column of square A\"\"\"\n        return np.full(self.n_min, self.size - 1, dtype=np.int)", "title": ""}
{"_id": "d3862", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d3863", "text": "def __getitem__(self, key):\n        \"\"\"Returns a new PRDD of elements from that key.\"\"\"\n        return self.from_rdd(self._rdd.map(lambda x: x[key]))", "title": ""}
{"_id": "d3864", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d3865", "text": "def load_file_to_base64_str(f_path):\n    \"\"\"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.\n    \"\"\"\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", "title": ""}
{"_id": "d3866", "text": "def url_to_image(url, flag=cv2.IMREAD_COLOR):\n    \"\"\" download the image, convert it to a NumPy array, and then read\n    it into OpenCV format \"\"\"\n    resp = urlopen(url)\n    image = np.asarray(bytearray(resp.read()), dtype=\"uint8\")\n    image = cv2.imdecode(image, flag)\n    return image", "title": ""}
{"_id": "d3867", "text": "def visible_area(self):\n        \"\"\"\n        Calculated like in the official client.\n        Returns (top_left, bottom_right).\n        \"\"\"\n        # looks like zeach has a nice big screen\n        half_viewport = Vec(1920, 1080) / 2 / self.scale\n        top_left = self.world.center - half_viewport\n        bottom_right = self.world.center + half_viewport\n        return top_left, bottom_right", "title": ""}
{"_id": "d3868", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d3869", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d3870", "text": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "title": ""}
{"_id": "d3871", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d3872", "text": "def fit_gaussian(x, y, yerr, p0):\n    \"\"\" Fit a Gaussian to the data \"\"\"\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", "title": ""}
{"_id": "d3873", "text": "def last(self):\n        \"\"\"Get the last object in file.\"\"\"\n        # End of file\n        self.__file.seek(0, 2)\n\n        # Get the last struct\n        data = self.get(self.length - 1)\n\n        return data", "title": ""}
{"_id": "d3874", "text": "def resize_image_with_crop_or_pad(img, target_height, target_width):\n    \"\"\"\n    Crops and/or pads an image to a target width and height.\n\n    Resizes an image to a target width and height by either cropping the image or padding it with zeros.\n\n    NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom right)\n\n    :param img: Numpy array representing the image.\n    :param target_height: Target height.\n    :param target_width: Target width.\n    :return: The cropped and padded image.\n    \"\"\"\n    h, w = target_height, target_width\n    max_h, max_w, c = img.shape\n\n    # crop\n    img = crop_center(img, min(max_h, h), min(max_w, w))\n\n    # pad\n    padded_img = np.zeros(shape=(h, w, c), dtype=img.dtype)\n    padded_img[:img.shape[0], :img.shape[1], :img.shape[2]] = img\n\n    return padded_img", "title": ""}
{"_id": "d3875", "text": "def load_from_file(cls, file_path: str):\n        \"\"\" Read and reconstruct the data from a JSON file. \"\"\"\n        with open(file_path, \"r\") as f:\n            data = json.load(f)\n            item = cls.decode(data=data)\n        return item", "title": ""}
{"_id": "d3876", "text": "def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to be padded.\n\n        Returns:\n            PIL Image: Padded image.\n        \"\"\"\n        return F.pad(img, self.padding, self.fill, self.padding_mode)", "title": ""}
{"_id": "d3877", "text": "def rAsciiLine(ifile):\n    \"\"\"Returns the next non-blank line in an ASCII file.\"\"\"\n\n    _line = ifile.readline().strip()\n    while len(_line) == 0:\n        _line = ifile.readline().strip()\n    return _line", "title": ""}
{"_id": "d3878", "text": "def filter_query(s):\n    \"\"\"\n    Filters given query with the below regex\n    and returns lists of quoted and unquoted strings\n    \"\"\"\n    matches = re.findall(r'(?:\"([^\"]*)\")|([^\"]*)', s)\n    result_quoted = [t[0].strip() for t in matches if t[0]]\n    result_unquoted = [t[1].strip() for t in matches if t[1]]\n    return result_quoted, result_unquoted", "title": ""}
{"_id": "d3879", "text": "def lambda_from_file(python_file):\n    \"\"\"\n    Reads a python file and returns a awslambda.Code object\n    :param python_file:\n    :return:\n    \"\"\"\n    lambda_function = []\n    with open(python_file, 'r') as f:\n        lambda_function.extend(f.read().splitlines())\n\n    return awslambda.Code(ZipFile=(Join('\\n', lambda_function)))", "title": ""}
{"_id": "d3880", "text": "def list_formatter(handler, item, value):\n    \"\"\"Format list.\"\"\"\n    return u', '.join(str(v) for v in value)", "title": ""}
{"_id": "d3881", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d3882", "text": "def Proxy(f):\n  \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n\n  return Wrapped", "title": ""}
{"_id": "d3883", "text": "def read_large_int(self, bits, signed=True):\n        \"\"\"Reads a n-bits long integer value.\"\"\"\n        return int.from_bytes(\n            self.read(bits // 8), byteorder='little', signed=signed)", "title": ""}
{"_id": "d3884", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d3885", "text": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "title": ""}
{"_id": "d3886", "text": "def parse_form(self, req, name, field):\n        \"\"\"Pull a form value from the request.\"\"\"\n        return get_value(req.body_arguments, name, field)", "title": ""}
{"_id": "d3887", "text": "def get_starting_chunk(filename, length=1024):\n    \"\"\"\n    :param filename: File to open and get the first little chunk of.\n    :param length: Number of bytes to read, default 1024.\n    :returns: Starting chunk of bytes.\n    \"\"\"\n    # Ensure we open the file in binary mode\n    with open(filename, 'rb') as f:\n        chunk = f.read(length)\n        return chunk", "title": ""}
{"_id": "d3888", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d3889", "text": "def standard_input():\n    \"\"\"Generator that yields lines from standard input.\"\"\"\n    with click.get_text_stream(\"stdin\") as stdin:\n        while stdin.readable():\n            line = stdin.readline()\n            if line:\n                yield line.strip().encode(\"utf-8\")", "title": ""}
{"_id": "d3890", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d3891", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d3892", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d3893", "text": "def mouse_move_event(self, event):\n        \"\"\"\n        Forward mouse cursor position events to the example\n        \"\"\"\n        self.example.mouse_position_event(event.x(), event.y())", "title": ""}
{"_id": "d3894", "text": "def cor(y_true, y_pred):\n    \"\"\"Compute Pearson correlation coefficient.\n    \"\"\"\n    y_true, y_pred = _mask_nan(y_true, y_pred)\n    return np.corrcoef(y_true, y_pred)[0, 1]", "title": ""}
{"_id": "d3895", "text": "def flat_list(lst):\n    \"\"\"This function flatten given nested list.\n    Argument:\n        nested list\n    Returns:\n        flat list\n    \"\"\"\n    if isinstance(lst, list):\n        for item in lst:\n            for i in flat_list(item):\n                yield i\n    else:\n        yield lst", "title": ""}
{"_id": "d3896", "text": "def log_magnitude_spectrum(frames):\n    \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))", "title": ""}
{"_id": "d3897", "text": "def get(self, key):  \n        \"\"\" get a set of keys from redis \"\"\"\n        res = self.connection.get(key)\n        print(res)\n        return res", "title": ""}
{"_id": "d3898", "text": "def multi_pop(d, *args):\n    \"\"\" pops multiple keys off a dict like object \"\"\"\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval", "title": ""}
{"_id": "d3899", "text": "def _ReturnConnection(self):\n\t\t\"\"\"\n\t\tReturns a connection back to the pool\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 9/7/2008\n\t\t\"\"\"\n\t\tif self.conn is not None:\n\t\t\tif self.connInfo.commitOnEnd is True or self.commitOnEnd is True:\n\t\t\t\tself.conn.Commit()\n\t\t\t\t\t\n\t\t\tPool().returnConnection(self.conn)\n\t\t\tself.conn = None", "title": ""}
{"_id": "d3900", "text": "def multi_pop(d, *args):\n    \"\"\" pops multiple keys off a dict like object \"\"\"\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval", "title": ""}
{"_id": "d3901", "text": "def from_url(url, db=None, **kwargs):\n    \"\"\"\n    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.\n    \"\"\"\n    from redis.client import Redis\n    return Redis.from_url(url, db, **kwargs)", "title": ""}
{"_id": "d3902", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d3903", "text": "def __setitem__(self, field, value):\n        \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n        return self._client.hset(self.key_prefix, field, self._dumps(value))", "title": ""}
{"_id": "d3904", "text": "def parse_prefix(identifier):\n    \"\"\"\n    Parse identifier such as a|c|le|d|li|re|or|AT4G00480.1 and return\n    tuple of prefix string (separated at '|') and suffix (AGI identifier)\n    \"\"\"\n    pf, id = (), identifier\n    if \"|\" in identifier:\n        pf, id = tuple(identifier.split('|')[:-1]), identifier.split('|')[-1]\n\n    return pf, id", "title": ""}
{"_id": "d3905", "text": "def resize_by_area(img, size):\n  \"\"\"image resize function used by quite a few image problems.\"\"\"\n  return tf.to_int64(\n      tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))", "title": ""}
{"_id": "d3906", "text": "def ordered_yaml_dump(data, stream=None, Dumper=None, **kwds):\n    \"\"\"Dumps the stream from an OrderedDict.\n    Taken from\n\n    http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-\n    mappings-as-ordereddicts\"\"\"\n    Dumper = Dumper or yaml.Dumper\n\n    class OrderedDumper(Dumper):\n        pass\n\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    return yaml.dump(data, stream, OrderedDumper, **kwds)", "title": ""}
{"_id": "d3907", "text": "def lines(input):\n    \"\"\"Remove comments and empty lines\"\"\"\n    for raw_line in input:\n        line = raw_line.strip()\n        if line and not line.startswith('#'):\n            yield strip_comments(line)", "title": ""}
{"_id": "d3908", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d3909", "text": "def to_dict(self):\n        \"\"\"Serialize representation of the table for local caching.\"\"\"\n        return {'schema': self.schema, 'name': self.name, 'columns': [col.to_dict() for col in self._columns],\n                'foreign_keys': self.foreign_keys.to_dict(), 'ref_keys': self.ref_keys.to_dict()}", "title": ""}
{"_id": "d3910", "text": "def replace_print(fileobj=sys.stderr):\n  \"\"\"Sys.out replacer, by default with stderr.\n\n  Use it like this:\n  with replace_print_with(fileobj):\n    print \"hello\"  # writes to the file\n  print \"done\"  # prints to stdout\n\n  Args:\n    fileobj: a file object to replace stdout.\n\n  Yields:\n    The printer.\n  \"\"\"\n  printer = _Printer(fileobj)\n\n  previous_stdout = sys.stdout\n  sys.stdout = printer\n  try:\n    yield printer\n  finally:\n    sys.stdout = previous_stdout", "title": ""}
{"_id": "d3911", "text": "def var_dump(*obs):\n\t\"\"\"\n\t  shows structured information of a object, list, tuple etc\n\t\"\"\"\n\ti = 0\n\tfor x in obs:\n\t\t\n\t\tstr = var_dump_output(x, 0, '  ', '\\n', True)\n\t\tprint (str.strip())\n\t\t\n\t\t#dump(x, 0, i, '', object)\n\t\ti += 1", "title": ""}
{"_id": "d3912", "text": "def camelcase_underscore(name):\n    \"\"\" Convert camelcase names to underscore \"\"\"\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()", "title": ""}
{"_id": "d3913", "text": "def first(series, order_by=None):\n    \"\"\"\n    Returns the first value of a series.\n\n    Args:\n        series (pandas.Series): column to summarize.\n\n    Kwargs:\n        order_by: a pandas.Series or list of series (can be symbolic) to order\n            the input series by before summarization.\n    \"\"\"\n\n    if order_by is not None:\n        series = order_series_by(series, order_by)\n    first_s = series.iloc[0]\n    return first_s", "title": ""}
{"_id": "d3914", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d3915", "text": "def cprint(string, fg=None, bg=None, end='\\n', target=sys.stdout):\n    \"\"\"Print a colored string to the target handle.\n\n    fg and bg specify foreground- and background colors, respectively. The\n    remaining keyword arguments are the same as for Python's built-in print\n    function. Colors are returned to their defaults before the function\n    returns.\n\n    \"\"\"\n    _color_manager.set_color(fg, bg)\n    target.write(string + end)\n    target.flush()  # Needed for Python 3.x\n    _color_manager.set_defaults()", "title": ""}
{"_id": "d3916", "text": "def _clean_str(self, s):\n        \"\"\" Returns a lowercase string with punctuation and bad chars removed\n        :param s: string to clean\n        \"\"\"\n        return s.translate(str.maketrans('', '', punctuation)).replace('\\u200b', \" \").strip().lower()", "title": ""}
{"_id": "d3917", "text": "def printc(cls, txt, color=colors.red):\n        \"\"\"Print in color.\"\"\"\n        print(cls.color_txt(txt, color))", "title": ""}
{"_id": "d3918", "text": "def __normalize_list(self, msg):\n        \"\"\"Split message to list by commas and trim whitespace.\"\"\"\n        if isinstance(msg, list):\n            msg = \"\".join(msg)\n        return list(map(lambda x: x.strip(), msg.split(\",\")))", "title": ""}
{"_id": "d3919", "text": "def Print(x, data, message, **kwargs):  # pylint: disable=invalid-name\n  \"\"\"Call tf.Print.\n\n  Args:\n    x: a Tensor.\n    data: a list of Tensor\n    message: a string\n    **kwargs: keyword arguments to tf.Print\n  Returns:\n    a Tensor which is identical in value to x\n  \"\"\"\n  return PrintOperation(x, data, message, **kwargs).outputs[0]", "title": ""}
{"_id": "d3920", "text": "def remove_dups(seq):\n    \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d3921", "text": "def csvpretty(csvfile: csvfile=sys.stdin):\n    \"\"\" Pretty print a CSV file. \"\"\"\n    shellish.tabulate(csv.reader(csvfile))", "title": ""}
{"_id": "d3922", "text": "def clean_py_files(path):\n    \"\"\"\n    Removes all .py files.\n\n    :param path: the path\n    :return: None\n    \"\"\"\n\n    for dirname, subdirlist, filelist in os.walk(path):\n\n        for f in filelist:\n            if f.endswith('py'):\n                os.remove(os.path.join(dirname, f))", "title": ""}
{"_id": "d3923", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d3924", "text": "def clean_whitespace(statement):\n    \"\"\"\n    Remove any consecutive whitespace characters from the statement text.\n    \"\"\"\n    import re\n\n    # Replace linebreaks and tabs with spaces\n    statement.text = statement.text.replace('\\n', ' ').replace('\\r', ' ').replace('\\t', ' ')\n\n    # Remove any leeding or trailing whitespace\n    statement.text = statement.text.strip()\n\n    # Remove consecutive spaces\n    statement.text = re.sub(' +', ' ', statement.text)\n\n    return statement", "title": ""}
{"_id": "d3925", "text": "def _to_base_type(self, msg):\n    \"\"\"Convert a Message value to a Model instance (entity).\"\"\"\n    ent = _message_to_entity(msg, self._modelclass)\n    ent.blob_ = self._protocol_impl.encode_message(msg)\n    return ent", "title": ""}
{"_id": "d3926", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d3927", "text": "def toJson(protoObject, indent=None):\n    \"\"\"\n    Serialises a protobuf object as json\n    \"\"\"\n    # Using the internal method because this way we can reformat the JSON\n    js = json_format.MessageToDict(protoObject, False)\n    return json.dumps(js, indent=indent)", "title": ""}
{"_id": "d3928", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d3929", "text": "def created_today(self):\n        \"\"\"Return True if created today.\"\"\"\n        if self.datetime.date() == datetime.today().date():\n            return True\n        return False", "title": ""}
{"_id": "d3930", "text": "def _clean_str(self, s):\n        \"\"\" Returns a lowercase string with punctuation and bad chars removed\n        :param s: string to clean\n        \"\"\"\n        return s.translate(str.maketrans('', '', punctuation)).replace('\\u200b', \" \").strip().lower()", "title": ""}
{"_id": "d3931", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d3932", "text": "def purge_duplicates(list_in):\n    \"\"\"Remove duplicates from list while preserving order.\n\n    Parameters\n    ----------\n    list_in: Iterable\n\n    Returns\n    -------\n    list\n        List of first occurences in order\n    \"\"\"\n    _list = []\n    for item in list_in:\n        if item not in _list:\n            _list.append(item)\n    return _list", "title": ""}
{"_id": "d3933", "text": "def is_string(obj):\n    \"\"\"Is this a string.\n\n    :param object obj:\n    :rtype: bool\n    \"\"\"\n    if PYTHON3:\n        str_type = (bytes, str)\n    else:\n        str_type = (bytes, str, unicode)\n    return isinstance(obj, str_type)", "title": ""}
{"_id": "d3934", "text": "def strip_xml_namespace(root):\n    \"\"\"Strip out namespace data from an ElementTree.\n\n    This function is recursive and will traverse all\n    subnodes to the root element\n\n    @param root: the root element\n\n    @return: the same root element, minus namespace\n    \"\"\"\n    try:\n        root.tag = root.tag.split('}')[1]\n    except IndexError:\n        pass\n\n    for element in root.getchildren():\n        strip_xml_namespace(element)", "title": ""}
{"_id": "d3935", "text": "def filter_(stream_spec, filter_name, *args, **kwargs):\n    \"\"\"Alternate name for ``filter``, so as to not collide with the\n    built-in python ``filter`` operator.\n    \"\"\"\n    return filter(stream_spec, filter_name, *args, **kwargs)", "title": ""}
{"_id": "d3936", "text": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "title": ""}
{"_id": "d3937", "text": "def first_sunday(self, year, month):\n        \"\"\"Get the first sunday of a month.\"\"\"\n        date = datetime(year, month, 1, 0)\n        days_until_sunday = 6 - date.weekday()\n\n        return date + timedelta(days=days_until_sunday)", "title": ""}
{"_id": "d3938", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d3939", "text": "def bin_to_int(string):\n    \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n    if isinstance(string, str):\n        return struct.unpack(\"b\", string)[0]\n    else:\n        return struct.unpack(\"b\", bytes([string]))[0]", "title": ""}
{"_id": "d3940", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d3941", "text": "def time_func(func, name, *args, **kwargs):\n    \"\"\" call a func with args and kwargs, print name of func and how\n    long it took. \"\"\"\n    tic = time.time()\n    out = func(*args, **kwargs)\n    toc = time.time()\n    print('%s took %0.2f seconds' % (name, toc - tic))\n    return out", "title": ""}
{"_id": "d3942", "text": "def get_unique_indices(df, axis=1):\n    \"\"\"\n\n    :param df:\n    :param axis:\n    :return:\n    \"\"\"\n    return dict(zip(df.columns.names, dif.columns.levels))", "title": ""}
{"_id": "d3943", "text": "def register_extension_class(ext, base, *args, **kwargs):\n    \"\"\"Instantiate the given extension class and register as a public attribute of the given base.\n\n    README: The expected protocol here is to instantiate the given extension and pass the base\n    object as the first positional argument, then unpack args and kwargs as additional arguments to\n    the extension's constructor.\n    \"\"\"\n    ext_instance = ext.plugin(base, *args, **kwargs)\n    setattr(base, ext.name.lstrip('_'), ext_instance)", "title": ""}
{"_id": "d3944", "text": "def lowstrip(term):\n    \"\"\"Convert to lowercase and strip spaces\"\"\"\n    term = re.sub('\\s+', ' ', term)\n    term = term.lower()\n    return term", "title": ""}
{"_id": "d3945", "text": "def validate_string(option, value):\n    \"\"\"Validates that 'value' is an instance of `basestring` for Python 2\n    or `str` for Python 3.\n    \"\"\"\n    if isinstance(value, string_type):\n        return value\n    raise TypeError(\"Wrong type for %s, value must be \"\n                    \"an instance of %s\" % (option, string_type.__name__))", "title": ""}
{"_id": "d3946", "text": "def clear_global(self):\n        \"\"\"Clear only any cached global data.\n\n        \"\"\"\n        vname = self.varname\n        logger.debug(f'global clearning {vname}')\n        if vname in globals():\n            logger.debug('removing global instance var: {}'.format(vname))\n            del globals()[vname]", "title": ""}
{"_id": "d3947", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d3948", "text": "def save_image(pdf_path, img_path, page_num):\n    \"\"\"\n\n    Creates images for a page of the input pdf document and saves it\n    at img_path.\n\n    :param pdf_path: path to pdf to create images for.\n    :param img_path: path where to save the images.\n    :param page_num: page number to create image from in the pdf file.\n    :return:\n    \"\"\"\n    pdf_img = Image(filename=\"{}[{}]\".format(pdf_path, page_num))\n    with pdf_img.convert(\"png\") as converted:\n        # Set white background.\n        converted.background_color = Color(\"white\")\n        converted.alpha_channel = \"remove\"\n        converted.save(filename=img_path)", "title": ""}
{"_id": "d3949", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d3950", "text": "def remove_punctuation(text, exceptions=[]):\n    \"\"\"\n    Return a string with punctuation removed.\n\n    Parameters:\n        text (str): The text to remove punctuation from.\n        exceptions (list): List of symbols to keep in the given text.\n\n    Return:\n        str: The input text without the punctuation.\n    \"\"\"\n\n    all_but = [\n        r'\\w',\n        r'\\s'\n    ]\n\n    all_but.extend(exceptions)\n\n    pattern = '[^{}]'.format(''.join(all_but))\n\n    return re.sub(pattern, '', text)", "title": ""}
{"_id": "d3951", "text": "def __init__(self, master=None, compound=tk.RIGHT, autohidescrollbar=True, **kwargs):\n        \"\"\"\n        Create a Listbox with a vertical scrollbar.\n\n        :param master: master widget\n        :type master: widget\n        :param compound: side for the Scrollbar to be on (:obj:`tk.LEFT` or :obj:`tk.RIGHT`)\n        :type compound: str\n        :param autohidescrollbar: whether to use an :class:`~ttkwidgets.AutoHideScrollbar` or a :class:`ttk.Scrollbar`\n        :type autohidescrollbar: bool\n        :param kwargs: keyword arguments passed on to the :class:`tk.Listbox` initializer\n        \"\"\"\n        ttk.Frame.__init__(self, master)\n        self.columnconfigure(1, weight=1)\n        self.rowconfigure(0, weight=1)\n        self.listbox = tk.Listbox(self, **kwargs)\n        if autohidescrollbar:\n            self.scrollbar = AutoHideScrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n        else:\n            self.scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n        self.config_listbox(yscrollcommand=self.scrollbar.set)\n        if compound is not tk.LEFT and compound is not tk.RIGHT:\n            raise ValueError(\"Invalid compound value passed: {0}\".format(compound))\n        self.__compound = compound\n        self._grid_widgets()", "title": ""}
{"_id": "d3952", "text": "def draw_image(self, ax, image):\n        \"\"\"Process a matplotlib image object and call renderer.draw_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)", "title": ""}
{"_id": "d3953", "text": "def localize(dt):\n    \"\"\"Localize a datetime object to local time.\"\"\"\n    if dt.tzinfo is UTC:\n        return (dt + LOCAL_UTC_OFFSET).replace(tzinfo=None)\n    # No TZ info so not going to assume anything, return as-is.\n    return dt", "title": ""}
{"_id": "d3954", "text": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n    \"\"\"Clean a pandas dataframe by:\n        1. Filling empty values with Nan\n        2. Dropping columns with all empty values\n\n    Args:\n        df: Pandas DataFrame\n        fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n        drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n    Returns:\n        DataFrame: cleaned DataFrame\n\n    \"\"\"\n    if fill_nan:\n        df = df.fillna(value=np.nan)\n    if drop_empty_columns:\n        df = df.dropna(axis=1, how='all')\n    return df.sort_index()", "title": ""}
{"_id": "d3955", "text": "def pop_all(self):\n        \"\"\"\n        NON-BLOCKING POP ALL IN QUEUE, IF ANY\n        \"\"\"\n        with self.lock:\n            output = list(self.queue)\n            self.queue.clear()\n\n        return output", "title": ""}
{"_id": "d3956", "text": "def join(mapping, bind, values):\n    \"\"\" Merge all the strings. Put space between them. \"\"\"\n    return [' '.join([six.text_type(v) for v in values if v is not None])]", "title": ""}
{"_id": "d3957", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d3958", "text": "def _replace_docstring_header(paragraph):\n    \"\"\"Process NumPy-like function docstrings.\"\"\"\n\n    # Replace Markdown headers in docstrings with light headers in bold.\n    paragraph = re.sub(_docstring_header_pattern,\n                       r'*\\1*',\n                       paragraph,\n                       )\n\n    paragraph = re.sub(_docstring_parameters_pattern,\n                       r'\\n* `\\1` (\\2)\\n',\n                       paragraph,\n                       )\n\n    return paragraph", "title": ""}
{"_id": "d3959", "text": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "title": ""}
{"_id": "d3960", "text": "def raise_(exception=ABSENT, *args, **kwargs):\n    \"\"\"Raise (or re-raises) an exception.\n\n    :param exception: Exception object to raise, or an exception class.\n                      In the latter case, remaining arguments are passed\n                      to the exception's constructor.\n                      If omitted, the currently handled exception is re-raised.\n    \"\"\"\n    if exception is ABSENT:\n        raise\n    else:\n        if inspect.isclass(exception):\n            raise exception(*args, **kwargs)\n        else:\n            if args or kwargs:\n                raise TypeError(\"can't pass arguments along with \"\n                                \"exception object to raise_()\")\n            raise exception", "title": ""}
{"_id": "d3961", "text": "async def _send_plain_text(self, request: Request, stack: Stack):\n        \"\"\"\n        Sends plain text using `_send_text()`.\n        \"\"\"\n\n        await self._send_text(request, stack, None)", "title": ""}
{"_id": "d3962", "text": "def underscore(text):\n    \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n    return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()", "title": ""}
{"_id": "d3963", "text": "def from_traceback(cls, tb):\n        \"\"\" Construct a Bytecode from the given traceback \"\"\"\n        while tb.tb_next:\n            tb = tb.tb_next\n        return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)", "title": ""}
{"_id": "d3964", "text": "def camel_to_underscore(string):\n    \"\"\"Convert camelcase to lowercase and underscore.\n\n    Recipe from http://stackoverflow.com/a/1176023\n\n    Args:\n        string (str): The string to convert.\n\n    Returns:\n        str: The converted string.\n    \"\"\"\n    string = FIRST_CAP_RE.sub(r'\\1_\\2', string)\n    return ALL_CAP_RE.sub(r'\\1_\\2', string).lower()", "title": ""}
{"_id": "d3965", "text": "def compute(args):\n    x, y, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot(x, y, params)", "title": ""}
{"_id": "d3966", "text": "def python_mime(fn):\n    \"\"\"\n    Decorator, which adds correct MIME type for python source to the decorated\n    bottle API function.\n    \"\"\"\n    @wraps(fn)\n    def python_mime_decorator(*args, **kwargs):\n        response.content_type = \"text/x-python\"\n\n        return fn(*args, **kwargs)\n\n    return python_mime_decorator", "title": ""}
{"_id": "d3967", "text": "def list(self):\n        \"\"\"position in 3d space\"\"\"\n        return [self._pos3d.x, self._pos3d.y, self._pos3d.z]", "title": ""}
{"_id": "d3968", "text": "def _scale_shape(dshape, scale = (1,1,1)):\n    \"\"\"returns the shape after scaling (should be the same as ndimage.zoom\"\"\"\n    nshape = np.round(np.array(dshape) * np.array(scale))\n    return tuple(nshape.astype(np.int))", "title": ""}
{"_id": "d3969", "text": "def get_value(key, obj, default=missing):\n    \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n    if isinstance(key, int):\n        return _get_value_for_key(key, obj, default)\n    return _get_value_for_keys(key.split('.'), obj, default)", "title": ""}
{"_id": "d3970", "text": "def index(self, value):\n\t\t\"\"\"\n\t\tReturn the smallest index of the row(s) with this column\n\t\tequal to value.\n\t\t\"\"\"\n\t\tfor i in xrange(len(self.parentNode)):\n\t\t\tif getattr(self.parentNode[i], self.Name) == value:\n\t\t\t\treturn i\n\t\traise ValueError(value)", "title": ""}
{"_id": "d3971", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d3972", "text": "def get_package_info(package):\n    \"\"\"Gets the PyPI information for a given package.\"\"\"\n    url = 'https://pypi.python.org/pypi/{}/json'.format(package)\n    r = requests.get(url)\n    r.raise_for_status()\n    return r.json()", "title": ""}
{"_id": "d3973", "text": "def setdefault(obj, field, default):\n    \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n    setattr(obj, field, getattr(obj, field, default))", "title": ""}
{"_id": "d3974", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d3975", "text": "def _add(self, codeobj):\n        \"\"\"Add a child (variable) to this object.\"\"\"\n        assert isinstance(codeobj, CodeVariable)\n        self.variables.append(codeobj)", "title": ""}
{"_id": "d3976", "text": "def keys(self):\n        \"\"\"Return a list of all keys in the dictionary.\n\n        Returns:\n            list of str: [key1,key2,...,keyN]\n        \"\"\"\n        all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]\n        return all_keys", "title": ""}
{"_id": "d3977", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d3978", "text": "def make_key(observer):\n        \"\"\"Construct a unique, hashable, immutable key for an observer.\"\"\"\n\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", "title": ""}
{"_id": "d3979", "text": "def update_dict(obj, dict, attributes):\n    \"\"\"Update dict with fields from obj.attributes.\n\n    :param obj: the object updated into dict\n    :param dict: the result dictionary\n    :param attributes: a list of attributes belonging to obj\n    \"\"\"\n    for attribute in attributes:\n        if hasattr(obj, attribute) and getattr(obj, attribute) is not None:\n            dict[attribute] = getattr(obj, attribute)", "title": ""}
{"_id": "d3980", "text": "def _count_leading_whitespace(text):\n  \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n  idx = 0\n  for idx, char in enumerate(text):\n    if not char.isspace():\n      return idx\n  return idx + 1", "title": ""}
{"_id": "d3981", "text": "def get_attr(self, method_name):\n        \"\"\"Get attribute from the target object\"\"\"\n        return self.attrs.get(method_name) or self.get_callable_attr(method_name)", "title": ""}
{"_id": "d3982", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d3983", "text": "def add_blank_row(self, label):\n        \"\"\"\n        Add a blank row with only an index value to self.df.\n        This is done inplace.\n        \"\"\"\n        col_labels = self.df.columns\n        blank_item = pd.Series({}, index=col_labels, name=label)\n        # use .loc to add in place (append won't do that)\n        self.df.loc[blank_item.name] = blank_item\n        return self.df", "title": ""}
{"_id": "d3984", "text": "def get_attribute_name_id(attr):\n    \"\"\"\n    Return the attribute name identifier\n    \"\"\"\n    return attr.value.id if isinstance(attr.value, ast.Name) else None", "title": ""}
{"_id": "d3985", "text": "def set_property(self, key, value):\n        \"\"\"\n        Update only one property in the dict\n        \"\"\"\n        self.properties[key] = value\n        self.sync_properties()", "title": ""}
{"_id": "d3986", "text": "def _shape(self):\n        \"\"\"Return the tensor shape of the matrix operator\"\"\"\n        return tuple(reversed(self.output_dims())) + tuple(\n            reversed(self.input_dims()))", "title": ""}
{"_id": "d3987", "text": "def set_json_item(key, value):\n    \"\"\" manipulate json data on the fly\n    \"\"\"\n    data = get_json()\n    data[key] = value\n\n    request = get_request()\n    request[\"BODY\"] = json.dumps(data)", "title": ""}
{"_id": "d3988", "text": "def cfloat64_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\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')", "title": ""}
{"_id": "d3989", "text": "def sub(name, func,**kwarg):\n    \"\"\" Add subparser\n\n    \"\"\"\n    sp = subparsers.add_parser(name, **kwarg)\n    sp.set_defaults(func=func)\n    sp.arg = sp.add_argument\n    return sp", "title": ""}
{"_id": "d3990", "text": "def gray2bgr(img):\n    \"\"\"Convert a grayscale image to BGR image.\n\n    Args:\n        img (ndarray or str): The input image.\n\n    Returns:\n        ndarray: The converted BGR image.\n    \"\"\"\n    img = img[..., None] if img.ndim == 2 else img\n    out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n    return out_img", "title": ""}
{"_id": "d3991", "text": "def add_text_to_image(fname, txt, opFilename):\n    \"\"\" convert an image by adding text \"\"\"\n    ft = ImageFont.load(\"T://user//dev//src//python//_AS_LIB//timR24.pil\")\n    #wh = ft.getsize(txt)\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)", "title": ""}
{"_id": "d3992", "text": "def roc_auc(y_true, y_score):\n    \"\"\"\n    Returns are under the ROC curve\n    \"\"\"\n    notnull = ~np.isnan(y_true)\n    fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true[notnull], y_score[notnull])\n    return sklearn.metrics.auc(fpr, tpr)", "title": ""}
{"_id": "d3993", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d3994", "text": "def rotateImage(image, angle):\n    \"\"\"\n        rotates a 2d array to a multiple of 90 deg.\n        0 = default\n        1 = 90 deg. cw\n        2 = 180 deg.\n        3 = 90 deg. ccw\n    \"\"\"\n    image = [list(row) for row in image]\n\n    for n in range(angle % 4):\n        image = list(zip(*image[::-1]))\n\n    return image", "title": ""}
{"_id": "d3995", "text": "def vec_angle(a, b):\n    \"\"\"\n    Calculate angle between two vectors\n    \"\"\"\n    cosang = np.dot(a, b)\n    sinang = fast_norm(np.cross(a, b))\n    return np.arctan2(sinang, cosang)", "title": ""}
{"_id": "d3996", "text": "def similarity_transformation(rot, mat):\n    \"\"\" R x M x R^-1 \"\"\"\n    return np.dot(rot, np.dot(mat, np.linalg.inv(rot)))", "title": ""}
{"_id": "d3997", "text": "def _iter_response(self, url, params=None):\n        \"\"\"Return an enumerable that iterates through a multi-page API request\"\"\"\n        if params is None:\n            params = {}\n        params['page_number'] = 1\n\n        # Last page lists itself as next page\n        while True:\n            response = self._request(url, params)\n\n            for item in response['result_data']:\n                yield item\n\n            # Last page lists itself as next page\n            if response['service_meta']['next_page_number'] == params['page_number']:\n                break\n\n            params['page_number'] += 1", "title": ""}
{"_id": "d3998", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d3999", "text": "def fetch_token(self, **kwargs):\n        \"\"\"Exchange a code (and 'state' token) for a bearer token\"\"\"\n        return super(AsanaOAuth2Session, self).fetch_token(self.token_url, client_secret=self.client_secret, **kwargs)", "title": ""}
{"_id": "d4000", "text": "def lint(args):\n    \"\"\"Run lint checks using flake8.\"\"\"\n    application = get_current_application()\n    if not args:\n        args = [application.name, 'tests']\n    args = ['flake8'] + list(args)\n    run.main(args, standalone_mode=False)", "title": ""}
{"_id": "d4001", "text": "def contains_extractor(document):\n    \"\"\"A basic document feature extractor that returns a dict of words that the\n    document contains.\"\"\"\n    tokens = _get_document_tokens(document)\n    features = dict((u'contains({0})'.format(w), True) for w in tokens)\n    return features", "title": ""}
{"_id": "d4002", "text": "def _handle_shell(self,cfg_file,*args,**options):\n        \"\"\"Command 'supervisord shell' runs the interactive command shell.\"\"\"\n        args = (\"--interactive\",) + args\n        return supervisorctl.main((\"-c\",cfg_file) + args)", "title": ""}
{"_id": "d4003", "text": "def interpolate(table, field, fmt, **kwargs):\n    \"\"\"\n    Convenience function to interpolate all values in the given `field` using\n    the `fmt` string.\n\n    The ``where`` keyword argument can be given with a callable or expression\n    which is evaluated on each row and which should return True if the\n    conversion should be applied on that row, else False.\n\n    \"\"\"\n\n    conv = lambda v: fmt % v\n    return convert(table, field, conv, **kwargs)", "title": ""}
{"_id": "d4004", "text": "def execute_in_background(self):\n        \"\"\"Executes a (shell) command in the background\n\n        :return: the process' pid\n        \"\"\"\n        # http://stackoverflow.com/questions/1605520\n        args = shlex.split(self.cmd)\n        p = Popen(args)\n        return p.pid", "title": ""}
{"_id": "d4005", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d4006", "text": "def bash(filename):\n    \"\"\"Runs a bash script in the local directory\"\"\"\n    sys.stdout.flush()\n    subprocess.call(\"bash {}\".format(filename), shell=True)", "title": ""}
{"_id": "d4007", "text": "def to_lisp(o, keywordize_keys: bool = True):\n    \"\"\"Recursively convert Python collections into Lisp collections.\"\"\"\n    if not isinstance(o, (dict, frozenset, list, set, tuple)):\n        return o\n    else:  # pragma: no cover\n        return _to_lisp_backup(o, keywordize_keys=keywordize_keys)", "title": ""}
{"_id": "d4008", "text": "def movingaverage(arr, window):\n    \"\"\"\n    Calculates the moving average (\"rolling mean\") of an array\n    of a certain window size.\n    \"\"\"\n    m = np.ones(int(window)) / int(window)\n    return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')", "title": ""}
{"_id": "d4009", "text": "def rotateImage(img, angle):\n    \"\"\"\n\n    querries scipy.ndimage.rotate routine\n    :param img: image to be rotated\n    :param angle: angle to be rotated (radian)\n    :return: rotated image\n    \"\"\"\n    imgR = scipy.ndimage.rotate(img, angle, reshape=False)\n    return imgR", "title": ""}
{"_id": "d4010", "text": "def version_jar(self):\n\t\t\"\"\"\n\t\tSpecial case of version() when the executable is a JAR file.\n\t\t\"\"\"\n\t\tcmd = config.get_command('java')\n\t\tcmd.append('-jar')\n\t\tcmd += self.cmd\n\t\tself.version(cmd=cmd, path=self.cmd[0])", "title": ""}
{"_id": "d4011", "text": "def make_table_map(table, headers):\n    \"\"\"Create a function to map from rows with the structure of the headers to the structure of the table.\"\"\"\n\n    header_parts = {}\n    for i, h in enumerate(headers):\n        header_parts[h] = 'row[{}]'.format(i)\n\n    body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(c.name, 'None') for c in table.columns))\n    header_code = 'lambda row: [{}]'.format(\n        ','.join(header_parts.get(c.name, \"'{}'\".format(c.name)) for c in table.columns))\n\n    return eval(header_code), eval(body_code)", "title": ""}
{"_id": "d4012", "text": "def test(*args):\n    \"\"\"\n    Run unit tests.\n    \"\"\"\n    subprocess.call([\"py.test-2.7\"] + list(args))\n    subprocess.call([\"py.test-3.4\"] + list(args))", "title": ""}
{"_id": "d4013", "text": "def print_statements(self):\n        \"\"\"Print all INDRA Statements collected by the processors.\"\"\"\n        for i, stmt in enumerate(self.statements):\n            print(\"%s: %s\" % (i, stmt))", "title": ""}
{"_id": "d4014", "text": "def test(*args):\n    \"\"\"\n    Run unit tests.\n    \"\"\"\n    subprocess.call([\"py.test-2.7\"] + list(args))\n    subprocess.call([\"py.test-3.4\"] + list(args))", "title": ""}
{"_id": "d4015", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d4016", "text": "def download_file(bucket_name, path, target, sagemaker_session):\n    \"\"\"Download a Single File from S3 into a local path\n\n    Args:\n        bucket_name (str): S3 bucket name\n        path (str): file path within the bucket\n        target (str): destination directory for the downloaded file.\n        sagemaker_session (:class:`sagemaker.session.Session`): a sagemaker session to interact with S3.\n    \"\"\"\n    path = path.lstrip('/')\n    boto_session = sagemaker_session.boto_session\n\n    s3 = boto_session.resource('s3')\n    bucket = s3.Bucket(bucket_name)\n    bucket.download_file(path, target)", "title": ""}
{"_id": "d4017", "text": "def set_subparsers_args(self, *args, **kwargs):\n        \"\"\"\n        Sets args and kwargs that are passed when creating a subparsers group\n        in an argparse.ArgumentParser i.e. when calling\n        argparser.ArgumentParser.add_subparsers\n        \"\"\"\n        self.subparsers_args = args\n        self.subparsers_kwargs = kwargs", "title": ""}
{"_id": "d4018", "text": "def save_keras_definition(keras_model, path):\n    \"\"\"\n    Save a Keras model definition to JSON with given path\n    \"\"\"\n    model_json = keras_model.to_json()\n    with open(path, \"w\") as json_file:\n        json_file.write(model_json)", "title": ""}
{"_id": "d4019", "text": "def add_arguments(parser):\n    \"\"\"\n    adds arguments for the swap urls command\n    \"\"\"\n    parser.add_argument('-o', '--old-environment', help='Old environment name', required=True)\n    parser.add_argument('-n', '--new-environment', help='New environment name', required=True)", "title": ""}
{"_id": "d4020", "text": "def adapt_array(arr):\n    \"\"\"\n    Adapts a Numpy array into an ARRAY string to put into the database.\n\n    Parameters\n    ----------\n    arr: array\n        The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n    Returns\n    -------\n    ARRAY\n            The adapted array object\n\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr), out.seek(0)\n    return buffer(out.read())", "title": ""}
{"_id": "d4021", "text": "def main(args=sys.argv):\n    \"\"\"\n    main entry point for the jardiff CLI\n    \"\"\"\n\n    parser = create_optparser(args[0])\n    return cli(parser.parse_args(args[1:]))", "title": ""}
{"_id": "d4022", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d4023", "text": "def set_subparsers_args(self, *args, **kwargs):\n        \"\"\"\n        Sets args and kwargs that are passed when creating a subparsers group\n        in an argparse.ArgumentParser i.e. when calling\n        argparser.ArgumentParser.add_subparsers\n        \"\"\"\n        self.subparsers_args = args\n        self.subparsers_kwargs = kwargs", "title": ""}
{"_id": "d4024", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d4025", "text": "def ensure_iterable(inst):\n    \"\"\"\n    Wraps scalars or string types as a list, or returns the iterable instance.\n    \"\"\"\n    if isinstance(inst, string_types):\n        return [inst]\n    elif not isinstance(inst, collections.Iterable):\n        return [inst]\n    else:\n        return inst", "title": ""}
{"_id": "d4026", "text": "def sav_to_pandas_rpy2(input_file):\n    \"\"\"\n    SPSS .sav files to Pandas DataFrame through Rpy2\n\n    :param input_file: string\n\n    :return:\n    \"\"\"\n    import pandas.rpy.common as com\n\n    w = com.robj.r('foreign::read.spss(\"%s\", to.data.frame=TRUE)' % input_file)\n    return com.convert_robj(w)", "title": ""}
{"_id": "d4027", "text": "def tail(self, n=10):\n        \"\"\"\n        Get an SArray that contains the last n elements in the SArray.\n\n        Parameters\n        ----------\n        n : int\n            The number of elements to fetch\n\n        Returns\n        -------\n        out : SArray\n            A new SArray which contains the last n rows of the current SArray.\n        \"\"\"\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.tail(n))", "title": ""}
{"_id": "d4028", "text": "def write(url, content, **args):\n    \"\"\"Put an object into a ftps URL.\"\"\"\n    with FTPSResource(url, **args) as resource:\n        resource.write(content)", "title": ""}
{"_id": "d4029", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d4030", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d4031", "text": "def get_seconds_until_next_day(now=None):\n    \"\"\"\n    Returns the number of seconds until the next day (utc midnight). This is the long-term rate limit used by Strava.\n    :param now: A (utc) timestamp\n    :type now: arrow.arrow.Arrow\n    :return: the number of seconds until next day, as int\n    \"\"\"\n    if now is None:\n        now = arrow.utcnow()\n    return (now.ceil('day') - now).seconds", "title": ""}
{"_id": "d4032", "text": "def unfolding(tens, i):\n    \"\"\"Compute the i-th unfolding of a tensor.\"\"\"\n    return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1))", "title": ""}
{"_id": "d4033", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d4034", "text": "def cli_command_quit(self, msg):\n        \"\"\"\\\n        kills the child and exits\n        \"\"\"\n        if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:\n            self.sprocess.proc.kill()\n        else:\n            sys.exit(0)", "title": ""}
{"_id": "d4035", "text": "def assert_exactly_one_true(bool_list):\n    \"\"\"This method asserts that only one value of the provided list is True.\n\n    :param bool_list: List of booleans to check\n    :return: True if only one value is True, False otherwise\n    \"\"\"\n    assert isinstance(bool_list, list)\n    counter = 0\n    for item in bool_list:\n        if item:\n            counter += 1\n    return counter == 1", "title": ""}
{"_id": "d4036", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d4037", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d4038", "text": "async def repeat(ctx, times: int, content='repeating...'):\n    \"\"\"Repeats a message multiple times.\"\"\"\n    for i in range(times):\n        await ctx.send(content)", "title": ""}
{"_id": "d4039", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d4040", "text": "def _digits(minval, maxval):\n    \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n    if minval == maxval:\n        return 3\n    else:\n        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "title": ""}
{"_id": "d4041", "text": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "title": ""}
{"_id": "d4042", "text": "def generate_split_tsv_lines(fn, header):\n    \"\"\"Returns dicts with header-keys and psm statistic values\"\"\"\n    for line in generate_tsv_psms_line(fn):\n        yield {x: y for (x, y) in zip(header, line.strip().split('\\t'))}", "title": ""}
{"_id": "d4043", "text": "def asynchronous(function, event):\n    \"\"\"\n    Runs the function asynchronously taking care of exceptions.\n    \"\"\"\n    thread = Thread(target=synchronous, args=(function, event))\n    thread.daemon = True\n    thread.start()", "title": ""}
{"_id": "d4044", "text": "def paste(xsel=False):\n    \"\"\"Returns system clipboard contents.\"\"\"\n    selection = \"primary\" if xsel else \"clipboard\"\n    try:\n        return subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"utf-8\")\n    except OSError as why:\n        raise XclipNotFound", "title": ""}
{"_id": "d4045", "text": "def StringIO(*args, **kwargs):\n    \"\"\"StringIO constructor shim for the async wrapper.\"\"\"\n    raw = sync_io.StringIO(*args, **kwargs)\n    return AsyncStringIOWrapper(raw)", "title": ""}
{"_id": "d4046", "text": "def add_form_widget_attr(field, attr_name, attr_value, replace=0):\n    \"\"\"\n    Adds widget attributes to a bound form field.\n\n    This is helpful if you would like to add a certain class to all your forms\n    (i.e. `form-control` to all form fields when you are using Bootstrap)::\n\n        {% load libs_tags %}\n        {% for field in form.fields %}\n            {% add_form_widget_attr field 'class' 'form-control' as field_ %}\n            {{ field_ }}\n        {% endfor %}\n\n    The tag will check if the attr already exists and only append your value.\n    If you would like to replace existing attrs, set `replace=1`::\n\n        {% add_form_widget_attr field 'class' 'form-control' replace=1 as\n          field_ %}\n\n\n    \"\"\"\n    if not replace:\n        attr = field.field.widget.attrs.get(attr_name, '')\n        attr += force_text(attr_value)\n        field.field.widget.attrs[attr_name] = attr\n        return field\n    else:\n        field.field.widget.attrs[attr_name] = attr_value\n        return field", "title": ""}
{"_id": "d4047", "text": "def exit(exit_code=0):\n  r\"\"\"A function to support exiting from exit hooks.\n\n  Could also be used to exit from the calling scripts in a thread safe manner.\n  \"\"\"\n  core.processExitHooks()\n\n  if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook\n    sys.stderr.flush()\n    sys.stdout.flush()\n    os._exit(exit_code) #pylint: disable=W0212\n\n  sys.exit(exit_code)", "title": ""}
{"_id": "d4048", "text": "def add(self, value):\n        \"\"\"Add the element *value* to the set.\"\"\"\n        if value not in self._set:\n            self._set.add(value)\n            self._list.add(value)", "title": ""}
{"_id": "d4049", "text": "def clear_globals_reload_modules(self):\n        \"\"\"Clears globals and reloads modules\"\"\"\n\n        self.code_array.clear_globals()\n        self.code_array.reload_modules()\n\n        # Clear result cache\n        self.code_array.result_cache.clear()", "title": ""}
{"_id": "d4050", "text": "def filter_symlog(y, base=10.0):\n    \"\"\"Symmetrical logarithmic scale.\n\n    Optional arguments:\n\n    *base*:\n        The base of the logarithm.\n    \"\"\"\n    log_base = np.log(base)\n    sign = np.sign(y)\n    logs = np.log(np.abs(y) / log_base)\n    return sign * logs", "title": ""}
{"_id": "d4051", "text": "def fill_form(form, data):\n    \"\"\"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.\n    \"\"\"\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", "title": ""}
{"_id": "d4052", "text": "def __init__(self, interval, key):\n    \"\"\"Constructor. See class docstring for parameter details.\"\"\"\n    self.interval = interval\n    self.key = key", "title": ""}
{"_id": "d4053", "text": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "title": ""}
{"_id": "d4054", "text": "def user_return(self, frame, return_value):\n        \"\"\"This function is called when a return trap is set here.\"\"\"\n        pdb.Pdb.user_return(self, frame, return_value)", "title": ""}
{"_id": "d4055", "text": "def average(arr):\n  \"\"\"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\n\n  \"\"\"\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))", "title": ""}
{"_id": "d4056", "text": "def setwinsize(self, rows, cols):\n        \"\"\"Set the terminal window size of the child tty.\n        \"\"\"\n        self._winsize = (rows, cols)\n        self.pty.set_size(cols, rows)", "title": ""}
{"_id": "d4057", "text": "def delete(gandi, resource):\n    \"\"\"Delete DNSSEC key.\n    \"\"\"\n\n    result = gandi.dnssec.delete(resource)\n    gandi.echo('Delete successful.')\n\n    return result", "title": ""}
{"_id": "d4058", "text": "def _parse_config(config_file_path):\n    \"\"\" Parse Config File from yaml file. \"\"\"\n    config_file = open(config_file_path, 'r')\n    config = yaml.load(config_file)\n    config_file.close()\n    return config", "title": ""}
{"_id": "d4059", "text": "def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key):\n    \"\"\"Creates an AWS Chalice project for deployment to AWS Lambda.\"\"\"\n    from canari.commands.create_aws_lambda import create_aws_lambda\n    create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key)", "title": ""}
{"_id": "d4060", "text": "def confusion_matrix(self):\n        \"\"\"Confusion matrix plot\n        \"\"\"\n        return plot.confusion_matrix(self.y_true, self.y_pred,\n                                     self.target_names, ax=_gen_ax())", "title": ""}
{"_id": "d4061", "text": "def s2b(s):\n    \"\"\"\n    String to binary.\n    \"\"\"\n    ret = []\n    for c in s:\n        ret.append(bin(ord(c))[2:].zfill(8))\n    return \"\".join(ret)", "title": ""}
{"_id": "d4062", "text": "def show_approx(self, numfmt='%.3g'):\n        \"\"\"Show the probabilities rounded and sorted by key, for the\n        sake of portable doctests.\"\"\"\n        return ', '.join([('%s: ' + numfmt) % (v, p)\n                          for (v, p) in sorted(self.prob.items())])", "title": ""}
{"_id": "d4063", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d4064", "text": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "title": ""}
{"_id": "d4065", "text": "def text(el, strip=True):\n    \"\"\"\n    Return the text of a ``BeautifulSoup`` element\n    \"\"\"\n    if not el:\n        return \"\"\n\n    text = el.text\n    if strip:\n        text = text.strip()\n    return text", "title": ""}
{"_id": "d4066", "text": "def underscore(text):\n    \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n    return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()", "title": ""}
{"_id": "d4067", "text": "def get_boto_session(\n        region,\n        aws_access_key_id=None,\n        aws_secret_access_key=None,\n        aws_session_token=None\n        ):\n    \"\"\"Get a boto3 session.\"\"\"\n    return boto3.session.Session(\n        region_name=region,\n        aws_secret_access_key=aws_secret_access_key,\n        aws_access_key_id=aws_access_key_id,\n        aws_session_token=aws_session_token\n    )", "title": ""}
{"_id": "d4068", "text": "def singleton(class_):\n    \"\"\"Singleton definition.\n\n    Method 1 from\n    https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n    \"\"\"\n    instances = {}\n\n    def get_instance(*args, **kwargs):\n        if class_ not in instances:\n            instances[class_] = class_(*args, **kwargs)\n        return instances[class_]\n    return get_instance", "title": ""}
{"_id": "d4069", "text": "def start():\n    \"\"\"Starts the web server.\"\"\"\n    global app\n    bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n               debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n               quiet=conf.WebQuiet)", "title": ""}
{"_id": "d4070", "text": "def lines(input):\n    \"\"\"Remove comments and empty lines\"\"\"\n    for raw_line in input:\n        line = raw_line.strip()\n        if line and not line.startswith('#'):\n            yield strip_comments(line)", "title": ""}
{"_id": "d4071", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d4072", "text": "def is_full_slice(obj, l):\n    \"\"\"\n    We have a full length slice.\n    \"\"\"\n    return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and\n            obj.step is None)", "title": ""}
{"_id": "d4073", "text": "def _make_cmd_list(cmd_list):\n    \"\"\"\n    Helper function to easily create the proper json formated string from a list of strs\n    :param cmd_list: list of strings\n    :return: str json formatted\n    \"\"\"\n    cmd = ''\n    for i in cmd_list:\n        cmd = cmd + '\"' + i + '\",'\n    cmd = cmd[:-1]\n    return cmd", "title": ""}
{"_id": "d4074", "text": "def ibatch(iterable, size):\n    \"\"\"Yield a series of batches from iterable, each size elements long.\"\"\"\n    source = iter(iterable)\n    while True:\n        batch = itertools.islice(source, size)\n        yield itertools.chain([next(batch)], batch)", "title": ""}
{"_id": "d4075", "text": "def filtered_image(self, im):\n        \"\"\"Returns a filtered image after applying the Fourier-space filters\"\"\"\n        q = np.fft.fftn(im)\n        for k,v in self.filters:\n            q[k] -= v\n        return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d4076", "text": "def sort_by_name(self):\n        \"\"\"Sort list elements by name.\"\"\"\n        super(JSSObjectList, self).sort(key=lambda k: k.name)", "title": ""}
{"_id": "d4077", "text": "def disable_cert_validation():\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d4078", "text": "def sort_data(data, cols):\n    \"\"\"Sort `data` rows and order columns\"\"\"\n    return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "title": ""}
{"_id": "d4079", "text": "def get_cache(self, decorated_function, *args, **kwargs):\n\t\t\"\"\" :meth:`WCacheStorage.get_cache` method implementation\n\t\t\"\"\"\n\t\thas_value = self.has(decorated_function, *args, **kwargs)\n\t\tcached_value = None\n\t\tif has_value is True:\n\t\t\tcached_value = self.get_result(decorated_function, *args, **kwargs)\n\t\treturn WCacheStorage.CacheEntry(has_value=has_value, cached_value=cached_value)", "title": ""}
{"_id": "d4080", "text": "def unsort_vector(data, indices_of_increasing):\n    \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n    return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])", "title": ""}
{"_id": "d4081", "text": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "title": ""}
{"_id": "d4082", "text": "def loadmat(filename):\n    \"\"\"This function should be called instead of direct spio.loadmat\n    as it cures the problem of not properly recovering python dictionaries\n    from mat files. It calls the function check keys to cure all entries\n    which are still mat-objects\n    \"\"\"\n    data = sploadmat(filename, struct_as_record=False, squeeze_me=True)\n    return _check_keys(data)", "title": ""}
{"_id": "d4083", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d4084", "text": "def python_mime(fn):\n    \"\"\"\n    Decorator, which adds correct MIME type for python source to the decorated\n    bottle API function.\n    \"\"\"\n    @wraps(fn)\n    def python_mime_decorator(*args, **kwargs):\n        response.content_type = \"text/x-python\"\n\n        return fn(*args, **kwargs)\n\n    return python_mime_decorator", "title": ""}
{"_id": "d4085", "text": "def run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv. Return result code.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tresult_code = __import__('pytest').main()\n\t\t\tif result_code:\n\t\t\t\traise SystemExit(result_code)", "title": ""}
{"_id": "d4086", "text": "def swap_priority(self, key1, key2):\n        \"\"\"\n        Fast way to swap the priority level of two items in the pqdict. Raises\n        ``KeyError`` if either key does not exist.\n\n        \"\"\"\n        heap = self._heap\n        position = self._position\n        if key1 not in self or key2 not in self:\n            raise KeyError\n        pos1, pos2 = position[key1], position[key2]\n        heap[pos1].key, heap[pos2].key = key2, key1\n        position[key1], position[key2] = pos2, pos1", "title": ""}
{"_id": "d4087", "text": "def recursively_get_files_from_directory(directory):\n    \"\"\"\n    Return all filenames under recursively found in a directory\n    \"\"\"\n    return [\n        os.path.join(root, filename)\n        for root, directories, filenames in os.walk(directory)\n        for filename in filenames\n    ]", "title": ""}
{"_id": "d4088", "text": "def _set_module_names_for_sphinx(modules: List, new_name: str):\n    \"\"\" Trick sphinx into displaying the desired module in these objects' documentation. \"\"\"\n    for obj in modules:\n        obj.__module__ = new_name", "title": ""}
{"_id": "d4089", "text": "def _depr(fn, usage, stacklevel=3):\n    \"\"\"Internal convenience function for deprecation warnings\"\"\"\n    warn('{0} is deprecated. Use {1} instead'.format(fn, usage),\n         stacklevel=stacklevel, category=DeprecationWarning)", "title": ""}
{"_id": "d4090", "text": "def chunks(arr, size):\n    \"\"\"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`\n    \"\"\"\n    for i in _range(0, len(arr), size):\n        yield arr[i:i+size]", "title": ""}
{"_id": "d4091", "text": "def _run_once(self):\n    \"\"\"Run once, should be called only from loop()\"\"\"\n    try:\n      self.do_wait()\n      self._execute_wakeup_tasks()\n      self._trigger_timers()\n    except Exception as e:\n      Log.error(\"Error occured during _run_once(): \" + str(e))\n      Log.error(traceback.format_exc())\n      self.should_exit = True", "title": ""}
{"_id": "d4092", "text": "def camelcase_to_slash(name):\n    \"\"\" Converts CamelCase to camel/case\n\n    code ripped from http://stackoverflow.com/questions/1175208/does-the-python-standard-library-have-function-to-convert-camelcase-to-camel-cas\n    \"\"\"\n\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()", "title": ""}
{"_id": "d4093", "text": "def from_pydatetime(cls, pydatetime):\n        \"\"\"\n        Creates sql datetime2 object from Python datetime object\n        ignoring timezone\n        @param pydatetime: Python datetime object\n        @return: sql datetime2 object\n        \"\"\"\n        return cls(date=Date.from_pydate(pydatetime.date),\n                   time=Time.from_pytime(pydatetime.time))", "title": ""}
{"_id": "d4094", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d4095", "text": "def from_pydatetime(cls, pydatetime):\n        \"\"\"\n        Creates sql datetime2 object from Python datetime object\n        ignoring timezone\n        @param pydatetime: Python datetime object\n        @return: sql datetime2 object\n        \"\"\"\n        return cls(date=Date.from_pydate(pydatetime.date),\n                   time=Time.from_pytime(pydatetime.time))", "title": ""}
{"_id": "d4096", "text": "def set_scrollregion(self, event=None):\n        \"\"\" Set the scroll region on the canvas\"\"\"\n        self.canvas.configure(scrollregion=self.canvas.bbox('all'))", "title": ""}
{"_id": "d4097", "text": "def is_alive(self):\n        \"\"\"\n        Will test whether the ACS service is up and alive.\n        \"\"\"\n        response = self.get_monitoring_heartbeat()\n        if response.status_code == 200 and response.content == 'alive':\n            return True\n\n        return False", "title": ""}
{"_id": "d4098", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d4099", "text": "def _subclassed(base, *classes):\n        \"\"\"Check if all classes are subclassed from base.\n        \"\"\"\n        return all(map(lambda obj: isinstance(obj, base), classes))", "title": ""}
{"_id": "d4100", "text": "def _opt_call_from_base_type(self, value):\n    \"\"\"Call _from_base_type() if necessary.\n\n    If the value is a _BaseValue instance, unwrap it and call all\n    _from_base_type() methods.  Otherwise, return the value\n    unchanged.\n    \"\"\"\n    if isinstance(value, _BaseValue):\n      value = self._call_from_base_type(value.b_val)\n    return value", "title": ""}
{"_id": "d4101", "text": "def _port_not_in_use():\n    \"\"\"Use the port 0 trick to find a port not in use.\"\"\"\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    port = 0\n    s.bind(('', port))\n    _, port = s.getsockname()\n    return port", "title": ""}
{"_id": "d4102", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d4103", "text": "def copy(a):\n    \"\"\" Copy an array to the shared memory. \n\n        Notes\n        -----\n        copy is not always necessary because the private memory is always copy-on-write.\n\n        Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory\n    \"\"\"\n    shared = anonymousmemmap(a.shape, dtype=a.dtype)\n    shared[:] = a[:]\n    return shared", "title": ""}
{"_id": "d4104", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d4105", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d4106", "text": "def load(self, name):\n        \"\"\"Loads and returns foreign library.\"\"\"\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)", "title": ""}
{"_id": "d4107", "text": "def weighted_std(values, weights):\n    \"\"\" Calculate standard deviation weighted by errors \"\"\"\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)", "title": ""}
{"_id": "d4108", "text": "def _maybe_to_categorical(array):\n    \"\"\"\n    Coerce to a categorical if a series is given.\n\n    Internal use ONLY.\n    \"\"\"\n    if isinstance(array, (ABCSeries, ABCCategoricalIndex)):\n        return array._values\n    elif isinstance(array, np.ndarray):\n        return Categorical(array)\n    return array", "title": ""}
{"_id": "d4109", "text": "def circstd(dts, axis=2):\n    \"\"\"Circular standard deviation\"\"\"\n    R = np.abs(np.exp(1.0j * dts).mean(axis=axis))\n    return np.sqrt(-2.0 * np.log(R))", "title": ""}
{"_id": "d4110", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d4111", "text": "def save_config_value(request, response, key, value):\n    \"\"\"Sets value of key `key` to `value` in both session and cookies.\"\"\"\n    request.session[key] = value\n    response.set_cookie(key, value, expires=one_year_from_now())\n    return response", "title": ""}
{"_id": "d4112", "text": "def set_label ( self, object, label ):\n        \"\"\" Sets the label for a specified object.\n        \"\"\"\n        label_name = self.label\n        if label_name[:1] != '=':\n            xsetattr( object, label_name, label )", "title": ""}
{"_id": "d4113", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d4114", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d4115", "text": "def next (self):    # File-like object.\n\n        \"\"\"This is to support iterators over a file-like object.\n        \"\"\"\n\n        result = self.readline()\n        if result == self._empty_buffer:\n            raise StopIteration\n        return result", "title": ""}
{"_id": "d4116", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d4117", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d4118", "text": "def _is_subsequence_of(self, sub, sup):\n        \"\"\"\n        Parameters\n        ----------\n        sub : str\n        sup : str\n\n        Returns\n        -------\n        bool\n        \"\"\"\n        return bool(re.search(\".*\".join(sub), sup))", "title": ""}
{"_id": "d4119", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d4120", "text": "def cmp_contents(filename1, filename2):\n    \"\"\" Returns True if contents of the files are the same\n\n    Parameters\n    ----------\n    filename1 : str\n        filename of first file to compare\n    filename2 : str\n        filename of second file to compare\n\n    Returns\n    -------\n    tf : bool\n        True if binary contents of `filename1` is same as binary contents of\n        `filename2`, False otherwise.\n    \"\"\"\n    with open_readable(filename1, 'rb') as fobj:\n        contents1 = fobj.read()\n    with open_readable(filename2, 'rb') as fobj:\n        contents2 = fobj.read()\n    return contents1 == contents2", "title": ""}
{"_id": "d4121", "text": "def _parse(self, date_str, format='%Y-%m-%d'):\n        \"\"\"\n        helper function for parsing FRED date string into datetime\n        \"\"\"\n        rv = pd.to_datetime(date_str, format=format)\n        if hasattr(rv, 'to_pydatetime'):\n            rv = rv.to_pydatetime()\n        return rv", "title": ""}
{"_id": "d4122", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d4123", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d4124", "text": "def _is_valid_api_url(self, url):\n        \"\"\"Callback for is_valid_api_url.\"\"\"\n        # Check response is a JSON with ok: 1\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\n        return data.get('ok', 0) == 1", "title": ""}
{"_id": "d4125", "text": "def straight_line_show(title, length=100, linestyle=\"=\", pad=0):\n        \"\"\"Print a formatted straight line.\n        \"\"\"\n        print(StrTemplate.straight_line(\n            title=title, length=length, linestyle=linestyle, pad=pad))", "title": ""}
{"_id": "d4126", "text": "def cudaMalloc(count, ctype=None):\n    \"\"\"\n    Allocate device memory.\n\n    Allocate memory on the device associated with the current active\n    context.\n\n    Parameters\n    ----------\n    count : int\n        Number of bytes of memory to allocate\n    ctype : _ctypes.SimpleType, optional\n        ctypes type to cast returned pointer.\n\n    Returns\n    -------\n    ptr : ctypes pointer\n        Pointer to allocated device memory.\n\n    \"\"\"\n\n    ptr = ctypes.c_void_p()\n    status = _libcudart.cudaMalloc(ctypes.byref(ptr), count)\n    cudaCheckStatus(status)\n    if ctype != None:\n        ptr = ctypes.cast(ptr, ctypes.POINTER(ctype))\n    return ptr", "title": ""}
{"_id": "d4127", "text": "def check_output(args):\n    \"\"\"Runs command and returns the output as string.\"\"\"\n    log.debug('run: %s', args)\n    out = subprocess.check_output(args=args).decode('utf-8')\n    log.debug('out: %r', out)\n    return out", "title": ""}
{"_id": "d4128", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d4129", "text": "def convert_time_string(date_str):\n    \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n    dt, _, _ = date_str.partition(\".\")\n    dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n    return dt", "title": ""}
{"_id": "d4130", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d4131", "text": "def Sum(a, axis, keep_dims):\n    \"\"\"\n    Sum reduction op.\n    \"\"\"\n    return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                  keepdims=keep_dims),", "title": ""}
{"_id": "d4132", "text": "def warn_deprecated(message, stacklevel=2):  # pragma: no cover\n    \"\"\"Warn deprecated.\"\"\"\n\n    warnings.warn(\n        message,\n        category=DeprecationWarning,\n        stacklevel=stacklevel\n    )", "title": ""}
{"_id": "d4133", "text": "def _accumulate(sequence, func):\n    \"\"\"\n    Python2 accumulate implementation taken from\n    https://docs.python.org/3/library/itertools.html#itertools.accumulate\n    \"\"\"\n    iterator = iter(sequence)\n    total = next(iterator)\n    yield total\n    for element in iterator:\n        total = func(total, element)\n        yield total", "title": ""}
{"_id": "d4134", "text": "def is_git_repo():\n    \"\"\"Check whether the current folder is a 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", "title": ""}
{"_id": "d4135", "text": "def Sum(a, axis, keep_dims):\n    \"\"\"\n    Sum reduction op.\n    \"\"\"\n    return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                  keepdims=keep_dims),", "title": ""}
{"_id": "d4136", "text": "def is_archlinux():\n    \"\"\"return True if the current distribution is running on debian like OS.\"\"\"\n    if platform.system().lower() == 'linux':\n        if platform.linux_distribution() == ('', '', ''):\n            # undefined distribution. Fixed in python 3.\n            if os.path.exists('/etc/arch-release'):\n                return True\n    return False", "title": ""}
{"_id": "d4137", "text": "def to_snake_case(s):\n    \"\"\"Converts camel-case identifiers to snake-case.\"\"\"\n    return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)", "title": ""}
{"_id": "d4138", "text": "def group_exists(groupname):\n    \"\"\"Check if a group exists\"\"\"\n    try:\n        grp.getgrnam(groupname)\n        group_exists = True\n    except KeyError:\n        group_exists = False\n    return group_exists", "title": ""}
{"_id": "d4139", "text": "def _swap_rows(self, i, j):\n        \"\"\"Swap i and j rows\n\n        As the side effect, determinant flips.\n\n        \"\"\"\n\n        L = np.eye(3, dtype='intc')\n        L[i, i] = 0\n        L[j, j] = 0\n        L[i, j] = 1\n        L[j, i] = 1\n        self._L.append(L.copy())\n        self._A = np.dot(L, self._A)", "title": ""}
{"_id": "d4140", "text": "def allsame(list_, strict=True):\n    \"\"\"\n    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\n    \"\"\"\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)", "title": ""}
{"_id": "d4141", "text": "def lazy_reverse_binmap(f, xs):\n    \"\"\"\n    Same as lazy_binmap, except the parameters are flipped for the binary function\n    \"\"\"\n    return (f(y, x) for x, y in zip(xs, xs[1:]))", "title": ""}
{"_id": "d4142", "text": "def isin(self, column, compare_list):\n        \"\"\"\n        Returns a boolean list where each elements is whether that element in the column is in the compare_list.\n\n        :param column: single column name, does not work for multiple columns\n        :param compare_list: list of items to compare to\n        :return: list of booleans\n        \"\"\"\n        return [x in compare_list for x in self._data[self._columns.index(column)]]", "title": ""}
{"_id": "d4143", "text": "def jsonify(symbol):\n    \"\"\" returns json format for symbol \"\"\"\n    try:\n        # all symbols have a toJson method, try it\n        return json.dumps(symbol.toJson(), indent='  ')\n    except AttributeError:\n        pass\n    return json.dumps(symbol, indent='  ')", "title": ""}
{"_id": "d4144", "text": "def is_http_running_on(port):\n  \"\"\" Check if an http server runs on a given port.\n\n  Args:\n    The port to check.\n  Returns:\n    True if it is used by an http server. False otherwise.\n  \"\"\"\n  try:\n    conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n    conn.connect()\n    conn.close()\n    return True\n  except Exception:\n    return False", "title": ""}
{"_id": "d4145", "text": "def table_width(self):\n        \"\"\"Return the width of the table including padding and borders.\"\"\"\n        outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]\n        outer_border = 2 if self.outer_border else 0\n        inner_border = 1 if self.inner_column_border else 0\n        return table_width(outer_widths, outer_border, inner_border)", "title": ""}
{"_id": "d4146", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d4147", "text": "def save_as_png(self, filename, width=300, height=250, render_time=1):\n        \"\"\"Open saved html file in an virtual browser and save a screen shot to PNG format.\"\"\"\n        self.driver.set_window_size(width, height)\n        self.driver.get('file://{path}/{filename}'.format(\n            path=os.getcwd(), filename=filename + \".html\"))\n        time.sleep(render_time)\n        self.driver.save_screenshot(filename + \".png\")", "title": ""}
{"_id": "d4148", "text": "def is_all_field_none(self):\n        \"\"\"\n        :rtype: bool\n        \"\"\"\n\n        if self._type_ is not None:\n            return False\n\n        if self._value is not None:\n            return False\n\n        if self._name is not None:\n            return False\n\n        return True", "title": ""}
{"_id": "d4149", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d4150", "text": "def is_json_file(filename, show_warnings = False):\n    \"\"\"Check configuration file type is JSON\n    Return a boolean indicating wheather the file is JSON format or not\n    \"\"\"\n    try:\n        config_dict = load_config(filename, file_type = \"json\")\n        is_json = True\n    except:\n        is_json = False\n    return(is_json)", "title": ""}
{"_id": "d4151", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d4152", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d4153", "text": "def softplus(attrs, inputs, proto_obj):\n    \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs", "title": ""}
{"_id": "d4154", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d4155", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d4156", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d4157", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d4158", "text": "def _get_line_no_from_comments(py_line):\n    \"\"\"Return the line number parsed from the comment or 0.\"\"\"\n    matched = LINECOL_COMMENT_RE.match(py_line)\n    if matched:\n        return int(matched.group(1))\n    else:\n        return 0", "title": ""}
{"_id": "d4159", "text": "def get_attr(self, method_name):\n        \"\"\"Get attribute from the target object\"\"\"\n        return self.attrs.get(method_name) or self.get_callable_attr(method_name)", "title": ""}
{"_id": "d4160", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d4161", "text": "def is_lazy_iterable(obj):\n    \"\"\"\n    Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n    \"\"\"\n    return isinstance(obj,\n        (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))", "title": ""}
{"_id": "d4162", "text": "def should_skip_logging(func):\n    \"\"\"\n    Should we skip logging for this handler?\n\n    \"\"\"\n    disabled = strtobool(request.headers.get(\"x-request-nolog\", \"false\"))\n    return disabled or getattr(func, SKIP_LOGGING, False)", "title": ""}
{"_id": "d4163", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d4164", "text": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "title": ""}
{"_id": "d4165", "text": "def can_route(self, endpoint, method=None, **kwargs):\n        \"\"\"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.\n\n        \"\"\"\n\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\n        return self.can('http.' + (method or 'GET').lower(), view, **kwargs)", "title": ""}
{"_id": "d4166", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d4167", "text": "def best(self):\n        \"\"\"\n        Returns the element with the highest probability.\n        \"\"\"\n        b = (-1e999999, None)\n        for k, c in iteritems(self.counts):\n            b = max(b, (c, k))\n        return b[1]", "title": ""}
{"_id": "d4168", "text": "def is_image(filename):\n    \"\"\"Determine if given filename is an image.\"\"\"\n    # note: isfile() also accepts symlinks\n    return os.path.isfile(filename) and filename.lower().endswith(ImageExts)", "title": ""}
{"_id": "d4169", "text": "def format_time(time):\n    \"\"\" Formats the given time into HH:MM:SS \"\"\"\n    h, r = divmod(time / 1000, 3600)\n    m, s = divmod(r, 60)\n\n    return \"%02d:%02d:%02d\" % (h, m, s)", "title": ""}
{"_id": "d4170", "text": "def kernelDriverActive(self, interface):\n        \"\"\"\n        Tell whether a kernel driver is active on given interface number.\n        \"\"\"\n        result = libusb1.libusb_kernel_driver_active(self.__handle, interface)\n        if result == 0:\n            return False\n        elif result == 1:\n            return True\n        raiseUSBError(result)", "title": ""}
{"_id": "d4171", "text": "def timedelta2millisecond(td):\n    \"\"\"Get milliseconds from a timedelta.\"\"\"\n    milliseconds = td.days * 24 * 60 * 60 * 1000\n    milliseconds += td.seconds * 1000\n    milliseconds += td.microseconds / 1000\n    return milliseconds", "title": ""}
{"_id": "d4172", "text": "def test_value(self, value):\n        \"\"\"Test if value is an instance of float.\"\"\"\n        if not isinstance(value, float):\n            raise ValueError('expected float value: ' + str(type(value)))", "title": ""}
{"_id": "d4173", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d4174", "text": "def is_valid_variable_name(string_to_check):\n    \"\"\"\n    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\n    \"\"\"\n\n    try:\n\n        parse('{} = None'.format(string_to_check))\n        return True\n\n    except (SyntaxError, ValueError, TypeError):\n\n        return False", "title": ""}
{"_id": "d4175", "text": "def speedtest(func, *args, **kwargs):\n    \"\"\" Test the speed of a function. \"\"\"\n    n = 100\n    start = time.time()\n    for i in range(n): func(*args,**kwargs)\n    end = time.time()\n    return (end-start)/n", "title": ""}
{"_id": "d4176", "text": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "title": ""}
{"_id": "d4177", "text": "def _column_resized(self, col, old_width, new_width):\n        \"\"\"Update the column width.\"\"\"\n        self.dataTable.setColumnWidth(col, new_width)\n        self._update_layout()", "title": ""}
{"_id": "d4178", "text": "def inside_softimage():\n    \"\"\"Returns a boolean indicating if the code is executed 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", "title": ""}
{"_id": "d4179", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d4180", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d4181", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d4182", "text": "def is_timestamp(obj):\n    \"\"\"\n    Yaml either have automatically converted it to a datetime object\n    or it is a string that will be validated later.\n    \"\"\"\n    return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)", "title": ""}
{"_id": "d4183", "text": "def from_df(data_frame):\n        \"\"\"Parses data and builds an instance of this class\n\n        :param data_frame: pandas DataFrame\n        :return: SqlTable\n        \"\"\"\n        labels = data_frame.keys().tolist()\n        data = data_frame.values.tolist()\n        return SqlTable(labels, data, \"{:.3f}\", \"\\n\")", "title": ""}
{"_id": "d4184", "text": "def check_length(value, length):\n    \"\"\"\n    Checks length of value\n\n    @param value: value to check\n    @type value: C{str}\n\n    @param length: length checking for\n    @type length: C{int}\n\n    @return: None when check successful\n\n    @raise ValueError: check failed\n    \"\"\"\n    _length = len(value)\n    if _length != length:\n        raise ValueError(\"length must be %d, not %d\" % \\\n                         (length, _length))", "title": ""}
{"_id": "d4185", "text": "def transpose(table):\n    \"\"\"\n    transpose matrix\n    \"\"\"\n    t = []\n    for i in range(0, len(table[0])):\n        t.append([row[i] for row in table])\n    return t", "title": ""}
{"_id": "d4186", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d4187", "text": "def truncate(self, table):\n        \"\"\"Empty a table by deleting all of its rows.\"\"\"\n        if isinstance(table, (list, set, tuple)):\n            for t in table:\n                self._truncate(t)\n        else:\n            self._truncate(table)", "title": ""}
{"_id": "d4188", "text": "def rsa_eq(key1, key2):\n    \"\"\"\n    Only works for RSAPublic Keys\n\n    :param key1:\n    :param key2:\n    :return:\n    \"\"\"\n    pn1 = key1.public_numbers()\n    pn2 = key2.public_numbers()\n    # Check if two RSA keys are in fact the same\n    if pn1 == pn2:\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d4189", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d4190", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d4191", "text": "def dispatch(self, request, *args, **kwargs):\n        \"\"\"Dispatch all HTTP methods to the proxy.\"\"\"\n        self.request = DownstreamRequest(request)\n        self.args = args\n        self.kwargs = kwargs\n\n        self._verify_config()\n\n        self.middleware = MiddlewareSet(self.proxy_middleware)\n\n        return self.proxy()", "title": ""}
{"_id": "d4192", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d4193", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d4194", "text": "def is_admin(self):\n        \"\"\"Is the user a system administrator\"\"\"\n        return self.role == self.roles.administrator.value and self.state == State.approved", "title": ""}
{"_id": "d4195", "text": "def abs_img(img):\n    \"\"\" Return an image with the binarised version of the data of `img`.\"\"\"\n    bool_img = np.abs(read_img(img).get_data())\n    return bool_img.astype(int)", "title": ""}
{"_id": "d4196", "text": "def is_timestamp(obj):\n    \"\"\"\n    Yaml either have automatically converted it to a datetime object\n    or it is a string that will be validated later.\n    \"\"\"\n    return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)", "title": ""}
{"_id": "d4197", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d4198", "text": "def type_converter(text):\n    \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n    if text.isdigit():\n        return int(text), int\n\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE", "title": ""}
{"_id": "d4199", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d4200", "text": "def is_complex(dtype):\n  \"\"\"Returns whether this is a complex floating point type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_complex'):\n    return dtype.is_complex\n  return np.issubdtype(np.dtype(dtype), np.complex)", "title": ""}
{"_id": "d4201", "text": "def stop_capture(self):\n        \"\"\"Stop listening for output from the stenotype machine.\"\"\"\n        super(Treal, self).stop_capture()\n        if self._machine:\n            self._machine.close()\n        self._stopped()", "title": ""}
{"_id": "d4202", "text": "def _tableExists(self, tableName):\n        cursor=_conn.execute(\"\"\"\n            SELECT * FROM sqlite_master WHERE name ='{0}' and type='table';\n        \"\"\".format(tableName))\n        exists = cursor.fetchone() is not None\n        cursor.close()\n        return exists", "title": ""}
{"_id": "d4203", "text": "def search_for_tweets_about(user_id, params):\n    \"\"\" Search twitter API \"\"\"\n    url = \"https://api.twitter.com/1.1/search/tweets.json\"\n    response = make_twitter_request(url, user_id, params)\n    return process_tweets(response.json()[\"statuses\"])", "title": ""}
{"_id": "d4204", "text": "def is_image(filename):\n    \"\"\"Determine if given filename is an image.\"\"\"\n    # note: isfile() also accepts symlinks\n    return os.path.isfile(filename) and filename.lower().endswith(ImageExts)", "title": ""}
{"_id": "d4205", "text": "def coerce(self, value):\n        \"\"\"Convert from whatever is given to a list of scalars for the lookup_field.\"\"\"\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]", "title": ""}
{"_id": "d4206", "text": "def chmod_plus_w(path):\n  \"\"\"Equivalent of unix `chmod +w path`\"\"\"\n  path_mode = os.stat(path).st_mode\n  path_mode &= int('777', 8)\n  path_mode |= stat.S_IWRITE\n  os.chmod(path, path_mode)", "title": ""}
{"_id": "d4207", "text": "def get_font_list():\n    \"\"\"Returns a sorted list of all system font names\"\"\"\n\n    font_map = pangocairo.cairo_font_map_get_default()\n    font_list = [f.get_name() for f in font_map.list_families()]\n    font_list.sort()\n\n    return font_list", "title": ""}
{"_id": "d4208", "text": "def on_source_directory_chooser_clicked(self):\n        \"\"\"Autoconnect slot activated when tbSourceDir is clicked.\"\"\"\n\n        title = self.tr('Set the source directory for script and scenario')\n        self.choose_directory(self.source_directory, title)", "title": ""}
{"_id": "d4209", "text": "def multipart_parse_json(api_url, data):\n    \"\"\"\n    Send a post request and parse the JSON response (potentially containing\n    non-ascii characters).\n    @param api_url: the url endpoint to post to.\n    @param data: a dictionary that will be passed to requests.post\n    \"\"\"\n    headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n    response_text = requests.post(api_url, data=data, headers=headers)\\\n        .text.encode('ascii', errors='replace')\n\n    return json.loads(response_text.decode())", "title": ""}
{"_id": "d4210", "text": "def chunks(iterable, chunk):\n    \"\"\"Yield successive n-sized chunks from an iterable.\"\"\"\n    for i in range(0, len(iterable), chunk):\n        yield iterable[i:i + chunk]", "title": ""}
{"_id": "d4211", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d4212", "text": "def make_unique_ngrams(s, n):\n    \"\"\"Make a set of unique n-grams from a string.\"\"\"\n    return set(s[i:i + n] for i in range(len(s) - n + 1))", "title": ""}
{"_id": "d4213", "text": "def finished(self):\n        \"\"\"\n        Must be called to print final progress label.\n        \"\"\"\n        self.progress_bar.set_state(ProgressBar.STATE_DONE)\n        self.progress_bar.show()", "title": ""}
{"_id": "d4214", "text": "def get_unique_indices(df, axis=1):\n    \"\"\"\n\n    :param df:\n    :param axis:\n    :return:\n    \"\"\"\n    return dict(zip(df.columns.names, dif.columns.levels))", "title": ""}
{"_id": "d4215", "text": "def clear_globals_reload_modules(self):\n        \"\"\"Clears globals and reloads modules\"\"\"\n\n        self.code_array.clear_globals()\n        self.code_array.reload_modules()\n\n        # Clear result cache\n        self.code_array.result_cache.clear()", "title": ""}
{"_id": "d4216", "text": "def uniquify_list(L):\n    \"\"\"Same order unique list using only a list compression.\"\"\"\n    return [e for i, e in enumerate(L) if L.index(e) == i]", "title": ""}
{"_id": "d4217", "text": "def stop(self, dummy_signum=None, dummy_frame=None):\n        \"\"\" Shutdown process (this method is also a signal handler) \"\"\"\n        logging.info('Shutting down ...')\n        self.socket.close()\n        sys.exit(0)", "title": ""}
{"_id": "d4218", "text": "def compose_all(tups):\n  \"\"\"Compose all given tuples together.\"\"\"\n  from . import ast  # I weep for humanity\n  return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))", "title": ""}
{"_id": "d4219", "text": "def shutdown():\n    \"\"\"Manually shutdown the async API.\n\n    Cancels all related tasks and all the socket transportation.\n    \"\"\"\n    global handler, transport, protocol\n    if handler is not None:\n        handler.close()\n        transport.close()\n        handler = None\n        transport = None\n        protocol = None", "title": ""}
{"_id": "d4220", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d4221", "text": "def __cmp__(self, other):\n        \"\"\"Comparsion not implemented.\"\"\"\n        # Stops python 2 from allowing comparsion of arbitrary objects\n        raise TypeError('unorderable types: {}, {}'\n                        ''.format(self.__class__.__name__, type(other)))", "title": ""}
{"_id": "d4222", "text": "def is_valid_image_extension(file_path):\n    \"\"\"is_valid_image_extension.\"\"\"\n    valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']\n    _, extension = os.path.splitext(file_path)\n    return extension.lower() in valid_extensions", "title": ""}
{"_id": "d4223", "text": "def install_from_zip(url):\n    \"\"\"Download and unzip from url.\"\"\"\n    fname = 'tmp.zip'\n    downlad_file(url, fname)\n    unzip_file(fname)\n    print(\"Removing {}\".format(fname))\n    os.unlink(fname)", "title": ""}
{"_id": "d4224", "text": "def Distance(lat1, lon1, lat2, lon2):\n    \"\"\"Get distance between pairs of lat-lon points\"\"\"\n\n    az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)\n    return az21, dist", "title": ""}
{"_id": "d4225", "text": "def restart(self, reset=False):\n        \"\"\"\n        Quit and Restart Spyder application.\n\n        If reset True it allows to reset spyder on restart.\n        \"\"\"\n        # Get start path to use in restart script\n        spyder_start_directory = get_module_path('spyder')\n        restart_script = osp.join(spyder_start_directory, 'app', 'restart.py')\n\n        # Get any initial argument passed when spyder was started\n        # Note: Variables defined in bootstrap.py and spyder/app/start.py\n        env = os.environ.copy()\n        bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)\n        spyder_args = env.pop('SPYDER_ARGS')\n\n        # Get current process and python running spyder\n        pid = os.getpid()\n        python = sys.executable\n\n        # Check if started with bootstrap.py\n        if bootstrap_args is not None:\n            spyder_args = bootstrap_args\n            is_bootstrap = True\n        else:\n            is_bootstrap = False\n\n        # Pass variables as environment variables (str) to restarter subprocess\n        env['SPYDER_ARGS'] = spyder_args\n        env['SPYDER_PID'] = str(pid)\n        env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)\n        env['SPYDER_RESET'] = str(reset)\n\n        if DEV:\n            if os.name == 'nt':\n                env['PYTHONPATH'] = ';'.join(sys.path)\n            else:\n                env['PYTHONPATH'] = ':'.join(sys.path)\n\n        # Build the command and popen arguments depending on the OS\n        if os.name == 'nt':\n            # Hide flashing command prompt\n            startupinfo = subprocess.STARTUPINFO()\n            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n            shell = False\n        else:\n            startupinfo = None\n            shell = True\n\n        command = '\"{0}\" \"{1}\"'\n        command = command.format(python, restart_script)\n\n        try:\n            if self.closing(True):\n                subprocess.Popen(command, shell=shell, env=env,\n                                 startupinfo=startupinfo)\n                self.console.quit()\n        except Exception as error:\n            # If there is an error with subprocess, Spyder should not quit and\n            # the error can be inspected in the internal console\n            print(error)  # spyder: test-skip\n            print(command)", "title": ""}
{"_id": "d4226", "text": "def get_conn(self):\n        \"\"\"\n        Opens a connection to the cloudant service and closes it automatically if used as context manager.\n\n        .. note::\n            In the connection form:\n            - 'host' equals the 'Account' (optional)\n            - 'login' equals the 'Username (or API Key)' (required)\n            - 'password' equals the 'Password' (required)\n\n        :return: an authorized cloudant session context manager object.\n        :rtype: cloudant\n        \"\"\"\n        conn = self.get_connection(self.cloudant_conn_id)\n\n        self._validate_connection(conn)\n\n        cloudant_session = cloudant(user=conn.login, passwd=conn.password, account=conn.host)\n\n        return cloudant_session", "title": ""}
{"_id": "d4227", "text": "def push(self, el):\n        \"\"\" Put a new element in the queue. \"\"\"\n        count = next(self.counter)\n        heapq.heappush(self._queue, (el, count))", "title": ""}
{"_id": "d4228", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d4229", "text": "def update_target(self, name, current, total):\n        \"\"\"Updates progress bar for a specified target.\"\"\"\n        self.refresh(self._bar(name, current, total))", "title": ""}
{"_id": "d4230", "text": "def is_valid_ipv6(ip_str):\n    \"\"\"\n    Check the validity of an IPv6 address\n    \"\"\"\n    try:\n        socket.inet_pton(socket.AF_INET6, ip_str)\n    except socket.error:\n        return False\n    return True", "title": ""}
{"_id": "d4231", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d4232", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d4233", "text": "def print_display_png(o):\n    \"\"\"\n    A function to display sympy expression using display style LaTeX in PNG.\n    \"\"\"\n    s = latex(o, mode='plain')\n    s = s.strip('$')\n    # As matplotlib does not support display style, dvipng backend is\n    # used here.\n    png = latex_to_png('$$%s$$' % s, backend='dvipng')\n    return png", "title": ""}
{"_id": "d4234", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d4235", "text": "def dist(x1, x2, axis=0):\n    \"\"\"Return the distance between two points.\n\n    Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances.\n    \"\"\"\n    return np.linalg.norm(x2 - x1, axis=axis)", "title": ""}
{"_id": "d4236", "text": "def get_indentation(func):\n    \"\"\"Extracts a function's indentation as a string,\n    In contrast to an inspect.indentsize based implementation,\n    this function preserves tabs if present.\n    \"\"\"\n    src_lines = getsourcelines(func)[0]\n    for line in src_lines:\n        if not (line.startswith('@') or line.startswith('def') or line.lstrip().startswith('#')):\n            return line[:len(line) - len(line.lstrip())]\n    return pytypes.default_indent", "title": ""}
{"_id": "d4237", "text": "def counter_from_str(self, string):\n        \"\"\"Build word frequency list from incoming string.\"\"\"\n        string_list = [chars for chars in string if chars not in self.punctuation]\n        string_joined = ''.join(string_list)\n        tokens = self.punkt.word_tokenize(string_joined)\n        return Counter(tokens)", "title": ""}
{"_id": "d4238", "text": "def count_string_diff(a,b):\n    \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n    shortest = min(len(a), len(b))\n    return sum(a[i] != b[i] for i in range(shortest))", "title": ""}
{"_id": "d4239", "text": "def _make_index(df, cols=META_IDX):\n    \"\"\"Create an index from the columns of a dataframe\"\"\"\n    return pd.MultiIndex.from_tuples(\n        pd.unique(list(zip(*[df[col] for col in cols]))), names=tuple(cols))", "title": ""}
{"_id": "d4240", "text": "def _try_compile(source, name):\n    \"\"\"Attempts to compile the given source, first as an expression and\n       then as a statement if the first approach fails.\n\n       Utility function to accept strings in functions that otherwise\n       expect code objects\n    \"\"\"\n    try:\n        c = compile(source, name, 'eval')\n    except SyntaxError:\n        c = compile(source, name, 'exec')\n    return c", "title": ""}
{"_id": "d4241", "text": "def _sort_lambda(sortedby='cpu_percent',\n                 sortedby_secondary='memory_percent'):\n    \"\"\"Return a sort lambda function for the sortedbykey\"\"\"\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", "title": ""}
{"_id": "d4242", "text": "def _accumulate(sequence, func):\n    \"\"\"\n    Python2 accumulate implementation taken from\n    https://docs.python.org/3/library/itertools.html#itertools.accumulate\n    \"\"\"\n    iterator = iter(sequence)\n    total = next(iterator)\n    yield total\n    for element in iterator:\n        total = func(total, element)\n        yield total", "title": ""}
{"_id": "d4243", "text": "def items(self, limit=0):\n        \"\"\"Return iterator for items in each page\"\"\"\n        i = ItemIterator(self.iterator)\n        i.limit = limit\n        return i", "title": ""}
{"_id": "d4244", "text": "def __init__(self, root_section='lago', defaults={}):\n        \"\"\"__init__\n        Args:\n            root_section (str): root section in the init\n            defaults (dict): Default dictonary to load, can be empty.\n        \"\"\"\n\n        self.root_section = root_section\n        self._defaults = defaults\n        self._config = defaultdict(dict)\n        self._config.update(self.load())\n        self._parser = None", "title": ""}
{"_id": "d4245", "text": "def conv2d(x_input, w_matrix):\n    \"\"\"conv2d returns a 2d convolution layer with full stride.\"\"\"\n    return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')", "title": ""}
{"_id": "d4246", "text": "def items(self, section_name):\n        \"\"\":return: list((option, value), ...) pairs of all items in the given section\"\"\"\n        return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']", "title": ""}
{"_id": "d4247", "text": "def SegmentMin(a, ids):\n    \"\"\"\n    Segmented min op.\n    \"\"\"\n    func = lambda idxs: np.amin(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d4248", "text": "def __connect():\n    \"\"\"\n    Connect to a redis instance.\n    \"\"\"\n    global redis_instance\n    if use_tcp_socket:\n        redis_instance = redis.StrictRedis(host=hostname, port=port)\n    else:\n        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "title": ""}
{"_id": "d4249", "text": "def percent_d(data, period):\n    \"\"\"\n    %D.\n\n    Formula:\n    %D = SMA(%K, 3)\n    \"\"\"\n    p_k = percent_k(data, period)\n    percent_d = sma(p_k, 3)\n    return percent_d", "title": ""}
{"_id": "d4250", "text": "def line_segment(X0, X1):\n    r\"\"\"\n    Calculate the voxel coordinates of a straight line between the two given\n    end points\n\n    Parameters\n    ----------\n    X0 and X1 : array_like\n        The [x, y] or [x, y, z] coordinates of the start and end points of\n        the line.\n\n    Returns\n    -------\n    coords : list of lists\n        A list of lists containing the X, Y, and Z coordinates of all voxels\n        that should be drawn between the start and end points to create a solid\n        line.\n    \"\"\"\n    X0 = sp.around(X0).astype(int)\n    X1 = sp.around(X1).astype(int)\n    if len(X0) == 3:\n        L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]], [X1[2]-X0[2]]])) + 1\n        x = sp.rint(sp.linspace(X0[0], X1[0], L)).astype(int)\n        y = sp.rint(sp.linspace(X0[1], X1[1], L)).astype(int)\n        z = sp.rint(sp.linspace(X0[2], X1[2], L)).astype(int)\n        return [x, y, z]\n    else:\n        L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]]])) + 1\n        x = sp.rint(sp.linspace(X0[0], X1[0], L)).astype(int)\n        y = sp.rint(sp.linspace(X0[1], X1[1], L)).astype(int)\n        return [x, y]", "title": ""}
{"_id": "d4251", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d4252", "text": "def get_line_flux(line_wave, wave, flux, **kwargs):\n    \"\"\"Interpolated flux at a given wavelength (calls np.interp).\"\"\"\n    return np.interp(line_wave, wave, flux, **kwargs)", "title": ""}
{"_id": "d4253", "text": "def to_json(data):\n    \"\"\"Return data as a JSON string.\"\"\"\n    return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)", "title": ""}
{"_id": "d4254", "text": "def method(func):\n    \"\"\"Wrap a function as a method.\"\"\"\n    attr = abc.abstractmethod(func)\n    attr.__imethod__ = True\n    return attr", "title": ""}
{"_id": "d4255", "text": "def version(self):\n        \"\"\"Spotify version information\"\"\"\n        url: str = get_url(\"/service/version.json\")\n        params = {\"service\": \"remote\"}\n        r = self._request(url=url, params=params)\n        return r.json()", "title": ""}
{"_id": "d4256", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d4257", "text": "def multiply(traj):\n    \"\"\"Sophisticated simulation of multiplication\"\"\"\n    z=traj.x*traj.y\n    traj.f_add_result('z',z=z, comment='I am the product of two reals!')", "title": ""}
{"_id": "d4258", "text": "def getOffset(self, loc):\n        \"\"\" Returns the offset between the given point and this point \"\"\"\n        return Location(loc.x - self.x, loc.y - self.y)", "title": ""}
{"_id": "d4259", "text": "def stdout_display():\n    \"\"\" Print results straight to stdout \"\"\"\n    if sys.version_info[0] == 2:\n        yield SmartBuffer(sys.stdout)\n    else:\n        yield SmartBuffer(sys.stdout.buffer)", "title": ""}
{"_id": "d4260", "text": "def peekiter(iterable):\n    \"\"\"Return first row and also iterable with same items as original\"\"\"\n    it = iter(iterable)\n    one = next(it)\n\n    def gen():\n        \"\"\"Generator that returns first and proxy other items from source\"\"\"\n        yield one\n        while True:\n            yield next(it)\n    return (one, gen())", "title": ""}
{"_id": "d4261", "text": "def unit_ball_L2(shape):\n  \"\"\"A tensorflow variable tranfomed to be constrained in a L2 unit ball.\n\n  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n  they are strong attacks. We are not yet confident in this code.\n  \"\"\"\n  x = tf.Variable(tf.zeros(shape))\n  return constrain_L2(x)", "title": ""}
{"_id": "d4262", "text": "def correlation(df, rowvar=False):\n    \"\"\"\n    Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``\n\n    Input data is masked to ignore NaNs when calculating correlations. Data is returned as\n    a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to\n    both axes.\n\n    :param df: Pandas DataFrame\n    :return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations\n    \"\"\"\n\n    # Create a correlation matrix for all correlations\n    # of the columns (filled with na for all values)\n    df = df.copy()\n    maskv = np.ma.masked_where(np.isnan(df.values), df.values)\n    cdf = np.ma.corrcoef(maskv, rowvar=False)\n    cdf = pd.DataFrame(np.array(cdf))\n    cdf.columns = df.columns\n    cdf.index = df.columns\n    cdf = cdf.sort_index(level=0, axis=1)\n    cdf = cdf.sort_index(level=0)\n    return cdf", "title": ""}
{"_id": "d4263", "text": "def assert_visible(self, locator, msg=None):\n        \"\"\"\n        Hard assert for whether and element is present and visible in the current window/frame\n\n        :params locator: the locator of the element to search for\n        :params msg: (Optional) msg explaining the difference\n        \"\"\"\n        e = driver.find_elements_by_locator(locator)\n        if len(e) == 0:\n            raise AssertionError(\"Element at %s was not found\" % locator)\n        assert e.is_displayed()", "title": ""}
{"_id": "d4264", "text": "def _factor_generator(n):\n    \"\"\"\n    From a given natural integer, returns the prime factors and their multiplicity\n    :param n: Natural integer\n    :return:\n    \"\"\"\n    p = prime_factors(n)\n    factors = {}\n    for p1 in p:\n        try:\n            factors[p1] += 1\n        except KeyError:\n            factors[p1] = 1\n    return factors", "title": ""}
{"_id": "d4265", "text": "def rgba_bytes_tuple(self, x):\n        \"\"\"Provides the color corresponding to value `x` in the\n        form of a tuple (R,G,B,A) with int values between 0 and 255.\n        \"\"\"\n        return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))", "title": ""}
{"_id": "d4266", "text": "def open_json(file_name):\n    \"\"\"\n    returns json contents as string\n    \"\"\"\n    with open(file_name, \"r\") as json_data:\n        data = json.load(json_data)\n        return data", "title": ""}
{"_id": "d4267", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d4268", "text": "def count_rows_with_nans(X):\n    \"\"\"Count the number of rows in 2D arrays that contain any nan values.\"\"\"\n    if X.ndim == 2:\n        return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()", "title": ""}
{"_id": "d4269", "text": "def compute_gradient(self):\n        \"\"\"Compute the gradient of the current model using the training set\n        \"\"\"\n        delta = self.predict(self.X) - self.y\n        return delta.dot(self.X) / len(self.X)", "title": ""}
{"_id": "d4270", "text": "def _get_indent_length(line):\n    \"\"\"Return the length of the indentation on the given token's line.\"\"\"\n    result = 0\n    for char in line:\n        if char == \" \":\n            result += 1\n        elif char == \"\\t\":\n            result += _TAB_LENGTH\n        else:\n            break\n    return result", "title": ""}
{"_id": "d4271", "text": "def quit(self):\n        \"\"\" Quits the application (called when the last window is closed)\n        \"\"\"\n        logger.debug(\"ArgosApplication.quit called\")\n        assert len(self.mainWindows) == 0, \\\n            \"Bug: still {} windows present at application quit!\".format(len(self.mainWindows))\n        self.qApplication.quit()", "title": ""}
{"_id": "d4272", "text": "def _count_leading_whitespace(text):\n  \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n  idx = 0\n  for idx, char in enumerate(text):\n    if not char.isspace():\n      return idx\n  return idx + 1", "title": ""}
{"_id": "d4273", "text": "def state(self):\n        \"\"\"Return internal state, useful for testing.\"\"\"\n        return {'c': self.c, 's0': self.s0, 's1': self.s1, 's2': self.s2}", "title": ""}
{"_id": "d4274", "text": "def count(lines):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  words = [w for l in lines for w in l.strip().split()]\n  return Counter(words)", "title": ""}
{"_id": "d4275", "text": "def indent(self):\n        \"\"\"\n        Begins an indented block. Must be used in a 'with' code block.\n        All calls to the logger inside of the block will be indented.\n        \"\"\"\n        blk = IndentBlock(self, self._indent)\n        self._indent += 1\n        return blk", "title": ""}
{"_id": "d4276", "text": "def nlargest(self, n=None):\n\t\t\"\"\"List the n most common elements and their counts.\n\n\t\tList is from the most\n\t\tcommon to the least.  If n is None, the list all element counts.\n\n\t\tRun time should be O(m log m) where m is len(self)\n\t\tArgs:\n\t\t\tn (int): The number of elements to return\n\t\t\"\"\"\n\t\tif n is None:\n\t\t\treturn sorted(self.counts(), key=itemgetter(1), reverse=True)\n\t\telse:\n\t\t\treturn heapq.nlargest(n, self.counts(), key=itemgetter(1))", "title": ""}
{"_id": "d4277", "text": "def _replace_file(path, content):\n  \"\"\"Writes a file if it doesn't already exist with the same content.\n\n  This is useful because cargo uses timestamps to decide whether to compile things.\"\"\"\n  if os.path.exists(path):\n    with open(path, 'r') as f:\n      if content == f.read():\n        print(\"Not overwriting {} because it is unchanged\".format(path), file=sys.stderr)\n        return\n\n  with open(path, 'w') as f:\n    f.write(content)", "title": ""}
{"_id": "d4278", "text": "def get_cov(config):\n    \"\"\"Returns the coverage object of pytest-cov.\"\"\"\n\n    # Check with hasplugin to avoid getplugin exception in older pytest.\n    if config.pluginmanager.hasplugin('_cov'):\n        plugin = config.pluginmanager.getplugin('_cov')\n        if plugin.cov_controller:\n            return plugin.cov_controller.cov\n    return None", "title": ""}
{"_id": "d4279", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d4280", "text": "def create_path(path):\n    \"\"\"Creates a absolute path in the file system.\n\n    :param path: The path to be created\n    \"\"\"\n    import os\n    if not os.path.exists(path):\n        os.makedirs(path)", "title": ""}
{"_id": "d4281", "text": "def setblocking(fd, blocking):\n    \"\"\"Set the O_NONBLOCK flag for a file descriptor. Availability: Unix.\"\"\"\n    if not fcntl:\n        warnings.warn('setblocking() not supported on Windows')\n    flags = fcntl.fcntl(fd, fcntl.F_GETFL)\n    if blocking:\n        flags |= os.O_NONBLOCK\n    else:\n        flags &= ~os.O_NONBLOCK\n    fcntl.fcntl(fd, fcntl.F_SETFL, flags)", "title": ""}
{"_id": "d4282", "text": "def from_rectangle(box):\n        \"\"\" Create a vector randomly within the given rectangle. \"\"\"\n        x = box.left + box.width * random.uniform(0, 1)\n        y = box.bottom + box.height * random.uniform(0, 1)\n        return Vector(x, y)", "title": ""}
{"_id": "d4283", "text": "def paste(xsel=False):\n    \"\"\"Returns system clipboard contents.\"\"\"\n    selection = \"primary\" if xsel else \"clipboard\"\n    try:\n        return subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"utf-8\")\n    except OSError as why:\n        raise XclipNotFound", "title": ""}
{"_id": "d4284", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d4285", "text": "def check_git():\n    \"\"\"Check if git command is available.\"\"\"\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.\")", "title": ""}
{"_id": "d4286", "text": "def fromDict(cls, _dict):\n        \"\"\" Builds instance from dictionary of properties. \"\"\"\n        obj = cls()\n        obj.__dict__.update(_dict)\n        return obj", "title": ""}
{"_id": "d4287", "text": "def get_readline_tail(self, n=10):\n        \"\"\"Get the last n items in readline history.\"\"\"\n        end = self.shell.readline.get_current_history_length() + 1\n        start = max(end-n, 1)\n        ghi = self.shell.readline.get_history_item\n        return [ghi(x) for x in range(start, end)]", "title": ""}
{"_id": "d4288", "text": "def surface(cls, predstr):\n        \"\"\"Instantiate a Pred from its quoted string representation.\"\"\"\n        lemma, pos, sense, _ = split_pred_string(predstr)\n        return cls(Pred.SURFACE, lemma, pos, sense, predstr)", "title": ""}
{"_id": "d4289", "text": "def csv_matrix_print(classes, table):\n    \"\"\"\n    Return matrix as csv data.\n\n    :param classes: classes list\n    :type classes:list\n    :param table: table\n    :type table:dict\n    :return:\n    \"\"\"\n    result = \"\"\n    classes.sort()\n    for i in classes:\n        for j in classes:\n            result += str(table[i][j]) + \",\"\n        result = result[:-1] + \"\\n\"\n    return result[:-1]", "title": ""}
{"_id": "d4290", "text": "def _ensure_element(tup, elem):\n    \"\"\"\n    Create a tuple containing all elements of tup, plus elem.\n\n    Returns the new tuple and the index of elem in the new tuple.\n    \"\"\"\n    try:\n        return tup, tup.index(elem)\n    except ValueError:\n        return tuple(chain(tup, (elem,))), len(tup)", "title": ""}
{"_id": "d4291", "text": "def to_unicode_repr( _letter ):\n    \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n        in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n    # Python 2-3 compatible\n    return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"", "title": ""}
{"_id": "d4292", "text": "def vectorize(values):\n    \"\"\"\n    Takes a value or list of values and returns a single result, joined by \",\"\n    if necessary.\n    \"\"\"\n    if isinstance(values, list):\n        return ','.join(str(v) for v in values)\n    return values", "title": ""}
{"_id": "d4293", "text": "def set_icon(self, bmp):\n        \"\"\"Sets main window icon to given wx.Bitmap\"\"\"\n\n        _icon = wx.EmptyIcon()\n        _icon.CopyFromBitmap(bmp)\n        self.SetIcon(_icon)", "title": ""}
{"_id": "d4294", "text": "def create_symlink(source, link_name):\n    \"\"\"\n    Creates symbolic link for either operating system.\n\n    http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows\n    \"\"\"\n    os_symlink = getattr(os, \"symlink\", None)\n    if isinstance(os_symlink, collections.Callable):\n        os_symlink(source, link_name)\n    else:\n        import ctypes\n        csl = ctypes.windll.kernel32.CreateSymbolicLinkW\n        csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n        csl.restype = ctypes.c_ubyte\n        flags = 1 if os.path.isdir(source) else 0\n        if csl(link_name, source, flags) == 0:\n            raise ctypes.WinError()", "title": ""}
{"_id": "d4295", "text": "def _update_bordercolor(self, bordercolor):\n        \"\"\"Updates background color\"\"\"\n\n        border_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVEBORDER)\n        border_color.SetRGB(bordercolor)\n\n        self.linecolor_choice.SetColour(border_color)", "title": ""}
{"_id": "d4296", "text": "def autoconvert(string):\n    \"\"\"Try to convert variables into datatypes.\"\"\"\n    for fn in (boolify, int, float):\n        try:\n            return fn(string)\n        except ValueError:\n            pass\n    return string", "title": ""}
{"_id": "d4297", "text": "def on_close(self, evt):\n    \"\"\"\n    Pop-up menu and wx.EVT_CLOSE closing event\n    \"\"\"\n    self.stop() # DoseWatcher\n    if evt.EventObject is not self: # Avoid deadlocks\n      self.Close() # wx.Frame\n    evt.Skip()", "title": ""}
{"_id": "d4298", "text": "def connect(*args, **kwargs):\n    \"\"\"Create database connection, use TraceCursor as the cursor_factory.\"\"\"\n    kwargs['cursor_factory'] = TraceCursor\n    conn = pg_connect(*args, **kwargs)\n    return conn", "title": ""}
{"_id": "d4299", "text": "def get_screen_resolution(self):\n        \"\"\"Return the screen resolution of the primary screen.\"\"\"\n        widget = QDesktopWidget()\n        geometry = widget.availableGeometry(widget.primaryScreen())\n        return geometry.width(), geometry.height()", "title": ""}
{"_id": "d4300", "text": "def from_tuple(tup):\n    \"\"\"Convert a tuple into a range with error handling.\n\n    Parameters\n    ----------\n    tup : tuple (len 2 or 3)\n        The tuple to turn into a range.\n\n    Returns\n    -------\n    range : range\n        The range from the tuple.\n\n    Raises\n    ------\n    ValueError\n        Raised when the tuple length is not 2 or 3.\n    \"\"\"\n    if len(tup) not in (2, 3):\n        raise ValueError(\n            'tuple must contain 2 or 3 elements, not: %d (%r' % (\n                len(tup),\n                tup,\n            ),\n        )\n    return range(*tup)", "title": ""}
{"_id": "d4301", "text": "def _trim(image):\n    \"\"\"Trim a PIL image and remove white space.\"\"\"\n    background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n    diff = PIL.ImageChops.difference(image, background)\n    diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n    bbox = diff.getbbox()\n    if bbox:\n        image = image.crop(bbox)\n    return image", "title": ""}
{"_id": "d4302", "text": "def cint8_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):\n        return np.fromiter(cptr, dtype=np.int8, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d4303", "text": "def submit(self, fn, *args, **kwargs):\n        \"\"\"Submit an operation\"\"\"\n        corofn = asyncio.coroutine(lambda: fn(*args, **kwargs))\n        return run_coroutine_threadsafe(corofn(), self.loop)", "title": ""}
{"_id": "d4304", "text": "def import_js(path, lib_name, globals):\n    \"\"\"Imports from javascript source file.\n      globals is your globals()\"\"\"\n    with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:\n        js = f.read()\n    e = EvalJs()\n    e.execute(js)\n    var = e.context['var']\n    globals[lib_name] = var.to_python()", "title": ""}
{"_id": "d4305", "text": "def sample_correlations(self):\n        \"\"\"Returns an `ExpMatrix` containing all pairwise sample correlations.\n\n        Returns\n        -------\n        `ExpMatrix`\n            The sample correlation matrix.\n\n        \"\"\"\n        C = np.corrcoef(self.X.T)\n        corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)\n        return corr_matrix", "title": ""}
{"_id": "d4306", "text": "def clone_with_copy(src_path, dest_path):\n    \"\"\"Clone a directory try by copying it.\n\n   Args:\n        src_path: The directory to be copied.\n        dest_path: The location to copy the directory to.\n    \"\"\"\n    log.info('Cloning directory tree %s to %s', src_path, dest_path)\n    shutil.copytree(src_path, dest_path)", "title": ""}
{"_id": "d4307", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d4308", "text": "def heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "title": ""}
{"_id": "d4309", "text": "def coverage():\n    \"\"\"check code coverage quickly with the default Python\"\"\"\n    run(\"coverage run --source {PROJECT_NAME} -m py.test\".format(PROJECT_NAME=PROJECT_NAME))\n    run(\"coverage report -m\")\n    run(\"coverage html\")\n\n    webbrowser.open('file://' + os.path.realpath(\"htmlcov/index.html\"), new=2)", "title": ""}
{"_id": "d4310", "text": "def action(self):\n        \"\"\"\n        This class overrides this method\n        \"\"\"\n        self.return_value = self.function(*self.args, **self.kwargs)", "title": ""}
{"_id": "d4311", "text": "def string_to_int( s ):\n  \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n  result = 0\n  for c in s:\n    if not isinstance(c, int): c = ord( c )\n    result = 256 * result + c\n  return result", "title": ""}
{"_id": "d4312", "text": "def one_hot2string(arr, vocab):\n    \"\"\"Convert a one-hot encoded array back to string\n    \"\"\"\n    tokens = one_hot2token(arr)\n    indexToLetter = _get_index_dict(vocab)\n\n    return [''.join([indexToLetter[x] for x in row]) for row in tokens]", "title": ""}
{"_id": "d4313", "text": "def new_from_list(cls, items, **kwargs):\n        \"\"\"Populates the ListView with a string list.\n\n        Args:\n            items (list): list of strings to fill the widget with.\n        \"\"\"\n        obj = cls(**kwargs)\n        for item in items:\n            obj.append(ListItem(item))\n        return obj", "title": ""}
{"_id": "d4314", "text": "def csvtolist(inputstr):\n    \"\"\" converts a csv string into a list \"\"\"\n    reader = csv.reader([inputstr], skipinitialspace=True)\n    output = []\n    for r in reader:\n        output += r\n    return output", "title": ""}
{"_id": "d4315", "text": "def get_naive(dt):\n  \"\"\"Gets a naive datetime from a datetime.\n\n  datetime_tz objects can't just have tzinfo replaced with None, you need to\n  call asdatetime.\n\n  Args:\n    dt: datetime object.\n\n  Returns:\n    datetime object without any timezone information.\n  \"\"\"\n  if not dt.tzinfo:\n    return dt\n  if hasattr(dt, \"asdatetime\"):\n    return dt.asdatetime()\n  return dt.replace(tzinfo=None)", "title": ""}
{"_id": "d4316", "text": "def putkeyword(self, keyword, value, makesubrecord=False):\n        \"\"\"Put the value of a column keyword.\n        (see :func:`table.putcolkeyword`)\"\"\"\n        return self._table.putcolkeyword(self._column, keyword, value, makesubrecord)", "title": ""}
{"_id": "d4317", "text": "def format_op_hdr():\n    \"\"\"\n    Build the header\n    \"\"\"\n    txt = 'Base Filename'.ljust(36) + ' '\n    txt += 'Lines'.rjust(7) + ' '\n    txt += 'Words'.rjust(7) + '  '\n    txt += 'Unique'.ljust(8) + ''\n    return txt", "title": ""}
{"_id": "d4318", "text": "def setValue(self, p_float):\n        \"\"\"Override method to set a value to show it as 0 to 100.\n\n        :param p_float: The float number that want to be set.\n        :type p_float: float\n        \"\"\"\n        p_float = p_float * 100\n\n        super(PercentageSpinBox, self).setValue(p_float)", "title": ""}
{"_id": "d4319", "text": "def get_adjacent_matrix(self):\n        \"\"\"Get adjacency matrix.\n\n        Returns:\n            :param adj: adjacency matrix\n            :type adj: np.ndarray\n        \"\"\"\n        edges = self.edges\n        num_edges = len(edges) + 1\n        adj = np.zeros([num_edges, num_edges])\n\n        for k in range(num_edges - 1):\n            adj[edges[k].L, edges[k].R] = 1\n            adj[edges[k].R, edges[k].L] = 1\n\n        return adj", "title": ""}
{"_id": "d4320", "text": "def format_arg(value):\n    \"\"\"\n    :param value:\n        Some value in a dataset.\n    :type value:\n        varies\n    :return:\n        unicode representation of that value\n    :rtype:\n        `unicode`\n    \"\"\"\n    translator = repr if isinstance(value, six.string_types) else six.text_type\n    return translator(value)", "title": ""}
{"_id": "d4321", "text": "def makedirs(directory):\n    \"\"\" Resursively create a named directory. \"\"\"\n    parent = os.path.dirname(os.path.abspath(directory))\n    if not os.path.exists(parent):\n        makedirs(parent)\n    os.mkdir(directory)", "title": ""}
{"_id": "d4322", "text": "def hex_to_hsv(color):\n    \"\"\"\n    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')\n    \"\"\"\n    color = normalize(color)\n    color = color[1:]\n    # color=tuple(ord(c)/255.0 for c in color.decode('hex'))\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)", "title": ""}
{"_id": "d4323", "text": "def create_db_schema(cls, cur, schema_name):\n        \"\"\"\n        Create Postgres schema script and execute it on cursor\n        \"\"\"\n        create_schema_script = \"CREATE SCHEMA {0} ;\\n\".format(schema_name)\n        cur.execute(create_schema_script)", "title": ""}
{"_id": "d4324", "text": "def format_time(time):\n    \"\"\" Formats the given time into HH:MM:SS \"\"\"\n    h, r = divmod(time / 1000, 3600)\n    m, s = divmod(r, 60)\n\n    return \"%02d:%02d:%02d\" % (h, m, s)", "title": ""}
{"_id": "d4325", "text": "def fromDict(cls, _dict):\n        \"\"\" Builds instance from dictionary of properties. \"\"\"\n        obj = cls()\n        obj.__dict__.update(_dict)\n        return obj", "title": ""}
{"_id": "d4326", "text": "def create_rot2d(angle):\n    \"\"\"Create 2D rotation matrix\"\"\"\n    ca = math.cos(angle)\n    sa = math.sin(angle)\n    return np.array([[ca, -sa], [sa, ca]])", "title": ""}
{"_id": "d4327", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d4328", "text": "def list(self):\n        \"\"\"position in 3d space\"\"\"\n        return [self._pos3d.x, self._pos3d.y, self._pos3d.z]", "title": ""}
{"_id": "d4329", "text": "def sp_rand(m,n,a):\n    \"\"\"\n    Generates an mxn sparse 'd' matrix with round(a*m*n) nonzeros.\n    \"\"\"\n    if m == 0 or n == 0: return spmatrix([], [], [], (m,n))\n    nnz = min(max(0, int(round(a*m*n))), m*n)\n    nz = matrix(random.sample(range(m*n), nnz), tc='i')\n    return spmatrix(normal(nnz,1), nz%m, matrix([int(ii) for ii in nz/m]), (m,n))", "title": ""}
{"_id": "d4330", "text": "def create_rot2d(angle):\n    \"\"\"Create 2D rotation matrix\"\"\"\n    ca = math.cos(angle)\n    sa = math.sin(angle)\n    return np.array([[ca, -sa], [sa, ca]])", "title": ""}
{"_id": "d4331", "text": "def append_table(self, name, **kwargs):\n        \"\"\"Create a new table.\"\"\"\n        self.stack.append(Table(name, **kwargs))", "title": ""}
{"_id": "d4332", "text": "def build_gui(self, container):\n        \"\"\"\n        This is responsible for building the viewer's UI.  It should\n        place the UI in `container`.  Override this to make a custom\n        UI.\n        \"\"\"\n        vbox = Widgets.VBox()\n        vbox.set_border_width(0)\n\n        w = Viewers.GingaViewerWidget(viewer=self)\n        vbox.add_widget(w, stretch=1)\n\n        # need to put this in an hbox with an expanding label or the\n        # browser wants to resize the canvas, distorting it\n        hbox = Widgets.HBox()\n        hbox.add_widget(vbox, stretch=0)\n        hbox.add_widget(Widgets.Label(''), stretch=1)\n\n        container.set_widget(hbox)", "title": ""}
{"_id": "d4333", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d4334", "text": "def add_object(self, obj):\n        \"\"\"Add object to local and app environment storage\n\n        :param obj: Instance of a .NET object\n        \"\"\"\n        if obj.top_level_object:\n            if isinstance(obj, DotNetNamespace):\n                self.namespaces[obj.name] = obj\n        self.objects[obj.id] = obj", "title": ""}
{"_id": "d4335", "text": "def get_2D_samples_gauss(n, m, sigma, random_state=None):\n    \"\"\" Deprecated see  make_2D_samples_gauss   \"\"\"\n    return make_2D_samples_gauss(n, m, sigma, random_state=None)", "title": ""}
{"_id": "d4336", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d4337", "text": "def str_to_class(class_name):\n    \"\"\"\n    Returns a class based on class name    \n    \"\"\"\n    mod_str, cls_str = class_name.rsplit('.', 1)\n    mod = __import__(mod_str, globals(), locals(), [''])\n    cls = getattr(mod, cls_str)\n    return cls", "title": ""}
{"_id": "d4338", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d4339", "text": "def next(self):\n        \"\"\"Retrieve the next row.\"\"\"\n        # I'm pretty sure this is the completely wrong way to go about this, but\n        # oh well, this works.\n        if not hasattr(self, '_iter'):\n            self._iter = self.readrow_as_dict()\n        return self._iter.next()", "title": ""}
{"_id": "d4340", "text": "def move_datetime_year(dt, direction, num_shifts):\n    \"\"\"\n    Move datetime 1 year in the chosen direction.\n    unit is a no-op, to keep the API the same as the day case\n    \"\"\"\n    delta = relativedelta(years=+num_shifts)\n    return _move_datetime(dt, direction, delta)", "title": ""}
{"_id": "d4341", "text": "def getBuffer(x):\n    \"\"\"\n    Copy @x into a (modifiable) ctypes byte array\n    \"\"\"\n    b = bytes(x)\n    return (c_ubyte * len(b)).from_buffer_copy(bytes(x))", "title": ""}
{"_id": "d4342", "text": "def write_color(string, name, style='normal', when='auto'):\n    \"\"\" Write the given colored string to standard out. \"\"\"\n    write(color(string, name, style, when))", "title": ""}
{"_id": "d4343", "text": "def cint8_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):\n        return np.fromiter(cptr, dtype=np.int8, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d4344", "text": "def dumped(text, level, indent=2):\n    \"\"\"Put curly brackets round an indented text\"\"\"\n    return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "title": ""}
{"_id": "d4345", "text": "def cfloat32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n        return np.fromiter(cptr, dtype=np.float32, count=length)\n    else:\n        raise RuntimeError('Expected float pointer')", "title": ""}
{"_id": "d4346", "text": "def version_jar(self):\n\t\t\"\"\"\n\t\tSpecial case of version() when the executable is a JAR file.\n\t\t\"\"\"\n\t\tcmd = config.get_command('java')\n\t\tcmd.append('-jar')\n\t\tcmd += self.cmd\n\t\tself.version(cmd=cmd, path=self.cmd[0])", "title": ""}
{"_id": "d4347", "text": "def c_str(string):\n    \"\"\"\"Convert a python string to C string.\"\"\"\n    if not isinstance(string, str):\n        string = string.decode('ascii')\n    return ctypes.c_char_p(string.encode('utf-8'))", "title": ""}
{"_id": "d4348", "text": "def write_line(self, line, count=1):\n        \"\"\"writes the line and count newlines after the line\"\"\"\n        self.write(line)\n        self.write_newlines(count)", "title": ""}
{"_id": "d4349", "text": "def cint8_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):\n        return np.fromiter(cptr, dtype=np.int8, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d4350", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d4351", "text": "def __enter__(self):\n        \"\"\" Implements the context manager protocol. Specially useful for asserting exceptions\n        \"\"\"\n        clone = self.clone()\n        self._contexts.append(clone)\n        self.reset()\n        return self", "title": ""}
{"_id": "d4352", "text": "def custodian_archive(packages=None):\n    \"\"\"Create a lambda code archive for running custodian.\n\n    Lambda archive currently always includes `c7n` and\n    `pkg_resources`. Add additional packages in the mode block.\n\n    Example policy that includes additional packages\n\n    .. code-block:: yaml\n\n        policy:\n          name: lambda-archive-example\n          resource: s3\n          mode:\n            packages:\n              - botocore\n\n    packages: List of additional packages to include in the lambda archive.\n\n    \"\"\"\n    modules = {'c7n', 'pkg_resources'}\n    if packages:\n        modules = filter(None, modules.union(packages))\n    return PythonPackageArchive(*sorted(modules))", "title": ""}
{"_id": "d4353", "text": "def group(data, num):\n    \"\"\" Split data into chunks of num chars each \"\"\"\n    return [data[i:i+num] for i in range(0, len(data), num)]", "title": ""}
{"_id": "d4354", "text": "def get_adjacent_matrix(self):\n        \"\"\"Get adjacency matrix.\n\n        Returns:\n            :param adj: adjacency matrix\n            :type adj: np.ndarray\n        \"\"\"\n        edges = self.edges\n        num_edges = len(edges) + 1\n        adj = np.zeros([num_edges, num_edges])\n\n        for k in range(num_edges - 1):\n            adj[edges[k].L, edges[k].R] = 1\n            adj[edges[k].R, edges[k].L] = 1\n\n        return adj", "title": ""}
{"_id": "d4355", "text": "def imdecode(image_path):\n    \"\"\"Return BGR image read by opencv\"\"\"\n    import os\n    assert os.path.exists(image_path), image_path + ' not found'\n    im = cv2.imread(image_path)\n    return im", "title": ""}
{"_id": "d4356", "text": "def _xls2col_widths(self, worksheet, tab):\n        \"\"\"Updates col_widths in code_array\"\"\"\n\n        for col in xrange(worksheet.ncols):\n            try:\n                xls_width = worksheet.colinfo_map[col].width\n                pys_width = self.xls_width2pys_width(xls_width)\n                self.code_array.col_widths[col, tab] = pys_width\n\n            except KeyError:\n                pass", "title": ""}
{"_id": "d4357", "text": "def del_Unnamed(df):\n    \"\"\"\n    Deletes all the unnamed columns\n\n    :param df: pandas dataframe\n    \"\"\"\n    cols_del=[c for c in df.columns if 'Unnamed' in c]\n    return df.drop(cols_del,axis=1)", "title": ""}
{"_id": "d4358", "text": "def to_query_parameters(parameters):\n    \"\"\"Converts DB-API parameter values into query parameters.\n\n    :type parameters: Mapping[str, Any] or Sequence[Any]\n    :param parameters: A dictionary or sequence of query parameter values.\n\n    :rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]\n    :returns: A list of query parameters.\n    \"\"\"\n    if parameters is None:\n        return []\n\n    if isinstance(parameters, collections_abc.Mapping):\n        return to_query_parameters_dict(parameters)\n\n    return to_query_parameters_list(parameters)", "title": ""}
{"_id": "d4359", "text": "def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):\n    \"\"\"Replace month strings occurrences with month number.\"\"\"\n    num, abbr = get_month_from_date_str(date_str, lang)\n    return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE)", "title": ""}
{"_id": "d4360", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d4361", "text": "def ToDatetime(self):\n    \"\"\"Converts Timestamp to datetime.\"\"\"\n    return datetime.utcfromtimestamp(\n        self.seconds + self.nanos / float(_NANOS_PER_SECOND))", "title": ""}
{"_id": "d4362", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d4363", "text": "def parse_datetime(dt_str, format):\n    \"\"\"Create a timezone-aware datetime object from a datetime string.\"\"\"\n    t = time.strptime(dt_str, format)\n    return datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], pytz.UTC)", "title": ""}
{"_id": "d4364", "text": "def vec_angle(a, b):\n    \"\"\"\n    Calculate angle between two vectors\n    \"\"\"\n    cosang = np.dot(a, b)\n    sinang = fast_norm(np.cross(a, b))\n    return np.arctan2(sinang, cosang)", "title": ""}
{"_id": "d4365", "text": "def date_to_timestamp(date):\n    \"\"\"\n        date to unix timestamp in milliseconds\n    \"\"\"\n    date_tuple = date.timetuple()\n    timestamp = calendar.timegm(date_tuple) * 1000\n    return timestamp", "title": ""}
{"_id": "d4366", "text": "def ansi(color, text):\n    \"\"\"Wrap text in an ansi escape sequence\"\"\"\n    code = COLOR_CODES[color]\n    return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)", "title": ""}
{"_id": "d4367", "text": "def _converter(self, value):\n        \"\"\"Convert raw input value of the field.\"\"\"\n        if not isinstance(value, datetime.date):\n            raise TypeError('{0} is not valid date'.format(value))\n        return value", "title": ""}
{"_id": "d4368", "text": "def set_as_object(self, value):\n        \"\"\"\n        Sets a new value to map element\n\n        :param value: a new element or map value.\n        \"\"\"\n        self.clear()\n        map = MapConverter.to_map(value)\n        self.append(map)", "title": ""}
{"_id": "d4369", "text": "def datetime_to_timestamp(dt):\n    \"\"\"Convert a UTC datetime to a Unix timestamp\"\"\"\n    delta = dt - datetime.utcfromtimestamp(0)\n    return delta.seconds + delta.days * 24 * 3600", "title": ""}
{"_id": "d4370", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d4371", "text": "def to_pydatetime(self):\n        \"\"\"\n        Converts datetimeoffset object into Python's datetime.datetime object\n        @return: time zone aware datetime.datetime\n        \"\"\"\n        dt = datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())\n        from .tz import FixedOffsetTimezone\n        return dt.replace(tzinfo=_utc).astimezone(FixedOffsetTimezone(self._offset))", "title": ""}
{"_id": "d4372", "text": "def normalize(self, string):\n        \"\"\"Normalize the string according to normalization list\"\"\"\n        return ''.join([self._normalize.get(x, x) for x in nfd(string)])", "title": ""}
{"_id": "d4373", "text": "def _DateToEpoch(date):\n  \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n  tz_zero = datetime.datetime.utcfromtimestamp(0)\n  diff_sec = int((date - tz_zero).total_seconds())\n  return diff_sec * 1000000", "title": ""}
{"_id": "d4374", "text": "def __enter__(self):\n        \"\"\"Enable the download log filter.\"\"\"\n        self.logger = logging.getLogger('pip.download')\n        self.logger.addFilter(self)", "title": ""}
{"_id": "d4375", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d4376", "text": "def triangle_area(pt1, pt2, pt3):\n    r\"\"\"Return the area of a triangle.\n\n    Parameters\n    ----------\n    pt1: (X,Y) ndarray\n        Starting vertex of a triangle\n    pt2: (X,Y) ndarray\n        Second vertex of a triangle\n    pt3: (X,Y) ndarray\n        Ending vertex of a triangle\n\n    Returns\n    -------\n    area: float\n        Area of the given triangle.\n\n    \"\"\"\n    a = 0.0\n\n    a += pt1[0] * pt2[1] - pt2[0] * pt1[1]\n    a += pt2[0] * pt3[1] - pt3[0] * pt2[1]\n    a += pt3[0] * pt1[1] - pt1[0] * pt3[1]\n\n    return abs(a) / 2", "title": ""}
{"_id": "d4377", "text": "def ToDatetime(self):\n    \"\"\"Converts Timestamp to datetime.\"\"\"\n    return datetime.utcfromtimestamp(\n        self.seconds + self.nanos / float(_NANOS_PER_SECOND))", "title": ""}
{"_id": "d4378", "text": "def parse_command_args():\n    \"\"\"Command line parser.\"\"\"\n    parser = argparse.ArgumentParser(description='Register PB devices.')\n    parser.add_argument('num_pb', type=int,\n                        help='Number of PBs devices to register.')\n    return parser.parse_args()", "title": ""}
{"_id": "d4379", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d4380", "text": "def __len__(self):\n        \"\"\" This will equal 124 for the V1 database. \"\"\"\n        length = 0\n        for typ, siz, _ in self.format:\n            length += siz\n        return length", "title": ""}
{"_id": "d4381", "text": "def string_to_int( s ):\n  \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n  result = 0\n  for c in s:\n    if not isinstance(c, int): c = ord( c )\n    result = 256 * result + c\n  return result", "title": ""}
{"_id": "d4382", "text": "def tail(self, n=10):\n        \"\"\"\n        Get an SArray that contains the last n elements in the SArray.\n\n        Parameters\n        ----------\n        n : int\n            The number of elements to fetch\n\n        Returns\n        -------\n        out : SArray\n            A new SArray which contains the last n rows of the current SArray.\n        \"\"\"\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.tail(n))", "title": ""}
{"_id": "d4383", "text": "def decompress(f):\n    \"\"\"Decompress a Plan 9 image file.  Assumes f is already cued past the\n    initial 'compressed\\n' string.\n    \"\"\"\n\n    r = meta(f.read(60))\n    return r, decomprest(f, r[4])", "title": ""}
{"_id": "d4384", "text": "def is_scalar(value):\n    \"\"\"Test if the given value is a scalar.\n\n    This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n    Args:\n        value: the value to test for being a scalar value\n\n    Returns:\n        boolean: if the given value is a scalar or not\n    \"\"\"\n    return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))", "title": ""}
{"_id": "d4385", "text": "def purge_duplicates(list_in):\n    \"\"\"Remove duplicates from list while preserving order.\n\n    Parameters\n    ----------\n    list_in: Iterable\n\n    Returns\n    -------\n    list\n        List of first occurences in order\n    \"\"\"\n    _list = []\n    for item in list_in:\n        if item not in _list:\n            _list.append(item)\n    return _list", "title": ""}
{"_id": "d4386", "text": "def is_parameter(self):\n        \"\"\"Whether this is a function parameter.\"\"\"\n        return (isinstance(self.scope, CodeFunction)\n                and self in self.scope.parameters)", "title": ""}
{"_id": "d4387", "text": "def input_int_default(question=\"\", default=0):\n    \"\"\"A function that works for both, Python 2.x and Python 3.x.\n       It asks the user for input and returns it as a string.\n    \"\"\"\n    answer = input_string(question)\n    if answer == \"\" or answer == \"yes\":\n        return default\n    else:\n        return int(answer)", "title": ""}
{"_id": "d4388", "text": "def figsize(x=8, y=7., aspect=1.):\n    \"\"\" manually set the default figure size of plots\n    ::Arguments::\n        x (float): x-axis size\n        y (float): y-axis size\n        aspect (float): aspect ratio scalar\n    \"\"\"\n    # update rcparams with adjusted figsize params\n    mpl.rcParams.update({'figure.figsize': (x*aspect, y)})", "title": ""}
{"_id": "d4389", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d4390", "text": "def assert_list(self, putative_list, expected_type=string_types, key_arg=None):\n    \"\"\"\n    :API: public\n    \"\"\"\n    return assert_list(putative_list, expected_type, key_arg=key_arg,\n                       raise_type=lambda msg: TargetDefinitionException(self, msg))", "title": ""}
{"_id": "d4391", "text": "def delete_cell(self,  key):\n        \"\"\"Deletes key cell\"\"\"\n\n        try:\n            self.code_array.pop(key)\n\n        except KeyError:\n            pass\n\n        self.grid.code_array.result_cache.clear()", "title": ""}
{"_id": "d4392", "text": "def pop():\n        \"\"\"Remove instance from instance list\"\"\"\n        pid = os.getpid()\n        thread = threading.current_thread()\n        Wdb._instances.pop((pid, thread))", "title": ""}
{"_id": "d4393", "text": "def runcoro(async_function):\n    \"\"\"\n    Runs an asynchronous function without needing to use await - useful for lambda\n\n    Args:\n        async_function (Coroutine): The asynchronous function to run\n    \"\"\"\n\n    future = _asyncio.run_coroutine_threadsafe(async_function, client.loop)\n    result = future.result()\n    return result", "title": ""}
{"_id": "d4394", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d4395", "text": "def datetime_from_timestamp(timestamp, content):\n    \"\"\"\n    Helper function to add timezone information to datetime,\n    so that datetime is comparable to other datetime objects in recent versions\n    that now also have timezone information.\n    \"\"\"\n    return set_date_tzinfo(\n        datetime.fromtimestamp(timestamp),\n        tz_name=content.settings.get('TIMEZONE', None))", "title": ""}
{"_id": "d4396", "text": "def remove(self, key):\n        \"\"\"remove the value found at key from the queue\"\"\"\n        item = self.item_finder.pop(key)\n        item[-1] = None\n        self.removed_count += 1", "title": ""}
{"_id": "d4397", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d4398", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d4399", "text": "def lambda_from_file(python_file):\n    \"\"\"\n    Reads a python file and returns a awslambda.Code object\n    :param python_file:\n    :return:\n    \"\"\"\n    lambda_function = []\n    with open(python_file, 'r') as f:\n        lambda_function.extend(f.read().splitlines())\n\n    return awslambda.Code(ZipFile=(Join('\\n', lambda_function)))", "title": ""}
{"_id": "d4400", "text": "def copy_user_agent_from_driver(self):\n        \"\"\" 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.\n        \"\"\"\n        selenium_user_agent = self.driver.execute_script(\"return navigator.userAgent;\")\n        self.headers.update({\"user-agent\": selenium_user_agent})", "title": ""}
{"_id": "d4401", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d4402", "text": "def lock_file(f, block=False):\n    \"\"\"\n    If block=False (the default), die hard and fast if another process has\n    already grabbed the lock for this file.\n\n    If block=True, wait for the lock to be released, then continue.\n    \"\"\"\n    try:\n        flags = fcntl.LOCK_EX\n        if not block:\n            flags |= fcntl.LOCK_NB\n        fcntl.flock(f.fileno(), flags)\n    except IOError as e:\n        if e.errno in (errno.EACCES, errno.EAGAIN):\n            raise SystemExit(\"ERROR: %s is locked by another process.\" %\n                             f.name)\n        raise", "title": ""}
{"_id": "d4403", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d4404", "text": "def is_connected(self):\n        \"\"\"\n        Return true if the socket managed by this connection is connected\n\n        :rtype: bool\n        \"\"\"\n        try:\n            return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)\n        except socket.error:\n            return False", "title": ""}
{"_id": "d4405", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d4406", "text": "def determine_interactive(self):\n\t\t\"\"\"Determine whether we're in an interactive shell.\n\t\tSets interactivity off if appropriate.\n\t\tcf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):\n\t\t\t\tself.interactive = 0\n\t\t\t\treturn False\n\t\texcept Exception:\n\t\t\tself.interactive = 0\n\t\t\treturn False\n\t\tif self.interactive == 0:\n\t\t\treturn False\n\t\treturn True", "title": ""}
{"_id": "d4407", "text": "def region_from_segment(image, segment):\n    \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n    x, y, w, h = segment\n    return image[y:y + h, x:x + w]", "title": ""}
{"_id": "d4408", "text": "def _swap_rows(self, i, j):\n        \"\"\"Swap i and j rows\n\n        As the side effect, determinant flips.\n\n        \"\"\"\n\n        L = np.eye(3, dtype='intc')\n        L[i, i] = 0\n        L[j, j] = 0\n        L[i, j] = 1\n        L[j, i] = 1\n        self._L.append(L.copy())\n        self._A = np.dot(L, self._A)", "title": ""}
{"_id": "d4409", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d4410", "text": "def create_bigquery_table(self, database, schema, table_name, callback,\n                              sql):\n        \"\"\"Create a bigquery table. The caller must supply a callback\n        that takes one argument, a `google.cloud.bigquery.Table`, and mutates\n        it.\n        \"\"\"\n        conn = self.get_thread_connection()\n        client = conn.handle\n\n        view_ref = self.table_ref(database, schema, table_name, conn)\n        view = google.cloud.bigquery.Table(view_ref)\n        callback(view)\n\n        with self.exception_handler(sql):\n            client.create_table(view)", "title": ""}
{"_id": "d4411", "text": "def _guess_extract_method(fname):\n  \"\"\"Guess extraction method, given file name (or path).\"\"\"\n  for method, extensions in _EXTRACTION_METHOD_TO_EXTS:\n    for ext in extensions:\n      if fname.endswith(ext):\n        return method\n  return ExtractMethod.NO_EXTRACT", "title": ""}
{"_id": "d4412", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d4413", "text": "def is_sparse_vector(x):\n    \"\"\" x is a 2D sparse matrix with it's first shape equal to 1.\n    \"\"\"\n    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1", "title": ""}
{"_id": "d4414", "text": "def xeval(source, optimize=True):\n    \"\"\"Compiles to native Python bytecode and runs program, returning the\n    topmost value on the stack.\n\n    Args:\n        optimize: Whether to optimize the code after parsing it.\n\n    Returns:\n        None: If the stack is empty\n        obj: If the stack contains a single value\n        [obj, obj, ...]: If the stack contains many values\n    \"\"\"\n    native = xcompile(source, optimize=optimize)\n    return native()", "title": ""}
{"_id": "d4415", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d4416", "text": "def bootstrap_indexes(data, n_samples=10000):\n    \"\"\"\nGiven data points data, where axis 0 is considered to delineate points, return\nan generator for sets of bootstrap indexes. This can be used as a list\nof bootstrap indexes (with list(bootstrap_indexes(data))) as well.\n    \"\"\"\n    for _ in xrange(n_samples):\n        yield randint(data.shape[0], size=(data.shape[0],))", "title": ""}
{"_id": "d4417", "text": "def is_callable(*p):\n    \"\"\" True if all the args are functions and / or subroutines\n    \"\"\"\n    import symbols\n    return all(isinstance(x, symbols.FUNCTION) for x in p)", "title": ""}
{"_id": "d4418", "text": "def _aws_get_instance_by_tag(region, name, tag, raw):\n    \"\"\"Get all instances matching a tag.\"\"\"\n    client = boto3.session.Session().client('ec2', region)\n    matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', [])\n    instances = []\n    [[instances.append(_aws_instance_from_dict(region, instance, raw))  # pylint: disable=expression-not-assigned\n      for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation]\n    return instances", "title": ""}
{"_id": "d4419", "text": "def is_image(filename):\n    \"\"\"Determine if given filename is an image.\"\"\"\n    # note: isfile() also accepts symlinks\n    return os.path.isfile(filename) and filename.lower().endswith(ImageExts)", "title": ""}
{"_id": "d4420", "text": "def default_static_path():\n    \"\"\"\n        Return the path to the javascript bundle\n    \"\"\"\n    fdir = os.path.dirname(__file__)\n    return os.path.abspath(os.path.join(fdir, '../assets/'))", "title": ""}
{"_id": "d4421", "text": "def display_len(text):\n    \"\"\"\n    Get the display length of a string. This can differ from the character\n    length if the string contains wide characters.\n    \"\"\"\n    text = unicodedata.normalize('NFD', text)\n    return sum(char_width(char) for char in text)", "title": ""}
{"_id": "d4422", "text": "def compute_boxplot(self, series):\n        \"\"\"\n        Compute boxplot for given pandas Series.\n        \"\"\"\n        from matplotlib.cbook import boxplot_stats\n        series = series[series.notnull()]\n        if len(series.values) == 0:\n            return {}\n        elif not is_numeric_dtype(series):\n            return self.non_numeric_stats(series)\n        stats = boxplot_stats(list(series.values))[0]\n        stats['count'] = len(series.values)\n        stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n        return stats", "title": ""}
{"_id": "d4423", "text": "def IsBinary(self, filename):\n\t\t\"\"\"Returns true if the guessed mimetyped isnt't in text group.\"\"\"\n\t\tmimetype = mimetypes.guess_type(filename)[0]\n\t\tif not mimetype:\n\t\t\treturn False  # e.g. README, \"real\" binaries usually have an extension\n\t\t# special case for text files which don't start with text/\n\t\tif mimetype in TEXT_MIMETYPES:\n\t\t\treturn False\n\t\treturn not mimetype.startswith(\"text/\")", "title": ""}
{"_id": "d4424", "text": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "title": ""}
{"_id": "d4425", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d4426", "text": "def retrieve_by_id(self, id_):\n        \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n        items_with_id = [item for item in self if item.id == int(id_)]\n        if len(items_with_id) == 1:\n            return items_with_id[0].retrieve()", "title": ""}
{"_id": "d4427", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d4428", "text": "def install_rpm_py():\n    \"\"\"Install RPM Python binding.\"\"\"\n    python_path = sys.executable\n    cmd = '{0} install.py'.format(python_path)\n    exit_status = os.system(cmd)\n    if exit_status != 0:\n        raise Exception('Command failed: {0}'.format(cmd))", "title": ""}
{"_id": "d4429", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d4430", "text": "def is_iter_non_string(obj):\n    \"\"\"test if object is a list or tuple\"\"\"\n    if isinstance(obj, list) or isinstance(obj, tuple):\n        return True\n    return False", "title": ""}
{"_id": "d4431", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d4432", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d4433", "text": "def dict_to_querystring(dictionary):\n    \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\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]", "title": ""}
{"_id": "d4434", "text": "def convert_timeval(seconds_since_epoch):\n    \"\"\"Convert time into C style timeval.\"\"\"\n    frac, whole = math.modf(seconds_since_epoch)\n    microseconds = math.floor(frac * 1000000)\n    seconds = math.floor(whole)\n    return seconds, microseconds", "title": ""}
{"_id": "d4435", "text": "def copy(self):\n        \"\"\"\n        Return a copy of the dictionary.\n\n        This is a middle-deep copy; the copy is independent of the original in\n        all attributes that have mutable types except for:\n\n        * The values in the dictionary\n\n        Note that the Python functions :func:`py:copy.copy` and\n        :func:`py:copy.deepcopy` can be used to create completely shallow or\n        completely deep copies of objects of this class.\n        \"\"\"\n        result = NocaseDict()\n        result._data = self._data.copy()  # pylint: disable=protected-access\n        return result", "title": ""}
{"_id": "d4436", "text": "def growthfromrange(rangegrowth, startdate, enddate):\n    \"\"\"\n    Annual growth given growth from start date to end date.\n    \"\"\"\n    _yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\\\n            dt.timedelta(365.25).total_seconds()\n    return yrlygrowth(rangegrowth, _yrs)", "title": ""}
{"_id": "d4437", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d4438", "text": "def double_exponential_moving_average(data, period):\n    \"\"\"\n    Double Exponential Moving Average.\n\n    Formula:\n    DEMA = 2*EMA - EMA(EMA)\n    \"\"\"\n    catch_errors.check_for_period_error(data, period)\n\n    dema = (2 * ema(data, period)) - ema(ema(data, period), period)\n    return dema", "title": ""}
{"_id": "d4439", "text": "def multi_pop(d, *args):\n    \"\"\" pops multiple keys off a dict like object \"\"\"\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval", "title": ""}
{"_id": "d4440", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d4441", "text": "def dict_update_newkeys(dict_, dict2):\n    \"\"\" Like dict.update, but does not overwrite items \"\"\"\n    for key, val in six.iteritems(dict2):\n        if key not in dict_:\n            dict_[key] = val", "title": ""}
{"_id": "d4442", "text": "def v_normalize(v):\n    \"\"\"\n    Normalizes the given vector.\n    \n    The vector given may have any number of dimensions.\n    \"\"\"\n    vmag = v_magnitude(v)\n    return [ v[i]/vmag  for i in range(len(v)) ]", "title": ""}
{"_id": "d4443", "text": "def recursively_update(d, d2):\n  \"\"\"dict.update but which merges child dicts (dict2 takes precedence where there's conflict).\"\"\"\n  for k, v in d2.items():\n    if k in d:\n      if isinstance(v, dict):\n        recursively_update(d[k], v)\n        continue\n    d[k] = v", "title": ""}
{"_id": "d4444", "text": "def _days_in_month(date):\n    \"\"\"The number of days in the month of the given 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", "title": ""}
{"_id": "d4445", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d4446", "text": "def count_rows_with_nans(X):\n    \"\"\"Count the number of rows in 2D arrays that contain any nan values.\"\"\"\n    if X.ndim == 2:\n        return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()", "title": ""}
{"_id": "d4447", "text": "def c_array(ctype, values):\n    \"\"\"Convert a python string to c array.\"\"\"\n    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):\n        return (ctype * len(values)).from_buffer_copy(values)\n    return (ctype * len(values))(*values)", "title": ""}
{"_id": "d4448", "text": "def stderr(a):\n    \"\"\"\n    Calculate the standard error of a.\n    \"\"\"\n    return np.nanstd(a) / np.sqrt(sum(np.isfinite(a)))", "title": ""}
{"_id": "d4449", "text": "def is_readable_dir(path):\n  \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n  return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d4450", "text": "def import_js(path, lib_name, globals):\n    \"\"\"Imports from javascript source file.\n      globals is your globals()\"\"\"\n    with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:\n        js = f.read()\n    e = EvalJs()\n    e.execute(js)\n    var = e.context['var']\n    globals[lib_name] = var.to_python()", "title": ""}
{"_id": "d4451", "text": "def disable_cert_validation():\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d4452", "text": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "title": ""}
{"_id": "d4453", "text": "def disable_cert_validation():\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d4454", "text": "def reject(self):\n        \"\"\"\n        Rejects the snapshot and closes the widget.\n        \"\"\"\n        if self.hideWindow():\n            self.hideWindow().show()\n            \n        self.close()\n        self.deleteLater()", "title": ""}
{"_id": "d4455", "text": "def robust_int(v):\n    \"\"\"Parse an int robustly, ignoring commas and other cruft. \"\"\"\n\n    if isinstance(v, int):\n        return v\n\n    if isinstance(v, float):\n        return int(v)\n\n    v = str(v).replace(',', '')\n\n    if not v:\n        return None\n\n    return int(v)", "title": ""}
{"_id": "d4456", "text": "def send(socket, data, num_bytes=20):\n    \"\"\"Send data to specified socket.\n\n\n    :param socket: open socket instance\n    :param data: data to send\n    :param num_bytes: number of bytes to read\n\n    :return: received data\n    \"\"\"\n    pickled_data = pickle.dumps(data, -1)\n    length = str(len(pickled_data)).zfill(num_bytes)\n    socket.sendall(length.encode())\n    socket.sendall(pickled_data)", "title": ""}
{"_id": "d4457", "text": "def _trim_zeros_complex(str_complexes, na_rep='NaN'):\n    \"\"\"\n    Separates the real and imaginary parts from the complex number, and\n    executes the _trim_zeros_float method on each of those.\n    \"\"\"\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\n    return [''.join(separate_and_trim(x, na_rep)) for x in str_complexes]", "title": ""}
{"_id": "d4458", "text": "def to_unicode_repr( _letter ):\n    \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n        in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n    # Python 2-3 compatible\n    return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"", "title": ""}
{"_id": "d4459", "text": "def _text_to_graphiz(self, text):\n        \"\"\"create a graphviz graph from text\"\"\"\n        dot = Source(text, format='svg')\n        return dot.pipe().decode('utf-8')", "title": ""}
{"_id": "d4460", "text": "def to_identifier(s):\n  \"\"\"\n  Convert snake_case to camel_case.\n  \"\"\"\n  if s.startswith('GPS'):\n      s = 'Gps' + s[3:]\n  return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s", "title": ""}
{"_id": "d4461", "text": "def display(self):\n        \"\"\" Get screen width and height \"\"\"\n        w, h = self.session.window_size()\n        return Display(w*self.scale, h*self.scale)", "title": ""}
{"_id": "d4462", "text": "def _snake_to_camel_case(value):\n    \"\"\"Convert snake case string to camel case.\"\"\"\n    words = value.split(\"_\")\n    return words[0] + \"\".join(map(str.capitalize, words[1:]))", "title": ""}
{"_id": "d4463", "text": "def direct2dDistance(self, point):\n        \"\"\"consider the distance between two mapPoints, ignoring all terrain, pathing issues\"\"\"\n        if not isinstance(point, MapPoint): return 0.0\n        return  ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula", "title": ""}
{"_id": "d4464", "text": "def _snake_to_camel_case(value):\n    \"\"\"Convert snake case string to camel case.\"\"\"\n    words = value.split(\"_\")\n    return words[0] + \"\".join(map(str.capitalize, words[1:]))", "title": ""}
{"_id": "d4465", "text": "def deleted(self, instance):\n        \"\"\"\n        Convenience method for deleting a model (automatically commits the\n        delete to the database and returns with an HTTP 204 status code)\n        \"\"\"\n        self.session_manager.delete(instance, commit=True)\n        return '', HTTPStatus.NO_CONTENT", "title": ""}
{"_id": "d4466", "text": "def to_identifier(s):\n  \"\"\"\n  Convert snake_case to camel_case.\n  \"\"\"\n  if s.startswith('GPS'):\n      s = 'Gps' + s[3:]\n  return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s", "title": ""}
{"_id": "d4467", "text": "def show_image(self, key):\n        \"\"\"Show image (item is a PIL image)\"\"\"\n        data = self.model.get_data()\n        data[key].show()", "title": ""}
{"_id": "d4468", "text": "def check_output(args):\n    \"\"\"Runs command and returns the output as string.\"\"\"\n    log.debug('run: %s', args)\n    out = subprocess.check_output(args=args).decode('utf-8')\n    log.debug('out: %r', out)\n    return out", "title": ""}
{"_id": "d4469", "text": "def page_title(step, title):\n    \"\"\"\n    Check that the page title matches the given one.\n    \"\"\"\n\n    with AssertContextManager(step):\n        assert_equals(world.browser.title, title)", "title": ""}
{"_id": "d4470", "text": "def __run(self):\n    \"\"\"Hacked run function, which installs the trace.\"\"\"\n    sys.settrace(self.globaltrace)\n    self.__run_backup()\n    self.run = self.__run_backup", "title": ""}
{"_id": "d4471", "text": "def main():\n    \"\"\"Parse the command line and run :func:`migrate`.\"\"\"\n    parser = get_args_parser()\n    args = parser.parse_args()\n    config = Config.from_parse_args(args)\n    migrate(config)", "title": ""}
{"_id": "d4472", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d4473", "text": "def requests_post(url, data=None, json=None, **kwargs):\n    \"\"\"Requests-mock requests.post wrapper.\"\"\"\n    return requests_request('post', url, data=data, json=json, **kwargs)", "title": ""}
{"_id": "d4474", "text": "def __to_localdatetime(val):\n    \"\"\"Convert val into a local datetime for tz Europe/Amsterdam.\"\"\"\n    try:\n        dt = datetime.strptime(val, __DATE_FORMAT)\n        dt = pytz.timezone(__TIMEZONE).localize(dt)\n        return dt\n    except (ValueError, TypeError):\n        return None", "title": ""}
{"_id": "d4475", "text": "def merge(database=None, directory=None, verbose=None):\n    \"\"\"Merge migrations into one.\"\"\"\n    router = get_router(directory, database, verbose)\n    router.merge()", "title": ""}
{"_id": "d4476", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d4477", "text": "def _add_params_docstring(params):\n    \"\"\" Add params to doc string\n    \"\"\"\n    p_string = \"\\nAccepts the following paramters: \\n\"\n    for param in params:\n         p_string += \"name: %s, required: %s, description: %s \\n\" % (param['name'], param['required'], param['description'])\n    return p_string", "title": ""}
{"_id": "d4478", "text": "def deserialize_date(string):\n    \"\"\"\n    Deserializes string to date.\n\n    :param string: str.\n    :type string: str\n    :return: date.\n    :rtype: date\n    \"\"\"\n    try:\n        from dateutil.parser import parse\n        return parse(string).date()\n    except ImportError:\n        return string", "title": ""}
{"_id": "d4479", "text": "def _add_params_docstring(params):\n    \"\"\" Add params to doc string\n    \"\"\"\n    p_string = \"\\nAccepts the following paramters: \\n\"\n    for param in params:\n         p_string += \"name: %s, required: %s, description: %s \\n\" % (param['name'], param['required'], param['description'])\n    return p_string", "title": ""}
{"_id": "d4480", "text": "def from_string(cls, string):\n        \"\"\"\n        Simply logs a warning if the desired enum value is not found.\n\n        :param string:\n        :return:\n        \"\"\"\n\n        # find enum value\n        for attr in dir(cls):\n            value = getattr(cls, attr)\n            if value == string:\n                return value\n\n        # if not found, log warning and return the value passed in\n        logger.warning(\"{} is not a valid enum value for {}.\".format(string, cls.__name__))\n        return string", "title": ""}
{"_id": "d4481", "text": "def fill_document(doc):\n    \"\"\"Add a section, a subsection and some text to the document.\n\n    :param doc: the document\n    :type doc: :class:`pylatex.document.Document` instance\n    \"\"\"\n    with doc.create(Section('A section')):\n        doc.append('Some regular text and some ')\n        doc.append(italic('italic text. '))\n\n        with doc.create(Subsection('A subsection')):\n            doc.append('Also some crazy characters: $&#{}')", "title": ""}
{"_id": "d4482", "text": "def _attrprint(d, delimiter=', '):\n    \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n    return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))", "title": ""}
{"_id": "d4483", "text": "def callJavaFunc(func, *args):\n    \"\"\" Call Java Function \"\"\"\n    gateway = _get_gateway()\n    args = [_py2java(gateway, a) for a in args]\n    result = func(*args)\n    return _java2py(gateway, result)", "title": ""}
{"_id": "d4484", "text": "def underscore(text):\n    \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n    return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()", "title": ""}
{"_id": "d4485", "text": "def to_str(obj):\n    \"\"\"Attempts to convert given object to a string object\n    \"\"\"\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)", "title": ""}
{"_id": "d4486", "text": "def ucamel_method(func):\n    \"\"\"\n    Decorator to ensure the given snake_case method is also written in\n    UpperCamelCase in the given namespace. That was mainly written to\n    avoid confusion when using wxPython and its UpperCamelCaseMethods.\n    \"\"\"\n    frame_locals = inspect.currentframe().f_back.f_locals\n    frame_locals[snake2ucamel(func.__name__)] = func\n    return func", "title": ""}
{"_id": "d4487", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d4488", "text": "def _converter(self, value):\n        \"\"\"Convert raw input value of the field.\"\"\"\n        if not isinstance(value, datetime.date):\n            raise TypeError('{0} is not valid date'.format(value))\n        return value", "title": ""}
{"_id": "d4489", "text": "def bbox(self):\n        \"\"\"\n        The minimal `~photutils.aperture.BoundingBox` for the cutout\n        region with respect to the original (large) image.\n        \"\"\"\n\n        return BoundingBox(self.slices[1].start, self.slices[1].stop,\n                           self.slices[0].start, self.slices[0].stop)", "title": ""}
{"_id": "d4490", "text": "def linedelimited (inlist,delimiter):\n    \"\"\"\nReturns a string composed of elements in inlist, with each element\nseparated by 'delimiter.'  Used by function writedelimited.  Use '\\t'\nfor tab-delimiting.\n\nUsage:   linedelimited (inlist,delimiter)\n\"\"\"\n    outstr = ''\n    for item in inlist:\n        if type(item) != StringType:\n            item = str(item)\n        outstr = outstr + item + delimiter\n    outstr = outstr[0:-1]\n    return outstr", "title": ""}
{"_id": "d4491", "text": "def _draw_lines_internal(self, coords, colour, bg):\n        \"\"\"Helper to draw lines connecting a set of nodes that are scaled for the Screen.\"\"\"\n        for i, (x, y) in enumerate(coords):\n            if i == 0:\n                self._screen.move(x, y)\n            else:\n                self._screen.draw(x, y, colour=colour, bg=bg, thin=True)", "title": ""}
{"_id": "d4492", "text": "def change_dir(directory):\n  \"\"\"\n  Wraps a function to run in a given directory.\n\n  \"\"\"\n  def cd_decorator(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n      org_path = os.getcwd()\n      os.chdir(directory)\n      func(*args, **kwargs)\n      os.chdir(org_path)\n    return wrapper\n  return cd_decorator", "title": ""}
{"_id": "d4493", "text": "def remove_non_magic_cols(self):\n        \"\"\"\n        Remove all non-MagIC columns from all tables.\n        \"\"\"\n        for table_name in self.tables:\n            table = self.tables[table_name]\n            table.remove_non_magic_cols_from_table()", "title": ""}
{"_id": "d4494", "text": "def title(msg):\n    \"\"\"Sets the title of the console window.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "title": ""}
{"_id": "d4495", "text": "def TextWidget(*args, **kw):\n    \"\"\"Forces a parameter value to be text\"\"\"\n    kw['value'] = str(kw['value'])\n    kw.pop('options', None)\n    return TextInput(*args,**kw)", "title": ""}
{"_id": "d4496", "text": "def scale_dtype(arr, dtype):\n    \"\"\"Convert an array from 0..1 to dtype, scaling up linearly\n    \"\"\"\n    max_int = np.iinfo(dtype).max\n    return (arr * max_int).astype(dtype)", "title": ""}
{"_id": "d4497", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d4498", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d4499", "text": "def ffmpeg_works():\n  \"\"\"Tries to encode images with ffmpeg to check if it 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", "title": ""}
{"_id": "d4500", "text": "def _to_corrected_pandas_type(dt):\n    \"\"\"\n    When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n    This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n    \"\"\"\n    import numpy as np\n    if type(dt) == ByteType:\n        return np.int8\n    elif type(dt) == ShortType:\n        return np.int16\n    elif type(dt) == IntegerType:\n        return np.int32\n    elif type(dt) == FloatType:\n        return np.float32\n    else:\n        return None", "title": ""}
{"_id": "d4501", "text": "def get_record_by_name(self, index, name):\n        \"\"\"\n        Searches for a single document in the given index on the 'name' field .\n        Performs a case-insensitive search by utilizing Elasticsearch's `match_phrase` query.\n    \n        Args:\n            index: `str`. The name of an Elasticsearch index (i.e. biosamples).\n            name: `str`. The value of a document's name key to search for.\n    \n        Returns:\n            `dict` containing the document that was indexed into Elasticsearch.\n    \n        Raises:\n            `MultipleHitsException`: More than 1 hit is returned.\n        \"\"\"\n        result = self.ES.search(\n            index=index,\n            body={\n                \"query\": {\n                    \"match_phrase\": {\n                        \"name\": name,\n                    }\n                }\n            }\n        )\n        hits = result[\"hits\"][\"hits\"]\n        if not hits:\n            return {}\n        elif len(hits) == 1:\n            return hits[0][\"_source\"]\n        else:\n            # Mult. records found with same prefix. See if a single record whose name attr matches\n            # the match phrase exactly (in a lower-case comparison).  \n            for h in hits:\n                source = h[\"_source\"]\n                record_name = source[\"name\"]\n                if record_name.lower().strip() == name.lower().strip():\n                    return source\n            msg = \"match_phrase search found multiple records matching query '{}' for index '{}'.\".format(name, index)\n            raise MultipleHitsException(msg)", "title": ""}
{"_id": "d4502", "text": "def add_datetime(dataframe, timestamp_key='UNIXTIME'):\n    \"\"\"Add an additional DATETIME column with standar datetime format.\n\n    This currently manipulates the incoming DataFrame!\n    \"\"\"\n\n    def convert_data(timestamp):\n        return datetime.fromtimestamp(float(timestamp) / 1e3, UTC_TZ)\n\n    try:\n        log.debug(\"Adding DATETIME column to the data\")\n        converted = dataframe[timestamp_key].apply(convert_data)\n        dataframe['DATETIME'] = converted\n    except KeyError:\n        log.warning(\"Could not add DATETIME column\")", "title": ""}
{"_id": "d4503", "text": "def clear_es():\n        \"\"\"Clear all indexes in the es core\"\"\"\n        # TODO: should receive a catalog slug.\n        ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])\n        LOGGER.debug('Elasticsearch: Index cleared')", "title": ""}
{"_id": "d4504", "text": "def copy_user_agent_from_driver(self):\n        \"\"\" 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.\n        \"\"\"\n        selenium_user_agent = self.driver.execute_script(\"return navigator.userAgent;\")\n        self.headers.update({\"user-agent\": selenium_user_agent})", "title": ""}
{"_id": "d4505", "text": "def keys(self):\n        \"\"\"Return ids of all indexed documents.\"\"\"\n        result = []\n        if self.fresh_index is not None:\n            result += self.fresh_index.keys()\n        if self.opt_index is not None:\n            result += self.opt_index.keys()\n        return result", "title": ""}
{"_id": "d4506", "text": "def move_datetime_year(dt, direction, num_shifts):\n    \"\"\"\n    Move datetime 1 year in the chosen direction.\n    unit is a no-op, to keep the API the same as the day case\n    \"\"\"\n    delta = relativedelta(years=+num_shifts)\n    return _move_datetime(dt, direction, delta)", "title": ""}
{"_id": "d4507", "text": "def all_documents(index=INDEX_NAME):\n    \"\"\"\n    Get all documents from the given index.\n\n    Returns full Elasticsearch objects so you can get metadata too.\n    \"\"\"\n    query = {\n        'query': {\n            'match_all': {}\n        }\n    }\n    for result in raw_query(query, index=index):\n        yield result", "title": ""}
{"_id": "d4508", "text": "def flat(l):\n    \"\"\"\nReturns the flattened version of a '2D' list.  List-correlate to the a.flat()\nmethod of NumPy arrays.\n\nUsage:    flat(l)\n\"\"\"\n    newl = []\n    for i in range(len(l)):\n        for j in range(len(l[i])):\n            newl.append(l[i][j])\n    return newl", "title": ""}
{"_id": "d4509", "text": "def get_by(self, name):\n    \"\"\"get element by name\"\"\"\n    return next((item for item in self if item.name == name), None)", "title": ""}
{"_id": "d4510", "text": "def ylabelsize(self, size, index=1):\n        \"\"\"Set the size of the label.\n\n        Parameters\n        ----------\n        size : int\n\n        Returns\n        -------\n        Chart\n\n        \"\"\"\n        self.layout['yaxis' + str(index)]['titlefont']['size'] = size\n        return self", "title": ""}
{"_id": "d4511", "text": "def Softsign(a):\n    \"\"\"\n    Softsign op.\n    \"\"\"\n    return np.divide(a, np.add(np.abs(a), 1)),", "title": ""}
{"_id": "d4512", "text": "def title(msg):\n    \"\"\"Sets the title of the console window.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "title": ""}
{"_id": "d4513", "text": "def isetdiff_flags(list1, list2):\n    \"\"\"\n    move to util_iter\n    \"\"\"\n    set2 = set(list2)\n    return (item not in set2 for item in list1)", "title": ""}
{"_id": "d4514", "text": "def _extract_value(self, value):\n        \"\"\"If the value is true/false/null replace with Python equivalent.\"\"\"\n        return ModelEndpoint._value_map.get(smart_str(value).lower(), value)", "title": ""}
{"_id": "d4515", "text": "def __getattribute__(self, attr):\n        \"\"\"Retrieve attr from current active etree implementation\"\"\"\n        if (attr not in object.__getattribute__(self, '__dict__')\n                and attr not in Etree.__dict__):\n            return object.__getattribute__(self._etree, attr)\n        return object.__getattribute__(self, attr)", "title": ""}
{"_id": "d4516", "text": "def decode_unicode_string(string):\n    \"\"\"\n    Decode string encoded by `unicode_string`\n    \"\"\"\n    if string.startswith('[BASE64-DATA]') and string.endswith('[/BASE64-DATA]'):\n        return base64.b64decode(string[len('[BASE64-DATA]'):-len('[/BASE64-DATA]')])\n    return string", "title": ""}
{"_id": "d4517", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d4518", "text": "def is_list_of_list(item):\n    \"\"\"\n    check whether the item is list (tuple)\n    and consist of list (tuple) elements\n    \"\"\"\n    if (\n        type(item) in (list, tuple)\n        and len(item)\n        and isinstance(item[0], (list, tuple))\n    ):\n        return True\n    return False", "title": ""}
{"_id": "d4519", "text": "def add_element_to_doc(doc, tag, value):\n    \"\"\"Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist.\"\"\"\n    element = doc.find(\".//%s\" % tag)\n    if element is None:\n        element = etree.SubElement(doc, tag)\n    element.text = value", "title": ""}
{"_id": "d4520", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d4521", "text": "def read_from_file(file_path, encoding=\"utf-8\"):\n    \"\"\"\n    Read helper method\n\n    :type file_path: str|unicode\n    :type encoding: str|unicode\n    :rtype: str|unicode\n    \"\"\"\n    with codecs.open(file_path, \"r\", encoding) as f:\n        return f.read()", "title": ""}
{"_id": "d4522", "text": "def is_sequence(obj):\n    \"\"\"Check if `obj` is a sequence, but not a string or bytes.\"\"\"\n    return isinstance(obj, Sequence) and not (\n        isinstance(obj, str) or BinaryClass.is_valid_type(obj))", "title": ""}
{"_id": "d4523", "text": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "title": ""}
{"_id": "d4524", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d4525", "text": "def write_enum(fo, datum, schema):\n    \"\"\"An enum is encoded by a int, representing the zero-based position of\n    the symbol in the schema.\"\"\"\n    index = schema['symbols'].index(datum)\n    write_int(fo, index)", "title": ""}
{"_id": "d4526", "text": "def is_http_running_on(port):\n  \"\"\" Check if an http server runs on a given port.\n\n  Args:\n    The port to check.\n  Returns:\n    True if it is used by an http server. False otherwise.\n  \"\"\"\n  try:\n    conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n    conn.connect()\n    conn.close()\n    return True\n  except Exception:\n    return False", "title": ""}
{"_id": "d4527", "text": "def make_exception_message(exc):\n    \"\"\"\n    An exception is passed in and this function\n    returns the proper string depending on the result\n    so it is readable enough.\n    \"\"\"\n    if str(exc):\n        return '%s: %s\\n' % (exc.__class__.__name__, exc)\n    else:\n        return '%s\\n' % (exc.__class__.__name__)", "title": ""}
{"_id": "d4528", "text": "def is_float_array(l):\n    r\"\"\"Checks if l is a numpy array of floats (any dimension\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.dtype.kind == 'f':\n            return True\n    return False", "title": ""}
{"_id": "d4529", "text": "def exec_function(ast, globals_map):\n    \"\"\"Execute a python code object in the given environment.\n\n    Args:\n      globals_map: Dictionary to use as the globals context.\n    Returns:\n      locals_map: Dictionary of locals from the environment after execution.\n    \"\"\"\n    locals_map = globals_map\n    exec ast in globals_map, locals_map\n    return locals_map", "title": ""}
{"_id": "d4530", "text": "def task_property_present_predicate(service, task, prop):\n    \"\"\" True if the json_element passed is present for the task specified.\n    \"\"\"\n    try:\n        response = get_service_task(service, task)\n    except Exception as e:\n        pass\n\n    return (response is not None) and (prop in response)", "title": ""}
{"_id": "d4531", "text": "def fast_exit(code):\n    \"\"\"Exit without garbage collection, this speeds up exit by about 10ms for\n    things like bash completion.\n    \"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(code)", "title": ""}
{"_id": "d4532", "text": "def is_float_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy float array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy float array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.floating)", "title": ""}
{"_id": "d4533", "text": "def prepare_query_params(**kwargs):\n    \"\"\"\n    Prepares given parameters to be used in querystring.\n    \"\"\"\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    ]", "title": ""}
{"_id": "d4534", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d4535", "text": "def expandvars_dict(settings):\n    \"\"\"Expands all environment variables in a settings dictionary.\"\"\"\n    return dict(\n        (key, os.path.expandvars(value))\n        for key, value in settings.iteritems()\n    )", "title": ""}
{"_id": "d4536", "text": "def is_nested_object(obj):\n    \"\"\"\n    return a boolean if we have a nested object, e.g. a Series with 1 or\n    more Series elements\n\n    This may not be necessarily be performant.\n\n    \"\"\"\n\n    if isinstance(obj, ABCSeries) and is_object_dtype(obj):\n\n        if any(isinstance(v, ABCSeries) for v in obj.values):\n            return True\n\n    return False", "title": ""}
{"_id": "d4537", "text": "def get_indent(text):\n    \"\"\"Get indent of text.\n\n    https://stackoverflow.com/questions/2268532/grab-a-lines-whitespace-\n    indention-with-python\n    \"\"\"\n    indent = ''\n\n    ret = re.match(r'(\\s*)', text)\n    if ret:\n        indent = ret.group(1)\n\n    return indent", "title": ""}
{"_id": "d4538", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d4539", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d4540", "text": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "title": ""}
{"_id": "d4541", "text": "def launched():\n    \"\"\"Test whether the current python environment is the correct lore env.\n\n    :return:  :any:`True` if the environment is launched\n    :rtype: bool\n    \"\"\"\n    if not PREFIX:\n        return False\n\n    return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)", "title": ""}
{"_id": "d4542", "text": "def ffmpeg_version():\n    \"\"\"Returns the available ffmpeg version\n\n    Returns\n    ----------\n    version : str\n        version number as string\n    \"\"\"\n\n    cmd = [\n        'ffmpeg',\n        '-version'\n    ]\n\n    output = sp.check_output(cmd)\n    aac_codecs = [\n        x for x in\n        output.splitlines() if \"ffmpeg version \" in str(x)\n    ][0]\n    hay = aac_codecs.decode('ascii')\n    match = re.findall(r'ffmpeg version (\\d+\\.)?(\\d+\\.)?(\\*|\\d+)', hay)\n    if match:\n        return \"\".join(match[0])\n    else:\n        return None", "title": ""}
{"_id": "d4543", "text": "def is_json_file(filename, show_warnings = False):\n    \"\"\"Check configuration file type is JSON\n    Return a boolean indicating wheather the file is JSON format or not\n    \"\"\"\n    try:\n        config_dict = load_config(filename, file_type = \"json\")\n        is_json = True\n    except:\n        is_json = False\n    return(is_json)", "title": ""}
{"_id": "d4544", "text": "def fft_freqs(n_fft, fs):\n    \"\"\"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.\n    \"\"\"\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)", "title": ""}
{"_id": "d4545", "text": "def is_same_file (filename1, filename2):\n    \"\"\"Check if filename1 and filename2 point to the same file object.\n    There can be false negatives, ie. the result is False, but it is\n    the same file anyway. Reason is that network filesystems can create\n    different paths to the same physical file.\n    \"\"\"\n    if filename1 == filename2:\n        return True\n    if os.name == 'posix':\n        return os.path.samefile(filename1, filename2)\n    return is_same_filename(filename1, filename2)", "title": ""}
{"_id": "d4546", "text": "def fft_freqs(n_fft, fs):\n    \"\"\"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.\n    \"\"\"\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)", "title": ""}
{"_id": "d4547", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d4548", "text": "def file_read(filename):\n    \"\"\"Read a file and close it.  Returns the file source.\"\"\"\n    fobj = open(filename,'r');\n    source = fobj.read();\n    fobj.close()\n    return source", "title": ""}
{"_id": "d4549", "text": "def is_archlinux():\n    \"\"\"return True if the current distribution is running on debian like OS.\"\"\"\n    if platform.system().lower() == 'linux':\n        if platform.linux_distribution() == ('', '', ''):\n            # undefined distribution. Fixed in python 3.\n            if os.path.exists('/etc/arch-release'):\n                return True\n    return False", "title": ""}
{"_id": "d4550", "text": "def _maybe_fill(arr, fill_value=np.nan):\n    \"\"\"\n    if we have a compatible fill_value and arr dtype, then fill\n    \"\"\"\n    if _isna_compat(arr, fill_value):\n        arr.fill(fill_value)\n    return arr", "title": ""}
{"_id": "d4551", "text": "def _is_proper_sequence(seq):\n    \"\"\"Returns is seq is sequence and not string.\"\"\"\n    return (isinstance(seq, collections.abc.Sequence) and\n            not isinstance(seq, str))", "title": ""}
{"_id": "d4552", "text": "def get_column_definition(self, table, column):\n        \"\"\"Retrieve the column definition statement for a column from a table.\"\"\"\n        # Parse column definitions for match\n        for col in self.get_column_definition_all(table):\n            if col.strip('`').startswith(column):\n                return col.strip(',')", "title": ""}
{"_id": "d4553", "text": "def is_palindrome(string, strict=True):\n    \"\"\"\n    Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n    :param string: String to check.\n    :type string: str\n    :param strict: True if white spaces matter (default), false otherwise.\n    :type strict: bool\n    :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\n    False otherwise\n    \"\"\"\n    if is_full_string(string):\n        if strict:\n            return reverse(string) == string\n        return is_palindrome(SPACES_RE.sub('', string))\n    return False", "title": ""}
{"_id": "d4554", "text": "def filter_dict_by_key(d, keys):\n    \"\"\"Filter the dict *d* to remove keys not in *keys*.\"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d4555", "text": "def eqstr(a, b):\n    \"\"\"\n    Determine whether two strings are equivalent.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html\n\n    :param a: Arbitrary character string.\n    :type a: str\n    :param b: Arbitrary character string.\n    :type b: str\n    :return: True if A and B are equivalent.\n    :rtype: bool\n    \"\"\"\n    return bool(libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)))", "title": ""}
{"_id": "d4556", "text": "def remove_na_arraylike(arr):\n    \"\"\"\n    Return array-like containing only true/non-NaN values, possibly empty.\n    \"\"\"\n    if is_extension_array_dtype(arr):\n        return arr[notna(arr)]\n    else:\n        return arr[notna(lib.values_from_object(arr))]", "title": ""}
{"_id": "d4557", "text": "def test_value(self, value):\n        \"\"\"Test if value is an instance of float.\"\"\"\n        if not isinstance(value, float):\n            raise ValueError('expected float value: ' + str(type(value)))", "title": ""}
{"_id": "d4558", "text": "def tuple_search(t, i, v):\n    \"\"\"\n    Search tuple array by index and value\n    :param t: tuple array\n    :param i: index of the value in each tuple\n    :param v: value\n    :return: the first tuple in the array with the specific index / value\n    \"\"\"\n    for e in t:\n        if e[i] == v:\n            return e\n    return None", "title": ""}
{"_id": "d4559", "text": "def is_valid_variable_name(string_to_check):\n    \"\"\"\n    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\n    \"\"\"\n\n    try:\n\n        parse('{} = None'.format(string_to_check))\n        return True\n\n    except (SyntaxError, ValueError, TypeError):\n\n        return False", "title": ""}
{"_id": "d4560", "text": "def _factor_generator(n):\n    \"\"\"\n    From a given natural integer, returns the prime factors and their multiplicity\n    :param n: Natural integer\n    :return:\n    \"\"\"\n    p = prime_factors(n)\n    factors = {}\n    for p1 in p:\n        try:\n            factors[p1] += 1\n        except KeyError:\n            factors[p1] = 1\n    return factors", "title": ""}
{"_id": "d4561", "text": "def contains_geometric_info(var):\n    \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)", "title": ""}
{"_id": "d4562", "text": "def findfirst(f, coll):\n    \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n    result = list(dropwhile(f, coll))\n    return result[0] if result else None", "title": ""}
{"_id": "d4563", "text": "def contains_empty(features):\n    \"\"\"Check features data are not empty\n\n    :param features: The features data to check.\n    :type features: list of numpy arrays.\n\n    :return: True if one of the array is empty, False else.\n\n    \"\"\"\n    if not features:\n        return True\n    for feature in features:\n        if feature.shape[0] == 0:\n            return True\n    return False", "title": ""}
{"_id": "d4564", "text": "def fit_gaussian(x, y, yerr, p0):\n    \"\"\" Fit a Gaussian to the data \"\"\"\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", "title": ""}
{"_id": "d4565", "text": "def is_valid_variable_name(string_to_check):\n    \"\"\"\n    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\n    \"\"\"\n\n    try:\n\n        parse('{} = None'.format(string_to_check))\n        return True\n\n    except (SyntaxError, ValueError, TypeError):\n\n        return False", "title": ""}
{"_id": "d4566", "text": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "title": ""}
{"_id": "d4567", "text": "def is_lazy_iterable(obj):\n    \"\"\"\n    Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n    \"\"\"\n    return isinstance(obj,\n        (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))", "title": ""}
{"_id": "d4568", "text": "def initialize_api(flask_app):\n    \"\"\"Initialize an API.\"\"\"\n    if not flask_restplus:\n        return\n\n    api = flask_restplus.Api(version=\"1.0\", title=\"My Example API\")\n    api.add_resource(HelloWorld, \"/hello\")\n\n    blueprint = flask.Blueprint(\"api\", __name__, url_prefix=\"/api\")\n    api.init_app(blueprint)\n    flask_app.register_blueprint(blueprint)", "title": ""}
{"_id": "d4569", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d4570", "text": "def init_app(self, app):\n        \"\"\"Initialize Flask application.\"\"\"\n        app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True)", "title": ""}
{"_id": "d4571", "text": "def converged(matrix1, matrix2):\n    \"\"\"\n    Check for convergence by determining if \n    matrix1 and matrix2 are approximately equal.\n    \n    :param matrix1: The matrix to compare with matrix2\n    :param matrix2: The matrix to compare with matrix1\n    :returns: True if matrix1 and matrix2 approximately equal\n    \"\"\"\n    if isspmatrix(matrix1) or isspmatrix(matrix2):\n        return sparse_allclose(matrix1, matrix2)\n\n    return np.allclose(matrix1, matrix2)", "title": ""}
{"_id": "d4572", "text": "def chmod_plus_w(path):\n  \"\"\"Equivalent of unix `chmod +w path`\"\"\"\n  path_mode = os.stat(path).st_mode\n  path_mode &= int('777', 8)\n  path_mode |= stat.S_IWRITE\n  os.chmod(path, path_mode)", "title": ""}
{"_id": "d4573", "text": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "title": ""}
{"_id": "d4574", "text": "def render_template(template_name, **context):\n    \"\"\"Render a template into a response.\"\"\"\n    tmpl = jinja_env.get_template(template_name)\n    context[\"url_for\"] = url_for\n    return Response(tmpl.render(context), mimetype=\"text/html\")", "title": ""}
{"_id": "d4575", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d4576", "text": "def getFlaskResponse(responseString, httpStatus=200):\n    \"\"\"\n    Returns a Flask response object for the specified data and HTTP status.\n    \"\"\"\n    return flask.Response(responseString, status=httpStatus, mimetype=MIMETYPE)", "title": ""}
{"_id": "d4577", "text": "def __eq__(self, other):\n        \"\"\"Determine if two objects are equal.\"\"\"\n        return isinstance(other, self.__class__) \\\n            and self._freeze() == other._freeze()", "title": ""}
{"_id": "d4578", "text": "async def json_or_text(response):\n    \"\"\"Turns response into a properly formatted json or text object\"\"\"\n    text = await response.text()\n    if response.headers['Content-Type'] == 'application/json; charset=utf-8':\n        return json.loads(text)\n    return text", "title": ""}
{"_id": "d4579", "text": "def random_choice(sequence):\n    \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n    return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)", "title": ""}
{"_id": "d4580", "text": "def flatten(l):\n    \"\"\"Flatten a nested list.\"\"\"\n    return sum(map(flatten, l), []) \\\n        if isinstance(l, list) or isinstance(l, tuple) else [l]", "title": ""}
{"_id": "d4581", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d4582", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d4583", "text": "def get_duckduckgo_links(limit, params, headers):\n\t\"\"\"\n\tfunction to fetch links equal to limit\n\n\tduckduckgo pagination is not static, so there is a limit on\n\tmaximum number of links that can be scraped\n\t\"\"\"\n\tresp = s.get('https://duckduckgo.com/html', params = params, headers = headers)\n\tlinks = scrape_links(resp.content, engine = 'd')\n\treturn links[:limit]", "title": ""}
{"_id": "d4584", "text": "def fmt_sz(intval):\n    \"\"\" Format a byte sized value.\n    \"\"\"\n    try:\n        return fmt.human_size(intval)\n    except (ValueError, TypeError):\n        return \"N/A\".rjust(len(fmt.human_size(0)))", "title": ""}
{"_id": "d4585", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d4586", "text": "def skip(self, n):\n        \"\"\"Skip the specified number of elements in the list.\n\n        If the number skipped is greater than the number of elements in\n        the list, hasNext() becomes false and available() returns zero\n        as there are no more elements to retrieve.\n\n        arg:    n (cardinal): the number of elements to skip\n        *compliance: mandatory -- This method must be implemented.*\n\n        \"\"\"\n        try:\n            self._iter_object.skip(n)\n        except AttributeError:\n            for i in range(0, n):\n                self.next()", "title": ""}
{"_id": "d4587", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d4588", "text": "def replace_nones(dict_or_list):\n    \"\"\"Update a dict or list in place to replace\n    'none' string values with Python None.\"\"\"\n\n    def replace_none_in_value(value):\n        if isinstance(value, basestring) and value.lower() == \"none\":\n            return None\n        return value\n\n    items = dict_or_list.iteritems() if isinstance(dict_or_list, dict) else enumerate(dict_or_list)\n\n    for accessor, value in items:\n        if isinstance(value, (dict, list)):\n            replace_nones(value)\n        else:\n            dict_or_list[accessor] = replace_none_in_value(value)", "title": ""}
{"_id": "d4589", "text": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "title": ""}
{"_id": "d4590", "text": "def safe_format(s, **kwargs):\n  \"\"\"\n  :type s str\n  \"\"\"\n  return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))", "title": ""}
{"_id": "d4591", "text": "def get_column_keys_and_names(table):\n    \"\"\"\n    Return a generator of tuples k, c such that k is the name of the python attribute for\n    the column and c is the name of the column in the sql table.\n    \"\"\"\n    ins = inspect(table)\n    return ((k, c.name) for k, c in ins.mapper.c.items())", "title": ""}
{"_id": "d4592", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d4593", "text": "def write_color(string, name, style='normal', when='auto'):\n    \"\"\" Write the given colored string to standard out. \"\"\"\n    write(color(string, name, style, when))", "title": ""}
{"_id": "d4594", "text": "def isdir(self, path):\n        \"\"\"Return true if the path refers to an existing directory.\n\n        Parameters\n        ----------\n        path : str\n            Path of directory on the remote side to check.\n        \"\"\"\n        result = True\n        try:\n            self.sftp_client.lstat(path)\n        except FileNotFoundError:\n            result = False\n\n        return result", "title": ""}
{"_id": "d4595", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d4596", "text": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "title": ""}
{"_id": "d4597", "text": "def _merge_maps(m1, m2):\n    \"\"\"merge two Mapping objects, keeping the type of the first mapping\"\"\"\n    return type(m1)(chain(m1.items(), m2.items()))", "title": ""}
{"_id": "d4598", "text": "def write(url, content, **args):\n    \"\"\"Put an object into a ftps URL.\"\"\"\n    with FTPSResource(url, **args) as resource:\n        resource.write(content)", "title": ""}
{"_id": "d4599", "text": "def cartesian_lists(d):\n    \"\"\"\n    turns a dict of lists into a list of dicts that represents\n    the cartesian product of the initial lists\n\n    Example\n    -------\n    cartesian_lists({'a':[0, 2], 'b':[3, 4, 5]}\n    returns\n    [ {'a':0, 'b':3}, {'a':0, 'b':4}, ... {'a':2, 'b':5} ]\n\n    \"\"\"\n    return [{k: v for k, v in zip(d.keys(), args)}\n            for args in itertools.product(*d.values())]", "title": ""}
{"_id": "d4600", "text": "def see_doc(obj_with_doc):\n    \"\"\"Copy docstring from existing object to the decorated callable.\"\"\"\n    def decorator(fn):\n        fn.__doc__ = obj_with_doc.__doc__\n        return fn\n    return decorator", "title": ""}
{"_id": "d4601", "text": "def compare(a, b):\n    \"\"\"\n     Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))\n    \"\"\"\n    s=0\n    for i in range(len(a)):\n        s=s+abs(a[i]-b[i])\n    return s", "title": ""}
{"_id": "d4602", "text": "def is_scalar(value):\n    \"\"\"Test if the given value is a scalar.\n\n    This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n    Args:\n        value: the value to test for being a scalar value\n\n    Returns:\n        boolean: if the given value is a scalar or not\n    \"\"\"\n    return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))", "title": ""}
{"_id": "d4603", "text": "def iiscgi(application):\n\t\"\"\"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.\n\t\"\"\"\n\ttry:\n\t\tfrom wsgiref.handlers import IISCGIHandler\n\texcept ImportError:\n\t\tprint(\"Python 3.2 or newer is required.\")\n\t\n\tif not __debug__:\n\t\twarnings.warn(\"Interactive debugging and other persistence-based processes will not work.\")\n\t\n\tIISCGIHandler().run(application)", "title": ""}
{"_id": "d4604", "text": "def arguments_as_dict(cls, *args, **kwargs):\n        \"\"\"\n        Generate the arguments dictionary provided to :py:meth:`generate_name` and :py:meth:`calculate_total_steps`.\n\n        This makes it possible to fetch arguments by name regardless of\n        whether they were passed as positional or keyword arguments.  Unnamed\n        positional arguments are provided as a tuple under the key ``pos``.\n        \"\"\"\n        all_args = (None, ) + args\n        return inspect.getcallargs(cls.run, *all_args, **kwargs)", "title": ""}
{"_id": "d4605", "text": "def is_int(string):\n    \"\"\"\n    Checks if a string is an integer. If the string value is an integer\n    return True, otherwise return False. \n    \n    Args:\n        string: a string to test.\n\n    Returns: \n        boolean\n    \"\"\"\n    try:\n        a = float(string)\n        b = int(a)\n    except ValueError:\n        return False\n    else:\n        return a == b", "title": ""}
{"_id": "d4606", "text": "def update(self, **kwargs):\n    \"\"\"Creates or updates a property for the instance for each parameter.\"\"\"\n    for key, value in kwargs.items():\n      setattr(self, key, value)", "title": ""}
{"_id": "d4607", "text": "def cmp_contents(filename1, filename2):\n    \"\"\" Returns True if contents of the files are the same\n\n    Parameters\n    ----------\n    filename1 : str\n        filename of first file to compare\n    filename2 : str\n        filename of second file to compare\n\n    Returns\n    -------\n    tf : bool\n        True if binary contents of `filename1` is same as binary contents of\n        `filename2`, False otherwise.\n    \"\"\"\n    with open_readable(filename1, 'rb') as fobj:\n        contents1 = fobj.read()\n    with open_readable(filename2, 'rb') as fobj:\n        contents2 = fobj.read()\n    return contents1 == contents2", "title": ""}
{"_id": "d4608", "text": "def hamming(s, t):\n    \"\"\"\n    Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.\n\n    :param s: string 1\n    :type s: str\n    :param t: string 2\n    :type s: str\n    :return: Hamming distance\n    :rtype: float\n    \"\"\"\n    if len(s) != len(t):\n        raise ValueError('Hamming distance needs strings of equal length.')\n    return sum(s_ != t_ for s_, t_ in zip(s, t))", "title": ""}
{"_id": "d4609", "text": "def _check_for_int(x):\n    \"\"\"\n    This is a compatibility function that takes a C{float} and converts it to an\n    C{int} if the values are equal.\n    \"\"\"\n    try:\n        y = int(x)\n    except (OverflowError, ValueError):\n        pass\n    else:\n        # There is no way in AMF0 to distinguish between integers and floats\n        if x == x and y == x:\n            return y\n\n    return x", "title": ""}
{"_id": "d4610", "text": "def get_free_mb(folder):\n    \"\"\" Return folder/drive free space (in bytes)\n    \"\"\"\n    if platform.system() == 'Windows':\n        free_bytes = ctypes.c_ulonglong(0)\n        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))\n        return free_bytes.value/1024/1024\n    else:\n        st = os.statvfs(folder)\n        return st.f_bavail * st.f_frsize/1024/1024", "title": ""}
{"_id": "d4611", "text": "def _check_for_int(x):\n    \"\"\"\n    This is a compatibility function that takes a C{float} and converts it to an\n    C{int} if the values are equal.\n    \"\"\"\n    try:\n        y = int(x)\n    except (OverflowError, ValueError):\n        pass\n    else:\n        # There is no way in AMF0 to distinguish between integers and floats\n        if x == x and y == x:\n            return y\n\n    return x", "title": ""}
{"_id": "d4612", "text": "def static_method(cls, f):\n        \"\"\"Decorator which dynamically binds static methods to the model for later use.\"\"\"\n        setattr(cls, f.__name__, staticmethod(f))\n        return f", "title": ""}
{"_id": "d4613", "text": "def count_string_diff(a,b):\n    \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n    shortest = min(len(a), len(b))\n    return sum(a[i] != b[i] for i in range(shortest))", "title": ""}
{"_id": "d4614", "text": "def min_or_none(val1, val2):\n    \"\"\"Returns min(val1, val2) returning None only if both values are None\"\"\"\n    return min(val1, val2, key=lambda x: sys.maxint if x is None else x)", "title": ""}
{"_id": "d4615", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d4616", "text": "def get_size(objects):\n    \"\"\"Compute the total size of all elements in objects.\"\"\"\n    res = 0\n    for o in objects:\n        try:\n            res += _getsizeof(o)\n        except AttributeError:\n            print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n    return res", "title": ""}
{"_id": "d4617", "text": "def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE):\n    \"\"\"\n    Returns value of a sine wave at a given frequency and framerate\n    for a given sample i\n    \"\"\"\n    omega = 2.0 * pi * float(frequency)\n    sine = sin(omega * (float(i) / float(framerate)))\n    return float(amplitude) * sine", "title": ""}
{"_id": "d4618", "text": "def _cdf(self, xloc, dist, cache):\n        \"\"\"Cumulative distribution function.\"\"\"\n        return evaluation.evaluate_forward(dist, numpy.e**xloc, cache=cache)", "title": ""}
{"_id": "d4619", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d4620", "text": "def manhattan(h1, h2): # # 7 us @array, 31 us @list \\w 100 bins\n    r\"\"\"\n    Equal to Minowski distance with :math:`p=1`.\n    \n    See also\n    --------\n    minowski\n    \"\"\"\n    h1, h2 = __prepare_histogram(h1, h2)\n    return scipy.sum(scipy.absolute(h1 - h2))", "title": ""}
{"_id": "d4621", "text": "def data_from_techshop_ws(tws_url):\n    \"\"\"Scrapes data from techshop.ws.\"\"\"\n\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\n    return data", "title": ""}
{"_id": "d4622", "text": "def deskew(S):\n    \"\"\"Converts a skew-symmetric cross-product matrix to its corresponding\n    vector. Only works for 3x3 matrices.\n\n    Parameters\n    ----------\n    S : :obj:`numpy.ndarray` of float\n        A 3x3 skew-symmetric matrix.\n\n    Returns\n    -------\n    :obj:`numpy.ndarray` of float\n        A 3-entry vector that corresponds to the given cross product matrix.\n    \"\"\"\n    x = np.zeros(3)\n    x[0] = S[2,1]\n    x[1] = S[0,2]\n    x[2] = S[1,0]\n    return x", "title": ""}
{"_id": "d4623", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d4624", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d4625", "text": "def unzip_file_to_dir(path_to_zip, output_directory):\n    \"\"\"\n    Extract a ZIP archive to a directory\n    \"\"\"\n    z = ZipFile(path_to_zip, 'r')\n    z.extractall(output_directory)\n    z.close()", "title": ""}
{"_id": "d4626", "text": "def get_distance_matrix(x):\n    \"\"\"Get distance matrix given a matrix. Used in testing.\"\"\"\n    square = nd.sum(x ** 2.0, axis=1, keepdims=True)\n    distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))\n    return nd.sqrt(distance_square)", "title": ""}
{"_id": "d4627", "text": "def _mean_absolute_error(y, y_pred, w):\n    \"\"\"Calculate the mean absolute error.\"\"\"\n    return np.average(np.abs(y_pred - y), weights=w)", "title": ""}
{"_id": "d4628", "text": "def dft(blk, freqs, normalize=True):\n  \"\"\"\n  Complex non-optimized Discrete Fourier Transform\n\n  Finds the DFT for values in a given frequency list, in order, over the data\n  block seen as periodic.\n\n  Parameters\n  ----------\n  blk :\n    An iterable with well-defined length. Don't use this function with Stream\n    objects!\n  freqs :\n    List of frequencies to find the DFT, in rad/sample. FFT implementations\n    like numpy.fft.ftt finds the coefficients for N frequencies equally\n    spaced as ``line(N, 0, 2 * pi, finish=False)`` for N frequencies.\n  normalize :\n    If True (default), the coefficient sums are divided by ``len(blk)``,\n    and the coefficient for the DC level (frequency equals to zero) is the\n    mean of the block. If False, that coefficient would be the sum of the\n    data in the block.\n\n  Returns\n  -------\n  A list of DFT values for each frequency, in the same order that they appear\n  in the freqs input.\n\n  Note\n  ----\n  This isn't a FFT implementation, and performs :math:`O(M . N)` float\n  pointing operations, with :math:`M` and :math:`N` equals to the length of\n  the inputs. This function can find the DFT for any specific frequency, with\n  no need for zero padding or finding all frequencies in a linearly spaced\n  band grid with N frequency bins at once.\n\n  \"\"\"\n  dft_data = (sum(xn * cexp(-1j * n * f) for n, xn in enumerate(blk))\n                                         for f in freqs)\n  if normalize:\n    lblk = len(blk)\n    return [v / lblk for v in dft_data]\n  return list(dft_data)", "title": ""}
{"_id": "d4629", "text": "def softmax(xs):\n    \"\"\"Stable implementation of the softmax function.\"\"\"\n    ys = xs - np.max(xs)\n    exps = np.exp(ys)\n    return exps / exps.sum(axis=0)", "title": ""}
{"_id": "d4630", "text": "def timestamp_filename(basename, ext=None):\n    \"\"\"\n    Return a string of the form [basename-TIMESTAMP.ext]\n    where TIMESTAMP is of the form YYYYMMDD-HHMMSS-MILSEC\n    \"\"\"\n    dt = datetime.now().strftime('%Y%m%d-%H%M%S-%f')\n    if ext:\n        return '%s-%s.%s' % (basename, dt, ext)\n    return '%s-%s' % (basename, dt)", "title": ""}
{"_id": "d4631", "text": "def random_id(length):\n    \"\"\"Generates a random ID of given length\"\"\"\n\n    def char():\n        \"\"\"Generate single random char\"\"\"\n\n        return random.choice(string.ascii_letters + string.digits)\n\n    return \"\".join(char() for _ in range(length))", "title": ""}
{"_id": "d4632", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d4633", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d4634", "text": "def auth_request(self, url, headers, body):\n        \"\"\"Perform auth request for token.\"\"\"\n\n        return self.req.post(url, headers, body=body)", "title": ""}
{"_id": "d4635", "text": "def get_incomplete_path(filename):\n  \"\"\"Returns a temporary filename based on filename.\"\"\"\n  random_suffix = \"\".join(\n      random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n  return filename + \".incomplete\" + random_suffix", "title": ""}
{"_id": "d4636", "text": "def adjacency(tree):\n    \"\"\"\n    Construct the adjacency matrix of the tree\n    :param tree:\n    :return:\n    \"\"\"\n    dd = ids(tree)\n    N = len(dd)\n    A = np.zeros((N, N))\n\n    def _adj(node):\n        if np.isscalar(node):\n            return\n        elif isinstance(node, tuple) and len(node) == 2:\n            A[dd[node], dd[node[0]]] = 1\n            A[dd[node[0]], dd[node]] = 1\n            _adj(node[0])\n\n            A[dd[node], dd[node[1]]] = 1\n            A[dd[node[1]], dd[node]] = 1\n            _adj(node[1])\n\n    _adj(tree)\n    return A", "title": ""}
{"_id": "d4637", "text": "def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"Generate random id numbers.\"\"\"\n    return \"\".join(random.choice(chars) for x in range(size))", "title": ""}
{"_id": "d4638", "text": "def nest(thing):\n    \"\"\"Use tensorflows nest function if available, otherwise just wrap object in an array\"\"\"\n    tfutil = util.get_module('tensorflow.python.util')\n    if tfutil:\n        return tfutil.nest.flatten(thing)\n    else:\n        return [thing]", "title": ""}
{"_id": "d4639", "text": "def get_ref_dict(self, schema):\n        \"\"\"Method to create a dictionary containing a JSON reference to the\n        schema in the spec\n        \"\"\"\n        schema_key = make_schema_key(schema)\n        ref_schema = build_reference(\n            \"schema\", self.openapi_version.major, self.refs[schema_key]\n        )\n        if getattr(schema, \"many\", False):\n            return {\"type\": \"array\", \"items\": ref_schema}\n        return ref_schema", "title": ""}
{"_id": "d4640", "text": "def _iter_response(self, url, params=None):\n        \"\"\"Return an enumerable that iterates through a multi-page API request\"\"\"\n        if params is None:\n            params = {}\n        params['page_number'] = 1\n\n        # Last page lists itself as next page\n        while True:\n            response = self._request(url, params)\n\n            for item in response['result_data']:\n                yield item\n\n            # Last page lists itself as next page\n            if response['service_meta']['next_page_number'] == params['page_number']:\n                break\n\n            params['page_number'] += 1", "title": ""}
{"_id": "d4641", "text": "def sine_wave(frequency):\n  \"\"\"Emit a sine wave at the given frequency.\"\"\"\n  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n  ts = xs / FLAGS.sample_rate\n  return tf.sin(2 * math.pi * frequency * ts)", "title": ""}
{"_id": "d4642", "text": "def text_response(self, contents, code=200, headers={}):\n        \"\"\"shortcut to return simple plain/text messages in the response.\n\n        :param contents: a string with the response contents\n        :param code: the http status code\n        :param headers: a dict with optional headers\n        :returns: a :py:class:`flask.Response` with the ``text/plain`` **Content-Type** header.\n        \"\"\"\n        return Response(contents, status=code, headers={\n            'Content-Type': 'text/plain'\n        })", "title": ""}
{"_id": "d4643", "text": "def make_name(estimator):\n  \"\"\"Helper function that returns the name of estimator or the given string\n  if a string is given\n  \"\"\"\n  if estimator is not None:\n    if isinstance(estimator, six.string_types):\n      estimator_name = estimator\n    else:\n      estimator_name = estimator.__class__.__name__\n  else:\n    estimator_name = None\n  return estimator_name", "title": ""}
{"_id": "d4644", "text": "def OnContextMenu(self, event):\n        \"\"\"Context menu event handler\"\"\"\n\n        self.grid.PopupMenu(self.grid.contextmenu)\n\n        event.Skip()", "title": ""}
{"_id": "d4645", "text": "def list_files(directory):\n    \"\"\"Returns all files in a given directory\n    \"\"\"\n    return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]", "title": ""}
{"_id": "d4646", "text": "def OnMove(self, event):\n        \"\"\"Main window move event\"\"\"\n\n        # Store window position in config\n        position = self.main_window.GetScreenPositionTuple()\n\n        config[\"window_position\"] = repr(position)", "title": ""}
{"_id": "d4647", "text": "def list_files(directory):\n    \"\"\"Returns all files in a given directory\n    \"\"\"\n    return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]", "title": ""}
{"_id": "d4648", "text": "def filter_query_string(query):\n    \"\"\"\n        Return a version of the query string with the _e, _k and _s values\n        removed.\n    \"\"\"\n    return '&'.join([q for q in query.split('&')\n        if not (q.startswith('_k=') or q.startswith('_e=') or q.startswith('_s'))])", "title": ""}
{"_id": "d4649", "text": "def unique_items(seq):\n    \"\"\"Return the unique items from iterable *seq* (in order).\"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d4650", "text": "def adjust(cols, light):\n    \"\"\"Create palette.\"\"\"\n    raw_colors = [cols[0], *cols, \"#FFFFFF\",\n                  \"#000000\", *cols, \"#FFFFFF\"]\n\n    return colors.generic_adjust(raw_colors, light)", "title": ""}
{"_id": "d4651", "text": "def median_date(dt_list):\n    \"\"\"Calcuate median datetime from datetime list\n    \"\"\"\n    #dt_list_sort = sorted(dt_list)\n    idx = len(dt_list)/2\n    if len(dt_list) % 2 == 0:\n        md = mean_date([dt_list[idx-1], dt_list[idx]])\n    else:\n        md = dt_list[idx]\n    return md", "title": ""}
{"_id": "d4652", "text": "def RadiusGrid(gridSize):\n    \"\"\"\n    Return a square grid with values of the distance from the centre \n    of the grid to each gridpoint\n    \"\"\"\n    x,y=np.mgrid[0:gridSize,0:gridSize]\n    x = x-(gridSize-1.0)/2.0\n    y = y-(gridSize-1.0)/2.0\n    return np.abs(x+1j*y)", "title": ""}
{"_id": "d4653", "text": "def __absolute__(self, uri):\n        \"\"\" Get the absolute uri for a file\n\n        :param uri: URI of the resource to be retrieved\n        :return: Absolute Path\n        \"\"\"\n        return op.abspath(op.join(self.__path__, uri))", "title": ""}
{"_id": "d4654", "text": "def autocorr_coeff(x, t, tau1, tau2):\n    \"\"\"Calculate the autocorrelation coefficient.\"\"\"\n    return corr_coeff(x, x, t, tau1, tau2)", "title": ""}
{"_id": "d4655", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d4656", "text": "def indentsize(line):\n    \"\"\"Return the indent size, in spaces, at the start of a line of text.\"\"\"\n    expline = string.expandtabs(line)\n    return len(expline) - len(string.lstrip(expline))", "title": ""}
{"_id": "d4657", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d4658", "text": "def paren_change(inputstring, opens=opens, closes=closes):\n    \"\"\"Determine the parenthetical change of level (num closes - num opens).\"\"\"\n    count = 0\n    for c in inputstring:\n        if c in opens:  # open parens/brackets/braces\n            count -= 1\n        elif c in closes:  # close parens/brackets/braces\n            count += 1\n    return count", "title": ""}
{"_id": "d4659", "text": "def get_month_start_end_day():\n    \"\"\"\n    Get the month start date a nd end date\n    \"\"\"\n    t = date.today()\n    n = mdays[t.month]\n    return (date(t.year, t.month, 1), date(t.year, t.month, n))", "title": ""}
{"_id": "d4660", "text": "def count(data, axis=None):\n    \"\"\"Count the number of non-NA in this array along the given axis or axes\n    \"\"\"\n    return np.sum(np.logical_not(isnull(data)), axis=axis)", "title": ""}
{"_id": "d4661", "text": "def circ_permutation(items):\n    \"\"\"Calculate the circular permutation for a given list of items.\"\"\"\n    permutations = []\n    for i in range(len(items)):\n        permutations.append(items[i:] + items[:i])\n    return permutations", "title": ""}
{"_id": "d4662", "text": "def string_to_list(string, sep=\",\", filter_empty=False):\n    \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n    return [value.strip() for value in string.split(sep)\n            if (not filter_empty or value)]", "title": ""}
{"_id": "d4663", "text": "def data_directory():\n    \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")", "title": ""}
{"_id": "d4664", "text": "def go_to_new_line(self):\n        \"\"\"Go to the end of the current line and create a new line\"\"\"\n        self.stdkey_end(False, False)\n        self.insert_text(self.get_line_separator())", "title": ""}
{"_id": "d4665", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d4666", "text": "def make_unique_ngrams(s, n):\n    \"\"\"Make a set of unique n-grams from a string.\"\"\"\n    return set(s[i:i + n] for i in range(len(s) - n + 1))", "title": ""}
{"_id": "d4667", "text": "def read_string(buff, byteorder='big'):\n    \"\"\"Read a string from a file-like object.\"\"\"\n    length = read_numeric(USHORT, buff, byteorder)\n    return buff.read(length).decode('utf-8')", "title": ""}
{"_id": "d4668", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d4669", "text": "def extract_module_locals(depth=0):\n    \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n    f = sys._getframe(depth + 1)\n    global_ns = f.f_globals\n    module = sys.modules[global_ns['__name__']]\n    return (module, f.f_locals)", "title": ""}
{"_id": "d4670", "text": "def sparse_to_matrix(sparse):\n    \"\"\"\n    Take a sparse (n,3) list of integer indexes of filled cells,\n    turn it into a dense (m,o,p) matrix.\n\n    Parameters\n    -----------\n    sparse: (n,3) int, index of filled cells\n\n    Returns\n    ------------\n    dense: (m,o,p) bool, matrix of filled cells\n    \"\"\"\n\n    sparse = np.asanyarray(sparse, dtype=np.int)\n    if not util.is_shape(sparse, (-1, 3)):\n        raise ValueError('sparse must be (n,3)!')\n\n    shape = sparse.max(axis=0) + 1\n    matrix = np.zeros(np.product(shape), dtype=np.bool)\n    multiplier = np.array([np.product(shape[1:]), shape[2], 1])\n\n    index = (sparse * multiplier).sum(axis=1)\n    matrix[index] = True\n\n    dense = matrix.reshape(shape)\n    return dense", "title": ""}
{"_id": "d4671", "text": "def get_size(self):\n        \"\"\"see doc in Term class\"\"\"\n        self.curses.setupterm()\n        return self.curses.tigetnum('cols'), self.curses.tigetnum('lines')", "title": ""}
{"_id": "d4672", "text": "def ensure_dir_exists(directory):\n    \"\"\"Se asegura de que un directorio exista.\"\"\"\n    if directory and not os.path.exists(directory):\n        os.makedirs(directory)", "title": ""}
{"_id": "d4673", "text": "def get_mouse_location(self):\n        \"\"\"\n        Get the current mouse location (coordinates and screen number).\n\n        :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields\n        \"\"\"\n        x = ctypes.c_int(0)\n        y = ctypes.c_int(0)\n        screen_num = ctypes.c_int(0)\n        _libxdo.xdo_get_mouse_location(\n            self._xdo, ctypes.byref(x), ctypes.byref(y),\n            ctypes.byref(screen_num))\n        return mouse_location(x.value, y.value, screen_num.value)", "title": ""}
{"_id": "d4674", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d4675", "text": "def get_system_cpu_times():\n    \"\"\"Return system CPU times as a namedtuple.\"\"\"\n    user, nice, system, idle = _psutil_osx.get_system_cpu_times()\n    return _cputimes_ntuple(user, nice, system, idle)", "title": ""}
{"_id": "d4676", "text": "def write_property(fh, key, value):\n  \"\"\"\n    Write a single property to the file in Java properties format.\n\n    :param fh: a writable file-like object\n    :param key: the key to write\n    :param value: the value to write\n  \"\"\"\n  if key is COMMENT:\n    write_comment(fh, value)\n    return\n\n  _require_string(key, 'keys')\n  _require_string(value, 'values')\n\n  fh.write(_escape_key(key))\n  fh.write(b'=')\n  fh.write(_escape_value(value))\n  fh.write(b'\\n')", "title": ""}
{"_id": "d4677", "text": "def get_current_branch():\n    \"\"\"\n    Return the current branch\n    \"\"\"\n    cmd = [\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"]\n    output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n    return output.strip().decode(\"utf-8\")", "title": ""}
{"_id": "d4678", "text": "def from_dict(cls, d):\n        \"\"\"Create an instance from a dictionary.\"\"\"\n        return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})", "title": ""}
{"_id": "d4679", "text": "def memory_used(self):\n        \"\"\"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.\n        \"\"\"\n        if self._end_memory:\n            memory_used = self._end_memory - self._start_memory\n            return memory_used\n        else:\n            return None", "title": ""}
{"_id": "d4680", "text": "def colorbar(height, length, colormap):\n    \"\"\"Return the channels of a colorbar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.colorize(cbar)", "title": ""}
{"_id": "d4681", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d4682", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d4683", "text": "def _get_config_or_default(self, key, default, as_type=lambda x: x):\n        \"\"\"Return a main config value, or default if it does not exist.\"\"\"\n\n        if self.main_config.has_option(self.main_section, key):\n            return as_type(self.main_config.get(self.main_section, key))\n        return default", "title": ""}
{"_id": "d4684", "text": "def bytes_to_c_array(data):\n    \"\"\"\n    Make a C array using the given string.\n    \"\"\"\n    chars = [\n        \"'{}'\".format(encode_escape(i))\n        for i in decode_escape(data)\n    ]\n    return ', '.join(chars) + ', 0'", "title": ""}
{"_id": "d4685", "text": "def disable_stdout_buffering():\n    \"\"\"This turns off stdout buffering so that outputs are immediately\n    materialized and log messages show up before the program exits\"\"\"\n    stdout_orig = sys.stdout\n    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n    # NOTE(brandyn): This removes the original stdout\n    return stdout_orig", "title": ""}
{"_id": "d4686", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d4687", "text": "def get_list_dimensions(_list):\n    \"\"\"\n    Takes a nested list and returns the size of each dimension followed\n    by the element type in the list\n    \"\"\"\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []", "title": ""}
{"_id": "d4688", "text": "def load(self, name):\n        \"\"\"Loads and returns foreign library.\"\"\"\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)", "title": ""}
{"_id": "d4689", "text": "def horz_dpi(self):\n        \"\"\"\n        Integer dots per inch for the width of this image. Defaults to 72\n        when not present in the file, as is often the case.\n        \"\"\"\n        pHYs = self._chunks.pHYs\n        if pHYs is None:\n            return 72\n        return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)", "title": ""}
{"_id": "d4690", "text": "def get_distance_matrix(x):\n    \"\"\"Get distance matrix given a matrix. Used in testing.\"\"\"\n    square = nd.sum(x ** 2.0, axis=1, keepdims=True)\n    distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))\n    return nd.sqrt(distance_square)", "title": ""}
{"_id": "d4691", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d4692", "text": "def plot_target(target, ax):\n    \"\"\"Ajoute la target au plot\"\"\"\n    ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)", "title": ""}
{"_id": "d4693", "text": "def remove_ext(fname):\n    \"\"\"Removes the extension from a filename\n    \"\"\"\n    bn = os.path.basename(fname)\n    return os.path.splitext(bn)[0]", "title": ""}
{"_id": "d4694", "text": "def _crop_list_to_size(l, size):\n    \"\"\"Make a list a certain size\"\"\"\n    for x in range(size - len(l)):\n        l.append(False)\n    for x in range(len(l) - size):\n        l.pop()\n    return l", "title": ""}
{"_id": "d4695", "text": "def get_month_start(day=None):\n    \"\"\"Returns the first day of the given month.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(day=1)", "title": ""}
{"_id": "d4696", "text": "def uint8sc(im):\n    \"\"\"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\n    \"\"\"\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)", "title": ""}
{"_id": "d4697", "text": "def qualified_name_import(cls):\n    \"\"\"Full name of a class, including the module. Like qualified_class_name, but when you already have a class \"\"\"\n\n    parts = qualified_name(cls).split('.')\n\n    return \"from {} import {}\".format('.'.join(parts[:-1]), parts[-1])", "title": ""}
{"_id": "d4698", "text": "def getvariable(name):\n    \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n    import inspect\n    fr = inspect.currentframe()\n    try:\n        while fr:\n            fr = fr.f_back\n            vars = fr.f_locals\n            if name in vars:\n                return vars[name]\n    except:\n        pass\n    return None", "title": ""}
{"_id": "d4699", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d4700", "text": "def server(self):\n        \"\"\"Returns the size of remote files\n        \"\"\"\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 \" \"", "title": ""}
{"_id": "d4701", "text": "def cric__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n    model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)\n\n    # we want to explain the raw probability outputs of the trees\n    model.predict = lambda X: model.predict_proba(X)[:,1]\n    \n    return model", "title": ""}
{"_id": "d4702", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d4703", "text": "def xeval(source, optimize=True):\n    \"\"\"Compiles to native Python bytecode and runs program, returning the\n    topmost value on the stack.\n\n    Args:\n        optimize: Whether to optimize the code after parsing it.\n\n    Returns:\n        None: If the stack is empty\n        obj: If the stack contains a single value\n        [obj, obj, ...]: If the stack contains many values\n    \"\"\"\n    native = xcompile(source, optimize=optimize)\n    return native()", "title": ""}
{"_id": "d4704", "text": "def load_object_by_name(object_name):\n    \"\"\"Load an object from a module by name\"\"\"\n    mod_name, attr = object_name.rsplit('.', 1)\n    mod = import_module(mod_name)\n    return getattr(mod, attr)", "title": ""}
{"_id": "d4705", "text": "def __eq__(self, other):\n        \"\"\"Determine if two objects are equal.\"\"\"\n        return isinstance(other, self.__class__) \\\n            and self._freeze() == other._freeze()", "title": ""}
{"_id": "d4706", "text": "def __getitem__(self, index):\n    \"\"\"Get the item at the given index.\n\n    Index is a tuple of (row, col)\n    \"\"\"\n    row, col = index\n    return self.rows[row][col]", "title": ""}
{"_id": "d4707", "text": "def _release(self):\n        \"\"\"Destroy self since closures cannot be called again.\"\"\"\n        del self.funcs\n        del self.variables\n        del self.variable_values\n        del self.satisfied", "title": ""}
{"_id": "d4708", "text": "def itervalues(d, **kw):\n    \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n    if not PY2:\n        return iter(d.values(**kw))\n    return d.itervalues(**kw)", "title": ""}
{"_id": "d4709", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d4710", "text": "def del_label(self, name):\n        \"\"\"Delete a label by name.\"\"\"\n        labels_tag = self.root[0]\n        labels_tag.remove(self._find_label(name))", "title": ""}
{"_id": "d4711", "text": "def get_properties(cls):\n        \"\"\"Get all properties of the MessageFlags class.\"\"\"\n        property_names = [p for p in dir(cls)\n                          if isinstance(getattr(cls, p), property)]\n        return property_names", "title": ""}
{"_id": "d4712", "text": "def cleanup(self):\n        \"\"\"Clean up any temporary files.\"\"\"\n        for file in glob.glob(self.basename + '*'):\n            os.unlink(file)", "title": ""}
{"_id": "d4713", "text": "def get_coordinates_by_full_name(self, name):\n        \"\"\"Retrieves a person's coordinates by full name\"\"\"\n        person = self.get_person_by_full_name(name)\n        if not person:\n            return '', ''\n        return person.latitude, person.longitude", "title": ""}
{"_id": "d4714", "text": "def remove(self, key):\n        \"\"\"remove the value found at key from the queue\"\"\"\n        item = self.item_finder.pop(key)\n        item[-1] = None\n        self.removed_count += 1", "title": ""}
{"_id": "d4715", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d4716", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d4717", "text": "def get_model(name):\n    \"\"\"\n    Convert a model's verbose name to the model class. This allows us to\n    use the models verbose name in steps.\n    \"\"\"\n\n    model = MODELS.get(name.lower(), None)\n\n    assert model, \"Could not locate model by name '%s'\" % name\n\n    return model", "title": ""}
{"_id": "d4718", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d4719", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d4720", "text": "def clean_out_dir(directory):\n    \"\"\"\n    Delete all the files and subdirectories in a directory.\n    \"\"\"\n    if not isinstance(directory, path):\n        directory = path(directory)\n    for file_path in directory.files():\n        file_path.remove()\n    for dir_path in directory.dirs():\n        dir_path.rmtree()", "title": ""}
{"_id": "d4721", "text": "def tail(self, n=10):\n        \"\"\"\n        Get an SArray that contains the last n elements in the SArray.\n\n        Parameters\n        ----------\n        n : int\n            The number of elements to fetch\n\n        Returns\n        -------\n        out : SArray\n            A new SArray which contains the last n rows of the current SArray.\n        \"\"\"\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.tail(n))", "title": ""}
{"_id": "d4722", "text": "def inside_softimage():\n    \"\"\"Returns a boolean indicating if the code is executed 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", "title": ""}
{"_id": "d4723", "text": "def typename(obj):\n    \"\"\"Returns the type of obj as a string. More descriptive and specific than\n    type(obj), and safe for any object, unlike __class__.\"\"\"\n    if hasattr(obj, '__class__'):\n        return getattr(obj, '__class__').__name__\n    else:\n        return type(obj).__name__", "title": ""}
{"_id": "d4724", "text": "def datatype(dbtype, description, cursor):\n    \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n    dt = cursor.db.introspection.get_field_type(dbtype, description)\n    if type(dt) is tuple:\n        return dt[0]\n    else:\n        return dt", "title": ""}
{"_id": "d4725", "text": "def get_month_start_date(self):\n        \"\"\"Returns the first day of the current month\"\"\"\n        now = timezone.now()\n        return timezone.datetime(day=1, month=now.month, year=now.year, tzinfo=now.tzinfo)", "title": ""}
{"_id": "d4726", "text": "def _to_corrected_pandas_type(dt):\n    \"\"\"\n    When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n    This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n    \"\"\"\n    import numpy as np\n    if type(dt) == ByteType:\n        return np.int8\n    elif type(dt) == ShortType:\n        return np.int16\n    elif type(dt) == IntegerType:\n        return np.int32\n    elif type(dt) == FloatType:\n        return np.float32\n    else:\n        return None", "title": ""}
{"_id": "d4727", "text": "def get_parent_dir(name):\n    \"\"\"Get the parent directory of a filename.\"\"\"\n    parent_dir = os.path.dirname(os.path.dirname(name))\n    if parent_dir:\n        return parent_dir\n    return os.path.abspath('.')", "title": ""}
{"_id": "d4728", "text": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "title": ""}
{"_id": "d4729", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d4730", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d4731", "text": "def get_propety_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    warn(\"This method has been deprecated in favor of get_property_by_name\")\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d4732", "text": "def dict_to_html_attrs(dict_):\n    \"\"\"\n    Banana banana\n    \"\"\"\n    res = ' '.join('%s=\"%s\"' % (k, v) for k, v in dict_.items())\n    return res", "title": ""}
{"_id": "d4733", "text": "def get(self, key):  \n        \"\"\" get a set of keys from redis \"\"\"\n        res = self.connection.get(key)\n        print(res)\n        return res", "title": ""}
{"_id": "d4734", "text": "def update(self, params):\n        \"\"\"Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device.\n        \"\"\"\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "title": ""}
{"_id": "d4735", "text": "def _nbytes(buf):\n    \"\"\"Return byte-size of a memoryview or buffer.\"\"\"\n    if isinstance(buf, memoryview):\n        if PY3:\n            # py3 introduces nbytes attribute\n            return buf.nbytes\n        else:\n            # compute nbytes on py2\n            size = buf.itemsize\n            for dim in buf.shape:\n                size *= dim\n            return size\n    else:\n        # not a memoryview, raw bytes/ py2 buffer\n        return len(buf)", "title": ""}
{"_id": "d4736", "text": "def compare_dict(da, db):\n    \"\"\"\n    Compare differencs from two dicts\n    \"\"\"\n    sa = set(da.items())\n    sb = set(db.items())\n    \n    diff = sa & sb\n    return dict(sa - diff), dict(sb - diff)", "title": ""}
{"_id": "d4737", "text": "def dir_modtime(dpath):\n    \"\"\"\n    Returns the latest modification time of all files/subdirectories in a\n    directory\n    \"\"\"\n    return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))", "title": ""}
{"_id": "d4738", "text": "def _increase_file_handle_limit():\n    \"\"\"Raise the open file handles permitted by the Dusty daemon process\n    and its child processes. The number we choose here needs to be within\n    the OS X default kernel hard limit, which is 10240.\"\"\"\n    logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT))\n    resource.setrlimit(resource.RLIMIT_NOFILE,\n                       (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))", "title": ""}
{"_id": "d4739", "text": "def count_rows(self, table_name):\n        \"\"\"Return the number of entries in a table by counting them.\"\"\"\n        self.table_must_exist(table_name)\n        query = \"SELECT COUNT (*) FROM `%s`\" % table_name.lower()\n        self.own_cursor.execute(query)\n        return int(self.own_cursor.fetchone()[0])", "title": ""}
{"_id": "d4740", "text": "def get_user_by_id(self, id):\n        \"\"\"Retrieve a User object by ID.\"\"\"\n        return self.db_adapter.get_object(self.UserClass, id=id)", "title": ""}
{"_id": "d4741", "text": "def datetime_delta_to_ms(delta):\n    \"\"\"\n    Given a datetime.timedelta object, return the delta in milliseconds\n    \"\"\"\n    delta_ms = delta.days * 24 * 60 * 60 * 1000\n    delta_ms += delta.seconds * 1000\n    delta_ms += delta.microseconds / 1000\n    delta_ms = int(delta_ms)\n    return delta_ms", "title": ""}
{"_id": "d4742", "text": "def url_to_image(url):\n    \"\"\"\n    Fetch an image from url and convert it into a Pillow Image object\n    \"\"\"\n    r = requests.get(url)\n    image = StringIO(r.content)\n    return image", "title": ""}
{"_id": "d4743", "text": "def dt2ts(dt):\n    \"\"\"Converts to float representing number of seconds since 1970-01-01 GMT.\"\"\"\n    # Note: no assertion to really keep this fast\n    assert isinstance(dt, (datetime.datetime, datetime.date))\n    ret = time.mktime(dt.timetuple())\n    if isinstance(dt, datetime.datetime):\n        ret += 1e-6 * dt.microsecond\n    return ret", "title": ""}
{"_id": "d4744", "text": "def Print(self):\n        \"\"\"Prints the values and freqs/probs in ascending order.\"\"\"\n        for val, prob in sorted(self.d.iteritems()):\n            print(val, prob)", "title": ""}
{"_id": "d4745", "text": "def ver_to_tuple(value):\n    \"\"\"\n    Convert version like string to a tuple of integers.\n    \"\"\"\n    return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "title": ""}
{"_id": "d4746", "text": "def get_plain_image_as_widget(self):\n        \"\"\"Used for generating thumbnails.  Does not include overlaid\n        graphics.\n        \"\"\"\n        arr = self.getwin_array(order=self.rgb_order)\n        image = self._get_qimage(arr, self.qimg_fmt)\n        return image", "title": ""}
{"_id": "d4747", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d4748", "text": "def vector_distance(a, b):\n    \"\"\"The Euclidean distance between two vectors.\"\"\"\n    a = np.array(a)\n    b = np.array(b)\n    return np.linalg.norm(a - b)", "title": ""}
{"_id": "d4749", "text": "def get_user_by_id(self, id):\n        \"\"\"Retrieve a User object by ID.\"\"\"\n        return self.db_adapter.get_object(self.UserClass, id=id)", "title": ""}
{"_id": "d4750", "text": "def parse_env_var(s):\n    \"\"\"Parse an environment variable string\n\n    Returns a key-value tuple\n\n    Apply the same logic as `docker run -e`:\n    \"If the operator names an environment variable without specifying a value,\n    then the current value of the named variable is propagated into the\n    container's environment\n    \"\"\"\n    parts = s.split('=', 1)\n    if len(parts) == 2:\n        k, v = parts\n        return (k, v)\n\n    k = parts[0]\n    return (k, os.getenv(k, ''))", "title": ""}
{"_id": "d4751", "text": "def get_user_id_from_email(self, email):\n        \"\"\" Uses the get-all-user-accounts Portals API to retrieve the\n        user-id by supplying an email. \"\"\"\n        accts = self.get_all_user_accounts()\n\n        for acct in accts:\n            if acct['email'] == email:\n                return acct['id']\n        return None", "title": ""}
{"_id": "d4752", "text": "def check_create_folder(filename):\n    \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n    os.makedirs(os.path.dirname(filename), exist_ok=True)", "title": ""}
{"_id": "d4753", "text": "def get_nt_system_uid():\n    \"\"\"Get the MachineGuid from\n    HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Cryptography\\MachineGuid\n    \"\"\"\n    try:\n        import _winreg as winreg\n    except ImportError:\n        import winreg\n    lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\n    try:\n        key = winreg.OpenKey(lm, r\"Software\\Microsoft\\Cryptography\")\n        try:\n            return winreg.QueryValueEx(key, \"MachineGuid\")[0]\n        finally:\n            key.Close()\n    finally:\n        lm.Close()", "title": ""}
{"_id": "d4754", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d4755", "text": "def get_inputs_from_cm(index, cm):\n    \"\"\"Return indices of inputs to the node with the given index.\"\"\"\n    return tuple(i for i in range(cm.shape[0]) if cm[i][index])", "title": ""}
{"_id": "d4756", "text": "def raw_print(*args, **kw):\n    \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()", "title": ""}
{"_id": "d4757", "text": "def process_bool_arg(arg):\n    \"\"\" Determine True/False from argument \"\"\"\n    if isinstance(arg, bool):\n        return arg\n    elif isinstance(arg, basestring):\n        if arg.lower() in [\"true\", \"1\"]:\n            return True\n        elif arg.lower() in [\"false\", \"0\"]:\n            return False", "title": ""}
{"_id": "d4758", "text": "def graph_from_dot_file(path):\n    \"\"\"Load graph as defined by a DOT file.\n    \n    The file is assumed to be in DOT format. It will\n    be loaded, parsed and a Dot class will be returned, \n    representing the graph.\n    \"\"\"\n    \n    fd = file(path, 'rb')\n    data = fd.read()\n    fd.close()\n    \n    return graph_from_dot_data(data)", "title": ""}
{"_id": "d4759", "text": "def getAttributeData(self, name, channel=None):\n        \"\"\" Returns a attribut \"\"\"\n        return self._getNodeData(name, self._ATTRIBUTENODE, channel)", "title": ""}
{"_id": "d4760", "text": "def dot(self, w):\n        \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n        return sum([x * y for x, y in zip(self, w)])", "title": ""}
{"_id": "d4761", "text": "def __getLogger(cls):\n    \"\"\" Get the logger for this object.\n\n    :returns: (Logger) A Logger object.\n    \"\"\"\n    if cls.__logger is None:\n      cls.__logger = opf_utils.initLogger(cls)\n    return cls.__logger", "title": ""}
{"_id": "d4762", "text": "def depgraph_to_dotsrc(dep_graph, show_cycles, nodot, reverse):\n    \"\"\"Convert the dependency graph (DepGraph class) to dot source code.\n    \"\"\"\n    if show_cycles:\n        dotsrc = cycles2dot(dep_graph, reverse=reverse)\n    elif not nodot:\n        dotsrc = dep2dot(dep_graph, reverse=reverse)\n    else:\n        dotsrc = None\n    return dotsrc", "title": ""}
{"_id": "d4763", "text": "def commit(self, message=None, amend=False, stage=True):\n        \"\"\"Commit any changes, optionally staging all changes beforehand.\"\"\"\n        return git_commit(self.repo_dir, message=message,\n                          amend=amend, stage=stage)", "title": ""}
{"_id": "d4764", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d4765", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d4766", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d4767", "text": "def get_buffer(self, data_np, header, format, output=None):\n        \"\"\"Get image as a buffer in (format).\n        Format should be 'jpeg', 'png', etc.\n        \"\"\"\n        if not have_pil:\n            raise Exception(\"Install PIL to use this method\")\n        image = PILimage.fromarray(data_np)\n        buf = output\n        if buf is None:\n            buf = BytesIO()\n        image.save(buf, format)\n        return buf", "title": ""}
{"_id": "d4768", "text": "def del_Unnamed(df):\n    \"\"\"\n    Deletes all the unnamed columns\n\n    :param df: pandas dataframe\n    \"\"\"\n    cols_del=[c for c in df.columns if 'Unnamed' in c]\n    return df.drop(cols_del,axis=1)", "title": ""}
{"_id": "d4769", "text": "def int_to_date(date):\n    \"\"\"\n    Convert an int of form yyyymmdd to a python date object.\n    \"\"\"\n\n    year = date // 10**4\n    month = date % 10**4 // 10**2\n    day = date % 10**2\n\n    return datetime.date(year, month, day)", "title": ""}
{"_id": "d4770", "text": "def poke_array(self, store, name, elemtype, elements, container, visited, _stack):\n        \"\"\"abstract method\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d4771", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d4772", "text": "def wrap(text, width=70, **kwargs):\n    \"\"\"Wrap a single paragraph of text, returning a list of wrapped lines.\n\n    Reformat the single paragraph in 'text' so it fits in lines of no\n    more than 'width' columns, and return a list of wrapped lines.  By\n    default, tabs in 'text' are expanded with string.expandtabs(), and\n    all other whitespace characters (including newline) are converted to\n    space.  See TextWrapper class for available keyword args to customize\n    wrapping behaviour.\n    \"\"\"\n    w = TextWrapper(width=width, **kwargs)\n    return w.wrap(text)", "title": ""}
{"_id": "d4773", "text": "def remove_na_arraylike(arr):\n    \"\"\"\n    Return array-like containing only true/non-NaN values, possibly empty.\n    \"\"\"\n    if is_extension_array_dtype(arr):\n        return arr[notna(arr)]\n    else:\n        return arr[notna(lib.values_from_object(arr))]", "title": ""}
{"_id": "d4774", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d4775", "text": "def norm_slash(name):\n    \"\"\"Normalize path slashes.\"\"\"\n\n    if isinstance(name, str):\n        return name.replace('/', \"\\\\\") if not is_case_sensitive() else name\n    else:\n        return name.replace(b'/', b\"\\\\\") if not is_case_sensitive() else name", "title": ""}
{"_id": "d4776", "text": "def scan(client, query=None, scroll='5m', raise_on_error=True,\n         preserve_order=False, size=1000, **kwargs):\n    \"\"\"\n    Simple abstraction on top of the\n    :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that\n    yields all hits as returned by underlining scroll requests.\n    By default scan does not return results in any pre-determined order. To\n    have a standard order in the returned documents (either by score or\n    explicit sort definition) when scrolling, use ``preserve_order=True``. This\n    may be an expensive operation and will negate the performance benefits of\n    using ``scan``.\n    :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n    :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api\n    :arg scroll: Specify how long a consistent view of the index should be\n        maintained for scrolled search\n    :arg raise_on_error: raises an exception (``ScanError``) if an error is\n        encountered (some shards fail to execute). By default we raise.\n    :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will\n        cause the scroll to paginate with preserving the order. Note that this\n        can be an extremely expensive operation and can easily lead to\n        unpredictable results, use with caution.\n    :arg size: size (per shard) of the batch send at each iteration.\n    Any additional keyword arguments will be passed to the initial\n    :meth:`~elasticsearch.Elasticsearch.search` call::\n        scan(es,\n            query={\"query\": {\"match\": {\"title\": \"python\"}}},\n            index=\"orders-*\",\n            doc_type=\"books\"\n        )\n    \"\"\"\n    if not preserve_order:\n        kwargs['search_type'] = 'scan'\n    # initial search\n    resp = client.search(body=query, scroll=scroll, size=size, **kwargs)\n\n    scroll_id = resp.get('_scroll_id')\n    if scroll_id is None:\n        return\n\n    first_run = True\n    while True:\n        # if we didn't set search_type to scan initial search contains data\n        if preserve_order and first_run:\n            first_run = False\n        else:\n            resp = client.scroll(scroll_id, scroll=scroll)\n\n        for hit in resp['hits']['hits']:\n            yield hit\n\n        # check if we have any errrors\n        if resp[\"_shards\"][\"failed\"]:\n            logger.warning(\n                'Scroll request has failed on %d shards out of %d.',\n                resp['_shards']['failed'], resp['_shards']['total']\n            )\n            if raise_on_error:\n                raise ScanError(\n                    'Scroll request has failed on %d shards out of %d.' %\n                    (resp['_shards']['failed'], resp['_shards']['total'])\n                )\n\n        scroll_id = resp.get('_scroll_id')\n        # end of scroll\n        if scroll_id is None or not resp['hits']['hits']:\n            break", "title": ""}
{"_id": "d4777", "text": "def check_git():\n    \"\"\"Check if git command is available.\"\"\"\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.\")", "title": ""}
{"_id": "d4778", "text": "def remove_duplicates(lst):\n    \"\"\"\n    Emulate what a Python ``set()`` does, but keeping the element's order.\n    \"\"\"\n    dset = set()\n    return [l for l in lst if l not in dset and not dset.add(l)]", "title": ""}
{"_id": "d4779", "text": "def double_sha256(data):\n    \"\"\"A standard compound hash.\"\"\"\n    return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())", "title": ""}
{"_id": "d4780", "text": "def _encode_bool(name, value, dummy0, dummy1):\n    \"\"\"Encode a python boolean (True/False).\"\"\"\n    return b\"\\x08\" + name + (value and b\"\\x01\" or b\"\\x00\")", "title": ""}
{"_id": "d4781", "text": "def _read_group_h5(filename, groupname):\n    \"\"\"Return group content.\n\n    Args:\n        filename (:class:`pathlib.Path`): path of hdf5 file.\n        groupname (str): name of group to read.\n    Returns:\n        :class:`numpy.array`: content of group.\n    \"\"\"\n    with h5py.File(filename, 'r') as h5f:\n        data = h5f[groupname][()]\n    return data", "title": ""}
{"_id": "d4782", "text": "def Value(self, name):\n    \"\"\"Returns the value coresponding to the given enum name.\"\"\"\n    if name in self._enum_type.values_by_name:\n      return self._enum_type.values_by_name[name].number\n    raise ValueError('Enum %s has no value defined for name %s' % (\n        self._enum_type.name, name))", "title": ""}
{"_id": "d4783", "text": "def async_comp_check(self, original, loc, tokens):\n        \"\"\"Check for Python 3.6 async comprehension.\"\"\"\n        return self.check_py(\"36\", \"async comprehension\", original, loc, tokens)", "title": ""}
{"_id": "d4784", "text": "def _size_36():\n    \"\"\" returns the rows, columns of terminal \"\"\"\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", "title": ""}
{"_id": "d4785", "text": "def __str__(self):\n        \"\"\"Executes self.function to convert LazyString instance to a real\n        str.\"\"\"\n        if not hasattr(self, '_str'):\n            self._str=self.function(*self.args, **self.kwargs)\n        return self._str", "title": ""}
{"_id": "d4786", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d4787", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d4788", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d4789", "text": "def cover(session):\n    \"\"\"Run the final coverage report.\n    This outputs the coverage report aggregating coverage from the unit\n    test runs (not system test runs), and then erases coverage data.\n    \"\"\"\n    session.interpreter = 'python3.6'\n    session.install('coverage', 'pytest-cov')\n    session.run('coverage', 'report', '--show-missing', '--fail-under=100')\n    session.run('coverage', 'erase')", "title": ""}
{"_id": "d4790", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d4791", "text": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "title": ""}
{"_id": "d4792", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d4793", "text": "def _from_list_dict(cls, list_dic):\n        \"\"\"Takes a list of dict like objects and uses `champ_id` field as Id\"\"\"\n        return cls({_convert_id(dic[cls.CHAMP_ID]): dict(dic) for dic in list_dic})", "title": ""}
{"_id": "d4794", "text": "def export_context(cls, context):\n\t\t\"\"\" Export the specified context to be capable context transferring\n\n\t\t:param context: context to export\n\t\t:return: tuple\n\t\t\"\"\"\n\t\tif context is None:\n\t\t\treturn\n\t\tresult = [(x.context_name(), x.context_value()) for x in context]\n\t\tresult.reverse()\n\t\treturn tuple(result)", "title": ""}
{"_id": "d4795", "text": "def get_filesize(self, pdf):\n        \"\"\"Compute the filesize of the PDF\n        \"\"\"\n        try:\n            filesize = float(pdf.get_size())\n            return filesize / 1024\n        except (POSKeyError, TypeError):\n            return 0", "title": ""}
{"_id": "d4796", "text": "def _get_os_environ_dict(keys):\n  \"\"\"Return a dictionary of key/values from os.environ.\"\"\"\n  return {k: os.environ.get(k, _UNDEFINED) for k in keys}", "title": ""}
{"_id": "d4797", "text": "def parse(filename):\n    \"\"\"Parse ASDL from the given file and return a Module node describing it.\"\"\"\n    with open(filename) as f:\n        parser = ASDLParser()\n        return parser.parse(f.read())", "title": ""}
{"_id": "d4798", "text": "def set_timeout(scope, timeout):\n    \"\"\"\n    Defines the time after which Exscript fails if it does not receive a\n    prompt from the remote host.\n\n    :type  timeout: int\n    :param timeout: The timeout in seconds.\n    \"\"\"\n    conn = scope.get('__connection__')\n    conn.set_timeout(int(timeout[0]))\n    return True", "title": ""}
{"_id": "d4799", "text": "def send_file(self, local_path, remote_path, user='root', unix_mode=None):\n        \"\"\"Upload a local file on the remote host.\n        \"\"\"\n        self.enable_user(user)\n        return self.ssh_pool.send_file(user, local_path, remote_path, unix_mode=unix_mode)", "title": ""}
{"_id": "d4800", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d4801", "text": "def _fill_array_from_list(the_list, the_array):\n        \"\"\"Fill an `array` from a `list`\"\"\"\n        for i, val in enumerate(the_list):\n            the_array[i] = val\n        return the_array", "title": ""}
{"_id": "d4802", "text": "def assign_to(self, obj):\n    \"\"\"Assign `x` and `y` to an object that has properties `x` and `y`.\"\"\"\n    obj.x = self.x\n    obj.y = self.y", "title": ""}
{"_id": "d4803", "text": "def BROADCAST_FILTER_NOT(func):\n        \"\"\"\n        Composes the passed filters into an and-joined filter.\n        \"\"\"\n        return lambda u, command, *args, **kwargs: not func(u, command, *args, **kwargs)", "title": ""}
{"_id": "d4804", "text": "def clean_time(time_string):\n    \"\"\"Return a datetime from the Amazon-provided datetime string\"\"\"\n    # Get a timezone-aware datetime object from the string\n    time = dateutil.parser.parse(time_string)\n    if not settings.USE_TZ:\n        # If timezone support is not active, convert the time to UTC and\n        # remove the timezone field\n        time = time.astimezone(timezone.utc).replace(tzinfo=None)\n    return time", "title": ""}
{"_id": "d4805", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d4806", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d4807", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d4808", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d4809", "text": "def dropna(self, subset=None):\n        \"\"\"Remove missing values according to Baloo's convention.\n\n        Parameters\n        ----------\n        subset : list of str, optional\n            Which columns to check for missing values in.\n\n        Returns\n        -------\n        DataFrame\n            DataFrame with no null values in columns.\n\n        \"\"\"\n        subset = check_and_obtain_subset_columns(subset, self)\n        not_nas = [v.notna() for v in self[subset]._iter()]\n        and_filter = reduce(lambda x, y: x & y, not_nas)\n\n        return self[and_filter]", "title": ""}
{"_id": "d4810", "text": "def underline(self, msg):\n        \"\"\"Underline the input\"\"\"\n        return click.style(msg, underline=True) if self.colorize else msg", "title": ""}
{"_id": "d4811", "text": "def registered_filters_list(self):\n        \"\"\"\n        Return the list of registered filters (as a list of strings).\n\n        The list **only** includes registered filters (**not** the predefined :program:`Jinja2` filters).\n\n        \"\"\"\n        return [filter_name for filter_name in self.__jinja2_environment.filters.keys() if filter_name not in self.__jinja2_predefined_filters ]", "title": ""}
{"_id": "d4812", "text": "def indent(self):\n        \"\"\"\n        Begins an indented block. Must be used in a 'with' code block.\n        All calls to the logger inside of the block will be indented.\n        \"\"\"\n        blk = IndentBlock(self, self._indent)\n        self._indent += 1\n        return blk", "title": ""}
{"_id": "d4813", "text": "def get_average_color(colors):\n    \"\"\"Calculate the average color from the list of colors, where each color\n    is a 3-tuple of (r, g, b) values.\n    \"\"\"\n    c = reduce(color_reducer, colors)\n    total = len(colors)\n    return tuple(v / total for v in c)", "title": ""}
{"_id": "d4814", "text": "def is_valid_file(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.exists(arg):\n        parser.error(\"The file %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d4815", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d4816", "text": "def user_exists(username):\n    \"\"\"Check if a user exists\"\"\"\n    try:\n        pwd.getpwnam(username)\n        user_exists = True\n    except KeyError:\n        user_exists = False\n    return user_exists", "title": ""}
{"_id": "d4817", "text": "def bisect_index(a, x):\n    \"\"\" Find the leftmost index of an element in a list using binary search.\n\n    Parameters\n    ----------\n    a: list\n        A sorted list.\n    x: arbitrary\n        The element.\n\n    Returns\n    -------\n    int\n        The index.\n\n    \"\"\"\n    i = bisect.bisect_left(a, x)\n    if i != len(a) and a[i] == x:\n        return i\n    raise ValueError", "title": ""}
{"_id": "d4818", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d4819", "text": "def findMax(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMax(arr, out)\n    return out", "title": ""}
{"_id": "d4820", "text": "def is_file(path):\n    \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n    try:\n        return path.expanduser().absolute().is_file()\n    except AttributeError:\n        return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))", "title": ""}
{"_id": "d4821", "text": "def get_member(thing_obj, member_string):\n    \"\"\"Get a member from an object by (string) name\"\"\"\n    mems = {x[0]: x[1] for x in inspect.getmembers(thing_obj)}\n    if member_string in mems:\n        return mems[member_string]", "title": ""}
{"_id": "d4822", "text": "def _internet_on(address):\n    \"\"\"\n    Check to see if the internet is on by pinging a set address.\n    :param address: the IP or address to hit\n    :return: a boolean - true if can be reached, false if not.\n    \"\"\"\n    try:\n        urllib2.urlopen(address, timeout=1)\n        return True\n    except urllib2.URLError as err:\n        return False", "title": ""}
{"_id": "d4823", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d4824", "text": "def clear(self):\n        \"\"\"Remove all items.\"\"\"\n        self._fwdm.clear()\n        self._invm.clear()\n        self._sntl.nxt = self._sntl.prv = self._sntl", "title": ""}
{"_id": "d4825", "text": "def count_string_diff(a,b):\n    \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n    shortest = min(len(a), len(b))\n    return sum(a[i] != b[i] for i in range(shortest))", "title": ""}
{"_id": "d4826", "text": "def isetdiff_flags(list1, list2):\n    \"\"\"\n    move to util_iter\n    \"\"\"\n    set2 = set(list2)\n    return (item not in set2 for item in list1)", "title": ""}
{"_id": "d4827", "text": "def get_months_apart(d1, d2):\n    \"\"\"\n    Get amount of months between dates\n    http://stackoverflow.com/a/4040338\n    \"\"\"\n\n    return (d1.year - d2.year)*12 + d1.month - d2.month", "title": ""}
{"_id": "d4828", "text": "def _interval_to_bound_points(array):\n    \"\"\"\n    Helper function which returns an array\n    with the Intervals' boundaries.\n    \"\"\"\n\n    array_boundaries = np.array([x.left for x in array])\n    array_boundaries = np.concatenate(\n        (array_boundaries, np.array([array[-1].right])))\n\n    return array_boundaries", "title": ""}
{"_id": "d4829", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d4830", "text": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "title": ""}
{"_id": "d4831", "text": "def getdefaultencoding():\n    \"\"\"Return IPython's guess for the default encoding for bytes as text.\n\n    Asks for stdin.encoding first, to match the calling Terminal, but that\n    is often None for subprocesses.  Fall back on locale.getpreferredencoding()\n    which should be a sensible platform default (that respects LANG environment),\n    and finally to sys.getdefaultencoding() which is the most conservative option,\n    and usually ASCII.\n    \"\"\"\n    enc = get_stream_enc(sys.stdin)\n    if not enc or enc=='ascii':\n        try:\n            # There are reports of getpreferredencoding raising errors\n            # in some cases, which may well be fixed, but let's be conservative here.\n            enc = locale.getpreferredencoding()\n        except Exception:\n            pass\n    return enc or sys.getdefaultencoding()", "title": ""}
{"_id": "d4832", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d4833", "text": "def Gaussian(x, a, x0, sigma, y0):\n    \"\"\"Gaussian peak\n\n    Inputs:\n    -------\n        ``x``: independent variable\n        ``a``: scaling factor (extremal value)\n        ``x0``: center\n        ``sigma``: half width at half maximum\n        ``y0``: additive constant\n\n    Formula:\n    --------\n        ``a*exp(-(x-x0)^2)/(2*sigma^2)+y0``\n    \"\"\"\n    return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) + y0", "title": ""}
{"_id": "d4834", "text": "def glr_path_static():\n    \"\"\"Returns path to packaged static files\"\"\"\n    return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))", "title": ""}
{"_id": "d4835", "text": "def _increment(self, *args):\n        \"\"\"Move the slider only by increment given by resolution.\"\"\"\n        value = self._var.get()\n        if self._resolution:\n            value = self._start + int(round((value - self._start) / self._resolution)) * self._resolution\n            self._var.set(value)\n        self.display_value(value)", "title": ""}
{"_id": "d4836", "text": "def clear(self):\n        \"\"\"Clear the displayed image.\"\"\"\n        self._imgobj = None\n        try:\n            # See if there is an image on the canvas\n            self.canvas.delete_object_by_tag(self._canvas_img_tag)\n            self.redraw()\n        except KeyError:\n            pass", "title": ""}
{"_id": "d4837", "text": "def render_template(env, filename, values=None):\n    \"\"\"\n    Render a jinja template\n    \"\"\"\n    if not values:\n        values = {}\n    tmpl = env.get_template(filename)\n    return tmpl.render(values)", "title": ""}
{"_id": "d4838", "text": "def click_estimate_slope():\n    \"\"\"\n    Takes two clicks and returns the slope.\n\n    Right-click aborts.\n    \"\"\"\n\n    c1 = _pylab.ginput()\n    if len(c1)==0:\n        return None\n\n    c2 = _pylab.ginput()\n    if len(c2)==0:\n        return None\n\n    return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])", "title": ""}
{"_id": "d4839", "text": "def make_2d(ary):\n    \"\"\"Convert any array into a 2d numpy array.\n\n    In case the array is already more than 2 dimensional, will ravel the\n    dimensions after the first.\n    \"\"\"\n    dim_0, *_ = np.atleast_1d(ary).shape\n    return ary.reshape(dim_0, -1, order=\"F\")", "title": ""}
{"_id": "d4840", "text": "def flatten(l):\n    \"\"\"Flatten a nested list.\"\"\"\n    return sum(map(flatten, l), []) \\\n        if isinstance(l, list) or isinstance(l, tuple) else [l]", "title": ""}
{"_id": "d4841", "text": "def is_executable(path):\n  \"\"\"Returns whether a path names an existing executable file.\"\"\"\n  return os.path.isfile(path) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d4842", "text": "def imflip(img, direction='horizontal'):\n    \"\"\"Flip an image horizontally or vertically.\n\n    Args:\n        img (ndarray): Image to be flipped.\n        direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n    Returns:\n        ndarray: The flipped image.\n    \"\"\"\n    assert direction in ['horizontal', 'vertical']\n    if direction == 'horizontal':\n        return np.flip(img, axis=1)\n    else:\n        return np.flip(img, axis=0)", "title": ""}
{"_id": "d4843", "text": "def conv_dict(self):\n        \"\"\"dictionary of conversion\"\"\"\n        return dict(integer=self.integer, real=self.real, no_type=self.no_type)", "title": ""}
{"_id": "d4844", "text": "def hflip(img):\n    \"\"\"Horizontally flip the given PIL Image.\n\n    Args:\n        img (PIL Image): Image to be flipped.\n\n    Returns:\n        PIL Image:  Horizontall flipped image.\n    \"\"\"\n    if not _is_pil_image(img):\n        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n    return img.transpose(Image.FLIP_LEFT_RIGHT)", "title": ""}
{"_id": "d4845", "text": "def run (self):\n        \"\"\"Handle keyboard interrupt and other errors.\"\"\"\n        try:\n            self.run_checked()\n        except KeyboardInterrupt:\n            thread.interrupt_main()\n        except Exception:\n            self.internal_error()", "title": ""}
{"_id": "d4846", "text": "def hflip(img):\n    \"\"\"Horizontally flip the given PIL Image.\n\n    Args:\n        img (PIL Image): Image to be flipped.\n\n    Returns:\n        PIL Image:  Horizontall flipped image.\n    \"\"\"\n    if not _is_pil_image(img):\n        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n    return img.transpose(Image.FLIP_LEFT_RIGHT)", "title": ""}
{"_id": "d4847", "text": "def callPlaybook(self, playbook, ansibleArgs, wait=True, tags=[\"all\"]):\n        \"\"\"\n        Run a playbook.\n\n        :param playbook: An Ansible playbook to run.\n        :param ansibleArgs: Arguments to pass to the playbook.\n        :param wait: Wait for the play to finish if true.\n        :param tags: Control tags for the play.\n        \"\"\"\n        playbook = os.path.join(self.playbooks, playbook)  # Path to playbook being executed\n        verbosity = \"-vvvvv\" if logger.isEnabledFor(logging.DEBUG) else \"-v\"\n        command = [\"ansible-playbook\", verbosity, \"--tags\", \",\".join(tags), \"--extra-vars\"]\n        command.append(\" \".join([\"=\".join(i) for i in ansibleArgs.items()]))  # Arguments being passed to playbook\n        command.append(playbook)\n\n        logger.debug(\"Executing Ansible call `%s`\", \" \".join(command))\n        p = subprocess.Popen(command)\n        if wait:\n            p.communicate()\n            if p.returncode != 0:\n                # FIXME: parse error codes\n                raise RuntimeError(\"Ansible reported an error when executing playbook %s\" % playbook)", "title": ""}
{"_id": "d4848", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d4849", "text": "def wait_until_exit(self):\n        \"\"\" Wait until all the threads are finished.\n\n        \"\"\"\n        [t.join() for t in self.threads]\n\n        self.threads = list()", "title": ""}
{"_id": "d4850", "text": "def file_writelines_flush_sync(path, lines):\n    \"\"\"\n    Fill file at @path with @lines then flush all buffers\n    (Python and system buffers)\n    \"\"\"\n    fp = open(path, 'w')\n    try:\n        fp.writelines(lines)\n        flush_sync_file_object(fp)\n    finally:\n        fp.close()", "title": ""}
{"_id": "d4851", "text": "def _send_file(self, filename):\n        \"\"\"\n        Sends a file via FTP.\n        \"\"\"\n        # pylint: disable=E1101\n        ftp = ftplib.FTP(host=self.host)\n        ftp.login(user=self.user, passwd=self.password)\n        ftp.set_pasv(True)\n        ftp.storbinary(\"STOR %s\" % os.path.basename(filename),\n            file(filename, 'rb'))", "title": ""}
{"_id": "d4852", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d4853", "text": "def get_csrf_token(response):\n    \"\"\"\n    Extract the CSRF token out of the \"Set-Cookie\" header of a response.\n    \"\"\"\n    cookie_headers = [\n        h.decode('ascii') for h in response.headers.getlist(\"Set-Cookie\")\n    ]\n    if not cookie_headers:\n        return None\n    csrf_headers = [\n        h for h in cookie_headers if h.startswith(\"csrftoken=\")\n    ]\n    if not csrf_headers:\n        return None\n    match = re.match(\"csrftoken=([^ ;]+);\", csrf_headers[-1])\n    return match.group(1)", "title": ""}
{"_id": "d4854", "text": "def exception_format():\n    \"\"\"\n    Convert exception info into a string suitable for display.\n    \"\"\"\n    return \"\".join(traceback.format_exception(\n        sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]\n    ))", "title": ""}
{"_id": "d4855", "text": "def ttl(self):\n        \"\"\"how long you should cache results for cacheable queries\"\"\"\n        ret = 3600\n        cn = self.get_process()\n        if \"ttl\" in cn:\n            ret = cn[\"ttl\"]\n        return ret", "title": ""}
{"_id": "d4856", "text": "def version_triple(tag):\n    \"\"\"\n    returns: a triple of integers from a version tag\n    \"\"\"\n    groups = re.match(r'v?(\\d+)\\.(\\d+)\\.(\\d+)', tag).groups()\n    return tuple(int(n) for n in groups)", "title": ""}
{"_id": "d4857", "text": "def move_back(self, dt):\n        \"\"\" If called after an update, the sprite can move back\n        \"\"\"\n        self._position = self._old_position\n        self.rect.topleft = self._position\n        self.feet.midbottom = self.rect.midbottom", "title": ""}
{"_id": "d4858", "text": "def count(lines):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  words = [w for l in lines for w in l.strip().split()]\n  return Counter(words)", "title": ""}
{"_id": "d4859", "text": "def is_empty(self):\n        \"\"\"Checks for an empty image.\n        \"\"\"\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)", "title": ""}
{"_id": "d4860", "text": "def from_rectangle(box):\n        \"\"\" Create a vector randomly within the given rectangle. \"\"\"\n        x = box.left + box.width * random.uniform(0, 1)\n        y = box.bottom + box.height * random.uniform(0, 1)\n        return Vector(x, y)", "title": ""}
{"_id": "d4861", "text": "def update_not_existing_kwargs(to_update, update_from):\n    \"\"\"\n    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.\n    \"\"\"\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", "title": ""}
{"_id": "d4862", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d4863", "text": "def h5ToDict(h5, readH5pyDataset=True):\n    \"\"\" Read a hdf5 file into a dictionary \"\"\"\n    h = h5py.File(h5, \"r\")\n    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n    if readH5pyDataset: h.close()\n    return ret", "title": ""}
{"_id": "d4864", "text": "def insert_slash(string, every=2):\n    \"\"\"insert_slash insert / every 2 char\"\"\"\n    return os.path.join(string[i:i+every] for i in xrange(0, len(string), every))", "title": ""}
{"_id": "d4865", "text": "def is_valid_variable_name(string_to_check):\n    \"\"\"\n    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\n    \"\"\"\n\n    try:\n\n        parse('{} = None'.format(string_to_check))\n        return True\n\n    except (SyntaxError, ValueError, TypeError):\n\n        return False", "title": ""}
{"_id": "d4866", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d4867", "text": "def __copy__(self):\n        \"\"\"A magic method to implement shallow copy behavior.\"\"\"\n        return self.__class__.load(self.dump(), context=self.context)", "title": ""}
{"_id": "d4868", "text": "def circles_pycairo(width, height, color):\n    \"\"\" Implementation of circle border with PyCairo. \"\"\"\n\n    cairo_color = color / rgb(255, 255, 255)\n\n    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n    ctx = cairo.Context(surface)\n\n    # draw a circle in the center\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\n    surface.write_to_png('circles.png')", "title": ""}
{"_id": "d4869", "text": "def combinations(l):\n    \"\"\"Pure-Python implementation of itertools.combinations(l, 2).\"\"\"\n    result = []\n    for x in xrange(len(l) - 1):\n        ls = l[x + 1:]\n        for y in ls:\n            result.append((l[x], y))\n    return result", "title": ""}
{"_id": "d4870", "text": "def _get_history_next(self):\n        \"\"\" callback function for key down \"\"\"\n        if self._has_history:\n            ret = self._input_history.return_history(1)\n            self.string = ret\n            self._curs_pos = len(ret)", "title": ""}
{"_id": "d4871", "text": "def random_id(length):\n    \"\"\"Generates a random ID of given length\"\"\"\n\n    def char():\n        \"\"\"Generate single random char\"\"\"\n\n        return random.choice(string.ascii_letters + string.digits)\n\n    return \"\".join(char() for _ in range(length))", "title": ""}
{"_id": "d4872", "text": "def normalize(im, invert=False, scale=None, dtype=np.float64):\n    \"\"\"\n    Normalize a field to a (min, max) exposure range, default is (0, 255).\n    (min, max) exposure values. Invert the image if requested.\n    \"\"\"\n    if dtype not in {np.float16, np.float32, np.float64}:\n        raise ValueError('dtype must be numpy.float16, float32, or float64.')\n    out = im.astype('float').copy()\n\n    scale = scale or (0.0, 255.0)\n    l, u = (float(i) for i in scale)\n    out = (out - l) / (u - l)\n    if invert:\n        out = -out + (out.max() + out.min())\n    return out.astype(dtype)", "title": ""}
{"_id": "d4873", "text": "def rlognormal(mu, tau, size=None):\n    \"\"\"\n    Return random lognormal variates.\n    \"\"\"\n\n    return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "title": ""}
{"_id": "d4874", "text": "def set_user_password(environment, parameter, password):\n    \"\"\"\n    Sets a user's password in the keyring storage\n    \"\"\"\n    username = '%s:%s' % (environment, parameter)\n    return password_set(username, password)", "title": ""}
{"_id": "d4875", "text": "def R_rot_3d(th):\n    \"\"\"Return a 3-dimensional rotation matrix.\n\n    Parameters\n    ----------\n    th: array, shape (n, 3)\n        Angles about which to rotate along each axis.\n\n    Returns\n    -------\n    R: array, shape (n, 3, 3)\n    \"\"\"\n    sx, sy, sz = np.sin(th).T\n    cx, cy, cz = np.cos(th).T\n    R = np.empty((len(th), 3, 3), dtype=np.float)\n\n    R[:, 0, 0] = cy * cz\n    R[:, 0, 1] = -cy * sz\n    R[:, 0, 2] = sy\n\n    R[:, 1, 0] = sx * sy * cz + cx * sz\n    R[:, 1, 1] = -sx * sy * sz + cx * cz\n    R[:, 1, 2] = -sx * cy\n\n    R[:, 2, 0] = -cx * sy * cz + sx * sz\n    R[:, 2, 1] = cx * sy * sz + sx * cz\n    R[:, 2, 2] = cx * cy\n    return R", "title": ""}
{"_id": "d4876", "text": "def fill_nulls(self, col: str):\n        \"\"\"\n        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\")``\n        \"\"\"\n        n = [None, \"\"]\n        try:\n            self.df[col] = self.df[col].replace(n, nan)\n        except Exception as e:\n            self.err(e)", "title": ""}
{"_id": "d4877", "text": "def percentile(values, k):\n    \"\"\"Find the percentile of a list of values.\n\n    :param list values: The list of values to find the percentile of\n    :param int k: The percentile to find\n    :rtype: float or int\n\n    \"\"\"\n    if not values:\n        return None\n    values.sort()\n    index = (len(values) * (float(k) / 100)) - 1\n    return values[int(math.ceil(index))]", "title": ""}
{"_id": "d4878", "text": "def get_absolute_path(*args):\n    \"\"\"Transform relative pathnames into absolute pathnames.\"\"\"\n    directory = os.path.dirname(os.path.abspath(__file__))\n    return os.path.join(directory, *args)", "title": ""}
{"_id": "d4879", "text": "def percentile(values, k):\n    \"\"\"Find the percentile of a list of values.\n\n    :param list values: The list of values to find the percentile of\n    :param int k: The percentile to find\n    :rtype: float or int\n\n    \"\"\"\n    if not values:\n        return None\n    values.sort()\n    index = (len(values) * (float(k) / 100)) - 1\n    return values[int(math.ceil(index))]", "title": ""}
{"_id": "d4880", "text": "def read_dict_from_file(file_path):\n    \"\"\"\n    Read a dictionary of strings from a file\n    \"\"\"\n    with open(file_path) as file:\n        lines = file.read().splitlines()\n\n    obj = {}\n    for line in lines:\n        key, value = line.split(':', maxsplit=1)\n        obj[key] = eval(value)\n\n    return obj", "title": ""}
{"_id": "d4881", "text": "def get_methods(*objs):\n    \"\"\" Return the names of all callable attributes of an object\"\"\"\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    )", "title": ""}
{"_id": "d4882", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d4883", "text": "def dict_from_object(obj: object):\n    \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n    # If object is a dict instance, no need to convert.\n    return (obj if isinstance(obj, dict)\n            else {attr: getattr(obj, attr)\n                  for attr in dir(obj) if not attr.startswith('_')})", "title": ""}
{"_id": "d4884", "text": "def xmltreefromfile(filename):\n    \"\"\"Internal function to read an XML file\"\"\"\n    try:\n        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n    except TypeError:\n        return ElementTree.parse(filename, ElementTree.XMLParser())", "title": ""}
{"_id": "d4885", "text": "def calc_list_average(l):\n    \"\"\"\n    Calculates the average value of a list of numbers\n    Returns a float\n    \"\"\"\n    total = 0.0\n    for value in l:\n        total += value\n    return total / len(l)", "title": ""}
{"_id": "d4886", "text": "def redirect_output(fileobj):\n    \"\"\"Redirect standard out to file.\"\"\"\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old", "title": ""}
{"_id": "d4887", "text": "def get(s, delimiter='', format=\"diacritical\"):\n    \"\"\"Return pinyin of string, the string must be unicode\n    \"\"\"\n    return delimiter.join(_pinyin_generator(u(s), format=format))", "title": ""}
{"_id": "d4888", "text": "def remove_ext(fname):\n    \"\"\"Removes the extension from a filename\n    \"\"\"\n    bn = os.path.basename(fname)\n    return os.path.splitext(bn)[0]", "title": ""}
{"_id": "d4889", "text": "def estimate_complexity(self, x,y,z,n):\n        \"\"\" \n        calculates a rough guess of runtime based on product of parameters \n        \"\"\"\n        num_calculations = x * y * z * n\n        run_time = num_calculations / 100000  # a 2014 PC does about 100k calcs in a second (guess based on prior logs)\n        return self.show_time_as_short_string(run_time)", "title": ""}
{"_id": "d4890", "text": "def do_rewind(self, line):\n        \"\"\"\n        rewind\n        \"\"\"\n        self.print_response(\"Rewinding from frame %s to 0\" % self.bot._frame)\n        self.bot._frame = 0", "title": ""}
{"_id": "d4891", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d4892", "text": "def _file_exists(path, filename):\n  \"\"\"Checks if the filename exists under the path.\"\"\"\n  return os.path.isfile(os.path.join(path, filename))", "title": ""}
{"_id": "d4893", "text": "def unproject(self, xy):\n        \"\"\"\n        Returns the coordinates from position in meters\n        \"\"\"\n        (x, y) = xy\n        lng = x/EARTH_RADIUS * RAD_TO_DEG\n        lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG\n        return (lng, lat)", "title": ""}
{"_id": "d4894", "text": "def is_palindrome(string, strict=True):\n    \"\"\"\n    Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n    :param string: String to check.\n    :type string: str\n    :param strict: True if white spaces matter (default), false otherwise.\n    :type strict: bool\n    :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\n    False otherwise\n    \"\"\"\n    if is_full_string(string):\n        if strict:\n            return reverse(string) == string\n        return is_palindrome(SPACES_RE.sub('', string))\n    return False", "title": ""}
{"_id": "d4895", "text": "def _cosine(a, b):\n    \"\"\" Return the len(a & b) / len(a) \"\"\"\n    return 1. * len(a & b) / (math.sqrt(len(a)) * math.sqrt(len(b)))", "title": ""}
{"_id": "d4896", "text": "def count(self, X):\n        \"\"\"\n        Called from the fit method, this method gets all the\n        words from the corpus and their corresponding frequency\n        counts.\n\n        Parameters\n        ----------\n\n        X : ndarray or masked ndarray\n            Pass in the matrix of vectorized documents, can be masked in\n            order to sum the word frequencies for only a subset of documents.\n\n        Returns\n        -------\n\n        counts : array\n            A vector containing the counts of all words in X (columns)\n\n        \"\"\"\n        # Sum on axis 0 (by columns), each column is a word\n        # Convert the matrix to an array\n        # Squeeze to remove the 1 dimension objects (like ravel)\n        return np.squeeze(np.asarray(X.sum(axis=0)))", "title": ""}
{"_id": "d4897", "text": "def get_current_frames():\n    \"\"\"Return current threads prepared for \n    further processing.\n    \"\"\"\n    return dict(\n        (thread_id, {'frame': thread2list(frame), 'time': None})\n        for thread_id, frame in sys._current_frames().items()\n    )", "title": ""}
{"_id": "d4898", "text": "def _replace_none(self, aDict):\n        \"\"\" Replace all None values in a dict with 'none' \"\"\"\n        for k, v in aDict.items():\n            if v is None:\n                aDict[k] = 'none'", "title": ""}
{"_id": "d4899", "text": "def timestamp_from_datetime(dt):\n    \"\"\"\n    Compute timestamp from a datetime object that could be timezone aware\n    or unaware.\n    \"\"\"\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())", "title": ""}
{"_id": "d4900", "text": "def __normalize_list(self, msg):\n        \"\"\"Split message to list by commas and trim whitespace.\"\"\"\n        if isinstance(msg, list):\n            msg = \"\".join(msg)\n        return list(map(lambda x: x.strip(), msg.split(\",\")))", "title": ""}
{"_id": "d4901", "text": "def get_uniques(l):\n    \"\"\" Returns a list with no repeated elements.\n    \"\"\"\n    result = []\n\n    for i in l:\n        if i not in result:\n            result.append(i)\n\n    return result", "title": ""}
{"_id": "d4902", "text": "def _swap_rows(self, i, j):\n        \"\"\"Swap i and j rows\n\n        As the side effect, determinant flips.\n\n        \"\"\"\n\n        L = np.eye(3, dtype='intc')\n        L[i, i] = 0\n        L[j, j] = 0\n        L[i, j] = 1\n        L[j, i] = 1\n        self._L.append(L.copy())\n        self._A = np.dot(L, self._A)", "title": ""}
{"_id": "d4903", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d4904", "text": "def is_symlink(self):\n        \"\"\"\n        Whether this path is a symbolic link.\n        \"\"\"\n        try:\n            return S_ISLNK(self.lstat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            # Path doesn't exist\n            return False", "title": ""}
{"_id": "d4905", "text": "def vector_distance(a, b):\n    \"\"\"The Euclidean distance between two vectors.\"\"\"\n    a = np.array(a)\n    b = np.array(b)\n    return np.linalg.norm(a - b)", "title": ""}
{"_id": "d4906", "text": "def extract_module_locals(depth=0):\n    \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n    f = sys._getframe(depth + 1)\n    global_ns = f.f_globals\n    module = sys.modules[global_ns['__name__']]\n    return (module, f.f_locals)", "title": ""}
{"_id": "d4907", "text": "def is_binary(filename):\n    \"\"\" Returns True if the file is binary\n\n    \"\"\"\n    with open(filename, 'rb') as fp:\n        data = fp.read(1024)\n        if not data:\n            return False\n        if b'\\0' in data:\n            return True\n        return False", "title": ""}
{"_id": "d4908", "text": "def _get_image_numpy_dtype(self):\n        \"\"\"\n        Get the numpy dtype for the image\n        \"\"\"\n        try:\n            ftype = self._info['img_equiv_type']\n            npy_type = _image_bitpix2npy[ftype]\n        except KeyError:\n            raise KeyError(\"unsupported fits data type: %d\" % ftype)\n\n        return npy_type", "title": ""}
{"_id": "d4909", "text": "def printOut(value, end='\\n'):\n    \"\"\"\n    This function prints the given String immediately and flushes the output.\n    \"\"\"\n    sys.stdout.write(value)\n    sys.stdout.write(end)\n    sys.stdout.flush()", "title": ""}
{"_id": "d4910", "text": "def _get_item_position(self, idx):\n        \"\"\"Return a tuple of (start, end) indices of an item from its index.\"\"\"\n        start = 0 if idx == 0 else self._index[idx - 1] + 1\n        end = self._index[idx]\n        return start, end", "title": ""}
{"_id": "d4911", "text": "def warn(self, text):\n\t\t\"\"\" Ajout d'un message de log de type WARN \"\"\"\n\t\tself.logger.warn(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d4912", "text": "def get_model_index_properties(instance, index):\n    \"\"\"Return the list of properties specified for a model in an index.\"\"\"\n    mapping = get_index_mapping(index)\n    doc_type = instance._meta.model_name.lower()\n    return list(mapping[\"mappings\"][doc_type][\"properties\"].keys())", "title": ""}
{"_id": "d4913", "text": "def copy(self):\n        \"\"\"Return a copy of this list with each element copied to new memory\n        \"\"\"\n        out = type(self)()\n        for series in self:\n            out.append(series.copy())\n        return out", "title": ""}
{"_id": "d4914", "text": "def open_json(file_name):\n    \"\"\"\n    returns json contents as string\n    \"\"\"\n    with open(file_name, \"r\") as json_data:\n        data = json.load(json_data)\n        return data", "title": ""}
{"_id": "d4915", "text": "def markdown_to_text(body):\n    \"\"\"Converts markdown to text.\n\n    Args:\n        body: markdown (or plaintext, or maybe HTML) input\n\n    Returns:\n        Plaintext with all tags and frills removed\n    \"\"\"\n    # Turn our input into HTML\n    md = markdown.markdown(body, extensions=[\n        'markdown.extensions.extra'\n    ])\n\n    # Safely parse HTML so that we don't have to parse it ourselves\n    soup = BeautifulSoup(md, 'html.parser')\n\n    # Return just the text of the parsed HTML\n    return soup.get_text()", "title": ""}
{"_id": "d4916", "text": "def last_modified_date(filename):\n    \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n    mtime = os.path.getmtime(filename)\n    dt = datetime.datetime.utcfromtimestamp(mtime)\n    return dt.replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d4917", "text": "def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,\ncontent=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for not-authorized access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=401)", "title": ""}
{"_id": "d4918", "text": "def get_idx_rect(index_list):\n    \"\"\"Extract the boundaries from a list of indexes\"\"\"\n    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\n    return ( min(rows), max(rows), min(cols), max(cols) )", "title": ""}
{"_id": "d4919", "text": "def _getTypename(self, defn):\n        \"\"\" Returns the SQL typename required to store the given FieldDefinition \"\"\"\n        return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'", "title": ""}
{"_id": "d4920", "text": "def objectproxy_realaddress(obj):\n    \"\"\"\n    Obtain a real address as an integer from an objectproxy.\n    \"\"\"\n    voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)\n    return C.addressof(C.c_char.from_buffer(voidp))", "title": ""}
{"_id": "d4921", "text": "def server(self):\n        \"\"\"Returns the size of remote files\n        \"\"\"\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 \" \"", "title": ""}
{"_id": "d4922", "text": "def get_mouse_location(self):\n        \"\"\"\n        Get the current mouse location (coordinates and screen number).\n\n        :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields\n        \"\"\"\n        x = ctypes.c_int(0)\n        y = ctypes.c_int(0)\n        screen_num = ctypes.c_int(0)\n        _libxdo.xdo_get_mouse_location(\n            self._xdo, ctypes.byref(x), ctypes.byref(y),\n            ctypes.byref(screen_num))\n        return mouse_location(x.value, y.value, screen_num.value)", "title": ""}
{"_id": "d4923", "text": "def task_property_present_predicate(service, task, prop):\n    \"\"\" True if the json_element passed is present for the task specified.\n    \"\"\"\n    try:\n        response = get_service_task(service, task)\n    except Exception as e:\n        pass\n\n    return (response is not None) and (prop in response)", "title": ""}
{"_id": "d4924", "text": "def GetMountpoints():\n  \"\"\"List all the filesystems mounted on the system.\"\"\"\n  devices = {}\n\n  for filesys in GetFileSystems():\n    devices[filesys.f_mntonname] = (filesys.f_mntfromname, filesys.f_fstypename)\n\n  return devices", "title": ""}
{"_id": "d4925", "text": "def is_readable(fp, size=1):\n    \"\"\"\n    Check if the file-like object is readable.\n\n    :param fp: file-like object\n    :param size: byte size\n    :return: bool\n    \"\"\"\n    read_size = len(fp.read(size))\n    fp.seek(-read_size, 1)\n    return read_size == size", "title": ""}
{"_id": "d4926", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d4927", "text": "def ensure_dir_exists(directory):\n    \"\"\"Se asegura de que un directorio exista.\"\"\"\n    if directory and not os.path.exists(directory):\n        os.makedirs(directory)", "title": ""}
{"_id": "d4928", "text": "def _GetValue(self, name):\n    \"\"\"Returns the TextFSMValue object natching the requested name.\"\"\"\n    for value in self.values:\n      if value.name == name:\n        return value", "title": ""}
{"_id": "d4929", "text": "def issuperset(self, other):\n        \"\"\"Report whether this RangeSet contains another set.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issuperset(self, other)", "title": ""}
{"_id": "d4930", "text": "def check_output(args):\n    \"\"\"Runs command and returns the output as string.\"\"\"\n    log.debug('run: %s', args)\n    out = subprocess.check_output(args=args).decode('utf-8')\n    log.debug('out: %r', out)\n    return out", "title": ""}
{"_id": "d4931", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d4932", "text": "def owner(self):\n        \"\"\"\n        Username of document creator\n        \"\"\"\n        if self._owner:\n            return self._owner\n        elif not self.abstract:\n            return self.read_meta()._owner\n\n        raise EmptyDocumentException()", "title": ""}
{"_id": "d4933", "text": "def is_iterable(value):\n    \"\"\"must be an iterable (list, array, tuple)\"\"\"\n    return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "title": ""}
{"_id": "d4934", "text": "def dict_from_object(obj: object):\n    \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n    # If object is a dict instance, no need to convert.\n    return (obj if isinstance(obj, dict)\n            else {attr: getattr(obj, attr)\n                  for attr in dir(obj) if not attr.startswith('_')})", "title": ""}
{"_id": "d4935", "text": "def leaf_nodes(self):\n        \"\"\"\n        Return an interable of nodes with no edges pointing at them. This is\n        helpful to find all nodes without dependencies.\n        \"\"\"\n        # Now contains all nodes that contain dependencies.\n        deps = {item for sublist in self.edges.values() for item in sublist}\n        # contains all nodes *without* any dependencies (leaf nodes)\n        return self.nodes - deps", "title": ""}
{"_id": "d4936", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d4937", "text": "def check_color(cls, raw_image):\n        \"\"\"\n        Just check if raw_image is completely white.\n        http://stackoverflow.com/questions/14041562/python-pil-detect-if-an-image-is-completely-black-or-white\n        \"\"\"\n        # sum(img.convert(\"L\").getextrema()) in (0, 2)\n        extrema = raw_image.convert(\"L\").getextrema()\n        if extrema == (255, 255): # all white\n            raise cls.MonoImageException", "title": ""}
{"_id": "d4938", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d4939", "text": "def findMin(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMin(arr, out)\n    return out", "title": ""}
{"_id": "d4940", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d4941", "text": "def prevmonday(num):\n    \"\"\"\n    Return unix SECOND timestamp of \"num\" mondays ago\n    \"\"\"\n    today = get_today()\n    lastmonday = today - timedelta(days=today.weekday(), weeks=num)\n    return lastmonday", "title": ""}
{"_id": "d4942", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d4943", "text": "def end_index(self):\n        \"\"\"\n        Returns the 1-based index of the last object on this page,\n        relative to total objects found (hits).\n        \"\"\"\n        return ((self.number - 1) * self.paginator.per_page +\n            len(self.object_list))", "title": ""}
{"_id": "d4944", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d4945", "text": "def get_property(self, property_name):\n        \"\"\"\n        Get a property's value.\n\n        property_name -- the property to get the value of\n\n        Returns the properties value, if found, else None.\n        \"\"\"\n        prop = self.find_property(property_name)\n        if prop:\n            return prop.get_value()\n\n        return None", "title": ""}
{"_id": "d4946", "text": "def copyFile(input, output, replace=None):\n    \"\"\"Copy a file whole from input to output.\"\"\"\n\n    _found = findFile(output)\n    if not _found or (_found and replace):\n        shutil.copy2(input, output)", "title": ""}
{"_id": "d4947", "text": "def byte2int(s, index=0):\n    \"\"\"Get the ASCII int value of a character in a string.\n\n    :param s: a string\n    :param index: the position of desired character\n\n    :return: ASCII int value\n    \"\"\"\n    if six.PY2:\n        return ord(s[index])\n    return s[index]", "title": ""}
{"_id": "d4948", "text": "def indent(text, amount, ch=' '):\n    \"\"\"Indents a string by the given amount of characters.\"\"\"\n    padding = amount * ch\n    return ''.join(padding+line for line in text.splitlines(True))", "title": ""}
{"_id": "d4949", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d4950", "text": "def cint32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):\n        return np.fromiter(cptr, dtype=np.int32, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d4951", "text": "def get_user_name():\n    \"\"\"Get user name provide by operating system\n    \"\"\"\n\n    if sys.platform == 'win32':\n        #user = os.getenv('USERPROFILE')\n        user = os.getenv('USERNAME')\n    else:\n        user = os.getenv('LOGNAME')\n\n    return user", "title": ""}
{"_id": "d4952", "text": "def robust_int(v):\n    \"\"\"Parse an int robustly, ignoring commas and other cruft. \"\"\"\n\n    if isinstance(v, int):\n        return v\n\n    if isinstance(v, float):\n        return int(v)\n\n    v = str(v).replace(',', '')\n\n    if not v:\n        return None\n\n    return int(v)", "title": ""}
{"_id": "d4953", "text": "def _get_minidom_tag_value(station, tag_name):\n    \"\"\"get a value from a tag (if it exists)\"\"\"\n    tag = station.getElementsByTagName(tag_name)[0].firstChild\n    if tag:\n        return tag.nodeValue\n\n    return None", "title": ""}
{"_id": "d4954", "text": "def interpolate_slice(slice_rows, slice_cols, interpolator):\n    \"\"\"Interpolate the given slice of the larger array.\"\"\"\n    fine_rows = np.arange(slice_rows.start, slice_rows.stop, slice_rows.step)\n    fine_cols = np.arange(slice_cols.start, slice_cols.stop, slice_cols.step)\n    return interpolator(fine_cols, fine_rows)", "title": ""}
{"_id": "d4955", "text": "def _getVirtualScreenRect(self):\n        \"\"\" The virtual screen is the bounding box containing all monitors.\n\n        Not all regions in the virtual screen are actually visible. The (0,0) coordinate\n        is the top left corner of the primary screen rather than the whole bounding box, so\n        some regions of the virtual screen may have negative coordinates if another screen\n        is positioned in Windows as further to the left or above the primary screen.\n\n        Returns the rect as (x, y, w, h)\n        \"\"\"\n        SM_XVIRTUALSCREEN = 76  # Left of virtual screen\n        SM_YVIRTUALSCREEN = 77  # Top of virtual screen\n        SM_CXVIRTUALSCREEN = 78 # Width of virtual screen\n        SM_CYVIRTUALSCREEN = 79 # Height of virtual screen\n\n        return (self._user32.GetSystemMetrics(SM_XVIRTUALSCREEN), \\\n                self._user32.GetSystemMetrics(SM_YVIRTUALSCREEN), \\\n                self._user32.GetSystemMetrics(SM_CXVIRTUALSCREEN), \\\n                self._user32.GetSystemMetrics(SM_CYVIRTUALSCREEN))", "title": ""}
{"_id": "d4956", "text": "def resample(grid, wl, flux):\n    \"\"\" Resample spectrum onto desired grid \"\"\"\n    flux_rs = (interpolate.interp1d(wl, flux))(grid)\n    return flux_rs", "title": ""}
{"_id": "d4957", "text": "def title(self):\n        \"\"\" The title of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.title", "title": ""}
{"_id": "d4958", "text": "def pythonise(id, encoding='ascii'):\n    \"\"\"Return a Python-friendly id\"\"\"\n    replace = {'-': '_', ':': '_', '/': '_'}\n    func = lambda id, pair: id.replace(pair[0], pair[1])\n    id = reduce(func, replace.iteritems(), id)\n    id = '_%s' % id if id[0] in string.digits else id\n    return id.encode(encoding)", "title": ""}
{"_id": "d4959", "text": "def getEventTypeNameFromEnum(self, eType):\n        \"\"\"returns the name of an EVREvent enum value\"\"\"\n\n        fn = self.function_table.getEventTypeNameFromEnum\n        result = fn(eType)\n        return result", "title": ""}
{"_id": "d4960", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d4961", "text": "def check_git():\n    \"\"\"Check if git command is available.\"\"\"\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.\")", "title": ""}
{"_id": "d4962", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d4963", "text": "def is_palindrome(string, strict=True):\n    \"\"\"\n    Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n    :param string: String to check.\n    :type string: str\n    :param strict: True if white spaces matter (default), false otherwise.\n    :type strict: bool\n    :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\n    False otherwise\n    \"\"\"\n    if is_full_string(string):\n        if strict:\n            return reverse(string) == string\n        return is_palindrome(SPACES_RE.sub('', string))\n    return False", "title": ""}
{"_id": "d4964", "text": "def to_str(s):\n    \"\"\"\n    Convert bytes and non-string into Python 3 str\n    \"\"\"\n    if isinstance(s, bytes):\n        s = s.decode('utf-8')\n    elif not isinstance(s, str):\n        s = str(s)\n    return s", "title": ""}
{"_id": "d4965", "text": "def bbox(img):\n    \"\"\"Find the bounding box around nonzero elements in the given array\n\n    Copied from https://stackoverflow.com/a/31402351/5703449 .\n\n    Returns:\n        rowmin, rowmax, colmin, colmax\n    \"\"\"\n    rows = np.any(img, axis=1)\n    cols = np.any(img, axis=0)\n    rmin, rmax = np.where(rows)[0][[0, -1]]\n    cmin, cmax = np.where(cols)[0][[0, -1]]\n\n    return rmin, rmax, cmin, cmax", "title": ""}
{"_id": "d4966", "text": "def chunks(arr, size):\n    \"\"\"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`\n    \"\"\"\n    for i in _range(0, len(arr), size):\n        yield arr[i:i+size]", "title": ""}
{"_id": "d4967", "text": "def query_proc_row(procname, args=(), factory=None):\n    \"\"\"\n    Execute a stored procedure. Returns the first row of the result set,\n    or `None`.\n    \"\"\"\n    for row in query_proc(procname, args, factory):\n        return row\n    return None", "title": ""}
{"_id": "d4968", "text": "def concat(cls, iterables):\n    \"\"\"\n    Similar to #itertools.chain.from_iterable().\n    \"\"\"\n\n    def generator():\n      for it in iterables:\n        for element in it:\n          yield element\n    return cls(generator())", "title": ""}
{"_id": "d4969", "text": "def lazy_reverse_binmap(f, xs):\n    \"\"\"\n    Same as lazy_binmap, except the parameters are flipped for the binary function\n    \"\"\"\n    return (f(y, x) for x, y in zip(xs, xs[1:]))", "title": ""}
{"_id": "d4970", "text": "def __next__(self):\n    \"\"\"Pop the head off the iterator and return it.\"\"\"\n    res = self._head\n    self._fill()\n    if res is None:\n      raise StopIteration()\n    return res", "title": ""}
{"_id": "d4971", "text": "def _heappush_max(heap, item):\n    \"\"\" why is this not in heapq \"\"\"\n    heap.append(item)\n    heapq._siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d4972", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d4973", "text": "def min_depth(self, root):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: int\n    \"\"\"\n    if root is None:\n        return 0\n    if root.left is not None or root.right is not None:\n        return max(self.minDepth(root.left), self.minDepth(root.right))+1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1", "title": ""}
{"_id": "d4974", "text": "def each_img(dir_path):\n    \"\"\"\n    Iterates through each image in the given directory. (not recursive)\n    :param dir_path: Directory path where images files are present\n    :return: Iterator to iterate through image files\n    \"\"\"\n    for fname in os.listdir(dir_path):\n        if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'):\n            yield fname", "title": ""}
{"_id": "d4975", "text": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "title": ""}
{"_id": "d4976", "text": "def get_files(dir_name):\n    \"\"\"Simple directory walker\"\"\"\n    return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]", "title": ""}
{"_id": "d4977", "text": "def get_highlighted_code(name, code, type='terminal'):\n    \"\"\"\n    If pygments are available on the system\n    then returned output is colored. Otherwise\n    unchanged content is returned.\n    \"\"\"\n    import logging\n    try:\n        import pygments\n        pygments\n    except ImportError:\n        return code\n    from pygments import highlight\n    from pygments.lexers import guess_lexer_for_filename, ClassNotFound\n    from pygments.formatters import TerminalFormatter\n\n    try:\n        lexer = guess_lexer_for_filename(name, code)\n        formatter = TerminalFormatter()\n        content = highlight(code, lexer, formatter)\n    except ClassNotFound:\n        logging.debug(\"Couldn't guess Lexer, will not use pygments.\")\n        content = code\n    return content", "title": ""}
{"_id": "d4978", "text": "def _dict_values_sorted_by_key(dictionary):\n    # This should be a yield from instead.\n    \"\"\"Internal helper to return the values of a dictionary, sorted by key.\n    \"\"\"\n    for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):\n        yield value", "title": ""}
{"_id": "d4979", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d4980", "text": "def __iter__(self):\n\t\t\"\"\"Iterate through all elements.\n\n\t\tMultiple copies will be returned if they exist.\n\t\t\"\"\"\n\t\tfor value, count in self.counts():\n\t\t\tfor _ in range(count):\n\t\t\t\tyield value", "title": ""}
{"_id": "d4981", "text": "def isnumber(*args):\n    \"\"\"Checks if value is an integer, long integer or float.\n\n    NOTE: Treats booleans as numbers, where True=1 and False=0.\n    \"\"\"\n    return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))", "title": ""}
{"_id": "d4982", "text": "def _unordered_iterator(self):\n        \"\"\"\n        Return the value of each QuerySet, but also add the '#' property to each\n        return item.\n        \"\"\"\n        for i, qs in zip(self._queryset_idxs, self._querysets):\n            for item in qs:\n                setattr(item, '#', i)\n                yield item", "title": ""}
{"_id": "d4983", "text": "def pretty_xml(data):\n    \"\"\"Return a pretty formated xml\n    \"\"\"\n    parsed_string = minidom.parseString(data.decode('utf-8'))\n    return parsed_string.toprettyxml(indent='\\t', encoding='utf-8')", "title": ""}
{"_id": "d4984", "text": "def get_chunks(source, chunk_len):\n    \"\"\" Returns an iterator over 'chunk_len' chunks of 'source' \"\"\"\n    return (source[i: i + chunk_len] for i in range(0, len(source), chunk_len))", "title": ""}
{"_id": "d4985", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d4986", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d4987", "text": "def getpackagepath():\n    \"\"\"\n     *Get the root path for this python package - used in unit testing code*\n    \"\"\"\n    moduleDirectory = os.path.dirname(__file__)\n    packagePath = os.path.dirname(__file__) + \"/../\"\n\n    return packagePath", "title": ""}
{"_id": "d4988", "text": "def next(self):\n        \"\"\"Retrieve the next row.\"\"\"\n        # I'm pretty sure this is the completely wrong way to go about this, but\n        # oh well, this works.\n        if not hasattr(self, '_iter'):\n            self._iter = self.readrow_as_dict()\n        return self._iter.next()", "title": ""}
{"_id": "d4989", "text": "def first_sunday(self, year, month):\n        \"\"\"Get the first sunday of a month.\"\"\"\n        date = datetime(year, month, 1, 0)\n        days_until_sunday = 6 - date.weekday()\n\n        return date + timedelta(days=days_until_sunday)", "title": ""}
{"_id": "d4990", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d4991", "text": "def last(self):\n        \"\"\"Get the last object in file.\"\"\"\n        # End of file\n        self.__file.seek(0, 2)\n\n        # Get the last struct\n        data = self.get(self.length - 1)\n\n        return data", "title": ""}
{"_id": "d4992", "text": "def html(header_rows):\n    \"\"\"\n    Convert a list of tuples describing a table into a HTML string\n    \"\"\"\n    name = 'table%d' % next(tablecounter)\n    return HtmlTable([map(str, row) for row in header_rows], name).render()", "title": ""}
{"_id": "d4993", "text": "def authenticate(self, transport, account_name, password=None):\n        \"\"\"\n        Authenticates account using soap method.\n        \"\"\"\n        Authenticator.authenticate(self, transport, account_name, password)\n\n        if password == None:\n            return self.pre_auth(transport, account_name)\n        else:\n            return self.auth(transport, account_name, password)", "title": ""}
{"_id": "d4994", "text": "def render_template(template_name, **context):\n    \"\"\"Render a template into a response.\"\"\"\n    tmpl = jinja_env.get_template(template_name)\n    context[\"url_for\"] = url_for\n    return Response(tmpl.render(context), mimetype=\"text/html\")", "title": ""}
{"_id": "d4995", "text": "def comma_converter(float_string):\n    \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n    trans_table = maketrans(b',', b'.')\n    return float(float_string.translate(trans_table))", "title": ""}
{"_id": "d4996", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d4997", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d4998", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d4999", "text": "def __iter__(self):\n\t\t\"\"\"Iterate through all elements.\n\n\t\tMultiple copies will be returned if they exist.\n\t\t\"\"\"\n\t\tfor value, count in self.counts():\n\t\t\tfor _ in range(count):\n\t\t\t\tyield value", "title": ""}
{"_id": "d5000", "text": "def prepare_path(path):\n    \"\"\"\n    Path join helper method\n    Join paths if list passed\n\n    :type path: str|unicode|list\n    :rtype: str|unicode\n    \"\"\"\n    if type(path) == list:\n        return os.path.join(*path)\n    return path", "title": ""}
{"_id": "d5001", "text": "def finish_plot():\n    \"\"\"Helper for plotting.\"\"\"\n    plt.legend()\n    plt.grid(color='0.7')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.show()", "title": ""}
{"_id": "d5002", "text": "def is_valid_data(obj):\n    \"\"\"Check if data is JSON serializable.\n    \"\"\"\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", "title": ""}
{"_id": "d5003", "text": "def check_git():\n    \"\"\"Check if git command is available.\"\"\"\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.\")", "title": ""}
{"_id": "d5004", "text": "def _deserialize_datetime(self, data):\n        \"\"\"Take any values coming in as a datetime and deserialize them\n\n        \"\"\"\n        for key in data:\n            if isinstance(data[key], dict):\n                if data[key].get('type') == 'datetime':\n                    data[key] = \\\n                        datetime.datetime.fromtimestamp(data[key]['value'])\n        return data", "title": ""}
{"_id": "d5005", "text": "def set_float(val):\n    \"\"\" utility to set a floating value,\n    useful for converting from strings \"\"\"\n    out = None\n    if not val in (None, ''):\n        try:\n            out = float(val)\n        except ValueError:\n            return None\n        if numpy.isnan(out):\n            out = default\n    return out", "title": ""}
{"_id": "d5006", "text": "def parse_list(cls, api, json_list):\n        \"\"\"\n            Parse a list of JSON objects into\n            a result set of model instances.\n        \"\"\"\n        results = []\n        for json_obj in json_list:\n            if json_obj:\n                obj = cls.parse(api, json_obj)\n                results.append(obj)\n\n        return results", "title": ""}
{"_id": "d5007", "text": "def test():\n    \"\"\"Test program for telnetlib.\n\n    Usage: python telnetlib.py [-d] ... [host [port]]\n\n    Default host is localhost; default port is 23.\n\n    \"\"\"\n    debuglevel = 0\n    while sys.argv[1:] and sys.argv[1] == '-d':\n        debuglevel = debuglevel + 1\n        del sys.argv[1]\n    host = 'localhost'\n    if sys.argv[1:]:\n        host = sys.argv[1]\n    port = 0\n    if sys.argv[2:]:\n        portstr = sys.argv[2]\n        try:\n            port = int(portstr)\n        except ValueError:\n            port = socket.getservbyname(portstr, 'tcp')\n    tn = Telnet()\n    tn.set_debuglevel(debuglevel)\n    tn.open(host, port)\n    tn.interact()\n    tn.close()", "title": ""}
{"_id": "d5008", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d5009", "text": "def fast_exit(code):\n    \"\"\"Exit without garbage collection, this speeds up exit by about 10ms for\n    things like bash completion.\n    \"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(code)", "title": ""}
{"_id": "d5010", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d5011", "text": "def with_headers(self, headers):\n        \"\"\"Sets multiple headers on the request and returns the request itself.\n\n        Keyword arguments:\n        headers -- a dict-like object which contains the headers to set.\n        \"\"\"\n        for key, value in headers.items():\n            self.with_header(key, value)\n        return self", "title": ""}
{"_id": "d5012", "text": "def as_tree(context):\n    \"\"\"Return info about an object's members as JSON\"\"\"\n\n    tree = _build_tree(context, 2, 1)\n    if type(tree) == dict:\n        tree = [tree] \n    \n    return Response(content_type='application/json', body=json.dumps(tree))", "title": ""}
{"_id": "d5013", "text": "def normalize_matrix(matrix):\n  \"\"\"Fold all values of the matrix into [0, 1].\"\"\"\n  abs_matrix = np.abs(matrix.copy())\n  return abs_matrix / abs_matrix.max()", "title": ""}
{"_id": "d5014", "text": "def process_result_value(self, value, dialect):\n        \"\"\"convert value from json to a python object\"\"\"\n        if value is not None:\n            value = simplejson.loads(value)\n        return value", "title": ""}
{"_id": "d5015", "text": "def is_int(string):\n    \"\"\"\n    Checks if a string is an integer. If the string value is an integer\n    return True, otherwise return False. \n    \n    Args:\n        string: a string to test.\n\n    Returns: \n        boolean\n    \"\"\"\n    try:\n        a = float(string)\n        b = int(a)\n    except ValueError:\n        return False\n    else:\n        return a == b", "title": ""}
{"_id": "d5016", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d5017", "text": "def ratio_and_percentage(current, total, time_remaining):\n    \"\"\"Returns the progress ratio and percentage.\"\"\"\n    return \"{} / {} ({}% completed)\".format(current, total, int(current / total * 100))", "title": ""}
{"_id": "d5018", "text": "def lmx_h1k_f64k():\n  \"\"\"HParams for training languagemodel_lm1b32k_packed.  880M Params.\"\"\"\n  hparams = lmx_base()\n  hparams.hidden_size = 1024\n  hparams.filter_size = 65536\n  hparams.batch_size = 2048\n  return hparams", "title": ""}
{"_id": "d5019", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d5020", "text": "def kill_process_children(pid):\n    \"\"\"Find and kill child processes of a process.\n\n    :param pid: PID of parent process (process ID)\n    :return: Nothing\n    \"\"\"\n    if sys.platform == \"darwin\":\n        kill_process_children_osx(pid)\n    elif sys.platform == \"linux\":\n        kill_process_children_unix(pid)\n    else:\n        pass", "title": ""}
{"_id": "d5021", "text": "def extend(self, item):\n        \"\"\"Extend the list with another list. Each member of the list must be\n        a string.\"\"\"\n        if not isinstance(item, list):\n            raise TypeError(\n                'You can only extend lists with lists. '\n                'You supplied \\\"%s\\\"' % type(item))\n        for entry in item:\n            if not isinstance(entry, str):\n                raise TypeError(\n                    'Members of this object must be strings. '\n                    'You supplied \\\"%s\\\"' % type(entry))\n            list.append(self, entry)", "title": ""}
{"_id": "d5022", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d5023", "text": "def prettifysql(sql):\n    \"\"\"Returns a prettified version of the SQL as a list of lines to help\n    in creating a useful diff between two SQL statements.\"\"\"\n    pretty = []\n    for line in sql.split('\\n'):\n        pretty.extend([\"%s,\\n\" % x for x in line.split(',')])\n    return pretty", "title": ""}
{"_id": "d5024", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d5025", "text": "def make_lambda(call):\n    \"\"\"Wrap an AST Call node to lambda expression node.\n    call: ast.Call node\n    \"\"\"\n    empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n    return ast.Lambda(args=empty_args, body=call)", "title": ""}
{"_id": "d5026", "text": "def print_datetime_object(dt):\n    \"\"\"prints a date-object\"\"\"\n    print(dt)\n    print('ctime  :', dt.ctime())\n    print('tuple  :', dt.timetuple())\n    print('ordinal:', dt.toordinal())\n    print('Year   :', dt.year)\n    print('Mon    :', dt.month)\n    print('Day    :', dt.day)", "title": ""}
{"_id": "d5027", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d5028", "text": "def _clean_str(self, s):\n        \"\"\" Returns a lowercase string with punctuation and bad chars removed\n        :param s: string to clean\n        \"\"\"\n        return s.translate(str.maketrans('', '', punctuation)).replace('\\u200b', \" \").strip().lower()", "title": ""}
{"_id": "d5029", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d5030", "text": "def normalize_text(text, line_len=80, indent=\"\"):\n    \"\"\"Wrap the text on the given line length.\"\"\"\n    return \"\\n\".join(\n        textwrap.wrap(\n            text, width=line_len, initial_indent=indent, subsequent_indent=indent\n        )\n    )", "title": ""}
{"_id": "d5031", "text": "def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs):\n    \"\"\"Add plots to an existing plot\"\"\"\n    if LATEX:\n        xl_data = xl[1]  # NOQA\n        yl_data = yl[1]\n    else:\n        xl_data = xl[0]  # NOQA\n        yl_data = yl[0]\n\n    for idx in range(len(y)):\n        ax.plot(x, y[idx], label=yl_data[idx], linestyle=linestyle)\n\n    ax.legend(loc='upper right')\n    ax.set_ylim(auto=True)", "title": ""}
{"_id": "d5032", "text": "def _make_cmd_list(cmd_list):\n    \"\"\"\n    Helper function to easily create the proper json formated string from a list of strs\n    :param cmd_list: list of strings\n    :return: str json formatted\n    \"\"\"\n    cmd = ''\n    for i in cmd_list:\n        cmd = cmd + '\"' + i + '\",'\n    cmd = cmd[:-1]\n    return cmd", "title": ""}
{"_id": "d5033", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d5034", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d5035", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d5036", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d5037", "text": "def get_methods(*objs):\n    \"\"\" Return the names of all callable attributes of an object\"\"\"\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    )", "title": ""}
{"_id": "d5038", "text": "def read(fname):\n    \"\"\"Quick way to read a file content.\"\"\"\n    content = None\n    with open(os.path.join(here, fname)) as f:\n        content = f.read()\n    return content", "title": ""}
{"_id": "d5039", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d5040", "text": "def str_time_to_day_seconds(time):\n    \"\"\"\n    Converts time strings to integer seconds\n    :param time: %H:%M:%S string\n    :return: integer seconds\n    \"\"\"\n    t = str(time).split(':')\n    seconds = int(t[0]) * 3600 + int(t[1]) * 60 + int(t[2])\n    return seconds", "title": ""}
{"_id": "d5041", "text": "def remove_dups(seq):\n    \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d5042", "text": "def poke_array(self, store, name, elemtype, elements, container, visited, _stack):\n        \"\"\"abstract method\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d5043", "text": "def list_get(l, idx, default=None):\n    \"\"\"\n    Get from a list with an optional default value.\n    \"\"\"\n    try:\n        if l[idx]:\n            return l[idx]\n        else:\n            return default\n    except IndexError:\n        return default", "title": ""}
{"_id": "d5044", "text": "def _first_and_last_element(arr):\n    \"\"\"Returns first and last element of numpy array or sparse matrix.\"\"\"\n    if isinstance(arr, np.ndarray) or hasattr(arr, 'data'):\n        # numpy array or sparse matrix with .data attribute\n        data = arr.data if sparse.issparse(arr) else arr\n        return data.flat[0], data.flat[-1]\n    else:\n        # Sparse matrices without .data attribute. Only dok_matrix at\n        # the time of writing, in this case indexing is fast\n        return arr[0, 0], arr[-1, -1]", "title": ""}
{"_id": "d5045", "text": "def cfloat64_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\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')", "title": ""}
{"_id": "d5046", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d5047", "text": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n    \"\"\"\n    Returns the last `n` rows in the table\n    \"\"\"\n    return fetch(dbconn, tablename, n, uuid, end=True)", "title": ""}
{"_id": "d5048", "text": "def keys(self, index=None):\n        \"\"\"Returns a list of keys in the database\n        \"\"\"\n        with self._lmdb.begin() as txn:\n            return [key.decode() for key, _ in txn.cursor()]", "title": ""}
{"_id": "d5049", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d5050", "text": "def load(cls, fname):\n        \"\"\" Loads the dictionary from json file\n        :param fname: file to load from\n        :return: loaded dictionary\n        \"\"\"\n        with open(fname) as f:\n            return Config(**json.load(f))", "title": ""}
{"_id": "d5051", "text": "def show_correlation_matrix(self, correlation_matrix):\n        \"\"\"Shows the given correlation matrix as image\n\n        :param correlation_matrix: Correlation matrix of features\n        \"\"\"\n        cr_plot.create_correlation_matrix_plot(\n            correlation_matrix, self.title, self.headers_to_test\n        )\n        pyplot.show()", "title": ""}
{"_id": "d5052", "text": "def load(self, name):\n        \"\"\"Loads and returns foreign library.\"\"\"\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)", "title": ""}
{"_id": "d5053", "text": "def unpatch(obj, name):\n    \"\"\"\n    Undo the effects of patch(func, obj, name)\n    \"\"\"\n    setattr(obj, name, getattr(obj, name).original)", "title": ""}
{"_id": "d5054", "text": "def load(path):\n    \"\"\"Loads a pushdb maintained in a properties file at the given path.\"\"\"\n    with open(path, 'r') as props:\n      properties = Properties.load(props)\n      return PushDb(properties)", "title": ""}
{"_id": "d5055", "text": "def get_height_for_line(self, lineno):\n        \"\"\"\n        Return the height of the given line.\n        (The height that it would take, if this line became visible.)\n        \"\"\"\n        if self.wrap_lines:\n            return self.ui_content.get_height_for_line(lineno, self.window_width)\n        else:\n            return 1", "title": ""}
{"_id": "d5056", "text": "def load(filename):\n    \"\"\"Load a pickled obj from the filesystem.\n\n    You better know what you expect from the given pickle, because we don't check it.\n\n    Args:\n        filename (str): The filename we load the object from.\n\n    Returns:\n        The object we were able to unpickle, else None.\n    \"\"\"\n    if not os.path.exists(filename):\n        LOG.error(\"load object - File '%s' does not exist.\", filename)\n        return None\n\n    obj = None\n    with open(filename, 'rb') as obj_file:\n        obj = dill.load(obj_file)\n    return obj", "title": ""}
{"_id": "d5057", "text": "def generic_add(a, b):\n    \"\"\"Simple function to add two numbers\"\"\"\n    logger.debug('Called generic_add({}, {})'.format(a, b))\n    return a + b", "title": ""}
{"_id": "d5058", "text": "def graph_from_dot_file(path):\n    \"\"\"Load graph as defined by a DOT file.\n    \n    The file is assumed to be in DOT format. It will\n    be loaded, parsed and a Dot class will be returned, \n    representing the graph.\n    \"\"\"\n    \n    fd = file(path, 'rb')\n    data = fd.read()\n    fd.close()\n    \n    return graph_from_dot_data(data)", "title": ""}
{"_id": "d5059", "text": "def toggle_word_wrap(self):\n        \"\"\"\n        Toggles document word wrap.\n\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        self.setWordWrapMode(not self.wordWrapMode() and QTextOption.WordWrap or QTextOption.NoWrap)\n        return True", "title": ""}
{"_id": "d5060", "text": "async def load_unicode(reader):\n    \"\"\"\n    Loads UTF8 string\n    :param reader:\n    :return:\n    \"\"\"\n    ivalue = await load_uvarint(reader)\n    fvalue = bytearray(ivalue)\n    await reader.areadinto(fvalue)\n    return str(fvalue, 'utf8')", "title": ""}
{"_id": "d5061", "text": "def store_data(data):\n    \"\"\"Use this function to store data in a JSON file.\n\n    This function is used for loading up a JSON file and appending additional\n    data to the JSON file.\n\n    :param data: the data to add to the JSON file.\n    :type data: dict\n    \"\"\"\n    with open(url_json_path) as json_file:\n        try:\n            json_file_data = load(json_file)\n            json_file_data.update(data)\n        except (AttributeError, JSONDecodeError):\n            json_file_data = data\n    with open(url_json_path, 'w') as json_file:\n        dump(json_file_data, json_file, indent=4, sort_keys=True)", "title": ""}
{"_id": "d5062", "text": "def _openResources(self):\n        \"\"\" Uses numpy.load to open the underlying file\n        \"\"\"\n        arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n        check_is_an_array(arr)\n        self._array = arr", "title": ""}
{"_id": "d5063", "text": "def transform(self, df):\n        \"\"\"\n        Transforms a DataFrame in place. Computes all outputs of the DataFrame.\n\n        Args:\n            df (pandas.DataFrame): DataFrame to transform.\n        \"\"\"\n        for name, function in self.outputs:\n            df[name] = function(df)", "title": ""}
{"_id": "d5064", "text": "def load(self, path):\n        \"\"\"Load the pickled model weights.\"\"\"\n        with io.open(path, 'rb') as fin:\n            self.weights = pickle.load(fin)", "title": ""}
{"_id": "d5065", "text": "def _IsDirectory(parent, item):\n  \"\"\"Helper that returns if parent/item is a directory.\"\"\"\n  return tf.io.gfile.isdir(os.path.join(parent, item))", "title": ""}
{"_id": "d5066", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d5067", "text": "def get_average_color(colors):\n    \"\"\"Calculate the average color from the list of colors, where each color\n    is a 3-tuple of (r, g, b) values.\n    \"\"\"\n    c = reduce(color_reducer, colors)\n    total = len(colors)\n    return tuple(v / total for v in c)", "title": ""}
{"_id": "d5068", "text": "def elem_find(self, field, value):\n        \"\"\"\n        Return the indices of elements whose field first satisfies the given values\n\n        ``value`` should be unique in self.field.\n        This function does not check the uniqueness.\n\n        :param field: name of the supplied field\n        :param value: value of field of the elemtn to find\n        :return: idx of the elements\n        :rtype: list, int, float, str\n        \"\"\"\n        if isinstance(value, (int, float, str)):\n            value = [value]\n\n        f = list(self.__dict__[field])\n        uid = np.vectorize(f.index)(value)\n        return self.get_idx(uid)", "title": ""}
{"_id": "d5069", "text": "def camel_case(self, snake_case):\n        \"\"\" Convert snake case to camel case \"\"\"\n        components = snake_case.split('_')\n        return components[0] + \"\".join(x.title() for x in components[1:])", "title": ""}
{"_id": "d5070", "text": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "title": ""}
{"_id": "d5071", "text": "def simple_memoize(callable_object):\n    \"\"\"Simple memoization for functions without keyword arguments.\n\n    This is useful for mapping code objects to module in this context.\n    inspect.getmodule() requires a number of system calls, which may slow down\n    the tracing considerably. Caching the mapping from code objects (there is\n    *one* code object for each function, regardless of how many simultaneous\n    activations records there are).\n\n    In this context we can ignore keyword arguments, but a generic memoizer\n    ought to take care of that as well.\n    \"\"\"\n\n    cache = dict()\n\n    def wrapper(*rest):\n        if rest not in cache:\n            cache[rest] = callable_object(*rest)\n        return cache[rest]\n\n    return wrapper", "title": ""}
{"_id": "d5072", "text": "def buttonUp(self, button=mouse.LEFT):\n        \"\"\" Releases the specified mouse button.\n\n        Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT\n        \"\"\"\n        self._lock.acquire()\n        mouse.release(button)\n        self._lock.release()", "title": ""}
{"_id": "d5073", "text": "def moving_average(array, n=3):\n    \"\"\"\n    Calculates the moving average of an array.\n\n    Parameters\n    ----------\n    array : array\n        The array to have the moving average taken of\n    n : int\n        The number of points of moving average to take\n    \n    Returns\n    -------\n    MovingAverageArray : array\n        The n-point moving average of the input array\n    \"\"\"\n    ret = _np.cumsum(array, dtype=float)\n    ret[n:] = ret[n:] - ret[:-n]\n    return ret[n - 1:] / n", "title": ""}
{"_id": "d5074", "text": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "title": ""}
{"_id": "d5075", "text": "def log_magnitude_spectrum(frames):\n    \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))", "title": ""}
{"_id": "d5076", "text": "def to_str(obj):\n    \"\"\"Attempts to convert given object to a string object\n    \"\"\"\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)", "title": ""}
{"_id": "d5077", "text": "def log_loss(preds, labels):\n    \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n    log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n    return -log_likelihood", "title": ""}
{"_id": "d5078", "text": "def start_of_month(val):\n    \"\"\"\n    Return a new datetime.datetime object with values that represent\n    a start of a month.\n    :param val: Date to ...\n    :type val: datetime.datetime | datetime.date\n    :rtype: datetime.datetime\n    \"\"\"\n    if type(val) == date:\n        val = datetime.fromordinal(val.toordinal())\n    return start_of_day(val).replace(day=1)", "title": ""}
{"_id": "d5079", "text": "def load_config(filename=\"logging.ini\", *args, **kwargs):\n    \"\"\"\n    Load logger config from file\n    \n    Keyword arguments:\n    filename -- configuration filename (Default: \"logging.ini\")\n    *args -- options passed to fileConfig\n    **kwargs -- options passed to fileConfigg\n    \n    \"\"\"\n    logging.config.fileConfig(filename, *args, **kwargs)", "title": ""}
{"_id": "d5080", "text": "def make_stream_handler(graph, formatter):\n    \"\"\"\n    Create the stream handler. Used for console/debug output.\n\n    \"\"\"\n    return {\n        \"class\": graph.config.logging.stream_handler.class_,\n        \"formatter\": formatter,\n        \"level\": graph.config.logging.level,\n        \"stream\": graph.config.logging.stream_handler.stream,\n    }", "title": ""}
{"_id": "d5081", "text": "def logger(message, level=10):\n    \"\"\"Handle logging.\"\"\"\n    logging.getLogger(__name__).log(level, str(message))", "title": ""}
{"_id": "d5082", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d5083", "text": "def GetLoggingLocation():\n  \"\"\"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.\n  \"\"\"\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)", "title": ""}
{"_id": "d5084", "text": "def intToBin(i):\n    \"\"\" Integer to two bytes \"\"\"\n    # devide in two parts (bytes)\n    i1 = i % 256\n    i2 = int(i / 256)\n    # make string (little endian)\n    return chr(i1) + chr(i2)", "title": ""}
{"_id": "d5085", "text": "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d5086", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d5087", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d5088", "text": "def QA_util_datetime_to_strdate(dt):\n    \"\"\"\n    :param dt:  pythone datetime.datetime\n    :return:  1999-02-01 string type\n    \"\"\"\n    strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n    return strdate", "title": ""}
{"_id": "d5089", "text": "def timed_rotating_file_handler(name, logname, filename, when='h',\n                                interval=1, backupCount=0,\n                                encoding=None, delay=False, utc=False):\n    \"\"\"\n    A Bark logging handler logging output to a named file.  At\n    intervals specified by the 'when', the file will be rotated, under\n    control of 'backupCount'.\n\n    Similar to logging.handlers.TimedRotatingFileHandler.\n    \"\"\"\n\n    return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n        filename, when=when, interval=interval, backupCount=backupCount,\n        encoding=encoding, delay=delay, utc=utc))", "title": ""}
{"_id": "d5090", "text": "def _set_axis_limits(self, which, lims, d, scale, reverse=False):\n        \"\"\"Private method for setting axis limits.\n\n        Sets the axis limits on each axis for an individual plot.\n\n        Args:\n            which (str): The indicator of which part of the plots\n                to adjust. This currently handles `x` and `y`.\n            lims (len-2 list of floats): The limits for the axis.\n            d (float): Amount to increment by between the limits.\n            scale (str): Scale of the axis. Either `log` or `lin`.\n            reverse (bool, optional): If True, reverse the axis tick marks. Default is False.\n\n        \"\"\"\n        setattr(self.limits, which + 'lims', lims)\n        setattr(self.limits, 'd' + which, d)\n        setattr(self.limits, which + 'scale', scale)\n\n        if reverse:\n            setattr(self.limits, 'reverse_' + which + '_axis', True)\n        return", "title": ""}
{"_id": "d5091", "text": "def longest_run(da, dim='time'):\n    \"\"\"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\n        \"\"\"\n\n    d = rle(da, dim=dim)\n    rl_long = d.max(dim=dim)\n\n    return rl_long", "title": ""}
{"_id": "d5092", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d5093", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d5094", "text": "def skip(self, n):\n        \"\"\"Skip the specified number of elements in the list.\n\n        If the number skipped is greater than the number of elements in\n        the list, hasNext() becomes false and available() returns zero\n        as there are no more elements to retrieve.\n\n        arg:    n (cardinal): the number of elements to skip\n        *compliance: mandatory -- This method must be implemented.*\n\n        \"\"\"\n        try:\n            self._iter_object.skip(n)\n        except AttributeError:\n            for i in range(0, n):\n                self.next()", "title": ""}
{"_id": "d5095", "text": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "title": ""}
{"_id": "d5096", "text": "def osx_clipboard_get():\n    \"\"\" Get the clipboard's text on OS X.\n    \"\"\"\n    p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n        stdout=subprocess.PIPE)\n    text, stderr = p.communicate()\n    # Text comes in with old Mac \\r line endings. Change them to \\n.\n    text = text.replace('\\r', '\\n')\n    return text", "title": ""}
{"_id": "d5097", "text": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Like `pretty` but print to stdout.\n    \"\"\"\n    printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    sys.stdout.write(newline)\n    sys.stdout.flush()", "title": ""}
{"_id": "d5098", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d5099", "text": "def ansi(color, text):\n    \"\"\"Wrap text in an ansi escape sequence\"\"\"\n    code = COLOR_CODES[color]\n    return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)", "title": ""}
{"_id": "d5100", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d5101", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d5102", "text": "def fopenat(base_fd, path):\n    \"\"\"\n    Does openat read-only, then does fdopen to get a file object\n    \"\"\"\n\n    return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')", "title": ""}
{"_id": "d5103", "text": "def colorize(string, color, *args, **kwargs):\n    \"\"\"\n    Implements string formatting along with color specified in colorama.Fore\n    \"\"\"\n    string = string.format(*args, **kwargs)\n    return color + string + colorama.Fore.RESET", "title": ""}
{"_id": "d5104", "text": "def unpickle_stats(stats):\n    \"\"\"Unpickle a pstats.Stats object\"\"\"\n    stats = cPickle.loads(stats)\n    stats.stream = True\n    return stats", "title": ""}
{"_id": "d5105", "text": "def set_executable(filename):\n    \"\"\"Set the exectuable bit on the given filename\"\"\"\n    st = os.stat(filename)\n    os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d5106", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d5107", "text": "def col_rename(df,col_name,new_col_name):\n    \"\"\" Changes a column name in a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_name - string\n        Name of column to change\n    new_col_name - string\n        New name of column\n    \"\"\"\n    col_list = list(df.columns)\n    for index,value in enumerate(col_list):\n        if value == col_name:\n            col_list[index] = new_col_name\n            break\n    df.columns = col_list", "title": ""}
{"_id": "d5108", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d5109", "text": "def title(msg):\n    \"\"\"Sets the title of the console window.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "title": ""}
{"_id": "d5110", "text": "def create_search_url(self):\n        \"\"\" Generates (urlencoded) query string from stored key-values tuples\n\n        :returns: A string containing all arguments in a url-encoded format\n        \"\"\"\n\n        url = '?'\n        for key, value in self.arguments.items():\n            url += '%s=%s&' % (quote_plus(key), quote_plus(value))\n        self.url = url[:-1]\n        return self.url", "title": ""}
{"_id": "d5111", "text": "def append_user_agent(self, user_agent):\n        \"\"\"Append text to the User-Agent header for the request.\n\n        Use this method to update the User-Agent header by appending the\n        given string to the session's User-Agent header separated by a space.\n\n        :param user_agent: A string to append to the User-Agent header\n        :type user_agent: str\n        \"\"\"\n        old_ua = self.session.headers.get('User-Agent', '')\n        ua = old_ua + ' ' + user_agent\n        self.session.headers['User-Agent'] = ua.strip()", "title": ""}
{"_id": "d5112", "text": "def makedirs(path):\n    \"\"\"\n    Create directories if they do not exist, otherwise do nothing.\n\n    Return path for convenience\n    \"\"\"\n    if not os.path.isdir(path):\n        os.makedirs(path)\n    return path", "title": ""}
{"_id": "d5113", "text": "def str2int(string_with_int):\n    \"\"\" Collect digits from a string \"\"\"\n    return int(\"\".join([char for char in string_with_int if char in string.digits]) or 0)", "title": ""}
{"_id": "d5114", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d5115", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d5116", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d5117", "text": "def _validate_pos(df):\n    \"\"\"Validates the returned positional object\n    \"\"\"\n    assert isinstance(df, pd.DataFrame)\n    assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n    assert df.position.dtype == np.dtype(\"int64\")\n    assert df.strand.dtype == np.dtype(\"O\")\n    assert df.seqname.dtype == np.dtype(\"O\")\n    return df", "title": ""}
{"_id": "d5118", "text": "def server(port):\n    \"\"\"Start the Django dev server.\"\"\"\n    args = ['python', 'manage.py', 'runserver']\n    if port:\n        args.append(port)\n    run.main(args)", "title": ""}
{"_id": "d5119", "text": "def check(modname):\n    \"\"\"Check if required dependency is installed\"\"\"\n    for dependency in DEPENDENCIES:\n        if dependency.modname == modname:\n            return dependency.check()\n    else:\n        raise RuntimeError(\"Unkwown dependency %s\" % modname)", "title": ""}
{"_id": "d5120", "text": "def server(port):\n    \"\"\"Start the Django dev server.\"\"\"\n    args = ['python', 'manage.py', 'runserver']\n    if port:\n        args.append(port)\n    run.main(args)", "title": ""}
{"_id": "d5121", "text": "def check(modname):\n    \"\"\"Check if required dependency is installed\"\"\"\n    for dependency in DEPENDENCIES:\n        if dependency.modname == modname:\n            return dependency.check()\n    else:\n        raise RuntimeError(\"Unkwown dependency %s\" % modname)", "title": ""}
{"_id": "d5122", "text": "def generate_dumper(self, mapfile, names):\n        \"\"\"\n        Build dumpdata commands\n        \"\"\"\n        return self.build_template(mapfile, names, self._dumpdata_template)", "title": ""}
{"_id": "d5123", "text": "def health_check(self):\n        \"\"\"Uses head object to make sure the file exists in S3.\"\"\"\n        logger.debug('Health Check on S3 file for: {namespace}'.format(\n            namespace=self.namespace\n        ))\n\n        try:\n            self.client.head_object(Bucket=self.bucket_name, Key=self.data_file)\n            return True\n        except ClientError as e:\n            logger.debug('Error encountered with S3.  Assume unhealthy')", "title": ""}
{"_id": "d5124", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d5125", "text": "def str2int(string_with_int):\n    \"\"\" Collect digits from a string \"\"\"\n    return int(\"\".join([char for char in string_with_int if char in string.digits]) or 0)", "title": ""}
{"_id": "d5126", "text": "def colorbar(height, length, colormap):\n    \"\"\"Return the channels of a colorbar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.colorize(cbar)", "title": ""}
{"_id": "d5127", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d5128", "text": "def finish_plot():\n    \"\"\"Helper for plotting.\"\"\"\n    plt.legend()\n    plt.grid(color='0.7')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.show()", "title": ""}
{"_id": "d5129", "text": "def init_checks_registry():\n    \"\"\"Register all globally visible functions.\n\n    The first argument name is either 'physical_line' or 'logical_line'.\n    \"\"\"\n    mod = inspect.getmodule(register_check)\n    for (name, function) in inspect.getmembers(mod, inspect.isfunction):\n        register_check(function)", "title": ""}
{"_id": "d5130", "text": "def fig2x(figure, format):\n    \"\"\"Returns svg from matplotlib chart\"\"\"\n\n    # Save svg to file like object svg_io\n    io = StringIO()\n    figure.savefig(io, format=format)\n\n    # Rewind the file like object\n    io.seek(0)\n\n    data = io.getvalue()\n    io.close()\n\n    return data", "title": ""}
{"_id": "d5131", "text": "def check_git():\n    \"\"\"Check if git command is available.\"\"\"\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.\")", "title": ""}
{"_id": "d5132", "text": "def plot_and_save(self, **kwargs):\n        \"\"\"Used when the plot method defined does not create a figure nor calls save_plot\n        Then the plot method has to use self.fig\"\"\"\n        self.fig = pyplot.figure()\n        self.plot()\n        self.axes = pyplot.gca()\n        self.save_plot(self.fig, self.axes, **kwargs)\n        pyplot.close(self.fig)", "title": ""}
{"_id": "d5133", "text": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "title": ""}
{"_id": "d5134", "text": "def set_title(self, title, **kwargs):\n        \"\"\"Sets the title on the underlying matplotlib AxesSubplot.\"\"\"\n        ax = self.get_axes()\n        ax.set_title(title, **kwargs)", "title": ""}
{"_id": "d5135", "text": "def _file_exists(path, filename):\n  \"\"\"Checks if the filename exists under the path.\"\"\"\n  return os.path.isfile(os.path.join(path, filename))", "title": ""}
{"_id": "d5136", "text": "def maxlevel(lst):\n    \"\"\"Return maximum nesting depth\"\"\"\n    maxlev = 0\n    def f(lst, level):\n        nonlocal maxlev\n        if isinstance(lst, list):\n            level += 1\n            maxlev = max(level, maxlev)\n            for item in lst:\n                f(item, level)\n    f(lst, 0)\n    return maxlev", "title": ""}
{"_id": "d5137", "text": "def allsame(list_, strict=True):\n    \"\"\"\n    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\n    \"\"\"\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)", "title": ""}
{"_id": "d5138", "text": "def peak_memory_usage():\n    \"\"\"Return peak memory usage in MB\"\"\"\n    if sys.platform.startswith('win'):\n        p = psutil.Process()\n        return p.memory_info().peak_wset / 1024 / 1024\n\n    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n    factor_mb = 1 / 1024\n    if sys.platform == 'darwin':\n        factor_mb = 1 / (1024 * 1024)\n    return mem * factor_mb", "title": ""}
{"_id": "d5139", "text": "def is_clicked(self, MouseStateType):\n        \"\"\"\n        Did the user depress and release the button to signify a click?\n        MouseStateType is the button to query. Values found under StateTypes.py\n        \"\"\"\n        return self.previous_mouse_state.query_state(MouseStateType) and (\n        not self.current_mouse_state.query_state(MouseStateType))", "title": ""}
{"_id": "d5140", "text": "def listunion(ListOfLists):\n    \"\"\"\n    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`.\n\n    \"\"\"\n    u = []\n    for s in ListOfLists:\n        if s != None:\n            u.extend(s)\n    return u", "title": ""}
{"_id": "d5141", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d5142", "text": "def merge(self, other):\n        \"\"\" Merge another stats. \"\"\"\n        Stats.merge(self, other)\n        self.changes += other.changes", "title": ""}
{"_id": "d5143", "text": "def _check_for_duplicate_sequence_names(self, fasta_file_path):\n        \"\"\"Test if the given fasta file contains sequences with duplicate\n        sequence names.\n\n        Parameters\n        ----------\n        fasta_file_path: string\n            path to file that is to be checked\n\n        Returns\n        -------\n        The name of the first duplicate sequence found, else False.\n\n        \"\"\"\n        found_sequence_names = set()\n        for record in SeqIO.parse(fasta_file_path, 'fasta'):\n            name = record.name\n            if name in found_sequence_names:\n                return name\n            found_sequence_names.add(name)\n        return False", "title": ""}
{"_id": "d5144", "text": "def dict_merge(set1, set2):\n    \"\"\"Joins two dictionaries.\"\"\"\n    return dict(list(set1.items()) + list(set2.items()))", "title": ""}
{"_id": "d5145", "text": "def is_callable(*p):\n    \"\"\" True if all the args are functions and / or subroutines\n    \"\"\"\n    import symbols\n    return all(isinstance(x, symbols.FUNCTION) for x in p)", "title": ""}
{"_id": "d5146", "text": "def _get_minidom_tag_value(station, tag_name):\n    \"\"\"get a value from a tag (if it exists)\"\"\"\n    tag = station.getElementsByTagName(tag_name)[0].firstChild\n    if tag:\n        return tag.nodeValue\n\n    return None", "title": ""}
{"_id": "d5147", "text": "def is_symlink(self):\n        \"\"\"\n        Whether this path is a symbolic link.\n        \"\"\"\n        try:\n            return S_ISLNK(self.lstat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            # Path doesn't exist\n            return False", "title": ""}
{"_id": "d5148", "text": "def makedirs(path, mode=0o777, exist_ok=False):\n    \"\"\"A wrapper of os.makedirs().\"\"\"\n    os.makedirs(path, mode, exist_ok)", "title": ""}
{"_id": "d5149", "text": "def is_json_file(filename, show_warnings = False):\n    \"\"\"Check configuration file type is JSON\n    Return a boolean indicating wheather the file is JSON format or not\n    \"\"\"\n    try:\n        config_dict = load_config(filename, file_type = \"json\")\n        is_json = True\n    except:\n        is_json = False\n    return(is_json)", "title": ""}
{"_id": "d5150", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d5151", "text": "def __contains__(self, key):\n        \"\"\"\n        Invoked when determining whether a specific key is in the dictionary\n        using `key in d`.\n\n        The key is looked up case-insensitively.\n        \"\"\"\n        k = self._real_key(key)\n        return k in self._data", "title": ""}
{"_id": "d5152", "text": "def alter_change_column(self, table, column, field):\n        \"\"\"Support change columns.\"\"\"\n        return self._update_column(table, column, lambda a, b: b)", "title": ""}
{"_id": "d5153", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d5154", "text": "def update_loan_entry(database, entry):\n    \"\"\"Update a record of a loan report in the provided database.\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 entry: The entry to insert into the database, updating the entry with\n        the same recordID if one exists.\n    @type entry: dict\n    \"\"\"\n    entry = clean_entry(entry)\n    database.loans.update(\n        {'recordID': entry['recordID']},\n        {'$set': entry},\n        upsert=True\n    )", "title": ""}
{"_id": "d5155", "text": "def ffmpeg_works():\n  \"\"\"Tries to encode images with ffmpeg to check if it 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", "title": ""}
{"_id": "d5156", "text": "def json_obj_to_cursor(self, json):\n        \"\"\"(Deprecated) Converts a JSON object to a mongo db cursor\n\n        :param str json: A json string\n        :returns: dictionary with ObjectId type\n        :rtype: dict\n        \"\"\"\n        cursor = json_util.loads(json)\n        if \"id\" in json:\n            cursor[\"_id\"] = ObjectId(cursor[\"id\"])\n            del cursor[\"id\"]\n\n        return cursor", "title": ""}
{"_id": "d5157", "text": "def column_exists(cr, table, column):\n    \"\"\" Check whether a certain column exists \"\"\"\n    cr.execute(\n        'SELECT count(attname) FROM pg_attribute '\n        'WHERE attrelid = '\n        '( SELECT oid FROM pg_class WHERE relname = %s ) '\n        'AND attname = %s',\n        (table, column))\n    return cr.fetchone()[0] == 1", "title": ""}
{"_id": "d5158", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d5159", "text": "def check_permission_safety(path):\n    \"\"\"Check if the file at the given path is safe to use as a state file.\n\n    This checks that group and others have no permissions on the file and that the current user is\n    the owner.\n    \"\"\"\n    f_stats = os.stat(path)\n    return (f_stats.st_mode & (stat.S_IRWXG | stat.S_IRWXO)) == 0 and f_stats.st_uid == os.getuid()", "title": ""}
{"_id": "d5160", "text": "def _go_to_line(editor, line):\n    \"\"\"\n    Move cursor to this line in the current buffer.\n    \"\"\"\n    b = editor.application.current_buffer\n    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "title": ""}
{"_id": "d5161", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d5162", "text": "def move_up(lines=1, file=sys.stdout):\n    \"\"\" Move the cursor up a number of lines.\n\n        Esc[ValueA:\n        Moves the cursor up by the specified number of lines without changing\n        columns. If the cursor is already on the top line, ANSI.SYS ignores\n        this sequence.\n    \"\"\"\n    move.up(lines).write(file=file)", "title": ""}
{"_id": "d5163", "text": "def erase(self):\n        \"\"\"White out the progress bar.\"\"\"\n        with self._at_last_line():\n            self.stream.write(self._term.clear_eol)\n        self.stream.flush()", "title": ""}
{"_id": "d5164", "text": "def set_cursor(self, x, y):\n        \"\"\"\n        Sets the cursor to the desired position.\n\n        :param x: X position\n        :param y: Y position\n        \"\"\"\n        curses.curs_set(1)\n        self.screen.move(y, x)", "title": ""}
{"_id": "d5165", "text": "def __clear_buffers(self):\n        \"\"\"Clears the input and output buffers\"\"\"\n        try:\n            self._port.reset_input_buffer()\n            self._port.reset_output_buffer()\n        except AttributeError:\n            #pySerial 2.7\n            self._port.flushInput()\n            self._port.flushOutput()", "title": ""}
{"_id": "d5166", "text": "def moving_average(array, n=3):\n    \"\"\"\n    Calculates the moving average of an array.\n\n    Parameters\n    ----------\n    array : array\n        The array to have the moving average taken of\n    n : int\n        The number of points of moving average to take\n    \n    Returns\n    -------\n    MovingAverageArray : array\n        The n-point moving average of the input array\n    \"\"\"\n    ret = _np.cumsum(array, dtype=float)\n    ret[n:] = ret[n:] - ret[:-n]\n    return ret[n - 1:] / n", "title": ""}
{"_id": "d5167", "text": "def __clear_buffers(self):\n        \"\"\"Clears the input and output buffers\"\"\"\n        try:\n            self._port.reset_input_buffer()\n            self._port.reset_output_buffer()\n        except AttributeError:\n            #pySerial 2.7\n            self._port.flushInput()\n            self._port.flushOutput()", "title": ""}
{"_id": "d5168", "text": "def list(self):\n        \"\"\"position in 3d space\"\"\"\n        return [self._pos3d.x, self._pos3d.y, self._pos3d.z]", "title": ""}
{"_id": "d5169", "text": "def clear(self):\n        \"\"\"Clear the displayed image.\"\"\"\n        self._imgobj = None\n        try:\n            # See if there is an image on the canvas\n            self.canvas.delete_object_by_tag(self._canvas_img_tag)\n            self.redraw()\n        except KeyError:\n            pass", "title": ""}
{"_id": "d5170", "text": "def map(cls, iterable, func, *a, **kw):\n    \"\"\"\n    Iterable-first replacement of Python's built-in `map()` function.\n    \"\"\"\n\n    return cls(func(x, *a, **kw) for x in iterable)", "title": ""}
{"_id": "d5171", "text": "def cio_close(cio):\n    \"\"\"Wraps openjpeg library function cio_close.\n    \"\"\"\n    OPENJPEG.opj_cio_close.argtypes = [ctypes.POINTER(CioType)]\n    OPENJPEG.opj_cio_close(cio)", "title": ""}
{"_id": "d5172", "text": "async def result_processor(tasks):\n    \"\"\"An async result aggregator that combines all the results\n       This gets executed in unsync.loop and unsync.thread\"\"\"\n    output = {}\n    for task in tasks:\n        num, res = await task\n        output[num] = res\n    return output", "title": ""}
{"_id": "d5173", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d5174", "text": "def _parallel_compare_helper(class_obj, pairs, x, x_link=None):\n    \"\"\"Internal function to overcome pickling problem in python2.\"\"\"\n    return class_obj._compute(pairs, x, x_link)", "title": ""}
{"_id": "d5175", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d5176", "text": "def compute_partition_size(result, processes):\n    \"\"\"\n    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\n    \"\"\"\n    try:\n        return max(math.ceil(len(result) / processes), 1)\n    except TypeError:\n        return 1", "title": ""}
{"_id": "d5177", "text": "def __iadd__(self, other_model):\n        \"\"\"Incrementally add the content of another model to this model (+=).\n\n        Copies of all the reactions in the other model are added to this\n        model. The objective is the sum of the objective expressions for the\n        two models.\n        \"\"\"\n        warn('use model.merge instead', DeprecationWarning)\n        return self.merge(other_model, objective='sum', inplace=True)", "title": ""}
{"_id": "d5178", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d5179", "text": "def compare(a, b):\n    \"\"\"\n     Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))\n    \"\"\"\n    s=0\n    for i in range(len(a)):\n        s=s+abs(a[i]-b[i])\n    return s", "title": ""}
{"_id": "d5180", "text": "def machine_info():\n    \"\"\"Retrieve core and memory information for the current machine.\n    \"\"\"\n    import psutil\n    BYTES_IN_GIG = 1073741824.0\n    free_bytes = psutil.virtual_memory().total\n    return [{\"memory\": float(\"%.1f\" % (free_bytes / BYTES_IN_GIG)), \"cores\": multiprocessing.cpu_count(),\n             \"name\": socket.gethostname()}]", "title": ""}
{"_id": "d5181", "text": "def is_value_type_valid_for_exact_conditions(self, value):\n    \"\"\" Method to validate if the value is valid for exact match type evaluation.\n\n    Args:\n      value: Value to validate.\n\n    Returns:\n      Boolean: True if value is a string, boolean, or number. Otherwise False.\n    \"\"\"\n    # No need to check for bool since bool is a subclass of int\n    if isinstance(value, string_types) or isinstance(value, (numbers.Integral, float)):\n      return True\n\n    return False", "title": ""}
{"_id": "d5182", "text": "def _parallel_compare_helper(class_obj, pairs, x, x_link=None):\n    \"\"\"Internal function to overcome pickling problem in python2.\"\"\"\n    return class_obj._compute(pairs, x, x_link)", "title": ""}
{"_id": "d5183", "text": "def __eq__(self, other):\n        \"\"\"Determine if two objects are equal.\"\"\"\n        return isinstance(other, self.__class__) \\\n            and self._freeze() == other._freeze()", "title": ""}
{"_id": "d5184", "text": "def _root(self):\n        \"\"\"Attribute referencing the root node of the tree.\n\n        :returns: the root node of the tree containing this instance.\n        :rtype: Node\n        \"\"\"\n        _n = self\n        while _n.parent:\n            _n = _n.parent\n        return _n", "title": ""}
{"_id": "d5185", "text": "def pair_strings_sum_formatter(a, b):\n  \"\"\"\n  Formats the sum of a and b.\n\n  Note\n  ----\n  Both inputs are numbers already converted to strings.\n\n  \"\"\"\n  if b[:1] == \"-\":\n    return \"{0} - {1}\".format(a, b[1:])\n  return \"{0} + {1}\".format(a, b)", "title": ""}
{"_id": "d5186", "text": "def drop_all_tables(self):\n        \"\"\"Drop all tables in the database\"\"\"\n        for table_name in self.table_names():\n            self.execute_sql(\"DROP TABLE %s\" % table_name)\n        self.connection.commit()", "title": ""}
{"_id": "d5187", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d5188", "text": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "title": ""}
{"_id": "d5189", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d5190", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d5191", "text": "def paste(xsel=False):\n    \"\"\"Returns system clipboard contents.\"\"\"\n    selection = \"primary\" if xsel else \"clipboard\"\n    try:\n        return subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"utf-8\")\n    except OSError as why:\n        raise XclipNotFound", "title": ""}
{"_id": "d5192", "text": "def Cinv(self):\n        \"\"\"Inverse of the noise covariance.\"\"\"\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])", "title": ""}
{"_id": "d5193", "text": "def copyFile(input, output, replace=None):\n    \"\"\"Copy a file whole from input to output.\"\"\"\n\n    _found = findFile(output)\n    if not _found or (_found and replace):\n        shutil.copy2(input, output)", "title": ""}
{"_id": "d5194", "text": "def _method_scope(input_layer, name):\n  \"\"\"Creates a nested set of name and id scopes and avoids repeats.\"\"\"\n  global _in_method_scope\n  # pylint: disable=protected-access\n\n  with input_layer.g.as_default(), \\\n       scopes.var_and_name_scope(\n           None if _in_method_scope else input_layer._scope), \\\n       scopes.var_and_name_scope((name, None)) as (scope, var_scope):\n    was_in_method_scope = _in_method_scope\n    yield scope, var_scope\n    _in_method_scope = was_in_method_scope", "title": ""}
{"_id": "d5195", "text": "def arr_to_vector(arr):\n    \"\"\"Reshape a multidimensional array to a vector.\n    \"\"\"\n    dim = array_dim(arr)\n    tmp_arr = []\n    for n in range(len(dim) - 1):\n        for inner in arr:\n            for i in inner:\n                tmp_arr.append(i)\n        arr = tmp_arr\n        tmp_arr = []\n    return arr", "title": ""}
{"_id": "d5196", "text": "def is_serializable(obj):\n    \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool\n    \"\"\"\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')", "title": ""}
{"_id": "d5197", "text": "def line_count(fn):\n    \"\"\" Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)\n    \"\"\"\n\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "title": ""}
{"_id": "d5198", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d5199", "text": "def num_leaves(tree):\n    \"\"\"Determine the number of leaves in a tree\"\"\"\n    if tree.is_leaf:\n        return 1\n    else:\n        return num_leaves(tree.left_child) + num_leaves(tree.right_child)", "title": ""}
{"_id": "d5200", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d5201", "text": "def objectcount(data, key):\n    \"\"\"return the count of objects of key\"\"\"\n    objkey = key.upper()\n    return len(data.dt[objkey])", "title": ""}
{"_id": "d5202", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d5203", "text": "def line_count(fn):\n    \"\"\" Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)\n    \"\"\"\n\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "title": ""}
{"_id": "d5204", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d5205", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d5206", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d5207", "text": "def Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c=\"dg\", alpha=1):\n    \"\"\"\n    Build a pyramid of specified base size `s` and `height`, centered at `pos`.\n    \"\"\"\n    return Cone(pos, s, height, axis, c, alpha, 4)", "title": ""}
{"_id": "d5208", "text": "def test(nose_argsuments):\n    \"\"\" Run application tests \"\"\"\n    from nose import run\n\n    params = ['__main__', '-c', 'nose.ini']\n    params.extend(nose_argsuments)\n    run(argv=params)", "title": ""}
{"_id": "d5209", "text": "def symlink(source, destination):\n    \"\"\"Create a symbolic link\"\"\"\n    log(\"Symlinking {} as {}\".format(source, destination))\n    cmd = [\n        'ln',\n        '-sf',\n        source,\n        destination,\n    ]\n    subprocess.check_call(cmd)", "title": ""}
{"_id": "d5210", "text": "def run(self):\n        \"\"\"\n        Runs the unit test framework. Can be overridden to run anything.\n        Returns True on passing and False on failure.\n        \"\"\"\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", "title": ""}
{"_id": "d5211", "text": "def get_wordnet_syns(word):\n    \"\"\"\n    Utilize wordnet (installed with nltk) to get synonyms for words\n    word is the input word\n    returns a list of unique synonyms\n    \"\"\"\n    synonyms = []\n    regex = r\"_\"\n    pat = re.compile(regex)\n    synset = nltk.wordnet.wordnet.synsets(word)\n    for ss in synset:\n        for swords in ss.lemma_names:\n            synonyms.append(pat.sub(\" \", swords.lower()))\n    synonyms = f7(synonyms)\n    return synonyms", "title": ""}
{"_id": "d5212", "text": "def log_loss(preds, labels):\n    \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n    log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n    return -log_likelihood", "title": ""}
{"_id": "d5213", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d5214", "text": "def gday_of_year(self):\n        \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n        return (self.date - dt.date(self.date.year, 1, 1)).days", "title": ""}
{"_id": "d5215", "text": "def vals2bins(vals,res=100):\n    \"\"\"Maps values to bins\n    Args:\n    values (list or list of lists) - list of values to map to colors\n    res (int) - resolution of the color map (default: 100)\n    Returns:\n    list of numbers representing bins\n    \"\"\"\n    # flatten if list of lists\n    if any(isinstance(el, list) for el in vals):\n        vals = list(itertools.chain(*vals))\n    return list(np.digitize(vals, np.linspace(np.min(vals), np.max(vals)+1, res+1)) - 1)", "title": ""}
{"_id": "d5216", "text": "def gday_of_year(self):\n        \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n        return (self.date - dt.date(self.date.year, 1, 1)).days", "title": ""}
{"_id": "d5217", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d5218", "text": "def count_rows_with_nans(X):\n    \"\"\"Count the number of rows in 2D arrays that contain any nan values.\"\"\"\n    if X.ndim == 2:\n        return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()", "title": ""}
{"_id": "d5219", "text": "def from_dict(cls, d):\n        \"\"\"Create an instance from a dictionary.\"\"\"\n        return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})", "title": ""}
{"_id": "d5220", "text": "def count(data, axis=None):\n    \"\"\"Count the number of non-NA in this array along the given axis or axes\n    \"\"\"\n    return np.sum(np.logical_not(isnull(data)), axis=axis)", "title": ""}
{"_id": "d5221", "text": "def _decode_request(self, encoded_request):\n        \"\"\"Decode an request previously encoded\"\"\"\n        obj = self.serializer.loads(encoded_request)\n        return request_from_dict(obj, self.spider)", "title": ""}
{"_id": "d5222", "text": "def unit_vector(x):\n    \"\"\"Return a unit vector in the same direction as x.\"\"\"\n    y = np.array(x, dtype='float')\n    return y/norm(y)", "title": ""}
{"_id": "d5223", "text": "def disassemble_file(filename, outstream=None):\n    \"\"\"\n    disassemble Python byte-code file (.pyc)\n\n    If given a Python source file (\".py\") file, we'll\n    try to find the corresponding compiled object.\n    \"\"\"\n    filename = check_object_path(filename)\n    (version, timestamp, magic_int, co, is_pypy,\n     source_size) = load_module(filename)\n    if type(co) == list:\n        for con in co:\n            disco(version, con, outstream)\n    else:\n        disco(version, co, outstream, is_pypy=is_pypy)\n    co = None", "title": ""}
{"_id": "d5224", "text": "def img_encode(arr, **kwargs):\n    \"\"\"Encode ndarray to base64 string image data\n    \n    Parameters\n    ----------\n    arr: ndarray (rows, cols, depth)\n    kwargs: passed directly to matplotlib.image.imsave\n    \"\"\"\n    sio = BytesIO()\n    imsave(sio, arr, **kwargs)\n    sio.seek(0)\n    img_format = kwargs['format'] if kwargs.get('format') else 'png'\n    img_str = base64.b64encode(sio.getvalue()).decode()\n\n    return 'data:image/{};base64,{}'.format(img_format, img_str)", "title": ""}
{"_id": "d5225", "text": "def register_type(cls, name):\n    \"\"\"Register `name` as a type to validate as an instance of class `cls`.\"\"\"\n    x = TypeDefinition(name, (cls,), ())\n    Validator.types_mapping[name] = x", "title": ""}
{"_id": "d5226", "text": "def pairwise_indices(self):\n        \"\"\"ndarray containing tuples of pairwise indices.\"\"\"\n        return np.array([sig.pairwise_indices for sig in self.values]).T", "title": ""}
{"_id": "d5227", "text": "def printmp(msg):\n    \"\"\"Print temporarily, until next print overrides it.\n    \"\"\"\n    filler = (80 - len(msg)) * ' '\n    print(msg + filler, end='\\r')\n    sys.stdout.flush()", "title": ""}
{"_id": "d5228", "text": "def _numpy_bytes_to_char(arr):\n    \"\"\"Like netCDF4.stringtochar, but faster and more flexible.\n    \"\"\"\n    # ensure the array is contiguous\n    arr = np.array(arr, copy=False, order='C', dtype=np.string_)\n    return arr.reshape(arr.shape + (1,)).view('S1')", "title": ""}
{"_id": "d5229", "text": "def delete(self, row):\n        \"\"\"Delete a track value\"\"\"\n        i = self._get_key_index(row)\n        del self.keys[i]", "title": ""}
{"_id": "d5230", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d5231", "text": "def cli(env, identifier):\n    \"\"\"Delete an image.\"\"\"\n\n    image_mgr = SoftLayer.ImageManager(env.client)\n    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')\n\n    image_mgr.delete_image(image_id)", "title": ""}
{"_id": "d5232", "text": "def contains_all(self, array):\n        \"\"\"Test if `array` is an array of real numbers.\"\"\"\n        dtype = getattr(array, 'dtype', None)\n        if dtype is None:\n            dtype = np.result_type(*array)\n        return is_real_dtype(dtype)", "title": ""}
{"_id": "d5233", "text": "def _sanitize(text):\n    \"\"\"Return sanitized Eidos text field for human readability.\"\"\"\n    d = {'-LRB-': '(', '-RRB-': ')'}\n    return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text)", "title": ""}
{"_id": "d5234", "text": "def movingaverage(arr, window):\n    \"\"\"\n    Calculates the moving average (\"rolling mean\") of an array\n    of a certain window size.\n    \"\"\"\n    m = np.ones(int(window)) / int(window)\n    return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')", "title": ""}
{"_id": "d5235", "text": "def deprecate(func):\n  \"\"\" A deprecation warning emmiter as a decorator. \"\"\"\n  @wraps(func)\n  def wrapper(*args, **kwargs):\n    warn(\"Deprecated, this will be removed in the future\", DeprecationWarning)\n    return func(*args, **kwargs)\n  wrapper.__doc__ = \"Deprecated.\\n\" + (wrapper.__doc__ or \"\")\n  return wrapper", "title": ""}
{"_id": "d5236", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d5237", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d5238", "text": "def datetime64_to_datetime(dt):\n    \"\"\" convert numpy's datetime64 to datetime \"\"\"\n    dt64 = np.datetime64(dt)\n    ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')\n    return datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d5239", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d5240", "text": "def normalize(v, axis=None, eps=1e-10):\n  \"\"\"L2 Normalize along specified axes.\"\"\"\n  return v / max(anorm(v, axis=axis, keepdims=True), eps)", "title": ""}
{"_id": "d5241", "text": "def find_start_point(self):\n        \"\"\"\n        Find the first location in our array that is not empty\n        \"\"\"\n        for i, row in enumerate(self.data):\n            for j, _ in enumerate(row):\n                if self.data[i, j] != 0:  # or not np.isfinite(self.data[i,j]):\n                    return i, j", "title": ""}
{"_id": "d5242", "text": "def read_mm_header(fd, byte_order, dtype, count):\n    \"\"\"Read MM_HEADER tag from file and return as numpy.rec.array.\"\"\"\n    return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0]", "title": ""}
{"_id": "d5243", "text": "def as_html(self):\n        \"\"\"Generate HTML to display map.\"\"\"\n        if not self._folium_map:\n            self.draw()\n        return self._inline_map(self._folium_map, self._width, self._height)", "title": ""}
{"_id": "d5244", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d5245", "text": "def IsBinary(self, filename):\n\t\t\"\"\"Returns true if the guessed mimetyped isnt't in text group.\"\"\"\n\t\tmimetype = mimetypes.guess_type(filename)[0]\n\t\tif not mimetype:\n\t\t\treturn False  # e.g. README, \"real\" binaries usually have an extension\n\t\t# special case for text files which don't start with text/\n\t\tif mimetype in TEXT_MIMETYPES:\n\t\t\treturn False\n\t\treturn not mimetype.startswith(\"text/\")", "title": ""}
{"_id": "d5246", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d5247", "text": "def get_adjacent_matrix(self):\n        \"\"\"Get adjacency matrix.\n\n        Returns:\n            :param adj: adjacency matrix\n            :type adj: np.ndarray\n        \"\"\"\n        edges = self.edges\n        num_edges = len(edges) + 1\n        adj = np.zeros([num_edges, num_edges])\n\n        for k in range(num_edges - 1):\n            adj[edges[k].L, edges[k].R] = 1\n            adj[edges[k].R, edges[k].L] = 1\n\n        return adj", "title": ""}
{"_id": "d5248", "text": "def fn_min(self, a, axis=None):\n        \"\"\"\n        Return the minimum of an array, ignoring any NaNs.\n\n        :param a: The array.\n        :return: The minimum value of the array.\n        \"\"\"\n\n        return numpy.nanmin(self._to_ndarray(a), axis=axis)", "title": ""}
{"_id": "d5249", "text": "def clean_float(v):\n    \"\"\"Remove commas from a float\"\"\"\n\n    if v is None or not str(v).strip():\n        return None\n\n    return float(str(v).replace(',', ''))", "title": ""}
{"_id": "d5250", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d5251", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d5252", "text": "def rank(self):\n        \"\"\"how high in sorted list each key is. inverse permutation of sorter, such that sorted[rank]==keys\"\"\"\n        r = np.empty(self.size, np.int)\n        r[self.sorter] = np.arange(self.size)\n        return r", "title": ""}
{"_id": "d5253", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d5254", "text": "def name(self):\n        \"\"\"A unique name for this scraper.\"\"\"\n        return ''.join('_%s' % c if c.isupper() else c for c in self.__class__.__name__).strip('_').lower()", "title": ""}
{"_id": "d5255", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d5256", "text": "def __copy__(self):\n        \"\"\"A magic method to implement shallow copy behavior.\"\"\"\n        return self.__class__.load(self.dump(), context=self.context)", "title": ""}
{"_id": "d5257", "text": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "title": ""}
{"_id": "d5258", "text": "def is_serializable(obj):\n    \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool\n    \"\"\"\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')", "title": ""}
{"_id": "d5259", "text": "def synthesize(self, duration):\n        \"\"\"\n        Synthesize white noise\n\n        Args:\n            duration (numpy.timedelta64): The duration of the synthesized sound\n        \"\"\"\n        sr = self.samplerate.samples_per_second\n        seconds = duration / Seconds(1)\n        samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n        return AudioSamples(samples, self.samplerate)", "title": ""}
{"_id": "d5260", "text": "def _is_date_data(self, data_type):\n        \"\"\"Private method for determining if a data record is of type DATE.\"\"\"\n        dt = DATA_TYPES[data_type]\n        if isinstance(self.data, dt['type']):\n            self.type = data_type.upper()\n            self.len = None\n            return True", "title": ""}
{"_id": "d5261", "text": "def go_to_new_line(self):\n        \"\"\"Go to the end of the current line and create a new line\"\"\"\n        self.stdkey_end(False, False)\n        self.insert_text(self.get_line_separator())", "title": ""}
{"_id": "d5262", "text": "def part(z, s):\n    r\"\"\"Get the real or imaginary part of a complex number.\"\"\"\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", "title": ""}
{"_id": "d5263", "text": "def seq_include(records, filter_regex):\n    \"\"\"\n    Filter any sequences who's seq does not match the filter. Ignore case.\n    \"\"\"\n    regex = re.compile(filter_regex)\n    for record in records:\n        if regex.search(str(record.seq)):\n            yield record", "title": ""}
{"_id": "d5264", "text": "def _replace_file(path, content):\n  \"\"\"Writes a file if it doesn't already exist with the same content.\n\n  This is useful because cargo uses timestamps to decide whether to compile things.\"\"\"\n  if os.path.exists(path):\n    with open(path, 'r') as f:\n      if content == f.read():\n        print(\"Not overwriting {} because it is unchanged\".format(path), file=sys.stderr)\n        return\n\n  with open(path, 'w') as f:\n    f.write(content)", "title": ""}
{"_id": "d5265", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d5266", "text": "def graph_from_dot_file(path):\n    \"\"\"Load graph as defined by a DOT file.\n    \n    The file is assumed to be in DOT format. It will\n    be loaded, parsed and a Dot class will be returned, \n    representing the graph.\n    \"\"\"\n    \n    fd = file(path, 'rb')\n    data = fd.read()\n    fd.close()\n    \n    return graph_from_dot_data(data)", "title": ""}
{"_id": "d5267", "text": "def clean_error(err):\n    \"\"\"\n    Take stderr bytes returned from MicroPython and attempt to create a\n    non-verbose error message.\n    \"\"\"\n    if err:\n        decoded = err.decode('utf-8')\n        try:\n            return decoded.split('\\r\\n')[-2]\n        except Exception:\n            return decoded\n    return 'There was an error.'", "title": ""}
{"_id": "d5268", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d5269", "text": "def save_dot(self, fd):\n        \"\"\" Saves a representation of the case in the Graphviz DOT language.\n        \"\"\"\n        from pylon.io import DotWriter\n        DotWriter(self).write(fd)", "title": ""}
{"_id": "d5270", "text": "def fopenat(base_fd, path):\n    \"\"\"\n    Does openat read-only, then does fdopen to get a file object\n    \"\"\"\n\n    return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')", "title": ""}
{"_id": "d5271", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d5272", "text": "def get_image(self, source):\n        \"\"\"\n        Given a file-like object, loads it up into a PIL.Image object\n        and returns it.\n\n        :param file source: A file-like object to load the image from.\n        :rtype: PIL.Image\n        :returns: The loaded image.\n        \"\"\"\n        buf = StringIO(source.read())\n        return Image.open(buf)", "title": ""}
{"_id": "d5273", "text": "def tokenize_words(self, text):\n        \"\"\"Tokenize an input string into a list of words (with punctuation removed).\"\"\"\n        return [\n            self.strip_punctuation(word) for word in text.split(' ')\n            if self.strip_punctuation(word)\n        ]", "title": ""}
{"_id": "d5274", "text": "def getbyteslice(self, start, end):\n        \"\"\"Direct access to byte data.\"\"\"\n        c = self._rawarray[start:end]\n        return c", "title": ""}
{"_id": "d5275", "text": "def fit_gaussian(x, y, yerr, p0):\n    \"\"\" Fit a Gaussian to the data \"\"\"\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", "title": ""}
{"_id": "d5276", "text": "def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y):\n    \"\"\"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)\n    \"\"\"\n    return image_transform(\n        X,\n        cv2.GaussianBlur,\n        ksize=(ksize_width, ksize_height),\n        sigmaX=sigma_x,\n        sigmaY=sigma_y\n    )", "title": ""}
{"_id": "d5277", "text": "def flatten(l):\n    \"\"\"Flatten a nested list.\"\"\"\n    return sum(map(flatten, l), []) \\\n        if isinstance(l, list) or isinstance(l, tuple) else [l]", "title": ""}
{"_id": "d5278", "text": "def zoom_cv(x,z):\n    \"\"\" Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. \"\"\"\n    if z==0: return x\n    r,c,*_ = x.shape\n    M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.)\n    return cv2.warpAffine(x,M,(c,r))", "title": ""}
{"_id": "d5279", "text": "def warp(self, warp_matrix, img, iflag=cv2.INTER_NEAREST):\n        \"\"\" Function to warp input image given an estimated 2D linear transformation\n\n        :param warp_matrix: Linear 2x3 matrix to use to linearly warp the input images\n        :type warp_matrix: ndarray\n        :param img: Image to be warped with estimated transformation\n        :type img: ndarray\n        :param iflag: Interpolation flag, specified interpolation using during resampling of warped image\n        :type iflag: cv2.INTER_*\n        :return: Warped image using the linear matrix\n        \"\"\"\n\n        height, width = img.shape[:2]\n        warped_img = np.zeros_like(img, dtype=img.dtype)\n\n        # Check if image to warp is 2D or 3D. If 3D need to loop over channels\n        if (self.interpolation_type == InterpolationType.LINEAR) or img.ndim == 2:\n            warped_img = cv2.warpAffine(img.astype(np.float32), warp_matrix, (width, height),\n                                        flags=iflag).astype(img.dtype)\n\n        elif img.ndim == 3:\n            for idx in range(img.shape[-1]):\n                warped_img[..., idx] = cv2.warpAffine(img[..., idx].astype(np.float32), warp_matrix, (width, height),\n                                                      flags=iflag).astype(img.dtype)\n        else:\n            raise ValueError('Image has incorrect number of dimensions: {}'.format(img.ndim))\n\n        return warped_img", "title": ""}
{"_id": "d5280", "text": "def file_read(filename):\n    \"\"\"Read a file and close it.  Returns the file source.\"\"\"\n    fobj = open(filename,'r');\n    source = fobj.read();\n    fobj.close()\n    return source", "title": ""}
{"_id": "d5281", "text": "def set_stop_handler(self):\n        \"\"\"\n        Initializes functions that are invoked when the user or OS wants to kill this process.\n        :return:\n        \"\"\"\n        signal.signal(signal.SIGTERM, self.graceful_stop)\n        signal.signal(signal.SIGABRT, self.graceful_stop)\n        signal.signal(signal.SIGINT, self.graceful_stop)", "title": ""}
{"_id": "d5282", "text": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "title": ""}
{"_id": "d5283", "text": "def camel_case(self, snake_case):\n        \"\"\" Convert snake case to camel case \"\"\"\n        components = snake_case.split('_')\n        return components[0] + \"\".join(x.title() for x in components[1:])", "title": ""}
{"_id": "d5284", "text": "def help(self, level=0):\n        \"\"\"return the usage string for available options \"\"\"\n        self.cmdline_parser.formatter.output_level = level\n        with _patch_optparse():\n            return self.cmdline_parser.format_help()", "title": ""}
{"_id": "d5285", "text": "def unit_key_from_name(name):\n  \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n  result = name\n\n  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n    result = result.replace(old, new)\n\n  # Collapse redundant underscores and convert to uppercase.\n  result = re.sub(r'_+', '_', result.upper())\n\n  return result", "title": ""}
{"_id": "d5286", "text": "def column_names(self, table):\n      \"\"\"An iterable of column names, for a particular table or\n      view.\"\"\"\n\n      table_info = self.execute(\n        u'PRAGMA table_info(%s)' % quote(table))\n      return (column['name'] for column in table_info)", "title": ""}
{"_id": "d5287", "text": "def get_naive(dt):\n  \"\"\"Gets a naive datetime from a datetime.\n\n  datetime_tz objects can't just have tzinfo replaced with None, you need to\n  call asdatetime.\n\n  Args:\n    dt: datetime object.\n\n  Returns:\n    datetime object without any timezone information.\n  \"\"\"\n  if not dt.tzinfo:\n    return dt\n  if hasattr(dt, \"asdatetime\"):\n    return dt.asdatetime()\n  return dt.replace(tzinfo=None)", "title": ""}
{"_id": "d5288", "text": "def get_table_metadata(engine, table):\n    \"\"\" Extract all useful infos from the given table\n\n    Args:\n        engine: SQLAlchemy connection engine\n        table: table name\n\n    Returns:\n        Dictionary of infos\n    \"\"\"\n    metadata = MetaData()\n    metadata.reflect(bind=engine, only=[table])\n    table_metadata = Table(table, metadata, autoload=True)\n    return table_metadata", "title": ""}
{"_id": "d5289", "text": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "title": ""}
{"_id": "d5290", "text": "def truncate(self, table):\n        \"\"\"Empty a table by deleting all of its rows.\"\"\"\n        if isinstance(table, (list, set, tuple)):\n            for t in table:\n                self._truncate(t)\n        else:\n            self._truncate(table)", "title": ""}
{"_id": "d5291", "text": "def wget(url):\n    \"\"\"\n    Download the page into a string\n    \"\"\"\n    import urllib.parse\n    request = urllib.request.urlopen(url)\n    filestring = request.read()\n    return filestring", "title": ""}
{"_id": "d5292", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d5293", "text": "def _import(module, cls):\n    \"\"\"\n    A messy way to import library-specific classes.\n    TODO: I should really make a factory class or something, but I'm lazy.\n    Plus, factories remind me a lot of java...\n    \"\"\"\n    global Scanner\n\n    try:\n        cls = str(cls)\n        mod = __import__(str(module), globals(), locals(), [cls], 1)\n        Scanner = getattr(mod, cls)\n    except ImportError:\n        pass", "title": ""}
{"_id": "d5294", "text": "def redirect_output(fileobj):\n    \"\"\"Redirect standard out to file.\"\"\"\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old", "title": ""}
{"_id": "d5295", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d5296", "text": "def requests_request(method, url, **kwargs):\n    \"\"\"Requests-mock requests.request wrapper.\"\"\"\n    session = local_sessions.session\n    response = session.request(method=method, url=url, **kwargs)\n    session.close()\n    return response", "title": ""}
{"_id": "d5297", "text": "def column_names(self, table):\n      \"\"\"An iterable of column names, for a particular table or\n      view.\"\"\"\n\n      table_info = self.execute(\n        u'PRAGMA table_info(%s)' % quote(table))\n      return (column['name'] for column in table_info)", "title": ""}
{"_id": "d5298", "text": "def autopage(self):\n        \"\"\"Iterate through results from all pages.\n\n        :return: all results\n        :rtype: generator\n        \"\"\"\n        while self.items:\n            yield from self.items\n            self.items = self.fetch_next()", "title": ""}
{"_id": "d5299", "text": "def sample_correlations(self):\n        \"\"\"Returns an `ExpMatrix` containing all pairwise sample correlations.\n\n        Returns\n        -------\n        `ExpMatrix`\n            The sample correlation matrix.\n\n        \"\"\"\n        C = np.corrcoef(self.X.T)\n        corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)\n        return corr_matrix", "title": ""}
{"_id": "d5300", "text": "def parse(self):\n        \"\"\"\n        Parse file specified by constructor.\n        \"\"\"\n        f = open(self.parse_log_path, \"r\")\n        self.parse2(f)\n        f.close()", "title": ""}
{"_id": "d5301", "text": "def find(command, on):\n    \"\"\"Find the command usage.\"\"\"\n    output_lines = parse_man_page(command, on)\n    click.echo(''.join(output_lines))", "title": ""}
{"_id": "d5302", "text": "def serialize_json_string(self, value):\n        \"\"\"\n        Tries to load an encoded json string back into an object\n        :param json_string:\n        :return:\n        \"\"\"\n\n        # Check if the value might be a json string\n        if not isinstance(value, six.string_types):\n            return value\n\n        # Make sure it starts with a brace\n        if not value.startswith('{') or value.startswith('['):\n            return value\n\n        # Try to load the string\n        try:\n            return json.loads(value)\n        except:\n            return value", "title": ""}
{"_id": "d5303", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d5304", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d5305", "text": "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location", "title": ""}
{"_id": "d5306", "text": "def to_datetime(value):\n    \"\"\"Converts a string to a datetime.\"\"\"\n    if value is None:\n        return None\n\n    if isinstance(value, six.integer_types):\n        return parser.parse(value)\n    return parser.isoparse(value)", "title": ""}
{"_id": "d5307", "text": "def rel_path(filename):\n    \"\"\"\n    Function that gets relative path to the filename\n    \"\"\"\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)", "title": ""}
{"_id": "d5308", "text": "def parse_datetime(dt_str):\n    \"\"\"Parse datetime.\"\"\"\n    date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n    dt_str = dt_str.replace(\"Z\", \" +0000\")\n    return datetime.datetime.strptime(dt_str, date_format)", "title": ""}
{"_id": "d5309", "text": "def word_to_id(self, word):\n        \"\"\"Returns the integer word id of a word string.\"\"\"\n        if word in self.vocab:\n            return self.vocab[word]\n        else:\n            return self.unk_id", "title": ""}
{"_id": "d5310", "text": "def updateFromKwargs(self, properties, kwargs, collector, **unused):\n        \"\"\"Primary entry point to turn 'kwargs' into 'properties'\"\"\"\n        properties[self.name] = self.getFromKwargs(kwargs)", "title": ""}
{"_id": "d5311", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d5312", "text": "def run(args):\n    \"\"\"Process command line arguments and walk inputs.\"\"\"\n    raw_arguments = get_arguments(args[1:])\n    process_arguments(raw_arguments)\n    walk.run()\n    return True", "title": ""}
{"_id": "d5313", "text": "def reload_localzone():\n    \"\"\"Reload the cached localzone. You need to call this if the timezone has changed.\"\"\"\n    global _cache_tz\n    _cache_tz = pytz.timezone(get_localzone_name())\n    utils.assert_tz_offset(_cache_tz)\n    return _cache_tz", "title": ""}
{"_id": "d5314", "text": "def OnPasteAs(self, event):\n        \"\"\"Clipboard paste as event handler\"\"\"\n\n        data = self.main_window.clipboard.get_clipboard()\n        key = self.main_window.grid.actions.cursor\n\n        with undo.group(_(\"Paste As...\")):\n            self.main_window.actions.paste_as(key, data)\n\n        self.main_window.grid.ForceRefresh()\n\n        event.Skip()", "title": ""}
{"_id": "d5315", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d5316", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d5317", "text": "def datetime_to_ms(dt):\n    \"\"\"\n    Converts a datetime to a millisecond accuracy timestamp\n    \"\"\"\n    seconds = calendar.timegm(dt.utctimetuple())\n    return seconds * 1000 + int(dt.microsecond / 1000)", "title": ""}
{"_id": "d5318", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d5319", "text": "def OnMove(self, event):\n        \"\"\"Main window move event\"\"\"\n\n        # Store window position in config\n        position = self.main_window.GetScreenPositionTuple()\n\n        config[\"window_position\"] = repr(position)", "title": ""}
{"_id": "d5320", "text": "def set_trace():\n    \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n    # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n    pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "title": ""}
{"_id": "d5321", "text": "def shape(self):\n        \"\"\"Compute the shape of the dataset as (rows, cols).\"\"\"\n        if not self.data:\n            return (0, 0)\n        return (len(self.data), len(self.dimensions))", "title": ""}
{"_id": "d5322", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d5323", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d5324", "text": "def delete_entry(self, key):\n        \"\"\"Delete an object from the redis table\"\"\"\n        pipe = self.client.pipeline()\n        pipe.srem(self.keys_container, key)\n        pipe.delete(key)\n        pipe.execute()", "title": ""}
{"_id": "d5325", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d5326", "text": "def circ_permutation(items):\n    \"\"\"Calculate the circular permutation for a given list of items.\"\"\"\n    permutations = []\n    for i in range(len(items)):\n        permutations.append(items[i:] + items[:i])\n    return permutations", "title": ""}
{"_id": "d5327", "text": "def call_and_exit(self, cmd, shell=True):\n        \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n        sys.exit(subprocess.call(cmd, shell=shell))", "title": ""}
{"_id": "d5328", "text": "def getoutput_pexpect(self, cmd):\n        \"\"\"Run a command and return its stdout/stderr as a string.\n\n        Parameters\n        ----------\n        cmd : str\n          A command to be executed in the system shell.\n\n        Returns\n        -------\n        output : str\n          A string containing the combination of stdout and stderr from the\n        subprocess, in whatever order the subprocess originally wrote to its\n        file descriptors (so the order of the information in this string is the\n        correct order as would be seen if running the command in a terminal).\n        \"\"\"\n        try:\n            return pexpect.run(self.sh, args=['-c', cmd]).replace('\\r\\n', '\\n')\n        except KeyboardInterrupt:\n            print('^C', file=sys.stderr, end='')", "title": ""}
{"_id": "d5329", "text": "def get_stripped_file_lines(filename):\n    \"\"\"\n    Return lines of a file with whitespace removed\n    \"\"\"\n    try:\n        lines = open(filename).readlines()\n    except FileNotFoundError:\n        fatal(\"Could not open file: {!r}\".format(filename))\n\n    return [line.strip() for line in lines]", "title": ""}
{"_id": "d5330", "text": "def getoutput_pexpect(self, cmd):\n        \"\"\"Run a command and return its stdout/stderr as a string.\n\n        Parameters\n        ----------\n        cmd : str\n          A command to be executed in the system shell.\n\n        Returns\n        -------\n        output : str\n          A string containing the combination of stdout and stderr from the\n        subprocess, in whatever order the subprocess originally wrote to its\n        file descriptors (so the order of the information in this string is the\n        correct order as would be seen if running the command in a terminal).\n        \"\"\"\n        try:\n            return pexpect.run(self.sh, args=['-c', cmd]).replace('\\r\\n', '\\n')\n        except KeyboardInterrupt:\n            print('^C', file=sys.stderr, end='')", "title": ""}
{"_id": "d5331", "text": "def _get_str_columns(sf):\n    \"\"\"\n    Returns a list of names of columns that are string type.\n    \"\"\"\n    return [name for name in sf.column_names() if sf[name].dtype == str]", "title": ""}
{"_id": "d5332", "text": "def unpickle(pickle_file):\n    \"\"\"Unpickle a python object from the given path.\"\"\"\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", "title": ""}
{"_id": "d5333", "text": "def angle(x0, y0, x1, y1):\n    \"\"\" Returns the angle between two points.\n    \"\"\"\n    return degrees(atan2(y1-y0, x1-x0))", "title": ""}
{"_id": "d5334", "text": "def load(self, filename='classifier.dump'):\n        \"\"\"\n        Unpickles the classifier used\n        \"\"\"\n        ifile = open(filename, 'r+')\n        self.classifier = pickle.load(ifile)\n        ifile.close()", "title": ""}
{"_id": "d5335", "text": "def get():\n    \"\"\" Get local facts about this machine.\n\n    Returns:\n        json-compatible dict with all facts of this host\n    \"\"\"\n    result = runCommand('facter --json', raise_error_on_fail=True)\n    json_facts = result[1]\n    facts = json.loads(json_facts)\n    return facts", "title": ""}
{"_id": "d5336", "text": "def highlight_region(plt, start_x, end_x):\n  \"\"\"\n  Highlight a region on the chart between the specified start and end x-co-ordinates.\n  param pyplot plt: matplotlibk pyplot which contains the charts to be highlighted\n  param string start_x : epoch time millis\n  param string end_x : epoch time millis\n  \"\"\"\n  start_x = convert_to_mdate(start_x)\n  end_x = convert_to_mdate(end_x)\n  plt.axvspan(start_x, end_x, color=CONSTANTS.HIGHLIGHT_COLOR, alpha=CONSTANTS.HIGHLIGHT_ALPHA)", "title": ""}
{"_id": "d5337", "text": "def load_search_freq(fp=SEARCH_FREQ_JSON):\n    \"\"\"\n    Load the search_freq from JSON file\n    \"\"\"\n    try:\n        with open(fp) as f:\n            return Counter(json.load(f))\n    except FileNotFoundError:\n        return Counter()", "title": ""}
{"_id": "d5338", "text": "def barv(d, plt, title=None, rotation='vertical'):\n    \"\"\"A convenience function for plotting a vertical bar plot from a Counter\"\"\"\n    labels = sorted(d, key=d.get, reverse=True)\n    index = range(len(labels))\n    plt.xticks(index, labels, rotation=rotation)\n    plt.bar(index, [d[v] for v in labels])\n\n    if title is not None:\n        plt.title(title)", "title": ""}
{"_id": "d5339", "text": "def datatype(dbtype, description, cursor):\n    \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n    dt = cursor.db.introspection.get_field_type(dbtype, description)\n    if type(dt) is tuple:\n        return dt[0]\n    else:\n        return dt", "title": ""}
{"_id": "d5340", "text": "def plot_target(target, ax):\n    \"\"\"Ajoute la target au plot\"\"\"\n    ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)", "title": ""}
{"_id": "d5341", "text": "def find_first_number(ll):\n    \"\"\" Returns nr of first entry parseable to float in ll, None otherwise\"\"\"\n    for nr, entry in enumerate(ll):\n        try:\n            float(entry)\n        except (ValueError, TypeError) as e:\n            pass\n        else:\n            return nr\n    return None", "title": ""}
{"_id": "d5342", "text": "def blocking(func, *args, **kwargs):\n    \"\"\"Run a function that uses blocking IO.\n\n    The function is run in the IO thread pool.\n    \"\"\"\n    pool = get_io_pool()\n    fut = pool.submit(func, *args, **kwargs)\n    return fut.result()", "title": ""}
{"_id": "d5343", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d5344", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d5345", "text": "def _next_token(self, skipws=True):\n        \"\"\"Increment _token to the next token and return it.\"\"\"\n        self._token = next(self._tokens).group(0)\n        return self._next_token() if skipws and self._token.isspace() else self._token", "title": ""}
{"_id": "d5346", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d5347", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d5348", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d5349", "text": "def twitter_timeline(screen_name, since_id=None):\n    \"\"\" Return relevant twitter timeline \"\"\"\n    consumer_key = twitter_credential('consumer_key')\n    consumer_secret = twitter_credential('consumer_secret')\n    access_token = twitter_credential('access_token')\n    access_token_secret = twitter_credential('access_secret')\n    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n    auth.set_access_token(access_token, access_token_secret)\n    api = tweepy.API(auth)\n    return get_all_tweets(screen_name, api, since_id)", "title": ""}
{"_id": "d5350", "text": "def Print(self, output_writer):\n    \"\"\"Prints a human readable version of the filter.\n\n    Args:\n      output_writer (CLIOutputWriter): output writer.\n    \"\"\"\n    if self._filters:\n      output_writer.Write('Filters:\\n')\n      for file_entry_filter in self._filters:\n        file_entry_filter.Print(output_writer)", "title": ""}
{"_id": "d5351", "text": "def _get_minidom_tag_value(station, tag_name):\n    \"\"\"get a value from a tag (if it exists)\"\"\"\n    tag = station.getElementsByTagName(tag_name)[0].firstChild\n    if tag:\n        return tag.nodeValue\n\n    return None", "title": ""}
{"_id": "d5352", "text": "def print_param_values(self_):\n        \"\"\"Print the values of all this object's Parameters.\"\"\"\n        self = self_.self\n        for name,val in self.param.get_param_values():\n            print('%s.%s = %s' % (self.name,name,val))", "title": ""}
{"_id": "d5353", "text": "def title(self):\n        \"\"\" The title of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.title", "title": ""}
{"_id": "d5354", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d5355", "text": "def created_today(self):\n        \"\"\"Return True if created today.\"\"\"\n        if self.datetime.date() == datetime.today().date():\n            return True\n        return False", "title": ""}
{"_id": "d5356", "text": "def __call__(self, _):\n        \"\"\"Print the current iteration.\"\"\"\n        if self.iter % self.step == 0:\n            print(self.fmt.format(self.iter), **self.kwargs)\n\n        self.iter += 1", "title": ""}
{"_id": "d5357", "text": "def get_system_uid():\n    \"\"\"Get a (probably) unique ID to identify a system.\n    Used to differentiate votes.\n    \"\"\"\n    try:\n        if os.name == 'nt':\n            return get_nt_system_uid()\n        if sys.platform == 'darwin':\n            return get_osx_system_uid()\n    except Exception:\n        return get_mac_uid()\n    else:\n        return get_mac_uid()", "title": ""}
{"_id": "d5358", "text": "def Print(self):\n        \"\"\"Prints the values and freqs/probs in ascending order.\"\"\"\n        for val, prob in sorted(self.d.iteritems()):\n            print(val, prob)", "title": ""}
{"_id": "d5359", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d5360", "text": "def raw_print(*args, **kw):\n    \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()", "title": ""}
{"_id": "d5361", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d5362", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d5363", "text": "def assign_to(self, obj):\n    \"\"\"Assign `x` and `y` to an object that has properties `x` and `y`.\"\"\"\n    obj.x = self.x\n    obj.y = self.y", "title": ""}
{"_id": "d5364", "text": "def print_bintree(tree, indent='  '):\n    \"\"\"print a binary tree\"\"\"\n    for n in sorted(tree.keys()):\n        print \"%s%s\" % (indent * depth(n,tree), n)", "title": ""}
{"_id": "d5365", "text": "def plot_target(target, ax):\n    \"\"\"Ajoute la target au plot\"\"\"\n    ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)", "title": ""}
{"_id": "d5366", "text": "def save_dot(self, fd):\n        \"\"\" Saves a representation of the case in the Graphviz DOT language.\n        \"\"\"\n        from pylon.io import DotWriter\n        DotWriter(self).write(fd)", "title": ""}
{"_id": "d5367", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d5368", "text": "def _display(self, layout):\n        \"\"\"launch layouts display\"\"\"\n        print(file=self.out)\n        TextWriter().format(layout, self.out)", "title": ""}
{"_id": "d5369", "text": "def parse_cookies(self, req, name, field):\n        \"\"\"Pull the value from the cookiejar.\"\"\"\n        return core.get_value(req.COOKIES, name, field)", "title": ""}
{"_id": "d5370", "text": "def run(args):\n    \"\"\"Process command line arguments and walk inputs.\"\"\"\n    raw_arguments = get_arguments(args[1:])\n    process_arguments(raw_arguments)\n    walk.run()\n    return True", "title": ""}
{"_id": "d5371", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d5372", "text": "def compute_capture(args):\n    x, y, w, h, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot_capture(x, y, w, h, params)", "title": ""}
{"_id": "d5373", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d5374", "text": "def get_free_memory_win():\n    \"\"\"Return current free memory on the machine for windows.\n\n    Warning : this script is really not robust\n    Return in MB unit\n    \"\"\"\n    stat = MEMORYSTATUSEX()\n    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n    return int(stat.ullAvailPhys / 1024 / 1024)", "title": ""}
{"_id": "d5375", "text": "def cycle_focus(self):\n        \"\"\"\n        Cycle through all windows.\n        \"\"\"\n        windows = self.windows()\n        new_index = (windows.index(self.active_window) + 1) % len(windows)\n        self.active_window = windows[new_index]", "title": ""}
{"_id": "d5376", "text": "def __call__(self, _):\n        \"\"\"Update the progressbar.\"\"\"\n        if self.iter % self.step == 0:\n            self.pbar.update(self.step)\n\n        self.iter += 1", "title": ""}
{"_id": "d5377", "text": "def int32_to_negative(int32):\n    \"\"\"Checks if a suspicious number (e.g. ligand position) is in fact a negative number represented as a\n    32 bit integer and returns the actual number.\n    \"\"\"\n    dct = {}\n    if int32 == 4294967295:  # Special case in some structures (note, this is just a workaround)\n        return -1\n    for i in range(-1000, -1):\n        dct[np.uint32(i)] = i\n    if int32 in dct:\n        return dct[int32]\n    else:\n        return int32", "title": ""}
{"_id": "d5378", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d5379", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d5380", "text": "def acknowledge_time(self):\n        \"\"\"\n        Processor time when the alarm was acknowledged.\n\n        :type: :class:`~datetime.datetime`\n        \"\"\"\n        if (self.is_acknowledged and\n                self._proto.acknowledgeInfo.HasField('acknowledgeTime')):\n            return parse_isostring(self._proto.acknowledgeInfo.acknowledgeTime)\n        return None", "title": ""}
{"_id": "d5381", "text": "def get_order(self):\n        \"\"\"\n        Return a list of dicionaries. See `set_order`.\n        \"\"\"\n        return [dict(reverse=r[0], key=r[1]) for r in self.get_model()]", "title": ""}
{"_id": "d5382", "text": "def _prepare_proxy(self, conn):\n        \"\"\"\n        Establish tunnel connection early, because otherwise httplib\n        would improperly set Host: header to proxy's IP:port.\n        \"\"\"\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n        conn.connect()", "title": ""}
{"_id": "d5383", "text": "def use_theme(theme):\n    \"\"\"Make the given theme current.\n\n    There are two included themes: light_theme, dark_theme.\n    \"\"\"\n    global current\n    current = theme\n    import scene\n    if scene.current is not None:\n        scene.current.stylize()", "title": ""}
{"_id": "d5384", "text": "def packagenameify(s):\n  \"\"\"\n  Makes a package name\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('.')[-1:])", "title": ""}
{"_id": "d5385", "text": "def getpass(self, prompt, default=None):\n        \"\"\"Provide a password prompt.\"\"\"\n        return click.prompt(prompt, hide_input=True, default=default)", "title": ""}
{"_id": "d5386", "text": "def store_many(self, sql, values):\n        \"\"\"Abstraction over executemany method\"\"\"\n        cursor = self.get_cursor()\n        cursor.executemany(sql, values)\n        self.conn.commit()", "title": ""}
{"_id": "d5387", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d5388", "text": "def _single_page_pdf(page):\n    \"\"\"Construct a single page PDF from the provided page in memory\"\"\"\n    pdf = Pdf.new()\n    pdf.pages.append(page)\n    bio = BytesIO()\n    pdf.save(bio)\n    bio.seek(0)\n    return bio.read()", "title": ""}
{"_id": "d5389", "text": "def hide(self):\n        \"\"\"Hides the main window of the terminal and sets the visible\n        flag to False.\n        \"\"\"\n        if not HidePrevention(self.window).may_hide():\n            return\n        self.hidden = True\n        self.get_widget('window-root').unstick()\n        self.window.hide()", "title": ""}
{"_id": "d5390", "text": "def set_ylimits(self, row, column, min=None, max=None):\n        \"\"\"Set y-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_ylimits(min, max)", "title": ""}
{"_id": "d5391", "text": "def isBlockComment(self, line, column):\n        \"\"\"Check if text at given position is a block comment.\n\n        If language is not known, or text is not parsed yet, ``False`` is returned\n        \"\"\"\n        return self._highlighter is not None and \\\n               self._highlighter.isBlockComment(self.document().findBlockByNumber(line), column)", "title": ""}
{"_id": "d5392", "text": "def handle_qbytearray(obj, encoding):\n    \"\"\"Qt/Python2/3 compatibility helper.\"\"\"\n    if isinstance(obj, QByteArray):\n        obj = obj.data()\n\n    return to_text_string(obj, encoding=encoding)", "title": ""}
{"_id": "d5393", "text": "def _get_line_no_from_comments(py_line):\n    \"\"\"Return the line number parsed from the comment or 0.\"\"\"\n    matched = LINECOL_COMMENT_RE.match(py_line)\n    if matched:\n        return int(matched.group(1))\n    else:\n        return 0", "title": ""}
{"_id": "d5394", "text": "def _obj_cursor_to_dictionary(self, cursor):\n        \"\"\"Handle conversion of pymongo cursor into a JSON object formatted for UI consumption\n\n        :param dict cursor: a mongo document that should be converted to primitive types for the client code\n        :returns: a primitive dictionary\n        :rtype: dict\n        \"\"\"\n        if not cursor:\n            return cursor\n\n        cursor = json.loads(json.dumps(cursor, cls=BSONEncoder))\n\n        if cursor.get(\"_id\"):\n            cursor[\"id\"] = cursor.get(\"_id\")\n            del cursor[\"_id\"]\n\n        return cursor", "title": ""}
{"_id": "d5395", "text": "def __enter__(self):\n        \"\"\" Implements the context manager protocol. Specially useful for asserting exceptions\n        \"\"\"\n        clone = self.clone()\n        self._contexts.append(clone)\n        self.reset()\n        return self", "title": ""}
{"_id": "d5396", "text": "def dict_to_querystring(dictionary):\n    \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\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]", "title": ""}
{"_id": "d5397", "text": "def __call__(self, _):\n        \"\"\"Update the progressbar.\"\"\"\n        if self.iter % self.step == 0:\n            self.pbar.update(self.step)\n\n        self.iter += 1", "title": ""}
{"_id": "d5398", "text": "def is_nullable_list(val, vtype):\n    \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n    return (isinstance(val, list) and\n            any(isinstance(v, vtype) for v in val) and\n            all((isinstance(v, vtype) or v is None) for v in val))", "title": ""}
{"_id": "d5399", "text": "def set_font_size(self, size):\n        \"\"\"Convenience method for just changing font size.\"\"\"\n        if self.font.font_size == size:\n            pass\n        else:\n            self.font._set_size(size)", "title": ""}
{"_id": "d5400", "text": "def wait_until_exit(self):\n        \"\"\" Wait until all the threads are finished.\n\n        \"\"\"\n        [t.join() for t in self.threads]\n\n        self.threads = list()", "title": ""}
{"_id": "d5401", "text": "def intersect(d1, d2):\n    \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n    return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "title": ""}
{"_id": "d5402", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d5403", "text": "def directory_files(path):\n    \"\"\"Yield directory file names.\"\"\"\n\n    for entry in os.scandir(path):\n        if not entry.name.startswith('.') and entry.is_file():\n            yield entry.name", "title": ""}
{"_id": "d5404", "text": "def get_range(self, start=None, stop=None):\n\t\t\"\"\"Return a RangeMap for the range start to stop.\n\n\t\tReturns:\n\t\t\tA RangeMap\n\t\t\"\"\"\n\t\treturn self.from_iterable(self.ranges(start, stop))", "title": ""}
{"_id": "d5405", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d5406", "text": "def LinSpace(start, stop, num):\n    \"\"\"\n    Linspace op.\n    \"\"\"\n    return np.linspace(start, stop, num=num, dtype=np.float32),", "title": ""}
{"_id": "d5407", "text": "def ensure_hbounds(self):\n        \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "title": ""}
{"_id": "d5408", "text": "def _ratelimited_get(self, *args, **kwargs):\n        \"\"\"Perform get request, handling rate limiting.\"\"\"\n        with self._ratelimiter:\n            resp = self.session.get(*args, **kwargs)\n\n        # It's possible that Space-Track will return HTTP status 500 with a\n        # query rate limit violation. This can happen if a script is cancelled\n        # before it has finished sleeping to satisfy the rate limit and it is\n        # started again.\n        #\n        # Let's catch this specific instance and retry once if it happens.\n        if resp.status_code == 500:\n            # Let's only retry if the error page tells us it's a rate limit\n            # violation.\n            if 'violated your query rate limit' in resp.text:\n                # Mimic the RateLimiter callback behaviour.\n                until = time.time() + self._ratelimiter.period\n                t = threading.Thread(target=self._ratelimit_callback, args=(until,))\n                t.daemon = True\n                t.start()\n                time.sleep(self._ratelimiter.period)\n\n                # Now retry\n                with self._ratelimiter:\n                    resp = self.session.get(*args, **kwargs)\n\n        return resp", "title": ""}
{"_id": "d5409", "text": "def close(self):\n        \"\"\"Close child subprocess\"\"\"\n        if self._subprocess is not None:\n            os.killpg(self._subprocess.pid, signal.SIGTERM)\n            self._subprocess = None", "title": ""}
{"_id": "d5410", "text": "def split_comment(cls, code):\n        \"\"\" Removes comments (#...) from python code. \"\"\"\n        if '#' not in code: return code\n        #: Remove comments only (leave quoted strings as they are)\n        subf = lambda m: '' if m.group(0)[0]=='#' else m.group(0)\n        return re.sub(cls.re_pytokens, subf, code)", "title": ""}
{"_id": "d5411", "text": "def get_mnist(data_type=\"train\", location=\"/tmp/mnist\"):\n    \"\"\"\n    Get mnist dataset with features and label as ndarray.\n    Data would be downloaded automatically if it doesn't present at the specific location.\n\n    :param data_type: \"train\" for training data and \"test\" for testing data.\n    :param location: Location to store mnist dataset.\n    :return: (features: ndarray, label: ndarray)\n    \"\"\"\n    X, Y = mnist.read_data_sets(location, data_type)\n    return X, Y + 1", "title": ""}
{"_id": "d5412", "text": "def rAsciiLine(ifile):\n    \"\"\"Returns the next non-blank line in an ASCII file.\"\"\"\n\n    _line = ifile.readline().strip()\n    while len(_line) == 0:\n        _line = ifile.readline().strip()\n    return _line", "title": ""}
{"_id": "d5413", "text": "def import_js(path, lib_name, globals):\n    \"\"\"Imports from javascript source file.\n      globals is your globals()\"\"\"\n    with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:\n        js = f.read()\n    e = EvalJs()\n    e.execute(js)\n    var = e.context['var']\n    globals[lib_name] = var.to_python()", "title": ""}
{"_id": "d5414", "text": "def read_large_int(self, bits, signed=True):\n        \"\"\"Reads a n-bits long integer value.\"\"\"\n        return int.from_bytes(\n            self.read(bits // 8), byteorder='little', signed=signed)", "title": ""}
{"_id": "d5415", "text": "def scale_image(image, new_width):\n    \"\"\"Resizes an image preserving the aspect ratio.\n    \"\"\"\n    (original_width, original_height) = image.size\n    aspect_ratio = original_height/float(original_width)\n    new_height = int(aspect_ratio * new_width)\n\n    # This scales it wider than tall, since characters are biased\n    new_image = image.resize((new_width*2, new_height))\n    return new_image", "title": ""}
{"_id": "d5416", "text": "def readme():\n    \"\"\"Try converting the README to an RST document. Return it as is on failure.\"\"\"\n    try:\n        import pypandoc\n        readme_content = pypandoc.convert('README.md', 'rst')\n    except(IOError, ImportError):\n        print(\"Warning: no pypandoc module found.\")\n        try:\n            readme_content = open('README.md').read()\n        except IOError:\n            readme_content = ''\n    return readme_content", "title": ""}
{"_id": "d5417", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d5418", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d5419", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d5420", "text": "def _read_json_file(self, json_file):\n        \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n        self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n        with open(json_file, 'r') as f:\n            return json.load(f, object_pairs_hook=OrderedDict)", "title": ""}
{"_id": "d5421", "text": "def _basic_field_data(field, obj):\n    \"\"\"Returns ``obj.field`` data as a dict\"\"\"\n    value = field.value_from_object(obj)\n    return {Field.TYPE: FieldType.VAL, Field.VALUE: value}", "title": ""}
{"_id": "d5422", "text": "def get_list_from_file(file_name):\n    \"\"\"read the lines from a file into a list\"\"\"\n    with open(file_name, mode='r', encoding='utf-8') as f1:\n        lst = f1.readlines()\n    return lst", "title": ""}
{"_id": "d5423", "text": "def kick(self, channel, nick, comment=\"\"):\n        \"\"\"Send a KICK command.\"\"\"\n        self.send_items('KICK', channel, nick, comment and ':' + comment)", "title": ""}
{"_id": "d5424", "text": "def standard_input():\n    \"\"\"Generator that yields lines from standard input.\"\"\"\n    with click.get_text_stream(\"stdin\") as stdin:\n        while stdin.readable():\n            line = stdin.readline()\n            if line:\n                yield line.strip().encode(\"utf-8\")", "title": ""}
{"_id": "d5425", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d5426", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d5427", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d5428", "text": "def _readuntil(f, end=_TYPE_END):\n\t\"\"\"Helper function to read bytes until a certain end byte is hit\"\"\"\n\tbuf = bytearray()\n\tbyte = f.read(1)\n\twhile byte != end:\n\t\tif byte == b'':\n\t\t\traise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))\n\t\tbuf += byte\n\t\tbyte = f.read(1)\n\treturn buf", "title": ""}
{"_id": "d5429", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d5430", "text": "def read_data(file, endian, num=1):\n    \"\"\"\n    Read a given number of 32-bits unsigned integers from the given file\n    with the given endianness.\n    \"\"\"\n    res = struct.unpack(endian + 'L' * num, file.read(num * 4))\n    if len(res) == 1:\n        return res[0]\n    return res", "title": ""}
{"_id": "d5431", "text": "def counter_from_str(self, string):\n        \"\"\"Build word frequency list from incoming string.\"\"\"\n        string_list = [chars for chars in string if chars not in self.punctuation]\n        string_joined = ''.join(string_list)\n        tokens = self.punkt.word_tokenize(string_joined)\n        return Counter(tokens)", "title": ""}
{"_id": "d5432", "text": "def get_stripped_file_lines(filename):\n    \"\"\"\n    Return lines of a file with whitespace removed\n    \"\"\"\n    try:\n        lines = open(filename).readlines()\n    except FileNotFoundError:\n        fatal(\"Could not open file: {!r}\".format(filename))\n\n    return [line.strip() for line in lines]", "title": ""}
{"_id": "d5433", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d5434", "text": "def _multiline_width(multiline_s, line_width_fn=len):\n    \"\"\"Visible width of a potentially multiline content.\"\"\"\n    return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "title": ""}
{"_id": "d5435", "text": "def do_restart(self, line):\n        \"\"\"Request that the Outstation perform a cold restart. Command syntax is: restart\"\"\"\n        self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)", "title": ""}
{"_id": "d5436", "text": "def __setitem__(self, field, value):\n        \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n        return self._client.hset(self.key_prefix, field, self._dumps(value))", "title": ""}
{"_id": "d5437", "text": "def downcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n    return [ tt.lower() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d5438", "text": "def __setitem__(self, field, value):\n        \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n        return self._client.hset(self.key_prefix, field, self._dumps(value))", "title": ""}
{"_id": "d5439", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d5440", "text": "def hstrlen(self, name, key):\n        \"\"\"\n        Return the number of bytes stored in the value of ``key``\n        within hash ``name``\n        \"\"\"\n        with self.pipe as pipe:\n            return pipe.hstrlen(self.redis_key(name), key)", "title": ""}
{"_id": "d5441", "text": "def get_default_preds():\n    \"\"\"dynamically build autocomplete options based on an external file\"\"\"\n    g = ontospy.Ontospy(rdfsschema, text=True, verbose=False, hide_base_schemas=False)\n    classes = [(x.qname, x.bestDescription()) for x in g.all_classes]\n    properties = [(x.qname, x.bestDescription()) for x in g.all_properties]\n    commands = [('exit', 'exits the terminal'), ('show', 'show current buffer')]\n    return rdfschema + owlschema + classes + properties + commands", "title": ""}
{"_id": "d5442", "text": "def exit(self):\n        \"\"\"\n        Closes the connection\n        \"\"\"\n        self.pubsub.unsubscribe()\n        self.client.connection_pool.disconnect()\n\n        logger.info(\"Connection to Redis closed\")", "title": ""}
{"_id": "d5443", "text": "def changed(self):\n        \"\"\"Returns dict of fields that changed since save (with old values)\"\"\"\n        return dict(\n            (field, self.previous(field))\n            for field in self.fields\n            if self.has_changed(field)\n        )", "title": ""}
{"_id": "d5444", "text": "def _get_info(self, host, port, unix_socket, auth):\n        \"\"\"Return info dict from specified Redis instance\n\n:param str host: redis host\n:param int port: redis port\n:rtype: dict\n\n        \"\"\"\n\n        client = self._client(host, port, unix_socket, auth)\n        if client is None:\n            return None\n\n        info = client.info()\n        del client\n        return info", "title": ""}
{"_id": "d5445", "text": "def combinations(l):\n    \"\"\"Pure-Python implementation of itertools.combinations(l, 2).\"\"\"\n    result = []\n    for x in xrange(len(l) - 1):\n        ls = l[x + 1:]\n        for y in ls:\n            result.append((l[x], y))\n    return result", "title": ""}
{"_id": "d5446", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d5447", "text": "def rank(idx, dim):\n    \"\"\"Calculate the index rank according to Bertran's notation.\"\"\"\n    idxm = multi_index(idx, dim)\n    out = 0\n    while idxm[-1:] == (0,):\n        out += 1\n        idxm = idxm[:-1]\n    return out", "title": ""}
{"_id": "d5448", "text": "def extract_table_names(query):\n    \"\"\" Extract table names from an SQL query. \"\"\"\n    # a good old fashioned regex. turns out this worked better than actually parsing the code\n    tables_blocks = re.findall(r'(?:FROM|JOIN)\\s+(\\w+(?:\\s*,\\s*\\w+)*)', query, re.IGNORECASE)\n    tables = [tbl\n              for block in tables_blocks\n              for tbl in re.findall(r'\\w+', block)]\n    return set(tables)", "title": ""}
{"_id": "d5449", "text": "def _npiter(arr):\n    \"\"\"Wrapper for iterating numpy array\"\"\"\n    for a in np.nditer(arr, flags=[\"refs_ok\"]):\n        c = a.item()\n        if c is not None:\n            yield c", "title": ""}
{"_id": "d5450", "text": "def __absolute__(self, uri):\n        \"\"\" Get the absolute uri for a file\n\n        :param uri: URI of the resource to be retrieved\n        :return: Absolute Path\n        \"\"\"\n        return op.abspath(op.join(self.__path__, uri))", "title": ""}
{"_id": "d5451", "text": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d5452", "text": "def pages(self):\n        \"\"\"Get pages, reloading the site if needed.\"\"\"\n        rev = self.db.get('site:rev')\n        if int(rev) != self.revision:\n            self.reload_site()\n\n        return self._pages", "title": ""}
{"_id": "d5453", "text": "def logx_linear(x, a, b):\n    \"\"\"logx linear\n\n    Parameters\n    ----------\n    x: int\n    a: float\n    b: float\n\n    Returns\n    -------\n    float\n        a * np.log(x) + b\n    \"\"\"\n    x = np.log(x)\n    return a*x + b", "title": ""}
{"_id": "d5454", "text": "def uint32_to_uint8(cls, img):\n        \"\"\"\n        Cast uint32 RGB image to 4 uint8 channels.\n        \"\"\"\n        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))", "title": ""}
{"_id": "d5455", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d5456", "text": "def strip_accents(s):\n    \"\"\"\n    Strip accents to prepare for slugification.\n    \"\"\"\n    nfkd = unicodedata.normalize('NFKD', unicode(s))\n    return u''.join(ch for ch in nfkd if not unicodedata.combining(ch))", "title": ""}
{"_id": "d5457", "text": "def min_values(args):\n    \"\"\" Return possible range for min function. \"\"\"\n    return Interval(min(x.low for x in args), min(x.high for x in args))", "title": ""}
{"_id": "d5458", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d5459", "text": "def ensure_hbounds(self):\n        \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "title": ""}
{"_id": "d5460", "text": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "title": ""}
{"_id": "d5461", "text": "def timed (log=sys.stderr, limit=2.0):\n    \"\"\"Decorator to run a function with timing info.\"\"\"\n    return lambda func: timeit(func, log, limit)", "title": ""}
{"_id": "d5462", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d5463", "text": "def classnameify(s):\n  \"\"\"\n  Makes a classname\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))", "title": ""}
{"_id": "d5464", "text": "def __normalize_list(self, msg):\n        \"\"\"Split message to list by commas and trim whitespace.\"\"\"\n        if isinstance(msg, list):\n            msg = \"\".join(msg)\n        return list(map(lambda x: x.strip(), msg.split(\",\")))", "title": ""}
{"_id": "d5465", "text": "def multiply(self, number):\n        \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n        return self.from_list([x * number for x in self.to_list()])", "title": ""}
{"_id": "d5466", "text": "def CleanseComments(line):\n  \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n  Args:\n    line: A line of C++ source.\n\n  Returns:\n    The line with single-line comments removed.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1 and not IsCppString(line[:commentpos]):\n    line = line[:commentpos].rstrip()\n  # get rid of /* ... */\n  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "title": ""}
{"_id": "d5467", "text": "def get_cube(name):\n    \"\"\" Load the named cube from the current registered ``CubeManager``. \"\"\"\n    manager = get_manager()\n    if not manager.has_cube(name):\n        raise NotFound('No such cube: %r' % name)\n    return manager.get_cube(name)", "title": ""}
{"_id": "d5468", "text": "def remove_dups(seq):\n    \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d5469", "text": "def mark(self, lineno, count=1):\n        \"\"\"Mark a given source line as executed count times.\n\n        Multiple calls to mark for the same lineno add up.\n        \"\"\"\n        self.sourcelines[lineno] = self.sourcelines.get(lineno, 0) + count", "title": ""}
{"_id": "d5470", "text": "def dedupFasta(reads):\n    \"\"\"\n    Remove sequence duplicates (based on sequence) from FASTA.\n\n    @param reads: a C{dark.reads.Reads} instance.\n    @return: a generator of C{dark.reads.Read} instances with no duplicates.\n    \"\"\"\n    seen = set()\n    add = seen.add\n    for read in reads:\n        hash_ = md5(read.sequence.encode('UTF-8')).digest()\n        if hash_ not in seen:\n            add(hash_)\n            yield read", "title": ""}
{"_id": "d5471", "text": "def remove_na_arraylike(arr):\n    \"\"\"\n    Return array-like containing only true/non-NaN values, possibly empty.\n    \"\"\"\n    if is_extension_array_dtype(arr):\n        return arr[notna(arr)]\n    else:\n        return arr[notna(lib.values_from_object(arr))]", "title": ""}
{"_id": "d5472", "text": "def pop (self, key):\n        \"\"\"Remove key from dict and return value.\"\"\"\n        if key in self._keys:\n            self._keys.remove(key)\n        super(ListDict, self).pop(key)", "title": ""}
{"_id": "d5473", "text": "def load_image(fname):\n    \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n    with open(fname, \"rb\") as f:\n        i = Image.open(fname)\n        #i.load()\n        return i", "title": ""}
{"_id": "d5474", "text": "def file_read(filename):\n    \"\"\"Read a file and close it.  Returns the file source.\"\"\"\n    fobj = open(filename,'r');\n    source = fobj.read();\n    fobj.close()\n    return source", "title": ""}
{"_id": "d5475", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d5476", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d5477", "text": "def remover(file_path):\n    \"\"\"Delete a file or directory path only if it exists.\"\"\"\n    if os.path.isfile(file_path):\n        os.remove(file_path)\n        return True\n    elif os.path.isdir(file_path):\n        shutil.rmtree(file_path)\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d5478", "text": "def to_json(data):\n    \"\"\"Return data as a JSON string.\"\"\"\n    return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)", "title": ""}
{"_id": "d5479", "text": "def focusInEvent(self, event):\n        \"\"\"Reimplement Qt method to send focus change notification\"\"\"\n        self.focus_changed.emit()\n        return super(ControlWidget, self).focusInEvent(event)", "title": ""}
{"_id": "d5480", "text": "def jsonify(symbol):\n    \"\"\" returns json format for symbol \"\"\"\n    try:\n        # all symbols have a toJson method, try it\n        return json.dumps(symbol.toJson(), indent='  ')\n    except AttributeError:\n        pass\n    return json.dumps(symbol, indent='  ')", "title": ""}
{"_id": "d5481", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d5482", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d5483", "text": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "title": ""}
{"_id": "d5484", "text": "def _obj_cursor_to_dictionary(self, cursor):\n        \"\"\"Handle conversion of pymongo cursor into a JSON object formatted for UI consumption\n\n        :param dict cursor: a mongo document that should be converted to primitive types for the client code\n        :returns: a primitive dictionary\n        :rtype: dict\n        \"\"\"\n        if not cursor:\n            return cursor\n\n        cursor = json.loads(json.dumps(cursor, cls=BSONEncoder))\n\n        if cursor.get(\"_id\"):\n            cursor[\"id\"] = cursor.get(\"_id\")\n            del cursor[\"_id\"]\n\n        return cursor", "title": ""}
{"_id": "d5485", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d5486", "text": "def clean_float(v):\n    \"\"\"Remove commas from a float\"\"\"\n\n    if v is None or not str(v).strip():\n        return None\n\n    return float(str(v).replace(',', ''))", "title": ""}
{"_id": "d5487", "text": "def get_line_ending(line):\n    \"\"\"Return line ending.\"\"\"\n    non_whitespace_index = len(line.rstrip()) - len(line)\n    if not non_whitespace_index:\n        return ''\n    else:\n        return line[non_whitespace_index:]", "title": ""}
{"_id": "d5488", "text": "def _serialize_json(obj, fp):\n    \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n    json.dump(obj, fp, indent=4, default=serialize)", "title": ""}
{"_id": "d5489", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d5490", "text": "def random_choice(sequence):\n    \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n    return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)", "title": ""}
{"_id": "d5491", "text": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "title": ""}
{"_id": "d5492", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d5493", "text": "def format_screen(strng):\n    \"\"\"Format a string for screen printing.\n\n    This removes some latex-type format codes.\"\"\"\n    # Paragraph continue\n    par_re = re.compile(r'\\\\$',re.MULTILINE)\n    strng = par_re.sub('',strng)\n    return strng", "title": ""}
{"_id": "d5494", "text": "def __pop_top_frame(self):\n        \"\"\"Pops the top frame off the frame stack.\"\"\"\n        popped = self.__stack.pop()\n        if self.__stack:\n            self.__stack[-1].process_subframe(popped)", "title": ""}
{"_id": "d5495", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d5496", "text": "def cat_acc(y_true, y_pred):\n    \"\"\"Categorical accuracy\n    \"\"\"\n    return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))", "title": ""}
{"_id": "d5497", "text": "def remove(self, key):\n        \"\"\"remove the value found at key from the queue\"\"\"\n        item = self.item_finder.pop(key)\n        item[-1] = None\n        self.removed_count += 1", "title": ""}
{"_id": "d5498", "text": "def close_stream(self):\n\t\t\"\"\" Closes the stream. Performs cleanup. \"\"\"\n\t\tself.keep_listening = False\n\t\tself.stream.stop()\n\t\tself.stream.close()", "title": ""}
{"_id": "d5499", "text": "def strip_html(string, keep_tag_content=False):\n    \"\"\"\n    Remove html code contained into the given string.\n\n    :param string: String to manipulate.\n    :type string: str\n    :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).\n    :type keep_tag_content: bool\n    :return: String with html removed.\n    :rtype: str\n    \"\"\"\n    r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE\n    return r.sub('', string)", "title": ""}
{"_id": "d5500", "text": "def print_log(text, *colors):\n    \"\"\"Print a log message to standard error.\"\"\"\n    sys.stderr.write(sprint(\"{}: {}\".format(script_name, text), *colors) + \"\\n\")", "title": ""}
{"_id": "d5501", "text": "def remove_property(self, key=None, value=None):\n        \"\"\"Remove all properties matching both key and value.\n\n        :param str key: Key of the property.\n        :param str value: Value of the property.\n        \"\"\"\n        for k, v in self.properties[:]:\n            if (key is None or key == k) and (value is None or value == v):\n                del(self.properties[self.properties.index((k, v))])", "title": ""}
{"_id": "d5502", "text": "def fail_print(error):\n    \"\"\"Print an error in red text.\n    Parameters\n        error (HTTPError)\n            Error object to print.\n    \"\"\"\n    print(COLORS.fail, error.message, COLORS.end)\n    print(COLORS.fail, error.errors, COLORS.end)", "title": ""}
{"_id": "d5503", "text": "def generic_add(a, b):\n    print\n    \"\"\"Simple function to add two numbers\"\"\"\n    logger.info('Called generic_add({}, {})'.format(a, b))\n    return a + b", "title": ""}
{"_id": "d5504", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d5505", "text": "def csvpretty(csvfile: csvfile=sys.stdin):\n    \"\"\" Pretty print a CSV file. \"\"\"\n    shellish.tabulate(csv.reader(csvfile))", "title": ""}
{"_id": "d5506", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d5507", "text": "def pretty_print_post(req):\n    \"\"\"Helper to print a \"prepared\" query. Useful to debug a POST query.\n\n    However pay attention at the formatting used in\n    this function because it is programmed to be pretty\n    printed and may differ from the actual request.\n    \"\"\"\n    print(('{}\\n{}\\n{}\\n\\n{}'.format(\n        '-----------START-----------',\n        req.method + ' ' + req.url,\n        '\\n'.join('{}: {}'.format(k, v) for k, v in list(req.headers.items())),\n        req.body,\n    )))", "title": ""}
{"_id": "d5508", "text": "def camelcase_underscore(name):\n    \"\"\" Convert camelcase names to underscore \"\"\"\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()", "title": ""}
{"_id": "d5509", "text": "def object_type_repr(obj):\n    \"\"\"Returns the name of the object's type.  For some recognized\n    singletons the name of the object is returned instead. (For\n    example for `None` and `Ellipsis`).\n    \"\"\"\n    if obj is None:\n        return 'None'\n    elif obj is Ellipsis:\n        return 'Ellipsis'\n    if obj.__class__.__module__ == '__builtin__':\n        name = obj.__class__.__name__\n    else:\n        name = obj.__class__.__module__ + '.' + obj.__class__.__name__\n    return '%s object' % name", "title": ""}
{"_id": "d5510", "text": "def parse_querystring(self, req, name, field):\n        \"\"\"Pull a querystring value from the request.\"\"\"\n        return core.get_value(req.args, name, field)", "title": ""}
{"_id": "d5511", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d5512", "text": "def __call__(self, r):\n        \"\"\"Update the request headers.\"\"\"\n        r.headers['Authorization'] = 'JWT {jwt}'.format(jwt=self.token)\n        return r", "title": ""}
{"_id": "d5513", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d5514", "text": "def head(self, path, query=None, data=None, redirects=True):\n        \"\"\"\n        HEAD request wrapper for :func:`request()`\n        \"\"\"\n        return self.request('HEAD', path, query, None, redirects)", "title": ""}
{"_id": "d5515", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d5516", "text": "def session(self):\n        \"\"\"A context manager for this client's session.\n\n        This function closes the current session when this client goes out of\n        scope.\n        \"\"\"\n        self._session = requests.session()\n        yield\n        self._session.close()\n        self._session = None", "title": ""}
{"_id": "d5517", "text": "def Exponential(x, a, tau, y0):\n    \"\"\"Exponential function\n\n    Inputs:\n    -------\n        ``x``: independent variable\n        ``a``: scaling factor\n        ``tau``: time constant\n        ``y0``: additive constant\n\n    Formula:\n    --------\n        ``a*exp(x/tau)+y0``\n    \"\"\"\n    return np.exp(x / tau) * a + y0", "title": ""}
{"_id": "d5518", "text": "def send_post(self, url, data, remove_header=None):\n        \"\"\" Send a POST request\n        \"\"\"\n        return self.send_request(method=\"post\", url=url, data=data, remove_header=remove_header)", "title": ""}
{"_id": "d5519", "text": "def inverseHistogram(hist, bin_range):\n    \"\"\"sample data from given histogram and min, max values within range\n\n    Returns:\n        np.array: data that would create the same histogram as given\n    \"\"\"\n    data = hist.astype(float) / np.min(hist[np.nonzero(hist)])\n    new_data = np.empty(shape=np.sum(data, dtype=int))\n    i = 0\n    xvals = np.linspace(bin_range[0], bin_range[1], len(data))\n    for d, x in zip(data, xvals):\n        new_data[i:i + d] = x\n        i += int(d)\n    return new_data", "title": ""}
{"_id": "d5520", "text": "async def set_http_proxy(cls, url: typing.Optional[str]):\n        \"\"\"See `get_http_proxy`.\"\"\"\n        await cls.set_config(\"http_proxy\", \"\" if url is None else url)", "title": ""}
{"_id": "d5521", "text": "def print_out(self, *lst):\n      \"\"\" Print list of strings to the predefined stdout. \"\"\"\n      self.print2file(self.stdout, True, True, *lst)", "title": ""}
{"_id": "d5522", "text": "def parse_cookies(self, req, name, field):\n        \"\"\"Pull the value from the cookiejar.\"\"\"\n        return core.get_value(req.COOKIES, name, field)", "title": ""}
{"_id": "d5523", "text": "def get_db_version(session):\n    \"\"\"\n    :param session: actually it is a sqlalchemy session\n    :return: version number\n    \"\"\"\n    value = session.query(ProgramInformation.value).filter(ProgramInformation.name == \"db_version\").scalar()\n    return int(value)", "title": ""}
{"_id": "d5524", "text": "def resize_image_to_fit_width(image, dest_w):\n    \"\"\"\n    Resize and image to fit the passed in width, keeping the aspect ratio the same\n\n    :param image: PIL.Image\n    :param dest_w: The desired width\n    \"\"\"\n    scale_factor = dest_w / image.size[0]\n    dest_h = image.size[1] * scale_factor\n    \n    scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)\n\n    return scaled_image", "title": ""}
{"_id": "d5525", "text": "def _rnd_datetime(self, start, end):\n        \"\"\"Internal random datetime generator.\n        \"\"\"\n        return self.from_utctimestamp(\n            random.randint(\n                int(self.to_utctimestamp(start)),\n                int(self.to_utctimestamp(end)),\n            )\n        )", "title": ""}
{"_id": "d5526", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d5527", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d5528", "text": "def __getattr__(self, name):\n        \"\"\" For attributes not found in self, redirect\n        to the properties dictionary \"\"\"\n\n        try:\n            return self.__dict__[name]\n        except KeyError:\n            if hasattr(self._properties,name):\n                return getattr(self._properties, name)", "title": ""}
{"_id": "d5529", "text": "def extract_words(lines):\n    \"\"\"\n    Extract from the given iterable of lines the list of words.\n\n    :param lines: an iterable of lines;\n    :return: a generator of words of lines.\n    \"\"\"\n    for line in lines:\n        for word in re.findall(r\"\\w+\", line):\n            yield word", "title": ""}
{"_id": "d5530", "text": "def stats(self):\n        \"\"\"\n        Return a new raw REST interface to stats resources\n\n        :rtype: :py:class:`ns1.rest.stats.Stats`\n        \"\"\"\n        import ns1.rest.stats\n        return ns1.rest.stats.Stats(self.config)", "title": ""}
{"_id": "d5531", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d5532", "text": "def restore_default_settings():\n    \"\"\" Restore settings to default values. \n    \"\"\"\n    global __DEFAULTS\n    __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR\n    __DEFAULTS.SET_SEED = defaults.SET_SEED\n    __DEFAULTS.SEED = defaults.SEED\n    logging.info('Settings reverted to their default values.')", "title": ""}
{"_id": "d5533", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d5534", "text": "def set_mem_per_proc(self, mem_mb):\n        \"\"\"Set the memory per process in megabytes\"\"\"\n        super().set_mem_per_proc(mem_mb)\n        self.qparams[\"mem_per_cpu\"] = self.mem_per_proc", "title": ""}
{"_id": "d5535", "text": "def logout():\n    \"\"\" Log out the active user\n    \"\"\"\n    flogin.logout_user()\n    next = flask.request.args.get('next')\n    return flask.redirect(next or flask.url_for(\"user\"))", "title": ""}
{"_id": "d5536", "text": "def dict_pick(dictionary, allowed_keys):\n    \"\"\"\n    Return a dictionary only with keys found in `allowed_keys`\n    \"\"\"\n    return {key: value for key, value in viewitems(dictionary) if key in allowed_keys}", "title": ""}
{"_id": "d5537", "text": "def normalize_matrix(matrix):\n  \"\"\"Fold all values of the matrix into [0, 1].\"\"\"\n  abs_matrix = np.abs(matrix.copy())\n  return abs_matrix / abs_matrix.max()", "title": ""}
{"_id": "d5538", "text": "def click(self):\n        \"\"\"Click the element\n\n        :returns: page element instance\n        \"\"\"\n        try:\n            self.wait_until_clickable().web_element.click()\n        except StaleElementReferenceException:\n            # Retry if element has changed\n            self.web_element.click()\n        return self", "title": ""}
{"_id": "d5539", "text": "def standard_db_name(file_column_name):\n    \"\"\"return a standard name by following rules:\n    1. find all regular expression partners ((IDs)|(ID)|([A-Z][a-z]+)|([A-Z]{2,}))\n    2. lower very part and join again with _\n    This method is only used if values in table[model]['columns'] are str\n\n    :param str file_column_name: name of column in file\n    :return: standard name\n    :rtype: str\n    \"\"\"\n    found = id_re.findall(file_column_name)\n\n    if not found:\n        return file_column_name\n\n    return '_'.join(x[0].lower() for x in found)", "title": ""}
{"_id": "d5540", "text": "def index(m, val):\n    \"\"\"\n    Return the indices of all the ``val`` in ``m``\n    \"\"\"\n    mm = np.array(m)\n    idx_tuple = np.where(mm == val)\n    idx = idx_tuple[0].tolist()\n\n    return idx", "title": ""}
{"_id": "d5541", "text": "def cleanup_nodes(doc):\n    \"\"\"\n    Remove text nodes containing only whitespace\n    \"\"\"\n    for node in doc.documentElement.childNodes:\n        if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():\n            doc.documentElement.removeChild(node)\n    return doc", "title": ""}
{"_id": "d5542", "text": "def edge_index(self):\n        \"\"\"A map to look up the index of a edge\"\"\"\n        return dict((edge, index) for index, edge in enumerate(self.edges))", "title": ""}
{"_id": "d5543", "text": "def rm_empty_indices(*args):\n    \"\"\"\n    Remove unwanted list indices. First argument is the list\n    of indices to remove. Other elements are the lists\n    to trim.\n    \"\"\"\n    rm_inds = args[0]\n\n    if not rm_inds:\n        return args[1:]\n\n    keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n    return [[a[i] for i in keep_inds] for a in args[1:]]", "title": ""}
{"_id": "d5544", "text": "def get_size(objects):\n    \"\"\"Compute the total size of all elements in objects.\"\"\"\n    res = 0\n    for o in objects:\n        try:\n            res += _getsizeof(o)\n        except AttributeError:\n            print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n    return res", "title": ""}
{"_id": "d5545", "text": "def _delete_keys(dct, keys):\n    \"\"\"Returns a copy of dct without `keys` keys\n    \"\"\"\n    c = deepcopy(dct)\n    assert isinstance(keys, list)\n    for k in keys:\n        c.pop(k)\n    return c", "title": ""}
{"_id": "d5546", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d5547", "text": "def remove_instance(self, item):\n        \"\"\"Remove `instance` from model\"\"\"\n        self.instances.remove(item)\n        self.remove_item(item)", "title": ""}
{"_id": "d5548", "text": "def success_response(**data):\n    \"\"\"Return a generic success response.\"\"\"\n    data_out = {}\n    data_out[\"status\"] = \"success\"\n    data_out.update(data)\n    js = dumps(data_out, default=date_handler)\n    return Response(js, status=200, mimetype=\"application/json\")", "title": ""}
{"_id": "d5549", "text": "def remove_punctuation(text, exceptions=[]):\n    \"\"\"\n    Return a string with punctuation removed.\n\n    Parameters:\n        text (str): The text to remove punctuation from.\n        exceptions (list): List of symbols to keep in the given text.\n\n    Return:\n        str: The input text without the punctuation.\n    \"\"\"\n\n    all_but = [\n        r'\\w',\n        r'\\s'\n    ]\n\n    all_but.extend(exceptions)\n\n    pattern = '[^{}]'.format(''.join(all_but))\n\n    return re.sub(pattern, '', text)", "title": ""}
{"_id": "d5550", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d5551", "text": "def wordify(text):\n    \"\"\"Generate a list of words given text, removing punctuation.\n\n    Parameters\n    ----------\n    text : unicode\n        A piece of english text.\n\n    Returns\n    -------\n    words : list\n        List of words.\n    \"\"\"\n    stopset = set(nltk.corpus.stopwords.words('english'))\n    tokens = nltk.WordPunctTokenizer().tokenize(text)\n    return [w for w in tokens if w not in stopset]", "title": ""}
{"_id": "d5552", "text": "def copy_to_temp(object):\n    \"\"\"\n    Copy file-like object to temp file and return\n    path.\n    \"\"\"\n    temp_file = NamedTemporaryFile(delete=False)\n    _copy_and_close(object, temp_file)\n    return temp_file.name", "title": ""}
{"_id": "d5553", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d5554", "text": "def home():\n    \"\"\"Temporary helper function to link to the API routes\"\"\"\n    return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \\\n        HTTPStatus.OK", "title": ""}
{"_id": "d5555", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d5556", "text": "def get_short_url(self):\n        \"\"\" Returns short version of topic url (without page number) \"\"\"\n        return reverse('post_short_url', args=(self.forum.slug, self.slug, self.id))", "title": ""}
{"_id": "d5557", "text": "def text_cleanup(data, key, last_type):\n    \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data", "title": ""}
{"_id": "d5558", "text": "def rotateImage(img, angle):\n    \"\"\"\n\n    querries scipy.ndimage.rotate routine\n    :param img: image to be rotated\n    :param angle: angle to be rotated (radian)\n    :return: rotated image\n    \"\"\"\n    imgR = scipy.ndimage.rotate(img, angle, reshape=False)\n    return imgR", "title": ""}
{"_id": "d5559", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d5560", "text": "def R_rot_3d(th):\n    \"\"\"Return a 3-dimensional rotation matrix.\n\n    Parameters\n    ----------\n    th: array, shape (n, 3)\n        Angles about which to rotate along each axis.\n\n    Returns\n    -------\n    R: array, shape (n, 3, 3)\n    \"\"\"\n    sx, sy, sz = np.sin(th).T\n    cx, cy, cz = np.cos(th).T\n    R = np.empty((len(th), 3, 3), dtype=np.float)\n\n    R[:, 0, 0] = cy * cz\n    R[:, 0, 1] = -cy * sz\n    R[:, 0, 2] = sy\n\n    R[:, 1, 0] = sx * sy * cz + cx * sz\n    R[:, 1, 1] = -sx * sy * sz + cx * cz\n    R[:, 1, 2] = -sx * cy\n\n    R[:, 2, 0] = -cx * sy * cz + sx * sz\n    R[:, 2, 1] = cx * sy * sz + sx * cz\n    R[:, 2, 2] = cx * cy\n    return R", "title": ""}
{"_id": "d5561", "text": "def replace(s, replace):\n    \"\"\"Replace multiple values in a string\"\"\"\n    for r in replace:\n        s = s.replace(*r)\n    return s", "title": ""}
{"_id": "d5562", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d5563", "text": "def convert(name):\n    \"\"\"Convert CamelCase to underscore\n\n    Parameters\n    ----------\n    name : str\n        Camelcase string\n\n    Returns\n    -------\n    name : str\n        Converted name\n    \"\"\" \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()", "title": ""}
{"_id": "d5564", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d5565", "text": "def get_rounded(self, digits):\n        \"\"\" Return a vector with the elements rounded to the given number of digits. \"\"\"\n        result = self.copy()\n        result.round(digits)\n        return result", "title": ""}
{"_id": "d5566", "text": "def to_comment(value):\n  \"\"\"\n  Builds a comment.\n  \"\"\"\n  if value is None:\n    return\n  if len(value.split('\\n')) == 1:\n    return \"* \" + value\n  else:\n    return '\\n'.join([' * ' + l for l in value.split('\\n')[:-1]])", "title": ""}
{"_id": "d5567", "text": "def managepy(cmd, extra=None):\n    \"\"\"Run manage.py using this component's specific Django settings\"\"\"\n\n    extra = extra.split() if extra else []\n    run_django_cli(['invoke', cmd] + extra)", "title": ""}
{"_id": "d5568", "text": "def retrieve_by_id(self, id_):\n        \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n        items_with_id = [item for item in self if item.id == int(id_)]\n        if len(items_with_id) == 1:\n            return items_with_id[0].retrieve()", "title": ""}
{"_id": "d5569", "text": "def find_first_number(ll):\n    \"\"\" Returns nr of first entry parseable to float in ll, None otherwise\"\"\"\n    for nr, entry in enumerate(ll):\n        try:\n            float(entry)\n        except (ValueError, TypeError) as e:\n            pass\n        else:\n            return nr\n    return None", "title": ""}
{"_id": "d5570", "text": "def start(self):\n        \"\"\"Create a background thread for httpd and serve 'forever'\"\"\"\n        self._process = threading.Thread(target=self._background_runner)\n        self._process.start()", "title": ""}
{"_id": "d5571", "text": "def str_from_file(path):\n    \"\"\"\n    Return file contents as string.\n\n    \"\"\"\n    with open(path) as f:\n        s = f.read().strip()\n    return s", "title": ""}
{"_id": "d5572", "text": "def execute_in_background(self):\n        \"\"\"Executes a (shell) command in the background\n\n        :return: the process' pid\n        \"\"\"\n        # http://stackoverflow.com/questions/1605520\n        args = shlex.split(self.cmd)\n        p = Popen(args)\n        return p.pid", "title": ""}
{"_id": "d5573", "text": "def unique_items(seq):\n    \"\"\"Return the unique items from iterable *seq* (in order).\"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d5574", "text": "def stop_server(self):\n        \"\"\"\n        Stop receiving connections, wait for all tasks to end, and then \n        terminate the server.\n        \"\"\"\n        self.stop = True\n        while self.task_count:\n            time.sleep(END_RESP)\n        self.terminate = True", "title": ""}
{"_id": "d5575", "text": "def sort_nicely(l):\n    \"\"\"Sort the given list in the way that humans expect.\"\"\"\n    convert = lambda text: int(text) if text.isdigit() else text\n    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]\n    l.sort(key=alphanum_key)", "title": ""}
{"_id": "d5576", "text": "def is_writable_by_others(filename):\n    \"\"\"Check if file or directory is world writable.\"\"\"\n    mode = os.stat(filename)[stat.ST_MODE]\n    return mode & stat.S_IWOTH", "title": ""}
{"_id": "d5577", "text": "def round_to_n(x, n):\n    \"\"\"\n    Round to sig figs\n    \"\"\"\n    return round(x, -int(np.floor(np.log10(x))) + (n - 1))", "title": ""}
{"_id": "d5578", "text": "def save_dict_to_file(filename, dictionary):\n  \"\"\"Saves dictionary as CSV file.\"\"\"\n  with open(filename, 'w') as f:\n    writer = csv.writer(f)\n    for k, v in iteritems(dictionary):\n      writer.writerow([str(k), str(v)])", "title": ""}
{"_id": "d5579", "text": "def clean_float(v):\n    \"\"\"Remove commas from a float\"\"\"\n\n    if v is None or not str(v).strip():\n        return None\n\n    return float(str(v).replace(',', ''))", "title": ""}
{"_id": "d5580", "text": "def write(self):\n        \"\"\"Write content back to file.\"\"\"\n        with open(self.path, 'w') as file_:\n            file_.write(self.content)", "title": ""}
{"_id": "d5581", "text": "def get_func_posargs_name(f):\n    \"\"\"Returns the name of the function f's keyword argument parameter if it exists, otherwise None\"\"\"\n    sigparams = inspect.signature(f).parameters\n    for p in sigparams:\n        if sigparams[p].kind == inspect.Parameter.VAR_POSITIONAL:\n            return sigparams[p].name\n    return None", "title": ""}
{"_id": "d5582", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d5583", "text": "def _summarize_object_type(model):\n    \"\"\"\n        This function returns the summary for a given model\n    \"\"\"\n    # the fields for the service's model\n    model_fields = {field.name: field for field in list(model.fields())}\n    # summarize the model\n    return {\n        'fields': [{\n            'name': key,\n            'type': type(convert_peewee_field(value)).__name__\n            } for key, value in model_fields.items()\n        ]\n    }", "title": ""}
{"_id": "d5584", "text": "def _get_random_id():\n    \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n    symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(symbols) for _ in range(15))", "title": ""}
{"_id": "d5585", "text": "def get_list_dimensions(_list):\n    \"\"\"\n    Takes a nested list and returns the size of each dimension followed\n    by the element type in the list\n    \"\"\"\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []", "title": ""}
{"_id": "d5586", "text": "def fetch_hg_push_log(repo_name, repo_url):\n    \"\"\"\n    Run a HgPushlog etl process\n    \"\"\"\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)", "title": ""}
{"_id": "d5587", "text": "def main():\n    \"\"\"\n    Commandline interface to average parameters.\n    \"\"\"\n    setup_main_logger(console=True, file_logging=False)\n    params = argparse.ArgumentParser(description=\"Averages parameters from multiple models.\")\n    arguments.add_average_args(params)\n    args = params.parse_args()\n    average_parameters(args)", "title": ""}
{"_id": "d5588", "text": "def service_available(service_name):\n    \"\"\"Determine whether a system service is available\"\"\"\n    try:\n        subprocess.check_output(\n            ['service', service_name, 'status'],\n            stderr=subprocess.STDOUT).decode('UTF-8')\n    except subprocess.CalledProcessError as e:\n        return b'unrecognized service' not in e.output\n    else:\n        return True", "title": ""}
{"_id": "d5589", "text": "def update_cursor_position(self, line, index):\n        \"\"\"Update cursor position.\"\"\"\n        value = 'Line {}, Col {}'.format(line + 1, index + 1)\n        self.set_value(value)", "title": ""}
{"_id": "d5590", "text": "def demo(quiet, shell, speed, prompt, commentecho):\n    \"\"\"Run a demo doitlive session.\"\"\"\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    )", "title": ""}
{"_id": "d5591", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d5592", "text": "def scroll_element_into_view(self):\n        \"\"\"Scroll element into view\n\n        :returns: page element instance\n        \"\"\"\n        x = self.web_element.location['x']\n        y = self.web_element.location['y']\n        self.driver.execute_script('window.scrollTo({0}, {1})'.format(x, y))\n        return self", "title": ""}
{"_id": "d5593", "text": "def set_font_size(self, size):\n        \"\"\"Convenience method for just changing font size.\"\"\"\n        if self.font.font_size == size:\n            pass\n        else:\n            self.font._set_size(size)", "title": ""}
{"_id": "d5594", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d5595", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d5596", "text": "def send(r, stream=False):\n    \"\"\"Just sends the request using its send method and returns its response.  \"\"\"\n    r.send(stream=stream)\n    return r.response", "title": ""}
{"_id": "d5597", "text": "def _position():\n    \"\"\"Returns the current xy coordinates of the mouse cursor as a two-integer\n    tuple by calling the GetCursorPos() win32 function.\n\n    Returns:\n      (x, y) tuple of the current xy coordinates of the mouse cursor.\n    \"\"\"\n\n    cursor = POINT()\n    ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))\n    return (cursor.x, cursor.y)", "title": ""}
{"_id": "d5598", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d5599", "text": "def finished(self):\n        \"\"\"\n        Must be called to print final progress label.\n        \"\"\"\n        self.progress_bar.set_state(ProgressBar.STATE_DONE)\n        self.progress_bar.show()", "title": ""}
{"_id": "d5600", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d5601", "text": "def _help():\n    \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n    statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n    print statement.strip()", "title": ""}
{"_id": "d5602", "text": "def na_if(series, *values):\n    \"\"\"\n    If values in a series match a specified value, change them to `np.nan`.\n\n    Args:\n        series: Series or vector, often symbolic.\n        *values: Value(s) to convert to `np.nan` in the series.\n    \"\"\"\n\n    series = pd.Series(series)\n    series[series.isin(values)] = np.nan\n    return series", "title": ""}
{"_id": "d5603", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d5604", "text": "def python_mime(fn):\n    \"\"\"\n    Decorator, which adds correct MIME type for python source to the decorated\n    bottle API function.\n    \"\"\"\n    @wraps(fn)\n    def python_mime_decorator(*args, **kwargs):\n        response.content_type = \"text/x-python\"\n\n        return fn(*args, **kwargs)\n\n    return python_mime_decorator", "title": ""}
{"_id": "d5605", "text": "def skip(self, n):\n        \"\"\"Skip the specified number of elements in the list.\n\n        If the number skipped is greater than the number of elements in\n        the list, hasNext() becomes false and available() returns zero\n        as there are no more elements to retrieve.\n\n        arg:    n (cardinal): the number of elements to skip\n        *compliance: mandatory -- This method must be implemented.*\n\n        \"\"\"\n        try:\n            self._iter_object.skip(n)\n        except AttributeError:\n            for i in range(0, n):\n                self.next()", "title": ""}
{"_id": "d5606", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d5607", "text": "def getcolslice(self, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1):\n        \"\"\"Get a slice from a table column holding arrays.\n        (see :func:`table.getcolslice`)\"\"\"\n        return self._table.getcolslice(self._column, blc, trc, inc, startrow, nrow, rowincr)", "title": ""}
{"_id": "d5608", "text": "def ylim(self, low, high, index=1):\n        \"\"\"Set yaxis limits.\n\n        Parameters\n        ----------\n        low : number\n        high : number\n        index : int, optional\n\n        Returns\n        -------\n        Chart\n\n        \"\"\"\n        self.layout['yaxis' + str(index)]['range'] = [low, high]\n        return self", "title": ""}
{"_id": "d5609", "text": "def grow_slice(slc, size):\n    \"\"\"\n    Grow a slice object by 1 in each direction without overreaching the list.\n\n    Parameters\n    ----------\n    slc: slice\n        slice object to grow\n    size: int\n        list length\n\n    Returns\n    -------\n    slc: slice\n       extended slice \n\n    \"\"\"\n\n    return slice(max(0, slc.start-1), min(size, slc.stop+1))", "title": ""}
{"_id": "d5610", "text": "def reset(self):\n        \"\"\"Reset analyzer state\n        \"\"\"\n        self.prevframe = None\n        self.wasmoving = False\n        self.t0 = 0\n        self.ismoving = False", "title": ""}
{"_id": "d5611", "text": "def arglexsort(arrays):\n    \"\"\"\n    Returns the indices of the lexicographical sorting\n    order of the supplied arrays.\n    \"\"\"\n    dtypes = ','.join(array.dtype.str for array in arrays)\n    recarray = np.empty(len(arrays[0]), dtype=dtypes)\n    for i, array in enumerate(arrays):\n        recarray['f%s' % i] = array\n    return recarray.argsort()", "title": ""}
{"_id": "d5612", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d5613", "text": "def sort_nicely(l):\n    \"\"\"Sort the given list in the way that humans expect.\"\"\"\n    convert = lambda text: int(text) if text.isdigit() else text\n    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]\n    l.sort(key=alphanum_key)", "title": ""}
{"_id": "d5614", "text": "def test(ctx, all=False, verbose=False):\n    \"\"\"Run the tests.\"\"\"\n    cmd = 'tox' if all else 'py.test'\n    if verbose:\n        cmd += ' -v'\n    return ctx.run(cmd, pty=True).return_code", "title": ""}
{"_id": "d5615", "text": "def sort_data(x, y):\n    \"\"\"Sort the data.\"\"\"\n    xy = sorted(zip(x, y))\n    x, y = zip(*xy)\n    return x, y", "title": ""}
{"_id": "d5616", "text": "def _zerosamestates(self, A):\n        \"\"\"\n        zeros out states that should be identical\n\n        REQUIRED ARGUMENTS\n\n        A: the matrix whose entries are to be zeroed.\n\n        \"\"\"\n\n        for pair in self.samestates:\n            A[pair[0], pair[1]] = 0\n            A[pair[1], pair[0]] = 0", "title": ""}
{"_id": "d5617", "text": "def sort_data(data, cols):\n    \"\"\"Sort `data` rows and order columns\"\"\"\n    return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "title": ""}
{"_id": "d5618", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d5619", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d5620", "text": "def __run(self):\n    \"\"\"Hacked run function, which installs the trace.\"\"\"\n    sys.settrace(self.globaltrace)\n    self.__run_backup()\n    self.run = self.__run_backup", "title": ""}
{"_id": "d5621", "text": "def transpose(table):\n    \"\"\"\n    transpose matrix\n    \"\"\"\n    t = []\n    for i in range(0, len(table[0])):\n        t.append([row[i] for row in table])\n    return t", "title": ""}
{"_id": "d5622", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d5623", "text": "def _split_arrs(array_2d, slices):\n    \"\"\"\n    Equivalent to numpy.split(array_2d, slices),\n    but avoids fancy indexing\n    \"\"\"\n    if len(array_2d) == 0:\n        return np.empty(0, dtype=np.object)\n\n    rtn = np.empty(len(slices) + 1, dtype=np.object)\n    start = 0\n    for i, s in enumerate(slices):\n        rtn[i] = array_2d[start:s]\n        start = s\n    rtn[-1] = array_2d[start:]\n    return rtn", "title": ""}
{"_id": "d5624", "text": "def ynticks(self, nticks, index=1):\n        \"\"\"Set the number of ticks.\"\"\"\n        self.layout['yaxis' + str(index)]['nticks'] = nticks\n        return self", "title": ""}
{"_id": "d5625", "text": "def normalize_matrix(matrix):\n  \"\"\"Fold all values of the matrix into [0, 1].\"\"\"\n  abs_matrix = np.abs(matrix.copy())\n  return abs_matrix / abs_matrix.max()", "title": ""}
{"_id": "d5626", "text": "def empty(self, start=None, stop=None):\n\t\t\"\"\"Empty the range from start to stop.\n\n\t\tLike delete, but no Error is raised if the entire range isn't mapped.\n\t\t\"\"\"\n\t\tself.set(NOT_SET, start=start, stop=stop)", "title": ""}
{"_id": "d5627", "text": "def stop(pid):\n    \"\"\"Shut down a specific process.\n\n    Args:\n      pid: the pid of the process to shutdown.\n    \"\"\"\n    if psutil.pid_exists(pid):\n      try:\n        p = psutil.Process(pid)\n        p.kill()\n      except Exception:\n        pass", "title": ""}
{"_id": "d5628", "text": "def linebuffered_stdout():\n    \"\"\" Always line buffer stdout so pipes and redirects are CLI friendly. \"\"\"\n    if sys.stdout.line_buffering:\n        return sys.stdout\n    orig = sys.stdout\n    new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors,\n                     line_buffering=True)\n    new.mode = orig.mode\n    return new", "title": ""}
{"_id": "d5629", "text": "def save_session(self, sid, session, namespace=None):\n        \"\"\"Store the user session for a client.\n\n        The only difference with the :func:`socketio.Server.save_session`\n        method is that when the ``namespace`` argument is not given the\n        namespace associated with the class is used.\n        \"\"\"\n        return self.server.save_session(\n            sid, session, namespace=namespace or self.namespace)", "title": ""}
{"_id": "d5630", "text": "def dedupe_list(l):\n    \"\"\"Remove duplicates from a list preserving the order.\n\n    We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n    the order, which hinders testability and does not work for lists with\n    unhashable elements.\n    \"\"\"\n    result = []\n\n    for el in l:\n        if el not in result:\n            result.append(el)\n\n    return result", "title": ""}
{"_id": "d5631", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d5632", "text": "def unique(iterable):\n    \"\"\" Returns a list copy in which each item occurs only once (in-order).\n    \"\"\"\n    seen = set()\n    return [x for x in iterable if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d5633", "text": "def pair_strings_sum_formatter(a, b):\n  \"\"\"\n  Formats the sum of a and b.\n\n  Note\n  ----\n  Both inputs are numbers already converted to strings.\n\n  \"\"\"\n  if b[:1] == \"-\":\n    return \"{0} - {1}\".format(a, b[1:])\n  return \"{0} + {1}\".format(a, b)", "title": ""}
{"_id": "d5634", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d5635", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d5636", "text": "def main(argv, version=DEFAULT_VERSION):\n    \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n    tarball = download_setuptools()\n    _install(tarball, _build_install_args(argv))", "title": ""}
{"_id": "d5637", "text": "def split_comma_argument(comma_sep_str):\n    \"\"\"Split a comma separated option into a list.\"\"\"\n    terms = []\n    for term in comma_sep_str.split(','):\n        if term:\n            terms.append(term)\n    return terms", "title": ""}
{"_id": "d5638", "text": "def _swap_rows(self, i, j):\n        \"\"\"Swap i and j rows\n\n        As the side effect, determinant flips.\n\n        \"\"\"\n\n        L = np.eye(3, dtype='intc')\n        L[i, i] = 0\n        L[j, j] = 0\n        L[i, j] = 1\n        L[j, i] = 1\n        self._L.append(L.copy())\n        self._A = np.dot(L, self._A)", "title": ""}
{"_id": "d5639", "text": "def _sha1_for_file(filename):\n    \"\"\"Return sha1 for contents of filename.\"\"\"\n    with open(filename, \"rb\") as fileobj:\n        contents = fileobj.read()\n        return hashlib.sha1(contents).hexdigest()", "title": ""}
{"_id": "d5640", "text": "def convert_camel_case_to_snake_case(name):\n    \"\"\"Convert CamelCase to snake_case.\"\"\"\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()", "title": ""}
{"_id": "d5641", "text": "def sha1(s):\n    \"\"\" Returns a sha1 of the given string\n    \"\"\"\n    h = hashlib.new('sha1')\n    h.update(s)\n    return h.hexdigest()", "title": ""}
{"_id": "d5642", "text": "def from_years_range(start_year, end_year):\n        \"\"\"Transform a range of years (two ints) to a DateRange object.\"\"\"\n        start = datetime.date(start_year, 1 , 1)\n        end = datetime.date(end_year, 12 , 31)\n        return DateRange(start, end)", "title": ""}
{"_id": "d5643", "text": "def has_virtualenv(self):\n        \"\"\"\n        Returns true if the virtualenv tool is installed.\n        \"\"\"\n        with self.settings(warn_only=True):\n            ret = self.run_or_local('which virtualenv').strip()\n            return bool(ret)", "title": ""}
{"_id": "d5644", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d5645", "text": "def stft(func=None, **kwparams):\n  \"\"\"\n  Short Time Fourier Transform for real data keeping the full FFT block.\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,\n              inverse_transform=lambda *args: numpy.fft.ifft(*args).real)\n\n  See ``stft.base`` docs for more.\n  \"\"\"\n  from numpy.fft import fft, ifft\n  ifft_r = lambda *args: ifft(*args).real\n  return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)", "title": ""}
{"_id": "d5646", "text": "def is_managed():\n    \"\"\"\n    Check if a Django project is being managed with ``manage.py`` or\n    ``django-admin`` scripts\n\n    :return: Check result\n    :rtype: bool\n    \"\"\"\n    for item in sys.argv:\n        if re.search(r'manage.py|django-admin|django', item) is not None:\n            return True\n    return False", "title": ""}
{"_id": "d5647", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d5648", "text": "def timed_call(func, *args, log_level='DEBUG', **kwargs):\n    \"\"\"Logs a function's run time\n\n    :param func: The function to run\n    :param args: The args to pass to the function\n    :param kwargs: The keyword args to pass to the function\n    :param log_level: The log level at which to print the run time\n    :return: The function's return value\n    \"\"\"\n    start = time()\n    r = func(*args, **kwargs)\n    t = time() - start\n    log(log_level, \"Call to '{}' took {:0.6f}s\".format(func.__name__, t))\n    return r", "title": ""}
{"_id": "d5649", "text": "def display_pil_image(im):\n   \"\"\"Displayhook function for PIL Images, rendered as PNG.\"\"\"\n   from IPython.core import display\n   b = BytesIO()\n   im.save(b, format='png')\n   data = b.getvalue()\n\n   ip_img = display.Image(data=data, format='png', embed=True)\n   return ip_img._repr_png_()", "title": ""}
{"_id": "d5650", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d5651", "text": "def signal_handler(signal_name, frame):\n    \"\"\"Quit signal handler.\"\"\"\n    sys.stdout.flush()\n    print(\"\\nSIGINT in frame signal received. Quitting...\")\n    sys.stdout.flush()\n    sys.exit(0)", "title": ""}
{"_id": "d5652", "text": "def get_neg_infinity(dtype):\n    \"\"\"Return an appropriate positive infinity for this dtype.\n\n    Parameters\n    ----------\n    dtype : np.dtype\n\n    Returns\n    -------\n    fill_value : positive infinity value corresponding to this dtype.\n    \"\"\"\n    if issubclass(dtype.type, (np.floating, np.integer)):\n        return -np.inf\n\n    if issubclass(dtype.type, np.complexfloating):\n        return -np.inf - 1j * np.inf\n\n    return NINF", "title": ""}
{"_id": "d5653", "text": "def signal_handler(signal_name, frame):\n    \"\"\"Quit signal handler.\"\"\"\n    sys.stdout.flush()\n    print(\"\\nSIGINT in frame signal received. Quitting...\")\n    sys.stdout.flush()\n    sys.exit(0)", "title": ""}
{"_id": "d5654", "text": "def update_one(self, query, doc):\n        \"\"\"\n        Updates one element of the collection\n\n        :param query: dictionary representing the mongo query\n        :param doc: dictionary representing the item to be updated\n        :return: UpdateResult\n        \"\"\"\n        if self.table is None:\n            self.build_table()\n\n        if u\"$set\" in doc:\n            doc = doc[u\"$set\"]\n\n        allcond = self.parse_query(query)\n\n        try:\n            result = self.table.update(doc, allcond)\n        except:\n            # TODO: check table.update result\n            # check what pymongo does in that case\n            result = None\n\n        return UpdateResult(raw_result=result)", "title": ""}
{"_id": "d5655", "text": "def unescape_all(string):\n    \"\"\"Resolve all html entities to their corresponding unicode character\"\"\"\n    def escape_single(matchobj):\n        return _unicode_for_entity_with_name(matchobj.group(1))\n    return entities.sub(escape_single, string)", "title": ""}
{"_id": "d5656", "text": "def update(self, params):\n        \"\"\"Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device.\n        \"\"\"\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "title": ""}
{"_id": "d5657", "text": "def log_request(self, code='-', size='-'):\n        \"\"\"Selectively log an accepted request.\"\"\"\n\n        if self.server.logRequests:\n            BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)", "title": ""}
{"_id": "d5658", "text": "def update(self, params):\n        \"\"\"Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device.\n        \"\"\"\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "title": ""}
{"_id": "d5659", "text": "def calculate_size(name, timeout):\n    \"\"\" Calculates the request payload size\"\"\"\n    data_size = 0\n    data_size += calculate_size_str(name)\n    data_size += LONG_SIZE_IN_BYTES\n    return data_size", "title": ""}
{"_id": "d5660", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d5661", "text": "def _skip_frame(self):\n        \"\"\"Skip a single frame from the trajectory\"\"\"\n        size = self.read_size()\n        for i in range(size+1):\n            line = self._f.readline()\n            if len(line) == 0:\n                raise StopIteration", "title": ""}
{"_id": "d5662", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d5663", "text": "def _skip_newlines(self):\n        \"\"\"Increment over newlines.\"\"\"\n        while self._cur_token['type'] is TT.lbreak and not self._finished:\n            self._increment()", "title": ""}
{"_id": "d5664", "text": "def filter(self, obj, *args, **kwargs):\n        \"\"\"\n        Filter the given object through the filter chain.\n\n        :param obj: The object to filter\n        :param args: Additional arguments to pass to each filter function.\n        :param kwargs: Additional keyword arguments to pass to each filter\n                       function.\n        :return: The filtered object or :data:`None`\n\n        See the documentation of :class:`Filter` on how filtering operates.\n\n        Returns the object returned by the last function in the filter chain or\n        :data:`None` if any function returned :data:`None`.\n        \"\"\"\n        for _, _, func in self._filter_order:\n            obj = func(obj, *args, **kwargs)\n            if obj is None:\n                return None\n        return obj", "title": ""}
{"_id": "d5665", "text": "def _skip_frame(self):\n        \"\"\"Skip a single frame from the trajectory\"\"\"\n        size = self.read_size()\n        for i in range(size+1):\n            line = self._f.readline()\n            if len(line) == 0:\n                raise StopIteration", "title": ""}
{"_id": "d5666", "text": "def indent(txt, spacing=4):\n    \"\"\"\n    Indent given text using custom spacing, default is set to 4.\n    \"\"\"\n    return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))", "title": ""}
{"_id": "d5667", "text": "def roc_auc(y_true, y_score):\n    \"\"\"\n    Returns are under the ROC curve\n    \"\"\"\n    notnull = ~np.isnan(y_true)\n    fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true[notnull], y_score[notnull])\n    return sklearn.metrics.auc(fpr, tpr)", "title": ""}
{"_id": "d5668", "text": "def write_color(string, name, style='normal', when='auto'):\n    \"\"\" Write the given colored string to standard out. \"\"\"\n    write(color(string, name, style, when))", "title": ""}
{"_id": "d5669", "text": "def NeuralNetLearner(dataset, sizes):\n   \"\"\"Layered feed-forward network.\"\"\"\n\n   activations = map(lambda n: [0.0 for i in range(n)], sizes)\n   weights = []\n\n   def predict(example):\n      unimplemented()\n\n   return predict", "title": ""}
{"_id": "d5670", "text": "def Exponential(x, a, tau, y0):\n    \"\"\"Exponential function\n\n    Inputs:\n    -------\n        ``x``: independent variable\n        ``a``: scaling factor\n        ``tau``: time constant\n        ``y0``: additive constant\n\n    Formula:\n    --------\n        ``a*exp(x/tau)+y0``\n    \"\"\"\n    return np.exp(x / tau) * a + y0", "title": ""}
{"_id": "d5671", "text": "def main(idle):\n    \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n    while True:\n\n        LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n        time.sleep(idle)", "title": ""}
{"_id": "d5672", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d5673", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d5674", "text": "def html_to_text(content):\n    \"\"\" Converts html content to plain text \"\"\"\n    text = None\n    h2t = html2text.HTML2Text()\n    h2t.ignore_links = False\n    text = h2t.handle(content)\n    return text", "title": ""}
{"_id": "d5675", "text": "def is_full_slice(obj, l):\n    \"\"\"\n    We have a full length slice.\n    \"\"\"\n    return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and\n            obj.step is None)", "title": ""}
{"_id": "d5676", "text": "def _re_raise_as(NewExc, *args, **kw):\n    \"\"\"Raise a new exception using the preserved traceback of the last one.\"\"\"\n    etype, val, tb = sys.exc_info()\n    raise NewExc(*args, **kw), None, tb", "title": ""}
{"_id": "d5677", "text": "def partition(a, sz): \n    \"\"\"splits iterables a in equal parts of size sz\"\"\"\n    return [a[i:i+sz] for i in range(0, len(a), sz)]", "title": ""}
{"_id": "d5678", "text": "def alert(text='', title='', button=OK_TEXT, root=None, timeout=None):\n    \"\"\"Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.\"\"\"\n    assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox'\n    return _buttonbox(msg=text, title=title, choices=[str(button)], root=root, timeout=timeout)", "title": ""}
{"_id": "d5679", "text": "def output_scores(self, name=None):\n        \"\"\" Returns: N x #class scores, summed to one for each box.\"\"\"\n        return tf.nn.softmax(self.label_logits, name=name)", "title": ""}
{"_id": "d5680", "text": "def _validate_date_str(str_):\n    \"\"\"Validate str as a date and return string version of date\"\"\"\n\n    if not str_:\n        return None\n\n    # Convert to datetime so we can validate it's a real date that exists then\n    # convert it back to the string.\n    try:\n        date = datetime.strptime(str_, DATE_FMT)\n    except ValueError:\n        msg = 'Invalid date format, should be YYYY-MM-DD'\n        raise argparse.ArgumentTypeError(msg)\n\n    return date.strftime(DATE_FMT)", "title": ""}
{"_id": "d5681", "text": "def sort_by_name(self):\n        \"\"\"Sort list elements by name.\"\"\"\n        super(JSSObjectList, self).sort(key=lambda k: k.name)", "title": ""}
{"_id": "d5682", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d5683", "text": "def _dict_values_sorted_by_key(dictionary):\n    # This should be a yield from instead.\n    \"\"\"Internal helper to return the values of a dictionary, sorted by key.\n    \"\"\"\n    for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):\n        yield value", "title": ""}
{"_id": "d5684", "text": "def normalize_text(text, line_len=80, indent=\"\"):\n    \"\"\"Wrap the text on the given line length.\"\"\"\n    return \"\\n\".join(\n        textwrap.wrap(\n            text, width=line_len, initial_indent=indent, subsequent_indent=indent\n        )\n    )", "title": ""}
{"_id": "d5685", "text": "def sort_by_name(self):\n        \"\"\"Sort list elements by name.\"\"\"\n        super(JSSObjectList, self).sort(key=lambda k: k.name)", "title": ""}
{"_id": "d5686", "text": "def get_rounded(self, digits):\n        \"\"\" Return a vector with the elements rounded to the given number of digits. \"\"\"\n        result = self.copy()\n        result.round(digits)\n        return result", "title": ""}
{"_id": "d5687", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d5688", "text": "def comment (self, s, **args):\n        \"\"\"Write GML comment.\"\"\"\n        self.writeln(s=u'comment \"%s\"' % s, **args)", "title": ""}
{"_id": "d5689", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d5690", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d5691", "text": "def get_join_cols(by_entry):\n  \"\"\" helper function used for joins\n  builds left and right join list for join function\n  \"\"\"\n  left_cols = []\n  right_cols = []\n  for col in by_entry:\n    if isinstance(col, str):\n      left_cols.append(col)\n      right_cols.append(col)\n    else:\n      left_cols.append(col[0])\n      right_cols.append(col[1])\n  return left_cols, right_cols", "title": ""}
{"_id": "d5692", "text": "def split_on(s, sep=\" \"):\n    \"\"\"Split s by sep, unless it's inside a quote.\"\"\"\n    pattern = '''((?:[^%s\"']|\"[^\"]*\"|'[^']*')+)''' % sep\n\n    return [_strip_speechmarks(t) for t in re.split(pattern, s)[1::2]]", "title": ""}
{"_id": "d5693", "text": "def write_tsv_line_from_list(linelist, outfp):\n    \"\"\"Utility method to convert list to tsv line with carriage return\"\"\"\n    line = '\\t'.join(linelist)\n    outfp.write(line)\n    outfp.write('\\n')", "title": ""}
{"_id": "d5694", "text": "def ver_to_tuple(value):\n    \"\"\"\n    Convert version like string to a tuple of integers.\n    \"\"\"\n    return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "title": ""}
{"_id": "d5695", "text": "def pretty_dict_string(d, indent=0):\n    \"\"\"Pretty output of nested dictionaries.\n    \"\"\"\n    s = ''\n    for key, value in sorted(d.items()):\n        s += '    ' * indent + str(key)\n        if isinstance(value, dict):\n             s += '\\n' + pretty_dict_string(value, indent+1)\n        else:\n             s += '=' + str(value) + '\\n'\n    return s", "title": ""}
{"_id": "d5696", "text": "def split_len(s, length):\n    \"\"\"split string *s* into list of strings no longer than *length*\"\"\"\n    return [s[i:i+length] for i in range(0, len(s), length)]", "title": ""}
{"_id": "d5697", "text": "def upoint2exprpoint(upoint):\n    \"\"\"Convert an untyped point into an Expression point.\n\n    .. seealso::\n       For definitions of points and untyped points,\n       see the :mod:`pyeda.boolalg.boolfunc` module.\n    \"\"\"\n    point = dict()\n    for uniqid in upoint[0]:\n        point[_LITS[uniqid]] = 0\n    for uniqid in upoint[1]:\n        point[_LITS[uniqid]] = 1\n    return point", "title": ""}
{"_id": "d5698", "text": "def to_snake_case(s):\n    \"\"\"Converts camel-case identifiers to snake-case.\"\"\"\n    return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)", "title": ""}
{"_id": "d5699", "text": "def logical_or(self, other):\n        \"\"\"logical_or(t) = self(t) or other(t).\"\"\"\n        return self.operation(other, lambda x, y: int(x or y))", "title": ""}
{"_id": "d5700", "text": "def parse_query_string(query):\n    \"\"\"\n    parse_query_string:\n    very simplistic. won't do the right thing with list values\n    \"\"\"\n    result = {}\n    qparts = query.split('&')\n    for item in qparts:\n        key, value = item.split('=')\n        key = key.strip()\n        value = value.strip()\n        result[key] = unquote_plus(value)\n    return result", "title": ""}
{"_id": "d5701", "text": "def get_random_id(length):\n    \"\"\"Generate a random, alpha-numerical id.\"\"\"\n    alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(alphabet) for _ in range(length))", "title": ""}
{"_id": "d5702", "text": "def unescape_all(string):\n    \"\"\"Resolve all html entities to their corresponding unicode character\"\"\"\n    def escape_single(matchobj):\n        return _unicode_for_entity_with_name(matchobj.group(1))\n    return entities.sub(escape_single, string)", "title": ""}
{"_id": "d5703", "text": "def save(self):\n        \"\"\"Saves the updated model to the current entity db.\n        \"\"\"\n        self.session.add(self)\n        self.session.flush()\n        return self", "title": ""}
{"_id": "d5704", "text": "def md_to_text(content):\n    \"\"\" Converts markdown content to text \"\"\"\n    text = None\n    html = markdown.markdown(content)\n    if html:\n        text = html_to_text(content)\n    return text", "title": ""}
{"_id": "d5705", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d5706", "text": "def main(idle):\n    \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n    while True:\n\n        LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n        time.sleep(idle)", "title": ""}
{"_id": "d5707", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d5708", "text": "def _getTypename(self, defn):\n        \"\"\" Returns the SQL typename required to store the given FieldDefinition \"\"\"\n        return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'", "title": ""}
{"_id": "d5709", "text": "def get_last_id(self, cur, table='reaction'):\n        \"\"\"\n        Get the id of the last written row in table\n\n        Parameters\n        ----------\n        cur: database connection().cursor() object\n        table: str\n            'reaction', 'publication', 'publication_system', 'reaction_system'\n\n        Returns: id\n        \"\"\"\n        cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n                    .format(table))\n        result = cur.fetchone()\n        if result is not None:\n            id = result[0]\n        else:\n            id = 0\n        return id", "title": ""}
{"_id": "d5710", "text": "def visit_Str(self, node):\n        \"\"\" Set the pythonic string type. \"\"\"\n        self.result[node] = self.builder.NamedType(pytype_to_ctype(str))", "title": ""}
{"_id": "d5711", "text": "def _plot(self):\n        \"\"\"Plot stacked serie lines and stacked secondary lines\"\"\"\n        for serie in self.series[::-1 if self.stack_from_top else 1]:\n            self.line(serie)\n        for serie in self.secondary_series[::-1 if self.stack_from_top else 1]:\n            self.line(serie, True)", "title": ""}
{"_id": "d5712", "text": "def print(*a):\n    \"\"\" print just one that returns what you give it instead of None \"\"\"\n    try:\n        _print(*a)\n        return a[0] if len(a) == 1 else a\n    except:\n        _print(*a)", "title": ""}
{"_id": "d5713", "text": "def _stdout_raw(self, s):\n        \"\"\"Writes the string to stdout\"\"\"\n        print(s, end='', file=sys.stdout)\n        sys.stdout.flush()", "title": ""}
{"_id": "d5714", "text": "def validate_args(**args):\n\t\"\"\"\n\tfunction to check if input query is not None \n\tand set missing arguments to default value\n\t\"\"\"\n\tif not args['query']:\n\t\tprint(\"\\nMissing required query argument.\")\n\t\tsys.exit()\n\n\tfor key in DEFAULTS:\n\t\tif key not in args:\n\t\t\targs[key] = DEFAULTS[key]\n\n\treturn args", "title": ""}
{"_id": "d5715", "text": "def stop(self, reason=None):\n        \"\"\"Shutdown the service with a reason.\"\"\"\n        self.logger.info('stopping')\n        self.loop.stop(pyev.EVBREAK_ALL)", "title": ""}
{"_id": "d5716", "text": "def jaccard(c_1, c_2):\n    \"\"\"\n    Calculates the Jaccard similarity between two sets of nodes. Called by mroc.\n\n    Inputs:  - c_1: Community (set of nodes) 1.\n             - c_2: Community (set of nodes) 2.\n\n    Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.\n    \"\"\"\n    nom = np.intersect1d(c_1, c_2).size\n    denom = np.union1d(c_1, c_2).size\n    return nom/denom", "title": ""}
{"_id": "d5717", "text": "def MultiArgMax(x):\n  \"\"\"\n  Get tuple (actually a generator) of indices where the max value of\n  array x occurs. Requires that x have a max() method, as x.max()\n  (in the case of NumPy) is much faster than max(x).\n  For a simpler, faster argmax when there is only a single maximum entry,\n  or when knowing only the first index where the maximum occurs,\n  call argmax() on a NumPy array.\n\n  :param x: Any sequence that has a max() method.\n  :returns: Generator with the indices where the max value occurs.\n  \"\"\"\n  m = x.max()\n  return (i for i, v in enumerate(x) if v == m)", "title": ""}
{"_id": "d5718", "text": "def _encode_gif(images, fps):\n  \"\"\"Encodes numpy images into gif string.\n\n  Args:\n    images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape\n      `[time, height, width, channels]` where `channels` is 1 or 3.\n    fps: frames per second of the animation\n\n  Returns:\n    The encoded gif string.\n\n  Raises:\n    IOError: If the ffmpeg command returns an error.\n  \"\"\"\n  writer = WholeVideoWriter(fps)\n  writer.write_multi(images)\n  return writer.finish()", "title": ""}
{"_id": "d5719", "text": "def load_logged_in_user():\n    \"\"\"If a user id is stored in the session, load the user object from\n    the database into ``g.user``.\"\"\"\n    user_id = session.get(\"user_id\")\n    g.user = User.query.get(user_id) if user_id is not None else None", "title": ""}
{"_id": "d5720", "text": "def get_last_id(self, cur, table='reaction'):\n        \"\"\"\n        Get the id of the last written row in table\n\n        Parameters\n        ----------\n        cur: database connection().cursor() object\n        table: str\n            'reaction', 'publication', 'publication_system', 'reaction_system'\n\n        Returns: id\n        \"\"\"\n        cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n                    .format(table))\n        result = cur.fetchone()\n        if result is not None:\n            id = result[0]\n        else:\n            id = 0\n        return id", "title": ""}
{"_id": "d5721", "text": "def u2b(string):\n    \"\"\" unicode to bytes\"\"\"\n    if ((PY2 and isinstance(string, unicode)) or\n        ((not PY2) and isinstance(string, str))):\n        return string.encode('utf-8')\n    return string", "title": ""}
{"_id": "d5722", "text": "def _create_complete_graph(node_ids):\n    \"\"\"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)\n    \"\"\"\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", "title": ""}
{"_id": "d5723", "text": "def strip_spaces(x):\n    \"\"\"\n    Strips spaces\n    :param x:\n    :return:\n    \"\"\"\n    x = x.replace(b' ', b'')\n    x = x.replace(b'\\t', b'')\n    return x", "title": ""}
{"_id": "d5724", "text": "def pop (self, key):\n        \"\"\"Remove key from dict and return value.\"\"\"\n        if key in self._keys:\n            self._keys.remove(key)\n        super(ListDict, self).pop(key)", "title": ""}
{"_id": "d5725", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d5726", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d5727", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d5728", "text": "def scale_image(image, new_width):\n    \"\"\"Resizes an image preserving the aspect ratio.\n    \"\"\"\n    (original_width, original_height) = image.size\n    aspect_ratio = original_height/float(original_width)\n    new_height = int(aspect_ratio * new_width)\n\n    # This scales it wider than tall, since characters are biased\n    new_image = image.resize((new_width*2, new_height))\n    return new_image", "title": ""}
{"_id": "d5729", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d5730", "text": "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)", "title": ""}
{"_id": "d5731", "text": "def us2mc(string):\n    \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)", "title": ""}
{"_id": "d5732", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d5733", "text": "def _xls2col_widths(self, worksheet, tab):\n        \"\"\"Updates col_widths in code_array\"\"\"\n\n        for col in xrange(worksheet.ncols):\n            try:\n                xls_width = worksheet.colinfo_map[col].width\n                pys_width = self.xls_width2pys_width(xls_width)\n                self.code_array.col_widths[col, tab] = pys_width\n\n            except KeyError:\n                pass", "title": ""}
{"_id": "d5734", "text": "def getEventTypeNameFromEnum(self, eType):\n        \"\"\"returns the name of an EVREvent enum value\"\"\"\n\n        fn = self.function_table.getEventTypeNameFromEnum\n        result = fn(eType)\n        return result", "title": ""}
{"_id": "d5735", "text": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"React to a docstring event and append contracts to it.\"\"\"\n    # pylint: disable=unused-argument\n    # pylint: disable=too-many-arguments\n    lines.extend(_format_contracts(what=what, obj=obj))", "title": ""}
{"_id": "d5736", "text": "def timestamp_to_microseconds(timestamp):\n    \"\"\"Convert a timestamp string into a microseconds value\n    :param timestamp\n    :return time in microseconds\n    \"\"\"\n    timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX)\n    epoch_time_secs = calendar.timegm(timestamp_str.timetuple())\n    epoch_time_mus = epoch_time_secs * 1e6 + timestamp_str.microsecond\n    return epoch_time_mus", "title": ""}
{"_id": "d5737", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d5738", "text": "def FromString(s, **kwargs):\n    \"\"\"Like FromFile, but takes a string.\"\"\"\n    \n    f = StringIO.StringIO(s)\n    return FromFile(f, **kwargs)", "title": ""}
{"_id": "d5739", "text": "def findLastCharIndexMatching(text, func):\n    \"\"\" Return index of last character in string for which func(char) evaluates to True. \"\"\"\n    for i in range(len(text) - 1, -1, -1):\n      if func(text[i]):\n        return i", "title": ""}
{"_id": "d5740", "text": "def FromString(s, **kwargs):\n    \"\"\"Like FromFile, but takes a string.\"\"\"\n    \n    f = StringIO.StringIO(s)\n    return FromFile(f, **kwargs)", "title": ""}
{"_id": "d5741", "text": "def MultiArgMax(x):\n  \"\"\"\n  Get tuple (actually a generator) of indices where the max value of\n  array x occurs. Requires that x have a max() method, as x.max()\n  (in the case of NumPy) is much faster than max(x).\n  For a simpler, faster argmax when there is only a single maximum entry,\n  or when knowing only the first index where the maximum occurs,\n  call argmax() on a NumPy array.\n\n  :param x: Any sequence that has a max() method.\n  :returns: Generator with the indices where the max value occurs.\n  \"\"\"\n  m = x.max()\n  return (i for i, v in enumerate(x) if v == m)", "title": ""}
{"_id": "d5742", "text": "def drop_bad_characters(text):\n    \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n    also any whitespace characters that aren't space.\n\n    :arg str text: the text to fix\n\n    :returns: text with all bad characters dropped\n\n    \"\"\"\n    # Strip all non-ascii and non-printable characters\n    text = ''.join([c for c in text if c in ALLOWED_CHARS])\n    return text", "title": ""}
{"_id": "d5743", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d5744", "text": "def RoundToSeconds(cls, timestamp):\n    \"\"\"Takes a timestamp value and rounds it to a second precision.\"\"\"\n    leftovers = timestamp % definitions.MICROSECONDS_PER_SECOND\n    scrubbed = timestamp - leftovers\n    rounded = round(float(leftovers) / definitions.MICROSECONDS_PER_SECOND)\n\n    return int(scrubbed + rounded * definitions.MICROSECONDS_PER_SECOND)", "title": ""}
{"_id": "d5745", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d5746", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d5747", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d5748", "text": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "title": ""}
{"_id": "d5749", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d5750", "text": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "title": ""}
{"_id": "d5751", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d5752", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d5753", "text": "def camelcase(string):\n    \"\"\" Convert string into camel case.\n\n    Args:\n        string: String to convert.\n\n    Returns:\n        string: Camel case string.\n\n    \"\"\"\n\n    string = re.sub(r\"^[\\-_\\.]\", '', str(string))\n    if not string:\n        return string\n    return lowercase(string[0]) + re.sub(r\"[\\-_\\.\\s]([a-z])\", lambda matched: uppercase(matched.group(1)), string[1:])", "title": ""}
{"_id": "d5754", "text": "def asin(x):\n    \"\"\"\n    Inverse sine\n    \"\"\"\n    if isinstance(x, UncertainFunction):\n        mcpts = np.arcsin(x._mcpts)\n        return UncertainFunction(mcpts)\n    else:\n        return np.arcsin(x)", "title": ""}
{"_id": "d5755", "text": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "title": ""}
{"_id": "d5756", "text": "def synchronized(obj):\n  \"\"\"\n  This function has two purposes:\n\n  1. Decorate a function that automatically synchronizes access to the object\n     passed as the first argument (usually `self`, for member methods)\n  2. Synchronize access to the object, used in a `with`-statement.\n\n  Note that you can use #wait(), #notify() and #notify_all() only on\n  synchronized objects.\n\n  # Example\n  ```python\n  class Box(Synchronizable):\n    def __init__(self):\n      self.value = None\n    @synchronized\n    def get(self):\n      return self.value\n    @synchronized\n    def set(self, value):\n      self.value = value\n\n  box = Box()\n  box.set('foobar')\n  with synchronized(box):\n    box.value = 'taz\\'dingo'\n  print(box.get())\n  ```\n\n  # Arguments\n  obj (Synchronizable, function): The object to synchronize access to, or a\n    function to decorate.\n\n  # Returns\n  1. The decorated function.\n  2. The value of `obj.synchronizable_condition`, which should implement the\n     context-manager interface (to be used in a `with`-statement).\n  \"\"\"\n\n  if hasattr(obj, 'synchronizable_condition'):\n    return obj.synchronizable_condition\n  elif callable(obj):\n    @functools.wraps(obj)\n    def wrapper(self, *args, **kwargs):\n      with self.synchronizable_condition:\n        return obj(self, *args, **kwargs)\n    return wrapper\n  else:\n    raise TypeError('expected Synchronizable instance or callable to decorate')", "title": ""}
{"_id": "d5757", "text": "def main(filename):\n    \"\"\"\n    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.\n    \"\"\"\n\n    # Prepare font.\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\n    # Initialize PDF document on a stream.\n    with Document('output.pdf') as document:\n\n        # Initialize a new page and begin its context.\n        with document.Page() as ctx:\n\n            # Open the image to embed.\n            with Image(filename) as embed:\n\n                # Set the media box for the page to the same as the\n                # image to embed.\n                ctx.box = embed.box\n\n                # Embed the image.\n                ctx.embed(embed)\n\n            # Write some text.\n            ctx.add(Text('Hello World', font, size=14, x=100, y=60))", "title": ""}
{"_id": "d5758", "text": "def runcoro(async_function):\n    \"\"\"\n    Runs an asynchronous function without needing to use await - useful for lambda\n\n    Args:\n        async_function (Coroutine): The asynchronous function to run\n    \"\"\"\n\n    future = _asyncio.run_coroutine_threadsafe(async_function, client.loop)\n    result = future.result()\n    return result", "title": ""}
{"_id": "d5759", "text": "def setencoding():\n    \"\"\"Set the string encoding used by the Unicode implementation.  The\n    default is 'ascii', but if you're willing to experiment, you can\n    change this.\"\"\"\n    encoding = \"ascii\" # Default value set by _PyUnicode_Init()\n    if 0:\n        # Enable to support locale aware default string encodings.\n        import locale\n        loc = locale.getdefaultlocale()\n        if loc[1]:\n            encoding = loc[1]\n    if 0:\n        # Enable to switch off string to Unicode coercion and implicit\n        # Unicode to string conversion.\n        encoding = \"undefined\"\n    if encoding != \"ascii\":\n        # On Non-Unicode builds this will raise an AttributeError...\n        sys.setdefaultencoding(encoding)", "title": ""}
{"_id": "d5760", "text": "def lin_interp(x, rangeX, rangeY):\n    \"\"\"\n    Interpolate linearly variable x in rangeX onto rangeY.\n    \"\"\"\n    s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])\n    y = rangeY[0] * (1 - s) + rangeY[1] * s\n    return y", "title": ""}
{"_id": "d5761", "text": "def pass_from_pipe(cls):\n        \"\"\"Return password from pipe if not on TTY, else False.\n        \"\"\"\n        is_pipe = not sys.stdin.isatty()\n        return is_pipe and cls.strip_last_newline(sys.stdin.read())", "title": ""}
{"_id": "d5762", "text": "def lin_interp(x, rangeX, rangeY):\n    \"\"\"\n    Interpolate linearly variable x in rangeX onto rangeY.\n    \"\"\"\n    s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])\n    y = rangeY[0] * (1 - s) + rangeY[1] * s\n    return y", "title": ""}
{"_id": "d5763", "text": "def post_worker_init(worker):\n    \"\"\"Hook into Gunicorn to display message after launching.\n\n    This mimics the behaviour of Django's stock runserver command.\n    \"\"\"\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    )", "title": ""}
{"_id": "d5764", "text": "def unique_everseen(iterable, filterfalse_=itertools.filterfalse):\n    \"\"\"Unique elements, preserving order.\"\"\"\n    # Itertools recipes:\n    # https://docs.python.org/3/library/itertools.html#itertools-recipes\n    seen = set()\n    seen_add = seen.add\n    for element in filterfalse_(seen.__contains__, iterable):\n        seen_add(element)\n        yield element", "title": ""}
{"_id": "d5765", "text": "def findMax(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMax(arr, out)\n    return out", "title": ""}
{"_id": "d5766", "text": "def raw_print(*args, **kw):\n    \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()", "title": ""}
{"_id": "d5767", "text": "def file_found(filename,force):\n    \"\"\"Check if a file exists\"\"\"\n    if os.path.exists(filename) and not force:\n        logger.info(\"Found %s; skipping...\"%filename)\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d5768", "text": "def specialRound(number, rounding):\n    \"\"\"A method used to round a number in the way that UsefulUtils rounds.\"\"\"\n    temp = 0\n    if rounding == 0:\n        temp = number\n    else:\n        temp =  round(number, rounding)\n    if temp % 1 == 0:\n        return int(temp)\n    else:\n        return float(temp)", "title": ""}
{"_id": "d5769", "text": "def _request_limit_reached(exception):\n    \"\"\" Checks if exception was raised because of too many executed requests. (This is a temporal solution and\n    will be changed in later package versions.)\n\n    :param exception: Exception raised during download\n    :type exception: Exception\n    :return: True if exception is caused because too many requests were executed at once and False otherwise\n    :rtype: bool\n    \"\"\"\n    return isinstance(exception, requests.HTTPError) and \\\n        exception.response.status_code == requests.status_codes.codes.TOO_MANY_REQUESTS", "title": ""}
{"_id": "d5770", "text": "def bash(filename):\n    \"\"\"Runs a bash script in the local directory\"\"\"\n    sys.stdout.flush()\n    subprocess.call(\"bash {}\".format(filename), shell=True)", "title": ""}
{"_id": "d5771", "text": "def _platform_is_windows(platform=sys.platform):\n        \"\"\"Is the current OS a Windows?\"\"\"\n        matched = platform in ('cygwin', 'win32', 'win64')\n        if matched:\n            error_msg = \"Windows isn't supported yet\"\n            raise OSError(error_msg)\n        return matched", "title": ""}
{"_id": "d5772", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d5773", "text": "def get_tensor_device(self, tensor_name):\n    \"\"\"The device of a tensor.\n\n    Note that only tf tensors have device assignments.\n\n    Args:\n      tensor_name: a string, name of a tensor in the graph.\n\n    Returns:\n      a string or None, representing the device name.\n    \"\"\"\n    tensor = self._name_to_tensor(tensor_name)\n    if isinstance(tensor, tf.Tensor):\n      return tensor.device\n    else:  # mtf.Tensor\n      return None", "title": ""}
{"_id": "d5774", "text": "def mask_nonfinite(self):\n        \"\"\"Extend the mask with the image elements where the intensity is NaN.\"\"\"\n        self.mask = np.logical_and(self.mask, (np.isfinite(self.intensity)))", "title": ""}
{"_id": "d5775", "text": "def sg_init(sess):\n    r\"\"\" Initializes session variables.\n    \n    Args:\n      sess: Session to initialize. \n    \"\"\"\n    # initialize variables\n    sess.run(tf.group(tf.global_variables_initializer(),\n                      tf.local_variables_initializer()))", "title": ""}
{"_id": "d5776", "text": "async def iso(self, source):\n        \"\"\"Convert to timestamp.\"\"\"\n        from datetime import datetime\n        unix_timestamp = int(source)\n        return datetime.fromtimestamp(unix_timestamp).isoformat()", "title": ""}
{"_id": "d5777", "text": "def main(args):\n    \"\"\"\n    invoke wptools and exit safely\n    \"\"\"\n    start = time.time()\n    output = get(args)\n    _safe_exit(start, output)", "title": ""}
{"_id": "d5778", "text": "def chunks(iterable, n):\n    \"\"\"Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 \"\"\"\n    for i in range(0, len(iterable), n):\n        yield iterable[i:i + n]", "title": ""}
{"_id": "d5779", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d5780", "text": "def itervalues(d, **kw):\n    \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n    if not PY2:\n        return iter(d.values(**kw))\n    return d.itervalues(**kw)", "title": ""}
{"_id": "d5781", "text": "def is_binary(filename):\n    \"\"\" Returns True if the file is binary\n\n    \"\"\"\n    with open(filename, 'rb') as fp:\n        data = fp.read(1024)\n        if not data:\n            return False\n        if b'\\0' in data:\n            return True\n        return False", "title": ""}
{"_id": "d5782", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d5783", "text": "def is_square_matrix(mat):\n    \"\"\"Test if an array is a square matrix.\"\"\"\n    mat = np.array(mat)\n    if mat.ndim != 2:\n        return False\n    shape = mat.shape\n    return shape[0] == shape[1]", "title": ""}
{"_id": "d5784", "text": "def string_list_to_array(l):\n    \"\"\"\n    Turns a Python unicode string list into a Java String array.\n\n    :param l: the string list\n    :type: list\n    :rtype: java string array\n    :return: JB_Object\n    \"\"\"\n    result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class(\"java/lang/String\"))\n    for i in range(len(l)):\n        javabridge.get_env().set_object_array_element(result, i, javabridge.get_env().new_string_utf(l[i]))\n    return result", "title": ""}
{"_id": "d5785", "text": "def contains_geometric_info(var):\n    \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)", "title": ""}
{"_id": "d5786", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d5787", "text": "def _check_format(file_path, content):\n    \"\"\" check testcase format if valid\n    \"\"\"\n    # TODO: replace with JSON schema validation\n    if not content:\n        # testcase file content is empty\n        err_msg = u\"Testcase file content is empty: {}\".format(file_path)\n        logger.log_error(err_msg)\n        raise exceptions.FileFormatError(err_msg)\n\n    elif not isinstance(content, (list, dict)):\n        # testcase file content does not match testcase format\n        err_msg = u\"Testcase file content format invalid: {}\".format(file_path)\n        logger.log_error(err_msg)\n        raise exceptions.FileFormatError(err_msg)", "title": ""}
{"_id": "d5788", "text": "def dump_json(obj):\n    \"\"\"Dump Python object as JSON string.\"\"\"\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)", "title": ""}
{"_id": "d5789", "text": "def do_wordwrap(s, width=79, break_long_words=True):\n    \"\"\"\n    Return a copy of the string passed to the filter wrapped after\n    ``79`` characters.  You can override this default using the first\n    parameter.  If you set the second parameter to `false` Jinja will not\n    split words apart if they are longer than `width`.\n    \"\"\"\n    import textwrap\n    return u'\\n'.join(textwrap.wrap(s, width=width, expand_tabs=False,\n                                   replace_whitespace=False,\n                                   break_long_words=break_long_words))", "title": ""}
{"_id": "d5790", "text": "def from_json(value, **kwargs):\n        \"\"\"Coerces JSON string to boolean\"\"\"\n        if isinstance(value, string_types):\n            value = value.upper()\n            if value in ('TRUE', 'Y', 'YES', 'ON'):\n                return True\n            if value in ('FALSE', 'N', 'NO', 'OFF'):\n                return False\n        if isinstance(value, int):\n            return value\n        raise ValueError('Could not load boolean from JSON: {}'.format(value))", "title": ""}
{"_id": "d5791", "text": "def is_progressive(image):\n    \"\"\"\n    Check to see if an image is progressive.\n    \"\"\"\n    if not isinstance(image, Image.Image):\n        # Can only check PIL images for progressive encoding.\n        return False\n    return ('progressive' in image.info) or ('progression' in image.info)", "title": ""}
{"_id": "d5792", "text": "def json_dumps(self, obj):\n        \"\"\"Serializer for consistency\"\"\"\n        return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))", "title": ""}
{"_id": "d5793", "text": "def set(self):\n        \"\"\"Set the internal flag to true.\n\n        All threads waiting for the flag to become true are awakened. Threads\n        that call wait() once the flag is true will not block at all.\n\n        \"\"\"\n        with self.__cond:\n            self.__flag = True\n            self.__cond.notify_all()", "title": ""}
{"_id": "d5794", "text": "def dumps(obj):\n    \"\"\"Outputs json with formatting edits + object handling.\"\"\"\n    return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)", "title": ""}
{"_id": "d5795", "text": "def estimate_complexity(self, x,y,z,n):\n        \"\"\" \n        calculates a rough guess of runtime based on product of parameters \n        \"\"\"\n        num_calculations = x * y * z * n\n        run_time = num_calculations / 100000  # a 2014 PC does about 100k calcs in a second (guess based on prior logs)\n        return self.show_time_as_short_string(run_time)", "title": ""}
{"_id": "d5796", "text": "def read_json(location):\n    \"\"\"Open and load JSON from file.\n\n    location (Path): Path to JSON file.\n    RETURNS (dict): Loaded JSON content.\n    \"\"\"\n    location = ensure_path(location)\n    with location.open('r', encoding='utf8') as f:\n        return ujson.load(f)", "title": ""}
{"_id": "d5797", "text": "def timediff(time):\n    \"\"\"Return the difference in seconds between now and the given time.\"\"\"\n    now = datetime.datetime.utcnow()\n    diff = now - time\n    diff_sec = diff.total_seconds()\n    return diff_sec", "title": ""}
{"_id": "d5798", "text": "def is_webdriver_ios(webdriver):\n        \"\"\"\n        Check if a web driver if mobile.\n\n        Args:\n            webdriver (WebDriver): Selenium webdriver.\n\n        \"\"\"\n        browser = webdriver.capabilities['browserName']\n\n        if (browser == u('iPhone') or \n            browser == u('iPad')):\n            return True\n        else:\n            return False", "title": ""}
{"_id": "d5799", "text": "def hms_to_seconds(time_string):\n    \"\"\"\n    Converts string 'hh:mm:ss.ssssss' as a float\n    \"\"\"\n    s = time_string.split(':')\n    hours = int(s[0])\n    minutes = int(s[1])\n    secs = float(s[2])\n    return hours * 3600 + minutes * 60 + secs", "title": ""}
{"_id": "d5800", "text": "def sort_func(self, key):\n        \"\"\"Sorting logic for `Quantity` objects.\"\"\"\n        if key == self._KEYS.VALUE:\n            return 'aaa'\n        if key == self._KEYS.SOURCE:\n            return 'zzz'\n        return key", "title": ""}
{"_id": "d5801", "text": "def fromtimestamp(cls, timestamp):\n    \"\"\"Returns a datetime object of a given timestamp (in local tz).\"\"\"\n    d = cls.utcfromtimestamp(timestamp)\n    return d.astimezone(localtz())", "title": ""}
{"_id": "d5802", "text": "def checkbox_uncheck(self, force_check=False):\n        \"\"\"\n        Wrapper to uncheck a checkbox\n        \"\"\"\n        if self.get_attribute('checked'):\n            self.click(force_click=force_check)", "title": ""}
{"_id": "d5803", "text": "def stop_button_click_handler(self):\n        \"\"\"Method to handle what to do when the stop button is pressed\"\"\"\n        self.stop_button.setDisabled(True)\n        # Interrupt computations or stop debugging\n        if not self.shellwidget._reading:\n            self.interrupt_kernel()\n        else:\n            self.shellwidget.write_to_stdin('exit')", "title": ""}
{"_id": "d5804", "text": "def closeEvent(self, e):\n        \"\"\"Qt slot when the window is closed.\"\"\"\n        self.emit('close_widget')\n        super(DockWidget, self).closeEvent(e)", "title": ""}
{"_id": "d5805", "text": "def on_key_press(self, symbol, modifiers):\n        \"\"\"\n        Pyglet specific key press callback.\n        Forwards and translates the events to :py:func:`keyboard_event`\n        \"\"\"\n        self.keyboard_event(symbol, self.keys.ACTION_PRESS, modifiers)", "title": ""}
{"_id": "d5806", "text": "def _end_del(self):\n        \"\"\" Deletes the line content after the cursor  \"\"\"\n        text = self.edit_text[:self.edit_pos]\n        self.set_edit_text(text)", "title": ""}
{"_id": "d5807", "text": "def sigterm(self, signum, frame):\n        \"\"\"\n        These actions will be done after SIGTERM.\n        \"\"\"\n        self.logger.warning(\"Caught signal %s. Stopping daemon.\" % signum)\n        sys.exit(0)", "title": ""}
{"_id": "d5808", "text": "def _get(self, pos):\n        \"\"\"loads widget at given position; handling invalid arguments\"\"\"\n        res = None, None\n        if pos is not None:\n            try:\n                res = self[pos], pos\n            except (IndexError, KeyError):\n                pass\n        return res", "title": ""}
{"_id": "d5809", "text": "def get_access_datetime(filepath):\n    \"\"\"\n    Get the last time filepath was accessed.\n\n    Parameters\n    ----------\n    filepath : str\n\n    Returns\n    -------\n    access_datetime : datetime.datetime\n    \"\"\"\n    import tzlocal\n    tz = tzlocal.get_localzone()\n    mtime = datetime.fromtimestamp(os.path.getatime(filepath))\n    return mtime.replace(tzinfo=tz)", "title": ""}
{"_id": "d5810", "text": "def hide(self):\n        \"\"\"Hide the window.\"\"\"\n        self.tk.withdraw()\n        self._visible = False\n        if self._modal:\n            self.tk.grab_release()", "title": ""}
{"_id": "d5811", "text": "def clear_last_lines(self, n):\n        \"\"\"Clear last N lines of terminal output.\n        \"\"\"\n        self.term.stream.write(\n            self.term.move_up * n + self.term.clear_eos)\n        self.term.stream.flush()", "title": ""}
{"_id": "d5812", "text": "def _on_scale(self, event):\n        \"\"\"\n        Callback for the Scale widget, inserts an int value into the Entry.\n\n        :param event: Tkinter event\n        \"\"\"\n        self._entry.delete(0, tk.END)\n        self._entry.insert(0, str(self._variable.get()))", "title": ""}
{"_id": "d5813", "text": "def print_latex(o):\n    \"\"\"A function to generate the latex representation of sympy\n    expressions.\"\"\"\n    if can_print_latex(o):\n        s = latex(o, mode='plain')\n        s = s.replace('\\\\dag','\\\\dagger')\n        s = s.strip('$')\n        return '$$%s$$' % s\n    # Fallback to the string printer\n    return None", "title": ""}
{"_id": "d5814", "text": "def to_pascal_case(s):\n    \"\"\"Transform underscore separated string to pascal case\n\n    \"\"\"\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())", "title": ""}
{"_id": "d5815", "text": "def Distance(lat1, lon1, lat2, lon2):\n    \"\"\"Get distance between pairs of lat-lon points\"\"\"\n\n    az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)\n    return az21, dist", "title": ""}
{"_id": "d5816", "text": "def merge_pdfs(pdf_filepaths, out_filepath):\n    \"\"\" Merge all the PDF files in `pdf_filepaths` in a new PDF file `out_filepath`.\n\n    Parameters\n    ----------\n    pdf_filepaths: list of str\n        Paths to PDF files.\n\n    out_filepath: str\n        Path to the result PDF file.\n\n    Returns\n    -------\n    path: str\n        The output file path.\n    \"\"\"\n    merger = PdfFileMerger()\n    for pdf in pdf_filepaths:\n        merger.append(PdfFileReader(open(pdf, 'rb')))\n\n    merger.write(out_filepath)\n\n    return out_filepath", "title": ""}
{"_id": "d5817", "text": "def write_to(f, mode):\n    \"\"\"Flexible writing, where f can be a filename or f object, if filename, closed after writing\"\"\"\n    if hasattr(f, 'write'):\n        yield f\n    else:\n        f = open(f, mode)\n        yield f\n        f.close()", "title": ""}
{"_id": "d5818", "text": "def _aws_get_instance_by_tag(region, name, tag, raw):\n    \"\"\"Get all instances matching a tag.\"\"\"\n    client = boto3.session.Session().client('ec2', region)\n    matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', [])\n    instances = []\n    [[instances.append(_aws_instance_from_dict(region, instance, raw))  # pylint: disable=expression-not-assigned\n      for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation]\n    return instances", "title": ""}
{"_id": "d5819", "text": "def lemmatize(self, text, best_guess=True, return_frequencies=False):\n\t\t\"\"\"Lemmatize all tokens in a string or a list.  A string is first tokenized using punkt.\n\t\tThrow a type error if the input is neither a string nor a list.\n\t\t\"\"\"\n\t\tif isinstance(text, str):\n\t\t\ttokens = wordpunct_tokenize(text)\n\t\telif isinstance(text, list):\n\t\t\ttokens= text\n\t\telse:\n\t\t\traise TypeError(\"lemmatize only works with strings or lists of string tokens.\")\n\n\t\treturn [self._lemmatize_token(token, best_guess, return_frequencies) for token in tokens]", "title": ""}
{"_id": "d5820", "text": "def _sort_tensor(tensor):\n  \"\"\"Use `top_k` to sort a `Tensor` along the last dimension.\"\"\"\n  sorted_, _ = tf.nn.top_k(tensor, k=tf.shape(input=tensor)[-1])\n  sorted_.set_shape(tensor.shape)\n  return sorted_", "title": ""}
{"_id": "d5821", "text": "def norm_vec(vector):\n    \"\"\"Normalize the length of a vector to one\"\"\"\n    assert len(vector) == 3\n    v = np.array(vector)\n    return v/np.sqrt(np.sum(v**2))", "title": ""}
{"_id": "d5822", "text": "def start(args):\n    \"\"\"Run server with provided command line arguments.\n    \"\"\"\n    application = tornado.web.Application([(r\"/run\", run.get_handler(args)),\n                                           (r\"/status\", run.StatusHandler)])\n    application.runmonitor = RunMonitor()\n    application.listen(args.port)\n    tornado.ioloop.IOLoop.instance().start()", "title": ""}
{"_id": "d5823", "text": "def array_dim(arr):\n    \"\"\"Return the size of a multidimansional array.\n    \"\"\"\n    dim = []\n    while True:\n        try:\n            dim.append(len(arr))\n            arr = arr[0]\n        except TypeError:\n            return dim", "title": ""}
{"_id": "d5824", "text": "async def json_or_text(response):\n    \"\"\"Turns response into a properly formatted json or text object\"\"\"\n    text = await response.text()\n    if response.headers['Content-Type'] == 'application/json; charset=utf-8':\n        return json.loads(text)\n    return text", "title": ""}
{"_id": "d5825", "text": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Like `pretty` but print to stdout.\n    \"\"\"\n    printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    sys.stdout.write(newline)\n    sys.stdout.flush()", "title": ""}
{"_id": "d5826", "text": "def re_raise(self):\n        \"\"\" Raise this exception with the original traceback \"\"\"\n        if self.exc_info is not None:\n            six.reraise(type(self), self, self.exc_info[2])\n        else:\n            raise self", "title": ""}
{"_id": "d5827", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d5828", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d5829", "text": "def _linear_seaborn_(self, label=None, style=None, opts=None):\n        \"\"\"\n        Returns a Seaborn linear regression plot\n        \"\"\"\n        xticks, yticks = self._get_ticks(opts)\n        try:\n            fig = sns.lmplot(self.x, self.y, data=self.df)\n            fig = self._set_with_height(fig, opts)\n            return fig\n        except Exception as e:\n            self.err(e, self.linear_,\n                     \"Can not draw linear regression chart\")", "title": ""}
{"_id": "d5830", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d5831", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d5832", "text": "def remove_trailing_string(content, trailing):\n    \"\"\"\n    Strip trailing component `trailing` from `content` if it exists.\n    Used when generating names from view classes.\n    \"\"\"\n    if content.endswith(trailing) and content != trailing:\n        return content[:-len(trailing)]\n    return content", "title": ""}
{"_id": "d5833", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d5834", "text": "def abs_img(img):\n    \"\"\" Return an image with the binarised version of the data of `img`.\"\"\"\n    bool_img = np.abs(read_img(img).get_data())\n    return bool_img.astype(int)", "title": ""}
{"_id": "d5835", "text": "def get_order(self):\n        \"\"\"\n        Return a list of dicionaries. See `set_order`.\n        \"\"\"\n        return [dict(reverse=r[0], key=r[1]) for r in self.get_model()]", "title": ""}
{"_id": "d5836", "text": "def _unzip_handle(handle):\n    \"\"\"Transparently unzip the file handle\"\"\"\n    if isinstance(handle, basestring):\n        handle = _gzip_open_filename(handle)\n    else:\n        handle = _gzip_open_handle(handle)\n    return handle", "title": ""}
{"_id": "d5837", "text": "def isbinary(*args):\n    \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n    return all(map(lambda c: isnumber(c) or isbool(c), args))", "title": ""}
{"_id": "d5838", "text": "def comma_delimited_to_list(list_param):\n    \"\"\"Convert comma-delimited list / string into a list of strings\n\n    :param list_param: Comma-delimited string\n    :type list_param: str | unicode\n    :return: A list of strings\n    :rtype: list\n    \"\"\"\n    if isinstance(list_param, list):\n        return list_param\n    if isinstance(list_param, str):\n        return list_param.split(',')\n    else:\n        return []", "title": ""}
{"_id": "d5839", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d5840", "text": "def compose_all(tups):\n  \"\"\"Compose all given tuples together.\"\"\"\n  from . import ast  # I weep for humanity\n  return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))", "title": ""}
{"_id": "d5841", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d5842", "text": "def camel_to_(s):\n    \"\"\"\n    Convert CamelCase to camel_case\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', s)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d5843", "text": "def unique(transactions):\n    \"\"\" Remove any duplicate entries. \"\"\"\n    seen = set()\n    # TODO: Handle comments\n    return [x for x in transactions if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d5844", "text": "def _unjsonify(x, isattributes=False):\n    \"\"\"Convert JSON string to an ordered defaultdict.\"\"\"\n    if isattributes:\n        obj = json.loads(x)\n        return dict_class(obj)\n    return json.loads(x)", "title": ""}
{"_id": "d5845", "text": "def readCommaList(fileList):\n    \"\"\" Return a list of the files with the commas removed. \"\"\"\n    names=fileList.split(',')\n    fileList=[]\n    for item in names:\n        fileList.append(item)\n    return fileList", "title": ""}
{"_id": "d5846", "text": "def _convert_to_array(array_like, dtype):\n        \"\"\"\n        Convert Matrix attributes which are array-like or buffer to array.\n        \"\"\"\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)", "title": ""}
{"_id": "d5847", "text": "def _get_triplet_value_list(self, graph, identity, rdf_type):\n        \"\"\"\n        Get a list of values from RDF triples when more than one may be present\n        \"\"\"\n        values = []\n        for elem in graph.objects(identity, rdf_type):\n            values.append(elem.toPython())\n        return values", "title": ""}
{"_id": "d5848", "text": "def forward(self, step):\n        \"\"\"Move the turtle forward.\n\n        :param step: Integer. Distance to move forward.\n        \"\"\"\n        x = self.pos_x + math.cos(math.radians(self.rotation)) * step\n        y = self.pos_y + math.sin(math.radians(self.rotation)) * step\n        prev_brush_state = self.brush_on\n        self.brush_on = True\n        self.move(x, y)\n        self.brush_on = prev_brush_state", "title": ""}
{"_id": "d5849", "text": "def load_feature(fname, language):\n    \"\"\" Load and parse a feature file. \"\"\"\n\n    fname = os.path.abspath(fname)\n    feat = parse_file(fname, language)\n    return feat", "title": ""}
{"_id": "d5850", "text": "def __get__(self, obj, objtype):\n        if not self.is_method:\n            self.is_method = True\n        \"\"\"Support instance methods.\"\"\"\n        return functools.partial(self.__call__, obj)", "title": ""}
{"_id": "d5851", "text": "async def load_unicode(reader):\n    \"\"\"\n    Loads UTF8 string\n    :param reader:\n    :return:\n    \"\"\"\n    ivalue = await load_uvarint(reader)\n    fvalue = bytearray(ivalue)\n    await reader.areadinto(fvalue)\n    return str(fvalue, 'utf8')", "title": ""}
{"_id": "d5852", "text": "def parsed_args():\n    parser = argparse.ArgumentParser(description=\"\"\"python runtime functions\"\"\", epilog=\"\")\n    parser.add_argument('command',nargs='*',\n        help=\"Name of the function to run with arguments\")\n    args = parser.parse_args()\n    return (args, parser)", "title": ""}
{"_id": "d5853", "text": "def load_feature(fname, language):\n    \"\"\" Load and parse a feature file. \"\"\"\n\n    fname = os.path.abspath(fname)\n    feat = parse_file(fname, language)\n    return feat", "title": ""}
{"_id": "d5854", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d5855", "text": "def tuple_search(t, i, v):\n    \"\"\"\n    Search tuple array by index and value\n    :param t: tuple array\n    :param i: index of the value in each tuple\n    :param v: value\n    :return: the first tuple in the array with the specific index / value\n    \"\"\"\n    for e in t:\n        if e[i] == v:\n            return e\n    return None", "title": ""}
{"_id": "d5856", "text": "def page_title(step, title):\n    \"\"\"\n    Check that the page title matches the given one.\n    \"\"\"\n\n    with AssertContextManager(step):\n        assert_equals(world.browser.title, title)", "title": ""}
{"_id": "d5857", "text": "def pylog(self, *args, **kwargs):\n        \"\"\"Display all available logging information.\"\"\"\n        printerr(self.name, args, kwargs, traceback.format_exc())", "title": ""}
{"_id": "d5858", "text": "def _correct_args(func, kwargs):\n    \"\"\"\n        Convert a dictionary of arguments including __argv into a list\n        for passing to the function.\n    \"\"\"\n    args = inspect.getargspec(func)[0]\n    return [kwargs[arg] for arg in args] + kwargs['__args']", "title": ""}
{"_id": "d5859", "text": "def longest_run_1d(arr):\n    \"\"\"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.\n    \"\"\"\n    v, rl = rle_1d(arr)[:2]\n    return np.where(v, rl, 0).max()", "title": ""}
{"_id": "d5860", "text": "def unpack(self, s):\n        \"\"\"Parse bytes and return a namedtuple.\"\"\"\n        return self._create(super(NamedStruct, self).unpack(s))", "title": ""}
{"_id": "d5861", "text": "def tuple_search(t, i, v):\n    \"\"\"\n    Search tuple array by index and value\n    :param t: tuple array\n    :param i: index of the value in each tuple\n    :param v: value\n    :return: the first tuple in the array with the specific index / value\n    \"\"\"\n    for e in t:\n        if e[i] == v:\n            return e\n    return None", "title": ""}
{"_id": "d5862", "text": "def sarea_(self, col, x=None, y=None, rsum=None, rmean=None):\n\t\t\"\"\"\n\t\tGet an stacked area chart\n\t\t\"\"\"\n\t\ttry:\n\t\t\tcharts = self._multiseries(col, x, y, \"area\", rsum, rmean)\n\t\t\treturn hv.Area.stack(charts)\n\t\texcept Exception as e:\n\t\t\tself.err(e, self.sarea_, \"Can not draw stacked area chart\")", "title": ""}
{"_id": "d5863", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d5864", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d5865", "text": "async def sysinfo(dev: Device):\n    \"\"\"Print out system information (version, MAC addrs).\"\"\"\n    click.echo(await dev.get_system_info())\n    click.echo(await dev.get_interface_information())", "title": ""}
{"_id": "d5866", "text": "def glr_path_static():\n    \"\"\"Returns path to packaged static files\"\"\"\n    return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))", "title": ""}
{"_id": "d5867", "text": "def subscribe_to_quorum_channel(self):\n        \"\"\"In case the experiment enforces a quorum, listen for notifications\n        before creating Partipant objects.\n        \"\"\"\n        from dallinger.experiment_server.sockets import chat_backend\n\n        self.log(\"Bot subscribing to quorum channel.\")\n        chat_backend.subscribe(self, \"quorum\")", "title": ""}
{"_id": "d5868", "text": "def get_url_file_name(url):\n    \"\"\"Get the file name from an url\n    \n    Parameters\n    ----------\n    url : str\n\n    Returns\n    -------\n    str\n        The file name \n    \"\"\"\n\n    assert isinstance(url, (str, _oldstr))\n    return urlparse.urlparse(url).path.split('/')[-1]", "title": ""}
{"_id": "d5869", "text": "def copy(self):\n        \"\"\"Return a copy of this list with each element copied to new memory\n        \"\"\"\n        out = type(self)()\n        for series in self:\n            out.append(series.copy())\n        return out", "title": ""}
{"_id": "d5870", "text": "def GetPythonLibraryDirectoryPath():\n  \"\"\"Retrieves the Python library directory path.\"\"\"\n  path = sysconfig.get_python_lib(True)\n  _, _, path = path.rpartition(sysconfig.PREFIX)\n\n  if path.startswith(os.sep):\n    path = path[1:]\n\n  return path", "title": ""}
{"_id": "d5871", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d5872", "text": "def generate_id():\n    \"\"\"Generate new UUID\"\"\"\n    # TODO: Use six.string_type to Py3 compat\n    try:\n        return unicode(uuid1()).replace(u\"-\", u\"\")\n    except NameError:\n        return str(uuid1()).replace(u\"-\", u\"\")", "title": ""}
{"_id": "d5873", "text": "def on_welcome(self, connection, event):\n        \"\"\"\n        Join the channel once connected to the IRC server.\n        \"\"\"\n        connection.join(self.channel, key=settings.IRC_CHANNEL_KEY or \"\")", "title": ""}
{"_id": "d5874", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d5875", "text": "def pretty_dict_string(d, indent=0):\n    \"\"\"Pretty output of nested dictionaries.\n    \"\"\"\n    s = ''\n    for key, value in sorted(d.items()):\n        s += '    ' * indent + str(key)\n        if isinstance(value, dict):\n             s += '\\n' + pretty_dict_string(value, indent+1)\n        else:\n             s += '=' + str(value) + '\\n'\n    return s", "title": ""}
{"_id": "d5876", "text": "def venv():\n    \"\"\"Install venv + deps.\"\"\"\n    try:\n        import virtualenv  # NOQA\n    except ImportError:\n        sh(\"%s -m pip install virtualenv\" % PYTHON)\n    if not os.path.isdir(\"venv\"):\n        sh(\"%s -m virtualenv venv\" % PYTHON)\n    sh(\"venv\\\\Scripts\\\\pip install -r %s\" % (REQUIREMENTS_TXT))", "title": ""}
{"_id": "d5877", "text": "def url_encode(url):\n    \"\"\"\n    Convert special characters using %xx escape.\n\n    :param url: str\n    :return: str - encoded url\n    \"\"\"\n    if isinstance(url, text_type):\n        url = url.encode('utf8')\n    return quote(url, ':/%?&=')", "title": ""}
{"_id": "d5878", "text": "def _raise_error_if_column_exists(dataset, column_name = 'dataset',\n                            dataset_variable_name = 'dataset',\n                            column_name_error_message_name = 'column_name'):\n    \"\"\"\n    Check if a column exists in an SFrame with error message.\n    \"\"\"\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))", "title": ""}
{"_id": "d5879", "text": "def safe_unicode(string):\n    \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n    if not PY3:\n        uni = string.replace(u'\\u2019', \"'\")\n        return uni.encode('utf-8')\n        \n    return string", "title": ""}
{"_id": "d5880", "text": "def print_table(*args, **kwargs):\n    \"\"\"\n    if csv:\n        import csv\n        t = csv.writer(sys.stdout, delimiter=\";\")\n        t.writerow(header)\n    else:\n        t = PrettyTable(header)\n        t.align = \"r\"\n        t.align[\"details\"] = \"l\"\n    \"\"\"\n    t = format_table(*args, **kwargs)\n    click.echo(t)", "title": ""}
{"_id": "d5881", "text": "def quadratic_bezier(start, end, c0=(0, 0), c1=(0, 0), steps=50):\n    \"\"\"\n    Compute quadratic bezier spline given start and end coordinate and\n    two control points.\n    \"\"\"\n    steps = np.linspace(0, 1, steps)\n    sx, sy = start\n    ex, ey = end\n    cx0, cy0 = c0\n    cx1, cy1 = c1\n    xs = ((1-steps)**3*sx + 3*((1-steps)**2)*steps*cx0 +\n          3*(1-steps)*steps**2*cx1 + steps**3*ex)\n    ys = ((1-steps)**3*sy + 3*((1-steps)**2)*steps*cy0 +\n          3*(1-steps)*steps**2*cy1 + steps**3*ey)\n    return np.column_stack([xs, ys])", "title": ""}
{"_id": "d5882", "text": "def volume(self):\n        \"\"\"\n        The volume of the primitive extrusion.\n\n        Calculated from polygon and height to avoid mesh creation.\n\n        Returns\n        ----------\n        volume: float, volume of 3D extrusion\n        \"\"\"\n        volume = abs(self.primitive.polygon.area *\n                     self.primitive.height)\n        return volume", "title": ""}
{"_id": "d5883", "text": "def eval_script(self, expr):\n    \"\"\" Evaluates a piece of Javascript in the context of the current page and\n    returns its value. \"\"\"\n    ret = self.conn.issue_command(\"Evaluate\", expr)\n    return json.loads(\"[%s]\" % ret)[0]", "title": ""}
{"_id": "d5884", "text": "def classnameify(s):\n  \"\"\"\n  Makes a classname\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))", "title": ""}
{"_id": "d5885", "text": "def sine_wave(frequency):\n  \"\"\"Emit a sine wave at the given frequency.\"\"\"\n  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n  ts = xs / FLAGS.sample_rate\n  return tf.sin(2 * math.pi * frequency * ts)", "title": ""}
{"_id": "d5886", "text": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "title": ""}
{"_id": "d5887", "text": "def get_auth():\n    \"\"\"Get authentication.\"\"\"\n    import getpass\n    user = input(\"User Name: \")  # noqa\n    pswd = getpass.getpass('Password: ')\n    return Github(user, pswd)", "title": ""}
{"_id": "d5888", "text": "def get_page_and_url(session, url):\n    \"\"\"\n    Download an HTML page using the requests session and return\n    the final URL after following redirects.\n    \"\"\"\n    reply = get_reply(session, url)\n    return reply.text, reply.url", "title": ""}
{"_id": "d5889", "text": "def manhattan_distance_numpy(object1, object2):\n    \"\"\"!\n    @brief Calculate Manhattan distance between two objects using numpy.\n\n    @param[in] object1 (array_like): The first array_like object.\n    @param[in] object2 (array_like): The second array_like object.\n\n    @return (double) Manhattan distance between two objects.\n\n    \"\"\"\n    return numpy.sum(numpy.absolute(object1 - object2), axis=1).T", "title": ""}
{"_id": "d5890", "text": "def check_by_selector(self, selector):\n    \"\"\"Check the checkbox matching the CSS selector.\"\"\"\n    elem = find_element_by_jquery(world.browser, selector)\n    if not elem.is_selected():\n        elem.click()", "title": ""}
{"_id": "d5891", "text": "def autobuild_python_test(path):\n    \"\"\"Add pytest unit tests to be built as part of build/test/output.\"\"\"\n\n    env = Environment(tools=[])\n    target = env.Command(['build/test/output/pytest.log'], [path],\n                         action=env.Action(run_pytest, \"Running python unit tests\"))\n    env.AlwaysBuild(target)", "title": ""}
{"_id": "d5892", "text": "def find_elements_by_id(self, id_):\n        \"\"\"\n        Finds multiple elements by id.\n\n        :Args:\n         - id\\\\_ - The id of the elements to be found.\n\n        :Returns:\n         - list of WebElement - a list with elements if any was found.  An\n           empty list if not\n\n        :Usage:\n            ::\n\n                elements = driver.find_elements_by_id('foo')\n        \"\"\"\n        return self.find_elements(by=By.ID, value=id_)", "title": ""}
{"_id": "d5893", "text": "def intersect(d1, d2):\n    \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n    return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "title": ""}
{"_id": "d5894", "text": "def _get_item_position(self, idx):\n        \"\"\"Return a tuple of (start, end) indices of an item from its index.\"\"\"\n        start = 0 if idx == 0 else self._index[idx - 1] + 1\n        end = self._index[idx]\n        return start, end", "title": ""}
{"_id": "d5895", "text": "def add_arrow(self, x1, y1, x2, y2, **kws):\n        \"\"\"add arrow to plot\"\"\"\n        self.panel.add_arrow(x1, y1, x2, y2, **kws)", "title": ""}
{"_id": "d5896", "text": "def map_wrap(f):\n    \"\"\"Wrap standard function to easily pass into 'map' processing.\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d5897", "text": "def ident():\n    \"\"\"\n    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\n    \"\"\"\n    matrix = stypes.emptyDoubleMatrix()\n    libspice.ident_c(matrix)\n    return stypes.cMatrixToNumpy(matrix)", "title": ""}
{"_id": "d5898", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d5899", "text": "def heappush_max(heap, item):\n    \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n    heap.append(item)\n    _siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d5900", "text": "def flush(self):\n        \"\"\"Ensure contents are written to file.\"\"\"\n        for name in self.item_names:\n            item = self[name]\n            item.flush()\n        self.file.flush()", "title": ""}
{"_id": "d5901", "text": "def _multiline_width(multiline_s, line_width_fn=len):\n    \"\"\"Visible width of a potentially multiline content.\"\"\"\n    return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "title": ""}
{"_id": "d5902", "text": "def base64ToImage(imgData, out_path, out_file):\n        \"\"\" converts a base64 string to a file \"\"\"\n        fh = open(os.path.join(out_path, out_file), \"wb\")\n        fh.write(imgData.decode('base64'))\n        fh.close()\n        del fh\n        return os.path.join(out_path, out_file)", "title": ""}
{"_id": "d5903", "text": "def get_decimal_quantum(precision):\n    \"\"\"Return minimal quantum of a number, as defined by precision.\"\"\"\n    assert isinstance(precision, (int, decimal.Decimal))\n    return decimal.Decimal(10) ** (-precision)", "title": ""}
{"_id": "d5904", "text": "def _serialize_json(obj, fp):\n    \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n    json.dump(obj, fp, indent=4, default=serialize)", "title": ""}
{"_id": "d5905", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d5906", "text": "def serialize_yaml_tofile(filename, resource):\n    \"\"\"\n    Serializes a K8S resource to YAML-formatted file.\n    \"\"\"\n    stream = file(filename, \"w\")\n    yaml.dump(resource, stream, default_flow_style=False)", "title": ""}
{"_id": "d5907", "text": "def median_high(data):\n    \"\"\"Return the high median of data.\n\n    When the number of data points is odd, the middle value is returned.\n    When it is even, the larger of the two middle values is returned.\n\n    \"\"\"\n    data = sorted(data)\n    n = len(data)\n    if n == 0:\n        raise StatisticsError(\"no median for empty data\")\n    return data[n // 2]", "title": ""}
{"_id": "d5908", "text": "def write_str2file(pathname, astr):\n    \"\"\"writes a string to file\"\"\"\n    fname = pathname\n    fhandle = open(fname, 'wb')\n    fhandle.write(astr)\n    fhandle.close()", "title": ""}
{"_id": "d5909", "text": "def objectproxy_realaddress(obj):\n    \"\"\"\n    Obtain a real address as an integer from an objectproxy.\n    \"\"\"\n    voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)\n    return C.addressof(C.c_char.from_buffer(voidp))", "title": ""}
{"_id": "d5910", "text": "def write_config(self, outfile):\n        \"\"\"Write the configuration dictionary to an output file.\"\"\"\n        utils.write_yaml(self.config, outfile, default_flow_style=False)", "title": ""}
{"_id": "d5911", "text": "def _rel(self, path):\n        \"\"\"\n        Get the relative path for the given path from the current\n        file by working around https://bugs.python.org/issue20012.\n        \"\"\"\n        return os.path.relpath(\n            str(path), self._parent).replace(os.path.sep, '/')", "title": ""}
{"_id": "d5912", "text": "def end_block(self):\n        \"\"\"Ends an indentation block, leaving an empty line afterwards\"\"\"\n        self.current_indent -= 1\n\n        # If we did not add a new line automatically yet, now it's the time!\n        if not self.auto_added_line:\n            self.writeln()\n            self.auto_added_line = True", "title": ""}
{"_id": "d5913", "text": "def merge(self, other):\n        \"\"\"\n        Merge this range object with another (ranges need not overlap or abut).\n\n        :returns: a new Range object representing the interval containing both\n                  ranges.\n        \"\"\"\n        newstart = min(self._start, other.start)\n        newend = max(self._end, other.end)\n        return Range(newstart, newend)", "title": ""}
{"_id": "d5914", "text": "def _update_bordercolor(self, bordercolor):\n        \"\"\"Updates background color\"\"\"\n\n        border_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVEBORDER)\n        border_color.SetRGB(bordercolor)\n\n        self.linecolor_choice.SetColour(border_color)", "title": ""}
{"_id": "d5915", "text": "def merge(self, other):\n        \"\"\"\n        Merge this range object with another (ranges need not overlap or abut).\n\n        :returns: a new Range object representing the interval containing both\n                  ranges.\n        \"\"\"\n        newstart = min(self._start, other.start)\n        newend = max(self._end, other.end)\n        return Range(newstart, newend)", "title": ""}
{"_id": "d5916", "text": "def get_mouse_location(self):\n        \"\"\"\n        Get the current mouse location (coordinates and screen number).\n\n        :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields\n        \"\"\"\n        x = ctypes.c_int(0)\n        y = ctypes.c_int(0)\n        screen_num = ctypes.c_int(0)\n        _libxdo.xdo_get_mouse_location(\n            self._xdo, ctypes.byref(x), ctypes.byref(y),\n            ctypes.byref(screen_num))\n        return mouse_location(x.value, y.value, screen_num.value)", "title": ""}
{"_id": "d5917", "text": "def listunion(ListOfLists):\n    \"\"\"\n    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`.\n\n    \"\"\"\n    u = []\n    for s in ListOfLists:\n        if s != None:\n            u.extend(s)\n    return u", "title": ""}
{"_id": "d5918", "text": "def xml_str_to_dict(s):\n    \"\"\" Transforms an XML string it to python-zimbra dict format\n\n    For format, see:\n      https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n    :param: a string, containing XML\n    :returns: a dict, with python-zimbra format\n    \"\"\"\n    xml = minidom.parseString(s)\n    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)", "title": ""}
{"_id": "d5919", "text": "def send_notice(self, text):\n        \"\"\"Send a notice (from bot) message to the room.\"\"\"\n        return self.client.api.send_notice(self.room_id, text)", "title": ""}
{"_id": "d5920", "text": "def validate(self, xml_input):\n        \"\"\"\n        This method validate the parsing and schema, return a boolean\n        \"\"\"\n        parsed_xml = etree.parse(self._handle_xml(xml_input))\n        try:\n            return self.xmlschema.validate(parsed_xml)\n        except AttributeError:\n            raise CannotValidate('Set XSD to validate the XML')", "title": ""}
{"_id": "d5921", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d5922", "text": "def is_empty(self):\n        \"\"\"Returns True if the root node contains no child elements, no text,\n        and no attributes other than **type**. Returns False if any are present.\"\"\"\n        non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type']\n        return len(self.node) == 0 and len(non_type_attributes) == 0 \\\n            and not self.node.text and not self.node.tail", "title": ""}
{"_id": "d5923", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d5924", "text": "def _extract_node_text(node):\n    \"\"\"Extract text from a given lxml node.\"\"\"\n\n    texts = map(\n        six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n    )\n    return \" \".join(text for text in texts if text)", "title": ""}
{"_id": "d5925", "text": "def print_yaml(o):\n    \"\"\"Pretty print an object as YAML.\"\"\"\n    print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))", "title": ""}
{"_id": "d5926", "text": "def ensure_index(self, key, unique=False):\n        \"\"\"Wrapper for pymongo.Collection.ensure_index\n        \"\"\"\n        return self.collection.ensure_index(key, unique=unique)", "title": ""}
{"_id": "d5927", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d5928", "text": "def order_by(self, *fields):\n        \"\"\"An alternate to ``sort`` which allows you to specify a list\n        of fields and use a leading - (minus) to specify DESCENDING.\"\"\"\n        doc = []\n        for field in fields:\n            if field.startswith('-'):\n                doc.append((field.strip('-'), pymongo.DESCENDING))\n            else:\n                doc.append((field, pymongo.ASCENDING))\n        return self.sort(doc)", "title": ""}
{"_id": "d5929", "text": "def compressBuffer(buffer):\n    \"\"\"\n    Note that this code compresses into a buffer held in memory, rather\n    than a disk file. This is done through the use of cStringIO.StringIO().\n    \"\"\"\n    # http://jython.xhaus.com/http-compression-in-python-and-jython/\n    zbuf = cStringIO.StringIO()\n    zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)\n    zfile.write(buffer)\n    zfile.close()\n    return zbuf.getvalue()", "title": ""}
{"_id": "d5930", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d5931", "text": "def pieces(array, chunk_size):\n        \"\"\"Yield successive chunks from array/list/string.\n        Final chunk may be truncated if array is not evenly divisible by chunk_size.\"\"\"\n        for i in range(0, len(array), chunk_size): yield array[i:i+chunk_size]", "title": ""}
{"_id": "d5932", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d5933", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x.\"\"\"\n    i = bs.bisect_left(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d5934", "text": "def static_method(cls, f):\n        \"\"\"Decorator which dynamically binds static methods to the model for later use.\"\"\"\n        setattr(cls, f.__name__, staticmethod(f))\n        return f", "title": ""}
{"_id": "d5935", "text": "def from_series(cls, series):\n        \"\"\"Convert a pandas.Series into an xarray.DataArray.\n\n        If the series's index is a MultiIndex, it will be expanded into a\n        tensor product of one-dimensional coordinates (filling in missing\n        values with NaN). Thus this operation should be the inverse of the\n        `to_series` method.\n        \"\"\"\n        # TODO: add a 'name' parameter\n        name = series.name\n        df = pd.DataFrame({name: series})\n        ds = Dataset.from_dataframe(df)\n        return ds[name]", "title": ""}
{"_id": "d5936", "text": "def access(self, accessor, timeout=None):\n        \"\"\"Return a result from an asyncio future.\"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Loop is already running\")\n        coro = asyncio.wait_for(accessor, timeout, loop=self.loop)\n        return self.loop.run_until_complete(coro)", "title": ""}
{"_id": "d5937", "text": "def interpolate_nearest(self, xi, yi, zdata):\n        \"\"\"\n        Nearest-neighbour interpolation.\n        Calls nearnd to find the index of the closest neighbours to xi,yi\n\n        Parameters\n        ----------\n         xi : float / array of floats, shape (l,)\n            x coordinates on the Cartesian plane\n         yi : float / array of floats, shape (l,)\n            y coordinates on the Cartesian plane\n\n        Returns\n        -------\n         zi : float / array of floats, shape (l,)\n            nearest-neighbour interpolated value(s) of (xi,yi)\n        \"\"\"\n        if zdata.size != self.npoints:\n            raise ValueError('zdata should be same size as mesh')\n\n        zdata = self._shuffle_field(zdata)\n\n        ist = np.ones_like(xi, dtype=np.int32)\n        ist, dist = _tripack.nearnds(xi, yi, ist, self._x, self._y,\n                                     self.lst, self.lptr, self.lend)\n        return zdata[ist - 1]", "title": ""}
{"_id": "d5938", "text": "def ub_to_str(string):\n    \"\"\"\n    converts py2 unicode / py3 bytestring into str\n    Args:\n        string (unicode, byte_string): string to be converted\n        \n    Returns:\n        (str)\n    \"\"\"\n    if not isinstance(string, str):\n        if six.PY2:\n            return str(string)\n        else:\n            return string.decode()\n    return string", "title": ""}
{"_id": "d5939", "text": "def ex(self, cmd):\n        \"\"\"Execute a normal python statement in user namespace.\"\"\"\n        with self.builtin_trap:\n            exec cmd in self.user_global_ns, self.user_ns", "title": ""}
{"_id": "d5940", "text": "def inject_into_urllib3():\n    \"\"\"\n    Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n    \"\"\"\n    util.ssl_.SSLContext = SecureTransportContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_SECURETRANSPORT = True\n    util.ssl_.IS_SECURETRANSPORT = True", "title": ""}
{"_id": "d5941", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d5942", "text": "def isemptyfile(filepath):\n    \"\"\"Determine if the file both exists and isempty\n\n    Args:\n        filepath (str, path): file path\n\n    Returns:\n        bool\n    \"\"\"\n    exists = os.path.exists(safepath(filepath))\n    if exists:\n        filesize = os.path.getsize(safepath(filepath))\n        return filesize == 0\n    else:\n        return False", "title": ""}
{"_id": "d5943", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d5944", "text": "def isstring(value):\n    \"\"\"Report whether the given value is a byte or unicode string.\"\"\"\n    classes = (str, bytes) if pyutils.PY3 else basestring  # noqa: F821\n    return isinstance(value, classes)", "title": ""}
{"_id": "d5945", "text": "def get_gzipped_contents(input_file):\n    \"\"\"\n    Returns a gzipped version of a previously opened file's buffer.\n    \"\"\"\n    zbuf = StringIO()\n    zfile = GzipFile(mode=\"wb\", compresslevel=6, fileobj=zbuf)\n    zfile.write(input_file.read())\n    zfile.close()\n    return ContentFile(zbuf.getvalue())", "title": ""}
{"_id": "d5946", "text": "def is_enum_type(type_):\n    \"\"\" Checks if the given type is an enum type.\n\n    :param type_: The type to check\n    :return: True if the type is a enum type, otherwise False\n    :rtype: bool\n    \"\"\"\n\n    return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))", "title": ""}
{"_id": "d5947", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d5948", "text": "def is_alive(self):\n        \"\"\"\n        @rtype:  bool\n        @return: C{True} if the process is currently running.\n        \"\"\"\n        try:\n            self.wait(0)\n        except WindowsError:\n            e = sys.exc_info()[1]\n            return e.winerror == win32.WAIT_TIMEOUT\n        return False", "title": ""}
{"_id": "d5949", "text": "def v_normalize(v):\n    \"\"\"\n    Normalizes the given vector.\n    \n    The vector given may have any number of dimensions.\n    \"\"\"\n    vmag = v_magnitude(v)\n    return [ v[i]/vmag  for i in range(len(v)) ]", "title": ""}
{"_id": "d5950", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d5951", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d5952", "text": "def is_seq(obj):\n    \"\"\" Returns True if object is not a string but is iterable \"\"\"\n    if not hasattr(obj, '__iter__'):\n        return False\n    if isinstance(obj, basestring):\n        return False\n    return True", "title": ""}
{"_id": "d5953", "text": "def normalize(im, invert=False, scale=None, dtype=np.float64):\n    \"\"\"\n    Normalize a field to a (min, max) exposure range, default is (0, 255).\n    (min, max) exposure values. Invert the image if requested.\n    \"\"\"\n    if dtype not in {np.float16, np.float32, np.float64}:\n        raise ValueError('dtype must be numpy.float16, float32, or float64.')\n    out = im.astype('float').copy()\n\n    scale = scale or (0.0, 255.0)\n    l, u = (float(i) for i in scale)\n    out = (out - l) / (u - l)\n    if invert:\n        out = -out + (out.max() + out.min())\n    return out.astype(dtype)", "title": ""}
{"_id": "d5954", "text": "def bytes_to_str(s, encoding='utf-8'):\n    \"\"\"Returns a str if a bytes object is given.\"\"\"\n    if six.PY3 and isinstance(s, bytes):\n        return s.decode(encoding)\n    return s", "title": ""}
{"_id": "d5955", "text": "def get_gzipped_contents(input_file):\n    \"\"\"\n    Returns a gzipped version of a previously opened file's buffer.\n    \"\"\"\n    zbuf = StringIO()\n    zfile = GzipFile(mode=\"wb\", compresslevel=6, fileobj=zbuf)\n    zfile.write(input_file.read())\n    zfile.close()\n    return ContentFile(zbuf.getvalue())", "title": ""}
{"_id": "d5956", "text": "def is_valid_folder(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.isdir(arg):\n        parser.error(\"The folder %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d5957", "text": "def count_string_diff(a,b):\n    \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n    shortest = min(len(a), len(b))\n    return sum(a[i] != b[i] for i in range(shortest))", "title": ""}
{"_id": "d5958", "text": "def clean(some_string, uppercase=False):\n    \"\"\"\n    helper to clean up an input string\n    \"\"\"\n    if uppercase:\n        return some_string.strip().upper()\n    else:\n        return some_string.strip().lower()", "title": ""}
{"_id": "d5959", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d5960", "text": "def render(template, context):\n        \"\"\"Wrapper to the jinja2 render method from a template file\n\n        Parameters\n        ----------\n        template : str\n            Path to template file.\n        context : dict\n            Dictionary with kwargs context to populate the template\n        \"\"\"\n\n        path, filename = os.path.split(template)\n\n        return jinja2.Environment(\n            loader=jinja2.FileSystemLoader(path or './')\n        ).get_template(filename).render(context)", "title": ""}
{"_id": "d5961", "text": "def _unique_rows_numpy(a):\n    \"\"\"return unique rows\"\"\"\n    a = np.ascontiguousarray(a)\n    unique_a = np.unique(a.view([('', a.dtype)] * a.shape[1]))\n    return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))", "title": ""}
{"_id": "d5962", "text": "def scale_image(image, new_width):\n    \"\"\"Resizes an image preserving the aspect ratio.\n    \"\"\"\n    (original_width, original_height) = image.size\n    aspect_ratio = original_height/float(original_width)\n    new_height = int(aspect_ratio * new_width)\n\n    # This scales it wider than tall, since characters are biased\n    new_image = image.resize((new_width*2, new_height))\n    return new_image", "title": ""}
{"_id": "d5963", "text": "def ensure_us_time_resolution(val):\n    \"\"\"Convert val out of numpy time, for use in to_dict.\n    Needed because of numpy bug GH#7619\"\"\"\n    if np.issubdtype(val.dtype, np.datetime64):\n        val = val.astype('datetime64[us]')\n    elif np.issubdtype(val.dtype, np.timedelta64):\n        val = val.astype('timedelta64[us]')\n    return val", "title": ""}
{"_id": "d5964", "text": "def setup_request_sessions(self):\n        \"\"\" Sets up a requests.Session object for sharing headers across API requests.\n        \"\"\"\n        self.req_session = requests.Session()\n        self.req_session.headers.update(self.headers)", "title": ""}
{"_id": "d5965", "text": "def lognormcdf(x, mu, tau):\n    \"\"\"Log-normal cumulative density function\"\"\"\n    x = np.atleast_1d(x)\n    return np.array(\n        [0.5 * (1 - flib.derf(-(np.sqrt(tau / 2)) * (np.log(y) - mu))) for y in x])", "title": ""}
{"_id": "d5966", "text": "def xml_str_to_dict(s):\n    \"\"\" Transforms an XML string it to python-zimbra dict format\n\n    For format, see:\n      https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n    :param: a string, containing XML\n    :returns: a dict, with python-zimbra format\n    \"\"\"\n    xml = minidom.parseString(s)\n    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)", "title": ""}
{"_id": "d5967", "text": "def push(h, x):\n    \"\"\"Push a new value into heap.\"\"\"\n    h.push(x)\n    up(h, h.size()-1)", "title": ""}
{"_id": "d5968", "text": "def _first_and_last_element(arr):\n    \"\"\"Returns first and last element of numpy array or sparse matrix.\"\"\"\n    if isinstance(arr, np.ndarray) or hasattr(arr, 'data'):\n        # numpy array or sparse matrix with .data attribute\n        data = arr.data if sparse.issparse(arr) else arr\n        return data.flat[0], data.flat[-1]\n    else:\n        # Sparse matrices without .data attribute. Only dok_matrix at\n        # the time of writing, in this case indexing is fast\n        return arr[0, 0], arr[-1, -1]", "title": ""}
{"_id": "d5969", "text": "def run(self):\n        \"\"\"\n        consume message from channel on the consuming thread.\n        \"\"\"\n        LOGGER.debug(\"rabbitmq.Service.run\")\n        try:\n            self.channel.start_consuming()\n        except Exception as e:\n            LOGGER.warn(\"rabbitmq.Service.run - Exception raised while consuming\")", "title": ""}
{"_id": "d5970", "text": "def filter_duplicate_key(line, message, line_number, marked_line_numbers,\n                         source, previous_line=''):\n    \"\"\"Return '' if first occurrence of the key otherwise return `line`.\"\"\"\n    if marked_line_numbers and line_number == sorted(marked_line_numbers)[0]:\n        return ''\n\n    return line", "title": ""}
{"_id": "d5971", "text": "def reseed_random(seed):\n    \"\"\"Reseed factory.fuzzy's random generator.\"\"\"\n    r = random.Random(seed)\n    random_internal_state = r.getstate()\n    set_random_state(random_internal_state)", "title": ""}
{"_id": "d5972", "text": "def handle_m2m(self, sender, instance, **kwargs):\n    \"\"\" Handle many to many relationships \"\"\"\n    self.handle_save(instance.__class__, instance)", "title": ""}
{"_id": "d5973", "text": "def csv_to_dicts(file, header=None):\n    \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n    with open(file) as csvfile:\n        return [row for row in csv.DictReader(csvfile, fieldnames=header)]", "title": ""}
{"_id": "d5974", "text": "def getYamlDocument(filePath):\n    \"\"\"\n    Return a yaml file's contents as a dictionary\n    \"\"\"\n    with open(filePath) as stream:\n        doc = yaml.load(stream)\n        return doc", "title": ""}
{"_id": "d5975", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d5976", "text": "def load_image(fname):\n    \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n    with open(fname, \"rb\") as f:\n        i = Image.open(fname)\n        #i.load()\n        return i", "title": ""}
{"_id": "d5977", "text": "def _read_group_h5(filename, groupname):\n    \"\"\"Return group content.\n\n    Args:\n        filename (:class:`pathlib.Path`): path of hdf5 file.\n        groupname (str): name of group to read.\n    Returns:\n        :class:`numpy.array`: content of group.\n    \"\"\"\n    with h5py.File(filename, 'r') as h5f:\n        data = h5f[groupname][()]\n    return data", "title": ""}
{"_id": "d5978", "text": "def dot_v3(v, w):\n    \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n    return sum([x * y for x, y in zip(v, w)])", "title": ""}
{"_id": "d5979", "text": "def standard_input():\n    \"\"\"Generator that yields lines from standard input.\"\"\"\n    with click.get_text_stream(\"stdin\") as stdin:\n        while stdin.readable():\n            line = stdin.readline()\n            if line:\n                yield line.strip().encode(\"utf-8\")", "title": ""}
{"_id": "d5980", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d5981", "text": "def read(fname):\n    \"\"\"Quick way to read a file content.\"\"\"\n    content = None\n    with open(os.path.join(here, fname)) as f:\n        content = f.read()\n    return content", "title": ""}
{"_id": "d5982", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d5983", "text": "def versions_request(self):\n        \"\"\"List Available REST API Versions\"\"\"\n        ret = self.handle_api_exceptions('GET', '', api_ver='')\n        return [str_dict(x) for x in ret.json()]", "title": ""}
{"_id": "d5984", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d5985", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d5986", "text": "def _parse_response(self, response):\n        \"\"\"\n        Parse http raw respone into python\n        dictionary object.\n        \n        :param str response: http response\n        :returns: response dict\n        :rtype: dict\n        \"\"\"\n\n        response_dict = {}\n        for line in response.splitlines():\n            key, value = response.split(\"=\", 1)\n            response_dict[key] = value\n        return response_dict", "title": ""}
{"_id": "d5987", "text": "def _read_json_file(self, json_file):\n        \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n        self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n        with open(json_file, 'r') as f:\n            return json.load(f, object_pairs_hook=OrderedDict)", "title": ""}
{"_id": "d5988", "text": "def serialize_json_string(self, value):\n        \"\"\"\n        Tries to load an encoded json string back into an object\n        :param json_string:\n        :return:\n        \"\"\"\n\n        # Check if the value might be a json string\n        if not isinstance(value, six.string_types):\n            return value\n\n        # Make sure it starts with a brace\n        if not value.startswith('{') or value.startswith('['):\n            return value\n\n        # Try to load the string\n        try:\n            return json.loads(value)\n        except:\n            return value", "title": ""}
{"_id": "d5989", "text": "def print(cls, *args, **kwargs):\n        \"\"\"Print synchronized.\"\"\"\n        # pylint: disable=protected-access\n        with _shared._PRINT_LOCK:\n            print(*args, **kwargs)\n            _sys.stdout.flush()", "title": ""}
{"_id": "d5990", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d5991", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d5992", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d5993", "text": "def recursively_get_files_from_directory(directory):\n    \"\"\"\n    Return all filenames under recursively found in a directory\n    \"\"\"\n    return [\n        os.path.join(root, filename)\n        for root, directories, filenames in os.walk(directory)\n        for filename in filenames\n    ]", "title": ""}
{"_id": "d5994", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d5995", "text": "def recursively_get_files_from_directory(directory):\n    \"\"\"\n    Return all filenames under recursively found in a directory\n    \"\"\"\n    return [\n        os.path.join(root, filename)\n        for root, directories, filenames in os.walk(directory)\n        for filename in filenames\n    ]", "title": ""}
{"_id": "d5996", "text": "def cfloat64_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\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')", "title": ""}
{"_id": "d5997", "text": "def values(self):\n        \"\"\" :see::meth:RedisMap.keys \"\"\"\n        for val in self._client.hvals(self.key_prefix):\n            yield self._loads(val)", "title": ""}
{"_id": "d5998", "text": "def parse_domain(url):\n    \"\"\" parse the domain from the url \"\"\"\n    domain_match = lib.DOMAIN_REGEX.match(url)\n    if domain_match:\n        return domain_match.group()", "title": ""}
{"_id": "d5999", "text": "def dict_to_html_attrs(dict_):\n    \"\"\"\n    Banana banana\n    \"\"\"\n    res = ' '.join('%s=\"%s\"' % (k, v) for k, v in dict_.items())\n    return res", "title": ""}
{"_id": "d6000", "text": "def get_numbers(s):\n    \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n    result = map(int, re.findall(r'[0-9]+', unicode(s)))\n    return result + [1] * (2 - len(result))", "title": ""}
{"_id": "d6001", "text": "def cor(y_true, y_pred):\n    \"\"\"Compute Pearson correlation coefficient.\n    \"\"\"\n    y_true, y_pred = _mask_nan(y_true, y_pred)\n    return np.corrcoef(y_true, y_pred)[0, 1]", "title": ""}
{"_id": "d6002", "text": "def camel_to_(s):\n    \"\"\"\n    Convert CamelCase to camel_case\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', s)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d6003", "text": "def test(ctx, all=False, verbose=False):\n    \"\"\"Run the tests.\"\"\"\n    cmd = 'tox' if all else 'py.test'\n    if verbose:\n        cmd += ' -v'\n    return ctx.run(cmd, pty=True).return_code", "title": ""}
{"_id": "d6004", "text": "def is_valid_email(email):\n    \"\"\"\n    Check if email is valid\n    \"\"\"\n    pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n    return bool(pattern.match(email))", "title": ""}
{"_id": "d6005", "text": "def _linear_interpolation(x, X, Y):\n    \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n    \"\"\"\n    return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "title": ""}
{"_id": "d6006", "text": "def lines(input):\n    \"\"\"Remove comments and empty lines\"\"\"\n    for raw_line in input:\n        line = raw_line.strip()\n        if line and not line.startswith('#'):\n            yield strip_comments(line)", "title": ""}
{"_id": "d6007", "text": "def confusion_matrix(self):\n        \"\"\"Confusion matrix plot\n        \"\"\"\n        return plot.confusion_matrix(self.y_true, self.y_pred,\n                                     self.target_names, ax=_gen_ax())", "title": ""}
{"_id": "d6008", "text": "def remove_list_duplicates(lista, unique=False):\n    \"\"\"\n    Remove duplicated elements in a list.\n    Args:\n        lista: List with elements to clean duplicates.\n    \"\"\"\n    result = []\n    allready = []\n\n    for elem in lista:\n        if elem not in result:\n            result.append(elem)\n        else:\n            allready.append(elem)\n\n    if unique:\n        for elem in allready:\n            result = list(filter((elem).__ne__, result))\n\n    return result", "title": ""}
{"_id": "d6009", "text": "def confusion_matrix(self):\n        \"\"\"Confusion matrix plot\n        \"\"\"\n        return plot.confusion_matrix(self.y_true, self.y_pred,\n                                     self.target_names, ax=_gen_ax())", "title": ""}
{"_id": "d6010", "text": "def de_blank(val):\n    \"\"\"Remove blank elements in `val` and return `ret`\"\"\"\n    ret = list(val)\n    if type(val) == list:\n        for idx, item in enumerate(val):\n            if item.strip() == '':\n                ret.remove(item)\n            else:\n                ret[idx] = item.strip()\n    return ret", "title": ""}
{"_id": "d6011", "text": "def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE):\n    \"\"\"\n    Returns value of a sine wave at a given frequency and framerate\n    for a given sample i\n    \"\"\"\n    omega = 2.0 * pi * float(frequency)\n    sine = sin(omega * (float(i) / float(framerate)))\n    return float(amplitude) * sine", "title": ""}
{"_id": "d6012", "text": "def slugify(string):\n    \"\"\"\n    Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n    \"\"\"\n    string = re.sub('[^\\w .-]', '', string)\n    string = string.replace(\" \", \"-\")\n    return string", "title": ""}
{"_id": "d6013", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d6014", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d6015", "text": "def add_matplotlib_cmap(cm, name=None):\n    \"\"\"Add a matplotlib colormap.\"\"\"\n    global cmaps\n    cmap = matplotlib_to_ginga_cmap(cm, name=name)\n    cmaps[cmap.name] = cmap", "title": ""}
{"_id": "d6016", "text": "def rm_empty_indices(*args):\n    \"\"\"\n    Remove unwanted list indices. First argument is the list\n    of indices to remove. Other elements are the lists\n    to trim.\n    \"\"\"\n    rm_inds = args[0]\n\n    if not rm_inds:\n        return args[1:]\n\n    keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n    return [[a[i] for i in keep_inds] for a in args[1:]]", "title": ""}
{"_id": "d6017", "text": "def _request(self, data):\n        \"\"\"Moved out to make testing easier.\"\"\"\n        return requests.post(self.endpoint, data=data.encode(\"ascii\")).content", "title": ""}
{"_id": "d6018", "text": "def remove_bad(string):\n    \"\"\"\n    remove problem characters from string\n    \"\"\"\n    remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n    for c in remove:\n        string = string.replace(c, '_')\n    return string", "title": ""}
{"_id": "d6019", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d6020", "text": "def distinct(l):\n    \"\"\"\n    Return a list where the duplicates have been removed.\n\n    Args:\n        l (list): the list to filter.\n\n    Returns:\n        list: the same list without duplicates.\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return (_ for _ in l if not (_ in seen or seen_add(_)))", "title": ""}
{"_id": "d6021", "text": "def prettyprint(d):\n        \"\"\"Print dicttree in Json-like format. keys are sorted\n        \"\"\"\n        print(json.dumps(d, sort_keys=True, \n                         indent=4, separators=(\",\" , \": \")))", "title": ""}
{"_id": "d6022", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d6023", "text": "def print_matrix(X, decimals=1):\n    \"\"\"Pretty printing for numpy matrix X\"\"\"\n    for row in np.round(X, decimals=decimals):\n        print(row)", "title": ""}
{"_id": "d6024", "text": "def strip_spaces(s):\n    \"\"\" Strip excess spaces from a string \"\"\"\n    return u\" \".join([c for c in s.split(u' ') if c])", "title": ""}
{"_id": "d6025", "text": "def pprint_for_ordereddict():\n    \"\"\"\n    Context manager that causes pprint() to print OrderedDict objects as nicely\n    as standard Python dictionary objects.\n    \"\"\"\n    od_saved = OrderedDict.__repr__\n    try:\n        OrderedDict.__repr__ = dict.__repr__\n        yield\n    finally:\n        OrderedDict.__repr__ = od_saved", "title": ""}
{"_id": "d6026", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d6027", "text": "def pp_xml(body):\n    \"\"\"Pretty print format some XML so it's readable.\"\"\"\n    pretty = xml.dom.minidom.parseString(body)\n    return pretty.toprettyxml(indent=\"  \")", "title": ""}
{"_id": "d6028", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d6029", "text": "def insort_no_dup(lst, item):\n    \"\"\"\n    If item is not in lst, add item to list at its sorted position\n    \"\"\"\n    import bisect\n    ix = bisect.bisect_left(lst, item)\n    if lst[ix] != item: \n        lst[ix:ix] = [item]", "title": ""}
{"_id": "d6030", "text": "def remove_duplicates(lst):\n    \"\"\"\n    Emulate what a Python ``set()`` does, but keeping the element's order.\n    \"\"\"\n    dset = set()\n    return [l for l in lst if l not in dset and not dset.add(l)]", "title": ""}
{"_id": "d6031", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d6032", "text": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "title": ""}
{"_id": "d6033", "text": "def toggle_word_wrap(self):\n        \"\"\"\n        Toggles document word wrap.\n\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        self.setWordWrapMode(not self.wordWrapMode() and QTextOption.WordWrap or QTextOption.NoWrap)\n        return True", "title": ""}
{"_id": "d6034", "text": "def strip_head(sequence, values):\n    \"\"\"Strips elements of `values` from the beginning of `sequence`.\"\"\"\n    values = set(values)\n    return list(itertools.dropwhile(lambda x: x in values, sequence))", "title": ""}
{"_id": "d6035", "text": "def print_bintree(tree, indent='  '):\n    \"\"\"print a binary tree\"\"\"\n    for n in sorted(tree.keys()):\n        print \"%s%s\" % (indent * depth(n,tree), n)", "title": ""}
{"_id": "d6036", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d6037", "text": "def log_finished(self):\n\t\t\"\"\"Log that this task is done.\"\"\"\n\t\tdelta = time.perf_counter() - self.start_time\n\t\tlogger.log(\"Finished '\", logger.cyan(self.name),\n\t\t\t\"' after \", logger.magenta(time_to_text(delta)))", "title": ""}
{"_id": "d6038", "text": "def remove_last_entry(self):\n        \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n        self.current_beat -= 1.0 / self.bar[-1][1]\n        self.bar = self.bar[:-1]\n        return self.current_beat", "title": ""}
{"_id": "d6039", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d6040", "text": "def __delitem__(self, key):\n        \"\"\"Remove a variable from this dataset.\n        \"\"\"\n        del self._variables[key]\n        self._coord_names.discard(key)", "title": ""}
{"_id": "d6041", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d6042", "text": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n    \"\"\"Clean a pandas dataframe by:\n        1. Filling empty values with Nan\n        2. Dropping columns with all empty values\n\n    Args:\n        df: Pandas DataFrame\n        fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n        drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n    Returns:\n        DataFrame: cleaned DataFrame\n\n    \"\"\"\n    if fill_nan:\n        df = df.fillna(value=np.nan)\n    if drop_empty_columns:\n        df = df.dropna(axis=1, how='all')\n    return df.sort_index()", "title": ""}
{"_id": "d6043", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d6044", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d6045", "text": "def _load_data(filepath):\n  \"\"\"Loads the images and latent values into Numpy arrays.\"\"\"\n  with h5py.File(filepath, \"r\") as h5dataset:\n    image_array = np.array(h5dataset[\"images\"])\n    # The 'label' data set in the hdf5 file actually contains the float values\n    # and not the class labels.\n    values_array = np.array(h5dataset[\"labels\"])\n  return image_array, values_array", "title": ""}
{"_id": "d6046", "text": "def __convert_none_to_zero(self, ts):\n        \"\"\"\n        Convert None values to 0 so the data works with Matplotlib\n        :param ts:\n        :return: a list with 0s where Nones existed\n        \"\"\"\n\n        if not ts:\n            return ts\n\n        ts_clean = [val if val else 0 for val in ts]\n\n        return ts_clean", "title": ""}
{"_id": "d6047", "text": "def qubits(self):\n        \"\"\"Return a list of qubits as (QuantumRegister, index) pairs.\"\"\"\n        return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]", "title": ""}
{"_id": "d6048", "text": "def _clean_name(self, prefix, obj):\n        \"\"\"Create a C variable name with the given prefix based on the name of obj.\"\"\"\n        return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))", "title": ""}
{"_id": "d6049", "text": "def test():  # pragma: no cover\n    \"\"\"Execute the unit tests on an installed copy of unyt.\n\n    Note that this function requires pytest to run. If pytest is not\n    installed this function will raise ImportError.\n    \"\"\"\n    import pytest\n    import os\n\n    pytest.main([os.path.dirname(os.path.abspath(__file__))])", "title": ""}
{"_id": "d6050", "text": "def close_connection (self):\n        \"\"\"\n        Close an opened url connection.\n        \"\"\"\n        if self.url_connection is None:\n            # no connection is open\n            return\n        try:\n            self.url_connection.close()\n        except Exception:\n            # ignore close errors\n            pass\n        self.url_connection = None", "title": ""}
{"_id": "d6051", "text": "def lint_file(in_file, out_file=None):\n    \"\"\"Helps remove extraneous whitespace from the lines of a file\n\n    :param file in_file: A readable file or file-like\n    :param file out_file: A writable file or file-like\n    \"\"\"\n    for line in in_file:\n        print(line.strip(), file=out_file)", "title": ""}
{"_id": "d6052", "text": "def prepare_path(path):\n    \"\"\"\n    Path join helper method\n    Join paths if list passed\n\n    :type path: str|unicode|list\n    :rtype: str|unicode\n    \"\"\"\n    if type(path) == list:\n        return os.path.join(*path)\n    return path", "title": ""}
{"_id": "d6053", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d6054", "text": "def makedirs(path, mode=0o777, exist_ok=False):\n    \"\"\"A wrapper of os.makedirs().\"\"\"\n    os.makedirs(path, mode, exist_ok)", "title": ""}
{"_id": "d6055", "text": "def text_cleanup(data, key, last_type):\n    \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data", "title": ""}
{"_id": "d6056", "text": "def parse_query_string(query):\n    \"\"\"\n    parse_query_string:\n    very simplistic. won't do the right thing with list values\n    \"\"\"\n    result = {}\n    qparts = query.split('&')\n    for item in qparts:\n        key, value = item.split('=')\n        key = key.strip()\n        value = value.strip()\n        result[key] = unquote_plus(value)\n    return result", "title": ""}
{"_id": "d6057", "text": "def text_cleanup(data, key, last_type):\n    \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data", "title": ""}
{"_id": "d6058", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d6059", "text": "def is_number(obj):\n    \"\"\"Check if obj is number.\"\"\"\n    return isinstance(obj, (int, float, np.int_, np.float_))", "title": ""}
{"_id": "d6060", "text": "def clean_axis(axis):\n    \"\"\"Remove ticks, tick labels, and frame from axis\"\"\"\n    axis.get_xaxis().set_ticks([])\n    axis.get_yaxis().set_ticks([])\n    for spine in list(axis.spines.values()):\n        spine.set_visible(False)", "title": ""}
{"_id": "d6061", "text": "def is_non_empty_string(input_string):\n    \"\"\"\n    Validate if non empty string\n\n    :param input_string: Input is a *str*.\n    :return: True if input is string and non empty.\n       Raise :exc:`Exception` otherwise.\n    \"\"\"\n    try:\n        if not input_string.strip():\n            raise ValueError()\n    except AttributeError as error:\n        raise TypeError(error)\n\n    return True", "title": ""}
{"_id": "d6062", "text": "def cleanup_nodes(doc):\n    \"\"\"\n    Remove text nodes containing only whitespace\n    \"\"\"\n    for node in doc.documentElement.childNodes:\n        if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():\n            doc.documentElement.removeChild(node)\n    return doc", "title": ""}
{"_id": "d6063", "text": "def _clear(self):\n        \"\"\"Resets all assigned data for the current message.\"\"\"\n        self._finished = False\n        self._measurement = None\n        self._message = None\n        self._message_body = None", "title": ""}
{"_id": "d6064", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d6065", "text": "def _updateItemComboBoxIndex(self, item, column, num):\n        \"\"\"Callback for comboboxes: notifies us that a combobox for the given item and column has changed\"\"\"\n        item._combobox_current_index[column] = num\n        item._combobox_current_value[column] = item._combobox_option_list[column][num][0]", "title": ""}
{"_id": "d6066", "text": "def string_to_list(string, sep=\",\", filter_empty=False):\n    \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n    return [value.strip() for value in string.split(sep)\n            if (not filter_empty or value)]", "title": ""}
{"_id": "d6067", "text": "def _convert(tup, dictlist):\n    \"\"\"\n    :param tup: a list of tuples\n    :param di: a dictionary converted from tup\n    :return: dictionary\n    \"\"\"\n    di = {}\n    for a, b in tup:\n        di.setdefault(a, []).append(b)\n    for key, val in di.items():\n        dictlist.append((key, val))\n    return dictlist", "title": ""}
{"_id": "d6068", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d6069", "text": "def _cast_boolean(value):\n    \"\"\"\n    Helper to convert config values to boolean as ConfigParser do.\n    \"\"\"\n    _BOOLEANS = {'1': True, 'yes': True, 'true': True, 'on': True,\n                 '0': False, 'no': False, 'false': False, 'off': False, '': False}\n    value = str(value)\n    if value.lower() not in _BOOLEANS:\n        raise ValueError('Not a boolean: %s' % value)\n\n    return _BOOLEANS[value.lower()]", "title": ""}
{"_id": "d6070", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d6071", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d6072", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d6073", "text": "def replace_list(items, match, replacement):\n    \"\"\"Replaces occurrences of a match string in a given list of strings and returns\n    a list of new strings. The match string can be a regex expression.\n\n    Args:\n        items (list):       the list of strings to modify.\n        match (str):        the search expression.\n        replacement (str):  the string to replace with.\n    \"\"\"\n    return [replace(item, match, replacement) for item in items]", "title": ""}
{"_id": "d6074", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d6075", "text": "def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):\n    \"\"\"Replace month strings occurrences with month number.\"\"\"\n    num, abbr = get_month_from_date_str(date_str, lang)\n    return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE)", "title": ""}
{"_id": "d6076", "text": "def specialRound(number, rounding):\n    \"\"\"A method used to round a number in the way that UsefulUtils rounds.\"\"\"\n    temp = 0\n    if rounding == 0:\n        temp = number\n    else:\n        temp =  round(number, rounding)\n    if temp % 1 == 0:\n        return int(temp)\n    else:\n        return float(temp)", "title": ""}
{"_id": "d6077", "text": "def clean_with_zeros(self,x):\n        \"\"\" set nan and inf rows from x to zero\"\"\"\n        x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0\n        return x", "title": ""}
{"_id": "d6078", "text": "def percentile(values, k):\n    \"\"\"Find the percentile of a list of values.\n\n    :param list values: The list of values to find the percentile of\n    :param int k: The percentile to find\n    :rtype: float or int\n\n    \"\"\"\n    if not values:\n        return None\n    values.sort()\n    index = (len(values) * (float(k) / 100)) - 1\n    return values[int(math.ceil(index))]", "title": ""}
{"_id": "d6079", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d6080", "text": "def add_0x(string):\n    \"\"\"Add 0x to string at start.\n    \"\"\"\n    if isinstance(string, bytes):\n        string = string.decode('utf-8')\n    return '0x' + str(string)", "title": ""}
{"_id": "d6081", "text": "def safe_unicode(string):\n    \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n    if not PY3:\n        uni = string.replace(u'\\u2019', \"'\")\n        return uni.encode('utf-8')\n        \n    return string", "title": ""}
{"_id": "d6082", "text": "def submit(self, fn, *args, **kwargs):\n        \"\"\"Submit an operation\"\"\"\n        corofn = asyncio.coroutine(lambda: fn(*args, **kwargs))\n        return run_coroutine_threadsafe(corofn(), self.loop)", "title": ""}
{"_id": "d6083", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d6084", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d6085", "text": "def _get_user_agent(self):\n        \"\"\"Retrieve the request's User-Agent, if available.\n\n        Taken from Flask Login utils.py.\n        \"\"\"\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 ''", "title": ""}
{"_id": "d6086", "text": "def synthesize(self, duration):\n        \"\"\"\n        Synthesize white noise\n\n        Args:\n            duration (numpy.timedelta64): The duration of the synthesized sound\n        \"\"\"\n        sr = self.samplerate.samples_per_second\n        seconds = duration / Seconds(1)\n        samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n        return AudioSamples(samples, self.samplerate)", "title": ""}
{"_id": "d6087", "text": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "title": ""}
{"_id": "d6088", "text": "def synthesize(self, duration):\n        \"\"\"\n        Synthesize white noise\n\n        Args:\n            duration (numpy.timedelta64): The duration of the synthesized sound\n        \"\"\"\n        sr = self.samplerate.samples_per_second\n        seconds = duration / Seconds(1)\n        samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n        return AudioSamples(samples, self.samplerate)", "title": ""}
{"_id": "d6089", "text": "def _parallel_compare_helper(class_obj, pairs, x, x_link=None):\n    \"\"\"Internal function to overcome pickling problem in python2.\"\"\"\n    return class_obj._compute(pairs, x, x_link)", "title": ""}
{"_id": "d6090", "text": "def add_device_callback(self, callback):\n        \"\"\"Register a callback to be invoked when a new device appears.\"\"\"\n        _LOGGER.debug('Added new callback %s ', callback)\n        self._cb_new_device.append(callback)", "title": ""}
{"_id": "d6091", "text": "def _list_available_rest_versions(self):\n        \"\"\"Return a list of the REST API versions supported by the array\"\"\"\n        url = \"https://{0}/api/api_version\".format(self._target)\n\n        data = self._request(\"GET\", url, reestablish_session=False)\n        return data[\"version\"]", "title": ""}
{"_id": "d6092", "text": "def has_edge(self, p_from, p_to):\n        \"\"\" Returns True when the graph has the given edge. \"\"\"\n        return p_from in self._edges and p_to in self._edges[p_from]", "title": ""}
{"_id": "d6093", "text": "def type(self):\n        \"\"\"Returns type of the data for the given FeatureType.\"\"\"\n        if self is FeatureType.TIMESTAMP:\n            return list\n        if self is FeatureType.BBOX:\n            return BBox\n        return dict", "title": ""}
{"_id": "d6094", "text": "async def send_message():\n    \"\"\"Example of sending a message.\"\"\"\n    jar = aiohttp.CookieJar(unsafe=True)\n    websession = aiohttp.ClientSession(cookie_jar=jar)\n\n    modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession)\n    await modem.login(password=sys.argv[2])\n\n    await modem.sms(phone=sys.argv[3], message=sys.argv[4])\n\n    await modem.logout()\n    await websession.close()", "title": ""}
{"_id": "d6095", "text": "def get_property(self, filename):\n        \"\"\"Opens the file and reads the value\"\"\"\n\n        with open(self.filepath(filename)) as f:\n            return f.read().strip()", "title": ""}
{"_id": "d6096", "text": "def partition_all(n, iterable):\n    \"\"\"Partition a list into equally sized pieces, including last smaller parts\n    http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all\n    \"\"\"\n    it = iter(iterable)\n    while True:\n        chunk = list(itertools.islice(it, n))\n        if not chunk:\n            break\n        yield chunk", "title": ""}
{"_id": "d6097", "text": "def get_date_field(datetimes, field):\n    \"\"\"Adapted from pandas.tslib.get_date_field\"\"\"\n    return np.array([getattr(date, field) for date in datetimes])", "title": ""}
{"_id": "d6098", "text": "def bbox(img):\n    \"\"\"Find the bounding box around nonzero elements in the given array\n\n    Copied from https://stackoverflow.com/a/31402351/5703449 .\n\n    Returns:\n        rowmin, rowmax, colmin, colmax\n    \"\"\"\n    rows = np.any(img, axis=1)\n    cols = np.any(img, axis=0)\n    rmin, rmax = np.where(rows)[0][[0, -1]]\n    cmin, cmax = np.where(cols)[0][[0, -1]]\n\n    return rmin, rmax, cmin, cmax", "title": ""}
{"_id": "d6099", "text": "def _get_str_columns(sf):\n    \"\"\"\n    Returns a list of names of columns that are string type.\n    \"\"\"\n    return [name for name in sf.column_names() if sf[name].dtype == str]", "title": ""}
{"_id": "d6100", "text": "def generate_hash(self, length=30):\n        \"\"\" Generate random string of given length \"\"\"\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", "title": ""}
{"_id": "d6101", "text": "def most_common(items):\n    \"\"\"\n    Wanted functionality from Counters (new in Python 2.7).\n    \"\"\"\n    counts = {}\n    for i in items:\n        counts.setdefault(i, 0)\n        counts[i] += 1\n    return max(six.iteritems(counts), key=operator.itemgetter(1))", "title": ""}
{"_id": "d6102", "text": "def get_user_name():\n    \"\"\"Get user name provide by operating system\n    \"\"\"\n\n    if sys.platform == 'win32':\n        #user = os.getenv('USERPROFILE')\n        user = os.getenv('USERNAME')\n    else:\n        user = os.getenv('LOGNAME')\n\n    return user", "title": ""}
{"_id": "d6103", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x\"\"\"\n    i = bisect.bisect_left(a, x)\n    if i:\n        return a[i-1]\n    raise ValueError", "title": ""}
{"_id": "d6104", "text": "def _encode_gif(images, fps):\n  \"\"\"Encodes numpy images into gif string.\n\n  Args:\n    images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape\n      `[time, height, width, channels]` where `channels` is 1 or 3.\n    fps: frames per second of the animation\n\n  Returns:\n    The encoded gif string.\n\n  Raises:\n    IOError: If the ffmpeg command returns an error.\n  \"\"\"\n  writer = WholeVideoWriter(fps)\n  writer.write_multi(images)\n  return writer.finish()", "title": ""}
{"_id": "d6105", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d6106", "text": "def convert_args_to_sets(f):\n    \"\"\"\n    Converts all args to 'set' type via self.setify function.\n    \"\"\"\n    @wraps(f)\n    def wrapper(*args, **kwargs):\n        args = (setify(x) for x in args)\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d6107", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d6108", "text": "def _merge_args_with_kwargs(args_dict, kwargs_dict):\n    \"\"\"Merge args with kwargs.\"\"\"\n    ret = args_dict.copy()\n    ret.update(kwargs_dict)\n    return ret", "title": ""}
{"_id": "d6109", "text": "def __or__(self, other):\n        \"\"\"Return the union of two RangeSets as a new RangeSet.\n\n        (I.e. all elements that are in either set.)\n        \"\"\"\n        if not isinstance(other, set):\n            return NotImplemented\n        return self.union(other)", "title": ""}
{"_id": "d6110", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d6111", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d6112", "text": "def map_with_obj(f, dct):\n    \"\"\"\n        Implementation of Ramda's mapObjIndexed without the final argument.\n        This returns the original key with the mapped value. Use map_key_values to modify the keys too\n    :param f: Called with a key and value\n    :param dct:\n    :return {dict}: Keyed by the original key, valued by the mapped value\n    \"\"\"\n    f_dict = {}\n    for k, v in dct.items():\n        f_dict[k] = f(k, v)\n    return f_dict", "title": ""}
{"_id": "d6113", "text": "def rgba_bytes_tuple(self, x):\n        \"\"\"Provides the color corresponding to value `x` in the\n        form of a tuple (R,G,B,A) with int values between 0 and 255.\n        \"\"\"\n        return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))", "title": ""}
{"_id": "d6114", "text": "def transform(self, df):\n        \"\"\"\n        Transforms a DataFrame in place. Computes all outputs of the DataFrame.\n\n        Args:\n            df (pandas.DataFrame): DataFrame to transform.\n        \"\"\"\n        for name, function in self.outputs:\n            df[name] = function(df)", "title": ""}
{"_id": "d6115", "text": "def parse_markdown(markdown_content, site_settings):\n    \"\"\"Parse markdown text to html.\n\n    :param markdown_content: Markdown text lists #TODO#\n    \"\"\"\n    markdown_extensions = set_markdown_extensions(site_settings)\n\n    html_content = markdown.markdown(\n        markdown_content,\n        extensions=markdown_extensions,\n    )\n\n    return html_content", "title": ""}
{"_id": "d6116", "text": "def _rgbtomask(self, obj):\n        \"\"\"Convert RGB arrays from mask canvas object back to boolean mask.\"\"\"\n        dat = obj.get_image().get_data()  # RGB arrays\n        return dat.sum(axis=2).astype(np.bool)", "title": ""}
{"_id": "d6117", "text": "def similarity_transformation(rot, mat):\n    \"\"\" R x M x R^-1 \"\"\"\n    return np.dot(rot, np.dot(mat, np.linalg.inv(rot)))", "title": ""}
{"_id": "d6118", "text": "def process_bool_arg(arg):\n    \"\"\" Determine True/False from argument \"\"\"\n    if isinstance(arg, bool):\n        return arg\n    elif isinstance(arg, basestring):\n        if arg.lower() in [\"true\", \"1\"]:\n            return True\n        elif arg.lower() in [\"false\", \"0\"]:\n            return False", "title": ""}
{"_id": "d6119", "text": "def create_rot2d(angle):\n    \"\"\"Create 2D rotation matrix\"\"\"\n    ca = math.cos(angle)\n    sa = math.sin(angle)\n    return np.array([[ca, -sa], [sa, ca]])", "title": ""}
{"_id": "d6120", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d6121", "text": "def floor(self):\n    \"\"\"Round `x` and `y` down to integers.\"\"\"\n    return Point(int(math.floor(self.x)), int(math.floor(self.y)))", "title": ""}
{"_id": "d6122", "text": "def main(args=sys.argv):\n    \"\"\"\n    main entry point for the jardiff CLI\n    \"\"\"\n\n    parser = create_optparser(args[0])\n    return cli(parser.parse_args(args[1:]))", "title": ""}
{"_id": "d6123", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d6124", "text": "def set_subparsers_args(self, *args, **kwargs):\n        \"\"\"\n        Sets args and kwargs that are passed when creating a subparsers group\n        in an argparse.ArgumentParser i.e. when calling\n        argparser.ArgumentParser.add_subparsers\n        \"\"\"\n        self.subparsers_args = args\n        self.subparsers_kwargs = kwargs", "title": ""}
{"_id": "d6125", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d6126", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d6127", "text": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "title": ""}
{"_id": "d6128", "text": "def _openResources(self):\n        \"\"\" Uses numpy.load to open the underlying file\n        \"\"\"\n        arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n        check_is_an_array(arr)\n        self._array = arr", "title": ""}
{"_id": "d6129", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d6130", "text": "def cint32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):\n        return np.fromiter(cptr, dtype=np.int32, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d6131", "text": "def lint(ctx: click.Context, amend: bool = False, stage: bool = False):\n    \"\"\"\n    Runs all linters\n\n    Args:\n        ctx: click context\n        amend: whether or not to commit results\n        stage: whether or not to stage changes\n    \"\"\"\n    _lint(ctx, amend, stage)", "title": ""}
{"_id": "d6132", "text": "def c_array(ctype, values):\n    \"\"\"Convert a python string to c array.\"\"\"\n    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):\n        return (ctype * len(values)).from_buffer_copy(values)\n    return (ctype * len(values))(*values)", "title": ""}
{"_id": "d6133", "text": "def lint(ctx: click.Context, amend: bool = False, stage: bool = False):\n    \"\"\"\n    Runs all linters\n\n    Args:\n        ctx: click context\n        amend: whether or not to commit results\n        stage: whether or not to stage changes\n    \"\"\"\n    _lint(ctx, amend, stage)", "title": ""}
{"_id": "d6134", "text": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "title": ""}
{"_id": "d6135", "text": "def _save_cookies(requests_cookiejar, filename):\n    \"\"\"Save cookies to a file.\"\"\"\n    with open(filename, 'wb') as handle:\n        pickle.dump(requests_cookiejar, handle)", "title": ""}
{"_id": "d6136", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d6137", "text": "def seconds_to_hms(input_seconds):\n    \"\"\"Convert seconds to human-readable time.\"\"\"\n    minutes, seconds = divmod(input_seconds, 60)\n    hours, minutes = divmod(minutes, 60)\n\n    hours = int(hours)\n    minutes = int(minutes)\n    seconds = str(int(seconds)).zfill(2)\n\n    return hours, minutes, seconds", "title": ""}
{"_id": "d6138", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d6139", "text": "def list(self):\n        \"\"\"position in 3d space\"\"\"\n        return [self._pos3d.x, self._pos3d.y, self._pos3d.z]", "title": ""}
{"_id": "d6140", "text": "def p_if_statement_2(self, p):\n        \"\"\"if_statement : IF LPAREN expr RPAREN statement ELSE statement\"\"\"\n        p[0] = ast.If(predicate=p[3], consequent=p[5], alternative=p[7])", "title": ""}
{"_id": "d6141", "text": "def get_closest_index(myList, myNumber):\n    \"\"\"\n    Assumes myList is sorted. Returns closest value to myNumber.\n    If two numbers are equally close, return the smallest number.\n\n    Parameters\n    ----------\n    myList : array\n        The list in which to find the closest value to myNumber\n    myNumber : float\n        The number to find the closest to in MyList\n\n    Returns\n    -------\n    closest_values_index : int\n        The index in the array of the number closest to myNumber in myList\n    \"\"\"\n    closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n    return closest_values_index", "title": ""}
{"_id": "d6142", "text": "def update_table_row(self, table, row_idx):\n        \"\"\"Add this instance as a row on a `astropy.table.Table` \"\"\"\n        try:\n            table[row_idx]['timestamp'] = self.timestamp\n            table[row_idx]['status'] = self.status\n        except IndexError:\n            print(\"Index error\", len(table), row_idx)", "title": ""}
{"_id": "d6143", "text": "def dropna(self, subset=None):\n        \"\"\"Remove missing values according to Baloo's convention.\n\n        Parameters\n        ----------\n        subset : list of str, optional\n            Which columns to check for missing values in.\n\n        Returns\n        -------\n        DataFrame\n            DataFrame with no null values in columns.\n\n        \"\"\"\n        subset = check_and_obtain_subset_columns(subset, self)\n        not_nas = [v.notna() for v in self[subset]._iter()]\n        and_filter = reduce(lambda x, y: x & y, not_nas)\n\n        return self[and_filter]", "title": ""}
{"_id": "d6144", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d6145", "text": "def create_table_from_fits(fitsfile, hduname, colnames=None):\n    \"\"\"Memory efficient function for loading a table from a FITS\n    file.\"\"\"\n\n    if colnames is None:\n        return Table.read(fitsfile, hduname)\n\n    cols = []\n    with fits.open(fitsfile, memmap=True) as h:\n        for k in colnames:\n            data = h[hduname].data.field(k)\n            cols += [Column(name=k, data=data)]\n    return Table(cols)", "title": ""}
{"_id": "d6146", "text": "def check_no_element_by_selector(self, selector):\n    \"\"\"Assert an element does not exist matching the given 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)))", "title": ""}
{"_id": "d6147", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d6148", "text": "def POST(self, *args, **kwargs):\n        \"\"\" POST request \"\"\"\n        return self._handle_api(self.API_POST, args, kwargs)", "title": ""}
{"_id": "d6149", "text": "def run(*tasks: Awaitable, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop()):\n    \"\"\"Helper to run tasks in the event loop\n\n    :param tasks: Tasks to run in the event loop.\n    :param loop: The event loop.\n    \"\"\"\n    futures = [asyncio.ensure_future(task, loop=loop) for task in tasks]\n    return loop.run_until_complete(asyncio.gather(*futures))", "title": ""}
{"_id": "d6150", "text": "def shutdown():\n    \"\"\"Manually shutdown the async API.\n\n    Cancels all related tasks and all the socket transportation.\n    \"\"\"\n    global handler, transport, protocol\n    if handler is not None:\n        handler.close()\n        transport.close()\n        handler = None\n        transport = None\n        protocol = None", "title": ""}
{"_id": "d6151", "text": "def setobjattr(obj, key, value):\n    \"\"\"Sets an object attribute with the correct data type.\"\"\"\n    try:\n        setattr(obj, key, int(value))\n    except ValueError:\n        try:\n            setattr(obj, key, float(value))\n        except ValueError:\n            # string if not number\n            try:\n                setattr(obj, key, str(value))\n            except UnicodeEncodeError:\n                setattr(obj, key, value)", "title": ""}
{"_id": "d6152", "text": "def exit(exit_code=0):\n  r\"\"\"A function to support exiting from exit hooks.\n\n  Could also be used to exit from the calling scripts in a thread safe manner.\n  \"\"\"\n  core.processExitHooks()\n\n  if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook\n    sys.stderr.flush()\n    sys.stdout.flush()\n    os._exit(exit_code) #pylint: disable=W0212\n\n  sys.exit(exit_code)", "title": ""}
{"_id": "d6153", "text": "def _update_fontcolor(self, fontcolor):\n        \"\"\"Updates text font color button\n\n        Parameters\n        ----------\n\n        fontcolor: Integer\n        \\tText color in integer RGB format\n\n        \"\"\"\n\n        textcolor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n        textcolor.SetRGB(fontcolor)\n\n        self.textcolor_choice.SetColour(textcolor)", "title": ""}
{"_id": "d6154", "text": "def _single_page_pdf(page):\n    \"\"\"Construct a single page PDF from the provided page in memory\"\"\"\n    pdf = Pdf.new()\n    pdf.pages.append(page)\n    bio = BytesIO()\n    pdf.save(bio)\n    bio.seek(0)\n    return bio.read()", "title": ""}
{"_id": "d6155", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d6156", "text": "def dim_axis_label(dimensions, separator=', '):\n    \"\"\"\n    Returns an axis label for one or more dimensions.\n    \"\"\"\n    if not isinstance(dimensions, list): dimensions = [dimensions]\n    return separator.join([d.pprint_label for d in dimensions])", "title": ""}
{"_id": "d6157", "text": "def setPixel(self, x, y, color):\n        \"\"\"Set the pixel at (x,y) to the integers in sequence 'color'.\"\"\"\n        return _fitz.Pixmap_setPixel(self, x, y, color)", "title": ""}
{"_id": "d6158", "text": "def get_best_encoding(stream):\n    \"\"\"Returns the default stream encoding if not found.\"\"\"\n    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n    if is_ascii_encoding(rv):\n        return 'utf-8'\n    return rv", "title": ""}
{"_id": "d6159", "text": "def palettebar(height, length, colormap):\n    \"\"\"Return the channels of a palettebar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.palettize(cbar)", "title": ""}
{"_id": "d6160", "text": "def make_file_read_only(file_path):\n    \"\"\"\n    Removes the write permissions for the given file for owner, groups and others.\n\n    :param file_path: The file whose privileges are revoked.\n    :raise FileNotFoundError: If the given file does not exist.\n    \"\"\"\n    old_permissions = os.stat(file_path).st_mode\n    os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)", "title": ""}
{"_id": "d6161", "text": "def OnMove(self, event):\n        \"\"\"Main window move event\"\"\"\n\n        # Store window position in config\n        position = self.main_window.GetScreenPositionTuple()\n\n        config[\"window_position\"] = repr(position)", "title": ""}
{"_id": "d6162", "text": "def inpaint(self):\n        \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n        import inpaint\n        filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n        self.raster_data = np.ma.masked_invalid(filled)", "title": ""}
{"_id": "d6163", "text": "def writefile(openedfile, newcontents):\n    \"\"\"Set the contents of a file.\"\"\"\n    openedfile.seek(0)\n    openedfile.truncate()\n    openedfile.write(newcontents)", "title": ""}
{"_id": "d6164", "text": "def base64ToImage(imgData, out_path, out_file):\n        \"\"\" converts a base64 string to a file \"\"\"\n        fh = open(os.path.join(out_path, out_file), \"wb\")\n        fh.write(imgData.decode('base64'))\n        fh.close()\n        del fh\n        return os.path.join(out_path, out_file)", "title": ""}
{"_id": "d6165", "text": "def enable_proxy(self, host, port):\n        \"\"\"Enable a default web proxy\"\"\"\n\n        self.proxy = [host, _number(port)]\n        self.proxy_enabled = True", "title": ""}
{"_id": "d6166", "text": "def base64ToImage(imgData, out_path, out_file):\n        \"\"\" converts a base64 string to a file \"\"\"\n        fh = open(os.path.join(out_path, out_file), \"wb\")\n        fh.write(imgData.decode('base64'))\n        fh.close()\n        del fh\n        return os.path.join(out_path, out_file)", "title": ""}
{"_id": "d6167", "text": "def make_qs(n, m=None):\n    \"\"\"Make sympy symbols q0, q1, ...\n    \n    Args:\n        n(int), m(int, optional):\n            If specified both n and m, returns [qn, q(n+1), ..., qm],\n            Only n is specified, returns[q0, q1, ..., qn].\n\n    Return:\n        tuple(Symbol): Tuple of sympy symbols.\n    \"\"\"\n    try:\n        import sympy\n    except ImportError:\n        raise ImportError(\"This function requires sympy. Please install it.\")\n    if m is None:\n        syms = sympy.symbols(\" \".join(f\"q{i}\" for i in range(n)))\n        if isinstance(syms, tuple):\n            return syms\n        else:\n            return (syms,)\n    syms = sympy.symbols(\" \".join(f\"q{i}\" for i in range(n, m)))\n    if isinstance(syms, tuple):\n        return syms\n    else:\n        return (syms,)", "title": ""}
{"_id": "d6168", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d6169", "text": "def render_template(env, filename, values=None):\n    \"\"\"\n    Render a jinja template\n    \"\"\"\n    if not values:\n        values = {}\n    tmpl = env.get_template(filename)\n    return tmpl.render(values)", "title": ""}
{"_id": "d6170", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d6171", "text": "def update(self):\n        \"\"\"Updates image to be displayed with new time frame.\"\"\"\n        if self.single_channel:\n            self.im.set_data(self.data[self.ind, :, :])\n        else:\n            self.im.set_data(self.data[self.ind, :, :, :])\n        self.ax.set_ylabel('time frame %s' % self.ind)\n        self.im.axes.figure.canvas.draw()", "title": ""}
{"_id": "d6172", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d6173", "text": "def comments(tag, limit=0, flags=0, **kwargs):\n    \"\"\"Get comments only.\"\"\"\n\n    return [comment for comment in cm.CommentsMatch(tag).get_comments(limit)]", "title": ""}
{"_id": "d6174", "text": "def abs_img(img):\n    \"\"\" Return an image with the binarised version of the data of `img`.\"\"\"\n    bool_img = np.abs(read_img(img).get_data())\n    return bool_img.astype(int)", "title": ""}
{"_id": "d6175", "text": "def safe_setattr(obj, name, value):\n    \"\"\"Attempt to setattr but catch AttributeErrors.\"\"\"\n    try:\n        setattr(obj, name, value)\n        return True\n    except AttributeError:\n        return False", "title": ""}
{"_id": "d6176", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d6177", "text": "def top(n, width=WIDTH, style=STYLE):\n    \"\"\"Prints the top row of a table\"\"\"\n    return hrule(n, width, linestyle=STYLES[style].top)", "title": ""}
{"_id": "d6178", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d6179", "text": "def smallest_signed_angle(source, target):\n    \"\"\"Find the smallest angle going from angle `source` to angle `target`.\"\"\"\n    dth = target - source\n    dth = (dth + np.pi) % (2.0 * np.pi) - np.pi\n    return dth", "title": ""}
{"_id": "d6180", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d6181", "text": "def close_error_dlg(self):\n        \"\"\"Close error dialog.\"\"\"\n        if self.error_dlg.dismiss_box.isChecked():\n            self.dismiss_error = True\n        self.error_dlg.reject()", "title": ""}
{"_id": "d6182", "text": "def isbinary(*args):\n    \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n    return all(map(lambda c: isnumber(c) or isbool(c), args))", "title": ""}
{"_id": "d6183", "text": "def log_request(self, code='-', size='-'):\n        \"\"\"Selectively log an accepted request.\"\"\"\n\n        if self.server.logRequests:\n            BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)", "title": ""}
{"_id": "d6184", "text": "def list_autoscaling_group(region, filter_by_kwargs):\n    \"\"\"List all Auto Scaling Groups.\"\"\"\n    conn = boto.ec2.autoscale.connect_to_region(region)\n    groups = conn.get_all_groups()\n    return lookup(groups, filter_by=filter_by_kwargs)", "title": ""}
{"_id": "d6185", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d6186", "text": "def get_as_bytes(self, s3_path):\n        \"\"\"\n        Get the contents of an object stored in S3 as bytes\n\n        :param s3_path: URL for target S3 location\n        :return: File contents as pure bytes\n        \"\"\"\n        (bucket, key) = self._path_to_bucket_and_key(s3_path)\n        obj = self.s3.Object(bucket, key)\n        contents = obj.get()['Body'].read()\n        return contents", "title": ""}
{"_id": "d6187", "text": "def array_size(x, axis):\n  \"\"\"Calculate the size of `x` along `axis` dimensions only.\"\"\"\n  axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)\n  return max(numpy.prod(axis_shape), 1)", "title": ""}
{"_id": "d6188", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d6189", "text": "def __len__(self):\n        \"\"\"Return total data length of the list and its headers.\"\"\"\n        return self.chunk_length() + len(self.type) + len(self.header) + 4", "title": ""}
{"_id": "d6190", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d6191", "text": "def __len__(self):\n        \"\"\"Return total data length of the list and its headers.\"\"\"\n        return self.chunk_length() + len(self.type) + len(self.header) + 4", "title": ""}
{"_id": "d6192", "text": "def _to_bstr(l):\n    \"\"\"Convert to byte string.\"\"\"\n\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", "title": ""}
{"_id": "d6193", "text": "def batch(input_iter, batch_size=32):\n  \"\"\"Batches data from an iterator that returns single items at a time.\"\"\"\n  input_iter = iter(input_iter)\n  next_ = list(itertools.islice(input_iter, batch_size))\n  while next_:\n    yield next_\n    next_ = list(itertools.islice(input_iter, batch_size))", "title": ""}
{"_id": "d6194", "text": "def array_bytes(array):\n    \"\"\" Estimates the memory of the supplied array in bytes \"\"\"\n    return np.product(array.shape)*np.dtype(array.dtype).itemsize", "title": ""}
{"_id": "d6195", "text": "def n_choose_k(n, k):\n    \"\"\" get the number of quartets as n-choose-k. This is used\n    in equal splits to decide whether a split should be exhaustively sampled\n    or randomly sampled. Edges near tips can be exhaustive while highly nested\n    edges probably have too many quartets\n    \"\"\"\n    return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1))", "title": ""}
{"_id": "d6196", "text": "def _to_bstr(l):\n    \"\"\"Convert to byte string.\"\"\"\n\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", "title": ""}
{"_id": "d6197", "text": "def ratio_and_percentage(current, total, time_remaining):\n    \"\"\"Returns the progress ratio and percentage.\"\"\"\n    return \"{} / {} ({}% completed)\".format(current, total, int(current / total * 100))", "title": ""}
{"_id": "d6198", "text": "def bytes_to_c_array(data):\n    \"\"\"\n    Make a C array using the given string.\n    \"\"\"\n    chars = [\n        \"'{}'\".format(encode_escape(i))\n        for i in decode_escape(data)\n    ]\n    return ', '.join(chars) + ', 0'", "title": ""}
{"_id": "d6199", "text": "def MatrixSolve(a, rhs, adj):\n    \"\"\"\n    Matrix solve op.\n    \"\"\"\n    return np.linalg.solve(a if not adj else _adjoint(a), rhs),", "title": ""}
{"_id": "d6200", "text": "def cpp_prog_builder(build_context, target):\n    \"\"\"Build a C++ binary executable\"\"\"\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)", "title": ""}
{"_id": "d6201", "text": "def MatrixSolve(a, rhs, adj):\n    \"\"\"\n    Matrix solve op.\n    \"\"\"\n    return np.linalg.solve(a if not adj else _adjoint(a), rhs),", "title": ""}
{"_id": "d6202", "text": "def lighting(im, b, c):\n    \"\"\" Adjust image balance and contrast \"\"\"\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)", "title": ""}
{"_id": "d6203", "text": "def arglexsort(arrays):\n    \"\"\"\n    Returns the indices of the lexicographical sorting\n    order of the supplied arrays.\n    \"\"\"\n    dtypes = ','.join(array.dtype.str for array in arrays)\n    recarray = np.empty(len(arrays[0]), dtype=dtypes)\n    for i, array in enumerate(arrays):\n        recarray['f%s' % i] = array\n    return recarray.argsort()", "title": ""}
{"_id": "d6204", "text": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "title": ""}
{"_id": "d6205", "text": "def unique_list(lst):\n    \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n    uniq = []\n    for item in lst:\n        if item not in uniq:\n            uniq.append(item)\n    return uniq", "title": ""}
{"_id": "d6206", "text": "def jaccard(c_1, c_2):\n    \"\"\"\n    Calculates the Jaccard similarity between two sets of nodes. Called by mroc.\n\n    Inputs:  - c_1: Community (set of nodes) 1.\n             - c_2: Community (set of nodes) 2.\n\n    Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.\n    \"\"\"\n    nom = np.intersect1d(c_1, c_2).size\n    denom = np.union1d(c_1, c_2).size\n    return nom/denom", "title": ""}
{"_id": "d6207", "text": "def unique_list(lst):\n    \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n    uniq = []\n    for item in lst:\n        if item not in uniq:\n            uniq.append(item)\n    return uniq", "title": ""}
{"_id": "d6208", "text": "def getOffset(self, loc):\n        \"\"\" Returns the offset between the given point and this point \"\"\"\n        return Location(loc.x - self.x, loc.y - self.y)", "title": ""}
{"_id": "d6209", "text": "def sort_data(data, cols):\n    \"\"\"Sort `data` rows and order columns\"\"\"\n    return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "title": ""}
{"_id": "d6210", "text": "def elliot_function( signal, derivative=False ):\n    \"\"\" A fast approximation of sigmoid \"\"\"\n    s = 1 # steepness\n    \n    abs_signal = (1 + np.abs(signal * s))\n    if derivative:\n        return 0.5 * s / abs_signal**2\n    else:\n        # Return the activation signal\n        return 0.5*(signal * s) / abs_signal + 0.5", "title": ""}
{"_id": "d6211", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d6212", "text": "def get_element_offset(self, ty, position):\n        \"\"\"\n        Get byte offset of type's ty element at the given position\n        \"\"\"\n\n        offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position)\n        if offset == -1:\n            raise ValueError(\"Could not determined offset of {}th \"\n                    \"element of the type '{}'. Is it a struct type?\".format(\n                    position, str(ty)))\n        return offset", "title": ""}
{"_id": "d6213", "text": "def sort_func(self, key):\n        \"\"\"Sorting logic for `Quantity` objects.\"\"\"\n        if key == self._KEYS.VALUE:\n            return 'aaa'\n        if key == self._KEYS.SOURCE:\n            return 'zzz'\n        return key", "title": ""}
{"_id": "d6214", "text": "def logical_or(self, other):\n        \"\"\"logical_or(t) = self(t) or other(t).\"\"\"\n        return self.operation(other, lambda x, y: int(x or y))", "title": ""}
{"_id": "d6215", "text": "def shall_skip(app, module, private):\n    \"\"\"Check if we want to skip this module.\n\n    :param app: the sphinx app\n    :type app: :class:`sphinx.application.Sphinx`\n    :param module: the module name\n    :type module: :class:`str`\n    :param private: True, if privates are allowed\n    :type private: :class:`bool`\n    \"\"\"\n    logger.debug('Testing if %s should be skipped.', module)\n    # skip if it has a \"private\" name and this is selected\n    if module != '__init__.py' and module.startswith('_') and \\\n       not private:\n        logger.debug('Skip %s because its either private or __init__.', module)\n        return True\n    logger.debug('Do not skip %s', module)\n    return False", "title": ""}
{"_id": "d6216", "text": "def set_scrollregion(self, event=None):\n        \"\"\" Set the scroll region on the canvas\"\"\"\n        self.canvas.configure(scrollregion=self.canvas.bbox('all'))", "title": ""}
{"_id": "d6217", "text": "def generate_split_tsv_lines(fn, header):\n    \"\"\"Returns dicts with header-keys and psm statistic values\"\"\"\n    for line in generate_tsv_psms_line(fn):\n        yield {x: y for (x, y) in zip(header, line.strip().split('\\t'))}", "title": ""}
{"_id": "d6218", "text": "def to_pascal_case(s):\n    \"\"\"Transform underscore separated string to pascal case\n\n    \"\"\"\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())", "title": ""}
{"_id": "d6219", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d6220", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d6221", "text": "def sqliteRowsToDicts(sqliteRows):\n    \"\"\"\n    Unpacks sqlite rows as returned by fetchall\n    into an array of simple dicts.\n\n    :param sqliteRows: array of rows returned from fetchall DB call\n    :return:  array of dicts, keyed by the column names.\n    \"\"\"\n    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "title": ""}
{"_id": "d6222", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d6223", "text": "def stack_push(self, thing):\n        \"\"\"\n        Push 'thing' to the stack, writing the thing to memory and adjusting the stack pointer.\n        \"\"\"\n        # increment sp\n        sp = self.regs.sp + self.arch.stack_change\n        self.regs.sp = sp\n        return self.memory.store(sp, thing, endness=self.arch.memory_endness)", "title": ""}
{"_id": "d6224", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d6225", "text": "def stackplot(marray, seconds=None, start_time=None, ylabels=None):\n    \"\"\"\n    will plot a stack of traces one above the other assuming\n    marray.shape = numRows, numSamples\n    \"\"\"\n    tarray = np.transpose(marray)\n    stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)\n    plt.show()", "title": ""}
{"_id": "d6226", "text": "def comma_delimited_to_list(list_param):\n    \"\"\"Convert comma-delimited list / string into a list of strings\n\n    :param list_param: Comma-delimited string\n    :type list_param: str | unicode\n    :return: A list of strings\n    :rtype: list\n    \"\"\"\n    if isinstance(list_param, list):\n        return list_param\n    if isinstance(list_param, str):\n        return list_param.split(',')\n    else:\n        return []", "title": ""}
{"_id": "d6227", "text": "async def _send_plain_text(self, request: Request, stack: Stack):\n        \"\"\"\n        Sends plain text using `_send_text()`.\n        \"\"\"\n\n        await self._send_text(request, stack, None)", "title": ""}
{"_id": "d6228", "text": "def to_str(obj):\n    \"\"\"Attempts to convert given object to a string object\n    \"\"\"\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)", "title": ""}
{"_id": "d6229", "text": "def weighted_std(values, weights):\n    \"\"\" Calculate standard deviation weighted by errors \"\"\"\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)", "title": ""}
{"_id": "d6230", "text": "def convert_value(bind, value):\n    \"\"\" Type casting. \"\"\"\n    type_name = get_type(bind)\n    try:\n        return typecast.cast(type_name, value)\n    except typecast.ConverterError:\n        return value", "title": ""}
{"_id": "d6231", "text": "def _mean_absolute_error(y, y_pred, w):\n    \"\"\"Calculate the mean absolute error.\"\"\"\n    return np.average(np.abs(y_pred - y), weights=w)", "title": ""}
{"_id": "d6232", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d6233", "text": "def lsem (inlist):\n    \"\"\"\nReturns the estimated standard error of the mean (sx-bar) of the\nvalues in the passed list.  sem = stdev / sqrt(n)\n\nUsage:   lsem(inlist)\n\"\"\"\n    sd = stdev(inlist)\n    n = len(inlist)\n    return sd/math.sqrt(n)", "title": ""}
{"_id": "d6234", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d6235", "text": "def range(*args, interval=0):\n    \"\"\"Generate a given range of numbers.\n\n    It supports the same arguments as the builtin function.\n    An optional interval can be given to space the values out.\n    \"\"\"\n    agen = from_iterable.raw(builtins.range(*args))\n    return time.spaceout.raw(agen, interval) if interval else agen", "title": ""}
{"_id": "d6236", "text": "def load(self, name):\n        \"\"\"Loads and returns foreign library.\"\"\"\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)", "title": ""}
{"_id": "d6237", "text": "def set_executable(filename):\n    \"\"\"Set the exectuable bit on the given filename\"\"\"\n    st = os.stat(filename)\n    os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d6238", "text": "async def result_processor(tasks):\n    \"\"\"An async result aggregator that combines all the results\n       This gets executed in unsync.loop and unsync.thread\"\"\"\n    output = {}\n    for task in tasks:\n        num, res = await task\n        output[num] = res\n    return output", "title": ""}
{"_id": "d6239", "text": "def _update_staticmethod(self, oldsm, newsm):\n        \"\"\"Update a staticmethod update.\"\"\"\n        # While we can't modify the staticmethod object itself (it has no\n        # mutable attributes), we *can* extract the underlying function\n        # (by calling __get__(), which returns it) and update it in-place.\n        # We don't have the class available to pass to __get__() but any\n        # object except None will do.\n        self._update(None, None, oldsm.__get__(0), newsm.__get__(0))", "title": ""}
{"_id": "d6240", "text": "def find_task_by_id(self, id, session=None):\n        \"\"\"\n        Find task with the given record ID.\n        \"\"\"\n        with self._session(session) as session:\n            return session.query(TaskRecord).get(id)", "title": ""}
{"_id": "d6241", "text": "def standard_deviation(numbers):\n    \"\"\"Return standard deviation.\"\"\"\n    numbers = list(numbers)\n    if not numbers:\n        return 0\n    mean = sum(numbers) / len(numbers)\n    return (sum((n - mean) ** 2 for n in numbers) /\n            len(numbers)) ** .5", "title": ""}
{"_id": "d6242", "text": "def getExperiments(uuid: str):\n    \"\"\" list active (running or completed) experiments\"\"\"\n    return jsonify([x.deserialize() for x in Experiment.query.all()])", "title": ""}
{"_id": "d6243", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d6244", "text": "def convert_camel_case_to_snake_case(name):\n    \"\"\"Convert CamelCase to snake_case.\"\"\"\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()", "title": ""}
{"_id": "d6245", "text": "def stop(self, timeout=None):\n        \"\"\"Stop the thread.\"\"\"\n        logger.debug(\"docker plugin - Close thread for container {}\".format(self._container.name))\n        self._stopper.set()", "title": ""}
{"_id": "d6246", "text": "def inc_date(date_obj, num, date_fmt):\n    \"\"\"Increment the date by a certain number and return date object.\n    as the specific string format.\n    \"\"\"\n    return (date_obj + timedelta(days=num)).strftime(date_fmt)", "title": ""}
{"_id": "d6247", "text": "def stop_button_click_handler(self):\n        \"\"\"Method to handle what to do when the stop button is pressed\"\"\"\n        self.stop_button.setDisabled(True)\n        # Interrupt computations or stop debugging\n        if not self.shellwidget._reading:\n            self.interrupt_kernel()\n        else:\n            self.shellwidget.write_to_stdin('exit')", "title": ""}
{"_id": "d6248", "text": "def excepthook(self, except_type, exception, traceback):\n    \"\"\"Not Used: Custom exception hook to replace sys.excepthook\n\n    This is for CPython's default shell. IPython does not use sys.exepthook.\n\n    https://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set\n    \"\"\"\n    if except_type is DeepReferenceError:\n        print(exception.msg)\n    else:\n        self.default_excepthook(except_type, exception, traceback)", "title": ""}
{"_id": "d6249", "text": "def wordify(text):\n    \"\"\"Generate a list of words given text, removing punctuation.\n\n    Parameters\n    ----------\n    text : unicode\n        A piece of english text.\n\n    Returns\n    -------\n    words : list\n        List of words.\n    \"\"\"\n    stopset = set(nltk.corpus.stopwords.words('english'))\n    tokens = nltk.WordPunctTokenizer().tokenize(text)\n    return [w for w in tokens if w not in stopset]", "title": ""}
{"_id": "d6250", "text": "def dict_update_newkeys(dict_, dict2):\n    \"\"\" Like dict.update, but does not overwrite items \"\"\"\n    for key, val in six.iteritems(dict2):\n        if key not in dict_:\n            dict_[key] = val", "title": ""}
{"_id": "d6251", "text": "def toList(variable, types=(basestring, int, float, )):\n    \"\"\"Converts a variable of type string, int, float to a list, containing the\n    variable as the only element.\n\n    :param variable: any python object\n    :type variable: (str, int, float, others)\n\n    :returns: [variable] or variable\n    \"\"\"\n    if isinstance(variable, types):\n        return [variable]\n    else:\n        return variable", "title": ""}
{"_id": "d6252", "text": "def set_json_item(key, value):\n    \"\"\" manipulate json data on the fly\n    \"\"\"\n    data = get_json()\n    data[key] = value\n\n    request = get_request()\n    request[\"BODY\"] = json.dumps(data)", "title": ""}
{"_id": "d6253", "text": "def to_binary(s, encoding='utf8'):\n    \"\"\"Portable cast function.\n\n    In python 2 the ``str`` function which is used to coerce objects to bytes does not\n    accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n    :param s: object to be converted to binary_type\n    :return: binary_type instance, representing s.\n    \"\"\"\n    if PY3:  # pragma: no cover\n        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n    return binary_type(s)", "title": ""}
{"_id": "d6254", "text": "def _updateItemComboBoxIndex(self, item, column, num):\n        \"\"\"Callback for comboboxes: notifies us that a combobox for the given item and column has changed\"\"\"\n        item._combobox_current_index[column] = num\n        item._combobox_current_value[column] = item._combobox_option_list[column][num][0]", "title": ""}
{"_id": "d6255", "text": "def xpathEvalExpression(self, str):\n        \"\"\"Evaluate the XPath expression in the given context. \"\"\"\n        ret = libxml2mod.xmlXPathEvalExpression(str, self._o)\n        if ret is None:raise xpathError('xmlXPathEvalExpression() failed')\n        return xpathObjectRet(ret)", "title": ""}
{"_id": "d6256", "text": "def unit_key_from_name(name):\n  \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n  result = name\n\n  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n    result = result.replace(old, new)\n\n  # Collapse redundant underscores and convert to uppercase.\n  result = re.sub(r'_+', '_', result.upper())\n\n  return result", "title": ""}
{"_id": "d6257", "text": "def loads(s, model=None, parser=None):\n    \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n    with StringIO(s) as f:\n        return load(f, model=model, parser=parser)", "title": ""}
{"_id": "d6258", "text": "def to_percentage(number, rounding=2):\n    \"\"\"Creates a percentage string representation from the given `number`. The\n    number is multiplied by 100 before adding a '%' character.\n\n    Raises `ValueError` if `number` cannot be converted to a number.\n    \"\"\"\n    number = float(number) * 100\n    number_as_int = int(number)\n    rounded = round(number, rounding)\n\n    return '{}%'.format(number_as_int if number_as_int == rounded else rounded)", "title": ""}
{"_id": "d6259", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d6260", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d6261", "text": "def is_stats_query(query):\n    \"\"\"\n    check if the query is a normal search or select query\n    :param query:\n    :return:\n    \"\"\"\n    if not query:\n        return False\n\n    # remove all \" enclosed strings\n    nq = re.sub(r'\"[^\"]*\"', '', query)\n\n    # check if there's | .... select\n    if re.findall(r'\\|.*\\bselect\\b', nq, re.I|re.DOTALL):\n        return True\n\n    return False", "title": ""}
{"_id": "d6262", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d6263", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d6264", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d6265", "text": "def to_bytes(s, encoding=\"utf-8\"):\n    \"\"\"Convert a string to bytes.\"\"\"\n    if isinstance(s, six.binary_type):\n        return s\n    if six.PY3:\n        return bytes(s, encoding)\n    return s.encode(encoding)", "title": ""}
{"_id": "d6266", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d6267", "text": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "title": ""}
{"_id": "d6268", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d6269", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d6270", "text": "def empty_tree(input_list):\n    \"\"\"Recursively iterate through values in nested lists.\"\"\"\n    for item in input_list:\n        if not isinstance(item, list) or not empty_tree(item):\n            return False\n    return True", "title": ""}
{"_id": "d6271", "text": "def is_element_present(driver, selector, by=By.CSS_SELECTOR):\n    \"\"\"\n    Returns whether the specified element selector is present 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 present)\n    \"\"\"\n    try:\n        driver.find_element(by=by, value=selector)\n        return True\n    except Exception:\n        return False", "title": ""}
{"_id": "d6272", "text": "def camelcase_underscore(name):\n    \"\"\" Convert camelcase names to underscore \"\"\"\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()", "title": ""}
{"_id": "d6273", "text": "def _uptime_syllable():\n    \"\"\"Returns uptime in seconds or None, on Syllable.\"\"\"\n    global __boottime\n    try:\n        __boottime = os.stat('/dev/pty/mst/pty0').st_mtime\n        return time.time() - __boottime\n    except (NameError, OSError):\n        return None", "title": ""}
{"_id": "d6274", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d6275", "text": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "title": ""}
{"_id": "d6276", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d6277", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d6278", "text": "def ss_tot(self):\n        \"\"\"Total sum of squares.\"\"\"\n        return np.sum(np.square(self.y - self.ybar), axis=0)", "title": ""}
{"_id": "d6279", "text": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "title": ""}
{"_id": "d6280", "text": "def list2string (inlist,delimit=' '):\n    \"\"\"\nConverts a 1D list to a single long string for file output, using\nthe string.join function.\n\nUsage:   list2string (inlist,delimit=' ')\nReturns: the string created from inlist\n\"\"\"\n    stringlist = [makestr(_) for _ in inlist]\n    return string.join(stringlist,delimit)", "title": ""}
{"_id": "d6281", "text": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "title": ""}
{"_id": "d6282", "text": "def stdout_display():\n    \"\"\" Print results straight to stdout \"\"\"\n    if sys.version_info[0] == 2:\n        yield SmartBuffer(sys.stdout)\n    else:\n        yield SmartBuffer(sys.stdout.buffer)", "title": ""}
{"_id": "d6283", "text": "def we_are_in_lyon():\n    \"\"\"Check if we are on a Lyon machine\"\"\"\n    import socket\n    try:\n        hostname = socket.gethostname()\n        ip = socket.gethostbyname(hostname)\n    except socket.gaierror:\n        return False\n    return ip.startswith(\"134.158.\")", "title": ""}
{"_id": "d6284", "text": "def get_tile_location(self, x, y):\n        \"\"\"Get the screen coordinate for the top-left corner of a tile.\"\"\"\n        x1, y1 = self.origin\n        x1 += self.BORDER + (self.BORDER + self.cell_width) * x\n        y1 += self.BORDER + (self.BORDER + self.cell_height) * y\n        return x1, y1", "title": ""}
{"_id": "d6285", "text": "def contains_empty(features):\n    \"\"\"Check features data are not empty\n\n    :param features: The features data to check.\n    :type features: list of numpy arrays.\n\n    :return: True if one of the array is empty, False else.\n\n    \"\"\"\n    if not features:\n        return True\n    for feature in features:\n        if feature.shape[0] == 0:\n            return True\n    return False", "title": ""}
{"_id": "d6286", "text": "def tf2():\n  \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n  Returns:\n    The root module of a TF-2.0 API, if available.\n\n  Raises:\n    ImportError: if a TF-2.0 API is not available.\n  \"\"\"\n  # Import the `tf` compat API from this file and check if it's already TF 2.0.\n  if tf.__version__.startswith('2.'):\n    return tf\n  elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n    # As a fallback, try `tensorflow.compat.v2` if it's defined.\n    return tf.compat.v2\n  raise ImportError('cannot import tensorflow 2.0 API')", "title": ""}
{"_id": "d6287", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d6288", "text": "def tfds_dir():\n  \"\"\"Path to tensorflow_datasets directory.\"\"\"\n  return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))", "title": ""}
{"_id": "d6289", "text": "def is_binary(filename):\n    \"\"\" Returns True if the file is binary\n\n    \"\"\"\n    with open(filename, 'rb') as fp:\n        data = fp.read(1024)\n        if not data:\n            return False\n        if b'\\0' in data:\n            return True\n        return False", "title": ""}
{"_id": "d6290", "text": "def do_exit(self, arg):\n        \"\"\"Exit the shell session.\"\"\"\n\n        if self.current:\n            self.current.close()\n        self.resource_manager.close()\n        del self.resource_manager\n        return True", "title": ""}
{"_id": "d6291", "text": "def is_binary(filename):\n    \"\"\" Returns True if the file is binary\n\n    \"\"\"\n    with open(filename, 'rb') as fp:\n        data = fp.read(1024)\n        if not data:\n            return False\n        if b'\\0' in data:\n            return True\n        return False", "title": ""}
{"_id": "d6292", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d6293", "text": "def is_http_running_on(port):\n  \"\"\" Check if an http server runs on a given port.\n\n  Args:\n    The port to check.\n  Returns:\n    True if it is used by an http server. False otherwise.\n  \"\"\"\n  try:\n    conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n    conn.connect()\n    conn.close()\n    return True\n  except Exception:\n    return False", "title": ""}
{"_id": "d6294", "text": "def has_value_name(self, name):\n        \"\"\"Check if this `enum` has a particular name among its values.\n\n        :param name: Enumeration value name\n        :type name: str\n        :rtype: True if there is an enumeration value with the given name\n        \"\"\"\n        for val, _ in self._values:\n            if val == name:\n                return True\n        return False", "title": ""}
{"_id": "d6295", "text": "def is_image_file_valid(file_path_name):\n    \"\"\"\n    Indicate whether the specified image file is valid or not.\n\n\n    @param file_path_name: absolute path and file name of an image.\n\n\n    @return: ``True`` if the image file is valid, ``False`` if the file is\n        truncated or does not correspond to a supported image.\n    \"\"\"\n    # Image.verify is only implemented for PNG images, and it only verifies\n    # the CRC checksum in the image.  The only way to check from within\n    # Pillow is to load the image in a try/except and check the error.  If\n    # as much info as possible is from the image is needed,\n    # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it\n    # will attempt to parse as much as possible.\n    try:\n        with Image.open(file_path_name) as image:\n            image.load()\n    except IOError:\n        return False\n\n    return True", "title": ""}
{"_id": "d6296", "text": "def launched():\n    \"\"\"Test whether the current python environment is the correct lore env.\n\n    :return:  :any:`True` if the environment is launched\n    :rtype: bool\n    \"\"\"\n    if not PREFIX:\n        return False\n\n    return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)", "title": ""}
{"_id": "d6297", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d6298", "text": "def this_quarter():\n        \"\"\" Return start and end date of this quarter. \"\"\"\n        since = TODAY + delta(day=1)\n        while since.month % 3 != 0:\n            since -= delta(months=1)\n        until = since + delta(months=3)\n        return Date(since), Date(until)", "title": ""}
{"_id": "d6299", "text": "def iter_with_last(iterable):\n    \"\"\"\n    :return: generator of tuples (isLastFlag, item)\n    \"\"\"\n    # Ensure it's an iterator and get the first field\n    iterable = iter(iterable)\n    prev = next(iterable)\n    for item in iterable:\n        # Lag by one item so I know I'm not at the end\n        yield False, prev\n        prev = item\n    # Last item\n    yield True, prev", "title": ""}
{"_id": "d6300", "text": "def singleton(class_):\n    \"\"\"Singleton definition.\n\n    Method 1 from\n    https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n    \"\"\"\n    instances = {}\n\n    def get_instance(*args, **kwargs):\n        if class_ not in instances:\n            instances[class_] = class_(*args, **kwargs)\n        return instances[class_]\n    return get_instance", "title": ""}
{"_id": "d6301", "text": "def task_property_present_predicate(service, task, prop):\n    \"\"\" True if the json_element passed is present for the task specified.\n    \"\"\"\n    try:\n        response = get_service_task(service, task)\n    except Exception as e:\n        pass\n\n    return (response is not None) and (prop in response)", "title": ""}
{"_id": "d6302", "text": "def querySQL(self, sql, args=()):\n        \"\"\"For use with SELECT (or SELECT-like PRAGMA) statements.\n        \"\"\"\n        if self.debug:\n            result = timeinto(self.queryTimes, self._queryandfetch, sql, args)\n        else:\n            result = self._queryandfetch(sql, args)\n        return result", "title": ""}
{"_id": "d6303", "text": "def empty_tree(input_list):\n    \"\"\"Recursively iterate through values in nested lists.\"\"\"\n    for item in input_list:\n        if not isinstance(item, list) or not empty_tree(item):\n            return False\n    return True", "title": ""}
{"_id": "d6304", "text": "def get_top_priority(self):\n        \"\"\"Pops the element that has the top (smallest) priority.\n\n        :returns: element with the top (smallest) priority.\n        :raises: IndexError -- Priority queue is empty.\n\n        \"\"\"\n        if self.is_empty():\n            raise IndexError(\"Priority queue is empty.\")\n        _, _, element = heapq.heappop(self.pq)\n        if element in self.element_finder:\n            del self.element_finder[element]\n        return element", "title": ""}
{"_id": "d6305", "text": "def is_list_of_ipachars(obj):\n    \"\"\"\n    Return ``True`` if the given object is a list of IPAChar objects.\n\n    :param object obj: the object to test\n    :rtype: bool\n    \"\"\"\n    if isinstance(obj, list):\n        for e in obj:\n            if not isinstance(e, IPAChar):\n                return False\n        return True\n    return False", "title": ""}
{"_id": "d6306", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d6307", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d6308", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d6309", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d6310", "text": "def listified_tokenizer(source):\n    \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n    io_obj = io.StringIO(source)\n    return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]", "title": ""}
{"_id": "d6311", "text": "def _using_stdout(self):\n        \"\"\"\n        Return whether the handler is using sys.stdout.\n        \"\"\"\n        if WINDOWS and colorama:\n            # Then self.stream is an AnsiToWin32 object.\n            return self.stream.wrapped is sys.stdout\n\n        return self.stream is sys.stdout", "title": ""}
{"_id": "d6312", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d6313", "text": "def isstring(value):\n    \"\"\"Report whether the given value is a byte or unicode string.\"\"\"\n    classes = (str, bytes) if pyutils.PY3 else basestring  # noqa: F821\n    return isinstance(value, classes)", "title": ""}
{"_id": "d6314", "text": "def datetime_to_ms(dt):\n    \"\"\"\n    Converts a datetime to a millisecond accuracy timestamp\n    \"\"\"\n    seconds = calendar.timegm(dt.utctimetuple())\n    return seconds * 1000 + int(dt.microsecond / 1000)", "title": ""}
{"_id": "d6315", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d6316", "text": "def register_view(self, view):\n        \"\"\"Register callbacks for button press events and selection changed\"\"\"\n        super(ListViewController, self).register_view(view)\n        self.tree_view.connect('button_press_event', self.mouse_click)", "title": ""}
{"_id": "d6317", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d6318", "text": "def slugify(string):\n    \"\"\"\n    Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n    \"\"\"\n    string = re.sub('[^\\w .-]', '', string)\n    string = string.replace(\" \", \"-\")\n    return string", "title": ""}
{"_id": "d6319", "text": "def default_number_converter(number_str):\n    \"\"\"\n    Converts the string representation of a json number into its python object equivalent, an\n    int, long, float or whatever type suits.\n    \"\"\"\n    is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()\n    # FIXME: this handles a wider range of numbers than allowed by the json standard,\n    # etc.: float('nan') and float('inf'). But is this a problem?\n    return int(number_str) if is_int else float(number_str)", "title": ""}
{"_id": "d6320", "text": "def _open_text(fname, **kwargs):\n    \"\"\"On Python 3 opens a file in text mode by using fs encoding and\n    a proper en/decoding errors handler.\n    On Python 2 this is just an alias for open(name, 'rt').\n    \"\"\"\n    if PY3:\n        kwargs.setdefault('encoding', ENCODING)\n        kwargs.setdefault('errors', ENCODING_ERRS)\n    return open(fname, \"rt\", **kwargs)", "title": ""}
{"_id": "d6321", "text": "def get_active_window():\n    \"\"\"Get the currently focused window\n    \"\"\"\n    active_win = None\n    default = wnck.screen_get_default()\n    while gtk.events_pending():\n        gtk.main_iteration(False)\n    window_list = default.get_windows()\n    if len(window_list) == 0:\n        print \"No Windows Found\"\n    for win in window_list:\n        if win.is_active():\n            active_win = win.get_name()\n    return active_win", "title": ""}
{"_id": "d6322", "text": "def parse_datetime(dt_str):\n    \"\"\"Parse datetime.\"\"\"\n    date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n    dt_str = dt_str.replace(\"Z\", \" +0000\")\n    return datetime.datetime.strptime(dt_str, date_format)", "title": ""}
{"_id": "d6323", "text": "def is_list_of_list(item):\n    \"\"\"\n    check whether the item is list (tuple)\n    and consist of list (tuple) elements\n    \"\"\"\n    if (\n        type(item) in (list, tuple)\n        and len(item)\n        and isinstance(item[0], (list, tuple))\n    ):\n        return True\n    return False", "title": ""}
{"_id": "d6324", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d6325", "text": "def is_integer(obj):\n    \"\"\"Is this an integer.\n\n    :param object obj:\n    :return:\n    \"\"\"\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))", "title": ""}
{"_id": "d6326", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d6327", "text": "def is_executable(path):\n  \"\"\"Returns whether a path names an existing executable file.\"\"\"\n  return os.path.isfile(path) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d6328", "text": "def csvtolist(inputstr):\n    \"\"\" converts a csv string into a list \"\"\"\n    reader = csv.reader([inputstr], skipinitialspace=True)\n    output = []\n    for r in reader:\n        output += r\n    return output", "title": ""}
{"_id": "d6329", "text": "def is_iterable(value):\n    \"\"\"must be an iterable (list, array, tuple)\"\"\"\n    return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "title": ""}
{"_id": "d6330", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d6331", "text": "def get_free_memory_win():\n    \"\"\"Return current free memory on the machine for windows.\n\n    Warning : this script is really not robust\n    Return in MB unit\n    \"\"\"\n    stat = MEMORYSTATUSEX()\n    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n    return int(stat.ullAvailPhys / 1024 / 1024)", "title": ""}
{"_id": "d6332", "text": "def file_to_str(fname):\n    \"\"\"\n    Read a file into a string\n    PRE: fname is a small file (to avoid hogging memory and its discontents)\n    \"\"\"\n    data = None\n    # rU = read with Universal line terminator\n    with open(fname, 'rU') as fd:\n        data = fd.read()\n    return data", "title": ""}
{"_id": "d6333", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d6334", "text": "def covstr(s):\n  \"\"\" convert string to int or float. \"\"\"\n  try:\n    ret = int(s)\n  except ValueError:\n    ret = float(s)\n  return ret", "title": ""}
{"_id": "d6335", "text": "def is_square_matrix(mat):\n    \"\"\"Test if an array is a square matrix.\"\"\"\n    mat = np.array(mat)\n    if mat.ndim != 2:\n        return False\n    shape = mat.shape\n    return shape[0] == shape[1]", "title": ""}
{"_id": "d6336", "text": "def to_str(obj):\n    \"\"\"Attempts to convert given object to a string object\n    \"\"\"\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)", "title": ""}
{"_id": "d6337", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d6338", "text": "def bytes_to_str(s, encoding='utf-8'):\n    \"\"\"Returns a str if a bytes object is given.\"\"\"\n    if six.PY3 and isinstance(s, bytes):\n        return s.decode(encoding)\n    return s", "title": ""}
{"_id": "d6339", "text": "def _is_valid_url(self, url):\n        \"\"\"Callback for is_valid_url.\"\"\"\n        try:\n            r = requests.head(url, proxies=self.proxy_servers)\n            value = r.status_code in [200]\n        except Exception as error:\n            logger.error(str(error))\n            value = False\n\n        return value", "title": ""}
{"_id": "d6340", "text": "def counter(items):\n    \"\"\"\n    Simplest required implementation of collections.Counter. Required as 2.6\n    does not have Counter in collections.\n    \"\"\"\n    results = {}\n    for item in items:\n        results[item] = results.get(item, 0) + 1\n    return results", "title": ""}
{"_id": "d6341", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d6342", "text": "def _id(self):\n        \"\"\"What this object is equal to.\"\"\"\n        return (self.__class__, self.number_of_needles, self.needle_positions,\n                self.left_end_needle)", "title": ""}
{"_id": "d6343", "text": "def isdir(s):\n    \"\"\"Return true if the pathname refers to an existing directory.\"\"\"\n    try:\n        st = os.stat(s)\n    except os.error:\n        return False\n    return stat.S_ISDIR(st.st_mode)", "title": ""}
{"_id": "d6344", "text": "def extract_all(zipfile, dest_folder):\n    \"\"\"\n    reads the zip file, determines compression\n    and unzips recursively until source files \n    are extracted \n    \"\"\"\n    z = ZipFile(zipfile)\n    print(z)\n    z.extract(dest_folder)", "title": ""}
{"_id": "d6345", "text": "def hasattrs(object, *names):\n    \"\"\"\n    Takes in an object and a variable length amount of named attributes,\n    and checks to see if the object has each property. If any of the\n    attributes are missing, this returns false.\n\n    :param object: an object that may or may not contain the listed attributes\n    :param names: a variable amount of attribute names to check for\n    :return: True if the object contains each named attribute, false otherwise\n    \"\"\"\n    for name in names:\n        if not hasattr(object, name):\n            return False\n    return True", "title": ""}
{"_id": "d6346", "text": "def _push_render(self):\n        \"\"\"Render the plot with bokeh.io and push to notebook.\n        \"\"\"\n        bokeh.io.push_notebook(handle=self.handle)\n        self.last_update = time.time()", "title": ""}
{"_id": "d6347", "text": "def make_writeable(filename):\n    \"\"\"\n    Make sure that the file is writeable.\n    Useful if our source is read-only.\n    \"\"\"\n    if not os.access(filename, os.W_OK):\n        st = os.stat(filename)\n        new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR\n        os.chmod(filename, new_permissions)", "title": ""}
{"_id": "d6348", "text": "def add_parent(self, parent):\n        \"\"\"\n        Adds self as child of parent, then adds parent.\n        \"\"\"\n        parent.add_child(self)\n        self.parent = parent\n        return parent", "title": ""}
{"_id": "d6349", "text": "def find_object(self, object_type):\n        \"\"\"Finds the closest object of a given type.\"\"\"\n        node = self\n        while node is not None:\n            if isinstance(node.obj, object_type):\n                return node.obj\n            node = node.parent", "title": ""}
{"_id": "d6350", "text": "def update_one(self, query, doc):\n        \"\"\"\n        Updates one element of the collection\n\n        :param query: dictionary representing the mongo query\n        :param doc: dictionary representing the item to be updated\n        :return: UpdateResult\n        \"\"\"\n        if self.table is None:\n            self.build_table()\n\n        if u\"$set\" in doc:\n            doc = doc[u\"$set\"]\n\n        allcond = self.parse_query(query)\n\n        try:\n            result = self.table.update(doc, allcond)\n        except:\n            # TODO: check table.update result\n            # check what pymongo does in that case\n            result = None\n\n        return UpdateResult(raw_result=result)", "title": ""}
{"_id": "d6351", "text": "def file_md5sum(filename):\n    \"\"\"\n    :param filename: The filename of the file to process\n    :returns: The MD5 hash of the file\n    \"\"\"\n    hash_md5 = hashlib.md5()\n    with open(filename, 'rb') as f:\n        for chunk in iter(lambda: f.read(1024 * 4), b''):\n            hash_md5.update(chunk)\n    return hash_md5.hexdigest()", "title": ""}
{"_id": "d6352", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d6353", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d6354", "text": "def closeEvent(self, e):\n        \"\"\"Qt slot when the window is closed.\"\"\"\n        self.emit('close_widget')\n        super(DockWidget, self).closeEvent(e)", "title": ""}
{"_id": "d6355", "text": "def remove_examples_all():\n    \"\"\"remove arduino/examples/all directory.\n\n    :rtype: None\n\n    \"\"\"\n    d = examples_all_dir()\n    if d.exists():\n        log.debug('remove %s', d)\n        d.rmtree()\n    else:\n        log.debug('nothing to remove: %s', d)", "title": ""}
{"_id": "d6356", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d6357", "text": "def _clear_dir(dirName):\n    \"\"\" Remove a directory and it contents. Ignore any failures.\n    \"\"\"\n    # If we got here, clear dir  \n    for fname in os.listdir(dirName):\n        try:\n            os.remove( os.path.join(dirName, fname) )\n        except Exception:\n            pass\n    try:\n        os.rmdir(dirName)\n    except Exception:\n        pass", "title": ""}
{"_id": "d6358", "text": "def _sourced_dict(self, source=None, **kwargs):\n        \"\"\"Like ``dict(**kwargs)``, but where the ``source`` key is special.\n        \"\"\"\n        if source:\n            kwargs['source'] = source\n        elif self.source:\n            kwargs['source'] = self.source\n        return kwargs", "title": ""}
{"_id": "d6359", "text": "def detach_all(self):\n        \"\"\"\n        Detach from all tracked classes and objects.\n        Restore the original constructors and cleanse the tracking lists.\n        \"\"\"\n        self.detach_all_classes()\n        self.objects.clear()\n        self.index.clear()\n        self._keepalive[:] = []", "title": ""}
{"_id": "d6360", "text": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "title": ""}
{"_id": "d6361", "text": "def bit_clone( bits ):\n    \"\"\"\n    Clone a bitset\n    \"\"\"\n    new = BitSet( bits.size )\n    new.ior( bits )\n    return new", "title": ""}
{"_id": "d6362", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d6363", "text": "def _clone(self, *args, **kwargs):\n        \"\"\"\n        Ensure attributes are copied to subsequent queries.\n        \"\"\"\n        for attr in (\"_search_terms\", \"_search_fields\", \"_search_ordered\"):\n            kwargs[attr] = getattr(self, attr)\n        return super(SearchableQuerySet, self)._clone(*args, **kwargs)", "title": ""}
{"_id": "d6364", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d6365", "text": "def kill(self):\n        \"\"\"Kill the browser.\n\n        This is useful when the browser is stuck.\n        \"\"\"\n        if self.process:\n            self.process.kill()\n            self.process.wait()", "title": ""}
{"_id": "d6366", "text": "def invert(dict_):\n    \"\"\"Return an inverted dictionary, where former values are keys\n    and former keys are values.\n\n    .. warning::\n\n        If more than one key maps to any given value in input dictionary,\n        it is undefined which one will be chosen for the result.\n\n    :param dict_: Dictionary to swap keys and values in\n    :return: Inverted dictionary\n    \"\"\"\n    ensure_mapping(dict_)\n    return dict_.__class__(izip(itervalues(dict_), iterkeys(dict_)))", "title": ""}
{"_id": "d6367", "text": "def close_log(log, verbose=True):\n    \"\"\"Close log\n\n    This method closes and active logging.Logger instance.\n\n    Parameters\n    ----------\n    log : logging.Logger\n        Logging instance\n\n    \"\"\"\n\n    if verbose:\n        print('Closing log file:', log.name)\n\n    # Send closing message.\n    log.info('The log file has been closed.')\n\n    # Remove all handlers from log.\n    [log.removeHandler(handler) for handler in log.handlers]", "title": ""}
{"_id": "d6368", "text": "def _write_color_colorama (fp, text, color):\n    \"\"\"Colorize text with given color.\"\"\"\n    foreground, background, style = get_win_color(color)\n    colorama.set_console(foreground=foreground, background=background,\n      style=style)\n    fp.write(text)\n    colorama.reset_console()", "title": ""}
{"_id": "d6369", "text": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "title": ""}
{"_id": "d6370", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d6371", "text": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "title": ""}
{"_id": "d6372", "text": "def _is_valid_url(self, url):\n        \"\"\"Callback for is_valid_url.\"\"\"\n        try:\n            r = requests.head(url, proxies=self.proxy_servers)\n            value = r.status_code in [200]\n        except Exception as error:\n            logger.error(str(error))\n            value = False\n\n        return value", "title": ""}
{"_id": "d6373", "text": "def execute_until_false(method, interval_s):  # pylint: disable=invalid-name\n  \"\"\"Executes a method forever until the method returns a false value.\n\n  Args:\n    method: The callable to execute.\n    interval_s: The number of seconds to start the execution after each method\n        finishes.\n  Returns:\n    An Interval object.\n  \"\"\"\n  interval = Interval(method, stop_if_false=True)\n  interval.start(interval_s)\n  return interval", "title": ""}
{"_id": "d6374", "text": "def version_jar(self):\n\t\t\"\"\"\n\t\tSpecial case of version() when the executable is a JAR file.\n\t\t\"\"\"\n\t\tcmd = config.get_command('java')\n\t\tcmd.append('-jar')\n\t\tcmd += self.cmd\n\t\tself.version(cmd=cmd, path=self.cmd[0])", "title": ""}
{"_id": "d6375", "text": "def _int64_feature(value):\n  \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))", "title": ""}
{"_id": "d6376", "text": "def _get_url(url):\n    \"\"\"Retrieve requested URL\"\"\"\n    try:\n        data = HTTP_SESSION.get(url, stream=True)\n        data.raise_for_status()\n    except requests.exceptions.RequestException as exc:\n        raise FetcherException(exc)\n\n    return data", "title": ""}
{"_id": "d6377", "text": "def _get_type(self, value):\n        \"\"\"Get the data type for *value*.\"\"\"\n        if value is None:\n            return type(None)\n        elif type(value) in int_types:\n            return int\n        elif type(value) in float_types:\n            return float\n        elif isinstance(value, binary_type):\n            return binary_type\n        else:\n            return text_type", "title": ""}
{"_id": "d6378", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d6379", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d6380", "text": "def read_next_block(infile, block_size=io.DEFAULT_BUFFER_SIZE):\n    \"\"\"Iterates over the file in blocks.\"\"\"\n    chunk = infile.read(block_size)\n\n    while chunk:\n        yield chunk\n\n        chunk = infile.read(block_size)", "title": ""}
{"_id": "d6381", "text": "def sprint(text, *colors):\n    \"\"\"Format text with color or other effects into ANSI escaped string.\"\"\"\n    return \"\\33[{}m{content}\\33[{}m\".format(\";\".join([str(color) for color in colors]), RESET, content=text) if IS_ANSI_TERMINAL and colors else text", "title": ""}
{"_id": "d6382", "text": "def is_valid_file(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.exists(arg):\n        parser.error(\"The file %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d6383", "text": "def row_to_dict(row):\n    \"\"\"Convert a table row to a dictionary.\"\"\"\n    o = {}\n    for colname in row.colnames:\n\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\n    return o", "title": ""}
{"_id": "d6384", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d6385", "text": "def join_images(img_files, out_file):\n    \"\"\"Join the list of images into the out file\"\"\"\n    images = [PIL.Image.open(f) for f in img_files]\n    joined = PIL.Image.new(\n        'RGB',\n        (sum(i.size[0] for i in images), max(i.size[1] for i in images))\n    )\n    left = 0\n    for img in images:\n        joined.paste(im=img, box=(left, 0))\n        left = left + img.size[0]\n    joined.save(out_file)", "title": ""}
{"_id": "d6386", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d6387", "text": "def merge_dict(data, *args):\n    \"\"\"Merge any number of dictionaries\n    \"\"\"\n    results = {}\n    for current in (data,) + args:\n        results.update(current)\n    return results", "title": ""}
{"_id": "d6388", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d6389", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d6390", "text": "def explained_variance(returns, values):\n    \"\"\" Calculate how much variance in returns do the values explain \"\"\"\n    exp_var = 1 - torch.var(returns - values) / torch.var(returns)\n    return exp_var.item()", "title": ""}
{"_id": "d6391", "text": "def _updateItemComboBoxIndex(self, item, column, num):\n        \"\"\"Callback for comboboxes: notifies us that a combobox for the given item and column has changed\"\"\"\n        item._combobox_current_index[column] = num\n        item._combobox_current_value[column] = item._combobox_option_list[column][num][0]", "title": ""}
{"_id": "d6392", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d6393", "text": "def count_string_diff(a,b):\n    \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n    shortest = min(len(a), len(b))\n    return sum(a[i] != b[i] for i in range(shortest))", "title": ""}
{"_id": "d6394", "text": "def cover(session):\n    \"\"\"Run the final coverage report.\n    This outputs the coverage report aggregating coverage from the unit\n    test runs (not system test runs), and then erases coverage data.\n    \"\"\"\n    session.interpreter = 'python3.6'\n    session.install('coverage', 'pytest-cov')\n    session.run('coverage', 'report', '--show-missing', '--fail-under=100')\n    session.run('coverage', 'erase')", "title": ""}
{"_id": "d6395", "text": "def count_string_diff(a,b):\n    \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n    shortest = min(len(a), len(b))\n    return sum(a[i] != b[i] for i in range(shortest))", "title": ""}
{"_id": "d6396", "text": "def nrows_expected(self):\n        \"\"\" based on our axes, compute the expected nrows \"\"\"\n        return np.prod([i.cvalues.shape[0] for i in self.index_axes])", "title": ""}
{"_id": "d6397", "text": "def clean_whitespace(string, compact=False):\n    \"\"\"Return string with compressed whitespace.\"\"\"\n    for a, b in (('\\r\\n', '\\n'), ('\\r', '\\n'), ('\\n\\n', '\\n'),\n                 ('\\t', ' '), ('  ', ' ')):\n        string = string.replace(a, b)\n    if compact:\n        for a, b in (('\\n', ' '), ('[ ', '['),\n                     ('  ', ' '), ('  ', ' '), ('  ', ' ')):\n            string = string.replace(a, b)\n    return string.strip()", "title": ""}
{"_id": "d6398", "text": "def vector_distance(a, b):\n    \"\"\"The Euclidean distance between two vectors.\"\"\"\n    a = np.array(a)\n    b = np.array(b)\n    return np.linalg.norm(a - b)", "title": ""}
{"_id": "d6399", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d6400", "text": "def boolean(value):\n    \"\"\"\n    Configuration-friendly boolean type converter.\n\n    Supports both boolean-valued and string-valued inputs (e.g. from env vars).\n\n    \"\"\"\n    if isinstance(value, bool):\n        return value\n\n    if value == \"\":\n        return False\n\n    return strtobool(value)", "title": ""}
{"_id": "d6401", "text": "def rAsciiLine(ifile):\n    \"\"\"Returns the next non-blank line in an ASCII file.\"\"\"\n\n    _line = ifile.readline().strip()\n    while len(_line) == 0:\n        _line = ifile.readline().strip()\n    return _line", "title": ""}
{"_id": "d6402", "text": "def compose_all(tups):\n  \"\"\"Compose all given tuples together.\"\"\"\n  from . import ast  # I weep for humanity\n  return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))", "title": ""}
{"_id": "d6403", "text": "def max(self):\n        \"\"\"\n        Returns the maximum value of the domain.\n\n        :rtype: `float` or `np.inf`\n        \"\"\"\n        return int(self._max) if not np.isinf(self._max) else self._max", "title": ""}
{"_id": "d6404", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d6405", "text": "def np_counts(self):\n    \"\"\"Dictionary of noun phrase frequencies in this text.\n    \"\"\"\n    counts = defaultdict(int)\n    for phrase in self.noun_phrases:\n        counts[phrase] += 1\n    return counts", "title": ""}
{"_id": "d6406", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d6407", "text": "def write_config(self, outfile):\n        \"\"\"Write the configuration dictionary to an output file.\"\"\"\n        utils.write_yaml(self.config, outfile, default_flow_style=False)", "title": ""}
{"_id": "d6408", "text": "def student_t(degrees_of_freedom, confidence=0.95):\n    \"\"\"Return Student-t statistic for given DOF and confidence interval.\"\"\"\n    return scipy.stats.t.interval(alpha=confidence,\n                                  df=degrees_of_freedom)[-1]", "title": ""}
{"_id": "d6409", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d6410", "text": "def items(self, section_name):\n        \"\"\":return: list((option, value), ...) pairs of all items in the given section\"\"\"\n        return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']", "title": ""}
{"_id": "d6411", "text": "def _write_json(file, contents):\n    \"\"\"Write a dict to a JSON file.\"\"\"\n    with open(file, 'w') as f:\n        return json.dump(contents, f, indent=2, sort_keys=True)", "title": ""}
{"_id": "d6412", "text": "def connect(*args, **kwargs):\n    \"\"\"Creates or returns a singleton :class:`.Connection` object\"\"\"\n    global __CONNECTION\n    if __CONNECTION is None:\n        __CONNECTION = Connection(*args, **kwargs)\n\n    return __CONNECTION", "title": ""}
{"_id": "d6413", "text": "def write_tsv_line_from_list(linelist, outfp):\n    \"\"\"Utility method to convert list to tsv line with carriage return\"\"\"\n    line = '\\t'.join(linelist)\n    outfp.write(line)\n    outfp.write('\\n')", "title": ""}
{"_id": "d6414", "text": "def install_postgres(user=None, dbname=None, password=None):\n    \"\"\"Install Postgres on remote\"\"\"\n    execute(pydiploy.django.install_postgres_server,\n            user=user, dbname=dbname, password=password)", "title": ""}
{"_id": "d6415", "text": "def get_hline():\n    \"\"\" gets a horiztonal line \"\"\"\n    return Window(\n        width=LayoutDimension.exact(1),\n        height=LayoutDimension.exact(1),\n        content=FillControl('-', token=Token.Line))", "title": ""}
{"_id": "d6416", "text": "def make_segments(x, y):\n    \"\"\"\n    Create list of line segments from x and y coordinates, in the correct format\n    for LineCollection: an array of the form numlines x (points per line) x 2 (x\n    and y) array\n    \"\"\"\n\n    points = np.array([x, y]).T.reshape(-1, 1, 2)\n    segments = np.concatenate([points[:-1], points[1:]], axis=1)\n    return segments", "title": ""}
{"_id": "d6417", "text": "def set_icon(self, bmp):\n        \"\"\"Sets main window icon to given wx.Bitmap\"\"\"\n\n        _icon = wx.EmptyIcon()\n        _icon.CopyFromBitmap(bmp)\n        self.SetIcon(_icon)", "title": ""}
{"_id": "d6418", "text": "def conv_dict(self):\n        \"\"\"dictionary of conversion\"\"\"\n        return dict(integer=self.integer, real=self.real, no_type=self.no_type)", "title": ""}
{"_id": "d6419", "text": "def _update_fontcolor(self, fontcolor):\n        \"\"\"Updates text font color button\n\n        Parameters\n        ----------\n\n        fontcolor: Integer\n        \\tText color in integer RGB format\n\n        \"\"\"\n\n        textcolor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n        textcolor.SetRGB(fontcolor)\n\n        self.textcolor_choice.SetColour(textcolor)", "title": ""}
{"_id": "d6420", "text": "def get_line_flux(line_wave, wave, flux, **kwargs):\n    \"\"\"Interpolated flux at a given wavelength (calls np.interp).\"\"\"\n    return np.interp(line_wave, wave, flux, **kwargs)", "title": ""}
{"_id": "d6421", "text": "def _do_layout(self):\n        \"\"\"Sizer hell, returns a sizer that contains all widgets\"\"\"\n\n        sizer_csvoptions = wx.FlexGridSizer(5, 4, 5, 5)\n\n        # Adding parameter widgets to sizer_csvoptions\n        leftpos = wx.LEFT | wx.ADJUST_MINSIZE\n        rightpos = wx.RIGHT | wx.EXPAND\n\n        current_label_margin = 0  # smaller for left column\n        other_label_margin = 15\n\n        for label, widget in zip(self.param_labels, self.param_widgets):\n            sizer_csvoptions.Add(label, 0, leftpos, current_label_margin)\n            sizer_csvoptions.Add(widget, 0, rightpos, current_label_margin)\n\n            current_label_margin, other_label_margin = \\\n                other_label_margin, current_label_margin\n\n        sizer_csvoptions.AddGrowableCol(1)\n        sizer_csvoptions.AddGrowableCol(3)\n\n        self.sizer_csvoptions = sizer_csvoptions", "title": ""}
{"_id": "d6422", "text": "def camelcase_underscore(name):\n    \"\"\" Convert camelcase names to underscore \"\"\"\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()", "title": ""}
{"_id": "d6423", "text": "def coords_on_grid(self, x, y):\n        \"\"\" Snap coordinates on the grid with integer coordinates \"\"\"\n\n        if isinstance(x, float):\n            x = int(self._round(x))\n        if isinstance(y, float):\n            y = int(self._round(y))\n        if not self._y_coord_down:\n            y = self._extents - y\n        return x, y", "title": ""}
{"_id": "d6424", "text": "def int_to_date(date):\n    \"\"\"\n    Convert an int of form yyyymmdd to a python date object.\n    \"\"\"\n\n    year = date // 10**4\n    month = date % 10**4 // 10**2\n    day = date % 10**2\n\n    return datetime.date(year, month, day)", "title": ""}
{"_id": "d6425", "text": "def set_xlimits(self, row, column, min=None, max=None):\n        \"\"\"Set x-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_xlimits(min, max)", "title": ""}
{"_id": "d6426", "text": "def string_to_float_list(string_var):\n        \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n        try:\n            return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n        except:\n            return [float(s) for s in string_var.strip('[').strip(']').split(',')]", "title": ""}
{"_id": "d6427", "text": "def multiply(traj):\n    \"\"\"Sophisticated simulation of multiplication\"\"\"\n    z=traj.x*traj.y\n    traj.f_add_result('z',z=z, comment='I am the product of two reals!')", "title": ""}
{"_id": "d6428", "text": "def convert_camel_case_to_snake_case(name):\n    \"\"\"Convert CamelCase to snake_case.\"\"\"\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()", "title": ""}
{"_id": "d6429", "text": "def schemaParse(self):\n        \"\"\"parse a schema definition resource and build an internal\n           XML Shema struture which can be used to validate instances. \"\"\"\n        ret = libxml2mod.xmlSchemaParse(self._o)\n        if ret is None:raise parserError('xmlSchemaParse() failed')\n        __tmp = Schema(_obj=ret)\n        return __tmp", "title": ""}
{"_id": "d6430", "text": "def convolve_fft(array, kernel):\n    \"\"\"\n    Convolve an array with a kernel using FFT.\n    Implemntation based on the convolve_fft function from astropy.\n\n    https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py\n    \"\"\"\n\n    array = np.asarray(array, dtype=np.complex)\n    kernel = np.asarray(kernel, dtype=np.complex)\n\n    if array.ndim != kernel.ndim:\n        raise ValueError(\"Image and kernel must have same number of \"\n                         \"dimensions\")\n\n    array_shape = array.shape\n    kernel_shape = kernel.shape\n    new_shape = np.array(array_shape) + np.array(kernel_shape)\n\n    array_slices = []\n    kernel_slices = []\n    for (new_dimsize, array_dimsize, kernel_dimsize) in zip(\n            new_shape, array_shape, kernel_shape):\n        center = new_dimsize - (new_dimsize + 1) // 2\n        array_slices += [slice(center - array_dimsize // 2,\n                         center + (array_dimsize + 1) // 2)]\n        kernel_slices += [slice(center - kernel_dimsize // 2,\n                          center + (kernel_dimsize + 1) // 2)]\n\n    array_slices = tuple(array_slices)\n    kernel_slices = tuple(kernel_slices)\n\n    if not np.all(new_shape == array_shape):\n        big_array = np.zeros(new_shape, dtype=np.complex)\n        big_array[array_slices] = array\n    else:\n        big_array = array\n\n    if not np.all(new_shape == kernel_shape):\n        big_kernel = np.zeros(new_shape, dtype=np.complex)\n        big_kernel[kernel_slices] = kernel\n    else:\n        big_kernel = kernel\n\n    array_fft = np.fft.fftn(big_array)\n    kernel_fft = np.fft.fftn(np.fft.ifftshift(big_kernel))\n\n    rifft = np.fft.ifftn(array_fft * kernel_fft)\n\n    return rifft[array_slices].real", "title": ""}
{"_id": "d6431", "text": "def Parse(text):\n  \"\"\"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.\n  \"\"\"\n  precondition.AssertType(text, Text)\n\n  if compatibility.PY2:\n    text = text.encode(\"utf-8\")\n\n  return yaml.safe_load(text)", "title": ""}
{"_id": "d6432", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d6433", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d6434", "text": "def pad_cells(table):\n    \"\"\"Pad each cell to the size of the largest cell in its column.\"\"\"\n    col_sizes = [max(map(len, col)) for col in zip(*table)]\n    for row in table:\n        for cell_num, cell in enumerate(row):\n            row[cell_num] = pad_to(cell, col_sizes[cell_num])\n    return table", "title": ""}
{"_id": "d6435", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d6436", "text": "def ub_to_str(string):\n    \"\"\"\n    converts py2 unicode / py3 bytestring into str\n    Args:\n        string (unicode, byte_string): string to be converted\n        \n    Returns:\n        (str)\n    \"\"\"\n    if not isinstance(string, str):\n        if six.PY2:\n            return str(string)\n        else:\n            return string.decode()\n    return string", "title": ""}
{"_id": "d6437", "text": "def ungzip_data(input_data):\n    \"\"\"Return a string of data after gzip decoding\n\n    :param the input gziped data\n    :return  the gzip decoded data\"\"\"\n    buf = StringIO(input_data)\n    f = gzip.GzipFile(fileobj=buf)\n    return f", "title": ""}
{"_id": "d6438", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d6439", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d6440", "text": "def notin(arg, values):\n    \"\"\"\n    Like isin, but checks whether this expression's value(s) are not\n    contained in the passed values. See isin docs for full usage.\n    \"\"\"\n    op = ops.NotContains(arg, values)\n    return op.to_expr()", "title": ""}
{"_id": "d6441", "text": "def np_hash(a):\n    \"\"\"Return a hash of a NumPy array.\"\"\"\n    if a is None:\n        return hash(None)\n    # Ensure that hashes are equal whatever the ordering in memory (C or\n    # Fortran)\n    a = np.ascontiguousarray(a)\n    # Compute the digest and return a decimal int\n    return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)", "title": ""}
{"_id": "d6442", "text": "def string_presenter(self, dumper, data):\n    \"\"\"Presenter to force yaml.dump to use multi-line string style.\"\"\"\n    if '\\n' in data:\n      return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')\n    else:\n      return dumper.represent_scalar('tag:yaml.org,2002:str', data)", "title": ""}
{"_id": "d6443", "text": "def join_cols(cols):\n    \"\"\"Join list of columns into a string for a SQL query\"\"\"\n    return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols", "title": ""}
{"_id": "d6444", "text": "def bytes_base64(x):\n    \"\"\"Turn bytes into base64\"\"\"\n    if six.PY2:\n        return base64.encodestring(x).replace('\\n', '')\n    return base64.encodebytes(bytes_encode(x)).replace(b'\\n', b'')", "title": ""}
{"_id": "d6445", "text": "def date_to_datetime(x):\n    \"\"\"Convert a date into a datetime\"\"\"\n    if not isinstance(x, datetime) and isinstance(x, date):\n        return datetime.combine(x, time())\n    return x", "title": ""}
{"_id": "d6446", "text": "def uint32_to_uint8(cls, img):\n        \"\"\"\n        Cast uint32 RGB image to 4 uint8 channels.\n        \"\"\"\n        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))", "title": ""}
{"_id": "d6447", "text": "def tokenize(string):\n    \"\"\"Match and yield all the tokens of the input string.\"\"\"\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())", "title": ""}
{"_id": "d6448", "text": "def normalize_enum_constant(s):\n    \"\"\"Return enum constant `s` converted to a canonical snake-case.\"\"\"\n    if s.islower(): return s\n    if s.isupper(): return s.lower()\n    return \"\".join(ch if ch.islower() else \"_\" + ch.lower() for ch in s).strip(\"_\")", "title": ""}
{"_id": "d6449", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d6450", "text": "def fromDict(cls, _dict):\n        \"\"\" Builds instance from dictionary of properties. \"\"\"\n        obj = cls()\n        obj.__dict__.update(_dict)\n        return obj", "title": ""}
{"_id": "d6451", "text": "def array(self):\n        \"\"\"\n        The underlying array of shape (N, L, I)\n        \"\"\"\n        return numpy.array([self[sid].array for sid in sorted(self)])", "title": ""}
{"_id": "d6452", "text": "def instance_contains(container, item):\n    \"\"\"Search into instance attributes, properties and return values of no-args methods.\"\"\"\n    return item in (member for _, member in inspect.getmembers(container))", "title": ""}
{"_id": "d6453", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d6454", "text": "def get_line_flux(line_wave, wave, flux, **kwargs):\n    \"\"\"Interpolated flux at a given wavelength (calls np.interp).\"\"\"\n    return np.interp(line_wave, wave, flux, **kwargs)", "title": ""}
{"_id": "d6455", "text": "def line_line_intersect(x, y):\n    \"\"\"Compute the intersection point of two lines\n\n    Parameters\n    ----------\n    x = x4 array: x1, x2, x3, x4\n    y = x4 array: y1, y2, y3, y4\n    line 1 is defined by p1,p2\n    line 2 is defined by p3,p4\n\n    Returns\n    -------\n    Ix: x-coordinate of intersection\n    Iy: y-coordinate of intersection\n    \"\"\"\n    A = x[0] * y[1] - y[0] * x[1]\n    B = x[2] * y[3] - y[2] * x[4]\n    C = (x[0] - x[1]) * (y[2] - y[3]) - (y[0] - y[1]) * (x[2] - x[3])\n\n    Ix = (A * (x[2] - x[3]) - (x[0] - x[1]) * B) / C\n    Iy = (A * (y[2] - y[3]) - (y[0] - y[1]) * B) / C\n    return Ix, Iy", "title": ""}
{"_id": "d6456", "text": "def deserialize_date(string):\n    \"\"\"\n    Deserializes string to date.\n\n    :param string: str.\n    :type string: str\n    :return: date.\n    :rtype: date\n    \"\"\"\n    try:\n        from dateutil.parser import parse\n        return parse(string).date()\n    except ImportError:\n        return string", "title": ""}
{"_id": "d6457", "text": "def to_comment(value):\n  \"\"\"\n  Builds a comment.\n  \"\"\"\n  if value is None:\n    return\n  if len(value.split('\\n')) == 1:\n    return \"* \" + value\n  else:\n    return '\\n'.join([' * ' + l for l in value.split('\\n')[:-1]])", "title": ""}
{"_id": "d6458", "text": "def from_series(series):\n        \"\"\"\n        Deseralize a PercentRankTransform the given pandas.Series, as returned\n        by `to_series()`.\n\n        Parameters\n        ----------\n        series : pandas.Series\n\n        Returns\n        -------\n        PercentRankTransform\n\n        \"\"\"\n        result = PercentRankTransform()\n        result.cdf = series.values\n        result.bin_edges = series.index.values[1:-1]\n        return result", "title": ""}
{"_id": "d6459", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d6460", "text": "def get_cursor(self):\n        \"\"\"Returns current grid cursor cell (row, col, tab)\"\"\"\n\n        return self.grid.GetGridCursorRow(), self.grid.GetGridCursorCol(), \\\n            self.grid.current_table", "title": ""}
{"_id": "d6461", "text": "def copyFile(input, output, replace=None):\n    \"\"\"Copy a file whole from input to output.\"\"\"\n\n    _found = findFile(output)\n    if not _found or (_found and replace):\n        shutil.copy2(input, output)", "title": ""}
{"_id": "d6462", "text": "def PopTask(self):\n    \"\"\"Retrieves and removes the first task from the heap.\n\n    Returns:\n      Task: the task or None if the heap is empty.\n    \"\"\"\n    try:\n      _, task = heapq.heappop(self._heap)\n\n    except IndexError:\n      return None\n    self._task_identifiers.remove(task.identifier)\n    return task", "title": ""}
{"_id": "d6463", "text": "def c_array(ctype, values):\n    \"\"\"Convert a python string to c array.\"\"\"\n    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):\n        return (ctype * len(values)).from_buffer_copy(values)\n    return (ctype * len(values))(*values)", "title": ""}
{"_id": "d6464", "text": "def find_root(self):\n        \"\"\" Traverse parent refs to top. \"\"\"\n        cmd = self\n        while cmd.parent:\n            cmd = cmd.parent\n        return cmd", "title": ""}
{"_id": "d6465", "text": "def main(argv, version=DEFAULT_VERSION):\n    \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n    tarball = download_setuptools()\n    _install(tarball, _build_install_args(argv))", "title": ""}
{"_id": "d6466", "text": "def parse_form(self, req, name, field):\n        \"\"\"Pull a form value from the request.\"\"\"\n        return get_value(req.body_arguments, name, field)", "title": ""}
{"_id": "d6467", "text": "def wordfreq(text, is_filename=False):\n    \"\"\"Return a dictionary of words and word counts in a string.\"\"\"\n    if is_filename:\n        with open(text) as f:\n            text = f.read()\n    freqs = {}\n    for word in text.split():\n        lword = word.lower()\n        freqs[lword] = freqs.get(lword, 0) + 1\n    return freqs", "title": ""}
{"_id": "d6468", "text": "def _increment_numeric_suffix(s):\n        \"\"\"Increment (or add) numeric suffix to identifier.\"\"\"\n        if re.match(r\".*\\d+$\", s):\n            return re.sub(r\"\\d+$\", lambda n: str(int(n.group(0)) + 1), s)\n        return s + \"_2\"", "title": ""}
{"_id": "d6469", "text": "def count(lines):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  words = [w for l in lines for w in l.strip().split()]\n  return Counter(words)", "title": ""}
{"_id": "d6470", "text": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "title": ""}
{"_id": "d6471", "text": "def convert_timestamp(timestamp):\n    \"\"\"\n    Converts bokehJS timestamp to datetime64.\n    \"\"\"\n    datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)\n    return np.datetime64(datetime.replace(tzinfo=None))", "title": ""}
{"_id": "d6472", "text": "def update(packages, env=None, user=None):\n    \"\"\"\n    Update conda packages in a conda env\n\n    Attributes\n    ----------\n        packages: list of packages comma delimited\n    \"\"\"\n    packages = ' '.join(packages.split(','))\n    cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user)\n    return _execcmd(cmd, user=user)", "title": ""}
{"_id": "d6473", "text": "def get_ntobj(self):\n        \"\"\"Create namedtuple object with GOEA fields.\"\"\"\n        if self.nts:\n            return cx.namedtuple(\"ntgoea\", \" \".join(vars(next(iter(self.nts))).keys()))", "title": ""}
{"_id": "d6474", "text": "def array_sha256(a):\n    \"\"\"Create a SHA256 hash from a Numpy array.\"\"\"\n    dtype = str(a.dtype).encode()\n    shape = numpy.array(a.shape)\n    sha = hashlib.sha256()\n    sha.update(dtype)\n    sha.update(shape)\n    sha.update(a.tobytes())\n    return sha.hexdigest()", "title": ""}
{"_id": "d6475", "text": "def _Enum(docstring, *names):\n  \"\"\"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.\n  \"\"\"\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)", "title": ""}
{"_id": "d6476", "text": "def create_run_logfile(folder):\n    \"\"\"Create a 'run.log' within folder. This file contains the time of the\n       latest successful run.\n    \"\"\"\n    with open(os.path.join(folder, \"run.log\"), \"w\") as f:\n        datestring = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\n        f.write(\"timestamp: '%s'\" % datestring)", "title": ""}
{"_id": "d6477", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d6478", "text": "def construct_from_string(cls, string):\n        \"\"\"\n        Construction from a string, raise a TypeError if not\n        possible\n        \"\"\"\n        if string == cls.name:\n            return cls()\n        raise TypeError(\"Cannot construct a '{}' from \"\n                        \"'{}'\".format(cls, string))", "title": ""}
{"_id": "d6479", "text": "def weighted_std(values, weights):\n    \"\"\" Calculate standard deviation weighted by errors \"\"\"\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)", "title": ""}
{"_id": "d6480", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d6481", "text": "def add_blank_row(self, label):\n        \"\"\"\n        Add a blank row with only an index value to self.df.\n        This is done inplace.\n        \"\"\"\n        col_labels = self.df.columns\n        blank_item = pd.Series({}, index=col_labels, name=label)\n        # use .loc to add in place (append won't do that)\n        self.df.loc[blank_item.name] = blank_item\n        return self.df", "title": ""}
{"_id": "d6482", "text": "def add_text_to_image(fname, txt, opFilename):\n    \"\"\" convert an image by adding text \"\"\"\n    ft = ImageFont.load(\"T://user//dev//src//python//_AS_LIB//timR24.pil\")\n    #wh = ft.getsize(txt)\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)", "title": ""}
{"_id": "d6483", "text": "def to_dict(self):\n        \"\"\"\n        Serialize representation of the column for local caching.\n        \"\"\"\n        return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type}", "title": ""}
{"_id": "d6484", "text": "def deep_update(d, u):\n  \"\"\"Deeply updates a dictionary. List values are concatenated.\n\n  Args:\n    d (dict): First dictionary which will be updated\n    u (dict): Second dictionary use to extend the first one\n\n  Returns:\n    dict: The merge dictionary\n\n  \"\"\"\n\n  for k, v in u.items():\n    if isinstance(v, Mapping):\n      d[k] = deep_update(d.get(k, {}), v)\n    elif isinstance(v, list):\n      existing_elements = d.get(k, [])\n      d[k] = existing_elements + [ele for ele in v if ele not in existing_elements]\n    else:\n      d[k] = v\n\n  return d", "title": ""}
{"_id": "d6485", "text": "def makedirs(directory):\n    \"\"\" Resursively create a named directory. \"\"\"\n    parent = os.path.dirname(os.path.abspath(directory))\n    if not os.path.exists(parent):\n        makedirs(parent)\n    os.mkdir(directory)", "title": ""}
{"_id": "d6486", "text": "def indent(s, spaces=4):\n    \"\"\"\n    Inserts `spaces` after each string of new lines in `s`\n    and before the start of the string.\n    \"\"\"\n    new = re.sub('(\\n+)', '\\\\1%s' % (' ' * spaces), s)\n    return (' ' * spaces) + new.strip()", "title": ""}
{"_id": "d6487", "text": "def makedirs(directory):\n    \"\"\" Resursively create a named directory. \"\"\"\n    parent = os.path.dirname(os.path.abspath(directory))\n    if not os.path.exists(parent):\n        makedirs(parent)\n    os.mkdir(directory)", "title": ""}
{"_id": "d6488", "text": "def  make_html_code( self, lines ):\n        \"\"\" convert a code sequence to HTML \"\"\"\n        line = code_header + '\\n'\n        for l in lines:\n            line = line + html_quote( l ) + '\\n'\n\n        return line + code_footer", "title": ""}
{"_id": "d6489", "text": "def _Enum(docstring, *names):\n  \"\"\"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.\n  \"\"\"\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)", "title": ""}
{"_id": "d6490", "text": "def CreateVertices(self, points):\n        \"\"\"\n        Returns a dictionary object with keys that are 2tuples\n        represnting a point.\n        \"\"\"\n        gr = digraph()\n\n        for z, x, Q in points:\n            node = (z, x, Q)\n            gr.add_nodes([node])\n\n        return gr", "title": ""}
{"_id": "d6491", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d6492", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d6493", "text": "def unit_key_from_name(name):\n  \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n  result = name\n\n  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n    result = result.replace(old, new)\n\n  # Collapse redundant underscores and convert to uppercase.\n  result = re.sub(r'_+', '_', result.upper())\n\n  return result", "title": ""}
{"_id": "d6494", "text": "def normalize_time(timestamp):\n    \"\"\"Normalize time in arbitrary timezone to UTC naive object.\"\"\"\n    offset = timestamp.utcoffset()\n    if offset is None:\n        return timestamp\n    return timestamp.replace(tzinfo=None) - offset", "title": ""}
{"_id": "d6495", "text": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    l = [v.strip() for v in value.split(',')]\n    if len(l) == 1:\n        l = value.split()\n    return l", "title": ""}
{"_id": "d6496", "text": "def transformer_ae_a3():\n  \"\"\"Set of hyperparameters.\"\"\"\n  hparams = transformer_ae_base()\n  hparams.batch_size = 4096\n  hparams.layer_prepostprocess_dropout = 0.3\n  hparams.optimizer = \"Adafactor\"\n  hparams.learning_rate = 0.25\n  hparams.learning_rate_warmup_steps = 10000\n  return hparams", "title": ""}
{"_id": "d6497", "text": "def vec_angle(a, b):\n    \"\"\"\n    Calculate angle between two vectors\n    \"\"\"\n    cosang = np.dot(a, b)\n    sinang = fast_norm(np.cross(a, b))\n    return np.arctan2(sinang, cosang)", "title": ""}
{"_id": "d6498", "text": "def sp_rand(m,n,a):\n    \"\"\"\n    Generates an mxn sparse 'd' matrix with round(a*m*n) nonzeros.\n    \"\"\"\n    if m == 0 or n == 0: return spmatrix([], [], [], (m,n))\n    nnz = min(max(0, int(round(a*m*n))), m*n)\n    nz = matrix(random.sample(range(m*n), nnz), tc='i')\n    return spmatrix(normal(nnz,1), nz%m, matrix([int(ii) for ii in nz/m]), (m,n))", "title": ""}
{"_id": "d6499", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d6500", "text": "def save_image(pdf_path, img_path, page_num):\n    \"\"\"\n\n    Creates images for a page of the input pdf document and saves it\n    at img_path.\n\n    :param pdf_path: path to pdf to create images for.\n    :param img_path: path where to save the images.\n    :param page_num: page number to create image from in the pdf file.\n    :return:\n    \"\"\"\n    pdf_img = Image(filename=\"{}[{}]\".format(pdf_path, page_num))\n    with pdf_img.convert(\"png\") as converted:\n        # Set white background.\n        converted.background_color = Color(\"white\")\n        converted.alpha_channel = \"remove\"\n        converted.save(filename=img_path)", "title": ""}
{"_id": "d6501", "text": "def create_path(path):\n    \"\"\"Creates a absolute path in the file system.\n\n    :param path: The path to be created\n    \"\"\"\n    import os\n    if not os.path.exists(path):\n        os.makedirs(path)", "title": ""}
{"_id": "d6502", "text": "def interpolate(table, field, fmt, **kwargs):\n    \"\"\"\n    Convenience function to interpolate all values in the given `field` using\n    the `fmt` string.\n\n    The ``where`` keyword argument can be given with a callable or expression\n    which is evaluated on each row and which should return True if the\n    conversion should be applied on that row, else False.\n\n    \"\"\"\n\n    conv = lambda v: fmt % v\n    return convert(table, field, conv, **kwargs)", "title": ""}
{"_id": "d6503", "text": "def csvpretty(csvfile: csvfile=sys.stdin):\n    \"\"\" Pretty print a CSV file. \"\"\"\n    shellish.tabulate(csv.reader(csvfile))", "title": ""}
{"_id": "d6504", "text": "def to_linspace(self):\n        \"\"\"\n        convert from full to linspace\n        \"\"\"\n        if hasattr(self.shape, '__len__'):\n            raise NotImplementedError(\"can only convert flat Full arrays to linspace\")\n        return Linspace(self.fill_value, self.fill_value, self.shape)", "title": ""}
{"_id": "d6505", "text": "def cint8_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):\n        return np.fromiter(cptr, dtype=np.int8, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d6506", "text": "def c_array(ctype, values):\n    \"\"\"Convert a python string to c array.\"\"\"\n    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):\n        return (ctype * len(values)).from_buffer_copy(values)\n    return (ctype * len(values))(*values)", "title": ""}
{"_id": "d6507", "text": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "title": ""}
{"_id": "d6508", "text": "def getBuffer(x):\n    \"\"\"\n    Copy @x into a (modifiable) ctypes byte array\n    \"\"\"\n    b = bytes(x)\n    return (c_ubyte * len(b)).from_buffer_copy(bytes(x))", "title": ""}
{"_id": "d6509", "text": "def rex_assert(self, rex, byte=False):\n        \"\"\"\n        If `rex` expression is not found then raise `DataNotFound` exception.\n        \"\"\"\n\n        self.rex_search(rex, byte=byte)", "title": ""}
{"_id": "d6510", "text": "def _monitor_callback_wrapper(callback):\n    \"\"\"A wrapper for the user-defined handle.\"\"\"\n    def callback_handle(name, array, _):\n        \"\"\" ctypes function \"\"\"\n        callback(name, array)\n    return callback_handle", "title": ""}
{"_id": "d6511", "text": "def _open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None,\n          closefd=True, opener=None, *, loop=None, executor=None):\n    \"\"\"Open an asyncio file.\"\"\"\n    if loop is None:\n        loop = asyncio.get_event_loop()\n    cb = partial(sync_open, file, mode=mode, buffering=buffering,\n                 encoding=encoding, errors=errors, newline=newline,\n                 closefd=closefd, opener=opener)\n    f = yield from loop.run_in_executor(executor, cb)\n\n    return wrap(f, loop=loop, executor=executor)", "title": ""}
{"_id": "d6512", "text": "def getBuffer(x):\n    \"\"\"\n    Copy @x into a (modifiable) ctypes byte array\n    \"\"\"\n    b = bytes(x)\n    return (c_ubyte * len(b)).from_buffer_copy(bytes(x))", "title": ""}
{"_id": "d6513", "text": "def destroy(self):\n\t\t\"\"\"Finish up a session.\n\t\t\"\"\"\n\t\tif self.session_type == 'bash':\n\t\t\t# TODO: does this work/handle already being logged out/logged in deep OK?\n\t\t\tself.logout()\n\t\telif self.session_type == 'vagrant':\n\t\t\t# TODO: does this work/handle already being logged out/logged in deep OK?\n\t\t\tself.logout()", "title": ""}
{"_id": "d6514", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d6515", "text": "def accel_prev(self, *args):\n        \"\"\"Callback to go to the previous tab. Called by the accel key.\n        \"\"\"\n        if self.get_notebook().get_current_page() == 0:\n            self.get_notebook().set_current_page(self.get_notebook().get_n_pages() - 1)\n        else:\n            self.get_notebook().prev_page()\n        return True", "title": ""}
{"_id": "d6516", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d6517", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d6518", "text": "def cint32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):\n        return np.fromiter(cptr, dtype=np.int32, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d6519", "text": "def s3(ctx, bucket_name, data_file, region):\n    \"\"\"Use the S3 SWAG backend.\"\"\"\n    if not ctx.data_file:\n        ctx.data_file = data_file\n\n    if not ctx.bucket_name:\n        ctx.bucket_name = bucket_name\n\n    if not ctx.region:\n        ctx.region = region\n\n    ctx.type = 's3'", "title": ""}
{"_id": "d6520", "text": "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()", "title": ""}
{"_id": "d6521", "text": "def get_files(client, bucket, prefix=''):\n    \"\"\"Lists files/objects on a bucket.\n    \n    TODO: docstring\"\"\"\n    bucket = client.get_bucket(bucket)\n    files = list(bucket.list_blobs(prefix=prefix))    \n    return files", "title": ""}
{"_id": "d6522", "text": "def get_capture_dimensions(capture):\n    \"\"\"Get the dimensions of a capture\"\"\"\n    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\n    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n    return width, height", "title": ""}
{"_id": "d6523", "text": "def exists(self, digest):\n        \"\"\"\n        Check if a blob exists\n\n        :param digest: Hex digest of the blob\n        :return: Boolean indicating existence of the blob\n        \"\"\"\n        return self.conn.client.blob_exists(self.container_name, digest)", "title": ""}
{"_id": "d6524", "text": "def SetValue(self, row, col, value):\n        \"\"\"\n        Set value in the pandas DataFrame\n        \"\"\"\n        self.dataframe.iloc[row, col] = value", "title": ""}
{"_id": "d6525", "text": "def s2b(s):\n    \"\"\"\n    String to binary.\n    \"\"\"\n    ret = []\n    for c in s:\n        ret.append(bin(ord(c))[2:].zfill(8))\n    return \"\".join(ret)", "title": ""}
{"_id": "d6526", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d6527", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d6528", "text": "def today(year=None):\n    \"\"\"this day, last year\"\"\"\n    return datetime.date(int(year), _date.month, _date.day) if year else _date", "title": ""}
{"_id": "d6529", "text": "def get_files(dir_name):\n    \"\"\"Simple directory walker\"\"\"\n    return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]", "title": ""}
{"_id": "d6530", "text": "def start_of_month(val):\n    \"\"\"\n    Return a new datetime.datetime object with values that represent\n    a start of a month.\n    :param val: Date to ...\n    :type val: datetime.datetime | datetime.date\n    :rtype: datetime.datetime\n    \"\"\"\n    if type(val) == date:\n        val = datetime.fromordinal(val.toordinal())\n    return start_of_day(val).replace(day=1)", "title": ""}
{"_id": "d6531", "text": "def xmltreefromfile(filename):\n    \"\"\"Internal function to read an XML file\"\"\"\n    try:\n        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n    except TypeError:\n        return ElementTree.parse(filename, ElementTree.XMLParser())", "title": ""}
{"_id": "d6532", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d6533", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d6534", "text": "def parse_json_date(value):\n    \"\"\"\n    Parses an ISO8601 formatted datetime from a string value\n    \"\"\"\n    if not value:\n        return None\n\n    return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)", "title": ""}
{"_id": "d6535", "text": "def get_bucket_page(page):\n    \"\"\"\n    Returns all the keys in a s3 bucket paginator page.\n    \"\"\"\n    key_list = page.get('Contents', [])\n    logger.debug(\"Retrieving page with {} keys\".format(\n        len(key_list),\n    ))\n    return dict((k.get('Key'), k) for k in key_list)", "title": ""}
{"_id": "d6536", "text": "def get_naive(dt):\n  \"\"\"Gets a naive datetime from a datetime.\n\n  datetime_tz objects can't just have tzinfo replaced with None, you need to\n  call asdatetime.\n\n  Args:\n    dt: datetime object.\n\n  Returns:\n    datetime object without any timezone information.\n  \"\"\"\n  if not dt.tzinfo:\n    return dt\n  if hasattr(dt, \"asdatetime\"):\n    return dt.asdatetime()\n  return dt.replace(tzinfo=None)", "title": ""}
{"_id": "d6537", "text": "def check_dependencies_remote(args):\n    \"\"\"\n    Invoke this command on a remote Python.\n    \"\"\"\n    cmd = [args.python, '-m', 'depends', args.requirement]\n    env = dict(PYTHONPATH=os.path.dirname(__file__))\n    return subprocess.check_call(cmd, env=env)", "title": ""}
{"_id": "d6538", "text": "def string_to_date(value):\n    \"\"\"\n    Return a Python date that corresponds to the specified string\n    representation.\n\n    @param value: string representation of a date.\n\n    @return: an instance ``datetime.datetime`` represented by the string.\n    \"\"\"\n    if isinstance(value, datetime.date):\n        return value\n\n    return dateutil.parser.parse(value).date()", "title": ""}
{"_id": "d6539", "text": "def angle_between_vectors(x, y):\n    \"\"\" Compute the angle between vector x and y \"\"\"\n    dp = dot_product(x, y)\n    if dp == 0:\n        return 0\n    xm = magnitude(x)\n    ym = magnitude(y)\n    return math.acos(dp / (xm*ym)) * (180. / math.pi)", "title": ""}
{"_id": "d6540", "text": "def ToDatetime(self):\n    \"\"\"Converts Timestamp to datetime.\"\"\"\n    return datetime.utcfromtimestamp(\n        self.seconds + self.nanos / float(_NANOS_PER_SECOND))", "title": ""}
{"_id": "d6541", "text": "def ci(a, which=95, axis=None):\n    \"\"\"Return a percentile range from an array of values.\"\"\"\n    p = 50 - which / 2, 50 + which / 2\n    return percentiles(a, p, axis)", "title": ""}
{"_id": "d6542", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d6543", "text": "def error_rate(predictions, labels):\n  \"\"\"Return the error rate based on dense predictions and 1-hot labels.\"\"\"\n  return 100.0 - (\n      100.0 *\n      np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) /\n      predictions.shape[0])", "title": ""}
{"_id": "d6544", "text": "def drop_trailing_zeros_decimal(num):\n    \"\"\" Drops the trailinz zeros from decimal value.\n        Returns a string\n    \"\"\"\n    out = str(num)\n    return out.rstrip('0').rstrip('.') if '.' in out else out", "title": ""}
{"_id": "d6545", "text": "def average_price(quantity_1, price_1, quantity_2, price_2):\n    \"\"\"Calculates the average price between two asset states.\"\"\"\n    return (quantity_1 * price_1 + quantity_2 * price_2) / \\\n            (quantity_1 + quantity_2)", "title": ""}
{"_id": "d6546", "text": "def human__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n\n    # build data\n    N = 1000000\n    M = 3\n    X = np.zeros((N,M))\n    X.shape\n    y = np.zeros(N)\n    X[0, 0] = 1\n    y[0] = 8\n    X[1, 1] = 1\n    y[1] = 8\n    X[2, 0:2] = 1\n    y[2] = 4\n\n    # fit model\n    xor_model = sklearn.tree.DecisionTreeRegressor(max_depth=2)\n    xor_model.fit(X, y)\n\n    return xor_model", "title": ""}
{"_id": "d6547", "text": "def elapsed_time_from(start_time):\n    \"\"\"calculate time delta from latched time and current 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", "title": ""}
{"_id": "d6548", "text": "def read_string(cls, string):\n        \"\"\"Decodes a given bencoded string or bytestring.\n\n        Returns decoded structure(s).\n\n        :param str string:\n        :rtype: list\n        \"\"\"\n        if PY3 and not isinstance(string, byte_types):\n            string = string.encode()\n\n        return cls.decode(string)", "title": ""}
{"_id": "d6549", "text": "def set(self, f):\n        \"\"\"Call a function after a delay, unless another function is set\n        in the meantime.\"\"\"\n        self.stop()\n        self._create_timer(f)\n        self.start()", "title": ""}
{"_id": "d6550", "text": "def __copy__(self):\n        \"\"\"A magic method to implement shallow copy behavior.\"\"\"\n        return self.__class__.load(self.dump(), context=self.context)", "title": ""}
{"_id": "d6551", "text": "def eval_script(self, expr):\n    \"\"\" Evaluates a piece of Javascript in the context of the current page and\n    returns its value. \"\"\"\n    ret = self.conn.issue_command(\"Evaluate\", expr)\n    return json.loads(\"[%s]\" % ret)[0]", "title": ""}
{"_id": "d6552", "text": "def validate_string_list(lst):\n    \"\"\"Validate that the input is a list of strings.\n\n    Raises ValueError if not.\"\"\"\n    if not isinstance(lst, list):\n        raise ValueError('input %r must be a list' % lst)\n    for x in lst:\n        if not isinstance(x, basestring):\n            raise ValueError('element %r in list must be a string' % x)", "title": ""}
{"_id": "d6553", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d6554", "text": "def camel_to_under(name):\n    \"\"\"\n    Converts camel-case string to lowercase string separated by underscores.\n\n    Written by epost (http://stackoverflow.com/questions/1175208).\n\n    :param name: String to be converted\n    :return: new String with camel-case converted to lowercase, underscored\n    \"\"\"\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()", "title": ""}
{"_id": "d6555", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d6556", "text": "def ndarr2str(arr, encoding='ascii'):\n    \"\"\" This is used to ensure that the return value of arr.tostring()\n    is actually a string.  This will prevent lots of if-checks in calling\n    code.  As of numpy v1.6.1 (in Python 3.2.3), the tostring() function\n    still returns type 'bytes', not 'str' as it advertises. \"\"\"\n    # be fast, don't check - just assume 'arr' is a numpy array - the tostring\n    # call will fail anyway if not\n    retval = arr.tostring()\n    # would rather check \"if isinstance(retval, bytes)\", but support 2.5.\n    # could rm the if PY3K check, but it makes this faster on 2.x.\n    if PY3K and not isinstance(retval, str):\n        return retval.decode(encoding)\n    else: # is str\n        return retval", "title": ""}
{"_id": "d6557", "text": "def setdefault(obj, field, default):\n    \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n    setattr(obj, field, getattr(obj, field, default))", "title": ""}
{"_id": "d6558", "text": "def get_decimal_quantum(precision):\n    \"\"\"Return minimal quantum of a number, as defined by precision.\"\"\"\n    assert isinstance(precision, (int, decimal.Decimal))\n    return decimal.Decimal(10) ** (-precision)", "title": ""}
{"_id": "d6559", "text": "def get_var(name, factory=None):\n    \"\"\"Gets a global variable given its name.\n\n    If factory is not None and the variable is not set, factory\n    is a callable that will set the variable.\n\n    If not set, returns None.\n    \"\"\"\n    if name not in _VARS and factory is not None:\n        _VARS[name] = factory()\n    return _VARS.get(name)", "title": ""}
{"_id": "d6560", "text": "def eval_script(self, expr):\n    \"\"\" Evaluates a piece of Javascript in the context of the current page and\n    returns its value. \"\"\"\n    ret = self.conn.issue_command(\"Evaluate\", expr)\n    return json.loads(\"[%s]\" % ret)[0]", "title": ""}
{"_id": "d6561", "text": "def uninstall(cls):\n        \"\"\"Remove the package manager from the system.\"\"\"\n        if os.path.exists(cls.home):\n            shutil.rmtree(cls.home)", "title": ""}
{"_id": "d6562", "text": "def unpickle_file(picklefile, **kwargs):\n    \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)", "title": ""}
{"_id": "d6563", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d6564", "text": "def edge_index(self):\n        \"\"\"A map to look up the index of a edge\"\"\"\n        return dict((edge, index) for index, edge in enumerate(self.edges))", "title": ""}
{"_id": "d6565", "text": "def clean_out_dir(directory):\n    \"\"\"\n    Delete all the files and subdirectories in a directory.\n    \"\"\"\n    if not isinstance(directory, path):\n        directory = path(directory)\n    for file_path in directory.files():\n        file_path.remove()\n    for dir_path in directory.dirs():\n        dir_path.rmtree()", "title": ""}
{"_id": "d6566", "text": "def getTuple(self):\n        \"\"\" Returns the shape of the region as (x, y, w, h) \"\"\"\n        return (self.x, self.y, self.w, self.h)", "title": ""}
{"_id": "d6567", "text": "def safe_delete(filename):\n  \"\"\"Delete a file safely. If it's not present, no-op.\"\"\"\n  try:\n    os.unlink(filename)\n  except OSError as e:\n    if e.errno != errno.ENOENT:\n      raise", "title": ""}
{"_id": "d6568", "text": "def _split(string, splitters):\n    \"\"\"Splits a string into parts at multiple characters\"\"\"\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", "title": ""}
{"_id": "d6569", "text": "def pop():\n        \"\"\"Remove instance from instance list\"\"\"\n        pid = os.getpid()\n        thread = threading.current_thread()\n        Wdb._instances.pop((pid, thread))", "title": ""}
{"_id": "d6570", "text": "def _split(string, splitters):\n    \"\"\"Splits a string into parts at multiple characters\"\"\"\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", "title": ""}
{"_id": "d6571", "text": "def rm_keys_from_dict(d, keys):\n    \"\"\"\n    Given a dictionary and a key list, remove any data in the dictionary with the given keys.\n\n    :param dict d: Metadata\n    :param list keys: Keys to be removed\n    :return dict d: Metadata\n    \"\"\"\n    # Loop for each key given\n    for key in keys:\n        # Is the key in the dictionary?\n        if key in d:\n            try:\n                d.pop(key, None)\n            except KeyError:\n                # Not concerned with an error. Keep going.\n                pass\n    return d", "title": ""}
{"_id": "d6572", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d6573", "text": "def is_symlink(self):\n        \"\"\"\n        Whether this path is a symbolic link.\n        \"\"\"\n        try:\n            return S_ISLNK(self.lstat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            # Path doesn't exist\n            return False", "title": ""}
{"_id": "d6574", "text": "def makedirs(path, mode=0o777, exist_ok=False):\n    \"\"\"A wrapper of os.makedirs().\"\"\"\n    os.makedirs(path, mode, exist_ok)", "title": ""}
{"_id": "d6575", "text": "def _platform_is_windows(platform=sys.platform):\n        \"\"\"Is the current OS a Windows?\"\"\"\n        matched = platform in ('cygwin', 'win32', 'win64')\n        if matched:\n            error_msg = \"Windows isn't supported yet\"\n            raise OSError(error_msg)\n        return matched", "title": ""}
{"_id": "d6576", "text": "def _snake_to_camel_case(value):\n    \"\"\"Convert snake case string to camel case.\"\"\"\n    words = value.split(\"_\")\n    return words[0] + \"\".join(map(str.capitalize, words[1:]))", "title": ""}
{"_id": "d6577", "text": "def _platform_is_windows(platform=sys.platform):\n        \"\"\"Is the current OS a Windows?\"\"\"\n        matched = platform in ('cygwin', 'win32', 'win64')\n        if matched:\n            error_msg = \"Windows isn't supported yet\"\n            raise OSError(error_msg)\n        return matched", "title": ""}
{"_id": "d6578", "text": "def _push_render(self):\n        \"\"\"Render the plot with bokeh.io and push to notebook.\n        \"\"\"\n        bokeh.io.push_notebook(handle=self.handle)\n        self.last_update = time.time()", "title": ""}
{"_id": "d6579", "text": "def first_unique_char(s):\n    \"\"\"\n    :type s: str\n    :rtype: int\n    \"\"\"\n    if (len(s) == 1):\n        return 0\n    ban = []\n    for i in range(len(s)):\n        if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:\n            return i\n        else:\n            ban.append(s[i])\n    return -1", "title": ""}
{"_id": "d6580", "text": "def call_out(command):\n  \"\"\"\n  Run the given command (with shell=False) and return a tuple of\n  (int returncode, str output). Strip the output of enclosing whitespace.\n  \"\"\"\n  # start external command process\n  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n  # get outputs\n  out, _ = p.communicate()\n\n  return p.returncode, out.strip()", "title": ""}
{"_id": "d6581", "text": "def determine_interactive(self):\n\t\t\"\"\"Determine whether we're in an interactive shell.\n\t\tSets interactivity off if appropriate.\n\t\tcf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):\n\t\t\t\tself.interactive = 0\n\t\t\t\treturn False\n\t\texcept Exception:\n\t\t\tself.interactive = 0\n\t\t\treturn False\n\t\tif self.interactive == 0:\n\t\t\treturn False\n\t\treturn True", "title": ""}
{"_id": "d6582", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d6583", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d6584", "text": "def stringify_dict_contents(dct):\n    \"\"\"Turn dict keys and values into native strings.\"\"\"\n    return {\n        str_if_nested_or_str(k): str_if_nested_or_str(v)\n        for k, v in dct.items()\n    }", "title": ""}
{"_id": "d6585", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d6586", "text": "def _defaultdict(dct, fallback=_illegal_character):\n    \"\"\"Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is\n    accessed.\n    \"\"\"\n    out = defaultdict(lambda: fallback)\n    for k, v in six.iteritems(dct):\n        out[k] = v\n    return out", "title": ""}
{"_id": "d6587", "text": "def str2bytes(x):\n  \"\"\"Convert input argument to bytes\"\"\"\n  if type(x) is bytes:\n    return x\n  elif type(x) is str:\n    return bytes([ ord(i) for i in x ])\n  else:\n    return str2bytes(str(x))", "title": ""}
{"_id": "d6588", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d6589", "text": "def parse_date(s):\n    \"\"\"Fast %Y-%m-%d parsing.\"\"\"\n    try:\n        return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10]))\n    except ValueError:  # other accepted format used in one-day data set\n        return datetime.datetime.strptime(s, '%d %B %Y').date()", "title": ""}
{"_id": "d6590", "text": "def get_single_value(d):\n    \"\"\"Get a value from a dict which contains just one item.\"\"\"\n    assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)\n    return next(six.itervalues(d))", "title": ""}
{"_id": "d6591", "text": "def date_to_datetime(x):\n    \"\"\"Convert a date into a datetime\"\"\"\n    if not isinstance(x, datetime) and isinstance(x, date):\n        return datetime.combine(x, time())\n    return x", "title": ""}
{"_id": "d6592", "text": "def _remove_keywords(d):\n    \"\"\"\n    copy the dict, filter_keywords\n\n    Parameters\n    ----------\n    d : dict\n    \"\"\"\n    return { k:v for k, v in iteritems(d) if k not in RESERVED }", "title": ""}
{"_id": "d6593", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d6594", "text": "def data(self, data):\n        \"\"\"Store a copy of the data.\"\"\"\n        self._data = {det: d.copy() for (det, d) in data.items()}", "title": ""}
{"_id": "d6595", "text": "def lower_ext(abspath):\n    \"\"\"Convert file extension to lowercase.\n    \"\"\"\n    fname, ext = os.path.splitext(abspath)\n    return fname + ext.lower()", "title": ""}
{"_id": "d6596", "text": "def stop_button_click_handler(self):\n        \"\"\"Method to handle what to do when the stop button is pressed\"\"\"\n        self.stop_button.setDisabled(True)\n        # Interrupt computations or stop debugging\n        if not self.shellwidget._reading:\n            self.interrupt_kernel()\n        else:\n            self.shellwidget.write_to_stdin('exit')", "title": ""}
{"_id": "d6597", "text": "def timestamp_to_datetime(timestamp):\n    \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n    from datetime import datetime, timedelta\n    obj = datetime.fromtimestamp(timestamp[0])\n    return obj + timedelta(microseconds=int(timestamp[1]))", "title": ""}
{"_id": "d6598", "text": "def disable_stdout_buffering():\n    \"\"\"This turns off stdout buffering so that outputs are immediately\n    materialized and log messages show up before the program exits\"\"\"\n    stdout_orig = sys.stdout\n    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n    # NOTE(brandyn): This removes the original stdout\n    return stdout_orig", "title": ""}
{"_id": "d6599", "text": "def scale_image(image, new_width):\n    \"\"\"Resizes an image preserving the aspect ratio.\n    \"\"\"\n    (original_width, original_height) = image.size\n    aspect_ratio = original_height/float(original_width)\n    new_height = int(aspect_ratio * new_width)\n\n    # This scales it wider than tall, since characters are biased\n    new_image = image.resize((new_width*2, new_height))\n    return new_image", "title": ""}
{"_id": "d6600", "text": "def _renamer(self, tre):\n        \"\"\" renames newick from numbers to sample names\"\"\"\n        ## get the tre with numbered tree tip labels\n        names = tre.get_leaves()\n\n        ## replace numbered names with snames\n        for name in names:\n            name.name = self.samples[int(name.name)]\n\n        ## return with only topology and leaf labels\n        return tre.write(format=9)", "title": ""}
{"_id": "d6601", "text": "def with_tz(request):\n    \"\"\"\n    Get the time with TZ enabled\n\n    \"\"\"\n    \n    dt = datetime.now() \n    t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}') \n    c = RequestContext(request)\n    response = t.render(c)\n    return HttpResponse(response)", "title": ""}
{"_id": "d6602", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d6603", "text": "def get_distance_matrix(x):\n    \"\"\"Get distance matrix given a matrix. Used in testing.\"\"\"\n    square = nd.sum(x ** 2.0, axis=1, keepdims=True)\n    distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))\n    return nd.sqrt(distance_square)", "title": ""}
{"_id": "d6604", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d6605", "text": "def name2rgb(hue):\n    \"\"\"Originally used to calculate color based on module name.\n    \"\"\"\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])", "title": ""}
{"_id": "d6606", "text": "def get_static_url():\n    \"\"\"Return a base static url, always ending with a /\"\"\"\n    path = getattr(settings, 'STATIC_URL', None)\n    if not path:\n        path = getattr(settings, 'MEDIA_URL', None)\n    if not path:\n        path = '/'\n    return path", "title": ""}
{"_id": "d6607", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d6608", "text": "def delete_all_from_db():\n    \"\"\"Clear the database.\n\n    Used for testing and debugging.\n\n    \"\"\"\n    # The models.CASCADE property is set on all ForeignKey fields, so tables can\n    # be deleted in any order without breaking constraints.\n    for model in django.apps.apps.get_models():\n        model.objects.all().delete()", "title": ""}
{"_id": "d6609", "text": "def scipy_sparse_to_spmatrix(A):\n    \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP", "title": ""}
{"_id": "d6610", "text": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "title": ""}
{"_id": "d6611", "text": "def convert_str_to_datetime(df, *, column: str, format: str):\n    \"\"\"\n    Convert string column into datetime column\n\n    ---\n\n    ### Parameters\n\n    *mandatory :*\n    - `column` (*str*): name of the column to format\n    - `format` (*str*): current format of the values (see [available formats](\n    https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))\n    \"\"\"\n    df[column] = pd.to_datetime(df[column], format=format)\n    return df", "title": ""}
{"_id": "d6612", "text": "def is_interactive(self):\n        \"\"\" Determine if the user requested interactive mode.\n        \"\"\"\n        # The Python interpreter sets sys.flags correctly, so use them!\n        if sys.flags.interactive:\n            return True\n\n        # IPython does not set sys.flags when -i is specified, so first\n        # check it if it is already imported.\n        if '__IPYTHON__' not in dir(six.moves.builtins):\n            return False\n\n        # Then we check the application singleton and determine based on\n        # a variable it sets.\n        try:\n            from IPython.config.application import Application as App\n            return App.initialized() and App.instance().interact\n        except (ImportError, AttributeError):\n            return False", "title": ""}
{"_id": "d6613", "text": "def install_postgres(user=None, dbname=None, password=None):\n    \"\"\"Install Postgres on remote\"\"\"\n    execute(pydiploy.django.install_postgres_server,\n            user=user, dbname=dbname, password=password)", "title": ""}
{"_id": "d6614", "text": "def multiply(self, number):\n        \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n        return self.from_list([x * number for x in self.to_list()])", "title": ""}
{"_id": "d6615", "text": "def inheritdoc(method):\n    \"\"\"Set __doc__ of *method* to __doc__ of *method* in its parent class.\n\n    Since this is used on :class:`.StringMixIn`, the \"parent class\" used is\n    ``str``. This function can be used as a decorator.\n    \"\"\"\n    method.__doc__ = getattr(str, method.__name__).__doc__\n    return method", "title": ""}
{"_id": "d6616", "text": "def decode_arr(data):\n    \"\"\"Extract a numpy array from a base64 buffer\"\"\"\n    data = data.encode('utf-8')\n    return frombuffer(base64.b64decode(data), float64)", "title": ""}
{"_id": "d6617", "text": "def format_doc_text(text):\n    \"\"\"\n    A very thin wrapper around textwrap.fill to consistently wrap documentation text\n    for display in a command line environment. The text is wrapped to 99 characters with an\n    indentation depth of 4 spaces. Each line is wrapped independently in order to preserve\n    manually added line breaks.\n\n    :param text: The text to format, it is cleaned by inspect.cleandoc.\n    :return: The formatted doc text.\n    \"\"\"\n\n    return '\\n'.join(\n        textwrap.fill(line, width=99, initial_indent='    ', subsequent_indent='    ')\n        for line in inspect.cleandoc(text).splitlines())", "title": ""}
{"_id": "d6618", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d6619", "text": "def fill_document(doc):\n    \"\"\"Add a section, a subsection and some text to the document.\n\n    :param doc: the document\n    :type doc: :class:`pylatex.document.Document` instance\n    \"\"\"\n    with doc.create(Section('A section')):\n        doc.append('Some regular text and some ')\n        doc.append(italic('italic text. '))\n\n        with doc.create(Subsection('A subsection')):\n            doc.append('Also some crazy characters: $&#{}')", "title": ""}
{"_id": "d6620", "text": "def set_locale(request):\n    \"\"\"Return locale from GET lang param or automatically.\"\"\"\n    return request.query.get('lang', app.ps.babel.select_locale_by_request(request))", "title": ""}
{"_id": "d6621", "text": "def inline_inputs(self):\n        \"\"\"Inline all input latex files references by this document. The\n        inlining is accomplished recursively. The document is modified\n        in place.\n        \"\"\"\n        self.text = texutils.inline(self.text,\n                                    os.path.dirname(self._filepath))\n        # Remove children\n        self._children = {}", "title": ""}
{"_id": "d6622", "text": "def setwinsize(self, rows, cols):\n        \"\"\"Set the terminal window size of the child tty.\n        \"\"\"\n        self._winsize = (rows, cols)\n        self.pty.set_size(cols, rows)", "title": ""}
{"_id": "d6623", "text": "def downsample_with_striding(array, factor):\n    \"\"\"Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x.\n    \"\"\"\n    return array[tuple(np.s_[::f] for f in factor)]", "title": ""}
{"_id": "d6624", "text": "def get_best_encoding(stream):\n    \"\"\"Returns the default stream encoding if not found.\"\"\"\n    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n    if is_ascii_encoding(rv):\n        return 'utf-8'\n    return rv", "title": ""}
{"_id": "d6625", "text": "def delete_collection(mongo_uri, database_name, collection_name):\n    \"\"\"\n    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.\n    \"\"\"\n    client = pymongo.MongoClient(mongo_uri)\n\n    db = client[database_name]\n\n    db.drop_collection(collection_name)", "title": ""}
{"_id": "d6626", "text": "def _float_almost_equal(float1, float2, places=7):\n    \"\"\"Return True if two numbers are equal up to the\n    specified number of \"places\" after the decimal point.\n    \"\"\"\n\n    if round(abs(float2 - float1), places) == 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d6627", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d6628", "text": "def any_contains_any(strings, candidates):\n    \"\"\"Whether any of the strings contains any of the candidates.\"\"\"\n    for string in strings:\n        for c in candidates:\n            if c in string:\n                return True", "title": ""}
{"_id": "d6629", "text": "def get_code(module):\n    \"\"\"\n    Compile and return a Module's code object.\n    \"\"\"\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()", "title": ""}
{"_id": "d6630", "text": "def is_complex(dtype):\n  \"\"\"Returns whether this is a complex floating point type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_complex'):\n    return dtype.is_complex\n  return np.issubdtype(np.dtype(dtype), np.complex)", "title": ""}
{"_id": "d6631", "text": "def command(name, mode):\n    \"\"\" Label a method as a command with name. \"\"\"\n    def decorator(fn):\n        commands[name] = fn.__name__\n        _Client._addMethod(fn.__name__, name, mode)\n        return fn\n    return decorator", "title": ""}
{"_id": "d6632", "text": "def is_complex(dtype):\n  \"\"\"Returns whether this is a complex floating point type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_complex'):\n    return dtype.is_complex\n  return np.issubdtype(np.dtype(dtype), np.complex)", "title": ""}
{"_id": "d6633", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d6634", "text": "def _is_initialized(self, entity):\n    \"\"\"Internal helper to ask if the entity has a value for this Property.\n\n    This returns False if a value is stored but it is None.\n    \"\"\"\n    return (not self._required or\n            ((self._has_value(entity) or self._default is not None) and\n             self._get_value(entity) is not None))", "title": ""}
{"_id": "d6635", "text": "def scan(client, query=None, scroll='5m', raise_on_error=True,\n         preserve_order=False, size=1000, **kwargs):\n    \"\"\"\n    Simple abstraction on top of the\n    :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that\n    yields all hits as returned by underlining scroll requests.\n    By default scan does not return results in any pre-determined order. To\n    have a standard order in the returned documents (either by score or\n    explicit sort definition) when scrolling, use ``preserve_order=True``. This\n    may be an expensive operation and will negate the performance benefits of\n    using ``scan``.\n    :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n    :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api\n    :arg scroll: Specify how long a consistent view of the index should be\n        maintained for scrolled search\n    :arg raise_on_error: raises an exception (``ScanError``) if an error is\n        encountered (some shards fail to execute). By default we raise.\n    :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will\n        cause the scroll to paginate with preserving the order. Note that this\n        can be an extremely expensive operation and can easily lead to\n        unpredictable results, use with caution.\n    :arg size: size (per shard) of the batch send at each iteration.\n    Any additional keyword arguments will be passed to the initial\n    :meth:`~elasticsearch.Elasticsearch.search` call::\n        scan(es,\n            query={\"query\": {\"match\": {\"title\": \"python\"}}},\n            index=\"orders-*\",\n            doc_type=\"books\"\n        )\n    \"\"\"\n    if not preserve_order:\n        kwargs['search_type'] = 'scan'\n    # initial search\n    resp = client.search(body=query, scroll=scroll, size=size, **kwargs)\n\n    scroll_id = resp.get('_scroll_id')\n    if scroll_id is None:\n        return\n\n    first_run = True\n    while True:\n        # if we didn't set search_type to scan initial search contains data\n        if preserve_order and first_run:\n            first_run = False\n        else:\n            resp = client.scroll(scroll_id, scroll=scroll)\n\n        for hit in resp['hits']['hits']:\n            yield hit\n\n        # check if we have any errrors\n        if resp[\"_shards\"][\"failed\"]:\n            logger.warning(\n                'Scroll request has failed on %d shards out of %d.',\n                resp['_shards']['failed'], resp['_shards']['total']\n            )\n            if raise_on_error:\n                raise ScanError(\n                    'Scroll request has failed on %d shards out of %d.' %\n                    (resp['_shards']['failed'], resp['_shards']['total'])\n                )\n\n        scroll_id = resp.get('_scroll_id')\n        # end of scroll\n        if scroll_id is None or not resp['hits']['hits']:\n            break", "title": ""}
{"_id": "d6636", "text": "def is_punctuation(text):\n    \"\"\"Check if given string is a punctuation\"\"\"\n    return not (text.lower() in config.AVRO_VOWELS or\n                text.lower() in config.AVRO_CONSONANTS)", "title": ""}
{"_id": "d6637", "text": "def clear_es():\n        \"\"\"Clear all indexes in the es core\"\"\"\n        # TODO: should receive a catalog slug.\n        ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])\n        LOGGER.debug('Elasticsearch: Index cleared')", "title": ""}
{"_id": "d6638", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d6639", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d6640", "text": "def __add__(self, other):\n        \"\"\"Handle the `+` operator.\"\"\"\n        return self._handle_type(other)(self.value + other.value)", "title": ""}
{"_id": "d6641", "text": "def _is_expired_response(self, response):\n        \"\"\"\n        Check if the response failed because of an expired access token.\n        \"\"\"\n        if response.status_code != 401:\n            return False\n        challenge = response.headers.get('www-authenticate', '')\n        return 'error=\"invalid_token\"' in challenge", "title": ""}
{"_id": "d6642", "text": "def get_element_with_id(self, id):\n        \"\"\"Return the element with the specified ID.\"\"\"\n        # Should we maintain a hashmap of ids to make this more efficient? Probably overkill.\n        # TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)\n        return next((el for el in self.elements if el.id == id), None)", "title": ""}
{"_id": "d6643", "text": "def isbinary(*args):\n    \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n    return all(map(lambda c: isnumber(c) or isbool(c), args))", "title": ""}
{"_id": "d6644", "text": "def add_parent(self, parent):\n        \"\"\"\n        Adds self as child of parent, then adds parent.\n        \"\"\"\n        parent.add_child(self)\n        self.parent = parent\n        return parent", "title": ""}
{"_id": "d6645", "text": "def column_exists(cr, table, column):\n    \"\"\" Check whether a certain column exists \"\"\"\n    cr.execute(\n        'SELECT count(attname) FROM pg_attribute '\n        'WHERE attrelid = '\n        '( SELECT oid FROM pg_class WHERE relname = %s ) '\n        'AND attname = %s',\n        (table, column))\n    return cr.fetchone()[0] == 1", "title": ""}
{"_id": "d6646", "text": "def is_non_empty_string(input_string):\n    \"\"\"\n    Validate if non empty string\n\n    :param input_string: Input is a *str*.\n    :return: True if input is string and non empty.\n       Raise :exc:`Exception` otherwise.\n    \"\"\"\n    try:\n        if not input_string.strip():\n            raise ValueError()\n    except AttributeError as error:\n        raise TypeError(error)\n\n    return True", "title": ""}
{"_id": "d6647", "text": "def _is_valid_url(url):\n        \"\"\" Helper function to validate that URLs are well formed, i.e that it contains a valid\n            protocol and a valid domain. It does not actually check if the URL exists\n        \"\"\"\n        try:\n            parsed = urlparse(url)\n            mandatory_parts = [parsed.scheme, parsed.netloc]\n            return all(mandatory_parts)\n        except:\n            return False", "title": ""}
{"_id": "d6648", "text": "def is_enum_type(type_):\n    \"\"\" Checks if the given type is an enum type.\n\n    :param type_: The type to check\n    :return: True if the type is a enum type, otherwise False\n    :rtype: bool\n    \"\"\"\n\n    return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))", "title": ""}
{"_id": "d6649", "text": "def is_nullable_list(val, vtype):\n    \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n    return (isinstance(val, list) and\n            any(isinstance(v, vtype) for v in val) and\n            all((isinstance(v, vtype) or v is None) for v in val))", "title": ""}
{"_id": "d6650", "text": "def EnumValueName(self, enum, value):\n    \"\"\"Returns the string name of an enum value.\n\n    This is just a small helper method to simplify a common operation.\n\n    Args:\n      enum: string name of the Enum.\n      value: int, value of the enum.\n\n    Returns:\n      string name of the enum value.\n\n    Raises:\n      KeyError if either the Enum doesn't exist or the value is not a valid\n        value for the enum.\n    \"\"\"\n    return self.enum_types_by_name[enum].values_by_number[value].name", "title": ""}
{"_id": "d6651", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d6652", "text": "def write_enum(fo, datum, schema):\n    \"\"\"An enum is encoded by a int, representing the zero-based position of\n    the symbol in the schema.\"\"\"\n    index = schema['symbols'].index(datum)\n    write_int(fo, index)", "title": ""}
{"_id": "d6653", "text": "def is_string(obj):\n    \"\"\"Is this a string.\n\n    :param object obj:\n    :rtype: bool\n    \"\"\"\n    if PYTHON3:\n        str_type = (bytes, str)\n    else:\n        str_type = (bytes, str, unicode)\n    return isinstance(obj, str_type)", "title": ""}
{"_id": "d6654", "text": "def _escape(s):\n    \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n    e = s\n    e = e.replace('\\\\', '\\\\\\\\')\n    e = e.replace('\\n', '\\\\n')\n    e = e.replace('\\r', '\\\\r')\n    e = e.replace(\"'\", \"\\\\'\")\n    e = e.replace('\"', '\\\\\"')\n    return e", "title": ""}
{"_id": "d6655", "text": "def contains_all(self, array):\n        \"\"\"Test if `array` is an array of real numbers.\"\"\"\n        dtype = getattr(array, 'dtype', None)\n        if dtype is None:\n            dtype = np.result_type(*array)\n        return is_real_dtype(dtype)", "title": ""}
{"_id": "d6656", "text": "def get_user_id_from_email(self, email):\n        \"\"\" Uses the get-all-user-accounts Portals API to retrieve the\n        user-id by supplying an email. \"\"\"\n        accts = self.get_all_user_accounts()\n\n        for acct in accts:\n            if acct['email'] == email:\n                return acct['id']\n        return None", "title": ""}
{"_id": "d6657", "text": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "title": ""}
{"_id": "d6658", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d6659", "text": "def is_int_type(val):\n    \"\"\"Return True if `val` is of integer type.\"\"\"\n    try:               # Python 2\n        return isinstance(val, (int, long))\n    except NameError:  # Python 3\n        return isinstance(val, int)", "title": ""}
{"_id": "d6660", "text": "def expandpath(path):\n    \"\"\"\n    Expand a filesystem path that may or may not contain user/env vars.\n\n    :param str path: path to expand\n    :return str: expanded version of input path\n    \"\"\"\n    return os.path.expandvars(os.path.expanduser(path)).replace(\"//\", \"/\")", "title": ""}
{"_id": "d6661", "text": "def is_square_matrix(mat):\n    \"\"\"Test if an array is a square matrix.\"\"\"\n    mat = np.array(mat)\n    if mat.ndim != 2:\n        return False\n    shape = mat.shape\n    return shape[0] == shape[1]", "title": ""}
{"_id": "d6662", "text": "def _expand(self, str, local_vars={}):\n        \"\"\"Expand $vars in a string.\"\"\"\n        return ninja_syntax.expand(str, self.vars, local_vars)", "title": ""}
{"_id": "d6663", "text": "def is_same_file (filename1, filename2):\n    \"\"\"Check if filename1 and filename2 point to the same file object.\n    There can be false negatives, ie. the result is False, but it is\n    the same file anyway. Reason is that network filesystems can create\n    different paths to the same physical file.\n    \"\"\"\n    if filename1 == filename2:\n        return True\n    if os.name == 'posix':\n        return os.path.samefile(filename1, filename2)\n    return is_same_filename(filename1, filename2)", "title": ""}
{"_id": "d6664", "text": "def validate_string(option, value):\n    \"\"\"Validates that 'value' is an instance of `basestring` for Python 2\n    or `str` for Python 3.\n    \"\"\"\n    if isinstance(value, string_type):\n        return value\n    raise TypeError(\"Wrong type for %s, value must be \"\n                    \"an instance of %s\" % (option, string_type.__name__))", "title": ""}
{"_id": "d6665", "text": "def eqstr(a, b):\n    \"\"\"\n    Determine whether two strings are equivalent.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html\n\n    :param a: Arbitrary character string.\n    :type a: str\n    :param b: Arbitrary character string.\n    :type b: str\n    :return: True if A and B are equivalent.\n    :rtype: bool\n    \"\"\"\n    return bool(libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)))", "title": ""}
{"_id": "d6666", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d6667", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d6668", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d6669", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d6670", "text": "def parse_domain(url):\n    \"\"\" parse the domain from the url \"\"\"\n    domain_match = lib.DOMAIN_REGEX.match(url)\n    if domain_match:\n        return domain_match.group()", "title": ""}
{"_id": "d6671", "text": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "title": ""}
{"_id": "d6672", "text": "def _relpath(name):\n    \"\"\"\n    Strip absolute components from path.\n    Inspired from zipfile.write().\n    \"\"\"\n    return os.path.normpath(os.path.splitdrive(name)[1]).lstrip(_allsep)", "title": ""}
{"_id": "d6673", "text": "def contains_geometric_info(var):\n    \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)", "title": ""}
{"_id": "d6674", "text": "def logv(msg, *args, **kwargs):\n    \"\"\"\n    Print out a log message, only if verbose mode.\n    \"\"\"\n    if settings.VERBOSE:\n        log(msg, *args, **kwargs)", "title": ""}
{"_id": "d6675", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d6676", "text": "def computeFactorial(n):\n    \"\"\"\n    computes factorial of n\n    \"\"\"\n    sleep_walk(10)\n    ret = 1\n    for i in range(n):\n        ret = ret * (i + 1)\n    return ret", "title": ""}
{"_id": "d6677", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d6678", "text": "def data_directory():\n    \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")", "title": ""}
{"_id": "d6679", "text": "def is_int_type(val):\n    \"\"\"Return True if `val` is of integer type.\"\"\"\n    try:               # Python 2\n        return isinstance(val, (int, long))\n    except NameError:  # Python 3\n        return isinstance(val, int)", "title": ""}
{"_id": "d6680", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d6681", "text": "def is_same_shape(self, other_im, check_channels=False):\n        \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n        Parameters\n        ----------\n        other_im : :obj:`Image`\n            image to compare\n        check_channels : bool\n            whether or not to check equality of the channels\n\n        Returns\n        -------\n        bool\n            True if the images are the same shape, False otherwise\n        \"\"\"\n        if self.height == other_im.height and self.width == other_im.width:\n            if check_channels and self.channels != other_im.channels:\n                return False\n            return True\n        return False", "title": ""}
{"_id": "d6682", "text": "def filter_greys_using_image(image, target):\n    \"\"\"Filter out any values in target not in image\n\n    :param image: image containing values to appear in filtered image\n    :param target: the image to filter\n    :rtype: 2d  :class:`numpy.ndarray` containing only value in image\n        and with the same dimensions as target\n\n    \"\"\"\n    maskbase = numpy.array(range(256), dtype=numpy.uint8)\n    mask = numpy.where(numpy.in1d(maskbase, numpy.unique(image)), maskbase, 0)\n    return mask[target]", "title": ""}
{"_id": "d6683", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d6684", "text": "def get_remote_content(filepath):\n        \"\"\" A handy wrapper to get a remote file content \"\"\"\n        with hide('running'):\n            temp = BytesIO()\n            get(filepath, temp)\n            content = temp.getvalue().decode('utf-8')\n        return content.strip()", "title": ""}
{"_id": "d6685", "text": "def numberp(v):\n    \"\"\"Return true iff 'v' is a number.\"\"\"\n    return (not(isinstance(v, bool)) and\n            (isinstance(v, int) or isinstance(v, float)))", "title": ""}
{"_id": "d6686", "text": "def fft_freqs(n_fft, fs):\n    \"\"\"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.\n    \"\"\"\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)", "title": ""}
{"_id": "d6687", "text": "def __eq__(self, other):\n        \"\"\"Determine if two objects are equal.\"\"\"\n        return isinstance(other, self.__class__) \\\n            and self._freeze() == other._freeze()", "title": ""}
{"_id": "d6688", "text": "def stft_magnitude(signal, fft_length,\n                   hop_length=None,\n                   window_length=None):\n  \"\"\"Calculate the short-time Fourier transform magnitude.\n\n  Args:\n    signal: 1D np.array of the input time-domain signal.\n    fft_length: Size of the FFT to apply.\n    hop_length: Advance (in samples) between each frame passed to FFT.\n    window_length: Length of each block of samples to pass to FFT.\n\n  Returns:\n    2D np.array where each row contains the magnitudes of the fft_length/2+1\n    unique values of the FFT for the corresponding frame of input samples.\n  \"\"\"\n  frames = frame(signal, window_length, hop_length)\n  # Apply frame window to each frame. We use a periodic Hann (cosine of period\n  # window_length) instead of the symmetric Hann of np.hanning (period\n  # window_length-1).\n  window = periodic_hann(window_length)\n  windowed_frames = frames * window\n  return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))", "title": ""}
{"_id": "d6689", "text": "def memory_used(self):\n        \"\"\"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.\n        \"\"\"\n        if self._end_memory:\n            memory_used = self._end_memory - self._start_memory\n            return memory_used\n        else:\n            return None", "title": ""}
{"_id": "d6690", "text": "def fft_freqs(n_fft, fs):\n    \"\"\"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.\n    \"\"\"\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)", "title": ""}
{"_id": "d6691", "text": "def is_iter_non_string(obj):\n    \"\"\"test if object is a list or tuple\"\"\"\n    if isinstance(obj, list) or isinstance(obj, tuple):\n        return True\n    return False", "title": ""}
{"_id": "d6692", "text": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n    \"\"\"\n    http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n    \"\"\"\n    fft = np.fft.fft(data)\n    # n = len(data)\n    # timestep = 1.0 / fs\n    # freq = np.fft.fftfreq(n, d=timestep)\n    bp = fft.copy()\n\n    # Zero out fft coefficients\n    # bp[10:-10] = 0\n\n    # Normalise\n    # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n    bp *= fft.dot(fft) / bp.dot(bp)\n\n    # must multipy by 2 to get the correct amplitude\n    ibp = 12 * np.fft.ifft(bp)\n    return ibp", "title": ""}
{"_id": "d6693", "text": "def percentile(values, k):\n    \"\"\"Find the percentile of a list of values.\n\n    :param list values: The list of values to find the percentile of\n    :param int k: The percentile to find\n    :rtype: float or int\n\n    \"\"\"\n    if not values:\n        return None\n    values.sort()\n    index = (len(values) * (float(k) / 100)) - 1\n    return values[int(math.ceil(index))]", "title": ""}
{"_id": "d6694", "text": "def file_writelines_flush_sync(path, lines):\n    \"\"\"\n    Fill file at @path with @lines then flush all buffers\n    (Python and system buffers)\n    \"\"\"\n    fp = open(path, 'w')\n    try:\n        fp.writelines(lines)\n        flush_sync_file_object(fp)\n    finally:\n        fp.close()", "title": ""}
{"_id": "d6695", "text": "def drop_bad_characters(text):\n    \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n    also any whitespace characters that aren't space.\n\n    :arg str text: the text to fix\n\n    :returns: text with all bad characters dropped\n\n    \"\"\"\n    # Strip all non-ascii and non-printable characters\n    text = ''.join([c for c in text if c in ALLOWED_CHARS])\n    return text", "title": ""}
{"_id": "d6696", "text": "def is_writable_by_others(filename):\n    \"\"\"Check if file or directory is world writable.\"\"\"\n    mode = os.stat(filename)[stat.ST_MODE]\n    return mode & stat.S_IWOTH", "title": ""}
{"_id": "d6697", "text": "def _clear(self):\n        \"\"\"\n        Helper that clears the composition.\n        \"\"\"\n        draw = ImageDraw.Draw(self._background_image)\n        draw.rectangle(self._device.bounding_box,\n                       fill=\"black\")\n        del draw", "title": ""}
{"_id": "d6698", "text": "def txt_line_iterator(path):\n  \"\"\"Iterate through lines of file.\"\"\"\n  with tf.gfile.Open(path) as f:\n    for line in f:\n      yield line.strip()", "title": ""}
{"_id": "d6699", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d6700", "text": "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)", "title": ""}
{"_id": "d6701", "text": "def clear_globals_reload_modules(self):\n        \"\"\"Clears globals and reloads modules\"\"\"\n\n        self.code_array.clear_globals()\n        self.code_array.reload_modules()\n\n        # Clear result cache\n        self.code_array.result_cache.clear()", "title": ""}
{"_id": "d6702", "text": "def rewindbody(self):\n        \"\"\"Rewind the file to the start of the body (if seekable).\"\"\"\n        if not self.seekable:\n            raise IOError, \"unseekable file\"\n        self.fp.seek(self.startofbody)", "title": ""}
{"_id": "d6703", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d6704", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d6705", "text": "def close_all_but_this(self):\n        \"\"\"Close all files but the current one\"\"\"\n        self.close_all_right()\n        for i in range(0, self.get_stack_count()-1  ):\n            self.close_file(0)", "title": ""}
{"_id": "d6706", "text": "def _fill_array_from_list(the_list, the_array):\n        \"\"\"Fill an `array` from a `list`\"\"\"\n        for i, val in enumerate(the_list):\n            the_array[i] = val\n        return the_array", "title": ""}
{"_id": "d6707", "text": "def _maybe_fill(arr, fill_value=np.nan):\n    \"\"\"\n    if we have a compatible fill_value and arr dtype, then fill\n    \"\"\"\n    if _isna_compat(arr, fill_value):\n        arr.fill(fill_value)\n    return arr", "title": ""}
{"_id": "d6708", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d6709", "text": "def apply_filters(df, filters):\n        \"\"\"Basic filtering for a dataframe.\"\"\"\n        idx = pd.Series([True]*df.shape[0])\n        for k, v in list(filters.items()):\n            if k not in df.columns:\n                continue\n            idx &= (df[k] == v)\n\n        return df.loc[idx]", "title": ""}
{"_id": "d6710", "text": "def combinations(l):\n    \"\"\"Pure-Python implementation of itertools.combinations(l, 2).\"\"\"\n    result = []\n    for x in xrange(len(l) - 1):\n        ls = l[x + 1:]\n        for y in ls:\n            result.append((l[x], y))\n    return result", "title": ""}
{"_id": "d6711", "text": "def BROADCAST_FILTER_NOT(func):\n        \"\"\"\n        Composes the passed filters into an and-joined filter.\n        \"\"\"\n        return lambda u, command, *args, **kwargs: not func(u, command, *args, **kwargs)", "title": ""}
{"_id": "d6712", "text": "def file_matches(filename, patterns):\n    \"\"\"Does this filename match any of the patterns?\"\"\"\n    return any(fnmatch.fnmatch(filename, pat) for pat in patterns)", "title": ""}
{"_id": "d6713", "text": "def _sim_fill(r1, r2, imsize):\n    \"\"\"\n        calculate the fill similarity over the image\n    \"\"\"\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", "title": ""}
{"_id": "d6714", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d6715", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d6716", "text": "def lint(args):\n    \"\"\"Run lint checks using flake8.\"\"\"\n    application = get_current_application()\n    if not args:\n        args = [application.name, 'tests']\n    args = ['flake8'] + list(args)\n    run.main(args, standalone_mode=False)", "title": ""}
{"_id": "d6717", "text": "def _sim_fill(r1, r2, imsize):\n    \"\"\"\n        calculate the fill similarity over the image\n    \"\"\"\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", "title": ""}
{"_id": "d6718", "text": "def docannotate(func):\n    \"\"\"Annotate a function using information from its docstring.\n\n    The annotation actually happens at the time the function is first called\n    to improve startup time.  For this function to work, the docstring must be\n    formatted correctly.  You should use the typedargs pylint plugin to make\n    sure there are no errors in the docstring.\n    \"\"\"\n\n    func = annotated(func)\n    func.metadata.load_from_doc = True\n\n    if func.decorated:\n        return func\n\n    func.decorated = True\n    return decorate(func, _check_and_execute)", "title": ""}
{"_id": "d6719", "text": "def unique(transactions):\n    \"\"\" Remove any duplicate entries. \"\"\"\n    seen = set()\n    # TODO: Handle comments\n    return [x for x in transactions if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d6720", "text": "def initialize_api(flask_app):\n    \"\"\"Initialize an API.\"\"\"\n    if not flask_restplus:\n        return\n\n    api = flask_restplus.Api(version=\"1.0\", title=\"My Example API\")\n    api.add_resource(HelloWorld, \"/hello\")\n\n    blueprint = flask.Blueprint(\"api\", __name__, url_prefix=\"/api\")\n    api.init_app(blueprint)\n    flask_app.register_blueprint(blueprint)", "title": ""}
{"_id": "d6721", "text": "def converged(matrix1, matrix2):\n    \"\"\"\n    Check for convergence by determining if \n    matrix1 and matrix2 are approximately equal.\n    \n    :param matrix1: The matrix to compare with matrix2\n    :param matrix2: The matrix to compare with matrix1\n    :returns: True if matrix1 and matrix2 approximately equal\n    \"\"\"\n    if isspmatrix(matrix1) or isspmatrix(matrix2):\n        return sparse_allclose(matrix1, matrix2)\n\n    return np.allclose(matrix1, matrix2)", "title": ""}
{"_id": "d6722", "text": "def touch_project():\n    \"\"\"\n    Touches the project to trigger refreshing its cauldron.json state.\n    \"\"\"\n    r = Response()\n    project = cd.project.get_internal_project()\n\n    if project:\n        project.refresh()\n    else:\n        r.fail(\n            code='NO_PROJECT',\n            message='No open project to refresh'\n        )\n\n    return r.update(\n        sync_time=sync_status.get('time', 0)\n    ).flask_serialize()", "title": ""}
{"_id": "d6723", "text": "def boolean(value):\n    \"\"\"\n    Configuration-friendly boolean type converter.\n\n    Supports both boolean-valued and string-valued inputs (e.g. from env vars).\n\n    \"\"\"\n    if isinstance(value, bool):\n        return value\n\n    if value == \"\":\n        return False\n\n    return strtobool(value)", "title": ""}
{"_id": "d6724", "text": "def get_code(module):\n    \"\"\"\n    Compile and return a Module's code object.\n    \"\"\"\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()", "title": ""}
{"_id": "d6725", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d6726", "text": "def _concatenate_virtual_arrays(arrs, cols=None, scaling=None):\n    \"\"\"Return a virtual concatenate of several NumPy arrays.\"\"\"\n    return None if not len(arrs) else ConcatenatedArrays(arrs, cols,\n                                                         scaling=scaling)", "title": ""}
{"_id": "d6727", "text": "def init_app(self, app):\n        \"\"\"Initialize Flask application.\"\"\"\n        app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True)", "title": ""}
{"_id": "d6728", "text": "def _concatenate_virtual_arrays(arrs, cols=None, scaling=None):\n    \"\"\"Return a virtual concatenate of several NumPy arrays.\"\"\"\n    return None if not len(arrs) else ConcatenatedArrays(arrs, cols,\n                                                         scaling=scaling)", "title": ""}
{"_id": "d6729", "text": "def serve_static(request, path, insecure=False, **kwargs):\n    \"\"\"Collect and serve static files.\n\n    This view serves up static files, much like Django's\n    :py:func:`~django.views.static.serve` view, with the addition that it\n    collects static files first (if enabled). This allows images, fonts, and\n    other assets to be served up without first loading a page using the\n    ``{% javascript %}`` or ``{% stylesheet %}`` template tags.\n\n    You can use this view by adding the following to any :file:`urls.py`::\n\n        urlpatterns += static('static/', view='pipeline.views.serve_static')\n    \"\"\"\n    # Follow the same logic Django uses for determining access to the\n    # static-serving view.\n    if not django_settings.DEBUG and not insecure:\n        raise ImproperlyConfigured(\"The staticfiles view can only be used in \"\n                                   \"debug mode or if the --insecure \"\n                                   \"option of 'runserver' is used\")\n\n    if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED:\n        # Collect only the requested file, in order to serve the result as\n        # fast as possible. This won't interfere with the template tags in any\n        # way, as those will still cause Django to collect all media.\n        default_collector.collect(request, files=[path])\n\n    return serve(request, path, document_root=django_settings.STATIC_ROOT,\n                 **kwargs)", "title": ""}
{"_id": "d6730", "text": "def generic_add(a, b):\n    \"\"\"Simple function to add two numbers\"\"\"\n    logger.debug('Called generic_add({}, {})'.format(a, b))\n    return a + b", "title": ""}
{"_id": "d6731", "text": "def parse_form(self, req, name, field):\n        \"\"\"Pull a form value from the request.\"\"\"\n        return get_value(req.body_arguments, name, field)", "title": ""}
{"_id": "d6732", "text": "def reseed_random(seed):\n    \"\"\"Reseed factory.fuzzy's random generator.\"\"\"\n    r = random.Random(seed)\n    random_internal_state = r.getstate()\n    set_random_state(random_internal_state)", "title": ""}
{"_id": "d6733", "text": "def html(header_rows):\n    \"\"\"\n    Convert a list of tuples describing a table into a HTML string\n    \"\"\"\n    name = 'table%d' % next(tablecounter)\n    return HtmlTable([map(str, row) for row in header_rows], name).render()", "title": ""}
{"_id": "d6734", "text": "def enable_proxy(self, host, port):\n        \"\"\"Enable a default web proxy\"\"\"\n\n        self.proxy = [host, _number(port)]\n        self.proxy_enabled = True", "title": ""}
{"_id": "d6735", "text": "def _linepoint(self, t, x0, y0, x1, y1):\n        \"\"\" Returns coordinates for point at t on the line.\n            Calculates the coordinates of x and y for a point at t on a straight line.\n            The t parameter is a number between 0.0 and 1.0,\n            x0 and y0 define the starting point of the line,\n            x1 and y1 the ending point of the line.\n        \"\"\"\n        # Originally from nodebox-gl\n        out_x = x0 + t * (x1 - x0)\n        out_y = y0 + t * (y1 - y0)\n        return (out_x, out_y)", "title": ""}
{"_id": "d6736", "text": "def connect(host, port, username, password):\n        \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n        # Instantiate ftplib client\n        session = ftplib.FTP()\n\n        # Connect to host without auth\n        session.connect(host, port)\n\n        # Authenticate connection\n        session.login(username, password)\n        return session", "title": ""}
{"_id": "d6737", "text": "def run(context, port):\n    \"\"\" Run the Webserver/SocketIO and app\n    \"\"\"\n    global ctx\n    ctx = context\n    app.run(port=port)", "title": ""}
{"_id": "d6738", "text": "def _loadf(ins):\n    \"\"\" Loads a floating point value from a memory address.\n    If 2nd arg. start with '*', it is always treated as\n    an indirect value.\n    \"\"\"\n    output = _float_oper(ins.quad[2])\n    output.extend(_fpush())\n    return output", "title": ""}
{"_id": "d6739", "text": "def serialize(self, value):\n        \"\"\"Takes a datetime object and returns a string\"\"\"\n        if isinstance(value, str):\n            return value\n        return value.strftime(DATETIME_FORMAT)", "title": ""}
{"_id": "d6740", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d6741", "text": "def sample_correlations(self):\n        \"\"\"Returns an `ExpMatrix` containing all pairwise sample correlations.\n\n        Returns\n        -------\n        `ExpMatrix`\n            The sample correlation matrix.\n\n        \"\"\"\n        C = np.corrcoef(self.X.T)\n        corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)\n        return corr_matrix", "title": ""}
{"_id": "d6742", "text": "def raise_figure_window(f=0):\n    \"\"\"\n    Raises the supplied figure number or figure window.\n    \"\"\"\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()", "title": ""}
{"_id": "d6743", "text": "def index_all(self, index_name):\n        \"\"\"Index all available documents, using streaming_bulk for speed\n        Args:\n\n        index_name (string): The index\n        \"\"\"\n        oks = 0\n        notoks = 0\n        for ok, item in streaming_bulk(\n            self.es_client,\n            self._iter_documents(index_name)\n        ):\n            if ok:\n                oks += 1\n            else:\n                notoks += 1\n        logging.info(\n            \"Import results: %d ok, %d not ok\",\n            oks,\n            notoks\n        )", "title": ""}
{"_id": "d6744", "text": "def isoformat(dt):\n    \"\"\"Return an ISO-8601 formatted string from the provided datetime object\"\"\"\n    if not isinstance(dt, datetime.datetime):\n        raise TypeError(\"Must provide datetime.datetime object to isoformat\")\n\n    if dt.tzinfo is None:\n        raise ValueError(\"naive datetime objects are not allowed beyond the library boundaries\")\n\n    return dt.isoformat().replace(\"+00:00\", \"Z\")", "title": ""}
{"_id": "d6745", "text": "def empty_line_count_at_the_end(self):\n        \"\"\"\n        Return number of empty lines at the end of the document.\n        \"\"\"\n        count = 0\n        for line in self.lines[::-1]:\n            if not line or line.isspace():\n                count += 1\n            else:\n                break\n\n        return count", "title": ""}
{"_id": "d6746", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d6747", "text": "def _visual_width(line):\n    \"\"\"Get the the number of columns required to display a string\"\"\"\n\n    return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, \"\", line))", "title": ""}
{"_id": "d6748", "text": "def string_format_func(s):\n\t\"\"\"\n\tFunction used internally to format string data for output to XML.\n\tEscapes back-slashes and quotes, and wraps the resulting string in\n\tquotes.\n\t\"\"\"\n\treturn u\"\\\"%s\\\"\" % unicode(s).replace(u\"\\\\\", u\"\\\\\\\\\").replace(u\"\\\"\", u\"\\\\\\\"\")", "title": ""}
{"_id": "d6749", "text": "def count(lines):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  words = [w for l in lines for w in l.strip().split()]\n  return Counter(words)", "title": ""}
{"_id": "d6750", "text": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "title": ""}
{"_id": "d6751", "text": "def min_depth(self, root):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: int\n    \"\"\"\n    if root is None:\n        return 0\n    if root.left is not None or root.right is not None:\n        return max(self.minDepth(root.left), self.minDepth(root.right))+1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1", "title": ""}
{"_id": "d6752", "text": "def _fullname(o):\n    \"\"\"Return the fully-qualified name of a function.\"\"\"\n    return o.__module__ + \".\" + o.__name__ if o.__module__ else o.__name__", "title": ""}
{"_id": "d6753", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d6754", "text": "def method_name(func):\n    \"\"\"Method wrapper that adds the name of the method being called to its arguments list in Pascal case\n\n    \"\"\"\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", "title": ""}
{"_id": "d6755", "text": "def Timestamp(year, month, day, hour, minute, second):\n    \"\"\"Constructs an object holding a datetime/timestamp value.\"\"\"\n    return datetime.datetime(year, month, day, hour, minute, second)", "title": ""}
{"_id": "d6756", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d6757", "text": "def copy(a):\n    \"\"\" Copy an array to the shared memory. \n\n        Notes\n        -----\n        copy is not always necessary because the private memory is always copy-on-write.\n\n        Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory\n    \"\"\"\n    shared = anonymousmemmap(a.shape, dtype=a.dtype)\n    shared[:] = a[:]\n    return shared", "title": ""}
{"_id": "d6758", "text": "def ceil_nearest(x, dx=1):\n    \"\"\"\n    ceil a number to within a given rounding accuracy\n    \"\"\"\n    precision = get_sig_digits(dx)\n    return round(math.ceil(float(x) / dx) * dx, precision)", "title": ""}
{"_id": "d6759", "text": "def get_latex_table(self, parameters=None, transpose=False, caption=None,\n                        label=\"tab:model_params\", hlines=True, blank_fill=\"--\"):  # pragma: no cover\n        \"\"\" Generates a LaTeX table from parameter summaries.\n\n        Parameters\n        ----------\n        parameters : list[str], optional\n            A list of what parameters to include in the table. By default, includes all parameters\n        transpose : bool, optional\n            Defaults to False, which gives each column as a parameter, each chain (framework)\n            as a row. You can swap it so that you have a parameter each row and a framework\n            each column by setting this to True\n        caption : str, optional\n            If you want to generate a caption for the table through Python, use this.\n            Defaults to an empty string\n        label : str, optional\n            If you want to generate a label for the table through Python, use this.\n            Defaults to an empty string\n        hlines : bool, optional\n            Inserts ``\\\\hline`` before and after the header, and at the end of table.\n        blank_fill : str, optional\n            If a framework does not have a particular parameter, will fill that cell of\n            the table with this string.\n\n        Returns\n        -------\n        str\n            the LaTeX table.\n        \"\"\"\n        if parameters is None:\n            parameters = self.parent._all_parameters\n        for p in parameters:\n            assert isinstance(p, str), \\\n                \"Generating a LaTeX table requires all parameters have labels\"\n        num_parameters = len(parameters)\n        num_chains = len(self.parent.chains)\n        fit_values = self.get_summary(squeeze=False)\n        if label is None:\n            label = \"\"\n        if caption is None:\n            caption = \"\"\n\n        end_text = \" \\\\\\\\ \\n\"\n        if transpose:\n            column_text = \"c\" * (num_chains + 1)\n        else:\n            column_text = \"c\" * (num_parameters + 1)\n\n        center_text = \"\"\n        hline_text = \"\\\\hline\\n\"\n        if hlines:\n            center_text += hline_text + \"\\t\\t\"\n        if transpose:\n            center_text += \" & \".join([\"Parameter\"] + [c.name for c in self.parent.chains]) + end_text\n            if hlines:\n                center_text += \"\\t\\t\" + hline_text\n            for p in parameters:\n                arr = [\"\\t\\t\" + p]\n                for chain_res in fit_values:\n                    if p in chain_res:\n                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n                    else:\n                        arr.append(blank_fill)\n                center_text += \" & \".join(arr) + end_text\n        else:\n            center_text += \" & \".join([\"Model\"] + parameters) + end_text\n            if hlines:\n                center_text += \"\\t\\t\" + hline_text\n            for name, chain_res in zip([c.name for c in self.parent.chains], fit_values):\n                arr = [\"\\t\\t\" + name]\n                for p in parameters:\n                    if p in chain_res:\n                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n                    else:\n                        arr.append(blank_fill)\n                center_text += \" & \".join(arr) + end_text\n        if hlines:\n            center_text += \"\\t\\t\" + hline_text\n        final_text = get_latex_table_frame(caption, label) % (column_text, center_text)\n\n        return final_text", "title": ""}
{"_id": "d6760", "text": "def get_closest_index(myList, myNumber):\n    \"\"\"\n    Assumes myList is sorted. Returns closest value to myNumber.\n    If two numbers are equally close, return the smallest number.\n\n    Parameters\n    ----------\n    myList : array\n        The list in which to find the closest value to myNumber\n    myNumber : float\n        The number to find the closest to in MyList\n\n    Returns\n    -------\n    closest_values_index : int\n        The index in the array of the number closest to myNumber in myList\n    \"\"\"\n    closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n    return closest_values_index", "title": ""}
{"_id": "d6761", "text": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d6762", "text": "def get_item_from_queue(Q, timeout=0.01):\n    \"\"\" Attempts to retrieve an item from the queue Q. If Q is\n        empty, None is returned.\n\n        Blocks for 'timeout' seconds in case the queue is empty,\n        so don't use this method for speedy retrieval of multiple\n        items (use get_all_from_queue for that).\n    \"\"\"\n    try:\n        item = Q.get(True, 0.01)\n    except Queue.Empty:\n        return None\n\n    return item", "title": ""}
{"_id": "d6763", "text": "def fileopenbox(msg=None, title=None, argInitialFile=None):\n    \"\"\"Original doc: A dialog to get a file name.\n        Returns the name of a file, or None if user chose to cancel.\n\n        if argInitialFile contains a valid filename, the dialog will\n        be positioned at that file when it appears.\n        \"\"\"\n    return psidialogs.ask_file(message=msg, title=title, default=argInitialFile)", "title": ""}
{"_id": "d6764", "text": "def create_db(app, appbuilder):\n    \"\"\"\n        Create all your database objects (SQLAlchemy specific).\n    \"\"\"\n    from flask_appbuilder.models.sqla import Base\n\n    _appbuilder = import_application(app, appbuilder)\n    engine = _appbuilder.get_session.get_bind(mapper=None, clause=None)\n    Base.metadata.create_all(engine)\n    click.echo(click.style(\"DB objects created\", fg=\"green\"))", "title": ""}
{"_id": "d6765", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d6766", "text": "def intersect(self, other):\n        \"\"\" Return a new :class:`DataFrame` containing rows only in\n        both this frame and another frame.\n\n        This is equivalent to `INTERSECT` in SQL.\n        \"\"\"\n        return DataFrame(self._jdf.intersect(other._jdf), self.sql_ctx)", "title": ""}
{"_id": "d6767", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d6768", "text": "def _to_java_object_rdd(rdd):\n    \"\"\" Return a 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.\n    \"\"\"\n    rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n    return rdd.ctx._jvm.org.apache.spark.mllib.api.python.SerDe.pythonToJava(rdd._jrdd, True)", "title": ""}
{"_id": "d6769", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d6770", "text": "def as_dict(df, ix=':'):\n    \"\"\" converts df to dict and adds a datetime field if df is datetime \"\"\"\n    if isinstance(df.index, pd.DatetimeIndex):\n        df['datetime'] = df.index\n    return df.to_dict(orient='records')[ix]", "title": ""}
{"_id": "d6771", "text": "def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"A quick and dirty way to get a unique string\"\"\"\n    return ''.join(random.choice(chars) for x in xrange(size))", "title": ""}
{"_id": "d6772", "text": "def remove_from_string(string, values):\n    \"\"\"\n\n    Parameters\n    ----------\n    string:\n    values:\n\n    Returns\n    -------\n    \"\"\"\n    for v in values:\n        string = string.replace(v, '')\n\n    return string", "title": ""}
{"_id": "d6773", "text": "def get_function(function_name):\n    \"\"\"\n    Given a Python function name, return the function it refers to.\n    \"\"\"\n    module, basename = str(function_name).rsplit('.', 1)\n    try:\n        return getattr(__import__(module, fromlist=[basename]), basename)\n    except (ImportError, AttributeError):\n        raise FunctionNotFound(function_name)", "title": ""}
{"_id": "d6774", "text": "def add(self, name, desc, func=None, args=None, krgs=None):\n        \"\"\"Add a menu entry.\"\"\"\n        self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))", "title": ""}
{"_id": "d6775", "text": "def dates_in_range(start_date, end_date):\n    \"\"\"Returns all dates between two dates.\n\n    Inclusive of the start date but not the end date.\n\n    Args:\n        start_date (datetime.date)\n        end_date (datetime.date)\n\n    Returns:\n        (list) of datetime.date objects\n    \"\"\"\n    return [\n        start_date + timedelta(n)\n        for n in range(int((end_date - start_date).days))\n    ]", "title": ""}
{"_id": "d6776", "text": "def _xxrange(self, start, end, step_count):\n        \"\"\"Generate n values between start and end.\"\"\"\n        _step = (end - start) / float(step_count)\n        return (start + (i * _step) for i in xrange(int(step_count)))", "title": ""}
{"_id": "d6777", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d6778", "text": "def register_logging_factories(loader):\n    \"\"\"\n    Registers default factories for logging standard package.\n\n    :param loader: Loader where you want register default logging factories\n    \"\"\"\n    loader.register_factory(logging.Logger, LoggerFactory)\n    loader.register_factory(logging.Handler, LoggingHandlerFactory)", "title": ""}
{"_id": "d6779", "text": "def _factor_generator(n):\n    \"\"\"\n    From a given natural integer, returns the prime factors and their multiplicity\n    :param n: Natural integer\n    :return:\n    \"\"\"\n    p = prime_factors(n)\n    factors = {}\n    for p1 in p:\n        try:\n            factors[p1] += 1\n        except KeyError:\n            factors[p1] = 1\n    return factors", "title": ""}
{"_id": "d6780", "text": "def cumsum(inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1, len(newlist)):\n        newlist[i] = newlist[i] + newlist[i - 1]\n    return newlist", "title": ""}
{"_id": "d6781", "text": "def get_column_keys_and_names(table):\n    \"\"\"\n    Return a generator of tuples k, c such that k is the name of the python attribute for\n    the column and c is the name of the column in the sql table.\n    \"\"\"\n    ins = inspect(table)\n    return ((k, c.name) for k, c in ins.mapper.c.items())", "title": ""}
{"_id": "d6782", "text": "def now_time(str=False):\n    \"\"\"Get the current time.\"\"\"\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()", "title": ""}
{"_id": "d6783", "text": "def reraise(error):\n    \"\"\"Re-raises the error that was processed by prepare_for_reraise earlier.\"\"\"\n    if hasattr(error, \"_type_\"):\n        six.reraise(type(error), error, error._traceback)\n    raise error", "title": ""}
{"_id": "d6784", "text": "def bbox(self):\n        \"\"\"\n        The bounding box ``(ymin, xmin, ymax, xmax)`` of the minimal\n        rectangular region containing the source segment.\n        \"\"\"\n\n        # (stop - 1) to return the max pixel location, not the slice index\n        return (self._slice[0].start, self._slice[1].start,\n                self._slice[0].stop - 1, self._slice[1].stop - 1) * u.pix", "title": ""}
{"_id": "d6785", "text": "def QA_util_datetime_to_strdate(dt):\n    \"\"\"\n    :param dt:  pythone datetime.datetime\n    :return:  1999-02-01 string type\n    \"\"\"\n    strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n    return strdate", "title": ""}
{"_id": "d6786", "text": "def vectorize(values):\n    \"\"\"\n    Takes a value or list of values and returns a single result, joined by \",\"\n    if necessary.\n    \"\"\"\n    if isinstance(values, list):\n        return ','.join(str(v) for v in values)\n    return values", "title": ""}
{"_id": "d6787", "text": "def get_dt_list(fn_list):\n    \"\"\"Get list of datetime objects, extracted from a filename\n    \"\"\"\n    dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])\n    return dt_list", "title": ""}
{"_id": "d6788", "text": "def bbox(img):\n    \"\"\"Find the bounding box around nonzero elements in the given array\n\n    Copied from https://stackoverflow.com/a/31402351/5703449 .\n\n    Returns:\n        rowmin, rowmax, colmin, colmax\n    \"\"\"\n    rows = np.any(img, axis=1)\n    cols = np.any(img, axis=0)\n    rmin, rmax = np.where(rows)[0][[0, -1]]\n    cmin, cmax = np.where(cols)[0][[0, -1]]\n\n    return rmin, rmax, cmin, cmax", "title": ""}
{"_id": "d6789", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d6790", "text": "def get_month_start_end_day():\n    \"\"\"\n    Get the month start date a nd end date\n    \"\"\"\n    t = date.today()\n    n = mdays[t.month]\n    return (date(t.year, t.month, 1), date(t.year, t.month, n))", "title": ""}
{"_id": "d6791", "text": "def _matrix3_to_dcm_array(self, m):\n        \"\"\"\n        Converts Matrix3 in an array\n        :param m: Matrix3\n        :returns: 3x3 array\n        \"\"\"\n        assert(isinstance(m, Matrix3))\n        return np.array([[m.a.x, m.a.y, m.a.z],\n                         [m.b.x, m.b.y, m.b.z],\n                         [m.c.x, m.c.y, m.c.z]])", "title": ""}
{"_id": "d6792", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d6793", "text": "def human__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n\n    # build data\n    N = 1000000\n    M = 3\n    X = np.zeros((N,M))\n    X.shape\n    y = np.zeros(N)\n    X[0, 0] = 1\n    y[0] = 8\n    X[1, 1] = 1\n    y[1] = 8\n    X[2, 0:2] = 1\n    y[2] = 4\n\n    # fit model\n    xor_model = sklearn.tree.DecisionTreeRegressor(max_depth=2)\n    xor_model.fit(X, y)\n\n    return xor_model", "title": ""}
{"_id": "d6794", "text": "def get_value(key, obj, default=missing):\n    \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n    if isinstance(key, int):\n        return _get_value_for_key(key, obj, default)\n    return _get_value_for_keys(key.split('.'), obj, default)", "title": ""}
{"_id": "d6795", "text": "def conv_dict(self):\n        \"\"\"dictionary of conversion\"\"\"\n        return dict(integer=self.integer, real=self.real, no_type=self.no_type)", "title": ""}
{"_id": "d6796", "text": "def get_by(self, name):\n    \"\"\"get element by name\"\"\"\n    return next((item for item in self if item.name == name), None)", "title": ""}
{"_id": "d6797", "text": "def join(mapping, bind, values):\n    \"\"\" Merge all the strings. Put space between them. \"\"\"\n    return [' '.join([six.text_type(v) for v in values if v is not None])]", "title": ""}
{"_id": "d6798", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d6799", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d6800", "text": "def base_path(self):\n        \"\"\"Base absolute path of container.\"\"\"\n        return os.path.join(self.container.base_path, self.name)", "title": ""}
{"_id": "d6801", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d6802", "text": "def remove_ext(fname):\n    \"\"\"Removes the extension from a filename\n    \"\"\"\n    bn = os.path.basename(fname)\n    return os.path.splitext(bn)[0]", "title": ""}
{"_id": "d6803", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d6804", "text": "def _remove_duplicate_files(xs):\n    \"\"\"Remove files specified multiple times in a list.\n    \"\"\"\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", "title": ""}
{"_id": "d6805", "text": "def rm(venv_name):\n    \"\"\" Removes the venv by name \"\"\"\n    inenv = InenvManager()\n    venv = inenv.get_venv(venv_name)\n    click.confirm(\"Delete dir {}\".format(venv.path))\n    shutil.rmtree(venv.path)", "title": ""}
{"_id": "d6806", "text": "def monthly(date=datetime.date.today()):\n    \"\"\"\n    Take a date object and return the first day of the month.\n    \"\"\"\n    return datetime.date(date.year, date.month, 1)", "title": ""}
{"_id": "d6807", "text": "def delete(filething):\n    \"\"\"Remove tags from a file.\n\n    Args:\n        filething (filething)\n    Raises:\n        mutagen.MutagenError\n    \"\"\"\n\n    f = FLAC(filething)\n    filething.fileobj.seek(0)\n    f.delete(filething)", "title": ""}
{"_id": "d6808", "text": "def findfirst(f, coll):\n    \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n    result = list(dropwhile(f, coll))\n    return result[0] if result else None", "title": ""}
{"_id": "d6809", "text": "def clear_es():\n        \"\"\"Clear all indexes in the es core\"\"\"\n        # TODO: should receive a catalog slug.\n        ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])\n        LOGGER.debug('Elasticsearch: Index cleared')", "title": ""}
{"_id": "d6810", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d6811", "text": "def counter(items):\n    \"\"\"\n    Simplest required implementation of collections.Counter. Required as 2.6\n    does not have Counter in collections.\n    \"\"\"\n    results = {}\n    for item in items:\n        results[item] = results.get(item, 0) + 1\n    return results", "title": ""}
{"_id": "d6812", "text": "def percentile_index(a, q):\n    \"\"\"\n    Returns the index of the value at the Qth percentile in array a.\n    \"\"\"\n    return np.where(\n        a==np.percentile(a, q, interpolation='nearest')\n    )[0][0]", "title": ""}
{"_id": "d6813", "text": "def pingback_url(self, server_name, target_url):\n        \"\"\"\n        Do a pingback call for the target URL.\n        \"\"\"\n        try:\n            server = ServerProxy(server_name)\n            reply = server.pingback.ping(self.entry_url, target_url)\n        except (Error, socket.error):\n            reply = '%s cannot be pinged.' % target_url\n        return reply", "title": ""}
{"_id": "d6814", "text": "def get_java_path():\n  \"\"\"Get the path of java executable\"\"\"\n  java_home = os.environ.get(\"JAVA_HOME\")\n  return os.path.join(java_home, BIN_DIR, \"java\")", "title": ""}
{"_id": "d6815", "text": "def rotateImage(img, angle):\n    \"\"\"\n\n    querries scipy.ndimage.rotate routine\n    :param img: image to be rotated\n    :param angle: angle to be rotated (radian)\n    :return: rotated image\n    \"\"\"\n    imgR = scipy.ndimage.rotate(img, angle, reshape=False)\n    return imgR", "title": ""}
{"_id": "d6816", "text": "def get_last_commit_line(git_path=None):\n    \"\"\"\n    Get one-line description of HEAD commit for repository in current dir.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    output = check_output([git_path, \"log\", \"--pretty=format:'%ad %h %s'\",\n                           \"--date=short\", \"-n1\"])\n    return output.strip()[1:-1]", "title": ""}
{"_id": "d6817", "text": "def lighting(im, b, c):\n    \"\"\" Adjust image balance and contrast \"\"\"\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)", "title": ""}
{"_id": "d6818", "text": "def last_modified_date(filename):\n    \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n    mtime = os.path.getmtime(filename)\n    dt = datetime.datetime.utcfromtimestamp(mtime)\n    return dt.replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d6819", "text": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "title": ""}
{"_id": "d6820", "text": "def prevmonday(num):\n    \"\"\"\n    Return unix SECOND timestamp of \"num\" mondays ago\n    \"\"\"\n    today = get_today()\n    lastmonday = today - timedelta(days=today.weekday(), weeks=num)\n    return lastmonday", "title": ""}
{"_id": "d6821", "text": "def clean(some_string, uppercase=False):\n    \"\"\"\n    helper to clean up an input string\n    \"\"\"\n    if uppercase:\n        return some_string.strip().upper()\n    else:\n        return some_string.strip().lower()", "title": ""}
{"_id": "d6822", "text": "def display_len(text):\n    \"\"\"\n    Get the display length of a string. This can differ from the character\n    length if the string contains wide characters.\n    \"\"\"\n    text = unicodedata.normalize('NFD', text)\n    return sum(char_width(char) for char in text)", "title": ""}
{"_id": "d6823", "text": "def get_shared_memory_bytes():\n    \"\"\"Get the size of the shared memory file system.\n\n    Returns:\n        The size of the shared memory file system in bytes.\n    \"\"\"\n    # Make sure this is only called on Linux.\n    assert sys.platform == \"linux\" or sys.platform == \"linux2\"\n\n    shm_fd = os.open(\"/dev/shm\", os.O_RDONLY)\n    try:\n        shm_fs_stats = os.fstatvfs(shm_fd)\n        # The value shm_fs_stats.f_bsize is the block size and the\n        # value shm_fs_stats.f_bavail is the number of available\n        # blocks.\n        shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail\n    finally:\n        os.close(shm_fd)\n\n    return shm_avail", "title": ""}
{"_id": "d6824", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d6825", "text": "def _histplot_bins(column, bins=100):\n    \"\"\"Helper to get bins for histplot.\"\"\"\n    col_min = np.min(column)\n    col_max = np.max(column)\n    return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))", "title": ""}
{"_id": "d6826", "text": "def last_modified_date(filename):\n    \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n    mtime = os.path.getmtime(filename)\n    dt = datetime.datetime.utcfromtimestamp(mtime)\n    return dt.replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d6827", "text": "def multidict_to_dict(d):\n    \"\"\"\n    Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with\n    list values\n    :param d: a MultiDict or MultiValueDict instance\n    :return: a dict instance\n    \"\"\"\n    return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))", "title": ""}
{"_id": "d6828", "text": "def _get_gid(name):\n    \"\"\"Returns a gid, given a group name.\"\"\"\n    if getgrnam is None or name is None:\n        return None\n    try:\n        result = getgrnam(name)\n    except KeyError:\n        result = None\n    if result is not None:\n        return result[2]\n    return None", "title": ""}
{"_id": "d6829", "text": "def stdout_display():\n    \"\"\" Print results straight to stdout \"\"\"\n    if sys.version_info[0] == 2:\n        yield SmartBuffer(sys.stdout)\n    else:\n        yield SmartBuffer(sys.stdout.buffer)", "title": ""}
{"_id": "d6830", "text": "def retrieve_by_id(self, id_):\n        \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n        items_with_id = [item for item in self if item.id == int(id_)]\n        if len(items_with_id) == 1:\n            return items_with_id[0].retrieve()", "title": ""}
{"_id": "d6831", "text": "async def delete(self):\n        \"\"\"\n        Delete this message\n\n        :return: bool\n        \"\"\"\n        return await self.bot.delete_message(self.chat.id, self.message_id)", "title": ""}
{"_id": "d6832", "text": "def border(self):\n        \"\"\"Region formed by taking border elements.\n\n        :returns: :class:`jicimagelib.region.Region`\n        \"\"\"\n\n        border_array = self.bitmap - self.inner.bitmap\n        return Region(border_array)", "title": ""}
{"_id": "d6833", "text": "def column_names(self, table):\n      \"\"\"An iterable of column names, for a particular table or\n      view.\"\"\"\n\n      table_info = self.execute(\n        u'PRAGMA table_info(%s)' % quote(table))\n      return (column['name'] for column in table_info)", "title": ""}
{"_id": "d6834", "text": "def stdout_display():\n    \"\"\" Print results straight to stdout \"\"\"\n    if sys.version_info[0] == 2:\n        yield SmartBuffer(sys.stdout)\n    else:\n        yield SmartBuffer(sys.stdout.buffer)", "title": ""}
{"_id": "d6835", "text": "def get_line_ending(line):\n    \"\"\"Return line ending.\"\"\"\n    non_whitespace_index = len(line.rstrip()) - len(line)\n    if not non_whitespace_index:\n        return ''\n    else:\n        return line[non_whitespace_index:]", "title": ""}
{"_id": "d6836", "text": "def Print(x, data, message, **kwargs):  # pylint: disable=invalid-name\n  \"\"\"Call tf.Print.\n\n  Args:\n    x: a Tensor.\n    data: a list of Tensor\n    message: a string\n    **kwargs: keyword arguments to tf.Print\n  Returns:\n    a Tensor which is identical in value to x\n  \"\"\"\n  return PrintOperation(x, data, message, **kwargs).outputs[0]", "title": ""}
{"_id": "d6837", "text": "def getScreenDims(self):\n        \"\"\"returns a tuple that contains (screen_width,screen_height)\n        \"\"\"\n        width = ale_lib.getScreenWidth(self.obj)\n        height = ale_lib.getScreenHeight(self.obj)\n        return (width,height)", "title": ""}
{"_id": "d6838", "text": "def pprint(self, seconds):\n        \"\"\"\n        Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n        :param seconds:  The time in seconds.\n        \"\"\"\n        return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))", "title": ""}
{"_id": "d6839", "text": "def get_keys_from_shelve(file_name, file_location):\n    \"\"\"\n    Function to retreive all keys in a shelve\n    Args:\n        file_name: Shelve storage file name\n        file_location: The location of the file, derive from the os module\n\n    Returns:\n        a list of the keys\n\n    \"\"\"\n    temp_list = list()\n    file = __os.path.join(file_location, file_name)\n    shelve_store = __shelve.open(file)\n    for key in shelve_store:\n        temp_list.append(key)\n    shelve_store.close()\n    return temp_list", "title": ""}
{"_id": "d6840", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d6841", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d6842", "text": "def Output(self):\n    \"\"\"Output all sections of the page.\"\"\"\n    self.Open()\n    self.Header()\n    self.Body()\n    self.Footer()", "title": ""}
{"_id": "d6843", "text": "def qsize(self):\n        \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n        self.mutex.acquire()\n        n = self._qsize()\n        self.mutex.release()\n        return n", "title": ""}
{"_id": "d6844", "text": "def hamming_distance(str1, str2):\n    \"\"\"Calculate the Hamming distance between two bit strings\n\n    Args:\n        str1 (str): First string.\n        str2 (str): Second string.\n    Returns:\n        int: Distance between strings.\n    Raises:\n        VisualizationError: Strings not same length\n    \"\"\"\n    if len(str1) != len(str2):\n        raise VisualizationError('Strings not same length.')\n    return sum(s1 != s2 for s1, s2 in zip(str1, str2))", "title": ""}
{"_id": "d6845", "text": "def max(self):\n        \"\"\"\n        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\n        \"\"\"\n\n        if len(self.regions) != 1:\n            raise ClaripyVSAOperationError(\"'max()' onlly works on single-region value-sets.\")\n\n        return self.get_si(next(iter(self.regions))).max", "title": ""}
{"_id": "d6846", "text": "def group(data, num):\n    \"\"\" Split data into chunks of num chars each \"\"\"\n    return [data[i:i+num] for i in range(0, len(data), num)]", "title": ""}
{"_id": "d6847", "text": "def check_str(obj):\n        \"\"\" Returns a string for various input types \"\"\"\n        if isinstance(obj, str):\n            return obj\n        if isinstance(obj, float):\n            return str(int(obj))\n        else:\n            return str(obj)", "title": ""}
{"_id": "d6848", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d6849", "text": "def int2str(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from integers to strings\"\"\"\n    return NumConv(radix, alphabet).int2str(num)", "title": ""}
{"_id": "d6850", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d6851", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d6852", "text": "def rollback(name, database=None, directory=None, verbose=None):\n    \"\"\"Rollback a migration with given name.\"\"\"\n    router = get_router(directory, database, verbose)\n    router.rollback(name)", "title": ""}
{"_id": "d6853", "text": "def get_page_text(self, page):\n        \"\"\"\n        Downloads and returns the full text of a particular page\n        in the document.\n        \"\"\"\n        url = self.get_page_text_url(page)\n        return self._get_url(url)", "title": ""}
{"_id": "d6854", "text": "def get_python():\n    \"\"\"Determine the path to the virtualenv 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", "title": ""}
{"_id": "d6855", "text": "def _get_closest_week(self, metric_date):\n        \"\"\"\n        Gets the closest monday to the date provided.\n        \"\"\"\n        #find the offset to the closest monday\n        days_after_monday = metric_date.isoweekday() - 1\n\n        return metric_date - datetime.timedelta(days=days_after_monday)", "title": ""}
{"_id": "d6856", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d6857", "text": "def server(port):\n    \"\"\"Start the Django dev server.\"\"\"\n    args = ['python', 'manage.py', 'runserver']\n    if port:\n        args.append(port)\n    run.main(args)", "title": ""}
{"_id": "d6858", "text": "def get_grid_spatial_dimensions(self, variable):\n        \"\"\"Returns (width, height) for the given variable\"\"\"\n\n        data = self.open_dataset(self.service).variables[variable.variable]\n        dimensions = list(data.dimensions)\n        return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.index(variable.y_dimension)]", "title": ""}
{"_id": "d6859", "text": "def _force_float(v):\n    \"\"\" 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.\n\n    \"\"\"\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))", "title": ""}
{"_id": "d6860", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d6861", "text": "def min_or_none(val1, val2):\n    \"\"\"Returns min(val1, val2) returning None only if both values are None\"\"\"\n    return min(val1, val2, key=lambda x: sys.maxint if x is None else x)", "title": ""}
{"_id": "d6862", "text": "def end_index(self):\n        \"\"\"\n        Returns the 1-based index of the last object on this page,\n        relative to total objects found (hits).\n        \"\"\"\n        return ((self.number - 1) * self.paginator.per_page +\n            len(self.object_list))", "title": ""}
{"_id": "d6863", "text": "def end_of_history(event):\n    \"\"\"\n    Move to the end of the input history, i.e., the line currently being entered.\n    \"\"\"\n    event.current_buffer.history_forward(count=10**100)\n    buff = event.current_buffer\n    buff.go_to_history(len(buff._working_lines) - 1)", "title": ""}
{"_id": "d6864", "text": "def objectproxy_realaddress(obj):\n    \"\"\"\n    Obtain a real address as an integer from an objectproxy.\n    \"\"\"\n    voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)\n    return C.addressof(C.c_char.from_buffer(voidp))", "title": ""}
{"_id": "d6865", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d6866", "text": "def size(dtype):\n  \"\"\"Returns the number of bytes to represent this `dtype`.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'size'):\n    return dtype.size\n  return np.dtype(dtype).itemsize", "title": ""}
{"_id": "d6867", "text": "def dot_v2(vec1, vec2):\n    \"\"\"Return the dot product of two vectors\"\"\"\n\n    return vec1.x * vec2.x + vec1.y * vec2.y", "title": ""}
{"_id": "d6868", "text": "def get_shared_memory_bytes():\n    \"\"\"Get the size of the shared memory file system.\n\n    Returns:\n        The size of the shared memory file system in bytes.\n    \"\"\"\n    # Make sure this is only called on Linux.\n    assert sys.platform == \"linux\" or sys.platform == \"linux2\"\n\n    shm_fd = os.open(\"/dev/shm\", os.O_RDONLY)\n    try:\n        shm_fs_stats = os.fstatvfs(shm_fd)\n        # The value shm_fs_stats.f_bsize is the block size and the\n        # value shm_fs_stats.f_bavail is the number of available\n        # blocks.\n        shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail\n    finally:\n        os.close(shm_fd)\n\n    return shm_avail", "title": ""}
{"_id": "d6869", "text": "def dot_v3(v, w):\n    \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n    return sum([x * y for x, y in zip(v, w)])", "title": ""}
{"_id": "d6870", "text": "def get_page_text(self, page):\n        \"\"\"\n        Downloads and returns the full text of a particular page\n        in the document.\n        \"\"\"\n        url = self.get_page_text_url(page)\n        return self._get_url(url)", "title": ""}
{"_id": "d6871", "text": "def drop_all_tables(self):\n        \"\"\"Drop all tables in the database\"\"\"\n        for table_name in self.table_names():\n            self.execute_sql(\"DROP TABLE %s\" % table_name)\n        self.connection.commit()", "title": ""}
{"_id": "d6872", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d6873", "text": "def check_str(obj):\n        \"\"\" Returns a string for various input types \"\"\"\n        if isinstance(obj, str):\n            return obj\n        if isinstance(obj, float):\n            return str(int(obj))\n        else:\n            return str(obj)", "title": ""}
{"_id": "d6874", "text": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n    \"\"\"Clean a pandas dataframe by:\n        1. Filling empty values with Nan\n        2. Dropping columns with all empty values\n\n    Args:\n        df: Pandas DataFrame\n        fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n        drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n    Returns:\n        DataFrame: cleaned DataFrame\n\n    \"\"\"\n    if fill_nan:\n        df = df.fillna(value=np.nan)\n    if drop_empty_columns:\n        df = df.dropna(axis=1, how='all')\n    return df.sort_index()", "title": ""}
{"_id": "d6875", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d6876", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d6877", "text": "def get_nt_system_uid():\n    \"\"\"Get the MachineGuid from\n    HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Cryptography\\MachineGuid\n    \"\"\"\n    try:\n        import _winreg as winreg\n    except ImportError:\n        import winreg\n    lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\n    try:\n        key = winreg.OpenKey(lm, r\"Software\\Microsoft\\Cryptography\")\n        try:\n            return winreg.QueryValueEx(key, \"MachineGuid\")[0]\n        finally:\n            key.Close()\n    finally:\n        lm.Close()", "title": ""}
{"_id": "d6878", "text": "def batch_get_item(self, batch_list):\n        \"\"\"\n        Return a set of attributes for a multiple items in\n        multiple tables using their primary keys.\n\n        :type batch_list: :class:`boto.dynamodb.batch.BatchList`\n        :param batch_list: A BatchList object which consists of a\n            list of :class:`boto.dynamoddb.batch.Batch` objects.\n            Each Batch object contains the information about one\n            batch of objects that you wish to retrieve in this\n            request.\n        \"\"\"\n        request_items = self.dynamize_request_items(batch_list)\n        return self.layer1.batch_get_item(request_items,\n                                          object_hook=item_object_hook)", "title": ""}
{"_id": "d6879", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d6880", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d6881", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d6882", "text": "def validate_email(email):\n    \"\"\"\n    Validates an email address\n    Source: Himanshu Shankar (https://github.com/iamhssingh)\n    Parameters\n    ----------\n    email: str\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    from django.core.validators import validate_email\n    from django.core.exceptions import ValidationError\n    try:\n        validate_email(email)\n        return True\n    except ValidationError:\n        return False", "title": ""}
{"_id": "d6883", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d6884", "text": "def _bytes_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, bytes):\n        value = base64.standard_b64encode(value).decode(\"ascii\")\n    return value", "title": ""}
{"_id": "d6885", "text": "def printheader(h=None):\n    \"\"\"Print the header for the CSV table.\"\"\"\n    writer = csv.writer(sys.stdout)\n    writer.writerow(header_fields(h))", "title": ""}
{"_id": "d6886", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d6887", "text": "def go_to_parent_directory(self):\n        \"\"\"Go to parent directory\"\"\"\n        self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))", "title": ""}
{"_id": "d6888", "text": "def page_guiref(arg_s=None):\n    \"\"\"Show a basic reference about the GUI Console.\"\"\"\n    from IPython.core import page\n    page.page(gui_reference, auto_html=True)", "title": ""}
{"_id": "d6889", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d6890", "text": "def reraise(error):\n    \"\"\"Re-raises the error that was processed by prepare_for_reraise earlier.\"\"\"\n    if hasattr(error, \"_type_\"):\n        six.reraise(type(error), error, error._traceback)\n    raise error", "title": ""}
{"_id": "d6891", "text": "def _check_graphviz_available(output_format):\n    \"\"\"check if we need graphviz for different output format\"\"\"\n    try:\n        subprocess.call([\"dot\", \"-V\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    except OSError:\n        print(\n            \"The output format '%s' is currently not available.\\n\"\n            \"Please install 'Graphviz' to have other output formats \"\n            \"than 'dot' or 'vcg'.\" % output_format\n        )\n        sys.exit(32)", "title": ""}
{"_id": "d6892", "text": "def _escape(s):\n    \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n    e = s\n    e = e.replace('\\\\', '\\\\\\\\')\n    e = e.replace('\\n', '\\\\n')\n    e = e.replace('\\r', '\\\\r')\n    e = e.replace(\"'\", \"\\\\'\")\n    e = e.replace('\"', '\\\\\"')\n    return e", "title": ""}
{"_id": "d6893", "text": "def normalize_job_id(job_id):\n\t\"\"\"\n\tConvert 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`\n\t\"\"\"\n\tif not isinstance(job_id, uuid.UUID):\n\t\tjob_id = uuid.UUID(job_id)\n\treturn job_id", "title": ""}
{"_id": "d6894", "text": "def _escape(s):\n    \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n    e = s\n    e = e.replace('\\\\', '\\\\\\\\')\n    e = e.replace('\\n', '\\\\n')\n    e = e.replace('\\r', '\\\\r')\n    e = e.replace(\"'\", \"\\\\'\")\n    e = e.replace('\"', '\\\\\"')\n    return e", "title": ""}
{"_id": "d6895", "text": "def ungzip_data(input_data):\n    \"\"\"Return a string of data after gzip decoding\n\n    :param the input gziped data\n    :return  the gzip decoded data\"\"\"\n    buf = StringIO(input_data)\n    f = gzip.GzipFile(fileobj=buf)\n    return f", "title": ""}
{"_id": "d6896", "text": "def euclidean(x, y):\n    \"\"\"Standard euclidean distance.\n\n    ..math::\n        D(x, y) = \\sqrt{\\sum_i (x_i - y_i)^2}\n    \"\"\"\n    result = 0.0\n    for i in range(x.shape[0]):\n        result += (x[i] - y[i]) ** 2\n    return np.sqrt(result)", "title": ""}
{"_id": "d6897", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d6898", "text": "def hclust_linearize(U):\n    \"\"\"Sorts the rows of a matrix by hierarchical clustering.\n\n    Parameters:\n        U (ndarray) : matrix of data\n\n    Returns:\n        prm (ndarray) : permutation of the rows\n    \"\"\"\n\n    from scipy.cluster import hierarchy\n    Z = hierarchy.ward(U)\n    return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))", "title": ""}
{"_id": "d6899", "text": "def _removeStopwords(text_list):\n    \"\"\"\n    Removes stopwords contained in a list of words.\n\n    :param text_string: A list of strings.\n    :type text_string: list.\n\n    :returns: The input ``text_list`` with stopwords removed.\n    :rtype: list\n    \"\"\"\n\n    output_list = []\n\n    for word in text_list:\n        if word.lower() not in _stopwords:\n            output_list.append(word)\n\n    return output_list", "title": ""}
{"_id": "d6900", "text": "def str2bytes(x):\n  \"\"\"Convert input argument to bytes\"\"\"\n  if type(x) is bytes:\n    return x\n  elif type(x) is str:\n    return bytes([ ord(i) for i in x ])\n  else:\n    return str2bytes(str(x))", "title": ""}
{"_id": "d6901", "text": "def main(argv=sys.argv, stream=sys.stderr):\n    \"\"\"Entry point for ``tappy`` command.\"\"\"\n    args = parse_args(argv)\n    suite = build_suite(args)\n    runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)\n    result = runner.run(suite)\n\n    return get_status(result)", "title": ""}
{"_id": "d6902", "text": "def activate(self):\n        \"\"\"Store ipython references in the __builtin__ namespace.\"\"\"\n\n        add_builtin = self.add_builtin\n        for name, func in self.auto_builtins.iteritems():\n            add_builtin(name, func)", "title": ""}
{"_id": "d6903", "text": "def _loop_timeout_cb(self, main_loop):\n        \"\"\"Stops the loop after the time specified in the `loop` call.\n        \"\"\"\n        self._anything_done = True\n        logger.debug(\"_loop_timeout_cb() called\")\n        main_loop.quit()", "title": ""}
{"_id": "d6904", "text": "def save_config_value(request, response, key, value):\n    \"\"\"Sets value of key `key` to `value` in both session and cookies.\"\"\"\n    request.session[key] = value\n    response.set_cookie(key, value, expires=one_year_from_now())\n    return response", "title": ""}
{"_id": "d6905", "text": "def call_and_exit(self, cmd, shell=True):\n        \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n        sys.exit(subprocess.call(cmd, shell=shell))", "title": ""}
{"_id": "d6906", "text": "def sets_are_rooted_compat(one_set, other):\n    \"\"\"treats the 2 sets are sets of taxon IDs on the same (unstated)\n    universe of taxon ids.\n    Returns True clades implied by each are compatible and False otherwise\n    \"\"\"\n    if one_set.issubset(other) or other.issubset(one_set):\n        return True\n    return not intersection_not_empty(one_set, other)", "title": ""}
{"_id": "d6907", "text": "def ip_address_list(ips):\n    \"\"\" IP address range validation and expansion. \"\"\"\n    # first, try it as a single IP address\n    try:\n        return ip_address(ips)\n    except ValueError:\n        pass\n    # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it\n    return list(ipaddress.ip_network(u(ips)).hosts())", "title": ""}
{"_id": "d6908", "text": "def lint(args):\n    \"\"\"Run lint checks using flake8.\"\"\"\n    application = get_current_application()\n    if not args:\n        args = [application.name, 'tests']\n    args = ['flake8'] + list(args)\n    run.main(args, standalone_mode=False)", "title": ""}
{"_id": "d6909", "text": "def skip_connection_distance(a, b):\n    \"\"\"The distance between two skip-connections.\"\"\"\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))", "title": ""}
{"_id": "d6910", "text": "def get_numbers(s):\n    \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n    result = map(int, re.findall(r'[0-9]+', unicode(s)))\n    return result + [1] * (2 - len(result))", "title": ""}
{"_id": "d6911", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d6912", "text": "def search_for_tweets_about(user_id, params):\n    \"\"\" Search twitter API \"\"\"\n    url = \"https://api.twitter.com/1.1/search/tweets.json\"\n    response = make_twitter_request(url, user_id, params)\n    return process_tweets(response.json()[\"statuses\"])", "title": ""}
{"_id": "d6913", "text": "def fmt_subst(regex, subst):\n    \"\"\"Replace regex with string.\"\"\"\n    return lambda text: re.sub(regex, subst, text) if text else text", "title": ""}
{"_id": "d6914", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d6915", "text": "def contains_empty(features):\n    \"\"\"Check features data are not empty\n\n    :param features: The features data to check.\n    :type features: list of numpy arrays.\n\n    :return: True if one of the array is empty, False else.\n\n    \"\"\"\n    if not features:\n        return True\n    for feature in features:\n        if feature.shape[0] == 0:\n            return True\n    return False", "title": ""}
{"_id": "d6916", "text": "def to_dict(dictish):\n    \"\"\"\n    Given something that closely resembles a dictionary, we attempt\n    to coerce it into a propery dictionary.\n    \"\"\"\n    if hasattr(dictish, 'iterkeys'):\n        m = dictish.iterkeys\n    elif hasattr(dictish, 'keys'):\n        m = dictish.keys\n    else:\n        raise ValueError(dictish)\n\n    return dict((k, dictish[k]) for k in m())", "title": ""}
{"_id": "d6917", "text": "def chunked_list(_list, _chunk_size=50):\n    \"\"\"\n    Break lists into small lists for processing:w\n    \"\"\"\n    for i in range(0, len(_list), _chunk_size):\n        yield _list[i:i + _chunk_size]", "title": ""}
{"_id": "d6918", "text": "def is_running(self):\n        \"\"\"Returns a bool determining if the process is in a running state or\n        not\n\n        :rtype: bool\n\n        \"\"\"\n        return self.state in [self.STATE_IDLE, self.STATE_ACTIVE,\n                              self.STATE_SLEEPING]", "title": ""}
{"_id": "d6919", "text": "def is_punctuation(text):\n    \"\"\"Check if given string is a punctuation\"\"\"\n    return not (text.lower() in config.AVRO_VOWELS or\n                text.lower() in config.AVRO_CONSONANTS)", "title": ""}
{"_id": "d6920", "text": "def run(self, value):\n        \"\"\" Determines if value value is empty.\n        Keyword arguments:\n        value str -- the value of the associated field to compare\n        \"\"\"\n        if self.pass_ and not value.strip():\n            return True\n\n        if not value:\n            return False\n        return True", "title": ""}
{"_id": "d6921", "text": "def time_func(func, name, *args, **kwargs):\n    \"\"\" call a func with args and kwargs, print name of func and how\n    long it took. \"\"\"\n    tic = time.time()\n    out = func(*args, **kwargs)\n    toc = time.time()\n    print('%s took %0.2f seconds' % (name, toc - tic))\n    return out", "title": ""}
{"_id": "d6922", "text": "def struct2dict(struct):\n    \"\"\"convert a ctypes structure to a dictionary\"\"\"\n    return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}", "title": ""}
{"_id": "d6923", "text": "def commajoin_as_strings(iterable):\n    \"\"\" Join the given iterable with ',' \"\"\"\n    return _(u',').join((six.text_type(i) for i in iterable))", "title": ""}
{"_id": "d6924", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d6925", "text": "def filter_set(input, **params):\n    \"\"\"\n    Apply WHERE filter to input dataset\n    :param input:\n    :param params:\n    :return: filtered data\n    \"\"\"\n    PARAM_WHERE = 'where'\n\n    return Converter.df2list(pd.DataFrame.from_records(input).query(params.get(PARAM_WHERE)))", "title": ""}
{"_id": "d6926", "text": "def del_Unnamed(df):\n    \"\"\"\n    Deletes all the unnamed columns\n\n    :param df: pandas dataframe\n    \"\"\"\n    cols_del=[c for c in df.columns if 'Unnamed' in c]\n    return df.drop(cols_del,axis=1)", "title": ""}
{"_id": "d6927", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d6928", "text": "def _py_ex_argtype(executable):\n    \"\"\"Returns the code to create the argtype to assign to the methods argtypes\n    attribute.\n    \"\"\"\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\n    if type(executable).__name__ == \"Function\":\n        result.extend(executable.argtypes)        \n            \n    return result", "title": ""}
{"_id": "d6929", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d6930", "text": "def properties(self):\n        \"\"\"All compartment properties as a dict.\"\"\"\n        properties = {'id': self._id}\n        if self._name is not None:\n            properties['name'] = self._name\n\n        return properties", "title": ""}
{"_id": "d6931", "text": "def unique_list(lst):\n    \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n    uniq = []\n    for item in lst:\n        if item not in uniq:\n            uniq.append(item)\n    return uniq", "title": ""}
{"_id": "d6932", "text": "def indexTupleFromItem(self, treeItem): # TODO: move to BaseTreeItem?\n        \"\"\" Return (first column model index, last column model index) tuple for a configTreeItem\n        \"\"\"\n        if not treeItem:\n            return (QtCore.QModelIndex(), QtCore.QModelIndex())\n\n        if not treeItem.parentItem: # TODO: only necessary because of childNumber?\n            return (QtCore.QModelIndex(), QtCore.QModelIndex())\n\n        # Is there a bug in Qt in QStandardItemModel::indexFromItem?\n        # It passes the parent in createIndex. TODO: investigate\n\n        row =  treeItem.childNumber()\n        return (self.createIndex(row, 0, treeItem),\n                self.createIndex(row, self.columnCount() - 1, treeItem))", "title": ""}
{"_id": "d6933", "text": "def locate(command, on):\n    \"\"\"Locate the command's man page.\"\"\"\n    location = find_page_location(command, on)\n    click.echo(location)", "title": ""}
{"_id": "d6934", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d6935", "text": "def find_geom(geom, geoms):\n    \"\"\"\n    Returns the index of a geometry in a list of geometries avoiding\n    expensive equality checks of `in` operator.\n    \"\"\"\n    for i, g in enumerate(geoms):\n        if g is geom:\n            return i", "title": ""}
{"_id": "d6936", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d6937", "text": "def calc_list_average(l):\n    \"\"\"\n    Calculates the average value of a list of numbers\n    Returns a float\n    \"\"\"\n    total = 0.0\n    for value in l:\n        total += value\n    return total / len(l)", "title": ""}
{"_id": "d6938", "text": "def growthfromrange(rangegrowth, startdate, enddate):\n    \"\"\"\n    Annual growth given growth from start date to end date.\n    \"\"\"\n    _yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\\\n            dt.timedelta(365.25).total_seconds()\n    return yrlygrowth(rangegrowth, _yrs)", "title": ""}
{"_id": "d6939", "text": "def find_centroid(region):\n    \"\"\"\n    Finds an approximate centroid for a region that is within the region.\n    \n    Parameters\n    ----------\n    region : np.ndarray(shape=(m, n), dtype='bool')\n        mask of the region.\n\n    Returns\n    -------\n    i, j : tuple(int, int)\n        2d index within the region nearest the center of mass.\n    \"\"\"\n\n    x, y = center_of_mass(region)\n    w = np.argwhere(region)\n    i, j = w[np.argmin(np.linalg.norm(w - (x, y), axis=1))]\n    return i, j", "title": ""}
{"_id": "d6940", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d6941", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d6942", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d6943", "text": "def copy(obj):\n    def copy(self):\n        \"\"\"\n        Copy self to a new object.\n        \"\"\"\n        from copy import deepcopy\n\n        return deepcopy(self)\n    obj.copy = copy\n    return obj", "title": ""}
{"_id": "d6944", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d6945", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d6946", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d6947", "text": "def add_to_toolbar(self, toolbar, widget):\n        \"\"\"Add widget actions to toolbar\"\"\"\n        actions = widget.toolbar_actions\n        if actions is not None:\n            add_actions(toolbar, actions)", "title": ""}
{"_id": "d6948", "text": "def distL1(x1,y1,x2,y2):\n    \"\"\"Compute the L1-norm (Manhattan) distance between two points.\n\n    The distance is rounded to the closest integer, for compatibility\n    with the TSPLIB convention.\n\n    The two points are located on coordinates (x1,y1) and (x2,y2),\n    sent as parameters\"\"\"\n    return int(abs(x2-x1) + abs(y2-y1)+.5)", "title": ""}
{"_id": "d6949", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d6950", "text": "def find(self, node, path):\n        \"\"\"Wrapper for lxml`s find.\"\"\"\n\n        return node.find(path, namespaces=self.namespaces)", "title": ""}
{"_id": "d6951", "text": "def deprecated(operation=None):\n    \"\"\"\n    Mark an operation deprecated.\n    \"\"\"\n    def inner(o):\n        o.deprecated = True\n        return o\n    return inner(operation) if operation else inner", "title": ""}
{"_id": "d6952", "text": "def _getTypename(self, defn):\n        \"\"\" Returns the SQL typename required to store the given FieldDefinition \"\"\"\n        return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'", "title": ""}
{"_id": "d6953", "text": "def es_field_sort(fld_name):\n    \"\"\" Used with lambda to sort fields \"\"\"\n    parts = fld_name.split(\".\")\n    if \"_\" not in parts[-1]:\n        parts[-1] = \"_\" + parts[-1]\n    return \".\".join(parts)", "title": ""}
{"_id": "d6954", "text": "def purge_duplicates(list_in):\n    \"\"\"Remove duplicates from list while preserving order.\n\n    Parameters\n    ----------\n    list_in: Iterable\n\n    Returns\n    -------\n    list\n        List of first occurences in order\n    \"\"\"\n    _list = []\n    for item in list_in:\n        if item not in _list:\n            _list.append(item)\n    return _list", "title": ""}
{"_id": "d6955", "text": "def _make_proxy_property(bind_attr, attr_name):\n    def proxy_property(self):\n        \"\"\"\n        proxy\n        \"\"\"\n        bind = getattr(self, bind_attr)\n        return getattr(bind, attr_name)\n    return property(proxy_property)", "title": ""}
{"_id": "d6956", "text": "def find_ge(a, x):\n    \"\"\"Find leftmost item greater than or equal to x.\"\"\"\n    i = bs.bisect_left(a, x)\n    if i != len(a): return i\n    raise ValueError", "title": ""}
{"_id": "d6957", "text": "def get_public_members(obj):\n    \"\"\"\n    Retrieves a list of member-like objects (members or properties) that are\n    publically exposed.\n\n    :param obj: The object to probe.\n    :return:    A list of strings.\n    \"\"\"\n    return {attr: getattr(obj, attr) for attr in dir(obj)\n            if not attr.startswith(\"_\")\n            and not hasattr(getattr(obj, attr), '__call__')}", "title": ""}
{"_id": "d6958", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d6959", "text": "def py(self, output):\n        \"\"\"Output data as a nicely-formatted python data structure\"\"\"\n        import pprint\n        pprint.pprint(output, stream=self.outfile)", "title": ""}
{"_id": "d6960", "text": "def _shutdown_transport(self):\n        \"\"\"Unwrap a Python 2.6 SSL socket, so we can call shutdown()\"\"\"\n        if self.sock is not None:\n            try:\n                unwrap = self.sock.unwrap\n            except AttributeError:\n                return\n            try:\n                self.sock = unwrap()\n            except ValueError:\n                # Failure within SSL might mean unwrap exists but socket is not\n                # deemed wrapped\n                pass", "title": ""}
{"_id": "d6961", "text": "def slugify(string):\n    \"\"\"\n    Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n    \"\"\"\n    string = re.sub('[^\\w .-]', '', string)\n    string = string.replace(\" \", \"-\")\n    return string", "title": ""}
{"_id": "d6962", "text": "def get_trace_id_from_flask():\n    \"\"\"Get trace_id from flask request headers.\n\n    :rtype: str\n    :returns: TraceID in HTTP request headers.\n    \"\"\"\n    if flask is None or not flask.request:\n        return None\n\n    header = flask.request.headers.get(_FLASK_TRACE_HEADER)\n\n    if header is None:\n        return None\n\n    trace_id = header.split(\"/\", 1)[0]\n\n    return trace_id", "title": ""}
{"_id": "d6963", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d6964", "text": "def uint32_to_uint8(cls, img):\n        \"\"\"\n        Cast uint32 RGB image to 4 uint8 channels.\n        \"\"\"\n        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))", "title": ""}
{"_id": "d6965", "text": "def getBuffer(x):\n    \"\"\"\n    Copy @x into a (modifiable) ctypes byte array\n    \"\"\"\n    b = bytes(x)\n    return (c_ubyte * len(b)).from_buffer_copy(bytes(x))", "title": ""}
{"_id": "d6966", "text": "def OnMove(self, event):\n        \"\"\"Main window move event\"\"\"\n\n        # Store window position in config\n        position = self.main_window.GetScreenPositionTuple()\n\n        config[\"window_position\"] = repr(position)", "title": ""}
{"_id": "d6967", "text": "def _stdout_raw(self, s):\n        \"\"\"Writes the string to stdout\"\"\"\n        print(s, end='', file=sys.stdout)\n        sys.stdout.flush()", "title": ""}
{"_id": "d6968", "text": "def fixed(ctx, number, decimals=2, no_commas=False):\n    \"\"\"\n    Formats the given number in decimal format using a period and commas\n    \"\"\"\n    value = _round(ctx, number, decimals)\n    format_str = '{:f}' if no_commas else '{:,f}'\n    return format_str.format(value)", "title": ""}
{"_id": "d6969", "text": "def list_backends(_):\n    \"\"\"List all available backends.\"\"\"\n    backends = [b.__name__ for b in available_backends()]\n    print('\\n'.join(backends))", "title": ""}
{"_id": "d6970", "text": "def fourier_series(x, f, n=0):\n    \"\"\"\n    Returns a symbolic fourier series of order `n`.\n\n    :param n: Order of the fourier series.\n    :param x: Independent variable\n    :param f: Frequency of the fourier series\n    \"\"\"\n    # Make the parameter objects for all the terms\n    a0, *cos_a = parameters(','.join(['a{}'.format(i) for i in range(0, n + 1)]))\n    sin_b = parameters(','.join(['b{}'.format(i) for i in range(1, n + 1)]))\n    # Construct the series\n    series = a0 + sum(ai * cos(i * f * x) + bi * sin(i * f * x)\n                     for i, (ai, bi) in enumerate(zip(cos_a, sin_b), start=1))\n    return series", "title": ""}
{"_id": "d6971", "text": "def dict_from_object(obj: object):\n    \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n    # If object is a dict instance, no need to convert.\n    return (obj if isinstance(obj, dict)\n            else {attr: getattr(obj, attr)\n                  for attr in dir(obj) if not attr.startswith('_')})", "title": ""}
{"_id": "d6972", "text": "def _convert_latitude(self, latitude):\n        \"\"\"Convert from latitude to the y position in overall map.\"\"\"\n        return int((180 - (180 / pi * log(tan(\n            pi / 4 + latitude * pi / 360)))) * (2 ** self._zoom) * self._size / 360)", "title": ""}
{"_id": "d6973", "text": "def get_java_path():\n  \"\"\"Get the path of java executable\"\"\"\n  java_home = os.environ.get(\"JAVA_HOME\")\n  return os.path.join(java_home, BIN_DIR, \"java\")", "title": ""}
{"_id": "d6974", "text": "def frombits(cls, bits):\n        \"\"\"Series from binary string arguments.\"\"\"\n        return cls.frombitsets(map(cls.BitSet.frombits, bits))", "title": ""}
{"_id": "d6975", "text": "def set_logxticks_for_all(self, row_column_list=None, logticks=None):\n        \"\"\"Manually specify the x-axis log tick values.\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\n        :param logticks: logarithm of the locations for the ticks along the\n            axis.\n\n        For example, if you specify [1, 2, 3], ticks will be placed at 10,\n        100 and 1000.\n\n        \"\"\"\n        if row_column_list is None:\n            self.ticks['x'] = ['1e%d' % u for u in logticks]\n        else:\n            for row, column in row_column_list:\n                self.set_logxticks(row, column, logticks)", "title": ""}
{"_id": "d6976", "text": "def remove_rows_matching(df, column, match):\n    \"\"\"\n    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\n    \"\"\"\n    df = df.copy()\n    mask = df[column].values != match\n    return df.iloc[mask, :]", "title": ""}
{"_id": "d6977", "text": "def get_kind(self, value):\n        \"\"\"Return the kind (type) of the attribute\"\"\"\n        if isinstance(value, float):\n            return 'f'\n        elif isinstance(value, int):\n            return 'i'\n        else:\n            raise ValueError(\"Only integer or floating point values can be stored.\")", "title": ""}
{"_id": "d6978", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d6979", "text": "def allsame(list_, strict=True):\n    \"\"\"\n    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\n    \"\"\"\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)", "title": ""}
{"_id": "d6980", "text": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "title": ""}
{"_id": "d6981", "text": "def get_public_members(obj):\n    \"\"\"\n    Retrieves a list of member-like objects (members or properties) that are\n    publically exposed.\n\n    :param obj: The object to probe.\n    :return:    A list of strings.\n    \"\"\"\n    return {attr: getattr(obj, attr) for attr in dir(obj)\n            if not attr.startswith(\"_\")\n            and not hasattr(getattr(obj, attr), '__call__')}", "title": ""}
{"_id": "d6982", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d6983", "text": "def path_to_list(pathstr):\n    \"\"\"Conver a path string to a list of path elements.\"\"\"\n    return [elem for elem in pathstr.split(os.path.pathsep) if elem]", "title": ""}
{"_id": "d6984", "text": "def exit_if_missing_graphviz(self):\n        \"\"\"\n        Detect the presence of the dot utility to make a png graph.\n        \"\"\"\n        (out, err) = utils.capture_shell(\"which dot\")\n\n        if \"dot\" not in out:\n            ui.error(c.MESSAGES[\"dot_missing\"])", "title": ""}
{"_id": "d6985", "text": "def __grid_widgets(self):\n        \"\"\"Places all the child widgets in the appropriate positions.\"\"\"\n        scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n        self._canvas.grid(row=0, column=1, sticky=\"nswe\")\n        self._scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")", "title": ""}
{"_id": "d6986", "text": "def _uniqueid(n=30):\n    \"\"\"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\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(\n                   string.ascii_uppercase + string.ascii_lowercase)\n                   for _ in range(n))", "title": ""}
{"_id": "d6987", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d6988", "text": "def to_dotfile(self):\n        \"\"\" Writes a DOT graphviz file of the domain structure, and returns the filename\"\"\"\n        domain = self.get_domain()\n        filename = \"%s.dot\" % (self.__class__.__name__)\n        nx.write_dot(domain, filename)\n        return filename", "title": ""}
{"_id": "d6989", "text": "def write_line(self, line, count=1):\n        \"\"\"writes the line and count newlines after the line\"\"\"\n        self.write(line)\n        self.write_newlines(count)", "title": ""}
{"_id": "d6990", "text": "def _gaps_from(intervals):\n    \"\"\"\n    From a list of intervals extract\n    a list of sorted gaps in the form of [(g,i)]\n    where g is the size of the ith gap.\n    \"\"\"\n    sliding_window = zip(intervals, intervals[1:])\n    gaps = [b[0] - a[1] for a, b in sliding_window]\n    return gaps", "title": ""}
{"_id": "d6991", "text": "def _write_json(file, contents):\n    \"\"\"Write a dict to a JSON file.\"\"\"\n    with open(file, 'w') as f:\n        return json.dump(contents, f, indent=2, sort_keys=True)", "title": ""}
{"_id": "d6992", "text": "def get_latex_table(self, parameters=None, transpose=False, caption=None,\n                        label=\"tab:model_params\", hlines=True, blank_fill=\"--\"):  # pragma: no cover\n        \"\"\" Generates a LaTeX table from parameter summaries.\n\n        Parameters\n        ----------\n        parameters : list[str], optional\n            A list of what parameters to include in the table. By default, includes all parameters\n        transpose : bool, optional\n            Defaults to False, which gives each column as a parameter, each chain (framework)\n            as a row. You can swap it so that you have a parameter each row and a framework\n            each column by setting this to True\n        caption : str, optional\n            If you want to generate a caption for the table through Python, use this.\n            Defaults to an empty string\n        label : str, optional\n            If you want to generate a label for the table through Python, use this.\n            Defaults to an empty string\n        hlines : bool, optional\n            Inserts ``\\\\hline`` before and after the header, and at the end of table.\n        blank_fill : str, optional\n            If a framework does not have a particular parameter, will fill that cell of\n            the table with this string.\n\n        Returns\n        -------\n        str\n            the LaTeX table.\n        \"\"\"\n        if parameters is None:\n            parameters = self.parent._all_parameters\n        for p in parameters:\n            assert isinstance(p, str), \\\n                \"Generating a LaTeX table requires all parameters have labels\"\n        num_parameters = len(parameters)\n        num_chains = len(self.parent.chains)\n        fit_values = self.get_summary(squeeze=False)\n        if label is None:\n            label = \"\"\n        if caption is None:\n            caption = \"\"\n\n        end_text = \" \\\\\\\\ \\n\"\n        if transpose:\n            column_text = \"c\" * (num_chains + 1)\n        else:\n            column_text = \"c\" * (num_parameters + 1)\n\n        center_text = \"\"\n        hline_text = \"\\\\hline\\n\"\n        if hlines:\n            center_text += hline_text + \"\\t\\t\"\n        if transpose:\n            center_text += \" & \".join([\"Parameter\"] + [c.name for c in self.parent.chains]) + end_text\n            if hlines:\n                center_text += \"\\t\\t\" + hline_text\n            for p in parameters:\n                arr = [\"\\t\\t\" + p]\n                for chain_res in fit_values:\n                    if p in chain_res:\n                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n                    else:\n                        arr.append(blank_fill)\n                center_text += \" & \".join(arr) + end_text\n        else:\n            center_text += \" & \".join([\"Model\"] + parameters) + end_text\n            if hlines:\n                center_text += \"\\t\\t\" + hline_text\n            for name, chain_res in zip([c.name for c in self.parent.chains], fit_values):\n                arr = [\"\\t\\t\" + name]\n                for p in parameters:\n                    if p in chain_res:\n                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n                    else:\n                        arr.append(blank_fill)\n                center_text += \" & \".join(arr) + end_text\n        if hlines:\n            center_text += \"\\t\\t\" + hline_text\n        final_text = get_latex_table_frame(caption, label) % (column_text, center_text)\n\n        return final_text", "title": ""}
{"_id": "d6993", "text": "def write_str2file(pathname, astr):\n    \"\"\"writes a string to file\"\"\"\n    fname = pathname\n    fhandle = open(fname, 'wb')\n    fhandle.write(astr)\n    fhandle.close()", "title": ""}
{"_id": "d6994", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d6995", "text": "def html(header_rows):\n    \"\"\"\n    Convert a list of tuples describing a table into a HTML string\n    \"\"\"\n    name = 'table%d' % next(tablecounter)\n    return HtmlTable([map(str, row) for row in header_rows], name).render()", "title": ""}
{"_id": "d6996", "text": "def _get_random_id():\n    \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n    symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(symbols) for _ in range(15))", "title": ""}
{"_id": "d6997", "text": "def add_header(self, name, value):\n        \"\"\" Add an additional response header, not removing duplicates. \"\"\"\n        self._headers.setdefault(_hkey(name), []).append(_hval(value))", "title": ""}
{"_id": "d6998", "text": "def runiform(lower, upper, size=None):\n    \"\"\"\n    Random uniform variates.\n    \"\"\"\n    return np.random.uniform(lower, upper, size)", "title": ""}
{"_id": "d6999", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d7000", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d7001", "text": "def test():\n    \"\"\"Test for ReverseDNS class\"\"\"\n    dns = ReverseDNS()\n\n    print(dns.lookup('192.168.0.1'))\n    print(dns.lookup('8.8.8.8'))\n\n    # Test cache\n    print(dns.lookup('8.8.8.8'))", "title": ""}
{"_id": "d7002", "text": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "title": ""}
{"_id": "d7003", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d7004", "text": "def random_alphanum(length):\n    \"\"\"\n    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\n    \"\"\"\n    charset = string.ascii_letters + string.digits\n    return random_string(length, charset)", "title": ""}
{"_id": "d7005", "text": "def na_if(series, *values):\n    \"\"\"\n    If values in a series match a specified value, change them to `np.nan`.\n\n    Args:\n        series: Series or vector, often symbolic.\n        *values: Value(s) to convert to `np.nan` in the series.\n    \"\"\"\n\n    series = pd.Series(series)\n    series[series.isin(values)] = np.nan\n    return series", "title": ""}
{"_id": "d7006", "text": "def get_available_gpus():\n  \"\"\"\n  Returns a list of string names of all available GPUs\n  \"\"\"\n  local_device_protos = device_lib.list_local_devices()\n  return [x.name for x in local_device_protos if x.device_type == 'GPU']", "title": ""}
{"_id": "d7007", "text": "def is_element_present(driver, selector, by=By.CSS_SELECTOR):\n    \"\"\"\n    Returns whether the specified element selector is present 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 present)\n    \"\"\"\n    try:\n        driver.find_element(by=by, value=selector)\n        return True\n    except Exception:\n        return False", "title": ""}
{"_id": "d7008", "text": "def circ_permutation(items):\n    \"\"\"Calculate the circular permutation for a given list of items.\"\"\"\n    permutations = []\n    for i in range(len(items)):\n        permutations.append(items[i:] + items[:i])\n    return permutations", "title": ""}
{"_id": "d7009", "text": "def _is_name_used_as_variadic(name, variadics):\n    \"\"\"Check if the given name is used as a variadic argument.\"\"\"\n    return any(\n        variadic.value == name or variadic.value.parent_of(name)\n        for variadic in variadics\n    )", "title": ""}
{"_id": "d7010", "text": "def ancestors(self, node):\n        \"\"\"Returns set of the ancestors of a node as DAGNodes.\"\"\"\n        if isinstance(node, int):\n            warnings.warn('Calling ancestors() with a node id is deprecated,'\n                          ' use a DAGNode instead',\n                          DeprecationWarning, 2)\n            node = self._id_to_node[node]\n\n        return nx.ancestors(self._multi_graph, node)", "title": ""}
{"_id": "d7011", "text": "def _trim(image):\n    \"\"\"Trim a PIL image and remove white space.\"\"\"\n    background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n    diff = PIL.ImageChops.difference(image, background)\n    diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n    bbox = diff.getbbox()\n    if bbox:\n        image = image.crop(bbox)\n    return image", "title": ""}
{"_id": "d7012", "text": "def ReadTif(tifFile):\n        \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n        img = Image.open(tifFile)\n        img = np.array(img)\n        return img", "title": ""}
{"_id": "d7013", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d7014", "text": "def get_attr(self, method_name):\n        \"\"\"Get attribute from the target object\"\"\"\n        return self.attrs.get(method_name) or self.get_callable_attr(method_name)", "title": ""}
{"_id": "d7015", "text": "def get_colors(img):\n    \"\"\"\n    Returns a list of all the image's colors.\n    \"\"\"\n    w, h = img.size\n    return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]", "title": ""}
{"_id": "d7016", "text": "def osx_clipboard_get():\n    \"\"\" Get the clipboard's text on OS X.\n    \"\"\"\n    p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n        stdout=subprocess.PIPE)\n    text, stderr = p.communicate()\n    # Text comes in with old Mac \\r line endings. Change them to \\n.\n    text = text.replace('\\r', '\\n')\n    return text", "title": ""}
{"_id": "d7017", "text": "def show(data, negate=False):\n    \"\"\"Show the stretched data.\n    \"\"\"\n    from PIL import Image as pil\n    data = np.array((data - data.min()) * 255.0 /\n                    (data.max() - data.min()), np.uint8)\n    if negate:\n        data = 255 - data\n    img = pil.fromarray(data)\n    img.show()", "title": ""}
{"_id": "d7018", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d7019", "text": "def get_image_dimension(self, url):\n        \"\"\"\n        Return a tuple that contains (width, height)\n        Pass in a url to an image and find out its size without loading the whole file\n        If the image wxh could not be found, the tuple will contain `None` values\n        \"\"\"\n        w_h = (None, None)\n        try:\n            if url.startswith('//'):\n                url = 'http:' + url\n            data = requests.get(url).content\n            im = Image.open(BytesIO(data))\n\n            w_h = im.size\n        except Exception:\n            logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n        return w_h", "title": ""}
{"_id": "d7020", "text": "def get_active_ajax_datatable(self):\n        \"\"\" Returns a single datatable according to the hint GET variable from an AJAX request. \"\"\"\n        data = getattr(self.request, self.request.method)\n        datatables_dict = self.get_datatables(only=data['datatable'])\n        return list(datatables_dict.values())[0]", "title": ""}
{"_id": "d7021", "text": "def filter_contour(imageFile, opFile):\n    \"\"\" convert an image by applying a contour \"\"\"\n    im = Image.open(imageFile)\n    im1 = im.filter(ImageFilter.CONTOUR)\n    im1.save(opFile)", "title": ""}
{"_id": "d7022", "text": "def last_modified_time(path):\n    \"\"\"\n    Get the last modified time of path as a Timestamp.\n    \"\"\"\n    return pd.Timestamp(os.path.getmtime(path), unit='s', tz='UTC')", "title": ""}
{"_id": "d7023", "text": "def __hash__(self):\n        \"\"\"Return ``hash(self)``.\"\"\"\n        return hash((type(self), self.domain, self.range, self.partition))", "title": ""}
{"_id": "d7024", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d7025", "text": "def normalize_vector(v):\n    \"\"\"Take a vector and return the normalized vector\n    :param v: a vector v\n    :returns : normalized vector v\n    \"\"\"\n    norm = np.linalg.norm(v)\n    return v/norm if not norm == 0 else v", "title": ""}
{"_id": "d7026", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d7027", "text": "def other_ind(self):\n        \"\"\"last row or column of square A\"\"\"\n        return np.full(self.n_min, self.size - 1, dtype=np.int)", "title": ""}
{"_id": "d7028", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d7029", "text": "def remove_index(self):\n        \"\"\"Remove Elasticsearch index associated to the campaign\"\"\"\n        self.index_client.close(self.index_name)\n        self.index_client.delete(self.index_name)", "title": ""}
{"_id": "d7030", "text": "def sorted_index(values, x):\n    \"\"\"\n    For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n    :param values: list\n    :param x: item\n    :return: integer index\n    \"\"\"\n    i = bisect_left(values, x)\n    j = bisect_right(values, x)\n    return values[i:j].index(x) + i", "title": ""}
{"_id": "d7031", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d7032", "text": "def find_start_point(self):\n        \"\"\"\n        Find the first location in our array that is not empty\n        \"\"\"\n        for i, row in enumerate(self.data):\n            for j, _ in enumerate(row):\n                if self.data[i, j] != 0:  # or not np.isfinite(self.data[i,j]):\n                    return i, j", "title": ""}
{"_id": "d7033", "text": "def end_block(self):\n        \"\"\"Ends an indentation block, leaving an empty line afterwards\"\"\"\n        self.current_indent -= 1\n\n        # If we did not add a new line automatically yet, now it's the time!\n        if not self.auto_added_line:\n            self.writeln()\n            self.auto_added_line = True", "title": ""}
{"_id": "d7034", "text": "def get_inputs_from_cm(index, cm):\n    \"\"\"Return indices of inputs to the node with the given index.\"\"\"\n    return tuple(i for i in range(cm.shape[0]) if cm[i][index])", "title": ""}
{"_id": "d7035", "text": "def input(self, prompt, default=None, show_default=True):\n        \"\"\"Provide a command prompt.\"\"\"\n        return click.prompt(prompt, default=default, show_default=show_default)", "title": ""}
{"_id": "d7036", "text": "def last_day(year=_year, month=_month):\n    \"\"\"\n    get the current month's last day\n    :param year:  default to current year\n    :param month:  default to current month\n    :return: month's last day\n    \"\"\"\n    last_day = calendar.monthrange(year, month)[1]\n    return datetime.date(year=year, month=month, day=last_day)", "title": ""}
{"_id": "d7037", "text": "def _check_for_int(x):\n    \"\"\"\n    This is a compatibility function that takes a C{float} and converts it to an\n    C{int} if the values are equal.\n    \"\"\"\n    try:\n        y = int(x)\n    except (OverflowError, ValueError):\n        pass\n    else:\n        # There is no way in AMF0 to distinguish between integers and floats\n        if x == x and y == x:\n            return y\n\n    return x", "title": ""}
{"_id": "d7038", "text": "def other_ind(self):\n        \"\"\"last row or column of square A\"\"\"\n        return np.full(self.n_min, self.size - 1, dtype=np.int)", "title": ""}
{"_id": "d7039", "text": "def lin_interp(x, rangeX, rangeY):\n    \"\"\"\n    Interpolate linearly variable x in rangeX onto rangeY.\n    \"\"\"\n    s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])\n    y = rangeY[0] * (1 - s) + rangeY[1] * s\n    return y", "title": ""}
{"_id": "d7040", "text": "def get_last_id(self, cur, table='reaction'):\n        \"\"\"\n        Get the id of the last written row in table\n\n        Parameters\n        ----------\n        cur: database connection().cursor() object\n        table: str\n            'reaction', 'publication', 'publication_system', 'reaction_system'\n\n        Returns: id\n        \"\"\"\n        cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n                    .format(table))\n        result = cur.fetchone()\n        if result is not None:\n            id = result[0]\n        else:\n            id = 0\n        return id", "title": ""}
{"_id": "d7041", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d7042", "text": "def get_last(self, table=None):\n        \"\"\"Just the last entry.\"\"\"\n        if table is None: table = self.main_table\n        query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n        return self.own_cursor.execute(query).fetchone()", "title": ""}
{"_id": "d7043", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d7044", "text": "def __len__(self):\n        \"\"\"Return total data length of the list and its headers.\"\"\"\n        return self.chunk_length() + len(self.type) + len(self.header) + 4", "title": ""}
{"_id": "d7045", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d7046", "text": "def difference(ydata1, ydata2):\n    \"\"\"\n\n    Returns the number you should add to ydata1 to make it line up with ydata2\n\n    \"\"\"\n\n    y1 = _n.array(ydata1)\n    y2 = _n.array(ydata2)\n\n    return(sum(y2-y1)/len(ydata1))", "title": ""}
{"_id": "d7047", "text": "def _ioctl (self, func, args):\n        \"\"\"Call ioctl() with given parameters.\"\"\"\n        import fcntl\n        return fcntl.ioctl(self.sockfd.fileno(), func, args)", "title": ""}
{"_id": "d7048", "text": "def _index_ordering(redshift_list):\n        \"\"\"\n\n        :param redshift_list: list of redshifts\n        :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n        \"\"\"\n        redshift_list = np.array(redshift_list)\n        sort_index = np.argsort(redshift_list)\n        return sort_index", "title": ""}
{"_id": "d7049", "text": "def _ipv4_text_to_int(self, ip_text):\n        \"\"\"convert ip v4 string to integer.\"\"\"\n        if ip_text is None:\n            return None\n        assert isinstance(ip_text, str)\n        return struct.unpack('!I', addrconv.ipv4.text_to_bin(ip_text))[0]", "title": ""}
{"_id": "d7050", "text": "def _lookup_parent(self, cls):\n        \"\"\"Lookup a transitive parent object that is an instance\n            of a given class.\"\"\"\n        codeobj = self.parent\n        while codeobj is not None and not isinstance(codeobj, cls):\n            codeobj = codeobj.parent\n        return codeobj", "title": ""}
{"_id": "d7051", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d7052", "text": "def get_week_start_end_day():\n    \"\"\"\n    Get the week start date and end date\n    \"\"\"\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))", "title": ""}
{"_id": "d7053", "text": "def match_files(files, pattern: Pattern):\n    \"\"\"Yields file name if matches a regular expression pattern.\"\"\"\n\n    for name in files:\n        if re.match(pattern, name):\n            yield name", "title": ""}
{"_id": "d7054", "text": "def get_memory_usage():\n    \"\"\"Gets RAM memory usage\n\n    :return: MB of memory used by this process\n    \"\"\"\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info().rss\n    return mem / (1024 * 1024)", "title": ""}
{"_id": "d7055", "text": "def extract_words(lines):\n    \"\"\"\n    Extract from the given iterable of lines the list of words.\n\n    :param lines: an iterable of lines;\n    :return: a generator of words of lines.\n    \"\"\"\n    for line in lines:\n        for word in re.findall(r\"\\w+\", line):\n            yield word", "title": ""}
{"_id": "d7056", "text": "def get_image_dimension(self, url):\n        \"\"\"\n        Return a tuple that contains (width, height)\n        Pass in a url to an image and find out its size without loading the whole file\n        If the image wxh could not be found, the tuple will contain `None` values\n        \"\"\"\n        w_h = (None, None)\n        try:\n            if url.startswith('//'):\n                url = 'http:' + url\n            data = requests.get(url).content\n            im = Image.open(BytesIO(data))\n\n            w_h = im.size\n        except Exception:\n            logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n        return w_h", "title": ""}
{"_id": "d7057", "text": "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)", "title": ""}
{"_id": "d7058", "text": "def get_week_start_end_day():\n    \"\"\"\n    Get the week start date and end date\n    \"\"\"\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))", "title": ""}
{"_id": "d7059", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d7060", "text": "def pop_row(self, idr=None, tags=False):\n        \"\"\"Pops a row, default the last\"\"\"\n        idr = idr if idr is not None else len(self.body) - 1\n        row = self.body.pop(idr)\n        return row if tags else [cell.childs[0] for cell in row]", "title": ""}
{"_id": "d7061", "text": "def convert_time_string(date_str):\n    \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n    dt, _, _ = date_str.partition(\".\")\n    dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n    return dt", "title": ""}
{"_id": "d7062", "text": "def find_start_point(self):\n        \"\"\"\n        Find the first location in our array that is not empty\n        \"\"\"\n        for i, row in enumerate(self.data):\n            for j, _ in enumerate(row):\n                if self.data[i, j] != 0:  # or not np.isfinite(self.data[i,j]):\n                    return i, j", "title": ""}
{"_id": "d7063", "text": "def _nth(arr, n):\n    \"\"\"\n    Return the nth value of array\n\n    If it is missing return NaN\n    \"\"\"\n    try:\n        return arr.iloc[n]\n    except (KeyError, IndexError):\n        return np.nan", "title": ""}
{"_id": "d7064", "text": "def record_diff(old, new):\n    \"\"\"Return a JSON-compatible structure capable turn the `new` record back\n    into the `old` record. The parameters must be structures compatible with\n    json.dumps *or* strings compatible with json.loads. Note that by design,\n    `old == record_patch(new, record_diff(old, new))`\"\"\"\n    old, new = _norm_json_params(old, new)\n    return json_delta.diff(new, old, verbose=False)", "title": ""}
{"_id": "d7065", "text": "def percentile(values, k):\n    \"\"\"Find the percentile of a list of values.\n\n    :param list values: The list of values to find the percentile of\n    :param int k: The percentile to find\n    :rtype: float or int\n\n    \"\"\"\n    if not values:\n        return None\n    values.sort()\n    index = (len(values) * (float(k) / 100)) - 1\n    return values[int(math.ceil(index))]", "title": ""}
{"_id": "d7066", "text": "def from_json(cls, json_str):\n        \"\"\"Deserialize the object from a JSON string.\"\"\"\n        d = json.loads(json_str)\n        return cls.from_dict(d)", "title": ""}
{"_id": "d7067", "text": "def explained_variance(returns, values):\n    \"\"\" Calculate how much variance in returns do the values explain \"\"\"\n    exp_var = 1 - torch.var(returns - values) / torch.var(returns)\n    return exp_var.item()", "title": ""}
{"_id": "d7068", "text": "def dump_json(obj):\n    \"\"\"Dump Python object as JSON string.\"\"\"\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)", "title": ""}
{"_id": "d7069", "text": "def get_free_memory_win():\n    \"\"\"Return current free memory on the machine for windows.\n\n    Warning : this script is really not robust\n    Return in MB unit\n    \"\"\"\n    stat = MEMORYSTATUSEX()\n    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n    return int(stat.ullAvailPhys / 1024 / 1024)", "title": ""}
{"_id": "d7070", "text": "def read_json(location):\n    \"\"\"Open and load JSON from file.\n\n    location (Path): Path to JSON file.\n    RETURNS (dict): Loaded JSON content.\n    \"\"\"\n    location = ensure_path(location)\n    with location.open('r', encoding='utf8') as f:\n        return ujson.load(f)", "title": ""}
{"_id": "d7071", "text": "def wordfreq(text, is_filename=False):\n    \"\"\"Return a dictionary of words and word counts in a string.\"\"\"\n    if is_filename:\n        with open(text) as f:\n            text = f.read()\n    freqs = {}\n    for word in text.split():\n        lword = word.lower()\n        freqs[lword] = freqs.get(lword, 0) + 1\n    return freqs", "title": ""}
{"_id": "d7072", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d7073", "text": "def json(body, charset='utf-8', **kwargs):\n    \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n    return json_converter.loads(text(body, charset=charset))", "title": ""}
{"_id": "d7074", "text": "def focusInEvent(self, event):\n        \"\"\"Reimplement Qt method to send focus change notification\"\"\"\n        self.focus_changed.emit()\n        return super(ControlWidget, self).focusInEvent(event)", "title": ""}
{"_id": "d7075", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d7076", "text": "def get_prep_value(self, value):\n        \"\"\"Convert JSON object to a string\"\"\"\n        if self.null and value is None:\n            return None\n        return json.dumps(value, **self.dump_kwargs)", "title": ""}
{"_id": "d7077", "text": "def setLib(self, lib):\n        \"\"\" Copy the lib items into our font. \"\"\"\n        for name, item in lib.items():\n            self.font.lib[name] = item", "title": ""}
{"_id": "d7078", "text": "def _unjsonify(x, isattributes=False):\n    \"\"\"Convert JSON string to an ordered defaultdict.\"\"\"\n    if isattributes:\n        obj = json.loads(x)\n        return dict_class(obj)\n    return json.loads(x)", "title": ""}
{"_id": "d7079", "text": "def go_to_parent_directory(self):\n        \"\"\"Go to parent directory\"\"\"\n        self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))", "title": ""}
{"_id": "d7080", "text": "def is_numeric(value):\n        \"\"\"Test if a value is numeric.\n        \"\"\"\n        return type(value) in [\n            int,\n            float,\n            \n            np.int8,\n            np.int16,\n            np.int32,\n            np.int64,\n\n            np.float16,\n            np.float32,\n            np.float64,\n            np.float128\n        ]", "title": ""}
{"_id": "d7081", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d7082", "text": "def is_identity():\n        \"\"\"Check to see if this matrix is an identity matrix.\"\"\"\n        for index, row in enumerate(self.dta):\n            if row[index] == 1:\n                for num, element in enumerate(row):\n                    if num != index:\n                        if element != 0:\n                            return False\n            else:\n                return False\n\n        return True", "title": ""}
{"_id": "d7083", "text": "def bounding_box(img):\n    r\"\"\"\n    Return the bounding box incorporating all non-zero values in the image.\n    \n    Parameters\n    ----------\n    img : array_like\n        An array containing non-zero objects.\n        \n    Returns\n    -------\n    bbox : a list of slicer objects defining the bounding box\n    \"\"\"\n    locations = numpy.argwhere(img)\n    mins = locations.min(0)\n    maxs = locations.max(0) + 1\n    return [slice(x, y) for x, y in zip(mins, maxs)]", "title": ""}
{"_id": "d7084", "text": "def do_files_exist(filenames):\n  \"\"\"Whether any of the filenames exist.\"\"\"\n  preexisting = [tf.io.gfile.exists(f) for f in filenames]\n  return any(preexisting)", "title": ""}
{"_id": "d7085", "text": "def adjacency(tree):\n    \"\"\"\n    Construct the adjacency matrix of the tree\n    :param tree:\n    :return:\n    \"\"\"\n    dd = ids(tree)\n    N = len(dd)\n    A = np.zeros((N, N))\n\n    def _adj(node):\n        if np.isscalar(node):\n            return\n        elif isinstance(node, tuple) and len(node) == 2:\n            A[dd[node], dd[node[0]]] = 1\n            A[dd[node[0]], dd[node]] = 1\n            _adj(node[0])\n\n            A[dd[node], dd[node[1]]] = 1\n            A[dd[node[1]], dd[node]] = 1\n            _adj(node[1])\n\n    _adj(tree)\n    return A", "title": ""}
{"_id": "d7086", "text": "def signal_handler(signal_name, frame):\n    \"\"\"Quit signal handler.\"\"\"\n    sys.stdout.flush()\n    print(\"\\nSIGINT in frame signal received. Quitting...\")\n    sys.stdout.flush()\n    sys.exit(0)", "title": ""}
{"_id": "d7087", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d7088", "text": "def _set_widget_background_color(widget, color):\n        \"\"\"\n        Changes the base color of a widget (background).\n        :param widget: widget to modify\n        :param color: the color to apply\n        \"\"\"\n        pal = widget.palette()\n        pal.setColor(pal.Base, color)\n        widget.setPalette(pal)", "title": ""}
{"_id": "d7089", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d7090", "text": "def one_hot_encoding(input_tensor, num_labels):\n    \"\"\" One-hot encode labels from input \"\"\"\n    xview = input_tensor.view(-1, 1).to(torch.long)\n\n    onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)\n    onehot.scatter_(1, xview, 1)\n    return onehot.view(list(input_tensor.shape) + [-1])", "title": ""}
{"_id": "d7091", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d7092", "text": "def monthly(date=datetime.date.today()):\n    \"\"\"\n    Take a date object and return the first day of the month.\n    \"\"\"\n    return datetime.date(date.year, date.month, 1)", "title": ""}
{"_id": "d7093", "text": "def compare(self, dn, attr, value):\n        \"\"\"\n        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.\n        \"\"\"\n        return self.connection.compare_s(dn, attr, value) == 1", "title": ""}
{"_id": "d7094", "text": "def _one_exists(input_files):\n    \"\"\"\n    at least one file must exist for multiqc to run properly\n    \"\"\"\n    for f in input_files:\n        if os.path.exists(f):\n            return True\n    return False", "title": ""}
{"_id": "d7095", "text": "def prox_zero(X, step):\n    \"\"\"Proximal operator to project onto zero\n    \"\"\"\n    return np.zeros(X.shape, dtype=X.dtype)", "title": ""}
{"_id": "d7096", "text": "def heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "title": ""}
{"_id": "d7097", "text": "def days_in_month(year, month):\n    \"\"\"\n    returns number of days for the given year and month\n\n    :param int year: calendar year\n    :param int month: calendar month\n    :return int:\n    \"\"\"\n\n    eom = _days_per_month[month - 1]\n    if is_leap_year(year) and month == 2:\n        eom += 1\n\n    return eom", "title": ""}
{"_id": "d7098", "text": "def _heappush_max(heap, item):\n    \"\"\" why is this not in heapq \"\"\"\n    heap.append(item)\n    heapq._siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d7099", "text": "def on_binop(self, node):    # ('left', 'op', 'right')\n        \"\"\"Binary operator.\"\"\"\n        return op2func(node.op)(self.run(node.left),\n                                self.run(node.right))", "title": ""}
{"_id": "d7100", "text": "def disable_wx(self):\n        \"\"\"Disable event loop integration with wxPython.\n\n        This merely sets PyOS_InputHook to NULL.\n        \"\"\"\n        if self._apps.has_key(GUI_WX):\n            self._apps[GUI_WX]._in_event_loop = False\n        self.clear_inputhook()", "title": ""}
{"_id": "d7101", "text": "def _shape(self, df):\n        \"\"\"\n        Calculate table chape considering index levels.\n        \"\"\"\n\n        row, col = df.shape\n        return row + df.columns.nlevels, col + df.index.nlevels", "title": ""}
{"_id": "d7102", "text": "def print_item_with_children(ac, classes, level):\n    \"\"\" Print the given item and all children items \"\"\"\n    print_row(ac.id, ac.name, f\"{ac.allocation:,.2f}\", level)\n    print_children_recursively(classes, ac, level + 1)", "title": ""}
{"_id": "d7103", "text": "def timed (log=sys.stderr, limit=2.0):\n    \"\"\"Decorator to run a function with timing info.\"\"\"\n    return lambda func: timeit(func, log, limit)", "title": ""}
{"_id": "d7104", "text": "def random_str(size=10):\n    \"\"\"\n    create random string of selected size\n\n    :param size: int, length of the string\n    :return: the string\n    \"\"\"\n    return ''.join(random.choice(string.ascii_lowercase) for _ in range(size))", "title": ""}
{"_id": "d7105", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d7106", "text": "def _scaleSinglePoint(point, scale=1, convertToInteger=True):\n    \"\"\"\n    Scale a single point\n    \"\"\"\n    x, y = point\n    if convertToInteger:\n        return int(round(x * scale)), int(round(y * scale))\n    else:\n        return (x * scale, y * scale)", "title": ""}
{"_id": "d7107", "text": "def l2_norm(params):\n    \"\"\"Computes l2 norm of params by flattening them into a vector.\"\"\"\n    flattened, _ = flatten(params)\n    return np.dot(flattened, flattened)", "title": ""}
{"_id": "d7108", "text": "def poke_array(self, store, name, elemtype, elements, container, visited, _stack):\n        \"\"\"abstract method\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d7109", "text": "def is_nullable_list(val, vtype):\n    \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n    return (isinstance(val, list) and\n            any(isinstance(v, vtype) for v in val) and\n            all((isinstance(v, vtype) or v is None) for v in val))", "title": ""}
{"_id": "d7110", "text": "def read_from_file(file_path, encoding=\"utf-8\"):\n    \"\"\"\n    Read helper method\n\n    :type file_path: str|unicode\n    :type encoding: str|unicode\n    :rtype: str|unicode\n    \"\"\"\n    with codecs.open(file_path, \"r\", encoding) as f:\n        return f.read()", "title": ""}
{"_id": "d7111", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d7112", "text": "def _prepare_proxy(self, conn):\n        \"\"\"\n        Establish tunnel connection early, because otherwise httplib\n        would improperly set Host: header to proxy's IP:port.\n        \"\"\"\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n        conn.connect()", "title": ""}
{"_id": "d7113", "text": "def list_get(l, idx, default=None):\n    \"\"\"\n    Get from a list with an optional default value.\n    \"\"\"\n    try:\n        if l[idx]:\n            return l[idx]\n        else:\n            return default\n    except IndexError:\n        return default", "title": ""}
{"_id": "d7114", "text": "def get_extract_value_function(column_identifier):\n    \"\"\"\n    returns a function that extracts the value for a column.\n    \"\"\"\n    def extract_value(run_result):\n        pos = None\n        for i, column in enumerate(run_result.columns):\n            if column.title == column_identifier:\n                pos = i\n                break\n        if pos is None:\n            sys.exit('CPU time missing for task {0}.'.format(run_result.task_id[0]))\n        return Util.to_decimal(run_result.values[pos])\n    return extract_value", "title": ""}
{"_id": "d7115", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d7116", "text": "def count_rows(self, table_name):\n        \"\"\"Return the number of entries in a table by counting them.\"\"\"\n        self.table_must_exist(table_name)\n        query = \"SELECT COUNT (*) FROM `%s`\" % table_name.lower()\n        self.own_cursor.execute(query)\n        return int(self.own_cursor.fetchone()[0])", "title": ""}
{"_id": "d7117", "text": "def items_to_dict(items):\n    \"\"\"\n    Converts list of tuples to dictionary with duplicate keys converted to\n    lists.\n\n    :param list items:\n        List of tuples.\n\n    :returns:\n        :class:`dict`\n\n    \"\"\"\n\n    res = collections.defaultdict(list)\n\n    for k, v in items:\n        res[k].append(v)\n\n    return normalize_dict(dict(res))", "title": ""}
{"_id": "d7118", "text": "def url_encode(url):\n    \"\"\"\n    Convert special characters using %xx escape.\n\n    :param url: str\n    :return: str - encoded url\n    \"\"\"\n    if isinstance(url, text_type):\n        url = url.encode('utf8')\n    return quote(url, ':/%?&=')", "title": ""}
{"_id": "d7119", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d7120", "text": "def deduplicate(list_object):\n    \"\"\"Rebuild `list_object` removing duplicated and keeping order\"\"\"\n    new = []\n    for item in list_object:\n        if item not in new:\n            new.append(item)\n    return new", "title": ""}
{"_id": "d7121", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d7122", "text": "def string_list_to_array(l):\n    \"\"\"\n    Turns a Python unicode string list into a Java String array.\n\n    :param l: the string list\n    :type: list\n    :rtype: java string array\n    :return: JB_Object\n    \"\"\"\n    result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class(\"java/lang/String\"))\n    for i in range(len(l)):\n        javabridge.get_env().set_object_array_element(result, i, javabridge.get_env().new_string_utf(l[i]))\n    return result", "title": ""}
{"_id": "d7123", "text": "def save_dict_to_file(filename, dictionary):\n  \"\"\"Saves dictionary as CSV file.\"\"\"\n  with open(filename, 'w') as f:\n    writer = csv.writer(f)\n    for k, v in iteritems(dictionary):\n      writer.writerow([str(k), str(v)])", "title": ""}
{"_id": "d7124", "text": "def get_uniques(l):\n    \"\"\" Returns a list with no repeated elements.\n    \"\"\"\n    result = []\n\n    for i in l:\n        if i not in result:\n            result.append(i)\n\n    return result", "title": ""}
{"_id": "d7125", "text": "def log(x):\n    \"\"\"\n    Natural logarithm\n    \"\"\"\n    if isinstance(x, UncertainFunction):\n        mcpts = np.log(x._mcpts)\n        return UncertainFunction(mcpts)\n    else:\n        return np.log(x)", "title": ""}
{"_id": "d7126", "text": "def hdf5_to_dict(filepath, group='/'):\n    \"\"\"load the content of an hdf5 file to a dict.\n\n    # TODO: how to split domain_type_dev : parameter : value ?\n    \"\"\"\n    if not h5py.is_hdf5(filepath):\n        raise RuntimeError(filepath, 'is not a valid HDF5 file.')\n\n    with h5py.File(filepath, 'r') as handler:\n        dic = walk_hdf5_to_dict(handler[group])\n    return dic", "title": ""}
{"_id": "d7127", "text": "def get_point_hash(self, point):\n        \"\"\"\n        return geohash for given point with self.precision\n        :param point: GeoPoint instance\n        :return: string\n        \"\"\"\n        return geohash.encode(point.latitude, point.longitude, self.precision)", "title": ""}
{"_id": "d7128", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d7129", "text": "def __deepcopy__(self, memo):\n        \"\"\"Create a deep copy of the node\"\"\"\n        # noinspection PyArgumentList\n        return self.__class__(\n            **{key: deepcopy(getattr(self, key), memo) for key in self.keys}\n        )", "title": ""}
{"_id": "d7130", "text": "def from_file(filename):\n    \"\"\"\n    load an nparray object from a json filename\n\n    @parameter str filename: path to the file\n    \"\"\"\n    f = open(filename, 'r')\n    j = json.load(f)\n    f.close()\n\n    return from_dict(j)", "title": ""}
{"_id": "d7131", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d7132", "text": "def from_json_str(cls, json_str):\n    \"\"\"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.\n    \"\"\"\n    return cls.from_json(json.loads(json_str, cls=JsonDecoder))", "title": ""}
{"_id": "d7133", "text": "def pause():\n\t\"\"\"Tell iTunes to pause\"\"\"\n\n\tif not settings.platformCompatible():\n\t\treturn False\n\n\t(output, error) = subprocess.Popen([\"osascript\", \"-e\", PAUSE], stdout=subprocess.PIPE).communicate()", "title": ""}
{"_id": "d7134", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d7135", "text": "def camel_case(self, snake_case):\n        \"\"\" Convert snake case to camel case \"\"\"\n        components = snake_case.split('_')\n        return components[0] + \"\".join(x.title() for x in components[1:])", "title": ""}
{"_id": "d7136", "text": "def get_frame_locals(stepback=0):\n    \"\"\"Returns locals dictionary from a given frame.\n\n    :param int stepback:\n\n    :rtype: dict\n\n    \"\"\"\n    with Frame(stepback=stepback) as frame:\n        locals_dict = frame.f_locals\n\n    return locals_dict", "title": ""}
{"_id": "d7137", "text": "def align_to_mmap(num, round_up):\n    \"\"\"\n    Align the given integer number to the closest page offset, which usually is 4096 bytes.\n\n    :param round_up: if True, the next higher multiple of page size is used, otherwise\n        the lower page_size will be used (i.e. if True, 1 becomes 4096, otherwise it becomes 0)\n    :return: num rounded to closest page\"\"\"\n    res = (num // ALLOCATIONGRANULARITY) * ALLOCATIONGRANULARITY\n    if round_up and (res != num):\n        res += ALLOCATIONGRANULARITY\n    # END handle size\n    return res", "title": ""}
{"_id": "d7138", "text": "def fromtimestamp(cls, timestamp):\n    \"\"\"Returns a datetime object of a given timestamp (in local tz).\"\"\"\n    d = cls.utcfromtimestamp(timestamp)\n    return d.astimezone(localtz())", "title": ""}
{"_id": "d7139", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d7140", "text": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "title": ""}
{"_id": "d7141", "text": "def case_us2mc(x):\n    \"\"\" underscore to mixed case notation \"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)", "title": ""}
{"_id": "d7142", "text": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "title": ""}
{"_id": "d7143", "text": "def length(self):\n        \"\"\"Array of vector lengths\"\"\"\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "title": ""}
{"_id": "d7144", "text": "def log_request(self, code='-', size='-'):\n        \"\"\"Selectively log an accepted request.\"\"\"\n\n        if self.server.logRequests:\n            BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)", "title": ""}
{"_id": "d7145", "text": "def do_file_show(client, args):\n    \"\"\"Output file contents to stdout\"\"\"\n    for src_uri in args.uris:\n        client.download_file(src_uri, sys.stdout.buffer)\n\n    return True", "title": ""}
{"_id": "d7146", "text": "def getLinesFromLogFile(stream):\n    \"\"\"\n    Returns all lines written to the passed in stream\n    \"\"\"\n    stream.flush()\n    stream.seek(0)\n    lines = stream.readlines()\n    return lines", "title": ""}
{"_id": "d7147", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d7148", "text": "def close_log(log, verbose=True):\n    \"\"\"Close log\n\n    This method closes and active logging.Logger instance.\n\n    Parameters\n    ----------\n    log : logging.Logger\n        Logging instance\n\n    \"\"\"\n\n    if verbose:\n        print('Closing log file:', log.name)\n\n    # Send closing message.\n    log.info('The log file has been closed.')\n\n    # Remove all handlers from log.\n    [log.removeHandler(handler) for handler in log.handlers]", "title": ""}
{"_id": "d7149", "text": "def pylog(self, *args, **kwargs):\n        \"\"\"Display all available logging information.\"\"\"\n        printerr(self.name, args, kwargs, traceback.format_exc())", "title": ""}
{"_id": "d7150", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d7151", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d7152", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d7153", "text": "def _configure_logger():\n    \"\"\"Configure the logging module.\"\"\"\n    if not app.debug:\n        _configure_logger_for_production(logging.getLogger())\n    elif not app.testing:\n        _configure_logger_for_debugging(logging.getLogger())", "title": ""}
{"_id": "d7154", "text": "def input_validate_yubikey_secret(data, name='data'):\n    \"\"\" Input validation for YHSM_YubiKeySecret or string. \"\"\"\n    if isinstance(data, pyhsm.aead_cmd.YHSM_YubiKeySecret):\n        data = data.pack()\n    return input_validate_str(data, name)", "title": ""}
{"_id": "d7155", "text": "def extract_log_level_from_environment(k, default):\n    \"\"\"Gets the log level from the environment variable.\"\"\"\n    return LOG_LEVELS.get(os.environ.get(k)) or int(os.environ.get(k, default))", "title": ""}
{"_id": "d7156", "text": "def dumped(text, level, indent=2):\n    \"\"\"Put curly brackets round an indented text\"\"\"\n    return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "title": ""}
{"_id": "d7157", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d7158", "text": "def add_arrow(self, x1, y1, x2, y2, **kws):\n        \"\"\"add arrow to plot\"\"\"\n        self.panel.add_arrow(x1, y1, x2, y2, **kws)", "title": ""}
{"_id": "d7159", "text": "def remove_all_handler(self):\n        \"\"\"\n        Unlink the file handler association.\n        \"\"\"\n        for handler in self.logger.handlers[:]:\n            self.logger.removeHandler(handler)\n            self._handler_cache.append(handler)", "title": ""}
{"_id": "d7160", "text": "def auth_request(self, url, headers, body):\n        \"\"\"Perform auth request for token.\"\"\"\n\n        return self.req.post(url, headers, body=body)", "title": ""}
{"_id": "d7161", "text": "def log_all(self, file):\n        \"\"\"Log all data received from RFLink to file.\"\"\"\n        global rflink_log\n        if file == None:\n            rflink_log = None\n        else:\n            log.debug('logging to: %s', file)\n            rflink_log = open(file, 'a')", "title": ""}
{"_id": "d7162", "text": "def set_title(self, title, **kwargs):\n        \"\"\"Sets the title on the underlying matplotlib AxesSubplot.\"\"\"\n        ax = self.get_axes()\n        ax.set_title(title, **kwargs)", "title": ""}
{"_id": "d7163", "text": "def setLoggerAll(self, mthd):\n        \"\"\" Sends all messages to ``logger.[mthd]()`` for handling \"\"\"\n        for key in self._logger_methods:\n            self._logger_methods[key] = mthd", "title": ""}
{"_id": "d7164", "text": "def adjust_bounding_box(bbox):\n    \"\"\"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.\n    \"\"\"\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", "title": ""}
{"_id": "d7165", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d7166", "text": "def _turn_sigterm_into_systemexit(): # pragma: no cover\n    \"\"\"\n    Attempts to turn a SIGTERM exception into a SystemExit exception.\n    \"\"\"\n    try:\n        import signal\n    except ImportError:\n        return\n    def handle_term(signo, frame):\n        raise SystemExit\n    signal.signal(signal.SIGTERM, handle_term)", "title": ""}
{"_id": "d7167", "text": "def info(self, message, *args, **kwargs):\n        \"\"\"More important level : default for print and save\n        \"\"\"\n        self._log(logging.INFO, message, *args, **kwargs)", "title": ""}
{"_id": "d7168", "text": "def patch_lines(x):\n    \"\"\"\n    Draw lines between groups\n    \"\"\"\n    for idx in range(len(x)-1):\n        x[idx] = np.vstack([x[idx], x[idx+1][0,:]])\n    return x", "title": ""}
{"_id": "d7169", "text": "def info(self, message, *args, **kwargs):\n        \"\"\"More important level : default for print and save\n        \"\"\"\n        self._log(logging.INFO, message, *args, **kwargs)", "title": ""}
{"_id": "d7170", "text": "def add_queue_handler(queue):\n    \"\"\"Add a queue log handler to the global logger.\"\"\"\n    handler = QueueLogHandler(queue)\n    handler.setFormatter(QueueFormatter())\n    handler.setLevel(DEBUG)\n    GLOBAL_LOGGER.addHandler(handler)", "title": ""}
{"_id": "d7171", "text": "def __init__(self, min_value, max_value, format=\"%(bar)s: %(percentage) 6.2f%% %(timeinfo)s\", width=40, barchar=\"#\", emptychar=\"-\", output=sys.stdout):\n\t\t\"\"\"\t\t\n\t\t\t:param min_value: minimum value for update(..)\n\t\t\t:param format: format specifier for the output\n\t\t\t:param width: width of the progress bar's (excluding extra text)\n\t\t\t:param barchar: character used to print the bar\n\t\t\t:param output: where to write the output to\n\t\t\"\"\"\n\t\tself.min_value = min_value\n\t\tself.max_value = max_value\n\t\tself.format = format\n\t\tself.width = width\n\t\tself.barchar = barchar\n\t\tself.emptychar = emptychar\n\t\tself.output = output\n\t\t\n\t\tself.firsttime = True\n\t\tself.prevtime = time.time()\n\t\tself.starttime = self.prevtime\n\t\tself.prevfraction = 0\n\t\tself.firsttimedone = False\n\t\tself.value = self.min_value", "title": ""}
{"_id": "d7172", "text": "def consts(self):\n        \"\"\"The constants referenced in this code object.\n        \"\"\"\n        # We cannot use a set comprehension because consts do not need\n        # to be hashable.\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)", "title": ""}
{"_id": "d7173", "text": "def __add__(self, other):\n        \"\"\"Left addition.\"\"\"\n        return chaospy.poly.collection.arithmetics.add(self, other)", "title": ""}
{"_id": "d7174", "text": "def gaussian_noise(x, severity=1):\n  \"\"\"Gaussian noise corruption to 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]. Added Gaussian noise.\n  \"\"\"\n  c = [.08, .12, 0.18, 0.26, 0.38][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(x + np.random.normal(size=x.shape, scale=c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d7175", "text": "def get_file_size(filename):\n    \"\"\"\n    Get the file size of a given file\n\n    :param filename: string: pathname of a file\n    :return: human readable filesize\n    \"\"\"\n    if os.path.isfile(filename):\n        return convert_size(os.path.getsize(filename))\n    return None", "title": ""}
{"_id": "d7176", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d7177", "text": "def sigterm(self, signum, frame):\n        \"\"\"\n        These actions will be done after SIGTERM.\n        \"\"\"\n        self.logger.warning(\"Caught signal %s. Stopping daemon.\" % signum)\n        sys.exit(0)", "title": ""}
{"_id": "d7178", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d7179", "text": "def decode_mysql_string_literal(text):\n    \"\"\"\n    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\n    \"\"\"\n    assert text.startswith(\"'\")\n    assert text.endswith(\"'\")\n\n    # Ditch quotes from the string literal.\n    text = text[1:-1]\n\n    return MYSQL_STRING_ESCAPE_SEQUENCE_PATTERN.sub(\n        unescape_single_character,\n        text,\n    )", "title": ""}
{"_id": "d7180", "text": "def get_bin_indices(self, values):\n        \"\"\"Returns index tuple in histogram of bin which contains value\"\"\"\n        return tuple([self.get_axis_bin_index(values[ax_i], ax_i)\n                      for ax_i in range(self.dimensions)])", "title": ""}
{"_id": "d7181", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d7182", "text": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d7183", "text": "def ver_to_tuple(value):\n    \"\"\"\n    Convert version like string to a tuple of integers.\n    \"\"\"\n    return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "title": ""}
{"_id": "d7184", "text": "def clean_with_zeros(self,x):\n        \"\"\" set nan and inf rows from x to zero\"\"\"\n        x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0\n        return x", "title": ""}
{"_id": "d7185", "text": "def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model):\n    \"\"\" The how well do the features plus a constant base rate sum up to the model output.\n    \"\"\"\n\n    X_train, X_test = to_array(X_train, X_test)\n\n    # how many features to mask\n    assert X_train.shape[1] == X_test.shape[1]\n\n    # keep nkeep top features and re-train the model for each test explanation\n    yp_test = trained_model.predict(X_test)\n\n    return metric(yp_test, strip_list(attr_test).sum(1))", "title": ""}
{"_id": "d7186", "text": "def url_encode(url):\n    \"\"\"\n    Convert special characters using %xx escape.\n\n    :param url: str\n    :return: str - encoded url\n    \"\"\"\n    if isinstance(url, text_type):\n        url = url.encode('utf8')\n    return quote(url, ':/%?&=')", "title": ""}
{"_id": "d7187", "text": "def calculate_bbox_area(bbox, rows, cols):\n    \"\"\"Calculate the area of a bounding box in pixels.\"\"\"\n    bbox = denormalize_bbox(bbox, rows, cols)\n    x_min, y_min, x_max, y_max = bbox[:4]\n    area = (x_max - x_min) * (y_max - y_min)\n    return area", "title": ""}
{"_id": "d7188", "text": "def tearDown(self):\n        \"\"\" Clean up environment\n\n        \"\"\"\n        if self.sdkobject and self.sdkobject.id:\n            self.sdkobject.delete()\n            self.sdkobject.id = None", "title": ""}
{"_id": "d7189", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d7190", "text": "def handle_m2m(self, sender, instance, **kwargs):\n    \"\"\" Handle many to many relationships \"\"\"\n    self.handle_save(instance.__class__, instance)", "title": ""}
{"_id": "d7191", "text": "def _get_log_prior_cl_func(self):\n        \"\"\"Get the CL log prior compute function.\n\n        Returns:\n            str: the compute function for computing the log prior.\n        \"\"\"\n        return SimpleCLFunction.from_string('''\n            mot_float_type _computeLogPrior(local const mot_float_type* x, void* data){\n                return ''' + self._log_prior_func.get_cl_function_name() + '''(x, data);\n            }\n        ''', dependencies=[self._log_prior_func])", "title": ""}
{"_id": "d7192", "text": "def datetime_match(data, dts):\n    \"\"\"\n    matching of datetimes in time columns for data filtering\n    \"\"\"\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)", "title": ""}
{"_id": "d7193", "text": "def idx(df, index):\n    \"\"\"Universal indexing for numpy and pandas objects.\"\"\"\n    if isinstance(df, (pd.DataFrame, pd.Series)):\n        return df.iloc[index]\n    else:\n        return df[index, :]", "title": ""}
{"_id": "d7194", "text": "def set_ylimits(self, row, column, min=None, max=None):\n        \"\"\"Set y-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_ylimits(min, max)", "title": ""}
{"_id": "d7195", "text": "def list_apis(awsclient):\n    \"\"\"List APIs in account.\"\"\"\n    client_api = awsclient.get_client('apigateway')\n\n    apis = client_api.get_rest_apis()['items']\n\n    for api in apis:\n        print(json2table(api))", "title": ""}
{"_id": "d7196", "text": "def uint32_to_uint8(cls, img):\n        \"\"\"\n        Cast uint32 RGB image to 4 uint8 channels.\n        \"\"\"\n        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))", "title": ""}
{"_id": "d7197", "text": "def quit(self):\n        \"\"\" Exit the program due to user's choices.\n        \"\"\"\n        self.script.LOG.warn(\"Abort due to user choice!\")\n        sys.exit(self.QUIT_RC)", "title": ""}
{"_id": "d7198", "text": "def raise_figure_window(f=0):\n    \"\"\"\n    Raises the supplied figure number or figure window.\n    \"\"\"\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()", "title": ""}
{"_id": "d7199", "text": "def mixedcase(path):\n    \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n    words = path.split('_')\n    return words[0] + ''.join(word.title() for word in words[1:])", "title": ""}
{"_id": "d7200", "text": "def raise_figure_window(f=0):\n    \"\"\"\n    Raises the supplied figure number or figure window.\n    \"\"\"\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()", "title": ""}
{"_id": "d7201", "text": "def to_camel(s):\n    \"\"\"\n    :param string s: under_scored string to be CamelCased\n    :return: CamelCase version of input\n    :rtype: str\n    \"\"\"\n    # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n    return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "title": ""}
{"_id": "d7202", "text": "def figsize(x=8, y=7., aspect=1.):\n    \"\"\" manually set the default figure size of plots\n    ::Arguments::\n        x (float): x-axis size\n        y (float): y-axis size\n        aspect (float): aspect ratio scalar\n    \"\"\"\n    # update rcparams with adjusted figsize params\n    mpl.rcParams.update({'figure.figsize': (x*aspect, y)})", "title": ""}
{"_id": "d7203", "text": "def to_camel_case(text):\n    \"\"\"Convert to camel case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    split = text.split('_')\n    return split[0] + \"\".join(x.title() for x in split[1:])", "title": ""}
{"_id": "d7204", "text": "def _process_legend(self):\n        \"\"\"\n        Disables legends if show_legend is disabled.\n        \"\"\"\n        for l in self.handles['plot'].legend:\n            l.items[:] = []\n            l.border_line_alpha = 0\n            l.background_fill_alpha = 0", "title": ""}
{"_id": "d7205", "text": "def snake_to_camel(name):\n    \"\"\"Takes a snake_field_name and returns a camelCaseFieldName\n\n    Args:\n        name (str): E.g. snake_field_name or SNAKE_FIELD_NAME\n\n    Returns:\n        str: camelCase converted name. E.g. capsFieldName\n    \"\"\"\n    ret = \"\".join(x.title() for x in name.split(\"_\"))\n    ret = ret[0].lower() + ret[1:]\n    return ret", "title": ""}
{"_id": "d7206", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d7207", "text": "def _tofloat(obj):\n    \"\"\"Convert to float if object is a float string.\"\"\"\n    if \"inf\" in obj.lower().strip():\n        return obj\n    try:\n        return int(obj)\n    except ValueError:\n        try:\n            return float(obj)\n        except ValueError:\n            return obj", "title": ""}
{"_id": "d7208", "text": "def fig2x(figure, format):\n    \"\"\"Returns svg from matplotlib chart\"\"\"\n\n    # Save svg to file like object svg_io\n    io = StringIO()\n    figure.savefig(io, format=format)\n\n    # Rewind the file like object\n    io.seek(0)\n\n    data = io.getvalue()\n    io.close()\n\n    return data", "title": ""}
{"_id": "d7209", "text": "def set_scale(self, scale, no_reset=False):\n        \"\"\"Scale the image in a channel.\n        Also see :meth:`zoom_to`.\n\n        Parameters\n        ----------\n        scale : tuple of float\n            Scaling factors for the image in the X and Y axes.\n\n        no_reset : bool\n            Do not reset ``autozoom`` setting.\n\n        \"\"\"\n        return self.scale_to(*scale[:2], no_reset=no_reset)", "title": ""}
{"_id": "d7210", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d7211", "text": "def set_xlimits(self, row, column, min=None, max=None):\n        \"\"\"Set x-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_xlimits(min, max)", "title": ""}
{"_id": "d7212", "text": "def as_tuple(self, value):\n        \"\"\"Utility function which converts lists to tuples.\"\"\"\n        if isinstance(value, list):\n            value = tuple(value)\n        return value", "title": ""}
{"_id": "d7213", "text": "def print_display_png(o):\n    \"\"\"\n    A function to display sympy expression using display style LaTeX in PNG.\n    \"\"\"\n    s = latex(o, mode='plain')\n    s = s.strip('$')\n    # As matplotlib does not support display style, dvipng backend is\n    # used here.\n    png = latex_to_png('$$%s$$' % s, backend='dvipng')\n    return png", "title": ""}
{"_id": "d7214", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d7215", "text": "def R_rot_3d(th):\n    \"\"\"Return a 3-dimensional rotation matrix.\n\n    Parameters\n    ----------\n    th: array, shape (n, 3)\n        Angles about which to rotate along each axis.\n\n    Returns\n    -------\n    R: array, shape (n, 3, 3)\n    \"\"\"\n    sx, sy, sz = np.sin(th).T\n    cx, cy, cz = np.cos(th).T\n    R = np.empty((len(th), 3, 3), dtype=np.float)\n\n    R[:, 0, 0] = cy * cz\n    R[:, 0, 1] = -cy * sz\n    R[:, 0, 2] = sy\n\n    R[:, 1, 0] = sx * sy * cz + cx * sz\n    R[:, 1, 1] = -sx * sy * sz + cx * cz\n    R[:, 1, 2] = -sx * cy\n\n    R[:, 2, 0] = -cx * sy * cz + sx * sz\n    R[:, 2, 1] = cx * sy * sz + sx * cz\n    R[:, 2, 2] = cx * cy\n    return R", "title": ""}
{"_id": "d7216", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d7217", "text": "def _heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "title": ""}
{"_id": "d7218", "text": "def col_rename(df,col_name,new_col_name):\n    \"\"\" Changes a column name in a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_name - string\n        Name of column to change\n    new_col_name - string\n        New name of column\n    \"\"\"\n    col_list = list(df.columns)\n    for index,value in enumerate(col_list):\n        if value == col_name:\n            col_list[index] = new_col_name\n            break\n    df.columns = col_list", "title": ""}
{"_id": "d7219", "text": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "title": ""}
{"_id": "d7220", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d7221", "text": "def m(name='', **kwargs):\n    \"\"\"\n    Print out memory usage at this point in time\n\n    http://docs.python.org/2/library/resource.html\n    http://stackoverflow.com/a/15448600/5006\n    http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended\n    \"\"\"\n    with Reflect.context(**kwargs) as r:\n        kwargs[\"name\"] = name\n        instance = M_CLASS(r, stream, **kwargs)\n        instance()", "title": ""}
{"_id": "d7222", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d7223", "text": "def nested_update(d, u):\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d7224", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d7225", "text": "def std_datestr(self, datestr):\n        \"\"\"Reformat a date string to standard format.\n        \"\"\"\n        return date.strftime(\n                self.str2date(datestr), self.std_dateformat)", "title": ""}
{"_id": "d7226", "text": "def from_string(cls, s):\n        \"\"\"Return a `Status` instance from its string representation.\"\"\"\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)", "title": ""}
{"_id": "d7227", "text": "def _get_minidom_tag_value(station, tag_name):\n    \"\"\"get a value from a tag (if it exists)\"\"\"\n    tag = station.getElementsByTagName(tag_name)[0].firstChild\n    if tag:\n        return tag.nodeValue\n\n    return None", "title": ""}
{"_id": "d7228", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d7229", "text": "def update(self, dictionary=None, **kwargs):\n        \"\"\"\n        Adds/overwrites all the keys and values from the dictionary.\n        \"\"\"\n        if not dictionary == None: kwargs.update(dictionary)\n        for k in list(kwargs.keys()): self[k] = kwargs[k]", "title": ""}
{"_id": "d7230", "text": "def update_one(self, query, doc):\n        \"\"\"\n        Updates one element of the collection\n\n        :param query: dictionary representing the mongo query\n        :param doc: dictionary representing the item to be updated\n        :return: UpdateResult\n        \"\"\"\n        if self.table is None:\n            self.build_table()\n\n        if u\"$set\" in doc:\n            doc = doc[u\"$set\"]\n\n        allcond = self.parse_query(query)\n\n        try:\n            result = self.table.update(doc, allcond)\n        except:\n            # TODO: check table.update result\n            # check what pymongo does in that case\n            result = None\n\n        return UpdateResult(raw_result=result)", "title": ""}
{"_id": "d7231", "text": "def unit_key_from_name(name):\n  \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n  result = name\n\n  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n    result = result.replace(old, new)\n\n  # Collapse redundant underscores and convert to uppercase.\n  result = re.sub(r'_+', '_', result.upper())\n\n  return result", "title": ""}
{"_id": "d7232", "text": "def _obj_cursor_to_dictionary(self, cursor):\n        \"\"\"Handle conversion of pymongo cursor into a JSON object formatted for UI consumption\n\n        :param dict cursor: a mongo document that should be converted to primitive types for the client code\n        :returns: a primitive dictionary\n        :rtype: dict\n        \"\"\"\n        if not cursor:\n            return cursor\n\n        cursor = json.loads(json.dumps(cursor, cls=BSONEncoder))\n\n        if cursor.get(\"_id\"):\n            cursor[\"id\"] = cursor.get(\"_id\")\n            del cursor[\"_id\"]\n\n        return cursor", "title": ""}
{"_id": "d7233", "text": "def comma_converter(float_string):\n    \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n    trans_table = maketrans(b',', b'.')\n    return float(float_string.translate(trans_table))", "title": ""}
{"_id": "d7234", "text": "def create_cursor(self, name=None):\n        \"\"\"\n        Returns an active connection cursor to the database.\n        \"\"\"\n        return Cursor(self.client_connection, self.connection, self.djongo_connection)", "title": ""}
{"_id": "d7235", "text": "def _possibly_convert_objects(values):\n    \"\"\"Convert arrays of datetime.datetime and datetime.timedelta objects into\n    datetime64 and timedelta64, according to the pandas convention.\n    \"\"\"\n    return np.asarray(pd.Series(values.ravel())).reshape(values.shape)", "title": ""}
{"_id": "d7236", "text": "def onLeftDown(self, event=None):\n        \"\"\" left button down: report x,y coords, start zooming mode\"\"\"\n        if event is None:\n            return\n        self.cursor_mode_action('leftdown', event=event)\n        self.ForwardEvent(event=event.guiEvent)", "title": ""}
{"_id": "d7237", "text": "def is_valid_variable_name(string_to_check):\n    \"\"\"\n    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\n    \"\"\"\n\n    try:\n\n        parse('{} = None'.format(string_to_check))\n        return True\n\n    except (SyntaxError, ValueError, TypeError):\n\n        return False", "title": ""}
{"_id": "d7238", "text": "def move_up(lines=1, file=sys.stdout):\n    \"\"\" Move the cursor up a number of lines.\n\n        Esc[ValueA:\n        Moves the cursor up by the specified number of lines without changing\n        columns. If the cursor is already on the top line, ANSI.SYS ignores\n        this sequence.\n    \"\"\"\n    move.up(lines).write(file=file)", "title": ""}
{"_id": "d7239", "text": "def is_collection(obj):\n    \"\"\"Tests if an object is a collection.\"\"\"\n\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n\n    if isinstance(obj, basestring):\n        val = False\n\n    return val", "title": ""}
{"_id": "d7240", "text": "def plot3d_init(fignum):\n    \"\"\"\n    initializes 3D plot\n    \"\"\"\n    from mpl_toolkits.mplot3d import Axes3D\n    fig = plt.figure(fignum)\n    ax = fig.add_subplot(111, projection='3d')\n    return ax", "title": ""}
{"_id": "d7241", "text": "def apply(self, func, workers=1, job_size=10000):\n    \"\"\"Apply `func` to lines of text in parallel or sequential.\n\n    Args:\n      func : a function that takes a list of lines.\n    \"\"\"\n    if workers == 1:\n      for lines in self.iter_chunks(job_size):\n        yield func(lines)\n    else:\n      with ProcessPoolExecutor(max_workers=workers) as executor:\n        for result in executor.map(func, self.iter_chunks(job_size)):\n          yield result", "title": ""}
{"_id": "d7242", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d7243", "text": "def multiprocess_mapping(func, iterable):\n    \"\"\"Multiprocess mapping the given function on the given iterable.\n\n    This only works in Linux and Mac systems since Windows has no forking capability. On Windows we fall back on\n    single processing. Also, if we reach memory limits we fall back on single cpu processing.\n\n    Args:\n        func (func): the function to apply\n        iterable (iterable): the iterable with the elements we want to apply the function on\n    \"\"\"\n    if os.name == 'nt':  # In Windows there is no fork.\n        return list(map(func, iterable))\n    try:\n        p = multiprocessing.Pool()\n        return_data = list(p.imap(func, iterable))\n        p.close()\n        p.join()\n        return return_data\n    except OSError:\n        return list(map(func, iterable))", "title": ""}
{"_id": "d7244", "text": "def is_gzipped_fastq(file_name):\n    \"\"\"\n    Determine whether indicated file appears to be a gzipped FASTQ.\n\n    :param str file_name: Name/path of file to check as gzipped FASTQ.\n    :return bool: Whether indicated file appears to be in gzipped FASTQ format.\n    \"\"\"\n    _, ext = os.path.splitext(file_name)\n    return file_name.endswith(\".fastq.gz\") or file_name.endswith(\".fq.gz\")", "title": ""}
{"_id": "d7245", "text": "def imapchain(*a, **kwa):\n    \"\"\" Like map but also chains the results. \"\"\"\n\n    imap_results = map( *a, **kwa )\n    return itertools.chain( *imap_results )", "title": ""}
{"_id": "d7246", "text": "def eqstr(a, b):\n    \"\"\"\n    Determine whether two strings are equivalent.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html\n\n    :param a: Arbitrary character string.\n    :type a: str\n    :param b: Arbitrary character string.\n    :type b: str\n    :return: True if A and B are equivalent.\n    :rtype: bool\n    \"\"\"\n    return bool(libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)))", "title": ""}
{"_id": "d7247", "text": "def compute(args):\n    x, y, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot(x, y, params)", "title": ""}
{"_id": "d7248", "text": "def is_all_field_none(self):\n        \"\"\"\n        :rtype: bool\n        \"\"\"\n\n        if self._type_ is not None:\n            return False\n\n        if self._value is not None:\n            return False\n\n        if self._name is not None:\n            return False\n\n        return True", "title": ""}
{"_id": "d7249", "text": "def get(self, queue_get):\n        \"\"\"\n        to get states from multiprocessing.queue\n        \"\"\"\n        if isinstance(queue_get, (tuple, list)):\n            self.result.extend(queue_get)", "title": ""}
{"_id": "d7250", "text": "def match_empty(self, el):\n        \"\"\"Check if element is empty (if requested).\"\"\"\n\n        is_empty = True\n        for child in self.get_children(el, tags=False):\n            if self.is_tag(child):\n                is_empty = False\n                break\n            elif self.is_content_string(child) and RE_NOT_EMPTY.search(child):\n                is_empty = False\n                break\n        return is_empty", "title": ""}
{"_id": "d7251", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d7252", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d7253", "text": "def imapchain(*a, **kwa):\n    \"\"\" Like map but also chains the results. \"\"\"\n\n    imap_results = map( *a, **kwa )\n    return itertools.chain( *imap_results )", "title": ""}
{"_id": "d7254", "text": "def allsame(list_, strict=True):\n    \"\"\"\n    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\n    \"\"\"\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)", "title": ""}
{"_id": "d7255", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d7256", "text": "def allsame(list_, strict=True):\n    \"\"\"\n    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\n    \"\"\"\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)", "title": ""}
{"_id": "d7257", "text": "def get_qapp():\n    \"\"\"Return an instance of QApplication. Creates one if neccessary.\n\n    :returns: a QApplication instance\n    :rtype: QApplication\n    :raises: None\n    \"\"\"\n    global app\n    app = QtGui.QApplication.instance()\n    if app is None:\n        app = QtGui.QApplication([], QtGui.QApplication.GuiClient)\n    return app", "title": ""}
{"_id": "d7258", "text": "def store_many(self, sql, values):\n        \"\"\"Abstraction over executemany method\"\"\"\n        cursor = self.get_cursor()\n        cursor.executemany(sql, values)\n        self.conn.commit()", "title": ""}
{"_id": "d7259", "text": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "title": ""}
{"_id": "d7260", "text": "def unpack(self, s):\n        \"\"\"Parse bytes and return a namedtuple.\"\"\"\n        return self._create(super(NamedStruct, self).unpack(s))", "title": ""}
{"_id": "d7261", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d7262", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d7263", "text": "def issubset(self, other):\n        \"\"\"Report whether another set contains this RangeSet.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issubset(self, other)", "title": ""}
{"_id": "d7264", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d7265", "text": "def __neg__(self):\n        \"\"\"Unary negation\"\"\"\n        return self.__class__(self[0], self._curve.p()-self[1], self._curve)", "title": ""}
{"_id": "d7266", "text": "def str_is_well_formed(xml_str):\n    \"\"\"\n  Args:\n    xml_str : str\n      DataONE API XML doc.\n\n  Returns:\n    bool: **True** if XML doc is well formed.\n  \"\"\"\n    try:\n        str_to_etree(xml_str)\n    except xml.etree.ElementTree.ParseError:\n        return False\n    else:\n        return True", "title": ""}
{"_id": "d7267", "text": "def flat_list(lst):\n    \"\"\"This function flatten given nested list.\n    Argument:\n        nested list\n    Returns:\n        flat list\n    \"\"\"\n    if isinstance(lst, list):\n        for item in lst:\n            for i in flat_list(item):\n                yield i\n    else:\n        yield lst", "title": ""}
{"_id": "d7268", "text": "def is_power_of_2(num):\n    \"\"\"Return whether `num` is a power of two\"\"\"\n    log = math.log2(num)\n    return int(log) == float(log)", "title": ""}
{"_id": "d7269", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d7270", "text": "def is_punctuation(text):\n    \"\"\"Check if given string is a punctuation\"\"\"\n    return not (text.lower() in config.AVRO_VOWELS or\n                text.lower() in config.AVRO_CONSONANTS)", "title": ""}
{"_id": "d7271", "text": "def comment (self, s, **args):\n        \"\"\"Write DOT comment.\"\"\"\n        self.write(u\"// \")\n        self.writeln(s=s, **args)", "title": ""}
{"_id": "d7272", "text": "def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model):\n    \"\"\" The how well do the features plus a constant base rate sum up to the model output.\n    \"\"\"\n\n    X_train, X_test = to_array(X_train, X_test)\n\n    # how many features to mask\n    assert X_train.shape[1] == X_test.shape[1]\n\n    # keep nkeep top features and re-train the model for each test explanation\n    yp_test = trained_model.predict(X_test)\n\n    return metric(yp_test, strip_list(attr_test).sum(1))", "title": ""}
{"_id": "d7273", "text": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"React to a docstring event and append contracts to it.\"\"\"\n    # pylint: disable=unused-argument\n    # pylint: disable=too-many-arguments\n    lines.extend(_format_contracts(what=what, obj=obj))", "title": ""}
{"_id": "d7274", "text": "def is_readable_dir(path):\n  \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n  return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d7275", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d7276", "text": "def are_in_interval(s, l, r, border = 'included'):\n        \"\"\"\n        Checks whether all number in the sequence s lie inside the interval formed by\n        l and r.\n        \"\"\"\n        return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s])", "title": ""}
{"_id": "d7277", "text": "def empty_line_count_at_the_end(self):\n        \"\"\"\n        Return number of empty lines at the end of the document.\n        \"\"\"\n        count = 0\n        for line in self.lines[::-1]:\n            if not line or line.isspace():\n                count += 1\n            else:\n                break\n\n        return count", "title": ""}
{"_id": "d7278", "text": "def is_unix_like(platform=None):\n    \"\"\"Returns whether the given platform is a Unix-like platform with the usual\n    Unix filesystem. When the parameter is omitted, it defaults to ``sys.platform``\n    \"\"\"\n    platform = platform or sys.platform\n    platform = platform.lower()\n    return platform.startswith(\"linux\") or platform.startswith(\"darwin\") or \\\n            platform.startswith(\"cygwin\")", "title": ""}
{"_id": "d7279", "text": "def get_uniques(l):\n    \"\"\" Returns a list with no repeated elements.\n    \"\"\"\n    result = []\n\n    for i in l:\n        if i not in result:\n            result.append(i)\n\n    return result", "title": ""}
{"_id": "d7280", "text": "def _clear(self):\n        \"\"\"\n        Helper that clears the composition.\n        \"\"\"\n        draw = ImageDraw.Draw(self._background_image)\n        draw.rectangle(self._device.bounding_box,\n                       fill=\"black\")\n        del draw", "title": ""}
{"_id": "d7281", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d7282", "text": "def forget_coords(self):\n        \"\"\"Forget all loaded coordinates.\"\"\"\n        self.w.ntotal.set_text('0')\n        self.coords_dict.clear()\n        self.redo()", "title": ""}
{"_id": "d7283", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d7284", "text": "def _clear(self):\n        \"\"\"\n        Helper that clears the composition.\n        \"\"\"\n        draw = ImageDraw.Draw(self._background_image)\n        draw.rectangle(self._device.bounding_box,\n                       fill=\"black\")\n        del draw", "title": ""}
{"_id": "d7285", "text": "def denorm(self,arr):\n        \"\"\"Reverse the normalization done to a batch of images.\n\n        Arguments:\n            arr: of shape/size (N,3,sz,sz)\n        \"\"\"\n        if type(arr) is not np.ndarray: arr = to_np(arr)\n        if len(arr.shape)==3: arr = arr[None]\n        return self.transform.denorm(np.rollaxis(arr,1,4))", "title": ""}
{"_id": "d7286", "text": "def _clear(self):\n        \"\"\"\n        Helper that clears the composition.\n        \"\"\"\n        draw = ImageDraw.Draw(self._background_image)\n        draw.rectangle(self._device.bounding_box,\n                       fill=\"black\")\n        del draw", "title": ""}
{"_id": "d7287", "text": "def normalize(name):\n    \"\"\"Normalize name for the Statsd convention\"\"\"\n\n    # Name should not contain some specials chars (issue #1068)\n    ret = name.replace(':', '')\n    ret = ret.replace('%', '')\n    ret = ret.replace(' ', '_')\n\n    return ret", "title": ""}
{"_id": "d7288", "text": "def accel_next(self, *args):\n        \"\"\"Callback to go to the next tab. Called by the accel key.\n        \"\"\"\n        if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n            self.get_notebook().set_current_page(0)\n        else:\n            self.get_notebook().next_page()\n        return True", "title": ""}
{"_id": "d7289", "text": "def test(nose_argsuments):\n    \"\"\" Run application tests \"\"\"\n    from nose import run\n\n    params = ['__main__', '-c', 'nose.ini']\n    params.extend(nose_argsuments)\n    run(argv=params)", "title": ""}
{"_id": "d7290", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d7291", "text": "def isetdiff_flags(list1, list2):\n    \"\"\"\n    move to util_iter\n    \"\"\"\n    set2 = set(list2)\n    return (item not in set2 for item in list1)", "title": ""}
{"_id": "d7292", "text": "def _array2cstr(arr):\n    \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())", "title": ""}
{"_id": "d7293", "text": "def cpp_prog_builder(build_context, target):\n    \"\"\"Build a C++ binary executable\"\"\"\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)", "title": ""}
{"_id": "d7294", "text": "def gday_of_year(self):\n        \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n        return (self.date - dt.date(self.date.year, 1, 1)).days", "title": ""}
{"_id": "d7295", "text": "def compressBuffer(buffer):\n    \"\"\"\n    Note that this code compresses into a buffer held in memory, rather\n    than a disk file. This is done through the use of cStringIO.StringIO().\n    \"\"\"\n    # http://jython.xhaus.com/http-compression-in-python-and-jython/\n    zbuf = cStringIO.StringIO()\n    zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)\n    zfile.write(buffer)\n    zfile.close()\n    return zbuf.getvalue()", "title": ""}
{"_id": "d7296", "text": "def _arrayFromBytes(dataBytes, metadata):\n    \"\"\"Generates and returns a numpy array from raw data bytes.\n\n    :param bytes: raw data bytes as generated by ``numpy.ndarray.tobytes()``\n    :param metadata: a dictionary containing the data type and optionally the\n        shape parameter to reconstruct a ``numpy.array`` from the raw data\n        bytes. ``{\"dtype\": \"float64\", \"shape\": (2, 3)}``\n\n    :returns: ``numpy.array``\n    \"\"\"\n    array = numpy.fromstring(dataBytes, dtype=numpy.typeDict[metadata['dtype']])\n    if 'shape' in metadata:\n        array = array.reshape(metadata['shape'])\n    return array", "title": ""}
{"_id": "d7297", "text": "def parse_s3_url(url):\n    \"\"\"\n    Parses S3 URL.\n\n    Returns bucket (domain) and file (full path).\n    \"\"\"\n    bucket = ''\n    path = ''\n    if url:\n        result = urlparse(url)\n        bucket = result.netloc\n        path = result.path.strip('/')\n    return bucket, path", "title": ""}
{"_id": "d7298", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d7299", "text": "def int_to_date(date):\n    \"\"\"\n    Convert an int of form yyyymmdd to a python date object.\n    \"\"\"\n\n    year = date // 10**4\n    month = date % 10**4 // 10**2\n    day = date % 10**2\n\n    return datetime.date(year, month, day)", "title": ""}
{"_id": "d7300", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d7301", "text": "def _read_stream_for_size(stream, buf_size=65536):\n    \"\"\"Reads a stream discarding the data read and returns its size.\"\"\"\n    size = 0\n    while True:\n        buf = stream.read(buf_size)\n        size += len(buf)\n        if not buf:\n            break\n    return size", "title": ""}
{"_id": "d7302", "text": "def _numpy_bytes_to_char(arr):\n    \"\"\"Like netCDF4.stringtochar, but faster and more flexible.\n    \"\"\"\n    # ensure the array is contiguous\n    arr = np.array(arr, copy=False, order='C', dtype=np.string_)\n    return arr.reshape(arr.shape + (1,)).view('S1')", "title": ""}
{"_id": "d7303", "text": "def movingaverage(arr, window):\n    \"\"\"\n    Calculates the moving average (\"rolling mean\") of an array\n    of a certain window size.\n    \"\"\"\n    m = np.ones(int(window)) / int(window)\n    return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')", "title": ""}
{"_id": "d7304", "text": "def log_magnitude_spectrum(frames):\n    \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))", "title": ""}
{"_id": "d7305", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d7306", "text": "def list2string (inlist,delimit=' '):\n    \"\"\"\nConverts a 1D list to a single long string for file output, using\nthe string.join function.\n\nUsage:   list2string (inlist,delimit=' ')\nReturns: the string created from inlist\n\"\"\"\n    stringlist = [makestr(_) for _ in inlist]\n    return string.join(stringlist,delimit)", "title": ""}
{"_id": "d7307", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d7308", "text": "def Exponential(x, a, tau, y0):\n    \"\"\"Exponential function\n\n    Inputs:\n    -------\n        ``x``: independent variable\n        ``a``: scaling factor\n        ``tau``: time constant\n        ``y0``: additive constant\n\n    Formula:\n    --------\n        ``a*exp(x/tau)+y0``\n    \"\"\"\n    return np.exp(x / tau) * a + y0", "title": ""}
{"_id": "d7309", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d7310", "text": "def inverseHistogram(hist, bin_range):\n    \"\"\"sample data from given histogram and min, max values within range\n\n    Returns:\n        np.array: data that would create the same histogram as given\n    \"\"\"\n    data = hist.astype(float) / np.min(hist[np.nonzero(hist)])\n    new_data = np.empty(shape=np.sum(data, dtype=int))\n    i = 0\n    xvals = np.linspace(bin_range[0], bin_range[1], len(data))\n    for d, x in zip(data, xvals):\n        new_data[i:i + d] = x\n        i += int(d)\n    return new_data", "title": ""}
{"_id": "d7311", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d7312", "text": "def setupLogFile(self):\n\t\t\"\"\"Set up the logging file for a new session- include date and some whitespace\"\"\"\n\t\tself.logWrite(\"\\n###############################################\")\n\t\tself.logWrite(\"calcpkg.py log from \" + str(datetime.datetime.now()))\n\t\tself.changeLogging(True)", "title": ""}
{"_id": "d7313", "text": "def normalized(vector):\n    \"\"\"\n    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.\n    \"\"\"\n    length = numpy.sum(vector * vector, axis=-1)\n    length = numpy.sqrt(length.reshape(length.shape + (1, )))\n    return vector / length", "title": ""}
{"_id": "d7314", "text": "def _to_array(value):\n    \"\"\"As a convenience, turn Python lists and tuples into NumPy arrays.\"\"\"\n    if isinstance(value, (tuple, list)):\n        return array(value)\n    elif isinstance(value, (float, int)):\n        return np.float64(value)\n    else:\n        return value", "title": ""}
{"_id": "d7315", "text": "def get_oauth_token():\n    \"\"\"Retrieve a simple OAuth Token for use with the local http client.\"\"\"\n    url = \"{0}/token\".format(DEFAULT_ORIGIN[\"Origin\"])\n    r = s.get(url=url)\n    return r.json()[\"t\"]", "title": ""}
{"_id": "d7316", "text": "def connected_socket(address, timeout=3):\n    \"\"\" yields a connected socket \"\"\"\n    sock = socket.create_connection(address, timeout)\n    yield sock\n    sock.close()", "title": ""}
{"_id": "d7317", "text": "def Serializable(o):\n    \"\"\"Make sure an object is JSON-serializable\n    Use this to return errors and other info that does not need to be\n    deserialized or does not contain important app data. Best for returning\n    error info and such\"\"\"\n    if isinstance(o, (str, dict, int)):\n        return o\n    else:\n        try:\n            json.dumps(o)\n            return o\n        except Exception:\n            LOG.debug(\"Got a non-serilizeable object: %s\" % o)\n            return o.__repr__()", "title": ""}
{"_id": "d7318", "text": "def updateFromKwargs(self, properties, kwargs, collector, **unused):\n        \"\"\"Primary entry point to turn 'kwargs' into 'properties'\"\"\"\n        properties[self.name] = self.getFromKwargs(kwargs)", "title": ""}
{"_id": "d7319", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d7320", "text": "def add_blank_row(self, label):\n        \"\"\"\n        Add a blank row with only an index value to self.df.\n        This is done inplace.\n        \"\"\"\n        col_labels = self.df.columns\n        blank_item = pd.Series({}, index=col_labels, name=label)\n        # use .loc to add in place (append won't do that)\n        self.df.loc[blank_item.name] = blank_item\n        return self.df", "title": ""}
{"_id": "d7321", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d7322", "text": "def linearRegressionAnalysis(series):\n    \"\"\"\n    Returns factor and offset of linear regression function by least\n    squares method.\n\n    \"\"\"\n    n = safeLen(series)\n    sumI = sum([i for i, v in enumerate(series) if v is not None])\n    sumV = sum([v for i, v in enumerate(series) if v is not None])\n    sumII = sum([i * i for i, v in enumerate(series) if v is not None])\n    sumIV = sum([i * v for i, v in enumerate(series) if v is not None])\n    denominator = float(n * sumII - sumI * sumI)\n    if denominator == 0:\n        return None\n    else:\n        factor = (n * sumIV - sumI * sumV) / denominator / series.step\n        offset = sumII * sumV - sumIV * sumI\n        offset = offset / denominator - factor * series.start\n        return factor, offset", "title": ""}
{"_id": "d7323", "text": "def json_serial(obj):\n    \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n    if isinstance(obj, LegipyModel):\n        return obj.to_json()\n    elif isinstance(obj, (datetime.date, datetime.datetime)):\n        return obj.isoformat()\n    raise TypeError(\"Type {0} not serializable\".format(repr(type(obj))))", "title": ""}
{"_id": "d7324", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d7325", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d7326", "text": "def delete_index(index):\n    \"\"\"Delete index entirely (removes all documents and mapping).\"\"\"\n    logger.info(\"Deleting search index: '%s'\", index)\n    client = get_client()\n    return client.indices.delete(index=index)", "title": ""}
{"_id": "d7327", "text": "def time2seconds(t):\n    \"\"\"Returns seconds since 0h00.\"\"\"\n    return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6", "title": ""}
{"_id": "d7328", "text": "def clear(self):\n        \"\"\"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.\n\n        \"\"\"\n        self.adj.clear()\n        self.node.clear()\n        self.graph.clear()", "title": ""}
{"_id": "d7329", "text": "def fit_linear(X, y):\n    \"\"\"\n    Uses OLS to fit the regression.\n    \"\"\"\n    model = linear_model.LinearRegression()\n    model.fit(X, y)\n    return model", "title": ""}
{"_id": "d7330", "text": "def is_palindrome(string, strict=True):\n    \"\"\"\n    Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n    :param string: String to check.\n    :type string: str\n    :param strict: True if white spaces matter (default), false otherwise.\n    :type strict: bool\n    :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\n    False otherwise\n    \"\"\"\n    if is_full_string(string):\n        if strict:\n            return reverse(string) == string\n        return is_palindrome(SPACES_RE.sub('', string))\n    return False", "title": ""}
{"_id": "d7331", "text": "def to_one_hot(dataY):\n    \"\"\"Convert the vector of labels dataY into one-hot encoding.\n\n    :param dataY: vector of labels\n    :return: one-hot encoded labels\n    \"\"\"\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", "title": ""}
{"_id": "d7332", "text": "def is_palindrome(string, strict=True):\n    \"\"\"\n    Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n    :param string: String to check.\n    :type string: str\n    :param strict: True if white spaces matter (default), false otherwise.\n    :type strict: bool\n    :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\n    False otherwise\n    \"\"\"\n    if is_full_string(string):\n        if strict:\n            return reverse(string) == string\n        return is_palindrome(SPACES_RE.sub('', string))\n    return False", "title": ""}
{"_id": "d7333", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d7334", "text": "def mouse_get_pos():\n    \"\"\"\n\n    :return:\n    \"\"\"\n    p = POINT()\n    AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))\n    return p.x, p.y", "title": ""}
{"_id": "d7335", "text": "def uint8sc(im):\n    \"\"\"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\n    \"\"\"\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)", "title": ""}
{"_id": "d7336", "text": "def get_encoding(binary):\n    \"\"\"Return the encoding type.\"\"\"\n\n    try:\n        from chardet import detect\n    except ImportError:\n        LOGGER.error(\"Please install the 'chardet' module\")\n        sys.exit(1)\n\n    encoding = detect(binary).get('encoding')\n\n    return 'iso-8859-1' if encoding == 'CP949' else encoding", "title": ""}
{"_id": "d7337", "text": "def Date(value):\n    \"\"\"Custom type for managing dates in the command-line.\"\"\"\n    from datetime import datetime\n    try:\n        return datetime(*reversed([int(val) for val in value.split('/')]))\n    except Exception as err:\n        raise argparse.ArgumentTypeError(\"invalid date '%s'\" % value)", "title": ""}
{"_id": "d7338", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d7339", "text": "def _index_ordering(redshift_list):\n        \"\"\"\n\n        :param redshift_list: list of redshifts\n        :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n        \"\"\"\n        redshift_list = np.array(redshift_list)\n        sort_index = np.argsort(redshift_list)\n        return sort_index", "title": ""}
{"_id": "d7340", "text": "def unproject(self, xy):\n        \"\"\"\n        Returns the coordinates from position in meters\n        \"\"\"\n        (x, y) = xy\n        lng = x/EARTH_RADIUS * RAD_TO_DEG\n        lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG\n        return (lng, lat)", "title": ""}
{"_id": "d7341", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d7342", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d7343", "text": "def pad_hex(value, bit_size):\n    \"\"\"\n    Pads a hex string up to the given bit_size\n    \"\"\"\n    value = remove_0x_prefix(value)\n    return add_0x_prefix(value.zfill(int(bit_size / 4)))", "title": ""}
{"_id": "d7344", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d7345", "text": "def clean_time(time_string):\n    \"\"\"Return a datetime from the Amazon-provided datetime string\"\"\"\n    # Get a timezone-aware datetime object from the string\n    time = dateutil.parser.parse(time_string)\n    if not settings.USE_TZ:\n        # If timezone support is not active, convert the time to UTC and\n        # remove the timezone field\n        time = time.astimezone(timezone.utc).replace(tzinfo=None)\n    return time", "title": ""}
{"_id": "d7346", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d7347", "text": "def parse_host_port (host_port):\n    \"\"\"Parse a host:port string into separate components.\"\"\"\n    host, port = urllib.splitport(host_port.strip())\n    if port is not None:\n        if urlutil.is_numeric_port(port):\n            port = int(port)\n    return host, port", "title": ""}
{"_id": "d7348", "text": "def get_in_samples(samples, fn):\n    \"\"\"\n    for a list of samples, return the value of a global option\n    \"\"\"\n    for sample in samples:\n        sample = to_single_data(sample)\n        if fn(sample, None):\n            return fn(sample)\n    return None", "title": ""}
{"_id": "d7349", "text": "def clean_markdown(text):\n    \"\"\"\n    Parse markdown sintaxt to html.\n    \"\"\"\n    result = text\n\n    if isinstance(text, str):\n        result = ''.join(\n            BeautifulSoup(markdown(text), 'lxml').findAll(text=True))\n\n    return result", "title": ""}
{"_id": "d7350", "text": "def _connection_failed(self, error=\"Error not specified!\"):\n        \"\"\"Clean up after connection failure detected.\"\"\"\n        if not self._error:\n            LOG.error(\"Connection failed: %s\", str(error))\n            self._error = error", "title": ""}
{"_id": "d7351", "text": "def md_to_text(content):\n    \"\"\" Converts markdown content to text \"\"\"\n    text = None\n    html = markdown.markdown(content)\n    if html:\n        text = html_to_text(content)\n    return text", "title": ""}
{"_id": "d7352", "text": "def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model):\n    \"\"\" The how well do the features plus a constant base rate sum up to the model output.\n    \"\"\"\n\n    X_train, X_test = to_array(X_train, X_test)\n\n    # how many features to mask\n    assert X_train.shape[1] == X_test.shape[1]\n\n    # keep nkeep top features and re-train the model for each test explanation\n    yp_test = trained_model.predict(X_test)\n\n    return metric(yp_test, strip_list(attr_test).sum(1))", "title": ""}
{"_id": "d7353", "text": "def read_proto_object(fobj, klass):\n    \"\"\"Read a block of data and parse using the given protobuf object.\"\"\"\n    log.debug('%s chunk', klass.__name__)\n    obj = klass()\n    obj.ParseFromString(read_block(fobj))\n    log.debug('Header: %s', str(obj))\n    return obj", "title": ""}
{"_id": "d7354", "text": "def _remove_keywords(d):\n    \"\"\"\n    copy the dict, filter_keywords\n\n    Parameters\n    ----------\n    d : dict\n    \"\"\"\n    return { k:v for k, v in iteritems(d) if k not in RESERVED }", "title": ""}
{"_id": "d7355", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d7356", "text": "def bash(filename):\n    \"\"\"Runs a bash script in the local directory\"\"\"\n    sys.stdout.flush()\n    subprocess.call(\"bash {}\".format(filename), shell=True)", "title": ""}
{"_id": "d7357", "text": "def main(args=sys.argv):\n    \"\"\"\n    main entry point for the jardiff CLI\n    \"\"\"\n\n    parser = create_optparser(args[0])\n    return cli(parser.parse_args(args[1:]))", "title": ""}
{"_id": "d7358", "text": "def run_command(cmd, *args):\n    \"\"\"\n    Runs command on the system with given ``args``.\n    \"\"\"\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", "title": ""}
{"_id": "d7359", "text": "def _render_table(data, fields=None):\n  \"\"\" Helper to render a list of dictionaries as an HTML display object. \"\"\"\n  return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))", "title": ""}
{"_id": "d7360", "text": "def extract_table_names(query):\n    \"\"\" Extract table names from an SQL query. \"\"\"\n    # a good old fashioned regex. turns out this worked better than actually parsing the code\n    tables_blocks = re.findall(r'(?:FROM|JOIN)\\s+(\\w+(?:\\s*,\\s*\\w+)*)', query, re.IGNORECASE)\n    tables = [tbl\n              for block in tables_blocks\n              for tbl in re.findall(r'\\w+', block)]\n    return set(tables)", "title": ""}
{"_id": "d7361", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d7362", "text": "def extract_table_names(query):\n    \"\"\" Extract table names from an SQL query. \"\"\"\n    # a good old fashioned regex. turns out this worked better than actually parsing the code\n    tables_blocks = re.findall(r'(?:FROM|JOIN)\\s+(\\w+(?:\\s*,\\s*\\w+)*)', query, re.IGNORECASE)\n    tables = [tbl\n              for block in tables_blocks\n              for tbl in re.findall(r'\\w+', block)]\n    return set(tables)", "title": ""}
{"_id": "d7363", "text": "def OnPasteAs(self, event):\n        \"\"\"Clipboard paste as event handler\"\"\"\n\n        data = self.main_window.clipboard.get_clipboard()\n        key = self.main_window.grid.actions.cursor\n\n        with undo.group(_(\"Paste As...\")):\n            self.main_window.actions.paste_as(key, data)\n\n        self.main_window.grid.ForceRefresh()\n\n        event.Skip()", "title": ""}
{"_id": "d7364", "text": "def _value_to_color(value, cmap):\n    \"\"\"Convert a value in the range [0,1] to an RGB tuple using a colormap.\"\"\"\n    cm = plt.get_cmap(cmap)\n    rgba = cm(value)\n    return [int(round(255*v)) for v in rgba[0:3]]", "title": ""}
{"_id": "d7365", "text": "def data_directory():\n    \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")", "title": ""}
{"_id": "d7366", "text": "def _rank(self, ranking, n):\n    \"\"\" return the first n sentences with highest ranking \"\"\"\n    return nlargest(n, ranking, key=ranking.get)", "title": ""}
{"_id": "d7367", "text": "def debug_on_error(type, value, tb):\n    \"\"\"Code due to Thomas Heller - published in Python Cookbook (O'Reilley)\"\"\"\n    traceback.print_exc(type, value, tb)\n    print()\n    pdb.pm()", "title": ""}
{"_id": "d7368", "text": "def _put_header(self):\n        \"\"\" Standard first line in a PDF. \"\"\"\n        self.session._out('%%PDF-%s' % self.pdf_version)\n        if self.session.compression:\n            self.session.buffer += '%' + chr(235) + chr(236) + chr(237) + chr(238) + \"\\n\"", "title": ""}
{"_id": "d7369", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d7370", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d7371", "text": "def fix_call(callable, *args, **kw):\n    \"\"\"\n    Call ``callable(*args, **kw)`` fixing any type errors that come out.\n    \"\"\"\n    try:\n        val = callable(*args, **kw)\n    except TypeError:\n        exc_info = fix_type_error(None, callable, args, kw)\n        reraise(*exc_info)\n    return val", "title": ""}
{"_id": "d7372", "text": "def cor(y_true, y_pred):\n    \"\"\"Compute Pearson correlation coefficient.\n    \"\"\"\n    y_true, y_pred = _mask_nan(y_true, y_pred)\n    return np.corrcoef(y_true, y_pred)[0, 1]", "title": ""}
{"_id": "d7373", "text": "def make_2d(ary):\n    \"\"\"Convert any array into a 2d numpy array.\n\n    In case the array is already more than 2 dimensional, will ravel the\n    dimensions after the first.\n    \"\"\"\n    dim_0, *_ = np.atleast_1d(ary).shape\n    return ary.reshape(dim_0, -1, order=\"F\")", "title": ""}
{"_id": "d7374", "text": "def topk(arg, k, by=None):\n    \"\"\"\n    Returns\n    -------\n    topk : TopK filter expression\n    \"\"\"\n    op = ops.TopK(arg, k, by=by)\n    return op.to_expr()", "title": ""}
{"_id": "d7375", "text": "def flatten( iterables ):\n    \"\"\" Flatten an iterable, except for string elements. \"\"\"\n    for it in iterables:\n        if isinstance(it, str):\n            yield it\n        else:\n            for element in it:\n                yield element", "title": ""}
{"_id": "d7376", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d7377", "text": "def set_stop_handler(self):\n        \"\"\"\n        Initializes functions that are invoked when the user or OS wants to kill this process.\n        :return:\n        \"\"\"\n        signal.signal(signal.SIGTERM, self.graceful_stop)\n        signal.signal(signal.SIGABRT, self.graceful_stop)\n        signal.signal(signal.SIGINT, self.graceful_stop)", "title": ""}
{"_id": "d7378", "text": "def _openResources(self):\n        \"\"\" Uses numpy.load to open the underlying file\n        \"\"\"\n        arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n        check_is_an_array(arr)\n        self._array = arr", "title": ""}
{"_id": "d7379", "text": "def fixed(ctx, number, decimals=2, no_commas=False):\n    \"\"\"\n    Formats the given number in decimal format using a period and commas\n    \"\"\"\n    value = _round(ctx, number, decimals)\n    format_str = '{:f}' if no_commas else '{:,f}'\n    return format_str.format(value)", "title": ""}
{"_id": "d7380", "text": "def focus(self):\n        \"\"\"\n        Call this to give this Widget the input focus.\n        \"\"\"\n        self._has_focus = True\n        self._frame.move_to(self._x, self._y, self._h)\n        if self._on_focus is not None:\n            self._on_focus()", "title": ""}
{"_id": "d7381", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d7382", "text": "def GeneratePassphrase(length=20):\n  \"\"\"Create a 20 char passphrase with easily typeable chars.\"\"\"\n  valid_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  valid_chars += \"0123456789 ,-_&$#\"\n  return \"\".join(random.choice(valid_chars) for i in range(length))", "title": ""}
{"_id": "d7383", "text": "def polyline(self, arr):\n        \"\"\"Draw a set of lines\"\"\"\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])", "title": ""}
{"_id": "d7384", "text": "def random_numbers(n):\n    \"\"\"\n    Generate a random string from 0-9\n    :param n: length of the string\n    :return: the random string\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(string.digits) for _ in range(n))", "title": ""}
{"_id": "d7385", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d7386", "text": "def lognorm(x, mu, sigma=1.0):\n    \"\"\" Log-normal function from scipy \"\"\"\n    return stats.lognorm(sigma, scale=mu).pdf(x)", "title": ""}
{"_id": "d7387", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d7388", "text": "def generate_uuid():\n    \"\"\"Generate a UUID.\"\"\"\n    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)\n    return r_uuid.decode().replace('=', '')", "title": ""}
{"_id": "d7389", "text": "def _linear_seaborn_(self, label=None, style=None, opts=None):\n        \"\"\"\n        Returns a Seaborn linear regression plot\n        \"\"\"\n        xticks, yticks = self._get_ticks(opts)\n        try:\n            fig = sns.lmplot(self.x, self.y, data=self.df)\n            fig = self._set_with_height(fig, opts)\n            return fig\n        except Exception as e:\n            self.err(e, self.linear_,\n                     \"Can not draw linear regression chart\")", "title": ""}
{"_id": "d7390", "text": "def make_unique_ngrams(s, n):\n    \"\"\"Make a set of unique n-grams from a string.\"\"\"\n    return set(s[i:i + n] for i in range(len(s) - n + 1))", "title": ""}
{"_id": "d7391", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d7392", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d7393", "text": "def oplot(self, x, y, **kw):\n        \"\"\"generic plotting method, overplotting any existing plot \"\"\"\n        self.panel.oplot(x, y, **kw)", "title": ""}
{"_id": "d7394", "text": "def get_available_gpus():\n  \"\"\"\n  Returns a list of string names of all available GPUs\n  \"\"\"\n  local_device_protos = device_lib.list_local_devices()\n  return [x.name for x in local_device_protos if x.device_type == 'GPU']", "title": ""}
{"_id": "d7395", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d7396", "text": "def dates_in_range(start_date, end_date):\n    \"\"\"Returns all dates between two dates.\n\n    Inclusive of the start date but not the end date.\n\n    Args:\n        start_date (datetime.date)\n        end_date (datetime.date)\n\n    Returns:\n        (list) of datetime.date objects\n    \"\"\"\n    return [\n        start_date + timedelta(n)\n        for n in range(int((end_date - start_date).days))\n    ]", "title": ""}
{"_id": "d7397", "text": "def pprint(self, stream=None, indent=1, width=80, depth=None):\n    \"\"\"\n    Pretty print the underlying literal Python object\n    \"\"\"\n    pp.pprint(to_literal(self), stream, indent, width, depth)", "title": ""}
{"_id": "d7398", "text": "def get_column_keys_and_names(table):\n    \"\"\"\n    Return a generator of tuples k, c such that k is the name of the python attribute for\n    the column and c is the name of the column in the sql table.\n    \"\"\"\n    ins = inspect(table)\n    return ((k, c.name) for k, c in ins.mapper.c.items())", "title": ""}
{"_id": "d7399", "text": "def print_matrix(X, decimals=1):\n    \"\"\"Pretty printing for numpy matrix X\"\"\"\n    for row in np.round(X, decimals=decimals):\n        print(row)", "title": ""}
{"_id": "d7400", "text": "def get_base_dir():\n    \"\"\"\n    Return the base directory\n    \"\"\"\n    return os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]", "title": ""}
{"_id": "d7401", "text": "def get_single_value(d):\n    \"\"\"Get a value from a dict which contains just one item.\"\"\"\n    assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)\n    return next(six.itervalues(d))", "title": ""}
{"_id": "d7402", "text": "def format_prettytable(table):\n    \"\"\"Converts SoftLayer.CLI.formatting.Table instance to a prettytable.\"\"\"\n    for i, row in enumerate(table.rows):\n        for j, item in enumerate(row):\n            table.rows[i][j] = format_output(item)\n\n    ptable = table.prettytable()\n    ptable.hrules = prettytable.FRAME\n    ptable.horizontal_char = '.'\n    ptable.vertical_char = ':'\n    ptable.junction_char = ':'\n    return ptable", "title": ""}
{"_id": "d7403", "text": "def diff(file_, imports):\n    \"\"\"Display the difference between modules in a file and imported modules.\"\"\"\n    modules_not_imported = compare_modules(file_, imports)\n\n    logging.info(\"The following modules are in {} but do not seem to be imported: \"\n                 \"{}\".format(file_, \", \".join(x for x in modules_not_imported)))", "title": ""}
{"_id": "d7404", "text": "def disable_stdout_buffering():\n    \"\"\"This turns off stdout buffering so that outputs are immediately\n    materialized and log messages show up before the program exits\"\"\"\n    stdout_orig = sys.stdout\n    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n    # NOTE(brandyn): This removes the original stdout\n    return stdout_orig", "title": ""}
{"_id": "d7405", "text": "def get_combined_size(tiles):\n    \"\"\"Calculate combined size of tiles.\"\"\"\n    # TODO: Refactor calculating layout to avoid repetition.\n    columns, rows = calc_columns_rows(len(tiles))\n    tile_size = tiles[0].image.size\n    return (tile_size[0] * columns, tile_size[1] * rows)", "title": ""}
{"_id": "d7406", "text": "def cli(env):\n    \"\"\"Show current configuration.\"\"\"\n\n    settings = config.get_settings_from_client(env.client)\n    env.fout(config.config_table(settings))", "title": ""}
{"_id": "d7407", "text": "def get_md5_for_file(file):\n    \"\"\"Get the md5 hash for a file.\n\n    :param file: the file to get the md5 hash for\n    \"\"\"\n    md5 = hashlib.md5()\n\n    while True:\n        data = file.read(md5.block_size)\n\n        if not data:\n            break\n\n        md5.update(data)\n\n    return md5.hexdigest()", "title": ""}
{"_id": "d7408", "text": "def show():\n    \"\"\"Show (print out) current environment variables.\"\"\"\n    env = get_environment()\n\n    for key, val in sorted(env.env.items(), key=lambda item: item[0]):\n        click.secho('%s = %s' % (key, val))", "title": ""}
{"_id": "d7409", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d7410", "text": "def _prtstr(self, obj, dashes):\n        \"\"\"Print object information using a namedtuple and a format pattern.\"\"\"\n        self.prt.write('{DASHES:{N}}'.format(\n            DASHES=self.fmt_dashes.format(DASHES=dashes, ID=obj.item_id),\n            N=self.dash_len))\n        self.prt.write(\"{INFO}\\n\".format(INFO=str(obj)))", "title": ""}
{"_id": "d7411", "text": "def globlookup(pattern, root):\n    \"\"\"globlookup finds filesystem objects whose relative path matches the\n    given pattern.\n\n    :param pattern: The pattern to wish to match relative filepaths to.\n    :param root: The root director to search within.\n\n    \"\"\"\n    for subdir, dirnames, filenames in os.walk(root):\n        d = subdir[len(root) + 1:]\n        files = (os.path.join(d, f) for f in filenames)\n        for f in fnmatch.filter(files, pattern):\n            yield f", "title": ""}
{"_id": "d7412", "text": "def debug(ftn, txt):\n    \"\"\"Used for debugging.\"\"\"\n    if debug_p:\n        sys.stdout.write(\"{0}.{1}:{2}\\n\".format(modname, ftn, txt))\n        sys.stdout.flush()", "title": ""}
{"_id": "d7413", "text": "def get_month_start(day=None):\n    \"\"\"Returns the first day of the given month.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(day=1)", "title": ""}
{"_id": "d7414", "text": "def process_instance(self, instance):\n        self.log.debug(\"e = mc^2\")\n        self.log.info(\"About to fail..\")\n        self.log.warning(\"Failing.. soooon..\")\n        self.log.critical(\"Ok, you're done.\")\n        assert False, \"\"\"ValidateFailureMock was destined to fail..\n\nHere's some extended information about what went wrong.\n\nIt has quite the long string associated with it, including\na few newlines and a list.\n\n- Item 1\n- Item 2\n\n\"\"\"", "title": ""}
{"_id": "d7415", "text": "def init_checks_registry():\n    \"\"\"Register all globally visible functions.\n\n    The first argument name is either 'physical_line' or 'logical_line'.\n    \"\"\"\n    mod = inspect.getmodule(register_check)\n    for (name, function) in inspect.getmembers(mod, inspect.isfunction):\n        register_check(function)", "title": ""}
{"_id": "d7416", "text": "def _prtfmt(self, item_id, dashes):\n        \"\"\"Print object information using a namedtuple and a format pattern.\"\"\"\n        ntprt = self.id2nt[item_id]\n        dct = ntprt._asdict()\n        self.prt.write('{DASHES:{N}}'.format(\n            DASHES=self.fmt_dashes.format(DASHES=dashes, ID=self.nm2prtfmt['ID'].format(**dct)),\n            N=self.dash_len))\n        self.prt.write(\"{INFO}\\n\".format(INFO=self.nm2prtfmt['ITEM'].format(**dct)))", "title": ""}
{"_id": "d7417", "text": "def get_memory_usage():\n    \"\"\"Gets RAM memory usage\n\n    :return: MB of memory used by this process\n    \"\"\"\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info().rss\n    return mem / (1024 * 1024)", "title": ""}
{"_id": "d7418", "text": "def print_tree(self, indent=2):\n        \"\"\" print_tree: prints out structure of tree\n            Args: indent (int): What level of indentation at which to start printing\n            Returns: None\n        \"\"\"\n        config.LOGGER.info(\"{indent}{data}\".format(indent=\"   \" * indent, data=str(self)))\n        for child in self.children:\n            child.print_tree(indent + 1)", "title": ""}
{"_id": "d7419", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d7420", "text": "def imp_print(self, text, end):\n\t\t\"\"\"Directly send utf8 bytes to stdout\"\"\"\n\t\tsys.stdout.write((text + end).encode(\"utf-8\"))", "title": ""}
{"_id": "d7421", "text": "def get_week_start_end_day():\n    \"\"\"\n    Get the week start date and end date\n    \"\"\"\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))", "title": ""}
{"_id": "d7422", "text": "def is_alive(self):\n        \"\"\"\n        @rtype:  bool\n        @return: C{True} if the process is currently running.\n        \"\"\"\n        try:\n            self.wait(0)\n        except WindowsError:\n            e = sys.exc_info()[1]\n            return e.winerror == win32.WAIT_TIMEOUT\n        return False", "title": ""}
{"_id": "d7423", "text": "def string_input(prompt=''):\n    \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n    v = sys.version[0]\n    if v == '3':\n        return input(prompt)\n    else:\n        return raw_input(prompt)", "title": ""}
{"_id": "d7424", "text": "def kill_mprocess(process):\n    \"\"\"kill process\n    Args:\n        process - Popen object for process\n    \"\"\"\n    if process and proc_alive(process):\n        process.terminate()\n        process.communicate()\n    return not proc_alive(process)", "title": ""}
{"_id": "d7425", "text": "def _strip_namespace(self, xml):\n        \"\"\"strips any namespaces from an xml string\"\"\"\n        p = re.compile(b\"xmlns=*[\\\"\\\"][^\\\"\\\"]*[\\\"\\\"]\")\n        allmatches = p.finditer(xml)\n        for match in allmatches:\n            xml = xml.replace(match.group(), b\"\")\n        return xml", "title": ""}
{"_id": "d7426", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d7427", "text": "def ave_list_v3(vec_list):\n    \"\"\"Return the average vector of a list of vectors.\"\"\"\n\n    vec = Vec3(0, 0, 0)\n    for v in vec_list:\n        vec += v\n    num_vecs = float(len(vec_list))\n    vec = Vec3(vec.x / num_vecs, vec.y / num_vecs, vec.z / num_vecs)\n    return vec", "title": ""}
{"_id": "d7428", "text": "def inheritdoc(method):\n    \"\"\"Set __doc__ of *method* to __doc__ of *method* in its parent class.\n\n    Since this is used on :class:`.StringMixIn`, the \"parent class\" used is\n    ``str``. This function can be used as a decorator.\n    \"\"\"\n    method.__doc__ = getattr(str, method.__name__).__doc__\n    return method", "title": ""}
{"_id": "d7429", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d7430", "text": "def input(self, prompt, default=None, show_default=True):\n        \"\"\"Provide a command prompt.\"\"\"\n        return click.prompt(prompt, default=default, show_default=show_default)", "title": ""}
{"_id": "d7431", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d7432", "text": "def rel_path(filename):\n    \"\"\"\n    Function that gets relative path to the filename\n    \"\"\"\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)", "title": ""}
{"_id": "d7433", "text": "def _set_property(self, val, *args):\n        \"\"\"Private method that sets the value currently of the property\"\"\"\n        val = UserClassAdapter._set_property(self, val, *args)\n        if val:\n            Adapter._set_property(self, val, *args)\n        return val", "title": ""}
{"_id": "d7434", "text": "def lastmod(self, author):\n        \"\"\"Return the last modification of the entry.\"\"\"\n        lastitems = EntryModel.objects.published().order_by('-modification_date').filter(author=author).only('modification_date')\n        return lastitems[0].modification_date", "title": ""}
{"_id": "d7435", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d7436", "text": "def calculate_size(name, data_list):\n    \"\"\" Calculates the request payload size\"\"\"\n    data_size = 0\n    data_size += calculate_size_str(name)\n    data_size += INT_SIZE_IN_BYTES\n    for data_list_item in data_list:\n        data_size += calculate_size_data(data_list_item)\n    return data_size", "title": ""}
{"_id": "d7437", "text": "def message_from_string(s, *args, **kws):\n    \"\"\"Parse a string into a Message object model.\n\n    Optional _class and strict are passed to the Parser constructor.\n    \"\"\"\n    from future.backports.email.parser import Parser\n    return Parser(*args, **kws).parsestr(s)", "title": ""}
{"_id": "d7438", "text": "def _count_leading_whitespace(text):\n  \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n  idx = 0\n  for idx, char in enumerate(text):\n    if not char.isspace():\n      return idx\n  return idx + 1", "title": ""}
{"_id": "d7439", "text": "def IsErrorSuppressedByNolint(category, linenum):\n  \"\"\"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.\n  \"\"\"\n  return (linenum in _error_suppressions.get(category, set()) or\n          linenum in _error_suppressions.get(None, set()))", "title": ""}
{"_id": "d7440", "text": "def _raise_if_wrong_file_signature(stream):\n    \"\"\" Reads the 4 first bytes of the stream to check that is LASF\"\"\"\n    file_sig = stream.read(len(headers.LAS_FILE_SIGNATURE))\n    if file_sig != headers.LAS_FILE_SIGNATURE:\n        raise errors.PylasError(\n            \"File Signature ({}) is not {}\".format(file_sig, headers.LAS_FILE_SIGNATURE)\n        )", "title": ""}
{"_id": "d7441", "text": "def unmatched(match):\n    \"\"\"Return unmatched part of re.Match object.\"\"\"\n    start, end = match.span(0)\n    return match.string[:start]+match.string[end:]", "title": ""}
{"_id": "d7442", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d7443", "text": "def loss(loss_value):\n  \"\"\"Calculates aggregated mean loss.\"\"\"\n  total_loss = tf.Variable(0.0, False)\n  loss_count = tf.Variable(0, False)\n  total_loss_update = tf.assign_add(total_loss, loss_value)\n  loss_count_update = tf.assign_add(loss_count, 1)\n  loss_op = total_loss / tf.cast(loss_count, tf.float32)\n  return [total_loss_update, loss_count_update], loss_op", "title": ""}
{"_id": "d7444", "text": "def create_app():\n    \"\"\"Create a Qt application.\"\"\"\n    global QT_APP\n    QT_APP = QApplication.instance()\n    if QT_APP is None:  # pragma: no cover\n        QT_APP = QApplication(sys.argv)\n    return QT_APP", "title": ""}
{"_id": "d7445", "text": "def dt_to_qdatetime(dt):\n    \"\"\"Convert a python datetime.datetime object to QDateTime\n\n    :param dt: the datetime object\n    :type dt: :class:`datetime.datetime`\n    :returns: the QDateTime conversion\n    :rtype: :class:`QtCore.QDateTime`\n    :raises: None\n    \"\"\"\n    return QtCore.QDateTime(QtCore.QDate(dt.year, dt.month, dt.day),\n                            QtCore.QTime(dt.hour, dt.minute, dt.second))", "title": ""}
{"_id": "d7446", "text": "def unique_items(seq):\n    \"\"\"Return the unique items from iterable *seq* (in order).\"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d7447", "text": "def done(self, result):\n        \"\"\"save the geometry before dialog is close to restore it later\"\"\"\n        self._geometry = self.geometry()\n        QtWidgets.QDialog.done(self, result)", "title": ""}
{"_id": "d7448", "text": "def unique_element(ll):\n    \"\"\" returns unique elements from a list preserving the original order \"\"\"\n    seen = {}\n    result = []\n    for item in ll:\n        if item in seen:\n            continue\n        seen[item] = 1\n        result.append(item)\n    return result", "title": ""}
{"_id": "d7449", "text": "def resize(self, width, height):\n        \"\"\"\n        Pyqt specific resize callback.\n        \"\"\"\n        if not self.fbo:\n            return\n\n        # pyqt reports sizes in actual buffer size\n        self.width = width // self.widget.devicePixelRatio()\n        self.height = height // self.widget.devicePixelRatio()\n        self.buffer_width = width\n        self.buffer_height = height\n\n        super().resize(width, height)", "title": ""}
{"_id": "d7450", "text": "def unique_(self, col):\n        \"\"\"\n        Returns unique values in a column\n        \"\"\"\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\")", "title": ""}
{"_id": "d7451", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d7452", "text": "def array_size(x, axis):\n  \"\"\"Calculate the size of `x` along `axis` dimensions only.\"\"\"\n  axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)\n  return max(numpy.prod(axis_shape), 1)", "title": ""}
{"_id": "d7453", "text": "def deinit(self):\n        \"\"\"Deinitialises the PulseIn and releases any hardware and software\n        resources for reuse.\"\"\"\n        # Clean up after ourselves\n        self._process.terminate()\n        procs.remove(self._process)\n        self._mq.remove()\n        queues.remove(self._mq)", "title": ""}
{"_id": "d7454", "text": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "title": ""}
{"_id": "d7455", "text": "def wait_until_exit(self):\n        \"\"\" Wait until all the threads are finished.\n\n        \"\"\"\n        [t.join() for t in self.threads]\n\n        self.threads = list()", "title": ""}
{"_id": "d7456", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d7457", "text": "def exec_rabbitmqctl(self, command, args=[], rabbitmqctl_opts=['-q']):\n        \"\"\"\n        Execute a ``rabbitmqctl`` command inside a running container.\n\n        :param command: the command to run\n        :param args: a list of args for the command\n        :param rabbitmqctl_opts:\n            a list of extra options to pass to ``rabbitmqctl``\n        :returns: a tuple of the command exit code and output\n        \"\"\"\n        cmd = ['rabbitmqctl'] + rabbitmqctl_opts + [command] + args\n        return self.inner().exec_run(cmd)", "title": ""}
{"_id": "d7458", "text": "def out(self, output, newline=True):\n        \"\"\"Outputs a string to the console (stdout).\"\"\"\n        click.echo(output, nl=newline)", "title": ""}
{"_id": "d7459", "text": "def gen_random_string(str_len):\n    \"\"\" generate random string with specified length\n    \"\"\"\n    return ''.join(\n        random.choice(string.ascii_letters + string.digits) for _ in range(str_len))", "title": ""}
{"_id": "d7460", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d7461", "text": "def sometimesish(fn):\n    \"\"\"\n    Has a 50/50 chance of calling a function\n    \"\"\"\n    def wrapped(*args, **kwargs):\n        if random.randint(1, 2) == 1:\n            return fn(*args, **kwargs)\n\n    return wrapped", "title": ""}
{"_id": "d7462", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d7463", "text": "def uniform_noise(points):\n    \"\"\"Init a uniform noise variable.\"\"\"\n    return np.random.rand(1) * np.random.uniform(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d7464", "text": "def runiform(lower, upper, size=None):\n    \"\"\"\n    Random uniform variates.\n    \"\"\"\n    return np.random.uniform(lower, upper, size)", "title": ""}
{"_id": "d7465", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d7466", "text": "def SampleSum(dists, n):\n    \"\"\"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\n    \"\"\"\n    pmf = MakePmfFromList(RandomSum(dists) for i in xrange(n))\n    return pmf", "title": ""}
{"_id": "d7467", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d7468", "text": "def _interval_to_bound_points(array):\n    \"\"\"\n    Helper function which returns an array\n    with the Intervals' boundaries.\n    \"\"\"\n\n    array_boundaries = np.array([x.left for x in array])\n    array_boundaries = np.concatenate(\n        (array_boundaries, np.array([array[-1].right])))\n\n    return array_boundaries", "title": ""}
{"_id": "d7469", "text": "def highlight_words(string, keywords, cls_name='highlighted'):\n    \"\"\" Given an list of words, this function highlights the matched words in the given string. \"\"\"\n\n    if not keywords:\n        return string\n    if not string:\n        return ''\n    include, exclude = get_text_tokenizer(keywords)\n    highlighted = highlight_text(include, string, cls_name, words=True)\n    return highlighted", "title": ""}
{"_id": "d7470", "text": "def get_env_default(self, variable, default):\n        \"\"\"\n        Fetch environment variables, returning a default if not found\n        \"\"\"\n        if variable in os.environ:\n            env_var = os.environ[variable]\n        else:\n            env_var = default\n        return env_var", "title": ""}
{"_id": "d7471", "text": "def _normal_prompt(self):\n        \"\"\"\n        Flushes the prompt before requesting the input\n\n        :return: The command line\n        \"\"\"\n        sys.stdout.write(self.__get_ps1())\n        sys.stdout.flush()\n        return safe_input()", "title": ""}
{"_id": "d7472", "text": "def read_string(buff, byteorder='big'):\n    \"\"\"Read a string from a file-like object.\"\"\"\n    length = read_numeric(USHORT, buff, byteorder)\n    return buff.read(length).decode('utf-8')", "title": ""}
{"_id": "d7473", "text": "def api_home(request, key=None, hproPk=None):\n    \"\"\"Show the home page for the API with all methods\"\"\"\n\n    if not check_api_key(request, key, hproPk):\n        return HttpResponseForbidden\n\n    return render_to_response('plugIt/api.html', {}, context_instance=RequestContext(request))", "title": ""}
{"_id": "d7474", "text": "def get_as_string(self, s3_path, encoding='utf-8'):\n        \"\"\"\n        Get the contents of an object stored in S3 as string.\n\n        :param s3_path: URL for target S3 location\n        :param encoding: Encoding to decode bytes to string\n        :return: File contents as a string\n        \"\"\"\n        content = self.get_as_bytes(s3_path)\n        return content.decode(encoding)", "title": ""}
{"_id": "d7475", "text": "def backward_delete_word(self, e): # (Control-Rubout)\n        u\"\"\"Delete the character behind the cursor. A numeric argument means\n        to kill the characters instead of deleting them.\"\"\"\n        self.l_buffer.backward_delete_word(self.argument_reset)\n        self.finalize()", "title": ""}
{"_id": "d7476", "text": "def load_tiff(file):\n    \"\"\"\n    Load a geotiff raster keeping ndv values using a masked array\n\n    Usage:\n            data = load_tiff(file)\n    \"\"\"\n    ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file)\n    data = gdalnumeric.LoadFile(file)\n    data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv)\n    return data", "title": ""}
{"_id": "d7477", "text": "def drag_and_drop(self, droppable):\n        \"\"\"\n        Performs drag a element to another elmenet.\n\n        Currently works only on Chrome driver.\n        \"\"\"\n        self.scroll_to()\n        ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()", "title": ""}
{"_id": "d7478", "text": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "title": ""}
{"_id": "d7479", "text": "def do_EOF(self, args):\n        \"\"\"Exit on system end of file character\"\"\"\n        if _debug: ConsoleCmd._debug(\"do_EOF %r\", args)\n        return self.do_exit(args)", "title": ""}
{"_id": "d7480", "text": "def _read_json_file(self, json_file):\n        \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n        self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n        with open(json_file, 'r') as f:\n            return json.load(f, object_pairs_hook=OrderedDict)", "title": ""}
{"_id": "d7481", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d7482", "text": "def lambda_from_file(python_file):\n    \"\"\"\n    Reads a python file and returns a awslambda.Code object\n    :param python_file:\n    :return:\n    \"\"\"\n    lambda_function = []\n    with open(python_file, 'r') as f:\n        lambda_function.extend(f.read().splitlines())\n\n    return awslambda.Code(ZipFile=(Join('\\n', lambda_function)))", "title": ""}
{"_id": "d7483", "text": "def add_arrow(self, x1, y1, x2, y2, **kws):\n        \"\"\"add arrow to plot\"\"\"\n        self.panel.add_arrow(x1, y1, x2, y2, **kws)", "title": ""}
{"_id": "d7484", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d7485", "text": "def stats(self):\n        \"\"\" shotcut to pull out useful info for interactive use \"\"\"\n        printDebug(\"Classes.....: %d\" % len(self.all_classes))\n        printDebug(\"Properties..: %d\" % len(self.all_properties))", "title": ""}
{"_id": "d7486", "text": "def ReadTif(tifFile):\n        \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n        img = Image.open(tifFile)\n        img = np.array(img)\n        return img", "title": ""}
{"_id": "d7487", "text": "def extract_words(lines):\n    \"\"\"\n    Extract from the given iterable of lines the list of words.\n\n    :param lines: an iterable of lines;\n    :return: a generator of words of lines.\n    \"\"\"\n    for line in lines:\n        for word in re.findall(r\"\\w+\", line):\n            yield word", "title": ""}
{"_id": "d7488", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d7489", "text": "def kwargs_to_string(kwargs):\n    \"\"\"\n    Given a set of kwargs, turns them into a string which can then be passed to a command.\n    :param kwargs: kwargs from a function call.\n    :return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.\n    \"\"\"\n    outstr = ''\n    for arg in kwargs:\n        outstr += ' -{} {}'.format(arg, kwargs[arg])\n    return outstr", "title": ""}
{"_id": "d7490", "text": "def file_to_str(fname):\n    \"\"\"\n    Read a file into a string\n    PRE: fname is a small file (to avoid hogging memory and its discontents)\n    \"\"\"\n    data = None\n    # rU = read with Universal line terminator\n    with open(fname, 'rU') as fd:\n        data = fd.read()\n    return data", "title": ""}
{"_id": "d7491", "text": "def valid_uuid(value):\n    \"\"\" Check if value is a valid UUID. \"\"\"\n\n    try:\n        uuid.UUID(value, version=4)\n        return True\n    except (TypeError, ValueError, AttributeError):\n        return False", "title": ""}
{"_id": "d7492", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d7493", "text": "def seq():\n    \"\"\"\n    Counts up sequentially from a number based on the current time\n\n    :rtype int:\n    \"\"\"\n    current_frame     = inspect.currentframe().f_back\n    trace_string      = \"\"\n    while current_frame.f_back:\n      trace_string = trace_string + current_frame.f_back.f_code.co_name\n      current_frame = current_frame.f_back\n    return counter.get_from_trace(trace_string)", "title": ""}
{"_id": "d7494", "text": "def _write_json(file, contents):\n    \"\"\"Write a dict to a JSON file.\"\"\"\n    with open(file, 'w') as f:\n        return json.dump(contents, f, indent=2, sort_keys=True)", "title": ""}
{"_id": "d7495", "text": "def add_blank_row(self, label):\n        \"\"\"\n        Add a blank row with only an index value to self.df.\n        This is done inplace.\n        \"\"\"\n        col_labels = self.df.columns\n        blank_item = pd.Series({}, index=col_labels, name=label)\n        # use .loc to add in place (append won't do that)\n        self.df.loc[blank_item.name] = blank_item\n        return self.df", "title": ""}
{"_id": "d7496", "text": "def as_dict(self):\n        \"\"\"Return all child objects in nested dict.\"\"\"\n        dicts = [x.as_dict for x in self.children]\n        return {'{0} {1}'.format(self.name, self.value): dicts}", "title": ""}
{"_id": "d7497", "text": "def issorted(list_, op=operator.le):\n    \"\"\"\n    Determines if a list is sorted\n\n    Args:\n        list_ (list):\n        op (func): sorted operation (default=operator.le)\n\n    Returns:\n        bool : True if the list is sorted\n    \"\"\"\n    return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))", "title": ""}
{"_id": "d7498", "text": "def get(self, key):\n        \"\"\"Get a value from the cache.\n\n        Returns None if the key is not in the cache.\n        \"\"\"\n        value = redis_conn.get(key)\n\n        if value is not None:\n            value = pickle.loads(value)\n\n        return value", "title": ""}
{"_id": "d7499", "text": "def type(self):\n        \"\"\"Returns type of the data for the given FeatureType.\"\"\"\n        if self is FeatureType.TIMESTAMP:\n            return list\n        if self is FeatureType.BBOX:\n            return BBox\n        return dict", "title": ""}
{"_id": "d7500", "text": "def __contains__(self, key):\n        \"\"\"Return ``True`` if *key* is present, else ``False``.\"\"\"\n        pickled_key = self._pickle_key(key)\n        return bool(self.redis.hexists(self.key, pickled_key))", "title": ""}
{"_id": "d7501", "text": "def get_memory_usage():\n    \"\"\"Gets RAM memory usage\n\n    :return: MB of memory used by this process\n    \"\"\"\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info().rss\n    return mem / (1024 * 1024)", "title": ""}
{"_id": "d7502", "text": "def get_instance(key, expire=None):\n    \"\"\"Return an instance of RedisSet.\"\"\"\n    global _instances\n    try:\n        instance = _instances[key]\n    except KeyError:\n        instance = RedisSet(\n            key,\n            _redis,\n            expire=expire\n        )\n        _instances[key] = instance\n\n    return instance", "title": ""}
{"_id": "d7503", "text": "def tag(self, nerdoc):\n        \"\"\"Tag the given document.\n        Parameters\n        ----------\n        nerdoc: estnltk.estner.Document\n            The document to be tagged.\n\n        Returns\n        -------\n        labels: list of lists of str\n            Predicted token Labels for each sentence in the document\n        \"\"\"\n\n        labels = []\n        for snt in nerdoc.sentences:\n            xseq = [t.feature_list() for t in snt]\n            yseq = self.tagger.tag(xseq)\n            labels.append(yseq)\n        return labels", "title": ""}
{"_id": "d7504", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d7505", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d7506", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d7507", "text": "async def load_unicode(reader):\n    \"\"\"\n    Loads UTF8 string\n    :param reader:\n    :return:\n    \"\"\"\n    ivalue = await load_uvarint(reader)\n    fvalue = bytearray(ivalue)\n    await reader.areadinto(fvalue)\n    return str(fvalue, 'utf8')", "title": ""}
{"_id": "d7508", "text": "def make_regex(separator):\n    \"\"\"Utility function to create regexp for matching escaped separators\n    in strings.\n\n    \"\"\"\n    return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +\n                      re.escape(separator) + r'\\\\]|\\\\.)+)')", "title": ""}
{"_id": "d7509", "text": "def on_IOError(self, e):\n        \"\"\" Handle an IOError exception. \"\"\"\n\n        sys.stderr.write(\"Error: %s: \\\"%s\\\"\\n\" % (e.strerror, e.filename))", "title": ""}
{"_id": "d7510", "text": "def _namematcher(regex):\n    \"\"\"Checks if a target name matches with an input regular expression.\"\"\"\n\n    matcher = re_compile(regex)\n\n    def match(target):\n        target_name = getattr(target, '__name__', '')\n        result = matcher.match(target_name)\n        return result\n\n    return match", "title": ""}
{"_id": "d7511", "text": "def error(self, text):\n\t\t\"\"\" Ajout d'un message de log de type ERROR \"\"\"\n\t\tself.logger.error(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d7512", "text": "def is_valid_email(email):\n    \"\"\"\n    Check if email is valid\n    \"\"\"\n    pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n    return bool(pattern.match(email))", "title": ""}
{"_id": "d7513", "text": "def int2str(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from integers to strings\"\"\"\n    return NumConv(radix, alphabet).int2str(num)", "title": ""}
{"_id": "d7514", "text": "def select_from_array(cls, array, identifier):\n        \"\"\"Return a region from a numpy array.\n        \n        :param array: :class:`numpy.ndarray`\n        :param identifier: value representing the region to select in the array\n        :returns: :class:`jicimagelib.region.Region`\n        \"\"\"\n\n        base_array = np.zeros(array.shape)\n        array_coords = np.where(array == identifier)\n        base_array[array_coords] = 1\n\n        return cls(base_array)", "title": ""}
{"_id": "d7515", "text": "def to_snake_case(name):\n    \"\"\" Given a name in camelCase return in snake_case \"\"\"\n    s1 = FIRST_CAP_REGEX.sub(r'\\1_\\2', name)\n    return ALL_CAP_REGEX.sub(r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d7516", "text": "def separator(self, menu=None):\n        \"\"\"Add a separator\"\"\"\n        self.gui.get_menu(menu or self.menu).addSeparator()", "title": ""}
{"_id": "d7517", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d7518", "text": "def once(func):\n    \"\"\"Runs a thing once and once only.\"\"\"\n    lock = threading.Lock()\n\n    def new_func(*args, **kwargs):\n        if new_func.called:\n            return\n        with lock:\n            if new_func.called:\n                return\n            rv = func(*args, **kwargs)\n            new_func.called = True\n            return rv\n\n    new_func = update_wrapper(new_func, func)\n    new_func.called = False\n    return new_func", "title": ""}
{"_id": "d7519", "text": "def CleanseComments(line):\n  \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n  Args:\n    line: A line of C++ source.\n\n  Returns:\n    The line with single-line comments removed.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1 and not IsCppString(line[:commentpos]):\n    line = line[:commentpos].rstrip()\n  # get rid of /* ... */\n  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "title": ""}
{"_id": "d7520", "text": "def as_list(callable):\n    \"\"\"Convert a scalar validator in a list validator\"\"\"\n    @wraps(callable)\n    def wrapper(value_iter):\n        return [callable(value) for value in value_iter]\n\n    return wrapper", "title": ""}
{"_id": "d7521", "text": "def delete_cell(self,  key):\n        \"\"\"Deletes key cell\"\"\"\n\n        try:\n            self.code_array.pop(key)\n\n        except KeyError:\n            pass\n\n        self.grid.code_array.result_cache.clear()", "title": ""}
{"_id": "d7522", "text": "def _listify(collection):\n        \"\"\"This is a workaround where Collections are no longer iterable\n        when using JPype.\"\"\"\n        new_list = []\n        for index in range(len(collection)):\n            new_list.append(collection[index])\n        return new_list", "title": ""}
{"_id": "d7523", "text": "def make_stream_handler(graph, formatter):\n    \"\"\"\n    Create the stream handler. Used for console/debug output.\n\n    \"\"\"\n    return {\n        \"class\": graph.config.logging.stream_handler.class_,\n        \"formatter\": formatter,\n        \"level\": graph.config.logging.level,\n        \"stream\": graph.config.logging.stream_handler.stream,\n    }", "title": ""}
{"_id": "d7524", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d7525", "text": "def log_leave(event, nick, channel):\n\t\"\"\"\n\tLog a quit or part event.\n\t\"\"\"\n\tif channel not in pmxbot.config.log_channels:\n\t\treturn\n\tParticipantLogger.store.log(nick, channel, event.type)", "title": ""}
{"_id": "d7526", "text": "def remove_dups(seq):\n    \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d7527", "text": "def _cumprod(l):\n  \"\"\"Cumulative product of a list.\n\n  Args:\n    l: a list of integers\n  Returns:\n    a list with one more element (starting with 1)\n  \"\"\"\n  ret = [1]\n  for item in l:\n    ret.append(ret[-1] * item)\n  return ret", "title": ""}
{"_id": "d7528", "text": "def not_matching_list(self):\n        \"\"\"\n        Return a list of string which don't match the\n        given regex.\n        \"\"\"\n\n        pre_result = comp(self.regex)\n\n        return [x for x in self.data if not pre_result.search(str(x))]", "title": ""}
{"_id": "d7529", "text": "def guess_title(basename):\n    \"\"\" Attempt to guess the title from the filename \"\"\"\n\n    base, _ = os.path.splitext(basename)\n    return re.sub(r'[ _-]+', r' ', base).title()", "title": ""}
{"_id": "d7530", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d7531", "text": "def access_to_sympy(self, var_name, access):\n        \"\"\"\n        Transform a (multidimensional) variable access to a flattend sympy expression.\n\n        Also works with flat array accesses.\n        \"\"\"\n        base_sizes = self.variables[var_name][1]\n\n        expr = sympy.Number(0)\n\n        for dimension, a in enumerate(access):\n            base_size = reduce(operator.mul, base_sizes[dimension+1:], sympy.Integer(1))\n\n            expr += base_size*a\n\n        return expr", "title": ""}
{"_id": "d7532", "text": "def md_to_text(content):\n    \"\"\" Converts markdown content to text \"\"\"\n    text = None\n    html = markdown.markdown(content)\n    if html:\n        text = html_to_text(content)\n    return text", "title": ""}
{"_id": "d7533", "text": "def cast_int(x):\n    \"\"\"\n    Cast unknown type into integer\n\n    :param any x:\n    :return int:\n    \"\"\"\n    try:\n        x = int(x)\n    except ValueError:\n        try:\n            x = x.strip()\n        except AttributeError as e:\n            logger_misc.warn(\"parse_str: AttributeError: String not number or word, {}, {}\".format(x, e))\n    return x", "title": ""}
{"_id": "d7534", "text": "def do_striptags(value):\n    \"\"\"Strip SGML/XML tags and replace adjacent whitespace by one space.\n    \"\"\"\n    if hasattr(value, '__html__'):\n        value = value.__html__()\n    return Markup(unicode(value)).striptags()", "title": ""}
{"_id": "d7535", "text": "def check_int(integer):\n    \"\"\"\n    Check if number is integer or not.\n\n    :param integer: Number as str\n    :return: Boolean\n    \"\"\"\n    if not isinstance(integer, str):\n        return False\n    if integer[0] in ('-', '+'):\n        return integer[1:].isdigit()\n    return integer.isdigit()", "title": ""}
{"_id": "d7536", "text": "def reduce_multiline(string):\n    \"\"\"\n    reduces a multiline string to a single line of text.\n\n\n    args:\n        string: the text to reduce\n    \"\"\"\n    string = str(string)\n    return \" \".join([item.strip()\n                     for item in string.split(\"\\n\")\n                     if item.strip()])", "title": ""}
{"_id": "d7537", "text": "def out(self, output, newline=True):\n        \"\"\"Outputs a string to the console (stdout).\"\"\"\n        click.echo(output, nl=newline)", "title": ""}
{"_id": "d7538", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d7539", "text": "def scatterplot_matrix(df, features, downsample_frac=None, figsize=(15, 15)):\n    \"\"\"\n    Plot a scatterplot matrix for a list of features, colored by target value.\n\n    Example: `scatterplot_matrix(X, X.columns.tolist(), downsample_frac=0.01)`\n\n    Args:\n        df: Pandas dataframe containing the target column (named 'target').\n        features: The list of features to include in the correlation plot.\n        downsample_frac: Dataframe downsampling rate (0.1 to include 10% of the dataset).\n        figsize: The size of the plot.\n    \"\"\"\n\n    if downsample_frac:\n        df = df.sample(frac=downsample_frac)\n\n    plt.figure(figsize=figsize)\n    sns.pairplot(df[features], hue='target')\n    plt.show()", "title": ""}
{"_id": "d7540", "text": "def _loadf(ins):\n    \"\"\" Loads a floating point value from a memory address.\n    If 2nd arg. start with '*', it is always treated as\n    an indirect value.\n    \"\"\"\n    output = _float_oper(ins.quad[2])\n    output.extend(_fpush())\n    return output", "title": ""}
{"_id": "d7541", "text": "def cleanup(self):\n        \"\"\"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.\n\n        \"\"\"\n\n        for instance in self.context:\n            del(instance)\n\n        for plugin in self.plugins:\n            del(plugin)", "title": ""}
{"_id": "d7542", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d7543", "text": "def _repr_strip(mystring):\n    \"\"\"\n    Returns the string without any initial or final quotes.\n    \"\"\"\n    r = repr(mystring)\n    if r.startswith(\"'\") and r.endswith(\"'\"):\n        return r[1:-1]\n    else:\n        return r", "title": ""}
{"_id": "d7544", "text": "def prox_zero(X, step):\n    \"\"\"Proximal operator to project onto zero\n    \"\"\"\n    return np.zeros(X.shape, dtype=X.dtype)", "title": ""}
{"_id": "d7545", "text": "def distinct(l):\n    \"\"\"\n    Return a list where the duplicates have been removed.\n\n    Args:\n        l (list): the list to filter.\n\n    Returns:\n        list: the same list without duplicates.\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return (_ for _ in l if not (_ in seen or seen_add(_)))", "title": ""}
{"_id": "d7546", "text": "def heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "title": ""}
{"_id": "d7547", "text": "def clean_strings(iterable):\n    \"\"\"\n    Take a list of strings and clear whitespace \n    on each one. If a value in the list is not a \n    string pass it through untouched.\n\n    Args:\n        iterable: mixed list\n\n    Returns: \n        mixed list\n    \"\"\"\n    retval = []\n    for val in iterable:\n        try:\n            retval.append(val.strip())\n        except(AttributeError):\n            retval.append(val)\n    return retval", "title": ""}
{"_id": "d7548", "text": "def build_output(self, fout):\n        \"\"\"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.\n        \"\"\"\n        fout.write('\\n'.join([s for s in self.out]))", "title": ""}
{"_id": "d7549", "text": "def normalize_time(timestamp):\n    \"\"\"Normalize time in arbitrary timezone to UTC naive object.\"\"\"\n    offset = timestamp.utcoffset()\n    if offset is None:\n        return timestamp\n    return timestamp.replace(tzinfo=None) - offset", "title": ""}
{"_id": "d7550", "text": "def string_input(prompt=''):\n    \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n    v = sys.version[0]\n    if v == '3':\n        return input(prompt)\n    else:\n        return raw_input(prompt)", "title": ""}
{"_id": "d7551", "text": "def _split_comma_separated(string):\n    \"\"\"Return a set of strings.\"\"\"\n    return set(text.strip() for text in string.split(',') if text.strip())", "title": ""}
{"_id": "d7552", "text": "def write_file(filename, content):\n    \"\"\"Create the file with the given content\"\"\"\n    print 'Generating {0}'.format(filename)\n    with open(filename, 'wb') as out_f:\n        out_f.write(content)", "title": ""}
{"_id": "d7553", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d7554", "text": "def set_font_size(self, size):\n        \"\"\"Convenience method for just changing font size.\"\"\"\n        if self.font.font_size == size:\n            pass\n        else:\n            self.font._set_size(size)", "title": ""}
{"_id": "d7555", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d7556", "text": "def __call__(self, factory_name, *args, **kwargs):\n        \"\"\"Create object.\"\"\"\n        return self.factories[factory_name](*args, **kwargs)", "title": ""}
{"_id": "d7557", "text": "def convert_str_to_datetime(df, *, column: str, format: str):\n    \"\"\"\n    Convert string column into datetime column\n\n    ---\n\n    ### Parameters\n\n    *mandatory :*\n    - `column` (*str*): name of the column to format\n    - `format` (*str*): current format of the values (see [available formats](\n    https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))\n    \"\"\"\n    df[column] = pd.to_datetime(df[column], format=format)\n    return df", "title": ""}
{"_id": "d7558", "text": "def to_camel(s):\n    \"\"\"\n    :param string s: under_scored string to be CamelCased\n    :return: CamelCase version of input\n    :rtype: str\n    \"\"\"\n    # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n    return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "title": ""}
{"_id": "d7559", "text": "def unescape_all(string):\n    \"\"\"Resolve all html entities to their corresponding unicode character\"\"\"\n    def escape_single(matchobj):\n        return _unicode_for_entity_with_name(matchobj.group(1))\n    return entities.sub(escape_single, string)", "title": ""}
{"_id": "d7560", "text": "def get_language_parameter(request, query_language_key='language', object=None, default=None):\n    \"\"\"\n    Get the language parameter from the current request.\n    \"\"\"\n    # This is the same logic as the django-admin uses.\n    # The only difference is the origin of the request parameter.\n    if not is_multilingual_project():\n        # By default, the objects are stored in a single static language.\n        # This makes the transition to multilingual easier as well.\n        # The default language can operate as fallback language too.\n        return default or appsettings.PARLER_LANGUAGES.get_default_language()\n    else:\n        # In multilingual mode, take the provided language of the request.\n        code = request.GET.get(query_language_key)\n\n        if not code:\n            # forms: show first tab by default\n            code = default or appsettings.PARLER_LANGUAGES.get_first_language()\n\n        return normalize_language_code(code)", "title": ""}
{"_id": "d7561", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d7562", "text": "def replaceNewlines(string, newlineChar):\n\t\"\"\"There's probably a way to do this with string functions but I was lazy.\n\t\tReplace all instances of \\r or \\n in a string with something else.\"\"\"\n\tif newlineChar in string:\n\t\tsegments = string.split(newlineChar)\n\t\tstring = \"\"\n\t\tfor segment in segments:\n\t\t\tstring += segment\n\treturn string", "title": ""}
{"_id": "d7563", "text": "def locate(command, on):\n    \"\"\"Locate the command's man page.\"\"\"\n    location = find_page_location(command, on)\n    click.echo(location)", "title": ""}
{"_id": "d7564", "text": "def replace_list(items, match, replacement):\n    \"\"\"Replaces occurrences of a match string in a given list of strings and returns\n    a list of new strings. The match string can be a regex expression.\n\n    Args:\n        items (list):       the list of strings to modify.\n        match (str):        the search expression.\n        replacement (str):  the string to replace with.\n    \"\"\"\n    return [replace(item, match, replacement) for item in items]", "title": ""}
{"_id": "d7565", "text": "def csv2yaml(in_file, out_file=None):\n    \"\"\"Convert a CSV SampleSheet to YAML run_info format.\n    \"\"\"\n    if out_file is None:\n        out_file = \"%s.yaml\" % os.path.splitext(in_file)[0]\n    barcode_ids = _generate_barcode_ids(_read_input_csv(in_file))\n    lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids)\n    with open(out_file, \"w\") as out_handle:\n        out_handle.write(yaml.safe_dump(lanes, default_flow_style=False))\n    return out_file", "title": ""}
{"_id": "d7566", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d7567", "text": "def merge_pdfs(pdf_filepaths, out_filepath):\n    \"\"\" Merge all the PDF files in `pdf_filepaths` in a new PDF file `out_filepath`.\n\n    Parameters\n    ----------\n    pdf_filepaths: list of str\n        Paths to PDF files.\n\n    out_filepath: str\n        Path to the result PDF file.\n\n    Returns\n    -------\n    path: str\n        The output file path.\n    \"\"\"\n    merger = PdfFileMerger()\n    for pdf in pdf_filepaths:\n        merger.append(PdfFileReader(open(pdf, 'rb')))\n\n    merger.write(out_filepath)\n\n    return out_filepath", "title": ""}
{"_id": "d7568", "text": "def _replace_token_range(tokens, start, end, replacement):\n    \"\"\"For a range indicated from start to end, replace with replacement.\"\"\"\n    tokens = tokens[:start] + replacement + tokens[end:]\n    return tokens", "title": ""}
{"_id": "d7569", "text": "def copy_and_update(dictionary, update):\n    \"\"\"Returns an updated copy of the dictionary without modifying the original\"\"\"\n    newdict = dictionary.copy()\n    newdict.update(update)\n    return newdict", "title": ""}
{"_id": "d7570", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d7571", "text": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "title": ""}
{"_id": "d7572", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d7573", "text": "def onRightUp(self, event=None):\n        \"\"\" right button up: put back to cursor mode\"\"\"\n        if event is None:\n            return\n        self.cursor_mode_action('rightup', event=event)\n        self.ForwardEvent(event=event.guiEvent)", "title": ""}
{"_id": "d7574", "text": "def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,\ncontent=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for not-authorized access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=401)", "title": ""}
{"_id": "d7575", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d7576", "text": "def geturl(self):\n        \"\"\"\n        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.\n        \"\"\"\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", "title": ""}
{"_id": "d7577", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d7578", "text": "def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None):\n        \"\"\"\n        Perform a chunked PUT request to url with requests.session\n        This is specifically to upload files.\n        \"\"\"\n        res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert)\n        return res.text, res.status_code", "title": ""}
{"_id": "d7579", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d7580", "text": "def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None):\n        \"\"\"\n        Perform a chunked PUT request to url with requests.session\n        This is specifically to upload files.\n        \"\"\"\n        res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert)\n        return res.text, res.status_code", "title": ""}
{"_id": "d7581", "text": "def from_file(cls, path, encoding, dialect, fields, converters, field_index):\n        \"\"\"Read delimited text from a text file.\"\"\"\n\n        return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index)", "title": ""}
{"_id": "d7582", "text": "def _reset_bind(self):\n        \"\"\"Internal utility function to reset binding.\"\"\"\n        self.binded = False\n        self._buckets = {}\n        self._curr_module = None\n        self._curr_bucket_key = None", "title": ""}
{"_id": "d7583", "text": "def get_image(self, source):\n        \"\"\"\n        Given a file-like object, loads it up into a PIL.Image object\n        and returns it.\n\n        :param file source: A file-like object to load the image from.\n        :rtype: PIL.Image\n        :returns: The loaded image.\n        \"\"\"\n        buf = StringIO(source.read())\n        return Image.open(buf)", "title": ""}
{"_id": "d7584", "text": "def reset_params(self):\n        \"\"\"Reset all parameters to their default values.\"\"\"\n        self.__params = dict([p, None] for p in self.param_names)\n        self.set_params(self.param_defaults)", "title": ""}
{"_id": "d7585", "text": "def covstr(s):\n  \"\"\" convert string to int or float. \"\"\"\n  try:\n    ret = int(s)\n  except ValueError:\n    ret = float(s)\n  return ret", "title": ""}
{"_id": "d7586", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d7587", "text": "def _parse_return(cls, result):\n        \"\"\"Extract the result, return value and context from a result object\n        \"\"\"\n\n        return_value = None\n        success = result['result']\n        context = result['context']\n\n        if 'return_value' in result:\n            return_value = result['return_value']\n\n        return success, return_value, context", "title": ""}
{"_id": "d7588", "text": "def unbroadcast_numpy_to(array, shape):\n  \"\"\"Reverse the broadcasting operation.\n\n  Args:\n    array: An array.\n    shape: A shape that could have been broadcasted to the shape of array.\n\n  Returns:\n    Array with dimensions summed to match `shape`.\n  \"\"\"\n  axis = create_unbroadcast_axis(shape, numpy.shape(array))\n  return numpy.reshape(numpy.sum(array, axis=axis), shape)", "title": ""}
{"_id": "d7589", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d7590", "text": "def resize_image_to_fit_width(image, dest_w):\n    \"\"\"\n    Resize and image to fit the passed in width, keeping the aspect ratio the same\n\n    :param image: PIL.Image\n    :param dest_w: The desired width\n    \"\"\"\n    scale_factor = dest_w / image.size[0]\n    dest_h = image.size[1] * scale_factor\n    \n    scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)\n\n    return scaled_image", "title": ""}
{"_id": "d7591", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d7592", "text": "def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,\ncontent=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for not-authorized access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=401)", "title": ""}
{"_id": "d7593", "text": "def load(self, filename='classifier.dump'):\n        \"\"\"\n        Unpickles the classifier used\n        \"\"\"\n        ifile = open(filename, 'r+')\n        self.classifier = pickle.load(ifile)\n        ifile.close()", "title": ""}
{"_id": "d7594", "text": "def do_stc_disconnectall(self, s):\n        \"\"\"Remove connections to all chassis (test ports) in this session.\"\"\"\n        if self._not_joined():\n            return\n        try:\n            self._stc.disconnectall()\n        except resthttp.RestHttpError as e:\n            print(e)\n            return\n        print('OK')", "title": ""}
{"_id": "d7595", "text": "def confusion_matrix(self):\n        \"\"\"Confusion matrix plot\n        \"\"\"\n        return plot.confusion_matrix(self.y_true, self.y_pred,\n                                     self.target_names, ax=_gen_ax())", "title": ""}
{"_id": "d7596", "text": "def _get_data(self):\n        \"\"\"\n        Extracts the session data from cookie.\n        \"\"\"\n        cookie = self.adapter.cookies.get(self.name)\n        return self._deserialize(cookie) if cookie else {}", "title": ""}
{"_id": "d7597", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d7598", "text": "def restore_default_settings():\n    \"\"\" Restore settings to default values. \n    \"\"\"\n    global __DEFAULTS\n    __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR\n    __DEFAULTS.SET_SEED = defaults.SET_SEED\n    __DEFAULTS.SEED = defaults.SEED\n    logging.info('Settings reverted to their default values.')", "title": ""}
{"_id": "d7599", "text": "def to_json(data):\n    \"\"\"Return data as a JSON string.\"\"\"\n    return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)", "title": ""}
{"_id": "d7600", "text": "def get_property(self, filename):\n        \"\"\"Opens the file and reads the value\"\"\"\n\n        with open(self.filepath(filename)) as f:\n            return f.read().strip()", "title": ""}
{"_id": "d7601", "text": "def __repr__(self):\n        \"\"\"Return list-lookalike of representation string of objects\"\"\"\n        strings = []\n        for currItem in self:\n            strings.append(\"%s\" % currItem)\n        return \"(%s)\" % (\", \".join(strings))", "title": ""}
{"_id": "d7602", "text": "def grandparent_path(self):\n        \"\"\" return grandparent's path string \"\"\"\n        return os.path.basename(os.path.join(self.path, '../..'))", "title": ""}
{"_id": "d7603", "text": "def out(self, output, newline=True):\n        \"\"\"Outputs a string to the console (stdout).\"\"\"\n        click.echo(output, nl=newline)", "title": ""}
{"_id": "d7604", "text": "def _find(string, sub_string, start_index):\n    \"\"\"Return index of sub_string in string.\n\n    Raise TokenError if sub_string is not found.\n    \"\"\"\n    result = string.find(sub_string, start_index)\n    if result == -1:\n        raise TokenError(\"expected '{0}'\".format(sub_string))\n    return result", "title": ""}
{"_id": "d7605", "text": "def _attrprint(d, delimiter=', '):\n    \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n    return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))", "title": ""}
{"_id": "d7606", "text": "def grandparent_path(self):\n        \"\"\" return grandparent's path string \"\"\"\n        return os.path.basename(os.path.join(self.path, '../..'))", "title": ""}
{"_id": "d7607", "text": "def series_index(self, series):\n        \"\"\"\n        Return the integer index of *series* in this sequence.\n        \"\"\"\n        for idx, s in enumerate(self):\n            if series is s:\n                return idx\n        raise ValueError('series not in chart data object')", "title": ""}
{"_id": "d7608", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d7609", "text": "def _run_parallel_process_with_profiling(self, start_path, stop_path, queue, filename):\n        \"\"\"\n        wrapper for usage of profiling\n        \"\"\"\n        runctx('Engine._run_parallel_process(self,  start_path, stop_path, queue)', globals(), locals(), filename)", "title": ""}
{"_id": "d7610", "text": "def _run_parallel_process_with_profiling(self, start_path, stop_path, queue, filename):\n        \"\"\"\n        wrapper for usage of profiling\n        \"\"\"\n        runctx('Engine._run_parallel_process(self,  start_path, stop_path, queue)', globals(), locals(), filename)", "title": ""}
{"_id": "d7611", "text": "def reduce_fn(x):\n    \"\"\"\n    Aggregation function to get the first non-zero value.\n    \"\"\"\n    values = x.values if pd and isinstance(x, pd.Series) else x\n    for v in values:\n        if not is_nan(v):\n            return v\n    return np.NaN", "title": ""}
{"_id": "d7612", "text": "def reraise(error):\n    \"\"\"Re-raises the error that was processed by prepare_for_reraise earlier.\"\"\"\n    if hasattr(error, \"_type_\"):\n        six.reraise(type(error), error, error._traceback)\n    raise error", "title": ""}
{"_id": "d7613", "text": "def round_sig(x, sig):\n    \"\"\"Round the number to the specified number of significant figures\"\"\"\n    return round(x, sig - int(floor(log10(abs(x)))) - 1)", "title": ""}
{"_id": "d7614", "text": "def list(self):\n        \"\"\"position in 3d space\"\"\"\n        return [self._pos3d.x, self._pos3d.y, self._pos3d.z]", "title": ""}
{"_id": "d7615", "text": "def round_to_x_digits(number, digits):\n    \"\"\"\n    Returns 'number' rounded to 'digits' digits.\n    \"\"\"\n    return round(number * math.pow(10, digits)) / math.pow(10, digits)", "title": ""}
{"_id": "d7616", "text": "def handle_exception(error):\n        \"\"\"Simple method for handling exceptions raised by `PyBankID`.\n\n        :param flask_pybankid.FlaskPyBankIDError error: The exception to handle.\n        :return: The exception represented as a dictionary.\n        :rtype: dict\n\n        \"\"\"\n        response = jsonify(error.to_dict())\n        response.status_code = error.status_code\n        return response", "title": ""}
{"_id": "d7617", "text": "def _removeStopwords(text_list):\n    \"\"\"\n    Removes stopwords contained in a list of words.\n\n    :param text_string: A list of strings.\n    :type text_string: list.\n\n    :returns: The input ``text_list`` with stopwords removed.\n    :rtype: list\n    \"\"\"\n\n    output_list = []\n\n    for word in text_list:\n        if word.lower() not in _stopwords:\n            output_list.append(word)\n\n    return output_list", "title": ""}
{"_id": "d7618", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d7619", "text": "def set(self, f):\n        \"\"\"Call a function after a delay, unless another function is set\n        in the meantime.\"\"\"\n        self.stop()\n        self._create_timer(f)\n        self.start()", "title": ""}
{"_id": "d7620", "text": "def __del__(self):\n        \"\"\"Cleanup the session if it was created here\"\"\"\n        if self._cleanup_session:\n            self._session.loop.run_until_complete(self._session.close())", "title": ""}
{"_id": "d7621", "text": "def sleep(self, time):\n        \"\"\"\n        Perform an asyncio sleep for the time specified in seconds. T\n        his method should be used in place of time.sleep()\n\n        :param time: time in seconds\n        :returns: No return value\n        \"\"\"\n        try:\n            task = asyncio.ensure_future(self.core.sleep(time))\n            self.loop.run_until_complete(task)\n\n        except asyncio.CancelledError:\n            pass\n        except RuntimeError:\n            pass", "title": ""}
{"_id": "d7622", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d7623", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d7624", "text": "def safe_mkdir_for(path, clean=False):\n  \"\"\"Ensure that the parent directory for a file is present.\n\n  If it's not there, create it. If it is, no-op.\n  \"\"\"\n  safe_mkdir(os.path.dirname(path), clean=clean)", "title": ""}
{"_id": "d7625", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d7626", "text": "def kill_mprocess(process):\n    \"\"\"kill process\n    Args:\n        process - Popen object for process\n    \"\"\"\n    if process and proc_alive(process):\n        process.terminate()\n        process.communicate()\n    return not proc_alive(process)", "title": ""}
{"_id": "d7627", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d7628", "text": "def save_cache(data, filename):\n    \"\"\"Save cookies to a file.\"\"\"\n    with open(filename, 'wb') as handle:\n        pickle.dump(data, handle)", "title": ""}
{"_id": "d7629", "text": "def standard_input():\n    \"\"\"Generator that yields lines from standard input.\"\"\"\n    with click.get_text_stream(\"stdin\") as stdin:\n        while stdin.readable():\n            line = stdin.readline()\n            if line:\n                yield line.strip().encode(\"utf-8\")", "title": ""}
{"_id": "d7630", "text": "def convert_camel_case_to_snake_case(name):\n    \"\"\"Convert CamelCase to snake_case.\"\"\"\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()", "title": ""}
{"_id": "d7631", "text": "def load_graph_from_rdf(fname):\n    \"\"\" reads an RDF file into a graph \"\"\"\n    print(\"reading RDF from \" + fname + \"....\")\n    store = Graph()\n    store.parse(fname, format=\"n3\")\n    print(\"Loaded \" + str(len(store)) + \" tuples\")\n    return store", "title": ""}
{"_id": "d7632", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d7633", "text": "def spline_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):\n    \"\"\"A datetime-version that takes datetime object list as x_axis\n    \"\"\"\n    numeric_datetime_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_axis\n    ]\n\n    numeric_datetime_new_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_new_axis\n    ]\n\n    return spline_interpolate(\n        numeric_datetime_axis, y_axis, numeric_datetime_new_axis)", "title": ""}
{"_id": "d7634", "text": "def html_to_text(content):\n    \"\"\" Converts html content to plain text \"\"\"\n    text = None\n    h2t = html2text.HTML2Text()\n    h2t.ignore_links = False\n    text = h2t.handle(content)\n    return text", "title": ""}
{"_id": "d7635", "text": "def scipy_sparse_to_spmatrix(A):\n    \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP", "title": ""}
{"_id": "d7636", "text": "def path(self):\n        \"\"\"\n        Return the path always without the \\\\?\\ prefix.\n        \"\"\"\n        path = super(WindowsPath2, self).path\n        if path.startswith(\"\\\\\\\\?\\\\\"):\n            return path[4:]\n        return path", "title": ""}
{"_id": "d7637", "text": "def write_wav(path, samples, sr=16000):\n    \"\"\"\n    Write to given samples to a wav file.\n    The samples are expected to be floating point numbers\n    in the range of -1.0 to 1.0.\n\n    Args:\n        path (str): The path to write the wav to.\n        samples (np.array): A float array .\n        sr (int): The sampling rate.\n    \"\"\"\n    max_value = np.abs(np.iinfo(np.int16).min)\n    data = (samples * max_value).astype(np.int16)\n    scipy.io.wavfile.write(path, sr, data)", "title": ""}
{"_id": "d7638", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d7639", "text": "def write_wav(path, samples, sr=16000):\n    \"\"\"\n    Write to given samples to a wav file.\n    The samples are expected to be floating point numbers\n    in the range of -1.0 to 1.0.\n\n    Args:\n        path (str): The path to write the wav to.\n        samples (np.array): A float array .\n        sr (int): The sampling rate.\n    \"\"\"\n    max_value = np.abs(np.iinfo(np.int16).min)\n    data = (samples * max_value).astype(np.int16)\n    scipy.io.wavfile.write(path, sr, data)", "title": ""}
{"_id": "d7640", "text": "def clean_axis(axis):\n    \"\"\"Remove ticks, tick labels, and frame from axis\"\"\"\n    axis.get_xaxis().set_ticks([])\n    axis.get_yaxis().set_ticks([])\n    for spine in list(axis.spines.values()):\n        spine.set_visible(False)", "title": ""}
{"_id": "d7641", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d7642", "text": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "title": ""}
{"_id": "d7643", "text": "def indentsize(line):\n    \"\"\"Return the indent size, in spaces, at the start of a line of text.\"\"\"\n    expline = string.expandtabs(line)\n    return len(expline) - len(string.lstrip(expline))", "title": ""}
{"_id": "d7644", "text": "def remove_list_duplicates(lista, unique=False):\n    \"\"\"\n    Remove duplicated elements in a list.\n    Args:\n        lista: List with elements to clean duplicates.\n    \"\"\"\n    result = []\n    allready = []\n\n    for elem in lista:\n        if elem not in result:\n            result.append(elem)\n        else:\n            allready.append(elem)\n\n    if unique:\n        for elem in allready:\n            result = list(filter((elem).__ne__, result))\n\n    return result", "title": ""}
{"_id": "d7645", "text": "def set_scrollregion(self, event=None):\n        \"\"\" Set the scroll region on the canvas\"\"\"\n        self.canvas.configure(scrollregion=self.canvas.bbox('all'))", "title": ""}
{"_id": "d7646", "text": "def get_line_ending(line):\n    \"\"\"Return line ending.\"\"\"\n    non_whitespace_index = len(line.rstrip()) - len(line)\n    if not non_whitespace_index:\n        return ''\n    else:\n        return line[non_whitespace_index:]", "title": ""}
{"_id": "d7647", "text": "def split_every(n, iterable):\n    \"\"\"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.\"\"\"\n    items = iter(iterable)\n    return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))", "title": ""}
{"_id": "d7648", "text": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "title": ""}
{"_id": "d7649", "text": "def date(start, end):\n    \"\"\"Get a random date between two dates\"\"\"\n\n    stime = date_to_timestamp(start)\n    etime = date_to_timestamp(end)\n\n    ptime = stime + random.random() * (etime - stime)\n\n    return datetime.date.fromtimestamp(ptime)", "title": ""}
{"_id": "d7650", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d7651", "text": "def selecttrue(table, field, complement=False):\n    \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n    return select(table, field, lambda v: bool(v), complement=complement)", "title": ""}
{"_id": "d7652", "text": "def format_screen(strng):\n    \"\"\"Format a string for screen printing.\n\n    This removes some latex-type format codes.\"\"\"\n    # Paragraph continue\n    par_re = re.compile(r'\\\\$',re.MULTILINE)\n    strng = par_re.sub('',strng)\n    return strng", "title": ""}
{"_id": "d7653", "text": "def strip_querystring(url):\n    \"\"\"Remove the querystring from the end of a URL.\"\"\"\n    p = six.moves.urllib.parse.urlparse(url)\n    return p.scheme + \"://\" + p.netloc + p.path", "title": ""}
{"_id": "d7654", "text": "def selecttrue(table, field, complement=False):\n    \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n    return select(table, field, lambda v: bool(v), complement=complement)", "title": ""}
{"_id": "d7655", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d7656", "text": "def selecttrue(table, field, complement=False):\n    \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n    return select(table, field, lambda v: bool(v), complement=complement)", "title": ""}
{"_id": "d7657", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d7658", "text": "def _pick_attrs(attrs, keys):\n    \"\"\" Return attrs with keys in keys list\n    \"\"\"\n    return dict((k, v) for k, v in attrs.items() if k in keys)", "title": ""}
{"_id": "d7659", "text": "def fix_dashes(string):\n    \"\"\"Fix bad Unicode special dashes in string.\"\"\"\n    string = string.replace(u'\\u05BE', '-')\n    string = string.replace(u'\\u1806', '-')\n    string = string.replace(u'\\u2E3A', '-')\n    string = string.replace(u'\\u2E3B', '-')\n    string = unidecode(string)\n    return re.sub(r'--+', '-', string)", "title": ""}
{"_id": "d7660", "text": "def _indexes(arr):\n    \"\"\" Returns the list of all indexes of the given array.\n\n    Currently works for one and two-dimensional arrays\n\n    \"\"\"\n    myarr = np.array(arr)\n    if myarr.ndim == 1:\n        return list(range(len(myarr)))\n    elif myarr.ndim == 2:\n        return tuple(itertools.product(list(range(arr.shape[0])),\n                                       list(range(arr.shape[1]))))\n    else:\n        raise NotImplementedError('Only supporting arrays of dimension 1 and 2 as yet.')", "title": ""}
{"_id": "d7661", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d7662", "text": "def copy(self):\n        \"\"\"Create an identical (deep) copy of this element.\"\"\"\n        result = self.space.element()\n        result.assign(self)\n        return result", "title": ""}
{"_id": "d7663", "text": "def wordify(text):\n    \"\"\"Generate a list of words given text, removing punctuation.\n\n    Parameters\n    ----------\n    text : unicode\n        A piece of english text.\n\n    Returns\n    -------\n    words : list\n        List of words.\n    \"\"\"\n    stopset = set(nltk.corpus.stopwords.words('english'))\n    tokens = nltk.WordPunctTokenizer().tokenize(text)\n    return [w for w in tokens if w not in stopset]", "title": ""}
{"_id": "d7664", "text": "async def send(self, data):\n        \"\"\" Add data to send queue. \"\"\"\n        self.writer.write(data)\n        await self.writer.drain()", "title": ""}
{"_id": "d7665", "text": "def symlink_remove(link):\n    \"\"\"Remove a symlink. Used for model shortcut links.\n\n    link (unicode / Path): The path to the symlink.\n    \"\"\"\n    # https://stackoverflow.com/q/26554135/6400719\n    if os.path.isdir(path2str(link)) and is_windows:\n        # this should only be on Py2.7 and windows\n        os.rmdir(path2str(link))\n    else:\n        os.unlink(path2str(link))", "title": ""}
{"_id": "d7666", "text": "def cli(yamlfile, format, output):\n    \"\"\" Generate an OWL representation of a biolink model \"\"\"\n    print(OwlSchemaGenerator(yamlfile, format).serialize(output=output))", "title": ""}
{"_id": "d7667", "text": "def get_stripped_file_lines(filename):\n    \"\"\"\n    Return lines of a file with whitespace removed\n    \"\"\"\n    try:\n        lines = open(filename).readlines()\n    except FileNotFoundError:\n        fatal(\"Could not open file: {!r}\".format(filename))\n\n    return [line.strip() for line in lines]", "title": ""}
{"_id": "d7668", "text": "def serialize(self, value, **kwargs):\n        \"\"\"Serialize every item of the list.\"\"\"\n        return [self.item_type.serialize(val, **kwargs) for val in value]", "title": ""}
{"_id": "d7669", "text": "def draw_image(self, ax, image):\n        \"\"\"Process a matplotlib image object and call renderer.draw_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)", "title": ""}
{"_id": "d7670", "text": "def na_if(series, *values):\n    \"\"\"\n    If values in a series match a specified value, change them to `np.nan`.\n\n    Args:\n        series: Series or vector, often symbolic.\n        *values: Value(s) to convert to `np.nan` in the series.\n    \"\"\"\n\n    series = pd.Series(series)\n    series[series.isin(values)] = np.nan\n    return series", "title": ""}
{"_id": "d7671", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d7672", "text": "def to_monthly(series, method='ffill', how='end'):\n    \"\"\"\n    Convenience method that wraps asfreq_actual\n    with 'M' param (method='ffill', how='end').\n    \"\"\"\n    return series.asfreq_actual('M', method=method, how=how)", "title": ""}
{"_id": "d7673", "text": "def internal_reset(self):\n        \"\"\"\n        internal state reset.\n        used e.g. in unittests\n        \"\"\"\n        log.critical(\"PIA internal_reset()\")\n        self.empty_key_toggle = True\n        self.current_input_char = None\n        self.input_repead = 0", "title": ""}
{"_id": "d7674", "text": "def dispatch(self):\n    \"\"\"Wraps the dispatch method to add session support.\"\"\"\n    try:\n      webapp2.RequestHandler.dispatch(self)\n    finally:\n      self.session_store.save_sessions(self.response)", "title": ""}
{"_id": "d7675", "text": "def restart_program():\n    \"\"\"\n    DOES NOT WORK WELL WITH MOPIDY\n    Hack from\n    https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program\n    to support updating the settings, since mopidy is not able to do that yet\n    Restarts the current program\n    Note: this function does not return. Any cleanup action (like\n    saving data) must be done before calling this function\n    \"\"\"\n\n    python = sys.executable\n    os.execl(python, python, * sys.argv)", "title": ""}
{"_id": "d7676", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d7677", "text": "def _cpu(self):\n        \"\"\"Record CPU usage.\"\"\"\n        value = int(psutil.cpu_percent())\n        set_metric(\"cpu\", value, category=self.category)\n        gauge(\"cpu\", value)", "title": ""}
{"_id": "d7678", "text": "def plot3d_init(fignum):\n    \"\"\"\n    initializes 3D plot\n    \"\"\"\n    from mpl_toolkits.mplot3d import Axes3D\n    fig = plt.figure(fignum)\n    ax = fig.add_subplot(111, projection='3d')\n    return ax", "title": ""}
{"_id": "d7679", "text": "def roundClosestValid(val, res, decimals=None):\n        \"\"\" round to closest resolution \"\"\"\n        if decimals is None and \".\" in str(res):\n            decimals = len(str(res).split('.')[1])\n\n        return round(round(val / res) * res, decimals)", "title": ""}
{"_id": "d7680", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d7681", "text": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "title": ""}
{"_id": "d7682", "text": "def ensure_hbounds(self):\n        \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "title": ""}
{"_id": "d7683", "text": "def unpack2D(_x):\n    \"\"\"\n        Helper function for splitting 2D data into x and y component to make\n        equations simpler\n    \"\"\"\n    _x = np.atleast_2d(_x)\n    x = _x[:, 0]\n    y = _x[:, 1]\n    return x, y", "title": ""}
{"_id": "d7684", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d7685", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d7686", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d7687", "text": "def set_xlimits(self, min=None, max=None):\n        \"\"\"Set limits for the x-axis.\n\n        :param min: minimum value to be displayed.  If None, it will be\n            calculated.\n        :param max: maximum value to be displayed.  If None, it will be\n            calculated.\n\n        \"\"\"\n        self.limits['xmin'] = min\n        self.limits['xmax'] = max", "title": ""}
{"_id": "d7688", "text": "def similarity_transformation(rot, mat):\n    \"\"\" R x M x R^-1 \"\"\"\n    return np.dot(rot, np.dot(mat, np.linalg.inv(rot)))", "title": ""}
{"_id": "d7689", "text": "def sha1(s):\n    \"\"\" Returns a sha1 of the given string\n    \"\"\"\n    h = hashlib.new('sha1')\n    h.update(s)\n    return h.hexdigest()", "title": ""}
{"_id": "d7690", "text": "def save_pdf(path):\n  \"\"\"\n  Saves a pdf of the current matplotlib figure.\n\n  :param path: str, filepath to save to\n  \"\"\"\n\n  pp = PdfPages(path)\n  pp.savefig(pyplot.gcf())\n  pp.close()", "title": ""}
{"_id": "d7691", "text": "def open(self, flag=\"c\"):\n        \"\"\"Open handle\n\n        set protocol=2 to fix python3\n\n        .. versionadded:: 1.3.1\n        \"\"\"\n        return shelve.open(os.path.join(gettempdir(), self.index), flag=flag, protocol=2)", "title": ""}
{"_id": "d7692", "text": "def save_pdf(path):\n  \"\"\"\n  Saves a pdf of the current matplotlib figure.\n\n  :param path: str, filepath to save to\n  \"\"\"\n\n  pp = PdfPages(path)\n  pp.savefig(pyplot.gcf())\n  pp.close()", "title": ""}
{"_id": "d7693", "text": "def hflip(img):\n    \"\"\"Horizontally flip the given PIL Image.\n\n    Args:\n        img (PIL Image): Image to be flipped.\n\n    Returns:\n        PIL Image:  Horizontall flipped image.\n    \"\"\"\n    if not _is_pil_image(img):\n        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n    return img.transpose(Image.FLIP_LEFT_RIGHT)", "title": ""}
{"_id": "d7694", "text": "def _save_file(self, filename, contents):\n        \"\"\"write the html file contents to disk\"\"\"\n        with open(filename, 'w') as f:\n            f.write(contents)", "title": ""}
{"_id": "d7695", "text": "def normalise_key(self, key):\n        \"\"\"Make sure key is a valid python attribute\"\"\"\n        key = key.replace('-', '_')\n        if key.startswith(\"noy_\"):\n            key = key[4:]\n        return key", "title": ""}
{"_id": "d7696", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d7697", "text": "def getFieldsColumnLengths(self):\n        \"\"\"\n        Gets the maximum length of each column in the field table\n        \"\"\"\n        nameLen = 0\n        descLen = 0\n        for f in self.fields:\n            nameLen = max(nameLen, len(f['title']))\n            descLen = max(descLen, len(f['description']))\n        return (nameLen, descLen)", "title": ""}
{"_id": "d7698", "text": "def resetScale(self):\n        \"\"\"Resets the scale on this image. Correctly aligns time scale, undoes manual scaling\"\"\"\n        self.img.scale(1./self.imgScale[0], 1./self.imgScale[1])\n        self.imgScale = (1.,1.)", "title": ""}
{"_id": "d7699", "text": "def format_exc(limit=None):\n    \"\"\"Like print_exc() but return a string. Backport for Python 2.3.\"\"\"\n    try:\n        etype, value, tb = sys.exc_info()\n        return ''.join(traceback.format_exception(etype, value, tb, limit))\n    finally:\n        etype = value = tb = None", "title": ""}
{"_id": "d7700", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d7701", "text": "def close(self, wait=False):\n        \"\"\"Close session, shutdown pool.\"\"\"\n        self.session.close()\n        self.pool.shutdown(wait=wait)", "title": ""}
{"_id": "d7702", "text": "def lengths( self ):\n        \"\"\"\n        The cell lengths.\n\n        Args:\n            None\n\n        Returns:\n            (np.array(a,b,c)): The cell lengths.\n        \"\"\"\n        return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) )", "title": ""}
{"_id": "d7703", "text": "def softplus(attrs, inputs, proto_obj):\n    \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs", "title": ""}
{"_id": "d7704", "text": "def rand_elem(seq, n=None):\n    \"\"\"returns a random element from seq n times. If n is None, it continues indefinitly\"\"\"\n    return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))", "title": ""}
{"_id": "d7705", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d7706", "text": "def other_ind(self):\n        \"\"\"last row or column of square A\"\"\"\n        return np.full(self.n_min, self.size - 1, dtype=np.int)", "title": ""}
{"_id": "d7707", "text": "def array_bytes(array):\n    \"\"\" Estimates the memory of the supplied array in bytes \"\"\"\n    return np.product(array.shape)*np.dtype(array.dtype).itemsize", "title": ""}
{"_id": "d7708", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d7709", "text": "def impute_data(self,x):\n        \"\"\"Imputes data set containing Nan values\"\"\"\n        imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n        return imp.fit_transform(x)", "title": ""}
{"_id": "d7710", "text": "def pwm(host, seq, m1, m2, m3, m4):\n    \"\"\"\n    Sends control values directly to the engines, overriding control loops.\n\n    Parameters:\n    seq -- sequence number\n    m1 -- Integer: front left command\n    m2 -- Integer: front right command\n    m3 -- Integer: back right command\n    m4 -- Integer: back left command\n    \"\"\"\n    at(host, 'PWM', seq, [m1, m2, m3, m4])", "title": ""}
{"_id": "d7711", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d7712", "text": "def unsort_vector(data, indices_of_increasing):\n    \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n    return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])", "title": ""}
{"_id": "d7713", "text": "def symmetrise(matrix, tri='upper'):\n    \"\"\"\n    Will copy the selected (upper or lower) triangle of a square matrix\n    to the opposite side, so that the matrix is symmetrical.\n    Alters in place.\n    \"\"\"\n    if tri == 'upper':\n        tri_fn = np.triu_indices\n    else:\n        tri_fn = np.tril_indices\n    size = matrix.shape[0]\n    matrix[tri_fn(size)[::-1]] = matrix[tri_fn(size)]\n    return matrix", "title": ""}
{"_id": "d7714", "text": "def unsort_vector(data, indices_of_increasing):\n    \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n    return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])", "title": ""}
{"_id": "d7715", "text": "def main():\n    \"\"\"Ideally we shouldn't lose the first second of events\"\"\"\n    time.sleep(1)\n    with Input() as input_generator:\n        for e in input_generator:\n            print(repr(e))", "title": ""}
{"_id": "d7716", "text": "def SetValue(self, row, col, value):\n        \"\"\"\n        Set value in the pandas DataFrame\n        \"\"\"\n        self.dataframe.iloc[row, col] = value", "title": ""}
{"_id": "d7717", "text": "def sort_by_name(self):\n        \"\"\"Sort list elements by name.\"\"\"\n        super(JSSObjectList, self).sort(key=lambda k: k.name)", "title": ""}
{"_id": "d7718", "text": "def parse(self, s):\n        \"\"\"\n        Parses a date string formatted like ``YYYY-MM-DD``.\n        \"\"\"\n        return datetime.datetime.strptime(s, self.date_format).date()", "title": ""}
{"_id": "d7719", "text": "def sort_key(val):\n    \"\"\"Sort key for sorting keys in grevlex order.\"\"\"\n    return numpy.sum((max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val)", "title": ""}
{"_id": "d7720", "text": "def sort_data(x, y):\n    \"\"\"Sort the data.\"\"\"\n    xy = sorted(zip(x, y))\n    x, y = zip(*xy)\n    return x, y", "title": ""}
{"_id": "d7721", "text": "def display(self):\n        \"\"\" Get screen width and height \"\"\"\n        w, h = self.session.window_size()\n        return Display(w*self.scale, h*self.scale)", "title": ""}
{"_id": "d7722", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d7723", "text": "def enable_proxy(self, host, port):\n        \"\"\"Enable a default web proxy\"\"\"\n\n        self.proxy = [host, _number(port)]\n        self.proxy_enabled = True", "title": ""}
{"_id": "d7724", "text": "def scipy_sparse_to_spmatrix(A):\n    \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP", "title": ""}
{"_id": "d7725", "text": "def set_proxy(proxy_url, transport_proxy=None):\n    \"\"\"Create the proxy to PyPI XML-RPC Server\"\"\"\n    global proxy, PYPI_URL\n    PYPI_URL = proxy_url\n    proxy = xmlrpc.ServerProxy(\n        proxy_url,\n        transport=RequestsTransport(proxy_url.startswith('https://')),\n        allow_none=True)", "title": ""}
{"_id": "d7726", "text": "def is_sparse_vector(x):\n    \"\"\" x is a 2D sparse matrix with it's first shape equal to 1.\n    \"\"\"\n    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1", "title": ""}
{"_id": "d7727", "text": "def value_to_python(self, value):\n        \"\"\"\n        Converts the input single value into the expected Python data type,\n        raising django.core.exceptions.ValidationError if the data can't be\n        converted.  Returns the converted value. Subclasses should override\n        this.\n        \"\"\"\n        if not isinstance(value, bytes):\n            raise tldap.exceptions.ValidationError(\"should be a bytes\")\n        value = value.decode(\"utf_8\")\n        return value", "title": ""}
{"_id": "d7728", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d7729", "text": "def sbessely(x, N):\n    \"\"\"Returns a vector of spherical bessel functions yn:\n\n        x:   The argument.\n        N:   values of n will run from 0 to N-1.\n\n    \"\"\"\n\n    out = np.zeros(N, dtype=np.float64)\n\n    out[0] = -np.cos(x) / x\n    out[1] = -np.cos(x) / (x ** 2) - np.sin(x) / x\n\n    for n in xrange(2, N):\n        out[n] = ((2.0 * n - 1.0) / x) * out[n - 1] - out[n - 2]\n\n    return out", "title": ""}
{"_id": "d7730", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d7731", "text": "def partition(a, sz): \n    \"\"\"splits iterables a in equal parts of size sz\"\"\"\n    return [a[i:i+sz] for i in range(0, len(a), sz)]", "title": ""}
{"_id": "d7732", "text": "def finish_plot():\n    \"\"\"Helper for plotting.\"\"\"\n    plt.legend()\n    plt.grid(color='0.7')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.show()", "title": ""}
{"_id": "d7733", "text": "def split_on(s, sep=\" \"):\n    \"\"\"Split s by sep, unless it's inside a quote.\"\"\"\n    pattern = '''((?:[^%s\"']|\"[^\"]*\"|'[^']*')+)''' % sep\n\n    return [_strip_speechmarks(t) for t in re.split(pattern, s)[1::2]]", "title": ""}
{"_id": "d7734", "text": "def error(*args):\n    \"\"\"Display error message via stderr or GUI.\"\"\"\n    if sys.stdin.isatty():\n        print('ERROR:', *args, file=sys.stderr)\n    else:\n        notify_error(*args)", "title": ""}
{"_id": "d7735", "text": "def show(self, title=''):\n        \"\"\"\n        Display Bloch sphere and corresponding data sets.\n        \"\"\"\n        self.render(title=title)\n        if self.fig:\n            plt.show(self.fig)", "title": ""}
{"_id": "d7736", "text": "def _split(value):\n    \"\"\"Split input/output value into two values.\"\"\"\n    if isinstance(value, str):\n        # iterable, but not meant for splitting\n        return value, value\n    try:\n        invalue, outvalue = value\n    except TypeError:\n        invalue = outvalue = value\n    except ValueError:\n        raise ValueError(\"Only single values and pairs are allowed\")\n    return invalue, outvalue", "title": ""}
{"_id": "d7737", "text": "def partition(a, sz): \n    \"\"\"splits iterables a in equal parts of size sz\"\"\"\n    return [a[i:i+sz] for i in range(0, len(a), sz)]", "title": ""}
{"_id": "d7738", "text": "def _split_batches(self, data, batch_size):\n        \"\"\"Yield successive n-sized chunks from l.\"\"\"\n        for i in range(0, len(data), batch_size):\n            yield data[i : i + batch_size]", "title": ""}
{"_id": "d7739", "text": "def getcolslice(self, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1):\n        \"\"\"Get a slice from a table column holding arrays.\n        (see :func:`table.getcolslice`)\"\"\"\n        return self._table.getcolslice(self._column, blc, trc, inc, startrow, nrow, rowincr)", "title": ""}
{"_id": "d7740", "text": "def restart(self, reset=False):\n        \"\"\"\n        Quit and Restart Spyder application.\n\n        If reset True it allows to reset spyder on restart.\n        \"\"\"\n        # Get start path to use in restart script\n        spyder_start_directory = get_module_path('spyder')\n        restart_script = osp.join(spyder_start_directory, 'app', 'restart.py')\n\n        # Get any initial argument passed when spyder was started\n        # Note: Variables defined in bootstrap.py and spyder/app/start.py\n        env = os.environ.copy()\n        bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)\n        spyder_args = env.pop('SPYDER_ARGS')\n\n        # Get current process and python running spyder\n        pid = os.getpid()\n        python = sys.executable\n\n        # Check if started with bootstrap.py\n        if bootstrap_args is not None:\n            spyder_args = bootstrap_args\n            is_bootstrap = True\n        else:\n            is_bootstrap = False\n\n        # Pass variables as environment variables (str) to restarter subprocess\n        env['SPYDER_ARGS'] = spyder_args\n        env['SPYDER_PID'] = str(pid)\n        env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)\n        env['SPYDER_RESET'] = str(reset)\n\n        if DEV:\n            if os.name == 'nt':\n                env['PYTHONPATH'] = ';'.join(sys.path)\n            else:\n                env['PYTHONPATH'] = ':'.join(sys.path)\n\n        # Build the command and popen arguments depending on the OS\n        if os.name == 'nt':\n            # Hide flashing command prompt\n            startupinfo = subprocess.STARTUPINFO()\n            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n            shell = False\n        else:\n            startupinfo = None\n            shell = True\n\n        command = '\"{0}\" \"{1}\"'\n        command = command.format(python, restart_script)\n\n        try:\n            if self.closing(True):\n                subprocess.Popen(command, shell=shell, env=env,\n                                 startupinfo=startupinfo)\n                self.console.quit()\n        except Exception as error:\n            # If there is an error with subprocess, Spyder should not quit and\n            # the error can be inspected in the internal console\n            print(error)  # spyder: test-skip\n            print(command)", "title": ""}
{"_id": "d7741", "text": "def smooth_array(array, amount=1):\n    \"\"\"\n\n    Returns the nearest-neighbor (+/- amount) smoothed array.\n    This does not modify the array or slice off the funny end points.\n\n    \"\"\"\n    if amount==0: return array\n\n    # we have to store the old values in a temp array to keep the\n    # smoothing from affecting the smoothing\n    new_array = _n.array(array)\n\n    for n in range(len(array)):\n        new_array[n] = smooth(array, n, amount)\n\n    return new_array", "title": ""}
{"_id": "d7742", "text": "def restart(self, reset=False):\n        \"\"\"\n        Quit and Restart Spyder application.\n\n        If reset True it allows to reset spyder on restart.\n        \"\"\"\n        # Get start path to use in restart script\n        spyder_start_directory = get_module_path('spyder')\n        restart_script = osp.join(spyder_start_directory, 'app', 'restart.py')\n\n        # Get any initial argument passed when spyder was started\n        # Note: Variables defined in bootstrap.py and spyder/app/start.py\n        env = os.environ.copy()\n        bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)\n        spyder_args = env.pop('SPYDER_ARGS')\n\n        # Get current process and python running spyder\n        pid = os.getpid()\n        python = sys.executable\n\n        # Check if started with bootstrap.py\n        if bootstrap_args is not None:\n            spyder_args = bootstrap_args\n            is_bootstrap = True\n        else:\n            is_bootstrap = False\n\n        # Pass variables as environment variables (str) to restarter subprocess\n        env['SPYDER_ARGS'] = spyder_args\n        env['SPYDER_PID'] = str(pid)\n        env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)\n        env['SPYDER_RESET'] = str(reset)\n\n        if DEV:\n            if os.name == 'nt':\n                env['PYTHONPATH'] = ';'.join(sys.path)\n            else:\n                env['PYTHONPATH'] = ':'.join(sys.path)\n\n        # Build the command and popen arguments depending on the OS\n        if os.name == 'nt':\n            # Hide flashing command prompt\n            startupinfo = subprocess.STARTUPINFO()\n            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n            shell = False\n        else:\n            startupinfo = None\n            shell = True\n\n        command = '\"{0}\" \"{1}\"'\n        command = command.format(python, restart_script)\n\n        try:\n            if self.closing(True):\n                subprocess.Popen(command, shell=shell, env=env,\n                                 startupinfo=startupinfo)\n                self.console.quit()\n        except Exception as error:\n            # If there is an error with subprocess, Spyder should not quit and\n            # the error can be inspected in the internal console\n            print(error)  # spyder: test-skip\n            print(command)", "title": ""}
{"_id": "d7743", "text": "def smooth_array(array, amount=1):\n    \"\"\"\n\n    Returns the nearest-neighbor (+/- amount) smoothed array.\n    This does not modify the array or slice off the funny end points.\n\n    \"\"\"\n    if amount==0: return array\n\n    # we have to store the old values in a temp array to keep the\n    # smoothing from affecting the smoothing\n    new_array = _n.array(array)\n\n    for n in range(len(array)):\n        new_array[n] = smooth(array, n, amount)\n\n    return new_array", "title": ""}
{"_id": "d7744", "text": "def join_cols(cols):\n    \"\"\"Join list of columns into a string for a SQL query\"\"\"\n    return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols", "title": ""}
{"_id": "d7745", "text": "def solve(A, x):\n    \"\"\"Solves a linear equation system with a matrix of shape (n, n) and an\n    array of shape (n, ...). The output has the same shape as the second\n    argument.\n    \"\"\"\n    # https://stackoverflow.com/a/48387507/353337\n    x = numpy.asarray(x)\n    return numpy.linalg.solve(A, x.reshape(x.shape[0], -1)).reshape(x.shape)", "title": ""}
{"_id": "d7746", "text": "def join_cols(cols):\n    \"\"\"Join list of columns into a string for a SQL query\"\"\"\n    return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols", "title": ""}
{"_id": "d7747", "text": "def MatrixSolve(a, rhs, adj):\n    \"\"\"\n    Matrix solve op.\n    \"\"\"\n    return np.linalg.solve(a if not adj else _adjoint(a), rhs),", "title": ""}
{"_id": "d7748", "text": "def callproc(self, name, params, param_types=None):\n    \"\"\"Calls a procedure.\n\n    :param name: the name of the procedure\n    :param params: a list or tuple of parameters to pass to the procedure.\n    :param param_types: a list or tuple of type names. If given, each param will be cast via\n                        sql_writers typecast method. This is useful to disambiguate procedure calls\n                        when several parameters are null and therefore cause overload resoluation\n                        issues.\n    :return: a 2-tuple of (cursor, params)\n    \"\"\"\n\n    if param_types:\n      placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t)\n                      for t in param_types]\n    else:\n      placeholders = [self.sql_writer.to_placeholder() for p in params]\n\n    # TODO: This may be Postgres specific...\n    qs = \"select * from {0}({1});\".format(name, \", \".join(placeholders))\n    return self.execute(qs, params), params", "title": ""}
{"_id": "d7749", "text": "def MatrixSolve(a, rhs, adj):\n    \"\"\"\n    Matrix solve op.\n    \"\"\"\n    return np.linalg.solve(a if not adj else _adjoint(a), rhs),", "title": ""}
{"_id": "d7750", "text": "def clear_all(self):\n        \"\"\"Delete all Labels.\"\"\"\n        logger.info(\"Clearing ALL Labels and LabelKeys.\")\n        self.session.query(Label).delete(synchronize_session=\"fetch\")\n        self.session.query(LabelKey).delete(synchronize_session=\"fetch\")", "title": ""}
{"_id": "d7751", "text": "def primary_keys_full(cls):\n        \"\"\"Get primary key properties for a SQLAlchemy cls.\n        Taken from marshmallow_sqlalchemy\n        \"\"\"\n        mapper = cls.__mapper__\n        return [\n            mapper.get_property_by_column(column)\n            for column in mapper.primary_key\n        ]", "title": ""}
{"_id": "d7752", "text": "def datetime_from_timestamp(timestamp, content):\n    \"\"\"\n    Helper function to add timezone information to datetime,\n    so that datetime is comparable to other datetime objects in recent versions\n    that now also have timezone information.\n    \"\"\"\n    return set_date_tzinfo(\n        datetime.fromtimestamp(timestamp),\n        tz_name=content.settings.get('TIMEZONE', None))", "title": ""}
{"_id": "d7753", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d7754", "text": "def has_permission(user, permission_name):\n    \"\"\"Check if a user has a given permission.\"\"\"\n    if user and user.is_superuser:\n        return True\n\n    return permission_name in available_perm_names(user)", "title": ""}
{"_id": "d7755", "text": "def from_pydatetime(cls, pydatetime):\n        \"\"\"\n        Creates sql datetime2 object from Python datetime object\n        ignoring timezone\n        @param pydatetime: Python datetime object\n        @return: sql datetime2 object\n        \"\"\"\n        return cls(date=Date.from_pydate(pydatetime.date),\n                   time=Time.from_pytime(pydatetime.time))", "title": ""}
{"_id": "d7756", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d7757", "text": "def sqliteRowsToDicts(sqliteRows):\n    \"\"\"\n    Unpacks sqlite rows as returned by fetchall\n    into an array of simple dicts.\n\n    :param sqliteRows: array of rows returned from fetchall DB call\n    :return:  array of dicts, keyed by the column names.\n    \"\"\"\n    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "title": ""}
{"_id": "d7758", "text": "def split_into_words(s):\n  \"\"\"Split a sentence into list of words.\"\"\"\n  s = re.sub(r\"\\W+\", \" \", s)\n  s = re.sub(r\"[_0-9]+\", \" \", s)\n  return s.split()", "title": ""}
{"_id": "d7759", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d7760", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d7761", "text": "def server(port):\n    \"\"\"Start the Django dev server.\"\"\"\n    args = ['python', 'manage.py', 'runserver']\n    if port:\n        args.append(port)\n    run.main(args)", "title": ""}
{"_id": "d7762", "text": "def split_into_words(s):\n  \"\"\"Split a sentence into list of words.\"\"\"\n  s = re.sub(r\"\\W+\", \" \", s)\n  s = re.sub(r\"[_0-9]+\", \" \", s)\n  return s.split()", "title": ""}
{"_id": "d7763", "text": "def static_method(cls, f):\n        \"\"\"Decorator which dynamically binds static methods to the model for later use.\"\"\"\n        setattr(cls, f.__name__, staticmethod(f))\n        return f", "title": ""}
{"_id": "d7764", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d7765", "text": "def is_static(*p):\n    \"\"\" A static value (does not change at runtime)\n    which is known at compile time\n    \"\"\"\n    return all(is_CONST(x) or\n               is_number(x) or\n               is_const(x)\n               for x in p)", "title": ""}
{"_id": "d7766", "text": "def quit(self):\n        \"\"\" Quits the application (called when the last window is closed)\n        \"\"\"\n        logger.debug(\"ArgosApplication.quit called\")\n        assert len(self.mainWindows) == 0, \\\n            \"Bug: still {} windows present at application quit!\".format(len(self.mainWindows))\n        self.qApplication.quit()", "title": ""}
{"_id": "d7767", "text": "def circstd(dts, axis=2):\n    \"\"\"Circular standard deviation\"\"\"\n    R = np.abs(np.exp(1.0j * dts).mean(axis=axis))\n    return np.sqrt(-2.0 * np.log(R))", "title": ""}
{"_id": "d7768", "text": "def setdefault(obj, field, default):\n    \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n    setattr(obj, field, getattr(obj, field, default))", "title": ""}
{"_id": "d7769", "text": "def getdefaultencoding():\n    \"\"\"Return IPython's guess for the default encoding for bytes as text.\n\n    Asks for stdin.encoding first, to match the calling Terminal, but that\n    is often None for subprocesses.  Fall back on locale.getpreferredencoding()\n    which should be a sensible platform default (that respects LANG environment),\n    and finally to sys.getdefaultencoding() which is the most conservative option,\n    and usually ASCII.\n    \"\"\"\n    enc = get_stream_enc(sys.stdin)\n    if not enc or enc=='ascii':\n        try:\n            # There are reports of getpreferredencoding raising errors\n            # in some cases, which may well be fixed, but let's be conservative here.\n            enc = locale.getpreferredencoding()\n        except Exception:\n            pass\n    return enc or sys.getdefaultencoding()", "title": ""}
{"_id": "d7770", "text": "def save(self, *args, **kwargs):\n        \"\"\"Saves an animation\n\n        A wrapper around :meth:`matplotlib.animation.Animation.save`\n        \"\"\"\n        self.timeline.index -= 1  # required for proper starting point for save\n        self.animation.save(*args, **kwargs)", "title": ""}
{"_id": "d7771", "text": "def read_stdin():\n    \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n    if sys.stdin.isatty() and sys.stdout.isatty():\n        print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n    return sys.stdin.read()", "title": ""}
{"_id": "d7772", "text": "def _swap_rows(self, i, j):\n        \"\"\"Swap i and j rows\n\n        As the side effect, determinant flips.\n\n        \"\"\"\n\n        L = np.eye(3, dtype='intc')\n        L[i, i] = 0\n        L[j, j] = 0\n        L[i, j] = 1\n        L[j, i] = 1\n        self._L.append(L.copy())\n        self._A = np.dot(L, self._A)", "title": ""}
{"_id": "d7773", "text": "def __init__(self, encoding='utf-8'):\n    \"\"\"Initializes an stdin input reader.\n\n    Args:\n      encoding (Optional[str]): input encoding.\n    \"\"\"\n    super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)", "title": ""}
{"_id": "d7774", "text": "def generate_split_tsv_lines(fn, header):\n    \"\"\"Returns dicts with header-keys and psm statistic values\"\"\"\n    for line in generate_tsv_psms_line(fn):\n        yield {x: y for (x, y) in zip(header, line.strip().split('\\t'))}", "title": ""}
{"_id": "d7775", "text": "def println(msg):\n    \"\"\"\n    Convenience function to print messages on a single line in the terminal\n    \"\"\"\n    sys.stdout.write(msg)\n    sys.stdout.flush()\n    sys.stdout.write('\\x08' * len(msg))\n    sys.stdout.flush()", "title": ""}
{"_id": "d7776", "text": "def issorted(list_, op=operator.le):\n    \"\"\"\n    Determines if a list is sorted\n\n    Args:\n        list_ (list):\n        op (func): sorted operation (default=operator.le)\n\n    Returns:\n        bool : True if the list is sorted\n    \"\"\"\n    return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))", "title": ""}
{"_id": "d7777", "text": "def nothread_quit(self, arg):\n        \"\"\" quit command when there's just one thread. \"\"\"\n\n        self.debugger.core.stop()\n        self.debugger.core.execution_status = 'Quit command'\n        raise Mexcept.DebuggerQuit", "title": ""}
{"_id": "d7778", "text": "def is_complex(dtype):\n  \"\"\"Returns whether this is a complex floating point type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_complex'):\n    return dtype.is_complex\n  return np.issubdtype(np.dtype(dtype), np.complex)", "title": ""}
{"_id": "d7779", "text": "def exit(self):\n        \"\"\"Stop the simple WSGI server running the appliation.\"\"\"\n        if self._server is not None:\n            self._server.shutdown()\n            self._server.server_close()\n            self._server = None", "title": ""}
{"_id": "d7780", "text": "def stop(self, reason=None):\n        \"\"\"Shutdown the service with a reason.\"\"\"\n        self.logger.info('stopping')\n        self.loop.stop(pyev.EVBREAK_ALL)", "title": ""}
{"_id": "d7781", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d7782", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d7783", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d7784", "text": "def __str__(self):\n        \"\"\"Executes self.function to convert LazyString instance to a real\n        str.\"\"\"\n        if not hasattr(self, '_str'):\n            self._str=self.function(*self.args, **self.kwargs)\n        return self._str", "title": ""}
{"_id": "d7785", "text": "def concat(cls, iterables):\n    \"\"\"\n    Similar to #itertools.chain.from_iterable().\n    \"\"\"\n\n    def generator():\n      for it in iterables:\n        for element in it:\n          yield element\n    return cls(generator())", "title": ""}
{"_id": "d7786", "text": "def next (self):    # File-like object.\n\n        \"\"\"This is to support iterators over a file-like object.\n        \"\"\"\n\n        result = self.readline()\n        if result == self._empty_buffer:\n            raise StopIteration\n        return result", "title": ""}
{"_id": "d7787", "text": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "title": ""}
{"_id": "d7788", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d7789", "text": "def runcoro(async_function):\n    \"\"\"\n    Runs an asynchronous function without needing to use await - useful for lambda\n\n    Args:\n        async_function (Coroutine): The asynchronous function to run\n    \"\"\"\n\n    future = _asyncio.run_coroutine_threadsafe(async_function, client.loop)\n    result = future.result()\n    return result", "title": ""}
{"_id": "d7790", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d7791", "text": "def to_camel_case(text):\n    \"\"\"Convert to camel case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    split = text.split('_')\n    return split[0] + \"\".join(x.title() for x in split[1:])", "title": ""}
{"_id": "d7792", "text": "def entropy(string):\n    \"\"\"Compute entropy on the string\"\"\"\n    p, lns = Counter(string), float(len(string))\n    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())", "title": ""}
{"_id": "d7793", "text": "def fill_nulls(self, col: str):\n        \"\"\"\n        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\")``\n        \"\"\"\n        n = [None, \"\"]\n        try:\n            self.df[col] = self.df[col].replace(n, nan)\n        except Exception as e:\n            self.err(e)", "title": ""}
{"_id": "d7794", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d7795", "text": "def notin(arg, values):\n    \"\"\"\n    Like isin, but checks whether this expression's value(s) are not\n    contained in the passed values. See isin docs for full usage.\n    \"\"\"\n    op = ops.NotContains(arg, values)\n    return op.to_expr()", "title": ""}
{"_id": "d7796", "text": "def exception_format():\n    \"\"\"\n    Convert exception info into a string suitable for display.\n    \"\"\"\n    return \"\".join(traceback.format_exception(\n        sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]\n    ))", "title": ""}
{"_id": "d7797", "text": "def graph_key_from_tag(tag, entity_index):\n    \"\"\"Returns a key from a tag entity\n\n    Args:\n        tag (tag) : this is the tag selected to get the key from\n        entity_index (int) : this is the index of the tagged entity\n\n    Returns:\n        str : String representing the key for the given tagged entity.\n    \"\"\"\n    start_token = tag.get('start_token')\n    entity = tag.get('entities', [])[entity_index]\n    return str(start_token) + '-' + entity.get('key') + '-' + str(entity.get('confidence'))", "title": ""}
{"_id": "d7798", "text": "def measure_string(self, text, fontname, fontsize, encoding=0):\n        \"\"\"Measure length of a string for a Base14 font.\"\"\"\n        return _fitz.Tools_measure_string(self, text, fontname, fontsize, encoding)", "title": ""}
{"_id": "d7799", "text": "def visit_BoolOp(self, node):\n        \"\"\" Return type may come from any boolop operand. \"\"\"\n        return sum((self.visit(value) for value in node.values), [])", "title": ""}
{"_id": "d7800", "text": "def __is__(cls, s):\n        \"\"\"Test if string matches this argument's format.\"\"\"\n        return s.startswith(cls.delims()[0]) and s.endswith(cls.delims()[1])", "title": ""}
{"_id": "d7801", "text": "def instance_contains(container, item):\n    \"\"\"Search into instance attributes, properties and return values of no-args methods.\"\"\"\n    return item in (member for _, member in inspect.getmembers(container))", "title": ""}
{"_id": "d7802", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d7803", "text": "def _internet_on(address):\n    \"\"\"\n    Check to see if the internet is on by pinging a set address.\n    :param address: the IP or address to hit\n    :return: a boolean - true if can be reached, false if not.\n    \"\"\"\n    try:\n        urllib2.urlopen(address, timeout=1)\n        return True\n    except urllib2.URLError as err:\n        return False", "title": ""}
{"_id": "d7804", "text": "def text_cleanup(data, key, last_type):\n    \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data", "title": ""}
{"_id": "d7805", "text": "def stft(func=None, **kwparams):\n  \"\"\"\n  Short Time Fourier Transform for real data keeping the full FFT block.\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,\n              inverse_transform=lambda *args: numpy.fft.ifft(*args).real)\n\n  See ``stft.base`` docs for more.\n  \"\"\"\n  from numpy.fft import fft, ifft\n  ifft_r = lambda *args: ifft(*args).real\n  return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)", "title": ""}
{"_id": "d7806", "text": "def to_snake_case(name):\n    \"\"\" Given a name in camelCase return in snake_case \"\"\"\n    s1 = FIRST_CAP_REGEX.sub(r'\\1_\\2', name)\n    return ALL_CAP_REGEX.sub(r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d7807", "text": "def stft(func=None, **kwparams):\n  \"\"\"\n  Short Time Fourier Transform for real data keeping the full FFT block.\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,\n              inverse_transform=lambda *args: numpy.fft.ifft(*args).real)\n\n  See ``stft.base`` docs for more.\n  \"\"\"\n  from numpy.fft import fft, ifft\n  ifft_r = lambda *args: ifft(*args).real\n  return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)", "title": ""}
{"_id": "d7808", "text": "def fsliceafter(astr, sub):\n    \"\"\"Return the slice after at sub in string astr\"\"\"\n    findex = astr.find(sub)\n    return astr[findex + len(sub):]", "title": ""}
{"_id": "d7809", "text": "def do_restart(self, line):\n        \"\"\"Request that the Outstation perform a cold restart. Command syntax is: restart\"\"\"\n        self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)", "title": ""}
{"_id": "d7810", "text": "def fsliceafter(astr, sub):\n    \"\"\"Return the slice after at sub in string astr\"\"\"\n    findex = astr.find(sub)\n    return astr[findex + len(sub):]", "title": ""}
{"_id": "d7811", "text": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "title": ""}
{"_id": "d7812", "text": "def bytes_to_c_array(data):\n    \"\"\"\n    Make a C array using the given string.\n    \"\"\"\n    chars = [\n        \"'{}'\".format(encode_escape(i))\n        for i in decode_escape(data)\n    ]\n    return ', '.join(chars) + ', 0'", "title": ""}
{"_id": "d7813", "text": "def is_string(val):\n    \"\"\"Determines whether the passed value is a string, safe for 2/3.\"\"\"\n    try:\n        basestring\n    except NameError:\n        return isinstance(val, str)\n    return isinstance(val, basestring)", "title": ""}
{"_id": "d7814", "text": "def _clean_str(self, s):\n        \"\"\" Returns a lowercase string with punctuation and bad chars removed\n        :param s: string to clean\n        \"\"\"\n        return s.translate(str.maketrans('', '', punctuation)).replace('\\u200b', \" \").strip().lower()", "title": ""}
{"_id": "d7815", "text": "def _print(self, msg, flush=False, end=\"\\n\"):\n        \"\"\"Helper function to print connection status messages when in verbose mode.\"\"\"\n        if self._verbose:\n            print2(msg, end=end, flush=flush)", "title": ""}
{"_id": "d7816", "text": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "title": ""}
{"_id": "d7817", "text": "def human__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n\n    # build data\n    N = 1000000\n    M = 3\n    X = np.zeros((N,M))\n    X.shape\n    y = np.zeros(N)\n    X[0, 0] = 1\n    y[0] = 8\n    X[1, 1] = 1\n    y[1] = 8\n    X[2, 0:2] = 1\n    y[2] = 4\n\n    # fit model\n    xor_model = sklearn.tree.DecisionTreeRegressor(max_depth=2)\n    xor_model.fit(X, y)\n\n    return xor_model", "title": ""}
{"_id": "d7818", "text": "def drop_trailing_zeros_decimal(num):\n    \"\"\" Drops the trailinz zeros from decimal value.\n        Returns a string\n    \"\"\"\n    out = str(num)\n    return out.rstrip('0').rstrip('.') if '.' in out else out", "title": ""}
{"_id": "d7819", "text": "def software_fibonacci(n):\n    \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n    a, b = 0, 1\n    for i in range(n):\n        a, b = b, a + b\n    return a", "title": ""}
{"_id": "d7820", "text": "def info(self, text):\n\t\t\"\"\" Ajout d'un message de log de type INFO \"\"\"\n\t\tself.logger.info(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d7821", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d7822", "text": "def write_document(doc, fnm):\n    \"\"\"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\n    \"\"\"\n    with codecs.open(fnm, 'wb', 'ascii') as f:\n        f.write(json.dumps(doc, indent=2))", "title": ""}
{"_id": "d7823", "text": "def bash(filename):\n    \"\"\"Runs a bash script in the local directory\"\"\"\n    sys.stdout.flush()\n    subprocess.call(\"bash {}\".format(filename), shell=True)", "title": ""}
{"_id": "d7824", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d7825", "text": "def _finish(self):\n        \"\"\"\n        Closes and waits for subprocess to exit.\n        \"\"\"\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", "title": ""}
{"_id": "d7826", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d7827", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d7828", "text": "def highpass(cutoff):\n  \"\"\"\n  This strategy uses an exponential approximation for cut-off frequency\n  calculation, found by matching the one-pole Laplace lowpass filter\n  and mirroring the resulting filter to get a highpass.\n  \"\"\"\n  R = thub(exp(cutoff - pi), 2)\n  return (1 - R) / (1 + R * z ** -1)", "title": ""}
{"_id": "d7829", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d7830", "text": "def median_high(data):\n    \"\"\"Return the high median of data.\n\n    When the number of data points is odd, the middle value is returned.\n    When it is even, the larger of the two middle values is returned.\n\n    \"\"\"\n    data = sorted(data)\n    n = len(data)\n    if n == 0:\n        raise StatisticsError(\"no median for empty data\")\n    return data[n // 2]", "title": ""}
{"_id": "d7831", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d7832", "text": "def any_contains_any(strings, candidates):\n    \"\"\"Whether any of the strings contains any of the candidates.\"\"\"\n    for string in strings:\n        for c in candidates:\n            if c in string:\n                return True", "title": ""}
{"_id": "d7833", "text": "def maybeparens(lparen, item, rparen):\n    \"\"\"Wrap an item in optional parentheses, only applying them if necessary.\"\"\"\n    return item | lparen.suppress() + item + rparen.suppress()", "title": ""}
{"_id": "d7834", "text": "def example_write_file_to_disk_if_changed():\n    \"\"\" Try to remove all comments from a file, and save it if changes were made. \"\"\"\n    my_file = FileAsObj('/tmp/example_file.txt')\n    my_file.rm(my_file.egrep('^#'))\n    if my_file.changed:\n        my_file.save()", "title": ""}
{"_id": "d7835", "text": "def exists(self):\n        \"\"\"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.\n        \"\"\"\n        client = self._instance._client\n        try:\n            client.instance_admin_client.get_cluster(name=self.name)\n            return True\n        # NOTE: There could be other exceptions that are returned to the user.\n        except NotFound:\n            return False", "title": ""}
{"_id": "d7836", "text": "def any_contains_any(strings, candidates):\n    \"\"\"Whether any of the strings contains any of the candidates.\"\"\"\n    for string in strings:\n        for c in candidates:\n            if c in string:\n                return True", "title": ""}
{"_id": "d7837", "text": "def getcolslice(self, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1):\n        \"\"\"Get a slice from a table column holding arrays.\n        (see :func:`table.getcolslice`)\"\"\"\n        return self._table.getcolslice(self._column, blc, trc, inc, startrow, nrow, rowincr)", "title": ""}
{"_id": "d7838", "text": "def handleFlaskPostRequest(flaskRequest, endpoint):\n    \"\"\"\n    Handles the specified flask request for one of the POST URLS\n    Invokes the specified endpoint to generate a response.\n    \"\"\"\n    if flaskRequest.method == \"POST\":\n        return handleHttpPost(flaskRequest, endpoint)\n    elif flaskRequest.method == \"OPTIONS\":\n        return handleHttpOptions()\n    else:\n        raise exceptions.MethodNotAllowedException()", "title": ""}
{"_id": "d7839", "text": "def top(n, width=WIDTH, style=STYLE):\n    \"\"\"Prints the top row of a table\"\"\"\n    return hrule(n, width, linestyle=STYLES[style].top)", "title": ""}
{"_id": "d7840", "text": "def get_path_from_query_string(req):\n    \"\"\"Gets path from query string\n\n    Args:\n        req (flask.request): Request object from Flask\n\n    Returns:\n        path (str): Value of \"path\" parameter from query string\n\n    Raises:\n        exceptions.UserError: If \"path\" is not found in query string\n    \"\"\"\n    if req.args.get('path') is None:\n        raise exceptions.UserError('Path not found in query string')\n    return req.args.get('path')", "title": ""}
{"_id": "d7841", "text": "def finish():\n    \"\"\"Print warning about interrupt and empty the job queue.\"\"\"\n    out.warn(\"Interrupted!\")\n    for t in threads:\n        t.stop()\n    jobs.clear()\n    out.warn(\"Waiting for download threads to finish.\")", "title": ""}
{"_id": "d7842", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d7843", "text": "def is_scalar(value):\n    \"\"\"Test if the given value is a scalar.\n\n    This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n    Args:\n        value: the value to test for being a scalar value\n\n    Returns:\n        boolean: if the given value is a scalar or not\n    \"\"\"\n    return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))", "title": ""}
{"_id": "d7844", "text": "def issubset(self, other):\n        \"\"\"Report whether another set contains this RangeSet.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issubset(self, other)", "title": ""}
{"_id": "d7845", "text": "def _squeeze(x, axis):\n  \"\"\"A version of squeeze that works with dynamic axis.\"\"\"\n  x = tf.convert_to_tensor(value=x, name='x')\n  if axis is None:\n    return tf.squeeze(x, axis=None)\n  axis = tf.convert_to_tensor(value=axis, name='axis', dtype=tf.int32)\n  axis += tf.zeros([1], dtype=axis.dtype)  # Make axis at least 1d.\n  keep_axis, _ = tf.compat.v1.setdiff1d(tf.range(0, tf.rank(x)), axis)\n  return tf.reshape(x, tf.gather(tf.shape(input=x), keep_axis))", "title": ""}
{"_id": "d7846", "text": "def _handle_authentication_error(self):\n        \"\"\"\n        Return an authentication error.\n        \"\"\"\n        response = make_response('Access Denied')\n        response.headers['WWW-Authenticate'] = self.auth.get_authenticate_header()\n        response.status_code = 401\n        return response", "title": ""}
{"_id": "d7847", "text": "def argmax(attrs, inputs, proto_obj):\n    \"\"\"Returns indices of the maximum values along an axis\"\"\"\n    axis = attrs.get('axis', 0)\n    keepdims = attrs.get('keepdims', 1)\n    argmax_op = symbol.argmax(inputs[0], axis=axis, keepdims=keepdims)\n    # onnx argmax operator always expects int64 as output type\n    cast_attrs = {'dtype': 'int64'}\n    return 'cast', cast_attrs, argmax_op", "title": ""}
{"_id": "d7848", "text": "def predict(self, X):\n        \"\"\"\n        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\n        \"\"\"\n        Xt, _, _ = self._transform(X)\n        return self._final_estimator.predict(Xt)", "title": ""}
{"_id": "d7849", "text": "def uniqify(cls, seq):\n        \"\"\"Returns a unique list of seq\"\"\"\n        seen = set()\n        seen_add = seen.add\n        return [ x for x in seq if x not in seen and not seen_add(x)]", "title": ""}
{"_id": "d7850", "text": "def available_gpus():\n  \"\"\"List of GPU device names detected by TensorFlow.\"\"\"\n  local_device_protos = device_lib.list_local_devices()\n  return [x.name for x in local_device_protos if x.device_type == 'GPU']", "title": ""}
{"_id": "d7851", "text": "def _ioctl (self, func, args):\n        \"\"\"Call ioctl() with given parameters.\"\"\"\n        import fcntl\n        return fcntl.ioctl(self.sockfd.fileno(), func, args)", "title": ""}
{"_id": "d7852", "text": "def flatten_all_but_last(a):\n  \"\"\"Flatten all dimensions of a except the last.\"\"\"\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", "title": ""}
{"_id": "d7853", "text": "def vline(self, x, y, height, color):\n        \"\"\"Draw a vertical line up to a given length.\"\"\"\n        self.rect(x, y, 1, height, color, fill=True)", "title": ""}
{"_id": "d7854", "text": "def assert_exactly_one_true(bool_list):\n    \"\"\"This method asserts that only one value of the provided list is True.\n\n    :param bool_list: List of booleans to check\n    :return: True if only one value is True, False otherwise\n    \"\"\"\n    assert isinstance(bool_list, list)\n    counter = 0\n    for item in bool_list:\n        if item:\n            counter += 1\n    return counter == 1", "title": ""}
{"_id": "d7855", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d7856", "text": "def is_closed(self):\n        \"\"\"\n        Are all entities connected to other entities.\n\n        Returns\n        -----------\n        closed : bool\n          Every entity is connected at its ends\n        \"\"\"\n        closed = all(i == 2 for i in\n                     dict(self.vertex_graph.degree()).values())\n\n        return closed", "title": ""}
{"_id": "d7857", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d7858", "text": "def is_lazy_iterable(obj):\n    \"\"\"\n    Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n    \"\"\"\n    return isinstance(obj,\n        (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))", "title": ""}
{"_id": "d7859", "text": "def series_index(self, series):\n        \"\"\"\n        Return the integer index of *series* in this sequence.\n        \"\"\"\n        for idx, s in enumerate(self):\n            if series is s:\n                return idx\n        raise ValueError('series not in chart data object')", "title": ""}
{"_id": "d7860", "text": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "title": ""}
{"_id": "d7861", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d7862", "text": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "title": ""}
{"_id": "d7863", "text": "def stdin_readable():\n    \"\"\"Determine whether stdin has any data to read.\"\"\"\n    if not WINDOWS:\n        try:\n            return bool(select([sys.stdin], [], [], 0)[0])\n        except Exception:\n            logger.log_exc()\n    try:\n        return not sys.stdin.isatty()\n    except Exception:\n        logger.log_exc()\n    return False", "title": ""}
{"_id": "d7864", "text": "def get_cell(self, index):\n        \"\"\"\n        For a single index and return the value\n\n        :param index: index value\n        :return: value\n        \"\"\"\n        i = sorted_index(self._index, index) if self._sort else self._index.index(index)\n        return self._data[i]", "title": ""}
{"_id": "d7865", "text": "def is_empty(self):\n        \"\"\"Returns True if the root node contains no child elements, no text,\n        and no attributes other than **type**. Returns False if any are present.\"\"\"\n        non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type']\n        return len(self.node) == 0 and len(non_type_attributes) == 0 \\\n            and not self.node.text and not self.node.tail", "title": ""}
{"_id": "d7866", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d7867", "text": "def __exit__(self, *exc_info):\n        \"\"\"Close connection to NATS when used in a context manager\"\"\"\n\n        self._loop.create_task(self._close(Client.CLOSED, True))", "title": ""}
{"_id": "d7868", "text": "def pprint(self, seconds):\n        \"\"\"\n        Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n        :param seconds:  The time in seconds.\n        \"\"\"\n        return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))", "title": ""}
{"_id": "d7869", "text": "def mcc(y, z):\n    \"\"\"Matthews correlation coefficient\n    \"\"\"\n    tp, tn, fp, fn = contingency_table(y, z)\n    return (tp * tn - fp * fn) / K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))", "title": ""}
{"_id": "d7870", "text": "def int2str(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from integers to strings\"\"\"\n    return NumConv(radix, alphabet).int2str(num)", "title": ""}
{"_id": "d7871", "text": "def time2seconds(t):\n    \"\"\"Returns seconds since 0h00.\"\"\"\n    return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6", "title": ""}
{"_id": "d7872", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d7873", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d7874", "text": "def Binary(x):\n    \"\"\"Return x as a binary type.\"\"\"\n    if isinstance(x, text_type) and not (JYTHON or IRONPYTHON):\n        return x.encode()\n    return bytes(x)", "title": ""}
{"_id": "d7875", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d7876", "text": "def value(self, progress_indicator):\n        \"\"\" Interpolate linearly between start and end \"\"\"\n        return interpolate.interpolate_linear_single(self.initial_value, self.final_value, progress_indicator)", "title": ""}
{"_id": "d7877", "text": "def focusNext(self, event):\n        \"\"\"Set focus to next item in sequence\"\"\"\n        try:\n            event.widget.tk_focusNext().focus_set()\n        except TypeError:\n            # see tkinter equivalent code for tk_focusNext to see\n            # commented original version\n            name = event.widget.tk.call('tk_focusNext', event.widget._w)\n            event.widget._nametowidget(str(name)).focus_set()", "title": ""}
{"_id": "d7878", "text": "def removeFromRegistery(obj) :\n\t\"\"\"Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory\n\ttaken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects,\n\tcascades to free the registeries of related rabalists also\"\"\"\n\t\n\tif isRabaObject(obj) :\n\t\t_unregisterRabaObjectInstance(obj)\n\telif isRabaList(obj) :\n\t\t_unregisterRabaListInstance(obj)", "title": ""}
{"_id": "d7879", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d7880", "text": "def removeFromRegistery(obj) :\n\t\"\"\"Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory\n\ttaken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects,\n\tcascades to free the registeries of related rabalists also\"\"\"\n\t\n\tif isRabaObject(obj) :\n\t\t_unregisterRabaObjectInstance(obj)\n\telif isRabaList(obj) :\n\t\t_unregisterRabaListInstance(obj)", "title": ""}
{"_id": "d7881", "text": "def get_all_items(self):\n        \"\"\"\n        Returns all items in the combobox dictionary.\n        \"\"\"\n        return [self._widget.itemText(k) for k in range(self._widget.count())]", "title": ""}
{"_id": "d7882", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d7883", "text": "def get_size(self):\n        \"\"\"see doc in Term class\"\"\"\n        self.curses.setupterm()\n        return self.curses.tigetnum('cols'), self.curses.tigetnum('lines')", "title": ""}
{"_id": "d7884", "text": "def find_if_expression_as_statement(node):\n    \"\"\"Finds an \"if\" expression as a statement\"\"\"\n    return (\n        isinstance(node, ast.Expr)\n        and isinstance(node.value, ast.IfExp)\n    )", "title": ""}
{"_id": "d7885", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d7886", "text": "def nonlocal_check(self, original, loc, tokens):\n        \"\"\"Check for Python 3 nonlocal statement.\"\"\"\n        return self.check_py(\"3\", \"nonlocal statement\", original, loc, tokens)", "title": ""}
{"_id": "d7887", "text": "def __grid_widgets(self):\n        \"\"\"Places all the child widgets in the appropriate positions.\"\"\"\n        scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n        self._canvas.grid(row=0, column=1, sticky=\"nswe\")\n        self._scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")", "title": ""}
{"_id": "d7888", "text": "def restore_scrollbar_position(self):\n        \"\"\"Restoring scrollbar position after main window is visible\"\"\"\n        scrollbar_pos = self.get_option('scrollbar_position', None)\n        if scrollbar_pos is not None:\n            self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)", "title": ""}
{"_id": "d7889", "text": "def singleton(class_):\n    \"\"\"Singleton definition.\n\n    Method 1 from\n    https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n    \"\"\"\n    instances = {}\n\n    def get_instance(*args, **kwargs):\n        if class_ not in instances:\n            instances[class_] = class_(*args, **kwargs)\n        return instances[class_]\n    return get_instance", "title": ""}
{"_id": "d7890", "text": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "title": ""}
{"_id": "d7891", "text": "def add_noise(Y, sigma):\n    \"\"\"Adds noise to Y\"\"\"\n    return Y + np.random.normal(0, sigma, Y.shape)", "title": ""}
{"_id": "d7892", "text": "def _dict_values_sorted_by_key(dictionary):\n    # This should be a yield from instead.\n    \"\"\"Internal helper to return the values of a dictionary, sorted by key.\n    \"\"\"\n    for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):\n        yield value", "title": ""}
{"_id": "d7893", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d7894", "text": "def add_bundled_jars():\n    \"\"\"\n    Adds the bundled jars to the JVM's classpath.\n    \"\"\"\n    # determine lib directory with jars\n    rootdir = os.path.split(os.path.dirname(__file__))[0]\n    libdir = rootdir + os.sep + \"lib\"\n\n    # add jars from lib directory\n    for l in glob.glob(libdir + os.sep + \"*.jar\"):\n        if l.lower().find(\"-src.\") == -1:\n            javabridge.JARS.append(str(l))", "title": ""}
{"_id": "d7895", "text": "def xyz2lonlat(x, y, z):\n    \"\"\"Convert cartesian to lon lat.\"\"\"\n    lon = xu.rad2deg(xu.arctan2(y, x))\n    lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2)))\n    return lon, lat", "title": ""}
{"_id": "d7896", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d7897", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d7898", "text": "def jupytext_cli(args=None):\n    \"\"\"Entry point for the jupytext script\"\"\"\n    try:\n        jupytext(args)\n    except (ValueError, TypeError, IOError) as err:\n        sys.stderr.write('[jupytext] Error: ' + str(err) + '\\n')\n        exit(1)", "title": ""}
{"_id": "d7899", "text": "def _get_user_agent(self):\n        \"\"\"Retrieve the request's User-Agent, if available.\n\n        Taken from Flask Login utils.py.\n        \"\"\"\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 ''", "title": ""}
{"_id": "d7900", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d7901", "text": "def __run(self):\n    \"\"\"Hacked run function, which installs the trace.\"\"\"\n    sys.settrace(self.globaltrace)\n    self.__run_backup()\n    self.run = self.__run_backup", "title": ""}
{"_id": "d7902", "text": "def timed_call(func, *args, log_level='DEBUG', **kwargs):\n    \"\"\"Logs a function's run time\n\n    :param func: The function to run\n    :param args: The args to pass to the function\n    :param kwargs: The keyword args to pass to the function\n    :param log_level: The log level at which to print the run time\n    :return: The function's return value\n    \"\"\"\n    start = time()\n    r = func(*args, **kwargs)\n    t = time() - start\n    log(log_level, \"Call to '{}' took {:0.6f}s\".format(func.__name__, t))\n    return r", "title": ""}
{"_id": "d7903", "text": "def iter_with_last(iterable):\n    \"\"\"\n    :return: generator of tuples (isLastFlag, item)\n    \"\"\"\n    # Ensure it's an iterator and get the first field\n    iterable = iter(iterable)\n    prev = next(iterable)\n    for item in iterable:\n        # Lag by one item so I know I'm not at the end\n        yield False, prev\n        prev = item\n    # Last item\n    yield True, prev", "title": ""}
{"_id": "d7904", "text": "def pprint(self, ind):\n        \"\"\"pretty prints the tree with indentation\"\"\"\n        pp = pprint.PrettyPrinter(indent=ind)\n        pp.pprint(self.tree)", "title": ""}
{"_id": "d7905", "text": "def is_numeric(value):\n        \"\"\"Test if a value is numeric.\n        \"\"\"\n        return type(value) in [\n            int,\n            float,\n            \n            np.int8,\n            np.int16,\n            np.int32,\n            np.int64,\n\n            np.float16,\n            np.float32,\n            np.float64,\n            np.float128\n        ]", "title": ""}
{"_id": "d7906", "text": "def _trim(self, somestr):\n        \"\"\" Trim left-right given string \"\"\"\n        tmp = RE_LSPACES.sub(\"\", somestr)\n        tmp = RE_TSPACES.sub(\"\", tmp)\n        return str(tmp)", "title": ""}
{"_id": "d7907", "text": "def _make_sentence(txt):\n    \"\"\"Make a sentence from a piece of text.\"\"\"\n    #Make sure first letter is capitalized\n    txt = txt.strip(' ')\n    txt = txt[0].upper() + txt[1:] + '.'\n    return txt", "title": ""}
{"_id": "d7908", "text": "def _trim(self, somestr):\n        \"\"\" Trim left-right given string \"\"\"\n        tmp = RE_LSPACES.sub(\"\", somestr)\n        tmp = RE_TSPACES.sub(\"\", tmp)\n        return str(tmp)", "title": ""}
{"_id": "d7909", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d7910", "text": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "title": ""}
{"_id": "d7911", "text": "def keyPressEvent(self, event):\n        \"\"\"\n        Pyqt specific key press callback function.\n        Translates and forwards events to :py:func:`keyboard_event`.\n        \"\"\"\n        self.keyboard_event(event.key(), self.keys.ACTION_PRESS, 0)", "title": ""}
{"_id": "d7912", "text": "def retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n\t\"\"\"\n\tGiven a callable func, trap the indicated exceptions\n\tfor up to 'retries' times, invoking cleanup on the\n\texception. On the final attempt, allow any exceptions\n\tto propagate.\n\t\"\"\"\n\tattempts = count() if retries == float('inf') else range(retries)\n\tfor attempt in attempts:\n\t\ttry:\n\t\t\treturn func()\n\t\texcept trap:\n\t\t\tcleanup()\n\n\treturn func()", "title": ""}
{"_id": "d7913", "text": "def _try_join_cancelled_thread(thread):\n    \"\"\"Join a thread, but if the thread doesn't terminate for some time, ignore it\n    instead of waiting infinitely.\"\"\"\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)", "title": ""}
{"_id": "d7914", "text": "def retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n\t\"\"\"\n\tGiven a callable func, trap the indicated exceptions\n\tfor up to 'retries' times, invoking cleanup on the\n\texception. On the final attempt, allow any exceptions\n\tto propagate.\n\t\"\"\"\n\tattempts = count() if retries == float('inf') else range(retries)\n\tfor attempt in attempts:\n\t\ttry:\n\t\t\treturn func()\n\t\texcept trap:\n\t\t\tcleanup()\n\n\treturn func()", "title": ""}
{"_id": "d7915", "text": "def classify_clusters(points, n=10):\n    \"\"\"\n    Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects.\n    \"\"\"\n    arr = [[p.x, p.y] for p in points.values]\n    clf = KMeans(n_clusters=n)\n    clf.fit(arr)\n    classes = clf.predict(arr)\n    return classes", "title": ""}
{"_id": "d7916", "text": "def yview(self, *args):\n        \"\"\"Update inplace widgets position when doing vertical scroll\"\"\"\n        self.after_idle(self.__updateWnds)\n        ttk.Treeview.yview(self, *args)", "title": ""}
{"_id": "d7917", "text": "def fit(self, X):\n        \"\"\" Apply KMeans Clustering\n              X: dataset with feature vectors\n        \"\"\"\n        self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \\\n              _kmeans(X, self.n_clusters, self.max_iter, self.n_trials, self.tol)", "title": ""}
{"_id": "d7918", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d7919", "text": "def l2_norm(arr):\n    \"\"\"\n    The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n    dot product of the vector.\n    \"\"\"\n    arr = np.asarray(arr)\n    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "title": ""}
{"_id": "d7920", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d7921", "text": "def projR(gamma, p):\n    \"\"\"return the KL projection on the row constrints \"\"\"\n    return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T", "title": ""}
{"_id": "d7922", "text": "def hash_iterable(it):\n\t\"\"\"Perform a O(1) memory hash of an iterable of arbitrary length.\n\n\thash(tuple(it)) creates a temporary tuple containing all values from it\n\twhich could be a problem if it is large.\n\n\tSee discussion at:\n\thttps://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ\n\t\"\"\"\n\thash_value = hash(type(it))\n\tfor value in it:\n\t\thash_value = hash((hash_value, value))\n\treturn hash_value", "title": ""}
{"_id": "d7923", "text": "def iter_with_last(iterable):\n    \"\"\"\n    :return: generator of tuples (isLastFlag, item)\n    \"\"\"\n    # Ensure it's an iterator and get the first field\n    iterable = iter(iterable)\n    prev = next(iterable)\n    for item in iterable:\n        # Lag by one item so I know I'm not at the end\n        yield False, prev\n        prev = item\n    # Last item\n    yield True, prev", "title": ""}
{"_id": "d7924", "text": "def norm_vec(vector):\n    \"\"\"Normalize the length of a vector to one\"\"\"\n    assert len(vector) == 3\n    v = np.array(vector)\n    return v/np.sqrt(np.sum(v**2))", "title": ""}
{"_id": "d7925", "text": "def json_to_initkwargs(self, json_data, kwargs):\n        \"\"\"Subclassing hook to specialize how JSON data is converted\n        to keyword arguments\"\"\"\n        if isinstance(json_data, basestring):\n            json_data = json.loads(json_data)\n        return json_to_initkwargs(self, json_data, kwargs)", "title": ""}
{"_id": "d7926", "text": "def heappush_max(heap, item):\n    \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n    heap.append(item)\n    _siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d7927", "text": "def json_to_initkwargs(self, json_data, kwargs):\n        \"\"\"Subclassing hook to specialize how JSON data is converted\n        to keyword arguments\"\"\"\n        if isinstance(json_data, basestring):\n            json_data = json.loads(json_data)\n        return json_to_initkwargs(self, json_data, kwargs)", "title": ""}
{"_id": "d7928", "text": "def bytes_to_str(s, encoding='utf-8'):\n    \"\"\"Returns a str if a bytes object is given.\"\"\"\n    if six.PY3 and isinstance(s, bytes):\n        return s.decode(encoding)\n    return s", "title": ""}
{"_id": "d7929", "text": "def set_ylimits(self, row, column, min=None, max=None):\n        \"\"\"Set y-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_ylimits(min, max)", "title": ""}
{"_id": "d7930", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d7931", "text": "def fit_linear(X, y):\n    \"\"\"\n    Uses OLS to fit the regression.\n    \"\"\"\n    model = linear_model.LinearRegression()\n    model.fit(X, y)\n    return model", "title": ""}
{"_id": "d7932", "text": "def delayed_close(self):\n        \"\"\" Delayed close - won't close immediately, but on the next reactor\n        loop. \"\"\"\n        self.state = SESSION_STATE.CLOSING\n        reactor.callLater(0, self.close)", "title": ""}
{"_id": "d7933", "text": "def get_free_memory_win():\n    \"\"\"Return current free memory on the machine for windows.\n\n    Warning : this script is really not robust\n    Return in MB unit\n    \"\"\"\n    stat = MEMORYSTATUSEX()\n    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n    return int(stat.ullAvailPhys / 1024 / 1024)", "title": ""}
{"_id": "d7934", "text": "def search_for_tweets_about(user_id, params):\n    \"\"\" Search twitter API \"\"\"\n    url = \"https://api.twitter.com/1.1/search/tweets.json\"\n    response = make_twitter_request(url, user_id, params)\n    return process_tweets(response.json()[\"statuses\"])", "title": ""}
{"_id": "d7935", "text": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "title": ""}
{"_id": "d7936", "text": "def urlize_twitter(text):\n    \"\"\"\n    Replace #hashtag and @username references in a tweet with HTML text.\n    \"\"\"\n    html = TwitterText(text).autolink.auto_link()\n    return mark_safe(html.replace(\n        'twitter.com/search?q=', 'twitter.com/search/realtime/'))", "title": ""}
{"_id": "d7937", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d7938", "text": "def is_int_type(val):\n    \"\"\"Return True if `val` is of integer type.\"\"\"\n    try:               # Python 2\n        return isinstance(val, (int, long))\n    except NameError:  # Python 3\n        return isinstance(val, int)", "title": ""}
{"_id": "d7939", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d7940", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d7941", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d7942", "text": "def test(ctx, all=False, verbose=False):\n    \"\"\"Run the tests.\"\"\"\n    cmd = 'tox' if all else 'py.test'\n    if verbose:\n        cmd += ' -v'\n    return ctx.run(cmd, pty=True).return_code", "title": ""}
{"_id": "d7943", "text": "def h5ToDict(h5, readH5pyDataset=True):\n    \"\"\" Read a hdf5 file into a dictionary \"\"\"\n    h = h5py.File(h5, \"r\")\n    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n    if readH5pyDataset: h.close()\n    return ret", "title": ""}
{"_id": "d7944", "text": "def cover(session):\n    \"\"\"Run the final coverage report.\n    This outputs the coverage report aggregating coverage from the unit\n    test runs (not system test runs), and then erases coverage data.\n    \"\"\"\n    session.interpreter = 'python3.6'\n    session.install('coverage', 'pytest-cov')\n    session.run('coverage', 'report', '--show-missing', '--fail-under=100')\n    session.run('coverage', 'erase')", "title": ""}
{"_id": "d7945", "text": "def decode_example(self, example):\n    \"\"\"Reconstruct the image from the tf example.\"\"\"\n    img = tf.image.decode_image(\n        example, channels=self._shape[-1], dtype=tf.uint8)\n    img.set_shape(self._shape)\n    return img", "title": ""}
{"_id": "d7946", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d7947", "text": "def load_db(file, db, verbose=True):\n    \"\"\"\n    Load :class:`mongomock.database.Database` from a local file.\n\n    :param file: file path.\n    :param db: instance of :class:`mongomock.database.Database`.\n    :param verbose: bool, toggle on log.\n    :return: loaded db.\n    \"\"\"\n    db_data = json.load(file, verbose=verbose)\n    return _load(db_data, db)", "title": ""}
{"_id": "d7948", "text": "def from_file(filename):\n    \"\"\"\n    load an nparray object from a json filename\n\n    @parameter str filename: path to the file\n    \"\"\"\n    f = open(filename, 'r')\n    j = json.load(f)\n    f.close()\n\n    return from_dict(j)", "title": ""}
{"_id": "d7949", "text": "def get_time():\n    \"\"\"Get time from a locally running NTP server\"\"\"\n\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)", "title": ""}
{"_id": "d7950", "text": "def plfit_lsq(x,y):\n    \"\"\"\n    Returns A and B in y=Ax^B\n    http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html\n    \"\"\"\n    n = len(x)\n    btop = n * (log(x)*log(y)).sum() - (log(x)).sum()*(log(y)).sum()\n    bbottom = n*(log(x)**2).sum() - (log(x).sum())**2\n    b = btop / bbottom\n    a = ( log(y).sum() - b * log(x).sum() ) / n\n\n    A = exp(a)\n    return A,b", "title": ""}
{"_id": "d7951", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d7952", "text": "def logger(message, level=10):\n    \"\"\"Handle logging.\"\"\"\n    logging.getLogger(__name__).log(level, str(message))", "title": ""}
{"_id": "d7953", "text": "def open_usb_handle(self, port_num):\n    \"\"\"open usb port\n\n    Args:\n      port_num: port number on the Cambrionix unit\n\n    Return:\n      usb handle\n    \"\"\"\n    serial = self.get_usb_serial(port_num)\n    return local_usb.LibUsbHandle.open(serial_number=serial)", "title": ""}
{"_id": "d7954", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d7955", "text": "def list2dict(list_of_options):\n    \"\"\"Transforms a list of 2 element tuples to a dictionary\"\"\"\n    d = {}\n    for key, value in list_of_options:\n        d[key] = value\n    return d", "title": ""}
{"_id": "d7956", "text": "def survival(value=t, lam=lam, f=failure):\n    \"\"\"Exponential survival likelihood, accounting for censoring\"\"\"\n    return sum(f * log(lam) - lam * value)", "title": ""}
{"_id": "d7957", "text": "def put_pidfile( pidfile_path, pid ):\n    \"\"\"\n    Put a PID into a pidfile\n    \"\"\"\n    with open( pidfile_path, \"w\" ) as f:\n        f.write(\"%s\" % pid)\n        os.fsync(f.fileno())\n\n    return", "title": ""}
{"_id": "d7958", "text": "def _log_multivariate_normal_density_tied(X, means, covars):\n    \"\"\"Compute Gaussian log-density at X for a tied model.\"\"\"\n    cv = np.tile(covars, (means.shape[0], 1, 1))\n    return _log_multivariate_normal_density_full(X, means, cv)", "title": ""}
{"_id": "d7959", "text": "def to_camel(s):\n    \"\"\"\n    :param string s: under_scored string to be CamelCased\n    :return: CamelCase version of input\n    :rtype: str\n    \"\"\"\n    # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n    return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "title": ""}
{"_id": "d7960", "text": "def _eq(self, other):\n        \"\"\"Compare two nodes for equality.\"\"\"\n        return (self.type, self.value) == (other.type, other.value)", "title": ""}
{"_id": "d7961", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d7962", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d7963", "text": "def copy(obj):\n    def copy(self):\n        \"\"\"\n        Copy self to a new object.\n        \"\"\"\n        from copy import deepcopy\n\n        return deepcopy(self)\n    obj.copy = copy\n    return obj", "title": ""}
{"_id": "d7964", "text": "def get_all_files(folder):\n    \"\"\"\n    Generator that loops through all absolute paths of the files within folder\n\n    Parameters\n    ----------\n    folder: str\n    Root folder start point for recursive search.\n\n    Yields\n    ------\n    fpath: str\n    Absolute path of one file in the folders\n    \"\"\"\n    for path, dirlist, filelist in os.walk(folder):\n        for fn in filelist:\n            yield op.join(path, fn)", "title": ""}
{"_id": "d7965", "text": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "title": ""}
{"_id": "d7966", "text": "def _adjust_offset(self, real_wave_mfcc, algo_parameters):\n        \"\"\"\n        OFFSET\n        \"\"\"\n        self.log(u\"Called _adjust_offset\")\n        self._apply_offset(offset=algo_parameters[0])", "title": ""}
{"_id": "d7967", "text": "def cols_str(columns):\n    \"\"\"Concatenate list of columns into a string.\"\"\"\n    cols = \"\"\n    for c in columns:\n        cols = cols + wrap(c) + ', '\n    return cols[:-2]", "title": ""}
{"_id": "d7968", "text": "def _ws_on_close(self, ws: websocket.WebSocketApp):\n        \"\"\"Callback for closing the websocket connection\n\n        Args:\n            ws: websocket connection (now closed)\n        \"\"\"\n        self.connected = False\n        self.logger.error('Websocket closed')\n        self._reconnect_websocket()", "title": ""}
{"_id": "d7969", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d7970", "text": "def cell_ends_with_code(lines):\n    \"\"\"Is the last line of the cell a line with code?\"\"\"\n    if not lines:\n        return False\n    if not lines[-1].strip():\n        return False\n    if lines[-1].startswith('#'):\n        return False\n    return True", "title": ""}
{"_id": "d7971", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d7972", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d7973", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d7974", "text": "def set_cursor(self, x, y):\n        \"\"\"\n        Sets the cursor to the desired position.\n\n        :param x: X position\n        :param y: Y position\n        \"\"\"\n        curses.curs_set(1)\n        self.screen.move(y, x)", "title": ""}
{"_id": "d7975", "text": "def house_explosions():\n    \"\"\"\n    Data from http://indexed.blogspot.com/2007/12/meltdown-indeed.html\n    \"\"\"\n    chart = PieChart2D(int(settings.width * 1.7), settings.height)\n    chart.add_data([10, 10, 30, 200])\n    chart.set_pie_labels([\n        'Budding Chemists',\n        'Propane issues',\n        'Meth Labs',\n        'Attempts to escape morgage',\n        ])\n    chart.download('pie-house-explosions.png')", "title": ""}
{"_id": "d7976", "text": "def RecurseKeys(self):\n    \"\"\"Recurses the subkeys starting with the key.\n\n    Yields:\n      WinRegistryKey: Windows Registry key.\n    \"\"\"\n    yield self\n    for subkey in self.GetSubkeys():\n      for key in subkey.RecurseKeys():\n        yield key", "title": ""}
{"_id": "d7977", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d7978", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d7979", "text": "def save_dict_to_file(filename, dictionary):\n  \"\"\"Saves dictionary as CSV file.\"\"\"\n  with open(filename, 'w') as f:\n    writer = csv.writer(f)\n    for k, v in iteritems(dictionary):\n      writer.writerow([str(k), str(v)])", "title": ""}
{"_id": "d7980", "text": "def matches(self, s):\n    \"\"\"Whether the pattern matches anywhere in the string s.\"\"\"\n    regex_matches = self.compiled_regex.search(s) is not None\n    return not regex_matches if self.inverted else regex_matches", "title": ""}
{"_id": "d7981", "text": "def save_notebook(work_notebook, write_file):\n    \"\"\"Saves the Jupyter work_notebook to write_file\"\"\"\n    with open(write_file, 'w') as out_nb:\n        json.dump(work_notebook, out_nb, indent=2)", "title": ""}
{"_id": "d7982", "text": "def get_tri_area(pts):\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d7983", "text": "def write_tsv_line_from_list(linelist, outfp):\n    \"\"\"Utility method to convert list to tsv line with carriage return\"\"\"\n    line = '\\t'.join(linelist)\n    outfp.write(line)\n    outfp.write('\\n')", "title": ""}
{"_id": "d7984", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d7985", "text": "def save_hdf(self,filename,path=''):\n        \"\"\"Saves all relevant data to .h5 file; so state can be restored.\n        \"\"\"\n        self.dataframe.to_hdf(filename,'{}/df'.format(path))", "title": ""}
{"_id": "d7986", "text": "def get_adjacent_matrix(self):\n        \"\"\"Get adjacency matrix.\n\n        Returns:\n            :param adj: adjacency matrix\n            :type adj: np.ndarray\n        \"\"\"\n        edges = self.edges\n        num_edges = len(edges) + 1\n        adj = np.zeros([num_edges, num_edges])\n\n        for k in range(num_edges - 1):\n            adj[edges[k].L, edges[k].R] = 1\n            adj[edges[k].R, edges[k].L] = 1\n\n        return adj", "title": ""}
{"_id": "d7987", "text": "def _write_json(file, contents):\n    \"\"\"Write a dict to a JSON file.\"\"\"\n    with open(file, 'w') as f:\n        return json.dump(contents, f, indent=2, sort_keys=True)", "title": ""}
{"_id": "d7988", "text": "def peak_memory_usage():\n    \"\"\"Return peak memory usage in MB\"\"\"\n    if sys.platform.startswith('win'):\n        p = psutil.Process()\n        return p.memory_info().peak_wset / 1024 / 1024\n\n    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n    factor_mb = 1 / 1024\n    if sys.platform == 'darwin':\n        factor_mb = 1 / (1024 * 1024)\n    return mem * factor_mb", "title": ""}
{"_id": "d7989", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d7990", "text": "def linedelimited (inlist,delimiter):\n    \"\"\"\nReturns a string composed of elements in inlist, with each element\nseparated by 'delimiter.'  Used by function writedelimited.  Use '\\t'\nfor tab-delimiting.\n\nUsage:   linedelimited (inlist,delimiter)\n\"\"\"\n    outstr = ''\n    for item in inlist:\n        if type(item) != StringType:\n            item = str(item)\n        outstr = outstr + item + delimiter\n    outstr = outstr[0:-1]\n    return outstr", "title": ""}
{"_id": "d7991", "text": "def memory_usage(method):\n  \"\"\"Log memory usage before and after a method.\"\"\"\n  def wrapper(*args, **kwargs):\n    logging.info('Memory before method %s is %s.',\n                 method.__name__, runtime.memory_usage().current())\n    result = method(*args, **kwargs)\n    logging.info('Memory after method %s is %s',\n                 method.__name__, runtime.memory_usage().current())\n    return result\n  return wrapper", "title": ""}
{"_id": "d7992", "text": "def copy_of_xml_element(elem):\n    \"\"\"\n    This method returns a shallow copy of a XML-Element.\n    This method is for compatibility with Python 2.6 or earlier..\n    In Python 2.7 you can use  'copyElem = elem.copy()'  instead.\n    \"\"\"\n\n    copyElem = ElementTree.Element(elem.tag, elem.attrib)\n    for child in elem:\n        copyElem.append(child)\n    return copyElem", "title": ""}
{"_id": "d7993", "text": "def __ror__(self, other):\n\t\t\"\"\"The main machinery of the Pipe, calling the chosen callable with the recorded arguments.\"\"\"\n\t\t\n\t\treturn self.callable(*(self.args + (other, )), **self.kwargs)", "title": ""}
{"_id": "d7994", "text": "def _get_minidom_tag_value(station, tag_name):\n    \"\"\"get a value from a tag (if it exists)\"\"\"\n    tag = station.getElementsByTagName(tag_name)[0].firstChild\n    if tag:\n        return tag.nodeValue\n\n    return None", "title": ""}
{"_id": "d7995", "text": "def _flush(self, buffer):\n        \"\"\"\n        Flush the write buffers of the stream if applicable.\n\n        Args:\n            buffer (memoryview): Buffer content.\n        \"\"\"\n        container, obj = self._client_args\n        with _handle_client_exception():\n            self._client.put_object(container, obj, buffer)", "title": ""}
{"_id": "d7996", "text": "def xml_str_to_dict(s):\n    \"\"\" Transforms an XML string it to python-zimbra dict format\n\n    For format, see:\n      https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n    :param: a string, containing XML\n    :returns: a dict, with python-zimbra format\n    \"\"\"\n    xml = minidom.parseString(s)\n    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)", "title": ""}
{"_id": "d7997", "text": "def oplot(self, x, y, **kw):\n        \"\"\"generic plotting method, overplotting any existing plot \"\"\"\n        self.panel.oplot(x, y, **kw)", "title": ""}
{"_id": "d7998", "text": "def series_table_row_offset(self, series):\n        \"\"\"\n        Return the number of rows preceding the data table for *series* in\n        the Excel worksheet.\n        \"\"\"\n        title_and_spacer_rows = series.index * 2\n        data_point_rows = series.data_point_offset\n        return title_and_spacer_rows + data_point_rows", "title": ""}
{"_id": "d7999", "text": "def transformer_tall_pretrain_lm_tpu_adafactor():\n  \"\"\"Hparams for transformer on LM pretraining (with 64k vocab) on TPU.\"\"\"\n  hparams = transformer_tall_pretrain_lm()\n  update_hparams_for_tpu(hparams)\n  hparams.max_length = 1024\n  # For multi-problem on TPU we need it in absolute examples.\n  hparams.batch_size = 8\n  hparams.multiproblem_vocab_size = 2**16\n  return hparams", "title": ""}
{"_id": "d8000", "text": "def extent(self):\n        \"\"\"Helper for matplotlib imshow\"\"\"\n        return (\n            self.intervals[1].pix1 - 0.5,\n            self.intervals[1].pix2 - 0.5,\n            self.intervals[0].pix1 - 0.5,\n            self.intervals[0].pix2 - 0.5,\n        )", "title": ""}
{"_id": "d8001", "text": "def api_test(method='GET', **response_kwargs):\n    \"\"\" Decorator to ensure API calls are made and return expected data. \"\"\"\n\n    method = method.lower()\n\n    def api_test_factory(fn):\n        @functools.wraps(fn)\n        @mock.patch('requests.{}'.format(method))\n        def execute_test(method_func, *args, **kwargs):\n            method_func.return_value = MockResponse(**response_kwargs)\n\n            expected_url, response = fn(*args, **kwargs)\n\n            method_func.assert_called_once()\n            assert_valid_api_call(method_func, expected_url)\n            assert isinstance(response, JSONAPIParser)\n            assert response.json_data is method_func.return_value.data\n\n        return execute_test\n\n    return api_test_factory", "title": ""}
{"_id": "d8002", "text": "def vertical_percent(plot, percent=0.1):\n    \"\"\"\n    Using the size of the y axis, return a fraction of that size.\n    \"\"\"\n    plot_bottom, plot_top = plot.get_ylim()\n    return percent * (plot_top - plot_bottom)", "title": ""}
{"_id": "d8003", "text": "def all_collections(db):\n\t\"\"\"\n\tYield all non-sytem collections in db.\n\t\"\"\"\n\tinclude_pattern = r'(?!system\\.)'\n\treturn (\n\t\tdb[name]\n\t\tfor name in db.list_collection_names()\n\t\tif re.match(include_pattern, name)\n\t)", "title": ""}
{"_id": "d8004", "text": "def _ParseYamlFromFile(filedesc):\n  \"\"\"Parses given YAML file.\"\"\"\n  content = filedesc.read()\n  return yaml.Parse(content) or collections.OrderedDict()", "title": ""}
{"_id": "d8005", "text": "def get_axis(array, axis, slice_num):\n    \"\"\"Returns a fixed axis\"\"\"\n\n    slice_list = [slice(None)] * array.ndim\n    slice_list[axis] = slice_num\n    slice_data = array[tuple(slice_list)].T  # transpose for proper orientation\n\n    return slice_data", "title": ""}
{"_id": "d8006", "text": "def print_yaml(o):\n    \"\"\"Pretty print an object as YAML.\"\"\"\n    print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))", "title": ""}
{"_id": "d8007", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d8008", "text": "def comments(tag, limit=0, flags=0, **kwargs):\n    \"\"\"Get comments only.\"\"\"\n\n    return [comment for comment in cm.CommentsMatch(tag).get_comments(limit)]", "title": ""}
{"_id": "d8009", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d8010", "text": "def replace_sys_args(new_args):\n    \"\"\"Temporarily replace sys.argv with current arguments\n\n    Restores sys.argv upon exit of the context manager.\n    \"\"\"\n    # Replace sys.argv arguments\n    # for module import\n    old_args = sys.argv\n    sys.argv = new_args\n    try:\n        yield\n    finally:\n        sys.argv = old_args", "title": ""}
{"_id": "d8011", "text": "def extract(self, destination):\n        \"\"\"Extract the archive.\"\"\"\n        with zipfile.ZipFile(self.archive, 'r') as zip_ref:\n            zip_ref.extractall(destination)", "title": ""}
{"_id": "d8012", "text": "def map_keys_deep(f, dct):\n    \"\"\"\n    Implementation of map that recurses. This tests the same keys at every level of dict and in lists\n    :param f: 2-ary function expecting a key and value and returns a modified key\n    :param dct: Dict for deep processing\n    :return: Modified dct with matching props mapped\n    \"\"\"\n    return _map_deep(lambda k, v: [f(k, v), v], dct)", "title": ""}
{"_id": "d8013", "text": "def compressBuffer(buffer):\n    \"\"\"\n    Note that this code compresses into a buffer held in memory, rather\n    than a disk file. This is done through the use of cStringIO.StringIO().\n    \"\"\"\n    # http://jython.xhaus.com/http-compression-in-python-and-jython/\n    zbuf = cStringIO.StringIO()\n    zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)\n    zfile.write(buffer)\n    zfile.close()\n    return zbuf.getvalue()", "title": ""}
{"_id": "d8014", "text": "def step_next_line(self):\n        \"\"\"Sets cursor as beginning of next line.\"\"\"\n        self._eol.append(self.position)\n        self._lineno += 1\n        self._col_offset = 0", "title": ""}
{"_id": "d8015", "text": "def __init__(self, stream_start):\n    \"\"\"Initializes a gzip member decompressor wrapper.\n\n    Args:\n      stream_start (int): offset to the compressed stream within the containing\n          file object.\n    \"\"\"\n    self._decompressor = zlib_decompressor.DeflateDecompressor()\n    self.last_read = stream_start\n    self.uncompressed_offset = 0\n    self._compressed_data = b''", "title": ""}
{"_id": "d8016", "text": "def bulk_query(self, query, *multiparams):\n        \"\"\"Bulk insert or update.\"\"\"\n\n        with self.get_connection() as conn:\n            conn.bulk_query(query, *multiparams)", "title": ""}
{"_id": "d8017", "text": "def mean_date(dt_list):\n    \"\"\"Calcuate mean datetime from datetime list\n    \"\"\"\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", "title": ""}
{"_id": "d8018", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d8019", "text": "def changed(self, *value):\n        \"\"\"Checks whether the value has changed since the last call.\"\"\"\n        if self._last_checked_value != value:\n            self._last_checked_value = value\n            return True\n        return False", "title": ""}
{"_id": "d8020", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d8021", "text": "def get_all_files(folder):\n    \"\"\"\n    Generator that loops through all absolute paths of the files within folder\n\n    Parameters\n    ----------\n    folder: str\n    Root folder start point for recursive search.\n\n    Yields\n    ------\n    fpath: str\n    Absolute path of one file in the folders\n    \"\"\"\n    for path, dirlist, filelist in os.walk(folder):\n        for fn in filelist:\n            yield op.join(path, fn)", "title": ""}
{"_id": "d8022", "text": "def draw_header(self, stream, header):\n        \"\"\"Draw header with underline\"\"\"\n        stream.writeln('=' * (len(header) + 4))\n        stream.writeln('| ' + header + ' |')\n        stream.writeln('=' * (len(header) + 4))\n        stream.writeln()", "title": ""}
{"_id": "d8023", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d8024", "text": "def get_server(address=None):\n        \"\"\"Return an SMTP servername guess from outgoing email address.\"\"\"\n        if address:\n            domain = address.split(\"@\")[1]\n            try:\n                return SMTP_SERVERS[domain]\n            except KeyError:\n                return (\"smtp.\" + domain, 465)\n        return (None, None)", "title": ""}
{"_id": "d8025", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d8026", "text": "def nlevels(self):\n        \"\"\"\n        Get the number of factor levels for each categorical column.\n\n        :returns: A list of the number of levels per column.\n        \"\"\"\n        levels = self.levels()\n        return [len(l) for l in levels] if levels else 0", "title": ""}
{"_id": "d8027", "text": "def to_str(s):\n    \"\"\"\n    Convert bytes and non-string into Python 3 str\n    \"\"\"\n    if isinstance(s, bytes):\n        s = s.decode('utf-8')\n    elif not isinstance(s, str):\n        s = str(s)\n    return s", "title": ""}
{"_id": "d8028", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d8029", "text": "def is_string(obj):\n    \"\"\"Is this a string.\n\n    :param object obj:\n    :rtype: bool\n    \"\"\"\n    if PYTHON3:\n        str_type = (bytes, str)\n    else:\n        str_type = (bytes, str, unicode)\n    return isinstance(obj, str_type)", "title": ""}
{"_id": "d8030", "text": "def _normalize_abmn(abmn):\n    \"\"\"return a normalized version of abmn\n    \"\"\"\n    abmn_2d = np.atleast_2d(abmn)\n    abmn_normalized = np.hstack((\n        np.sort(abmn_2d[:, 0:2], axis=1),\n        np.sort(abmn_2d[:, 2:4], axis=1),\n    ))\n    return abmn_normalized", "title": ""}
{"_id": "d8031", "text": "def _get_line_no_from_comments(py_line):\n    \"\"\"Return the line number parsed from the comment or 0.\"\"\"\n    matched = LINECOL_COMMENT_RE.match(py_line)\n    if matched:\n        return int(matched.group(1))\n    else:\n        return 0", "title": ""}
{"_id": "d8032", "text": "def denorm(self,arr):\n        \"\"\"Reverse the normalization done to a batch of images.\n\n        Arguments:\n            arr: of shape/size (N,3,sz,sz)\n        \"\"\"\n        if type(arr) is not np.ndarray: arr = to_np(arr)\n        if len(arr.shape)==3: arr = arr[None]\n        return self.transform.denorm(np.rollaxis(arr,1,4))", "title": ""}
{"_id": "d8033", "text": "def QA_util_datetime_to_strdate(dt):\n    \"\"\"\n    :param dt:  pythone datetime.datetime\n    :return:  1999-02-01 string type\n    \"\"\"\n    strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n    return strdate", "title": ""}
{"_id": "d8034", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d8035", "text": "def datetime_to_ms(dt):\n    \"\"\"\n    Converts a datetime to a millisecond accuracy timestamp\n    \"\"\"\n    seconds = calendar.timegm(dt.utctimetuple())\n    return seconds * 1000 + int(dt.microsecond / 1000)", "title": ""}
{"_id": "d8036", "text": "def normalize(im, invert=False, scale=None, dtype=np.float64):\n    \"\"\"\n    Normalize a field to a (min, max) exposure range, default is (0, 255).\n    (min, max) exposure values. Invert the image if requested.\n    \"\"\"\n    if dtype not in {np.float16, np.float32, np.float64}:\n        raise ValueError('dtype must be numpy.float16, float32, or float64.')\n    out = im.astype('float').copy()\n\n    scale = scale or (0.0, 255.0)\n    l, u = (float(i) for i in scale)\n    out = (out - l) / (u - l)\n    if invert:\n        out = -out + (out.max() + out.min())\n    return out.astype(dtype)", "title": ""}
{"_id": "d8037", "text": "def _histplot_bins(column, bins=100):\n    \"\"\"Helper to get bins for histplot.\"\"\"\n    col_min = np.min(column)\n    col_max = np.max(column)\n    return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))", "title": ""}
{"_id": "d8038", "text": "def index(self, value):\n\t\t\"\"\"\n\t\tReturn the smallest index of the row(s) with this column\n\t\tequal to value.\n\t\t\"\"\"\n\t\tfor i in xrange(len(self.parentNode)):\n\t\t\tif getattr(self.parentNode[i], self.Name) == value:\n\t\t\t\treturn i\n\t\traise ValueError(value)", "title": ""}
{"_id": "d8039", "text": "def __len__(self):\n        \"\"\" This will equal 124 for the V1 database. \"\"\"\n        length = 0\n        for typ, siz, _ in self.format:\n            length += siz\n        return length", "title": ""}
{"_id": "d8040", "text": "def grandparent_path(self):\n        \"\"\" return grandparent's path string \"\"\"\n        return os.path.basename(os.path.join(self.path, '../..'))", "title": ""}
{"_id": "d8041", "text": "def update_dict(obj, dict, attributes):\n    \"\"\"Update dict with fields from obj.attributes.\n\n    :param obj: the object updated into dict\n    :param dict: the result dictionary\n    :param attributes: a list of attributes belonging to obj\n    \"\"\"\n    for attribute in attributes:\n        if hasattr(obj, attribute) and getattr(obj, attribute) is not None:\n            dict[attribute] = getattr(obj, attribute)", "title": ""}
{"_id": "d8042", "text": "def check(modname):\n    \"\"\"Check if required dependency is installed\"\"\"\n    for dependency in DEPENDENCIES:\n        if dependency.modname == modname:\n            return dependency.check()\n    else:\n        raise RuntimeError(\"Unkwown dependency %s\" % modname)", "title": ""}
{"_id": "d8043", "text": "def _rgbtomask(self, obj):\n        \"\"\"Convert RGB arrays from mask canvas object back to boolean mask.\"\"\"\n        dat = obj.get_image().get_data()  # RGB arrays\n        return dat.sum(axis=2).astype(np.bool)", "title": ""}
{"_id": "d8044", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d8045", "text": "def delete(filething):\n    \"\"\"Remove tags from a file.\n\n    Args:\n        filething (filething)\n    Raises:\n        mutagen.MutagenError\n    \"\"\"\n\n    f = FLAC(filething)\n    filething.fileobj.seek(0)\n    f.delete(filething)", "title": ""}
{"_id": "d8046", "text": "def get_from_human_key(self, key):\n        \"\"\"Return the key (aka database value) of a human key (aka Python identifier).\"\"\"\n        if key in self._identifier_map:\n            return self._identifier_map[key]\n        raise KeyError(key)", "title": ""}
{"_id": "d8047", "text": "def cio_close(cio):\n    \"\"\"Wraps openjpeg library function cio_close.\n    \"\"\"\n    OPENJPEG.opj_cio_close.argtypes = [ctypes.POINTER(CioType)]\n    OPENJPEG.opj_cio_close(cio)", "title": ""}
{"_id": "d8048", "text": "def input_int_default(question=\"\", default=0):\n    \"\"\"A function that works for both, Python 2.x and Python 3.x.\n       It asks the user for input and returns it as a string.\n    \"\"\"\n    answer = input_string(question)\n    if answer == \"\" or answer == \"yes\":\n        return default\n    else:\n        return int(answer)", "title": ""}
{"_id": "d8049", "text": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "title": ""}
{"_id": "d8050", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d8051", "text": "def gray2bgr(img):\n    \"\"\"Convert a grayscale image to BGR image.\n\n    Args:\n        img (ndarray or str): The input image.\n\n    Returns:\n        ndarray: The converted BGR image.\n    \"\"\"\n    img = img[..., None] if img.ndim == 2 else img\n    out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n    return out_img", "title": ""}
{"_id": "d8052", "text": "def inject_into_urllib3():\n    \"\"\"\n    Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n    \"\"\"\n    util.ssl_.SSLContext = SecureTransportContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_SECURETRANSPORT = True\n    util.ssl_.IS_SECURETRANSPORT = True", "title": ""}
{"_id": "d8053", "text": "def find_path(self, start, end, grid):\n        \"\"\"\n        find a path from start to end node on grid using the A* algorithm\n        :param start: start node\n        :param end: end node\n        :param grid: grid that stores all possible steps/tiles as 2D-list\n        :return:\n        \"\"\"\n        start.g = 0\n        start.f = 0\n        return super(AStarFinder, self).find_path(start, end, grid)", "title": ""}
{"_id": "d8054", "text": "def strip_querystring(url):\n    \"\"\"Remove the querystring from the end of a URL.\"\"\"\n    p = six.moves.urllib.parse.urlparse(url)\n    return p.scheme + \"://\" + p.netloc + p.path", "title": ""}
{"_id": "d8055", "text": "def _uptime_syllable():\n    \"\"\"Returns uptime in seconds or None, on Syllable.\"\"\"\n    global __boottime\n    try:\n        __boottime = os.stat('/dev/pty/mst/pty0').st_mtime\n        return time.time() - __boottime\n    except (NameError, OSError):\n        return None", "title": ""}
{"_id": "d8056", "text": "def unpickle(pickle_file):\n    \"\"\"Unpickle a python object from the given path.\"\"\"\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", "title": ""}
{"_id": "d8057", "text": "def hasattrs(object, *names):\n    \"\"\"\n    Takes in an object and a variable length amount of named attributes,\n    and checks to see if the object has each property. If any of the\n    attributes are missing, this returns false.\n\n    :param object: an object that may or may not contain the listed attributes\n    :param names: a variable amount of attribute names to check for\n    :return: True if the object contains each named attribute, false otherwise\n    \"\"\"\n    for name in names:\n        if not hasattr(object, name):\n            return False\n    return True", "title": ""}
{"_id": "d8058", "text": "def parent_widget(self):\n        \"\"\" Reimplemented to only return GraphicsItems \"\"\"\n        parent = self.parent()\n        if parent is not None and isinstance(parent, QtGraphicsItem):\n            return parent.widget", "title": ""}
{"_id": "d8059", "text": "def save_keras_definition(keras_model, path):\n    \"\"\"\n    Save a Keras model definition to JSON with given path\n    \"\"\"\n    model_json = keras_model.to_json()\n    with open(path, \"w\") as json_file:\n        json_file.write(model_json)", "title": ""}
{"_id": "d8060", "text": "def reconnect(self):\n        \"\"\"Reconnect to rabbitmq server\"\"\"\n        import pika\n        import pika.exceptions\n\n        self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))\n        self.channel = self.connection.channel()\n        try:\n            self.channel.queue_declare(self.name)\n        except pika.exceptions.ChannelClosed:\n            self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))\n            self.channel = self.connection.channel()", "title": ""}
{"_id": "d8061", "text": "def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to be padded.\n\n        Returns:\n            PIL Image: Padded image.\n        \"\"\"\n        return F.pad(img, self.padding, self.fill, self.padding_mode)", "title": ""}
{"_id": "d8062", "text": "def raise_os_error(_errno, path=None):\n    \"\"\"\n    Helper for raising the correct exception under Python 3 while still\n    being able to raise the same common exception class in Python 2.7.\n    \"\"\"\n\n    msg = \"%s: '%s'\" % (strerror(_errno), path) if path else strerror(_errno)\n    raise OSError(_errno, msg)", "title": ""}
{"_id": "d8063", "text": "def indent(block, spaces):\n    \"\"\" indents paragraphs of text for rst formatting \"\"\"\n    new_block = ''\n    for line in block.split('\\n'):\n        new_block += spaces + line + '\\n'\n    return new_block", "title": ""}
{"_id": "d8064", "text": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "title": ""}
{"_id": "d8065", "text": "def message_from_string(s, *args, **kws):\n    \"\"\"Parse a string into a Message object model.\n\n    Optional _class and strict are passed to the Parser constructor.\n    \"\"\"\n    from future.backports.email.parser import Parser\n    return Parser(*args, **kws).parsestr(s)", "title": ""}
{"_id": "d8066", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d8067", "text": "def __getattr__(self, name):\n        \"\"\"Return wrapper to named api method.\"\"\"\n        return functools.partial(self._obj.request, self._api_prefix + name)", "title": ""}
{"_id": "d8068", "text": "def _rndPointDisposition(dx, dy):\n        \"\"\"Return random disposition point.\"\"\"\n        x = int(random.uniform(-dx, dx))\n        y = int(random.uniform(-dy, dy))\n        return (x, y)", "title": ""}
{"_id": "d8069", "text": "def minus(*args):\n    \"\"\"Also, converts either to ints or to floats.\"\"\"\n    if len(args) == 1:\n        return -to_numeric(args[0])\n    return to_numeric(args[0]) - to_numeric(args[1])", "title": ""}
{"_id": "d8070", "text": "def random_color(_min=MIN_COLOR, _max=MAX_COLOR):\n    \"\"\"Returns a random color between min and max.\"\"\"\n    return color(random.randint(_min, _max))", "title": ""}
{"_id": "d8071", "text": "def string_list_to_array(l):\n    \"\"\"\n    Turns a Python unicode string list into a Java String array.\n\n    :param l: the string list\n    :type: list\n    :rtype: java string array\n    :return: JB_Object\n    \"\"\"\n    result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class(\"java/lang/String\"))\n    for i in range(len(l)):\n        javabridge.get_env().set_object_array_element(result, i, javabridge.get_env().new_string_utf(l[i]))\n    return result", "title": ""}
{"_id": "d8072", "text": "def _remove_nonascii(self, df):\n    \"\"\"Make copy and remove non-ascii characters from it.\"\"\"\n\n    df_copy = df.copy(deep=True)\n    for col in df_copy.columns:\n      if (df_copy[col].dtype == np.dtype('O')):\n        df_copy[col] = df[col].apply(\n          lambda x: re.sub(r'[^\\x00-\\x7f]', r'', x) if isinstance(x, six.string_types) else x)\n\n    return df_copy", "title": ""}
{"_id": "d8073", "text": "def listified_tokenizer(source):\n    \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n    io_obj = io.StringIO(source)\n    return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]", "title": ""}
{"_id": "d8074", "text": "def __get_float(section, name):\n    \"\"\"Get the forecasted float from json section.\"\"\"\n    try:\n        return float(section[name])\n    except (ValueError, TypeError, KeyError):\n        return float(0)", "title": ""}
{"_id": "d8075", "text": "def read_string(buff, byteorder='big'):\n    \"\"\"Read a string from a file-like object.\"\"\"\n    length = read_numeric(USHORT, buff, byteorder)\n    return buff.read(length).decode('utf-8')", "title": ""}
{"_id": "d8076", "text": "def imapchain(*a, **kwa):\n    \"\"\" Like map but also chains the results. \"\"\"\n\n    imap_results = map( *a, **kwa )\n    return itertools.chain( *imap_results )", "title": ""}
{"_id": "d8077", "text": "def _read_json_file(self, json_file):\n        \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n        self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n        with open(json_file, 'r') as f:\n            return json.load(f, object_pairs_hook=OrderedDict)", "title": ""}
{"_id": "d8078", "text": "def GeneratePassphrase(length=20):\n  \"\"\"Create a 20 char passphrase with easily typeable chars.\"\"\"\n  valid_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  valid_chars += \"0123456789 ,-_&$#\"\n  return \"\".join(random.choice(valid_chars) for i in range(length))", "title": ""}
{"_id": "d8079", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d8080", "text": "def survival(value=t, lam=lam, f=failure):\n    \"\"\"Exponential survival likelihood, accounting for censoring\"\"\"\n    return sum(f * log(lam) - lam * value)", "title": ""}
{"_id": "d8081", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d8082", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d8083", "text": "def get(url):\n    \"\"\"Recieving the JSON file from uulm\"\"\"\n    response = urllib.request.urlopen(url)\n    data = response.read()\n    data = data.decode(\"utf-8\")\n    data = json.loads(data)\n    return data", "title": ""}
{"_id": "d8084", "text": "def random_choice(sequence):\n    \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n    return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)", "title": ""}
{"_id": "d8085", "text": "def stft_magnitude(signal, fft_length,\n                   hop_length=None,\n                   window_length=None):\n  \"\"\"Calculate the short-time Fourier transform magnitude.\n\n  Args:\n    signal: 1D np.array of the input time-domain signal.\n    fft_length: Size of the FFT to apply.\n    hop_length: Advance (in samples) between each frame passed to FFT.\n    window_length: Length of each block of samples to pass to FFT.\n\n  Returns:\n    2D np.array where each row contains the magnitudes of the fft_length/2+1\n    unique values of the FFT for the corresponding frame of input samples.\n  \"\"\"\n  frames = frame(signal, window_length, hop_length)\n  # Apply frame window to each frame. We use a periodic Hann (cosine of period\n  # window_length) instead of the symmetric Hann of np.hanning (period\n  # window_length-1).\n  window = periodic_hann(window_length)\n  windowed_frames = frames * window\n  return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))", "title": ""}
{"_id": "d8086", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d8087", "text": "def connected_socket(address, timeout=3):\n    \"\"\" yields a connected socket \"\"\"\n    sock = socket.create_connection(address, timeout)\n    yield sock\n    sock.close()", "title": ""}
{"_id": "d8088", "text": "def makeAnimation(self):\n        \"\"\"Use pymovie to render (visual+audio)+text overlays.\n        \"\"\"\n        aclip=mpy.AudioFileClip(\"sound.wav\")\n        self.iS=self.iS.set_audio(aclip)\n        self.iS.write_videofile(\"mixedVideo.webm\",15,audio=True)\n        print(\"wrote \"+\"mixedVideo.webm\")", "title": ""}
{"_id": "d8089", "text": "def getTopRight(self):\n        \"\"\"\n        Retrieves a tuple with the x,y coordinates of the upper right point of the ellipse. \n        Requires the radius and the coordinates to be numbers\n        \"\"\"\n        return (float(self.get_cx()) + float(self.get_rx()), float(self.get_cy()) + float(self.get_ry()))", "title": ""}
{"_id": "d8090", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d8091", "text": "def dfs_recursive(graph, node, seen):\n    \"\"\"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|)`\n    \"\"\"\n    seen[node] = True\n    for neighbor in graph[node]:\n        if not seen[neighbor]:\n            dfs_recursive(graph, neighbor, seen)", "title": ""}
{"_id": "d8092", "text": "def lognorm(x, mu, sigma=1.0):\n    \"\"\" Log-normal function from scipy \"\"\"\n    return stats.lognorm(sigma, scale=mu).pdf(x)", "title": ""}
{"_id": "d8093", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d8094", "text": "def mad(v):\n    \"\"\"MAD -- Median absolute deviation. More robust than standard deviation.\n    \"\"\"\n    return np.median(np.abs(v - np.median(v)))", "title": ""}
{"_id": "d8095", "text": "def remover(file_path):\n    \"\"\"Delete a file or directory path only if it exists.\"\"\"\n    if os.path.isfile(file_path):\n        os.remove(file_path)\n        return True\n    elif os.path.isdir(file_path):\n        shutil.rmtree(file_path)\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d8096", "text": "def lognorm(x, mu, sigma=1.0):\n    \"\"\" Log-normal function from scipy \"\"\"\n    return stats.lognorm(sigma, scale=mu).pdf(x)", "title": ""}
{"_id": "d8097", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d8098", "text": "def normalise_string(string):\n    \"\"\" Strips trailing whitespace from string, lowercases it and replaces\n        spaces with underscores\n    \"\"\"\n    string = (string.strip()).lower()\n    return re.sub(r'\\W+', '_', string)", "title": ""}
{"_id": "d8099", "text": "def cart2pol(x, y):\n    \"\"\"Cartesian to Polar coordinates conversion.\"\"\"\n    theta = np.arctan2(y, x)\n    rho = np.hypot(x, y)\n    return theta, rho", "title": ""}
{"_id": "d8100", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d8101", "text": "def multi_pop(d, *args):\n    \"\"\" pops multiple keys off a dict like object \"\"\"\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval", "title": ""}
{"_id": "d8102", "text": "def _remove_nonascii(self, df):\n    \"\"\"Make copy and remove non-ascii characters from it.\"\"\"\n\n    df_copy = df.copy(deep=True)\n    for col in df_copy.columns:\n      if (df_copy[col].dtype == np.dtype('O')):\n        df_copy[col] = df[col].apply(\n          lambda x: re.sub(r'[^\\x00-\\x7f]', r'', x) if isinstance(x, six.string_types) else x)\n\n    return df_copy", "title": ""}
{"_id": "d8103", "text": "def _get_printable_columns(columns, row):\n    \"\"\"Return only the part of the row which should be printed.\n    \"\"\"\n    if not columns:\n        return row\n\n    # Extract the column values, in the order specified.\n    return tuple(row[c] for c in columns)", "title": ""}
{"_id": "d8104", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d8105", "text": "def purge_duplicates(list_in):\n    \"\"\"Remove duplicates from list while preserving order.\n\n    Parameters\n    ----------\n    list_in: Iterable\n\n    Returns\n    -------\n    list\n        List of first occurences in order\n    \"\"\"\n    _list = []\n    for item in list_in:\n        if item not in _list:\n            _list.append(item)\n    return _list", "title": ""}
{"_id": "d8106", "text": "def parse_json(filename):\n    \"\"\" Parse a JSON file\n        First remove comments and then use the json module package\n        Comments look like :\n            // ...\n        or\n            /*\n            ...\n            */\n    \"\"\"\n    # Regular expression for comments\n    comment_re = re.compile(\n        '(^)?[^\\S\\n]*/(?:\\*(.*?)\\*/[^\\S\\n]*|/[^\\n]*)($)?',\n        re.DOTALL | re.MULTILINE\n    )\n\n    with open(filename) as f:\n        content = ''.join(f.readlines())\n\n        ## Looking for comments\n        match = comment_re.search(content)\n        while match:\n            # single line comment\n            content = content[:match.start()] + content[match.end():]\n            match = comment_re.search(content)\n\n        # Return json file\n        return json.loads(content)", "title": ""}
{"_id": "d8107", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d8108", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d8109", "text": "def _attrprint(d, delimiter=', '):\n    \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n    return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))", "title": ""}
{"_id": "d8110", "text": "def _remove_duplicate_files(xs):\n    \"\"\"Remove files specified multiple times in a list.\n    \"\"\"\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", "title": ""}
{"_id": "d8111", "text": "def toJson(protoObject, indent=None):\n    \"\"\"\n    Serialises a protobuf object as json\n    \"\"\"\n    # Using the internal method because this way we can reformat the JSON\n    js = json_format.MessageToDict(protoObject, False)\n    return json.dumps(js, indent=indent)", "title": ""}
{"_id": "d8112", "text": "def file_remove(self, path, filename):\n        \"\"\"Check if filename exists and remove\n        \"\"\"\n        if os.path.isfile(path + filename):\n            os.remove(path + filename)", "title": ""}
{"_id": "d8113", "text": "def printc(cls, txt, color=colors.red):\n        \"\"\"Print in color.\"\"\"\n        print(cls.color_txt(txt, color))", "title": ""}
{"_id": "d8114", "text": "def __convert_none_to_zero(self, ts):\n        \"\"\"\n        Convert None values to 0 so the data works with Matplotlib\n        :param ts:\n        :return: a list with 0s where Nones existed\n        \"\"\"\n\n        if not ts:\n            return ts\n\n        ts_clean = [val if val else 0 for val in ts]\n\n        return ts_clean", "title": ""}
{"_id": "d8115", "text": "def raw_print(*args, **kw):\n    \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()", "title": ""}
{"_id": "d8116", "text": "def strip_spaces(x):\n    \"\"\"\n    Strips spaces\n    :param x:\n    :return:\n    \"\"\"\n    x = x.replace(b' ', b'')\n    x = x.replace(b'\\t', b'')\n    return x", "title": ""}
{"_id": "d8117", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d8118", "text": "def info(txt):\n    \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d8119", "text": "def strip_line(line, sep=os.linesep):\n    \"\"\"\n    Removes occurrence of character (sep) from a line of text\n    \"\"\"\n\n    try:\n        return line.strip(sep)\n    except TypeError:\n        return line.decode('utf-8').strip(sep)", "title": ""}
{"_id": "d8120", "text": "def EvalBinomialPmf(k, n, p):\n    \"\"\"Evaluates the binomial pmf.\n\n    Returns the probabily of k successes in n trials with probability p.\n    \"\"\"\n    return scipy.stats.binom.pmf(k, n, p)", "title": ""}
{"_id": "d8121", "text": "def lines(input):\n    \"\"\"Remove comments and empty lines\"\"\"\n    for raw_line in input:\n        line = raw_line.strip()\n        if line and not line.startswith('#'):\n            yield strip_comments(line)", "title": ""}
{"_id": "d8122", "text": "def format_docstring(*args, **kwargs):\n    \"\"\"\n    Decorator for clean docstring formatting\n    \"\"\"\n    def decorator(func):\n        func.__doc__ = getdoc(func).format(*args, **kwargs)\n        return func\n    return decorator", "title": ""}
{"_id": "d8123", "text": "def unique(transactions):\n    \"\"\" Remove any duplicate entries. \"\"\"\n    seen = set()\n    # TODO: Handle comments\n    return [x for x in transactions if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d8124", "text": "def softplus(attrs, inputs, proto_obj):\n    \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs", "title": ""}
{"_id": "d8125", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d8126", "text": "def unapostrophe(text):\n    \"\"\"Strip apostrophe and 's' from the end of a string.\"\"\"\n    text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)\n    return text", "title": ""}
{"_id": "d8127", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d8128", "text": "def _obj_cursor_to_dictionary(self, cursor):\n        \"\"\"Handle conversion of pymongo cursor into a JSON object formatted for UI consumption\n\n        :param dict cursor: a mongo document that should be converted to primitive types for the client code\n        :returns: a primitive dictionary\n        :rtype: dict\n        \"\"\"\n        if not cursor:\n            return cursor\n\n        cursor = json.loads(json.dumps(cursor, cls=BSONEncoder))\n\n        if cursor.get(\"_id\"):\n            cursor[\"id\"] = cursor.get(\"_id\")\n            del cursor[\"_id\"]\n\n        return cursor", "title": ""}
{"_id": "d8129", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d8130", "text": "def add_0x(string):\n    \"\"\"Add 0x to string at start.\n    \"\"\"\n    if isinstance(string, bytes):\n        string = string.decode('utf-8')\n    return '0x' + str(string)", "title": ""}
{"_id": "d8131", "text": "def wordify(text):\n    \"\"\"Generate a list of words given text, removing punctuation.\n\n    Parameters\n    ----------\n    text : unicode\n        A piece of english text.\n\n    Returns\n    -------\n    words : list\n        List of words.\n    \"\"\"\n    stopset = set(nltk.corpus.stopwords.words('english'))\n    tokens = nltk.WordPunctTokenizer().tokenize(text)\n    return [w for w in tokens if w not in stopset]", "title": ""}
{"_id": "d8132", "text": "def is_iterable(obj):\n    \"\"\"\n    Are we being asked to look up a list of things, instead of a single thing?\n    We check for the `__iter__` attribute so that this can cover types that\n    don't have to be known by this module, such as NumPy arrays.\n\n    Strings, however, should be considered as atomic values to look up, not\n    iterables. The same goes for tuples, since they are immutable and therefore\n    valid entries.\n\n    We don't need to check for the Python 2 `unicode` type, because it doesn't\n    have an `__iter__` attribute anyway.\n    \"\"\"\n    return (\n        hasattr(obj, \"__iter__\")\n        and not isinstance(obj, str)\n        and not isinstance(obj, tuple)\n    )", "title": ""}
{"_id": "d8133", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d8134", "text": "def line_count(fn):\n    \"\"\" Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)\n    \"\"\"\n\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "title": ""}
{"_id": "d8135", "text": "def synthesize(self, duration):\n        \"\"\"\n        Synthesize white noise\n\n        Args:\n            duration (numpy.timedelta64): The duration of the synthesized sound\n        \"\"\"\n        sr = self.samplerate.samples_per_second\n        seconds = duration / Seconds(1)\n        samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n        return AudioSamples(samples, self.samplerate)", "title": ""}
{"_id": "d8136", "text": "def timed_rotating_file_handler(name, logname, filename, when='h',\n                                interval=1, backupCount=0,\n                                encoding=None, delay=False, utc=False):\n    \"\"\"\n    A Bark logging handler logging output to a named file.  At\n    intervals specified by the 'when', the file will be rotated, under\n    control of 'backupCount'.\n\n    Similar to logging.handlers.TimedRotatingFileHandler.\n    \"\"\"\n\n    return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n        filename, when=when, interval=interval, backupCount=backupCount,\n        encoding=encoding, delay=delay, utc=utc))", "title": ""}
{"_id": "d8137", "text": "def replace_list(items, match, replacement):\n    \"\"\"Replaces occurrences of a match string in a given list of strings and returns\n    a list of new strings. The match string can be a regex expression.\n\n    Args:\n        items (list):       the list of strings to modify.\n        match (str):        the search expression.\n        replacement (str):  the string to replace with.\n    \"\"\"\n    return [replace(item, match, replacement) for item in items]", "title": ""}
{"_id": "d8138", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d8139", "text": "def fmt_subst(regex, subst):\n    \"\"\"Replace regex with string.\"\"\"\n    return lambda text: re.sub(regex, subst, text) if text else text", "title": ""}
{"_id": "d8140", "text": "def Min(a, axis, keep_dims):\n    \"\"\"\n    Min reduction op.\n    \"\"\"\n    return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d8141", "text": "def delistify(x):\n    \"\"\" A basic slug version of a given parameter list. \"\"\"\n    if isinstance(x, list):\n        x = [e.replace(\"'\", \"\") for e in x]\n        return '-'.join(sorted(x))\n    return x", "title": ""}
{"_id": "d8142", "text": "def __grid_widgets(self):\n        \"\"\"Places all the child widgets in the appropriate positions.\"\"\"\n        scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n        self._canvas.grid(row=0, column=1, sticky=\"nswe\")\n        self._scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")", "title": ""}
{"_id": "d8143", "text": "def replace(s, replace):\n    \"\"\"Replace multiple values in a string\"\"\"\n    for r in replace:\n        s = s.replace(*r)\n    return s", "title": ""}
{"_id": "d8144", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d8145", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d8146", "text": "def _get_set(self, key, operation, create=False):\n        \"\"\"\n        Get (and maybe create) a set by name.\n        \"\"\"\n        return self._get_by_type(key, operation, create, b'set', set())", "title": ""}
{"_id": "d8147", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d8148", "text": "def get_abi3_suffix():\n    \"\"\"Return the file extension for an abi3-compliant Extension()\"\"\"\n    for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION):\n        if '.abi3' in suffix:  # Unix\n            return suffix\n        elif suffix == '.pyd':  # Windows\n            return suffix", "title": ""}
{"_id": "d8149", "text": "def replaceNewlines(string, newlineChar):\n\t\"\"\"There's probably a way to do this with string functions but I was lazy.\n\t\tReplace all instances of \\r or \\n in a string with something else.\"\"\"\n\tif newlineChar in string:\n\t\tsegments = string.split(newlineChar)\n\t\tstring = \"\"\n\t\tfor segment in segments:\n\t\t\tstring += segment\n\treturn string", "title": ""}
{"_id": "d8150", "text": "def mouse_get_pos():\n    \"\"\"\n\n    :return:\n    \"\"\"\n    p = POINT()\n    AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))\n    return p.x, p.y", "title": ""}
{"_id": "d8151", "text": "def replace(table, field, a, b, **kwargs):\n    \"\"\"\n    Convenience function to replace all occurrences of `a` with `b` under the\n    given field. See also :func:`convert`.\n\n    The ``where`` keyword argument can be given with a callable or expression\n    which is evaluated on each row and which should return True if the\n    conversion should be applied on that row, else False.\n\n    \"\"\"\n\n    return convert(table, field, {a: b}, **kwargs)", "title": ""}
{"_id": "d8152", "text": "def rm_empty_indices(*args):\n    \"\"\"\n    Remove unwanted list indices. First argument is the list\n    of indices to remove. Other elements are the lists\n    to trim.\n    \"\"\"\n    rm_inds = args[0]\n\n    if not rm_inds:\n        return args[1:]\n\n    keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n    return [[a[i] for i in keep_inds] for a in args[1:]]", "title": ""}
{"_id": "d8153", "text": "def submit_the_only_form(self):\n    \"\"\"\n    Look for a form on the page and submit it.\n\n    Asserts if more than one form exists.\n    \"\"\"\n    form = ElementSelector(world.browser, str('//form'))\n    assert form, \"Cannot find a form on the page.\"\n    form.submit()", "title": ""}
{"_id": "d8154", "text": "def get_args(method_or_func):\n    \"\"\"Returns method or function arguments.\"\"\"\n    try:\n        # Python 3.0+\n        args = list(inspect.signature(method_or_func).parameters.keys())\n    except AttributeError:\n        # Python 2.7\n        args = inspect.getargspec(method_or_func).args\n    return args", "title": ""}
{"_id": "d8155", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d8156", "text": "def _repr_strip(mystring):\n    \"\"\"\n    Returns the string without any initial or final quotes.\n    \"\"\"\n    r = repr(mystring)\n    if r.startswith(\"'\") and r.endswith(\"'\"):\n        return r[1:-1]\n    else:\n        return r", "title": ""}
{"_id": "d8157", "text": "def new_iteration(self, prefix):\n        \"\"\"When inside a loop logger, created a new iteration\n        \"\"\"\n        # Flush data for the current iteration\n        self.flush()\n\n        # Fix prefix\n        self.prefix[-1] = prefix\n        self.reset_formatter()", "title": ""}
{"_id": "d8158", "text": "def batchify(data, batch_size):\n    \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n    nbatch = data.shape[0] // batch_size\n    data = data[:nbatch * batch_size]\n    data = data.reshape((batch_size, nbatch)).T\n    return data", "title": ""}
{"_id": "d8159", "text": "def serialisasi(self):\n        \"\"\"Mengembalikan hasil serialisasi objek Makna ini.\n\n        :returns: Dictionary hasil serialisasi\n        :rtype: dict\n        \"\"\"\n\n        return {\n            \"kelas\": self.kelas,\n            \"submakna\": self.submakna,\n            \"info\": self.info,\n            \"contoh\": self.contoh\n        }", "title": ""}
{"_id": "d8160", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d8161", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d8162", "text": "def s3(ctx, bucket_name, data_file, region):\n    \"\"\"Use the S3 SWAG backend.\"\"\"\n    if not ctx.data_file:\n        ctx.data_file = data_file\n\n    if not ctx.bucket_name:\n        ctx.bucket_name = bucket_name\n\n    if not ctx.region:\n        ctx.region = region\n\n    ctx.type = 's3'", "title": ""}
{"_id": "d8163", "text": "def process_request(self, request, response):\n        \"\"\"Logs the basic endpoint requested\"\"\"\n        self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))", "title": ""}
{"_id": "d8164", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d8165", "text": "def filter_regex(names, regex):\n    \"\"\"\n    Return a tuple of strings that match the regular expression pattern.\n    \"\"\"\n    return tuple(name for name in names\n                 if regex.search(name) is not None)", "title": ""}
{"_id": "d8166", "text": "def accuracy(conf_matrix):\n  \"\"\"\n  Given a confusion matrix, returns the accuracy.\n  Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml\n  \"\"\"\n  total, correct = 0.0, 0.0\n  for true_response, guess_dict in conf_matrix.items():\n    for guess, count in guess_dict.items():\n      if true_response == guess:\n        correct += count\n      total += count\n  return correct/total", "title": ""}
{"_id": "d8167", "text": "def _npiter(arr):\n    \"\"\"Wrapper for iterating numpy array\"\"\"\n    for a in np.nditer(arr, flags=[\"refs_ok\"]):\n        c = a.item()\n        if c is not None:\n            yield c", "title": ""}
{"_id": "d8168", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d8169", "text": "def max(self):\n        \"\"\"\n        Returns the maximum value of the domain.\n\n        :rtype: `float` or `np.inf`\n        \"\"\"\n        return int(self._max) if not np.isinf(self._max) else self._max", "title": ""}
{"_id": "d8170", "text": "def add_noise(Y, sigma):\n    \"\"\"Adds noise to Y\"\"\"\n    return Y + np.random.normal(0, sigma, Y.shape)", "title": ""}
{"_id": "d8171", "text": "def make_unique_ngrams(s, n):\n    \"\"\"Make a set of unique n-grams from a string.\"\"\"\n    return set(s[i:i + n] for i in range(len(s) - n + 1))", "title": ""}
{"_id": "d8172", "text": "def generic_add(a, b):\n    \"\"\"Simple function to add two numbers\"\"\"\n    logger.debug('Called generic_add({}, {})'.format(a, b))\n    return a + b", "title": ""}
{"_id": "d8173", "text": "def getvariable(name):\n    \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n    import inspect\n    fr = inspect.currentframe()\n    try:\n        while fr:\n            fr = fr.f_back\n            vars = fr.f_locals\n            if name in vars:\n                return vars[name]\n    except:\n        pass\n    return None", "title": ""}
{"_id": "d8174", "text": "def reversed_lines(path):\n    \"\"\"Generate the lines of file in reverse order.\"\"\"\n    with open(path, 'r') as handle:\n        part = ''\n        for block in reversed_blocks(handle):\n            for c in reversed(block):\n                if c == '\\n' and part:\n                    yield part[::-1]\n                    part = ''\n                part += c\n        if part: yield part[::-1]", "title": ""}
{"_id": "d8175", "text": "def align_file_position(f, size):\n    \"\"\" Align the position in the file to the next block of specified size \"\"\"\n    align = (size - 1) - (f.tell() % size)\n    f.seek(align, 1)", "title": ""}
{"_id": "d8176", "text": "def hex_to_hsv(color):\n    \"\"\"\n    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')\n    \"\"\"\n    color = normalize(color)\n    color = color[1:]\n    # color=tuple(ord(c)/255.0 for c in color.decode('hex'))\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)", "title": ""}
{"_id": "d8177", "text": "def advance_one_line(self):\n    \"\"\"Advances to next line.\"\"\"\n\n    current_line = self._current_token.line_number\n    while current_line == self._current_token.line_number:\n      self._current_token = ConfigParser.Token(*next(self._token_generator))", "title": ""}
{"_id": "d8178", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d8179", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d8180", "text": "def rotateImage(img, angle):\n    \"\"\"\n\n    querries scipy.ndimage.rotate routine\n    :param img: image to be rotated\n    :param angle: angle to be rotated (radian)\n    :return: rotated image\n    \"\"\"\n    imgR = scipy.ndimage.rotate(img, angle, reshape=False)\n    return imgR", "title": ""}
{"_id": "d8181", "text": "def chunk_sequence(sequence, chunk_length):\n    \"\"\"Yield successive n-sized chunks from l.\"\"\"\n    for index in range(0, len(sequence), chunk_length):\n        yield sequence[index:index + chunk_length]", "title": ""}
{"_id": "d8182", "text": "def __round_time(self, dt):\n    \"\"\"Round a datetime object to a multiple of a timedelta\n    dt : datetime.datetime object, default now.\n    \"\"\"\n    round_to = self._resolution.total_seconds()\n    seconds  = (dt - dt.min).seconds\n    rounding = (seconds + round_to / 2) // round_to * round_to\n    return dt + timedelta(0, rounding - seconds, -dt.microsecond)", "title": ""}
{"_id": "d8183", "text": "def compose_all(tups):\n  \"\"\"Compose all given tuples together.\"\"\"\n  from . import ast  # I weep for humanity\n  return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))", "title": ""}
{"_id": "d8184", "text": "def _round_half_hour(record):\n    \"\"\"\n    Round a time DOWN to half nearest half-hour.\n    \"\"\"\n    k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))\n    return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)", "title": ""}
{"_id": "d8185", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d8186", "text": "def round_sig(x, sig):\n    \"\"\"Round the number to the specified number of significant figures\"\"\"\n    return round(x, sig - int(floor(log10(abs(x)))) - 1)", "title": ""}
{"_id": "d8187", "text": "def covstr(s):\n  \"\"\" convert string to int or float. \"\"\"\n  try:\n    ret = int(s)\n  except ValueError:\n    ret = float(s)\n  return ret", "title": ""}
{"_id": "d8188", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d8189", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d8190", "text": "def round_to_n(x, n):\n    \"\"\"\n    Round to sig figs\n    \"\"\"\n    return round(x, -int(np.floor(np.log10(x))) + (n - 1))", "title": ""}
{"_id": "d8191", "text": "def angle(x, y):\n    \"\"\"Return the angle between vectors a and b in degrees.\"\"\"\n    return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi", "title": ""}
{"_id": "d8192", "text": "def set(self, f):\n        \"\"\"Call a function after a delay, unless another function is set\n        in the meantime.\"\"\"\n        self.stop()\n        self._create_timer(f)\n        self.start()", "title": ""}
{"_id": "d8193", "text": "def flatten(lis):\n    \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n    new_lis = []\n    for item in lis:\n        if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n            new_lis.extend(flatten(item))\n        else:\n            new_lis.append(item)\n    return new_lis", "title": ""}
{"_id": "d8194", "text": "def get_code(module):\n    \"\"\"\n    Compile and return a Module's code object.\n    \"\"\"\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()", "title": ""}
{"_id": "d8195", "text": "def dictapply(d, fn):\n    \"\"\"\n    apply a function to all non-dict values in a dictionary\n    \"\"\"\n    for k, v in d.items():\n        if isinstance(v, dict):\n            v = dictapply(v, fn)\n        else:\n            d[k] = fn(v)\n    return d", "title": ""}
{"_id": "d8196", "text": "def store_many(self, sql, values):\n        \"\"\"Abstraction over executemany method\"\"\"\n        cursor = self.get_cursor()\n        cursor.executemany(sql, values)\n        self.conn.commit()", "title": ""}
{"_id": "d8197", "text": "def apply(self, node):\n        \"\"\" Apply transformation and return if an update happened. \"\"\"\n        new_node = self.run(node)\n        return self.update, new_node", "title": ""}
{"_id": "d8198", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d8199", "text": "def resize_image(self, data, size):\n        \"\"\" Resizes the given image to fit inside a box of the given size. \"\"\"\n        from machina.core.compat import PILImage as Image\n        image = Image.open(BytesIO(data))\n\n        # Resize!\n        image.thumbnail(size, Image.ANTIALIAS)\n\n        string = BytesIO()\n        image.save(string, format='PNG')\n        return string.getvalue()", "title": ""}
{"_id": "d8200", "text": "def compose(func_list):\n    \"\"\"\n    composion of preprocessing functions\n    \"\"\"\n\n    def f(G, bim):\n        for func in func_list:\n            G, bim = func(G, bim)\n        return G, bim\n\n    return f", "title": ""}
{"_id": "d8201", "text": "def multiply(traj):\n    \"\"\"Sophisticated simulation of multiplication\"\"\"\n    z=traj.x*traj.y\n    traj.f_add_result('z',z=z, comment='I am the product of two reals!')", "title": ""}
{"_id": "d8202", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d8203", "text": "def Dump(obj):\n  \"\"\"Stringifies a Python object into its YAML representation.\n\n  Args:\n    obj: A Python object to convert to YAML.\n\n  Returns:\n    A YAML representation of the given object.\n  \"\"\"\n  text = yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True)\n\n  if compatibility.PY2:\n    text = text.decode(\"utf-8\")\n\n  return text", "title": ""}
{"_id": "d8204", "text": "def parser():\n\n    \"\"\"Return a parser for setting one or more configuration paths\"\"\"\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-c', '--config_paths', default=[], action='append',\n                        help='path to a configuration directory')\n    return parser", "title": ""}
{"_id": "d8205", "text": "def save_session(self, sid, session, namespace=None):\n        \"\"\"Store the user session for a client.\n\n        The only difference with the :func:`socketio.Server.save_session`\n        method is that when the ``namespace`` argument is not given the\n        namespace associated with the class is used.\n        \"\"\"\n        return self.server.save_session(\n            sid, session, namespace=namespace or self.namespace)", "title": ""}
{"_id": "d8206", "text": "def set_subparsers_args(self, *args, **kwargs):\n        \"\"\"\n        Sets args and kwargs that are passed when creating a subparsers group\n        in an argparse.ArgumentParser i.e. when calling\n        argparser.ArgumentParser.add_subparsers\n        \"\"\"\n        self.subparsers_args = args\n        self.subparsers_kwargs = kwargs", "title": ""}
{"_id": "d8207", "text": "def on_pause(self):\n        \"\"\"Sync the database with the current state of the game.\"\"\"\n        self.engine.commit()\n        self.strings.save()\n        self.funcs.save()\n        self.config.write()", "title": ""}
{"_id": "d8208", "text": "def createArgumentParser(description):\n    \"\"\"\n    Create an argument parser\n    \"\"\"\n    parser = argparse.ArgumentParser(\n        description=description,\n        formatter_class=SortedHelpFormatter)\n    return parser", "title": ""}
{"_id": "d8209", "text": "def is_scalar(value):\n    \"\"\"Test if the given value is a scalar.\n\n    This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n    Args:\n        value: the value to test for being a scalar value\n\n    Returns:\n        boolean: if the given value is a scalar or not\n    \"\"\"\n    return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))", "title": ""}
{"_id": "d8210", "text": "def main(args=sys.argv):\n    \"\"\"\n    main entry point for the jardiff CLI\n    \"\"\"\n\n    parser = create_optparser(args[0])\n    return cli(parser.parse_args(args[1:]))", "title": ""}
{"_id": "d8211", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d8212", "text": "def parse_command_args():\n    \"\"\"Command line parser.\"\"\"\n    parser = argparse.ArgumentParser(description='Register PB devices.')\n    parser.add_argument('num_pb', type=int,\n                        help='Number of PBs devices to register.')\n    return parser.parse_args()", "title": ""}
{"_id": "d8213", "text": "def set_subparsers_args(self, *args, **kwargs):\n        \"\"\"\n        Sets args and kwargs that are passed when creating a subparsers group\n        in an argparse.ArgumentParser i.e. when calling\n        argparser.ArgumentParser.add_subparsers\n        \"\"\"\n        self.subparsers_args = args\n        self.subparsers_kwargs = kwargs", "title": ""}
{"_id": "d8214", "text": "def select_if(df, fun):\n    \"\"\"Selects columns where fun(ction) is true\n    Args:\n        fun: a function that will be applied to columns\n    \"\"\"\n\n    def _filter_f(col):\n        try:\n            return fun(df[col])\n        except:\n            return False\n\n    cols = list(filter(_filter_f, df.columns))\n    return df[cols]", "title": ""}
{"_id": "d8215", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d8216", "text": "def bisect_index(a, x):\n    \"\"\" Find the leftmost index of an element in a list using binary search.\n\n    Parameters\n    ----------\n    a: list\n        A sorted list.\n    x: arbitrary\n        The element.\n\n    Returns\n    -------\n    int\n        The index.\n\n    \"\"\"\n    i = bisect.bisect_left(a, x)\n    if i != len(a) and a[i] == x:\n        return i\n    raise ValueError", "title": ""}
{"_id": "d8217", "text": "def is_valid_folder(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.isdir(arg):\n        parser.error(\"The folder %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d8218", "text": "def auth_request(self, url, headers, body):\n        \"\"\"Perform auth request for token.\"\"\"\n\n        return self.req.post(url, headers, body=body)", "title": ""}
{"_id": "d8219", "text": "def pairwise_indices(self):\n        \"\"\"ndarray containing tuples of pairwise indices.\"\"\"\n        return np.array([sig.pairwise_indices for sig in self.values]).T", "title": ""}
{"_id": "d8220", "text": "def mouseMoveEvent(self, event):\n        \"\"\" Handle the mouse move event for a drag operation.\n\n        \"\"\"\n        self.declaration.mouse_move_event(event)\n        super(QtGraphicsView, self).mouseMoveEvent(event)", "title": ""}
{"_id": "d8221", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d8222", "text": "def data_from_file(file):\n    \"\"\"Return (first channel data, sample frequency, sample width) from a .wav\n    file.\"\"\"\n    fp = wave.open(file, 'r')\n    data = fp.readframes(fp.getnframes())\n    channels = fp.getnchannels()\n    freq = fp.getframerate()\n    bits = fp.getsampwidth()\n\n    # Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32\n    # bit not supported.\n    data = struct.unpack(('%sh' % fp.getnframes()) * channels, data)\n\n    # Only use first channel\n    channel1 = []\n    n = 0\n    for d in data:\n        if n % channels == 0:\n            channel1.append(d)\n        n += 1\n    fp.close()\n    return (channel1, freq, bits)", "title": ""}
{"_id": "d8223", "text": "def Diag(a):\n    \"\"\"\n    Diag op.\n    \"\"\"\n    r = np.zeros(2 * a.shape, dtype=a.dtype)\n    for idx, v in np.ndenumerate(a):\n        r[2 * idx] = v\n    return r,", "title": ""}
{"_id": "d8224", "text": "def split_strings_in_list_retain_spaces(orig_list):\n    \"\"\"\n    Function to split every line in a list, and retain spaces for a rejoin\n    :param orig_list: Original list\n    :return:\n        A List with split lines\n\n    \"\"\"\n    temp_list = list()\n    for line in orig_list:\n        line_split = __re.split(r'(\\s+)', line)\n        temp_list.append(line_split)\n\n    return temp_list", "title": ""}
{"_id": "d8225", "text": "def is_scalar(value):\n    \"\"\"Test if the given value is a scalar.\n\n    This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n    Args:\n        value: the value to test for being a scalar value\n\n    Returns:\n        boolean: if the given value is a scalar or not\n    \"\"\"\n    return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))", "title": ""}
{"_id": "d8226", "text": "def set_axis_options(self, row, column, text):\n        \"\"\"Set additionnal options as plain text.\"\"\"\n\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_axis_options(text)", "title": ""}
{"_id": "d8227", "text": "def _go_to_line(editor, line):\n    \"\"\"\n    Move cursor to this line in the current buffer.\n    \"\"\"\n    b = editor.application.current_buffer\n    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "title": ""}
{"_id": "d8228", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d8229", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d8230", "text": "def rex_assert(self, rex, byte=False):\n        \"\"\"\n        If `rex` expression is not found then raise `DataNotFound` exception.\n        \"\"\"\n\n        self.rex_search(rex, byte=byte)", "title": ""}
{"_id": "d8231", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d8232", "text": "def contains(self, element):\n        \"\"\"\n        Ensures :attr:`subject` contains *other*.\n        \"\"\"\n        self._run(unittest_case.assertIn, (element, self._subject))\n        return ChainInspector(self._subject)", "title": ""}
{"_id": "d8233", "text": "def setup(self, proxystr='', prompting=True):\n        \"\"\"\n        Sets the proxy handler given the option passed on the command\n        line.  If an empty string is passed it looks at the HTTP_PROXY\n        environment variable.\n        \"\"\"\n        self.prompting = prompting\n        proxy = self.get_proxy(proxystr)\n        if proxy:\n            proxy_support = urllib2.ProxyHandler({\"http\": proxy, \"ftp\": proxy})\n            opener = urllib2.build_opener(proxy_support, urllib2.CacheFTPHandler)\n            urllib2.install_opener(opener)", "title": ""}
{"_id": "d8234", "text": "def assert_list(self, putative_list, expected_type=string_types, key_arg=None):\n    \"\"\"\n    :API: public\n    \"\"\"\n    return assert_list(putative_list, expected_type, key_arg=key_arg,\n                       raise_type=lambda msg: TargetDefinitionException(self, msg))", "title": ""}
{"_id": "d8235", "text": "def resize(self, width, height):\n        \"\"\"\n        Pyqt specific resize callback.\n        \"\"\"\n        if not self.fbo:\n            return\n\n        # pyqt reports sizes in actual buffer size\n        self.width = width // self.widget.devicePixelRatio()\n        self.height = height // self.widget.devicePixelRatio()\n        self.buffer_width = width\n        self.buffer_height = height\n\n        super().resize(width, height)", "title": ""}
{"_id": "d8236", "text": "def assert_in(obj, seq, message=None, extra=None):\n    \"\"\"Raises an AssertionError if obj is not in seq.\"\"\"\n    assert obj in seq, _assert_fail_message(message, obj, seq, \"is not in\", extra)", "title": ""}
{"_id": "d8237", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d8238", "text": "def assert_is_instance(value, types, message=None, extra=None):\n    \"\"\"Raises an AssertionError if value is not an instance of type(s).\"\"\"\n    assert isinstance(value, types), _assert_fail_message(\n        message, value, types, \"is not an instance of\", extra\n    )", "title": ""}
{"_id": "d8239", "text": "def set_position(self, x, y, width, height):\n        \"\"\"Set window top-left corner position and size\"\"\"\n        SetWindowPos(self._hwnd, None, x, y, width, height, ctypes.c_uint(0))", "title": ""}
{"_id": "d8240", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d8241", "text": "def delegate(self, fn, *args, **kwargs):\n        \"\"\"Return the given operation as an asyncio future.\"\"\"\n        callback = functools.partial(fn, *args, **kwargs)\n        coro = self.loop.run_in_executor(self.subexecutor, callback)\n        return asyncio.ensure_future(coro)", "title": ""}
{"_id": "d8242", "text": "def _set_axis_limits(self, which, lims, d, scale, reverse=False):\n        \"\"\"Private method for setting axis limits.\n\n        Sets the axis limits on each axis for an individual plot.\n\n        Args:\n            which (str): The indicator of which part of the plots\n                to adjust. This currently handles `x` and `y`.\n            lims (len-2 list of floats): The limits for the axis.\n            d (float): Amount to increment by between the limits.\n            scale (str): Scale of the axis. Either `log` or `lin`.\n            reverse (bool, optional): If True, reverse the axis tick marks. Default is False.\n\n        \"\"\"\n        setattr(self.limits, which + 'lims', lims)\n        setattr(self.limits, 'd' + which, d)\n        setattr(self.limits, which + 'scale', scale)\n\n        if reverse:\n            setattr(self.limits, 'reverse_' + which + '_axis', True)\n        return", "title": ""}
{"_id": "d8243", "text": "def run_task(func):\n    \"\"\"\n    Decorator to wrap an async function in an event loop.\n    Use for main sync interface methods.\n    \"\"\"\n\n    def _wrapped(*a, **k):\n        loop = asyncio.get_event_loop()\n        return loop.run_until_complete(func(*a, **k))\n\n    return _wrapped", "title": ""}
{"_id": "d8244", "text": "def set_mem_per_proc(self, mem_mb):\n        \"\"\"Set the memory per process in megabytes\"\"\"\n        super().set_mem_per_proc(mem_mb)\n        self.qparams[\"mem_per_cpu\"] = self.mem_per_proc", "title": ""}
{"_id": "d8245", "text": "def safe_repr(obj):\n    \"\"\"\n    Try to get ``__name__`` first, ``__class__.__name__`` second\n    and finally, if we can't get anything acceptable, fallback\n    to user a ``repr()`` call.\n    \"\"\"\n    name = getattr(obj, '__name__', getattr(obj.__class__, '__name__'))\n    if name == 'ndict':\n        name = 'dict'\n    return name or repr(obj)", "title": ""}
{"_id": "d8246", "text": "async def smap(source, func, *more_sources):\n    \"\"\"Apply a given function to the elements of one or several\n    asynchronous sequences.\n\n    Each element is used as a positional argument, using the same order as\n    their respective sources. The generation continues until the shortest\n    sequence is exhausted. The function is treated synchronously.\n\n    Note: if more than one sequence is provided, they're awaited concurrently\n    so that their waiting times don't add up.\n    \"\"\"\n    if more_sources:\n        source = zip(source, *more_sources)\n    async with streamcontext(source) as streamer:\n        async for item in streamer:\n            yield func(*item) if more_sources else func(item)", "title": ""}
{"_id": "d8247", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d8248", "text": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "title": ""}
{"_id": "d8249", "text": "def align_file_position(f, size):\n    \"\"\" Align the position in the file to the next block of specified size \"\"\"\n    align = (size - 1) - (f.tell() % size)\n    f.seek(align, 1)", "title": ""}
{"_id": "d8250", "text": "def safe_setattr(obj, name, value):\n    \"\"\"Attempt to setattr but catch AttributeErrors.\"\"\"\n    try:\n        setattr(obj, name, value)\n        return True\n    except AttributeError:\n        return False", "title": ""}
{"_id": "d8251", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d8252", "text": "def load(self):\n        \"\"\"Load proxy list from configured proxy source\"\"\"\n        self._list = self._source.load()\n        self._list_iter = itertools.cycle(self._list)", "title": ""}
{"_id": "d8253", "text": "def longest_run_1d(arr):\n    \"\"\"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.\n    \"\"\"\n    v, rl = rle_1d(arr)[:2]\n    return np.where(v, rl, 0).max()", "title": ""}
{"_id": "d8254", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d8255", "text": "def longest_run_1d(arr):\n    \"\"\"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.\n    \"\"\"\n    v, rl = rle_1d(arr)[:2]\n    return np.where(v, rl, 0).max()", "title": ""}
{"_id": "d8256", "text": "def list_rds(region, filter_by_kwargs):\n    \"\"\"List all RDS thingys.\"\"\"\n    conn = boto.rds.connect_to_region(region)\n    instances = conn.get_all_dbinstances()\n    return lookup(instances, filter_by=filter_by_kwargs)", "title": ""}
{"_id": "d8257", "text": "def __init__(self, enumtype, index, key):\n        \"\"\" Set up a new instance. \"\"\"\n        self._enumtype = enumtype\n        self._index = index\n        self._key = key", "title": ""}
{"_id": "d8258", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d8259", "text": "def finish_plot():\n    \"\"\"Helper for plotting.\"\"\"\n    plt.legend()\n    plt.grid(color='0.7')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.show()", "title": ""}
{"_id": "d8260", "text": "def _bytes_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, bytes):\n        value = base64.standard_b64encode(value).decode(\"ascii\")\n    return value", "title": ""}
{"_id": "d8261", "text": "def bin_to_int(string):\n    \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n    if isinstance(string, str):\n        return struct.unpack(\"b\", string)[0]\n    else:\n        return struct.unpack(\"b\", bytes([string]))[0]", "title": ""}
{"_id": "d8262", "text": "def get_url(self, routename, **kargs):\n        \"\"\" Return a string that matches a named route \"\"\"\n        return '/' + self.routes.build(routename, **kargs).split(';', 1)[1]", "title": ""}
{"_id": "d8263", "text": "def _skip_frame(self):\n        \"\"\"Skip the next time frame\"\"\"\n        for line in self._f:\n            if line == 'ITEM: ATOMS\\n':\n                break\n        for i in range(self.num_atoms):\n            next(self._f)", "title": ""}
{"_id": "d8264", "text": "def mean_cl_boot(series, n_samples=1000, confidence_interval=0.95,\n                 random_state=None):\n    \"\"\"\n    Bootstrapped mean with confidence limits\n    \"\"\"\n    return bootstrap_statistics(series, np.mean,\n                                n_samples=n_samples,\n                                confidence_interval=confidence_interval,\n                                random_state=random_state)", "title": ""}
{"_id": "d8265", "text": "def test3():\n    \"\"\"Test the multiprocess\n    \"\"\"\n    import time\n    \n    p = MVisionProcess()\n    p.start()\n    time.sleep(5)\n    p.stop()", "title": ""}
{"_id": "d8266", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d8267", "text": "def getcolslice(self, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1):\n        \"\"\"Get a slice from a table column holding arrays.\n        (see :func:`table.getcolslice`)\"\"\"\n        return self._table.getcolslice(self._column, blc, trc, inc, startrow, nrow, rowincr)", "title": ""}
{"_id": "d8268", "text": "def start():\n    \"\"\"Starts the web server.\"\"\"\n    global app\n    bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n               debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n               quiet=conf.WebQuiet)", "title": ""}
{"_id": "d8269", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d8270", "text": "def get_http_method(self, method):\n        \"\"\"Gets the http method that will be called from the requests library\"\"\"\n        return self.http_methods[method](self.url, **self.http_method_args)", "title": ""}
{"_id": "d8271", "text": "def arglexsort(arrays):\n    \"\"\"\n    Returns the indices of the lexicographical sorting\n    order of the supplied arrays.\n    \"\"\"\n    dtypes = ','.join(array.dtype.str for array in arrays)\n    recarray = np.empty(len(arrays[0]), dtype=dtypes)\n    for i, array in enumerate(arrays):\n        recarray['f%s' % i] = array\n    return recarray.argsort()", "title": ""}
{"_id": "d8272", "text": "def __sort_up(self):\n\n        \"\"\"Sort the updatable objects according to ascending order\"\"\"\n        if self.__do_need_sort_up:\n            self.__up_objects.sort(key=cmp_to_key(self.__up_cmp))\n            self.__do_need_sort_up = False", "title": ""}
{"_id": "d8273", "text": "def disable_cert_validation():\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d8274", "text": "def unsort_vector(data, indices_of_increasing):\n    \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n    return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])", "title": ""}
{"_id": "d8275", "text": "def poke_array(self, store, name, elemtype, elements, container, visited, _stack):\n        \"\"\"abstract method\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d8276", "text": "def chunked(l, n):\n    \"\"\"Chunk one big list into few small lists.\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d8277", "text": "def update_index(index):\n    \"\"\"Re-index every document in a named index.\"\"\"\n    logger.info(\"Updating search index: '%s'\", index)\n    client = get_client()\n    responses = []\n    for model in get_index_models(index):\n        logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n        objects = model.objects.get_search_queryset(index).iterator()\n        actions = bulk_actions(objects, index=index, action=\"index\")\n        response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n        responses.append(response)\n    return responses", "title": ""}
{"_id": "d8278", "text": "def split_into_words(s):\n  \"\"\"Split a sentence into list of words.\"\"\"\n  s = re.sub(r\"\\W+\", \" \", s)\n  s = re.sub(r\"[_0-9]+\", \" \", s)\n  return s.split()", "title": ""}
{"_id": "d8279", "text": "def fmt_sz(intval):\n    \"\"\" Format a byte sized value.\n    \"\"\"\n    try:\n        return fmt.human_size(intval)\n    except (ValueError, TypeError):\n        return \"N/A\".rjust(len(fmt.human_size(0)))", "title": ""}
{"_id": "d8280", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d8281", "text": "def cleanup_lib(self):\n        \"\"\" unload the previously loaded shared library \"\"\"\n        if not self.using_openmp:\n            #this if statement is necessary because shared libraries that use\n            #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP\n            logging.debug('unloading shared library')\n            _ctypes.dlclose(self.lib._handle)", "title": ""}
{"_id": "d8282", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d8283", "text": "def _get_memoized_value(func, args, kwargs):\n    \"\"\"Used internally by memoize decorator to get/store function results\"\"\"\n    key = (repr(args), repr(kwargs))\n\n    if not key in func._cache_dict:\n        ret = func(*args, **kwargs)\n        func._cache_dict[key] = ret\n\n    return func._cache_dict[key]", "title": ""}
{"_id": "d8284", "text": "def locked_delete(self):\n        \"\"\"Delete credentials from the SQLAlchemy datastore.\"\"\"\n        filters = {self.key_name: self.key_value}\n        self.session.query(self.model_class).filter_by(**filters).delete()", "title": ""}
{"_id": "d8285", "text": "def triangle_normal(a, b, c):\n    \"\"\"Return a vector orthogonal to the given triangle\n\n       Arguments:\n         a, b, c  --  three 3D numpy vectors\n    \"\"\"\n    normal = np.cross(a - c, b - c)\n    norm = np.linalg.norm(normal)\n    return normal/norm", "title": ""}
{"_id": "d8286", "text": "def _shutdown_transport(self):\n        \"\"\"Unwrap a Python 2.6 SSL socket, so we can call shutdown()\"\"\"\n        if self.sock is not None:\n            try:\n                unwrap = self.sock.unwrap\n            except AttributeError:\n                return\n            try:\n                self.sock = unwrap()\n            except ValueError:\n                # Failure within SSL might mean unwrap exists but socket is not\n                # deemed wrapped\n                pass", "title": ""}
{"_id": "d8287", "text": "def get_tri_area(pts):\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d8288", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d8289", "text": "def distance_to_line(a, b, p):\n    \"\"\"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\n    \"\"\"\n    return distance(closest_point(a, b, p), p)", "title": ""}
{"_id": "d8290", "text": "def post_ratelimited(protocol, session, url, headers, data, allow_redirects=False, stream=False):\n    \"\"\"\n    There are two error-handling policies implemented here: a fail-fast policy intended for stand-alone scripts which\n    fails on all responses except HTTP 200. The other policy is intended for long-running tasks that need to respect\n    rate-limiting errors from the server and paper over outages of up to 1 hour.\n\n    Wrap POST requests in a try-catch loop with a lot of error handling logic and some basic rate-limiting. If a request\n    fails, and some conditions are met, the loop waits in increasing intervals, up to 1 hour, before trying again. The\n    reason for this is that servers often malfunction for short periods of time, either because of ongoing data\n    migrations or other maintenance tasks, misconfigurations or heavy load, or because the connecting user has hit a\n    throttling policy limit.\n\n    If the loop exited early, consumers of this package that don't implement their own rate-limiting code could quickly\n    swamp such a server with new requests. That would only make things worse. Instead, it's better if the request loop\n    waits patiently until the server is functioning again.\n\n    If the connecting user has hit a throttling policy, then the server will start to malfunction in many interesting\n    ways, but never actually tell the user what is happening. There is no way to distinguish this situation from other\n    malfunctions. The only cure is to stop making requests.\n\n    The contract on sessions here is to return the session that ends up being used, or retiring the session if we\n    intend to raise an exception. We give up on max_wait timeout, not number of retries.\n\n    An additional resource on handling throttling policies and client back off strategies:\n        https://msdn.microsoft.com/en-us/library/office/jj945066(v=exchg.150).aspx#bk_ThrottlingBatch\n    \"\"\"\n    thread_id = get_ident()\n    wait = 10  # seconds\n    retry = 0\n    redirects = 0\n    # In Python 2, we want this to be a 'str' object so logging doesn't break (all formatting arguments are 'str').\n    # We activated 'unicode_literals' at the top of this file, so it would be a 'unicode' object unless we convert\n    # to 'str' explicitly. This is a no-op for Python 3.\n    log_msg = str('''\\\nRetry: %(retry)s\nWaited: %(wait)s\nTimeout: %(timeout)s\nSession: %(session_id)s\nThread: %(thread_id)s\nAuth type: %(auth)s\nURL: %(url)s\nHTTP adapter: %(adapter)s\nAllow redirects: %(allow_redirects)s\nStreaming: %(stream)s\nResponse time: %(response_time)s\nStatus code: %(status_code)s\nRequest headers: %(request_headers)s\nResponse headers: %(response_headers)s\nRequest data: %(xml_request)s\nResponse data: %(xml_response)s\n''')\n    log_vals = dict(\n        retry=retry,\n        wait=wait,\n        timeout=protocol.TIMEOUT,\n        session_id=session.session_id,\n        thread_id=thread_id,\n        auth=session.auth,\n        url=url,\n        adapter=session.get_adapter(url),\n        allow_redirects=allow_redirects,\n        stream=stream,\n        response_time=None,\n        status_code=None,\n        request_headers=headers,\n        response_headers=None,\n        xml_request=data,\n        xml_response=None,\n    )\n    try:\n        while True:\n            _back_off_if_needed(protocol.credentials.back_off_until)\n            log.debug('Session %s thread %s: retry %s timeout %s POST\\'ing to %s after %ss wait', session.session_id,\n                      thread_id, retry, protocol.TIMEOUT, url, wait)\n            d_start = time_func()\n            # Always create a dummy response for logging purposes, in case we fail in the following\n            r = DummyResponse(url=url, headers={}, request_headers=headers)\n            try:\n                r = session.post(url=url, headers=headers, data=data, allow_redirects=False, timeout=protocol.TIMEOUT,\n                                 stream=stream)\n            except CONNECTION_ERRORS as e:\n                log.debug('Session %s thread %s: connection error POST\\'ing to %s', session.session_id, thread_id, url)\n                r = DummyResponse(url=url, headers={'TimeoutException': e}, request_headers=headers)\n            finally:\n                log_vals.update(\n                    retry=retry,\n                    wait=wait,\n                    session_id=session.session_id,\n                    url=str(r.url),\n                    response_time=time_func() - d_start,\n                    status_code=r.status_code,\n                    request_headers=r.request.headers,\n                    response_headers=r.headers,\n                    xml_response='[STREAMING]' if stream else r.content,\n                )\n            log.debug(log_msg, log_vals)\n            if _may_retry_on_error(r, protocol, wait):\n                log.info(\"Session %s thread %s: Connection error on URL %s (code %s). Cool down %s secs\",\n                         session.session_id, thread_id, r.url, r.status_code, wait)\n                time.sleep(wait)  # Increase delay for every retry\n                retry += 1\n                wait *= 2\n                session = protocol.renew_session(session)\n                continue\n            if r.status_code in (301, 302):\n                if stream:\n                    r.close()\n                url, redirects = _redirect_or_fail(r, redirects, allow_redirects)\n                continue\n            break\n    except (RateLimitError, RedirectError) as e:\n        log.warning(e.value)\n        protocol.retire_session(session)\n        raise\n    except Exception as e:\n        # Let higher layers handle this. Add full context for better debugging.\n        log.error(str('%s: %s\\n%s'), e.__class__.__name__, str(e), log_msg % log_vals)\n        protocol.retire_session(session)\n        raise\n    if r.status_code == 500 and r.content and is_xml(r.content):\n        # Some genius at Microsoft thinks it's OK to send a valid SOAP response as an HTTP 500\n        log.debug('Got status code %s but trying to parse content anyway', r.status_code)\n    elif r.status_code != 200:\n        protocol.retire_session(session)\n        try:\n            _raise_response_errors(r, protocol, log_msg, log_vals)  # Always raises an exception\n        finally:\n            if stream:\n                r.close()\n    log.debug('Session %s thread %s: Useful response from %s', session.session_id, thread_id, url)\n    return r, session", "title": ""}
{"_id": "d8291", "text": "def fft_freqs(n_fft, fs):\n    \"\"\"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.\n    \"\"\"\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)", "title": ""}
{"_id": "d8292", "text": "def get_previous_month(self):\n        \"\"\"Returns date range for the previous full month.\"\"\"\n        end = utils.get_month_start() - relativedelta(days=1)\n        end = utils.to_datetime(end)\n        start = utils.get_month_start(end)\n        return start, end", "title": ""}
{"_id": "d8293", "text": "def _hue(color, **kwargs):\n    \"\"\" Get hue value of HSL color.\n    \"\"\"\n    h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0]\n    return NumberValue(h * 360.0)", "title": ""}
{"_id": "d8294", "text": "def weighted_std(values, weights):\n    \"\"\" Calculate standard deviation weighted by errors \"\"\"\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)", "title": ""}
{"_id": "d8295", "text": "def estimate_complexity(self, x,y,z,n):\n        \"\"\" \n        calculates a rough guess of runtime based on product of parameters \n        \"\"\"\n        num_calculations = x * y * z * n\n        run_time = num_calculations / 100000  # a 2014 PC does about 100k calcs in a second (guess based on prior logs)\n        return self.show_time_as_short_string(run_time)", "title": ""}
{"_id": "d8296", "text": "def _update_staticmethod(self, oldsm, newsm):\n        \"\"\"Update a staticmethod update.\"\"\"\n        # While we can't modify the staticmethod object itself (it has no\n        # mutable attributes), we *can* extract the underlying function\n        # (by calling __get__(), which returns it) and update it in-place.\n        # We don't have the class available to pass to __get__() but any\n        # object except None will do.\n        self._update(None, None, oldsm.__get__(0), newsm.__get__(0))", "title": ""}
{"_id": "d8297", "text": "def submit(self, fn, *args, **kwargs):\n        \"\"\"Submit an operation\"\"\"\n        corofn = asyncio.coroutine(lambda: fn(*args, **kwargs))\n        return run_coroutine_threadsafe(corofn(), self.loop)", "title": ""}
{"_id": "d8298", "text": "def stop(self):\n\t\t\"\"\" Stops the video stream and resets the clock. \"\"\"\n\n\t\tlogger.debug(\"Stopping playback\")\n\t\t# Stop the clock\n\t\tself.clock.stop()\n\t\t# Set plauyer status to ready\n\t\tself.status = READY", "title": ""}
{"_id": "d8299", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d8300", "text": "def get_login_credentials(args):\n  \"\"\"\n    Gets the login credentials from the user, if not specified while invoking\n    the script.\n    @param args: arguments provided to the script.\n    \"\"\"\n  if not args.username:\n    args.username = raw_input(\"Enter Username: \")\n  if not args.password:\n    args.password = getpass.getpass(\"Enter Password: \")", "title": ""}
{"_id": "d8301", "text": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "title": ""}
{"_id": "d8302", "text": "def deserialize_ndarray_npy(d):\n    \"\"\"\n    Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's\n    :obj:`save` function.\n\n    Args:\n        d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created\n            using :obj:`numpy.save`.\n\n    Returns:\n        An :obj:`ndarray` object.\n    \"\"\"\n    with io.BytesIO() as f:\n        f.write(json.loads(d['npy']).encode('latin-1'))\n        f.seek(0)\n        return np.load(f)", "title": ""}
{"_id": "d8303", "text": "def mixedcase(path):\n    \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n    words = path.split('_')\n    return words[0] + ''.join(word.title() for word in words[1:])", "title": ""}
{"_id": "d8304", "text": "def getFunction(self):\n        \"\"\"Called by remote workers. Useful to populate main module globals()\n        for interactive shells. Retrieves the serialized function.\"\"\"\n        return functionFactory(\n            self.code,\n            self.name,\n            self.defaults,\n            self.globals,\n            self.imports,\n        )", "title": ""}
{"_id": "d8305", "text": "def add_suffix(fullname, suffix):\n    \"\"\" Add suffix to a full file name\"\"\"\n    name, ext = os.path.splitext(fullname)\n    return name + '_' + suffix + ext", "title": ""}
{"_id": "d8306", "text": "def _encode_bool(name, value, dummy0, dummy1):\n    \"\"\"Encode a python boolean (True/False).\"\"\"\n    return b\"\\x08\" + name + (value and b\"\\x01\" or b\"\\x00\")", "title": ""}
{"_id": "d8307", "text": "def angle_to_cartesian(lon, lat):\n    \"\"\"Convert spherical coordinates to cartesian unit vectors.\"\"\"\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", "title": ""}
{"_id": "d8308", "text": "def one_hot2string(arr, vocab):\n    \"\"\"Convert a one-hot encoded array back to string\n    \"\"\"\n    tokens = one_hot2token(arr)\n    indexToLetter = _get_index_dict(vocab)\n\n    return [''.join([indexToLetter[x] for x in row]) for row in tokens]", "title": ""}
{"_id": "d8309", "text": "def cartesian_product(arrays, flat=True, copy=False):\n    \"\"\"\n    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.\n    \"\"\"\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)", "title": ""}
{"_id": "d8310", "text": "def get_title(soup):\n  \"\"\"Given a soup, pick out a title\"\"\"\n  if soup.title:\n    return soup.title.string\n  if soup.h1:\n    return soup.h1.string\n  return ''", "title": ""}
{"_id": "d8311", "text": "def cart2pol(x, y):\n    \"\"\"Cartesian to Polar coordinates conversion.\"\"\"\n    theta = np.arctan2(y, x)\n    rho = np.hypot(x, y)\n    return theta, rho", "title": ""}
{"_id": "d8312", "text": "def covstr(s):\n  \"\"\" convert string to int or float. \"\"\"\n  try:\n    ret = int(s)\n  except ValueError:\n    ret = float(s)\n  return ret", "title": ""}
{"_id": "d8313", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d8314", "text": "def text_cleanup(data, key, last_type):\n    \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data", "title": ""}
{"_id": "d8315", "text": "def load(self, name):\n        \"\"\"Loads and returns foreign library.\"\"\"\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)", "title": ""}
{"_id": "d8316", "text": "def to_bytes(s, encoding=\"utf-8\"):\n    \"\"\"Convert a string to bytes.\"\"\"\n    if isinstance(s, six.binary_type):\n        return s\n    if six.PY3:\n        return bytes(s, encoding)\n    return s.encode(encoding)", "title": ""}
{"_id": "d8317", "text": "def pad_image(arr, max_size=400):\n    \"\"\"Pads an image to a square then resamples to max_size\"\"\"\n    dim = np.max(arr.shape)\n    img = np.zeros((dim, dim, 3), dtype=arr.dtype)\n    xl = (dim - arr.shape[0]) // 2\n    yl = (dim - arr.shape[1]) // 2\n    img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr\n    return resample_image(img, max_size=max_size)", "title": ""}
{"_id": "d8318", "text": "def _parse(self, date_str, format='%Y-%m-%d'):\n        \"\"\"\n        helper function for parsing FRED date string into datetime\n        \"\"\"\n        rv = pd.to_datetime(date_str, format=format)\n        if hasattr(rv, 'to_pydatetime'):\n            rv = rv.to_pydatetime()\n        return rv", "title": ""}
{"_id": "d8319", "text": "def QA_util_datetime_to_strdate(dt):\n    \"\"\"\n    :param dt:  pythone datetime.datetime\n    :return:  1999-02-01 string type\n    \"\"\"\n    strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n    return strdate", "title": ""}
{"_id": "d8320", "text": "def do_striptags(value):\n    \"\"\"Strip SGML/XML tags and replace adjacent whitespace by one space.\n    \"\"\"\n    if hasattr(value, '__html__'):\n        value = value.__html__()\n    return Markup(unicode(value)).striptags()", "title": ""}
{"_id": "d8321", "text": "def inc_date(date_obj, num, date_fmt):\n    \"\"\"Increment the date by a certain number and return date object.\n    as the specific string format.\n    \"\"\"\n    return (date_obj + timedelta(days=num)).strftime(date_fmt)", "title": ""}
{"_id": "d8322", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d8323", "text": "def convert_camel_case_to_snake_case(name):\n    \"\"\"Convert CamelCase to snake_case.\"\"\"\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()", "title": ""}
{"_id": "d8324", "text": "def _strptime(self, time_str):\n        \"\"\"Convert an ISO 8601 formatted string in UTC into a\n        timezone-aware datetime object.\"\"\"\n        if time_str:\n            # Parse UTC string into naive datetime, then add timezone\n            dt = datetime.strptime(time_str, __timeformat__)\n            return dt.replace(tzinfo=UTC())\n        return None", "title": ""}
{"_id": "d8325", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d8326", "text": "def pylog(self, *args, **kwargs):\n        \"\"\"Display all available logging information.\"\"\"\n        printerr(self.name, args, kwargs, traceback.format_exc())", "title": ""}
{"_id": "d8327", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d8328", "text": "def _svd(cls, matrix, num_concepts=5):\n        \"\"\"\n        Perform singular value decomposition for dimensionality reduction of the input matrix.\n        \"\"\"\n        u, s, v = svds(matrix, k=num_concepts)\n        return u, s, v", "title": ""}
{"_id": "d8329", "text": "def writer_acquire(self):\n        \"\"\"Acquire the lock to write\"\"\"\n\n        self._order_mutex.acquire()\n        self._access_mutex.acquire()\n        self._order_mutex.release()", "title": ""}
{"_id": "d8330", "text": "def imp_print(self, text, end):\n\t\t\"\"\"Directly send utf8 bytes to stdout\"\"\"\n\t\tsys.stdout.write((text + end).encode(\"utf-8\"))", "title": ""}
{"_id": "d8331", "text": "def set_executable(filename):\n    \"\"\"Set the exectuable bit on the given filename\"\"\"\n    st = os.stat(filename)\n    os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d8332", "text": "def h5ToDict(h5, readH5pyDataset=True):\n    \"\"\" Read a hdf5 file into a dictionary \"\"\"\n    h = h5py.File(h5, \"r\")\n    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n    if readH5pyDataset: h.close()\n    return ret", "title": ""}
{"_id": "d8333", "text": "def datetime_to_timezone(date, tz=\"UTC\"):\n    \"\"\" convert naive datetime to timezone-aware datetime \"\"\"\n    if not date.tzinfo:\n        date = date.replace(tzinfo=timezone(get_timezone()))\n    return date.astimezone(timezone(tz))", "title": ""}
{"_id": "d8334", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d8335", "text": "def is_image_file_valid(file_path_name):\n    \"\"\"\n    Indicate whether the specified image file is valid or not.\n\n\n    @param file_path_name: absolute path and file name of an image.\n\n\n    @return: ``True`` if the image file is valid, ``False`` if the file is\n        truncated or does not correspond to a supported image.\n    \"\"\"\n    # Image.verify is only implemented for PNG images, and it only verifies\n    # the CRC checksum in the image.  The only way to check from within\n    # Pillow is to load the image in a try/except and check the error.  If\n    # as much info as possible is from the image is needed,\n    # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it\n    # will attempt to parse as much as possible.\n    try:\n        with Image.open(file_path_name) as image:\n            image.load()\n    except IOError:\n        return False\n\n    return True", "title": ""}
{"_id": "d8336", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d8337", "text": "def _validate_pos(df):\n    \"\"\"Validates the returned positional object\n    \"\"\"\n    assert isinstance(df, pd.DataFrame)\n    assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n    assert df.position.dtype == np.dtype(\"int64\")\n    assert df.strand.dtype == np.dtype(\"O\")\n    assert df.seqname.dtype == np.dtype(\"O\")\n    return df", "title": ""}
{"_id": "d8338", "text": "def go_to_line(self, line):\n        \"\"\"\n        Moves the text cursor to given line.\n\n        :param line: Line to go to.\n        :type line: int\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        cursor = self.textCursor()\n        cursor.setPosition(self.document().findBlockByNumber(line - 1).position())\n        self.setTextCursor(cursor)\n        return True", "title": ""}
{"_id": "d8339", "text": "def _check_key(self, key):\n        \"\"\"\n        Ensures well-formedness of a key.\n        \"\"\"\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])", "title": ""}
{"_id": "d8340", "text": "def get_decimal_quantum(precision):\n    \"\"\"Return minimal quantum of a number, as defined by precision.\"\"\"\n    assert isinstance(precision, (int, decimal.Decimal))\n    return decimal.Decimal(10) ** (-precision)", "title": ""}
{"_id": "d8341", "text": "def required_attributes(element, *attributes):\n    \"\"\"Check element for required attributes. Raise ``NotValidXmlException`` on error.\n\n    :param element: ElementTree element\n    :param attributes: list of attributes names to check\n    :raises NotValidXmlException: if some argument is missing\n    \"\"\"\n    if not reduce(lambda still_valid, param: still_valid and param in element.attrib, attributes, True):\n        raise NotValidXmlException(msg_err_missing_attributes(element.tag, *attributes))", "title": ""}
{"_id": "d8342", "text": "def tf2():\n  \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n  Returns:\n    The root module of a TF-2.0 API, if available.\n\n  Raises:\n    ImportError: if a TF-2.0 API is not available.\n  \"\"\"\n  # Import the `tf` compat API from this file and check if it's already TF 2.0.\n  if tf.__version__.startswith('2.'):\n    return tf\n  elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n    # As a fallback, try `tensorflow.compat.v2` if it's defined.\n    return tf.compat.v2\n  raise ImportError('cannot import tensorflow 2.0 API')", "title": ""}
{"_id": "d8343", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d8344", "text": "def afx_small():\n  \"\"\"Small transformer model with small batch size for fast step times.\"\"\"\n  hparams = transformer.transformer_tpu()\n  hparams.filter_size = 1024\n  hparams.num_heads = 4\n  hparams.num_hidden_layers = 3\n  hparams.batch_size = 512\n  return hparams", "title": ""}
{"_id": "d8345", "text": "def _is_already_configured(configuration_details):\n    \"\"\"Returns `True` when alias already in shell config.\"\"\"\n    path = Path(configuration_details.path).expanduser()\n    with path.open('r') as shell_config:\n        return configuration_details.content in shell_config.read()", "title": ""}
{"_id": "d8346", "text": "def tf2():\n  \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n  Returns:\n    The root module of a TF-2.0 API, if available.\n\n  Raises:\n    ImportError: if a TF-2.0 API is not available.\n  \"\"\"\n  # Import the `tf` compat API from this file and check if it's already TF 2.0.\n  if tf.__version__.startswith('2.'):\n    return tf\n  elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n    # As a fallback, try `tensorflow.compat.v2` if it's defined.\n    return tf.compat.v2\n  raise ImportError('cannot import tensorflow 2.0 API')", "title": ""}
{"_id": "d8347", "text": "def _replace_file(path, content):\n  \"\"\"Writes a file if it doesn't already exist with the same content.\n\n  This is useful because cargo uses timestamps to decide whether to compile things.\"\"\"\n  if os.path.exists(path):\n    with open(path, 'r') as f:\n      if content == f.read():\n        print(\"Not overwriting {} because it is unchanged\".format(path), file=sys.stderr)\n        return\n\n  with open(path, 'w') as f:\n    f.write(content)", "title": ""}
{"_id": "d8348", "text": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "title": ""}
{"_id": "d8349", "text": "def clean_float(v):\n    \"\"\"Remove commas from a float\"\"\"\n\n    if v is None or not str(v).strip():\n        return None\n\n    return float(str(v).replace(',', ''))", "title": ""}
{"_id": "d8350", "text": "def is_same_shape(self, other_im, check_channels=False):\n        \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n        Parameters\n        ----------\n        other_im : :obj:`Image`\n            image to compare\n        check_channels : bool\n            whether or not to check equality of the channels\n\n        Returns\n        -------\n        bool\n            True if the images are the same shape, False otherwise\n        \"\"\"\n        if self.height == other_im.height and self.width == other_im.width:\n            if check_channels and self.channels != other_im.channels:\n                return False\n            return True\n        return False", "title": ""}
{"_id": "d8351", "text": "def _is_one_arg_pos_call(call):\n    \"\"\"Is this a call with exactly 1 argument,\n    where that argument is positional?\n    \"\"\"\n    return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords", "title": ""}
{"_id": "d8352", "text": "def wait_and_join(self, task):\n        \"\"\" Given a task, waits for it until it finishes\n        :param task: Task\n        :return:\n        \"\"\"\n        while not task.has_started:\n            time.sleep(self._polling_time)\n        task.thread.join()", "title": ""}
{"_id": "d8353", "text": "def is_changed():\n    \"\"\" Checks if current project has any noncommited changes. \"\"\"\n    executed, changed_lines = execute_git('status --porcelain', output=False)\n    merge_not_finished = mod_path.exists('.git/MERGE_HEAD')\n    return changed_lines.strip() or merge_not_finished", "title": ""}
{"_id": "d8354", "text": "def clear_timeline(self):\n        \"\"\"\n        Clear the contents of the TimeLine Canvas\n\n        Does not modify the actual markers dictionary and thus after\n        redrawing all markers are visible again.\n        \"\"\"\n        self._timeline.delete(tk.ALL)\n        self._canvas_ticks.delete(tk.ALL)", "title": ""}
{"_id": "d8355", "text": "def ensure_dir_exists(directory):\n    \"\"\"Se asegura de que un directorio exista.\"\"\"\n    if directory and not os.path.exists(directory):\n        os.makedirs(directory)", "title": ""}
{"_id": "d8356", "text": "def add_blank_row(self, label):\n        \"\"\"\n        Add a blank row with only an index value to self.df.\n        This is done inplace.\n        \"\"\"\n        col_labels = self.df.columns\n        blank_item = pd.Series({}, index=col_labels, name=label)\n        # use .loc to add in place (append won't do that)\n        self.df.loc[blank_item.name] = blank_item\n        return self.df", "title": ""}
{"_id": "d8357", "text": "def is_nullable_list(val, vtype):\n    \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n    return (isinstance(val, list) and\n            any(isinstance(v, vtype) for v in val) and\n            all((isinstance(v, vtype) or v is None) for v in val))", "title": ""}
{"_id": "d8358", "text": "def listified_tokenizer(source):\n    \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n    io_obj = io.StringIO(source)\n    return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]", "title": ""}
{"_id": "d8359", "text": "def url_syntax_check(url):  # pragma: no cover\n    \"\"\"\n    Check the syntax of the given URL.\n\n    :param url: The URL to check the syntax for.\n    :type url: str\n\n    :return: The syntax validity.\n    :rtype: bool\n\n    .. warning::\n        If an empty or a non-string :code:`url` is given, we return :code:`None`.\n    \"\"\"\n\n    if url and isinstance(url, str):\n        # The given URL is not empty nor None.\n        # and\n        # * The given URL is a string.\n\n        # We silently load the configuration.\n        load_config(True)\n\n        return Check(url).is_url_valid()\n\n    # We return None, there is nothing to check.\n    return None", "title": ""}
{"_id": "d8360", "text": "def print_ldamodel_topic_words(topic_word_distrib, vocab, n_top=10, row_labels=DEFAULT_TOPIC_NAME_FMT):\n    \"\"\"Print `n_top` values from a LDA model's topic-word distributions.\"\"\"\n    print_ldamodel_distribution(topic_word_distrib, row_labels=row_labels, val_labels=vocab,\n                                top_n=n_top)", "title": ""}
{"_id": "d8361", "text": "def drop_trailing_zeros(num):\n    \"\"\"\n    Drops the trailing zeros in a float that is printed.\n    \"\"\"\n    txt = '%f' %(num)\n    txt = txt.rstrip('0')\n    if txt.endswith('.'):\n        txt = txt[:-1]\n    return txt", "title": ""}
{"_id": "d8362", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d8363", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d8364", "text": "def is_binary(filename):\n    \"\"\" Returns True if the file is binary\n\n    \"\"\"\n    with open(filename, 'rb') as fp:\n        data = fp.read(1024)\n        if not data:\n            return False\n        if b'\\0' in data:\n            return True\n        return False", "title": ""}
{"_id": "d8365", "text": "def html_to_text(content):\n    \"\"\" Converts html content to plain text \"\"\"\n    text = None\n    h2t = html2text.HTML2Text()\n    h2t.ignore_links = False\n    text = h2t.handle(content)\n    return text", "title": ""}
{"_id": "d8366", "text": "def isstring(value):\n    \"\"\"Report whether the given value is a byte or unicode string.\"\"\"\n    classes = (str, bytes) if pyutils.PY3 else basestring  # noqa: F821\n    return isinstance(value, classes)", "title": ""}
{"_id": "d8367", "text": "def log_normalize(data):\n    \"\"\"Perform log transform log(x + 1).\n    \n    Parameters\n    ----------\n    data : array_like\n    \n    \"\"\"\n    if sp.issparse(data):\n        data = data.copy()\n        data.data = np.log2(data.data + 1)\n        return data\n\n    return np.log2(data.astype(np.float64) + 1)", "title": ""}
{"_id": "d8368", "text": "def is_collection(obj):\n    \"\"\"Tests if an object is a collection.\"\"\"\n\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n\n    if isinstance(obj, basestring):\n        val = False\n\n    return val", "title": ""}
{"_id": "d8369", "text": "def command_py2to3(args):\n    \"\"\"\n    Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n    \"\"\"\n    from lib2to3.main import main\n    sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "title": ""}
{"_id": "d8370", "text": "def str_check(*args, func=None):\n    \"\"\"Check if arguments are str type.\"\"\"\n    func = func or inspect.stack()[2][3]\n    for var in args:\n        if not isinstance(var, (str, collections.UserString, collections.abc.Sequence)):\n            name = type(var).__name__\n            raise StringError(\n                f'Function {func} expected str, {name} got instead.')", "title": ""}
{"_id": "d8371", "text": "def is_http_running_on(port):\n  \"\"\" Check if an http server runs on a given port.\n\n  Args:\n    The port to check.\n  Returns:\n    True if it is used by an http server. False otherwise.\n  \"\"\"\n  try:\n    conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n    conn.connect()\n    conn.close()\n    return True\n  except Exception:\n    return False", "title": ""}
{"_id": "d8372", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d8373", "text": "def is_int_type(val):\n    \"\"\"Return True if `val` is of integer type.\"\"\"\n    try:               # Python 2\n        return isinstance(val, (int, long))\n    except NameError:  # Python 3\n        return isinstance(val, int)", "title": ""}
{"_id": "d8374", "text": "def __contains__(self, key):\n        \"\"\"\n        Invoked when determining whether a specific key is in the dictionary\n        using `key in d`.\n\n        The key is looked up case-insensitively.\n        \"\"\"\n        k = self._real_key(key)\n        return k in self._data", "title": ""}
{"_id": "d8375", "text": "def set_scrollbars_cb(self, w, tf):\n        \"\"\"This callback is invoked when the user checks the 'Use Scrollbars'\n        box in the preferences pane.\"\"\"\n        scrollbars = 'on' if tf else 'off'\n        self.t_.set(scrollbars=scrollbars)", "title": ""}
{"_id": "d8376", "text": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "title": ""}
{"_id": "d8377", "text": "def hash_iterable(it):\n\t\"\"\"Perform a O(1) memory hash of an iterable of arbitrary length.\n\n\thash(tuple(it)) creates a temporary tuple containing all values from it\n\twhich could be a problem if it is large.\n\n\tSee discussion at:\n\thttps://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ\n\t\"\"\"\n\thash_value = hash(type(it))\n\tfor value in it:\n\t\thash_value = hash((hash_value, value))\n\treturn hash_value", "title": ""}
{"_id": "d8378", "text": "def require_root(fn):\n    \"\"\"\n    Decorator to make sure, that user is root.\n    \"\"\"\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\n    return xex", "title": ""}
{"_id": "d8379", "text": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "title": ""}
{"_id": "d8380", "text": "def all_equal(arg1,arg2):\n    \"\"\"\n    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.\n    \"\"\"\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", "title": ""}
{"_id": "d8381", "text": "def string_to_list(string, sep=\",\", filter_empty=False):\n    \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n    return [value.strip() for value in string.split(sep)\n            if (not filter_empty or value)]", "title": ""}
{"_id": "d8382", "text": "def is_closed(self):\n        \"\"\" Check if session was closed. \"\"\"\n        return (self.state == SESSION_STATE.CLOSED \n                or self.state == SESSION_STATE.CLOSING)", "title": ""}
{"_id": "d8383", "text": "def xml_str_to_dict(s):\n    \"\"\" Transforms an XML string it to python-zimbra dict format\n\n    For format, see:\n      https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n    :param: a string, containing XML\n    :returns: a dict, with python-zimbra format\n    \"\"\"\n    xml = minidom.parseString(s)\n    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)", "title": ""}
{"_id": "d8384", "text": "def _lookup_enum_in_ns(namespace, value):\n    \"\"\"Return the attribute of namespace corresponding to value.\"\"\"\n    for attribute in dir(namespace):\n        if getattr(namespace, attribute) == value:\n            return attribute", "title": ""}
{"_id": "d8385", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d8386", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d8387", "text": "def bytes_to_str(s, encoding='utf-8'):\n    \"\"\"Returns a str if a bytes object is given.\"\"\"\n    if six.PY3 and isinstance(s, bytes):\n        return s.decode(encoding)\n    return s", "title": ""}
{"_id": "d8388", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d8389", "text": "def require_root(fn):\n    \"\"\"\n    Decorator to make sure, that user is root.\n    \"\"\"\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\n    return xex", "title": ""}
{"_id": "d8390", "text": "def is_readable(filename):\n    \"\"\"Check if file is a regular file and is readable.\"\"\"\n    return os.path.isfile(filename) and os.access(filename, os.R_OK)", "title": ""}
{"_id": "d8391", "text": "def symbol_pos_int(*args, **kwargs):\n    \"\"\"Create a sympy.Symbol with positive and integer assumptions.\"\"\"\n    kwargs.update({'positive': True,\n                   'integer': True})\n    return sympy.Symbol(*args, **kwargs)", "title": ""}
{"_id": "d8392", "text": "def is_image_file_valid(file_path_name):\n    \"\"\"\n    Indicate whether the specified image file is valid or not.\n\n\n    @param file_path_name: absolute path and file name of an image.\n\n\n    @return: ``True`` if the image file is valid, ``False`` if the file is\n        truncated or does not correspond to a supported image.\n    \"\"\"\n    # Image.verify is only implemented for PNG images, and it only verifies\n    # the CRC checksum in the image.  The only way to check from within\n    # Pillow is to load the image in a try/except and check the error.  If\n    # as much info as possible is from the image is needed,\n    # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it\n    # will attempt to parse as much as possible.\n    try:\n        with Image.open(file_path_name) as image:\n            image.load()\n    except IOError:\n        return False\n\n    return True", "title": ""}
{"_id": "d8393", "text": "def peak_memory_usage():\n    \"\"\"Return peak memory usage in MB\"\"\"\n    if sys.platform.startswith('win'):\n        p = psutil.Process()\n        return p.memory_info().peak_wset / 1024 / 1024\n\n    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n    factor_mb = 1 / 1024\n    if sys.platform == 'darwin':\n        factor_mb = 1 / (1024 * 1024)\n    return mem * factor_mb", "title": ""}
{"_id": "d8394", "text": "def assert_any_call(self, *args, **kwargs):\n        \"\"\"assert the mock has been called with the specified arguments.\n\n        The assert passes if the mock has *ever* been called, unlike\n        `assert_called_with` and `assert_called_once_with` that only pass if\n        the call is the most recent one.\"\"\"\n        kall = call(*args, **kwargs)\n        if kall not in self.call_args_list:\n            expected_string = self._format_mock_call_signature(args, kwargs)\n            raise AssertionError(\n                '%s call not found' % expected_string\n            )", "title": ""}
{"_id": "d8395", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d8396", "text": "def column_exists(cr, table, column):\n    \"\"\" Check whether a certain column exists \"\"\"\n    cr.execute(\n        'SELECT count(attname) FROM pg_attribute '\n        'WHERE attrelid = '\n        '( SELECT oid FROM pg_class WHERE relname = %s ) '\n        'AND attname = %s',\n        (table, column))\n    return cr.fetchone()[0] == 1", "title": ""}
{"_id": "d8397", "text": "def unique(iterable):\n    \"\"\" Returns a list copy in which each item occurs only once (in-order).\n    \"\"\"\n    seen = set()\n    return [x for x in iterable if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d8398", "text": "def is_json_file(filename, show_warnings = False):\n    \"\"\"Check configuration file type is JSON\n    Return a boolean indicating wheather the file is JSON format or not\n    \"\"\"\n    try:\n        config_dict = load_config(filename, file_type = \"json\")\n        is_json = True\n    except:\n        is_json = False\n    return(is_json)", "title": ""}
{"_id": "d8399", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d8400", "text": "def set_locale(request):\n    \"\"\"Return locale from GET lang param or automatically.\"\"\"\n    return request.query.get('lang', app.ps.babel.select_locale_by_request(request))", "title": ""}
{"_id": "d8401", "text": "def isnamedtuple(obj):\n    \"\"\"Heuristic check if an object is a namedtuple.\"\"\"\n    return isinstance(obj, tuple) \\\n           and hasattr(obj, \"_fields\") \\\n           and hasattr(obj, \"_asdict\") \\\n           and callable(obj._asdict)", "title": ""}
{"_id": "d8402", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d8403", "text": "def getConnectionStats(self):\n        \"\"\"Returns dictionary with number of connections for each database.\n        \n        @return: Dictionary of database connection statistics.\n        \n        \"\"\"\n        cur = self._conn.cursor()\n        cur.execute(\"\"\"SELECT datname,numbackends FROM pg_stat_database;\"\"\")\n        rows = cur.fetchall()\n        if rows:\n            return dict(rows)\n        else:\n            return {}", "title": ""}
{"_id": "d8404", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d8405", "text": "def _check_model(obj, models=None):\n    \"\"\"Checks object if it's a peewee model and unique.\"\"\"\n    return isinstance(obj, type) and issubclass(obj, pw.Model) and hasattr(obj, '_meta')", "title": ""}
{"_id": "d8406", "text": "def setVolume(self, volume):\n        \"\"\"Changes volume\"\"\"\n        val = float(val)\n        cmd = \"volume %s\" % val\n        self._execute(cmd)", "title": ""}
{"_id": "d8407", "text": "def get_file_size(filename):\n    \"\"\"\n    Get the file size of a given file\n\n    :param filename: string: pathname of a file\n    :return: human readable filesize\n    \"\"\"\n    if os.path.isfile(filename):\n        return convert_size(os.path.getsize(filename))\n    return None", "title": ""}
{"_id": "d8408", "text": "def pool_args(function, sequence, kwargs):\n    \"\"\"Return a single iterator of n elements of lists of length 3, given a sequence of len n.\"\"\"\n    return zip(itertools.repeat(function), sequence, itertools.repeat(kwargs))", "title": ""}
{"_id": "d8409", "text": "def stdin_readable():\n    \"\"\"Determine whether stdin has any data to read.\"\"\"\n    if not WINDOWS:\n        try:\n            return bool(select([sys.stdin], [], [], 0)[0])\n        except Exception:\n            logger.log_exc()\n    try:\n        return not sys.stdin.isatty()\n    except Exception:\n        logger.log_exc()\n    return False", "title": ""}
{"_id": "d8410", "text": "def serve_dtool_directory(directory, port):\n    \"\"\"Serve the datasets in a directory over HTTP.\"\"\"\n    os.chdir(directory)\n    server_address = (\"localhost\", port)\n    httpd = DtoolHTTPServer(server_address, DtoolHTTPRequestHandler)\n    httpd.serve_forever()", "title": ""}
{"_id": "d8411", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d8412", "text": "def calculate_month(birth_date):\n    \"\"\"\n    Calculates and returns a month number basing on PESEL standard.\n    \"\"\"\n    year = int(birth_date.strftime('%Y'))\n    month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20\n\n    return month", "title": ""}
{"_id": "d8413", "text": "def is_valid_variable_name(string_to_check):\n    \"\"\"\n    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\n    \"\"\"\n\n    try:\n\n        parse('{} = None'.format(string_to_check))\n        return True\n\n    except (SyntaxError, ValueError, TypeError):\n\n        return False", "title": ""}
{"_id": "d8414", "text": "def is_file(path):\n    \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n    try:\n        return path.expanduser().absolute().is_file()\n    except AttributeError:\n        return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))", "title": ""}
{"_id": "d8415", "text": "def get_last_week_range(weekday_start=\"Sunday\"):\n    \"\"\" Gets the date for the first and the last day of the previous complete week.\n\n    :param weekday_start: Either \"Monday\" or \"Sunday\", indicating the first day of the week.\n    :returns: A tuple containing two date objects, for the first and the last day of the week\n              respectively.\n    \"\"\"\n    today = date.today()\n    # Get the first day of the past complete week.\n    start_of_week = snap_to_beginning_of_week(today, weekday_start) - timedelta(weeks=1)\n    end_of_week = start_of_week + timedelta(days=6)\n    return (start_of_week, end_of_week)", "title": ""}
{"_id": "d8416", "text": "def __check_success(resp):\n        \"\"\" Check a JSON server response to see if it was successful\n\n        :type resp: Dictionary (parsed JSON from response)\n        :param resp: the response string\n\n        :rtype: String\n        :returns: the success message, if it exists\n\n        :raises: APIError if the success message is not present\n\n\n        \"\"\"\n\n        if \"success\" not in resp.keys():\n            try:\n                raise APIError('200', 'Operation Failed', resp[\"error\"])\n            except KeyError:\n                raise APIError('200', 'Operation Failed', str(resp))\n        return resp[\"success\"]", "title": ""}
{"_id": "d8417", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d8418", "text": "def is_readable_dir(path):\n  \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n  return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d8419", "text": "def s3_connect(bucket_name, s3_access_key_id, s3_secret_key):\n    \"\"\" Returns a Boto connection to the provided S3 bucket. \"\"\"\n    conn = connect_s3(s3_access_key_id, s3_secret_key)\n    try:\n        return conn.get_bucket(bucket_name)\n    except S3ResponseError as e:\n        if e.status == 403:\n            raise Exception(\"Bad Amazon S3 credentials.\")\n        raise", "title": ""}
{"_id": "d8420", "text": "def _validate_pos(df):\n    \"\"\"Validates the returned positional object\n    \"\"\"\n    assert isinstance(df, pd.DataFrame)\n    assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n    assert df.position.dtype == np.dtype(\"int64\")\n    assert df.strand.dtype == np.dtype(\"O\")\n    assert df.seqname.dtype == np.dtype(\"O\")\n    return df", "title": ""}
{"_id": "d8421", "text": "def GeneratePassphrase(length=20):\n  \"\"\"Create a 20 char passphrase with easily typeable chars.\"\"\"\n  valid_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  valid_chars += \"0123456789 ,-_&$#\"\n  return \"\".join(random.choice(valid_chars) for i in range(length))", "title": ""}
{"_id": "d8422", "text": "def chmod(f):\n    \"\"\" change mod to writeable \"\"\"\n    try:\n        os.chmod(f, S_IWRITE)  # windows (cover all)\n    except Exception as e:\n        pass\n    try:\n        os.chmod(f, 0o777)  # *nix\n    except Exception as e:\n        pass", "title": ""}
{"_id": "d8423", "text": "def short_action_string(self):\n        \"\"\"\n        Returns string with actor and verb, allowing target/object\n        to be filled in manually.\n\n        Example:\n        [actor] [verb] or\n        \"Joe cool posted a comment\"\n        \"\"\"\n        output = \"{0} \".format(self.actor)\n        if self.override_string:\n            output += self.override_string\n        else:\n            output += self.verb\n        return output", "title": ""}
{"_id": "d8424", "text": "def full(self):\n        \"\"\"Return True if the queue is full\"\"\"\n        if not self.size: return False\n        return len(self.pq) == (self.size + self.removed_count)", "title": ""}
{"_id": "d8425", "text": "def to_gtp(coord):\n    \"\"\"Converts from a Minigo coordinate to a GTP coordinate.\"\"\"\n    if coord is None:\n        return 'pass'\n    y, x = coord\n    return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)", "title": ""}
{"_id": "d8426", "text": "def _check_fields(self, x, y):\n\t\t\"\"\"\n\t\tCheck x and y fields parameters and initialize\n\t\t\"\"\"\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", "title": ""}
{"_id": "d8427", "text": "def colorize(string, color, *args, **kwargs):\n    \"\"\"\n    Implements string formatting along with color specified in colorama.Fore\n    \"\"\"\n    string = string.format(*args, **kwargs)\n    return color + string + colorama.Fore.RESET", "title": ""}
{"_id": "d8428", "text": "def get(s, delimiter='', format=\"diacritical\"):\n    \"\"\"Return pinyin of string, the string must be unicode\n    \"\"\"\n    return delimiter.join(_pinyin_generator(u(s), format=format))", "title": ""}
{"_id": "d8429", "text": "def _trace_full (frame, event, arg):\n    \"\"\"Trace every executed line.\"\"\"\n    if event == \"line\":\n        _trace_line(frame, event, arg)\n    else:\n        _trace(frame, event, arg)\n    return _trace_full", "title": ""}
{"_id": "d8430", "text": "def _remove_empty_items(d, required):\n  \"\"\"Return a new dict with any empty items removed.\n\n  Note that this is not a deep check. If d contains a dictionary which\n  itself contains empty items, those are never checked.\n\n  This method exists to make to_serializable() functions cleaner.\n  We could revisit this some day, but for now, the serialized objects are\n  stripped of empty values to keep the output YAML more compact.\n\n  Args:\n    d: a dictionary\n    required: list of required keys (for example, TaskDescriptors always emit\n      the \"task-id\", even if None)\n\n  Returns:\n    A dictionary with empty items removed.\n  \"\"\"\n\n  new_dict = {}\n  for k, v in d.items():\n    if k in required:\n      new_dict[k] = v\n    elif isinstance(v, int) or v:\n      # \"if v\" would suppress emitting int(0)\n      new_dict[k] = v\n\n  return new_dict", "title": ""}
{"_id": "d8431", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d8432", "text": "def previous_key(tuple_of_tuples, key):\n    \"\"\"Returns the key which comes before the give key.\n\n    It Processes a tuple of 2-element tuples and returns the key which comes\n    before the given key.\n    \"\"\"\n    for i, t in enumerate(tuple_of_tuples):\n        if t[0] == key:\n            try:\n                return tuple_of_tuples[i - 1][0]\n            except IndexError:\n                return None", "title": ""}
{"_id": "d8433", "text": "def home():\n    \"\"\"Temporary helper function to link to the API routes\"\"\"\n    return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \\\n        HTTPStatus.OK", "title": ""}
{"_id": "d8434", "text": "def locate(command, on):\n    \"\"\"Locate the command's man page.\"\"\"\n    location = find_page_location(command, on)\n    click.echo(location)", "title": ""}
{"_id": "d8435", "text": "def validate(raw_schema, target=None, **kwargs):\n    \"\"\"\n    Given the python representation of a JSONschema as defined in the swagger\n    spec, validate that the schema complies to spec.  If `target` is provided,\n    that target will be validated against the provided schema.\n    \"\"\"\n    schema = schema_validator(raw_schema, **kwargs)\n    if target is not None:\n        validate_object(target, schema=schema, **kwargs)", "title": ""}
{"_id": "d8436", "text": "def locate(command, on):\n    \"\"\"Locate the command's man page.\"\"\"\n    location = find_page_location(command, on)\n    click.echo(location)", "title": ""}
{"_id": "d8437", "text": "def translation(language):\n    \"\"\"\n    Return a translation object in the default 'django' domain.\n    \"\"\"\n    global _translations\n    if language not in _translations:\n        _translations[language] = Translations(language)\n    return _translations[language]", "title": ""}
{"_id": "d8438", "text": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "title": ""}
{"_id": "d8439", "text": "def _convert_date_to_dict(field_date):\n        \"\"\"\n        Convert native python ``datetime.date`` object  to a format supported by the API\n        \"\"\"\n        return {DAY: field_date.day, MONTH: field_date.month, YEAR: field_date.year}", "title": ""}
{"_id": "d8440", "text": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "title": ""}
{"_id": "d8441", "text": "def get_common_elements(list1, list2):\n    \"\"\"find the common elements in two lists.  used to support auto align\n        might be faster with sets\n\n    Parameters\n    ----------\n    list1 : list\n        a list of objects\n    list2 : list\n        a list of objects\n\n    Returns\n    -------\n    list : list\n        list of common objects shared by list1 and list2\n        \n    \"\"\"\n    #result = []\n    #for item in list1:\n    #    if item in list2:\n    #        result.append(item)\n    #Return list(set(list1).intersection(set(list2)))\n    set2 = set(list2)\n    result = [item for item in list1 if item in set2]\n    return result", "title": ""}
{"_id": "d8442", "text": "def socket_close(self):\n        \"\"\"Close our socket.\"\"\"\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET", "title": ""}
{"_id": "d8443", "text": "def mouse_out(self):\n        \"\"\"\n        Performs a mouse out the element.\n\n        Currently works only on Chrome driver.\n        \"\"\"\n        self.scroll_to()\n        ActionChains(self.parent.driver).move_by_offset(0, 0).click().perform()", "title": ""}
{"_id": "d8444", "text": "def cancel(self, event=None):\n        \"\"\"Function called when Cancel-button clicked.\n\n        This method returns focus to parent, and destroys the dialog.\n        \"\"\"\n\n        if self.parent != None:\n            self.parent.focus_set()\n\n        self.destroy()", "title": ""}
{"_id": "d8445", "text": "def on_close(self, ws):\n        \"\"\" Called when websocket connection is closed\n        \"\"\"\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()", "title": ""}
{"_id": "d8446", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d8447", "text": "def _cal_dist2center(X, center):\n    \"\"\" Calculate the SSE to the cluster center\n    \"\"\"\n    dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')\n    return(np.sum(dmemb2cen))", "title": ""}
{"_id": "d8448", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d8449", "text": "def gaussian_variogram_model(m, d):\n    \"\"\"Gaussian model, m is [psill, range, nugget]\"\"\"\n    psill = float(m[0])\n    range_ = float(m[1])\n    nugget = float(m[2])\n    return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget", "title": ""}
{"_id": "d8450", "text": "def md_to_text(content):\n    \"\"\" Converts markdown content to text \"\"\"\n    text = None\n    html = markdown.markdown(content)\n    if html:\n        text = html_to_text(content)\n    return text", "title": ""}
{"_id": "d8451", "text": "def query_collision(collision_object):\n        \"\"\"\n        Check to see if the specified object is colliding with any of the objects currently in the Collision Manager\n        Returns the first object we are colliding with if there was a collision and None if no collisions was found\n        \"\"\"\n        global collidable_objects\n        # Note that we use a Brute Force approach for the time being.\n        # It performs horribly under heavy loads, but it meets\n        # our needs for the time being.\n        for obj in collidable_objects:\n            # Make sure we don't check ourself against ourself.\n            if obj.obj_id is not collision_object.obj_id:\n                if collision_object.is_colliding(obj):\n                    # A collision has been detected. Return the object that we are colliding with.\n                    return obj\n\n        # No collision was noticed. Return None.\n        return None", "title": ""}
{"_id": "d8452", "text": "def wrap(string, length, indent):\n    \"\"\" Wrap a string at a line length \"\"\"\n    newline = \"\\n\" + \" \" * indent\n    return newline.join((string[i : i + length] for i in range(0, len(string), length)))", "title": ""}
{"_id": "d8453", "text": "def _loadfilepath(self, filepath, **kwargs):\n        \"\"\"This loads a geojson file into a geojson python\n        dictionary using the json module.\n        \n        Note: to load with a different text encoding use the encoding argument.\n        \"\"\"\n        with open(filepath, \"r\") as f:\n            data = json.load(f, **kwargs)\n        return data", "title": ""}
{"_id": "d8454", "text": "def stop(pid):\n    \"\"\"Shut down a specific process.\n\n    Args:\n      pid: the pid of the process to shutdown.\n    \"\"\"\n    if psutil.pid_exists(pid):\n      try:\n        p = psutil.Process(pid)\n        p.kill()\n      except Exception:\n        pass", "title": ""}
{"_id": "d8455", "text": "def has_edit_permission(self, request):\n        \"\"\" Can edit this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "title": ""}
{"_id": "d8456", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d8457", "text": "def println(msg):\n    \"\"\"\n    Convenience function to print messages on a single line in the terminal\n    \"\"\"\n    sys.stdout.write(msg)\n    sys.stdout.flush()\n    sys.stdout.write('\\x08' * len(msg))\n    sys.stdout.flush()", "title": ""}
{"_id": "d8458", "text": "def disable_wx(self):\n        \"\"\"Disable event loop integration with wxPython.\n\n        This merely sets PyOS_InputHook to NULL.\n        \"\"\"\n        if self._apps.has_key(GUI_WX):\n            self._apps[GUI_WX]._in_event_loop = False\n        self.clear_inputhook()", "title": ""}
{"_id": "d8459", "text": "def comma_converter(float_string):\n    \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n    trans_table = maketrans(b',', b'.')\n    return float(float_string.translate(trans_table))", "title": ""}
{"_id": "d8460", "text": "def on_close(self, evt):\n    \"\"\"\n    Pop-up menu and wx.EVT_CLOSE closing event\n    \"\"\"\n    self.stop() # DoseWatcher\n    if evt.EventObject is not self: # Avoid deadlocks\n      self.Close() # wx.Frame\n    evt.Skip()", "title": ""}
{"_id": "d8461", "text": "def print_env_info(key, out=sys.stderr):\n    \"\"\"If given environment key is defined, print it out.\"\"\"\n    value = os.getenv(key)\n    if value is not None:\n        print(key, \"=\", repr(value), file=out)", "title": ""}
{"_id": "d8462", "text": "def set_icon(self, bmp):\n        \"\"\"Sets main window icon to given wx.Bitmap\"\"\"\n\n        _icon = wx.EmptyIcon()\n        _icon.CopyFromBitmap(bmp)\n        self.SetIcon(_icon)", "title": ""}
{"_id": "d8463", "text": "def reprkwargs(kwargs, sep=', ', fmt=\"{0!s}={1!r}\"):\n    \"\"\"Display kwargs.\"\"\"\n    return sep.join(fmt.format(k, v) for k, v in kwargs.iteritems())", "title": ""}
{"_id": "d8464", "text": "def disable_wx(self):\n        \"\"\"Disable event loop integration with wxPython.\n\n        This merely sets PyOS_InputHook to NULL.\n        \"\"\"\n        if self._apps.has_key(GUI_WX):\n            self._apps[GUI_WX]._in_event_loop = False\n        self.clear_inputhook()", "title": ""}
{"_id": "d8465", "text": "def _stop_instance(self):\n        \"\"\"Stop the instance.\"\"\"\n        instance = self._get_instance()\n        instance.stop()\n        self._wait_on_instance('stopped', self.timeout)", "title": ""}
{"_id": "d8466", "text": "def _update_bordercolor(self, bordercolor):\n        \"\"\"Updates background color\"\"\"\n\n        border_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVEBORDER)\n        border_color.SetRGB(bordercolor)\n\n        self.linecolor_choice.SetColour(border_color)", "title": ""}
{"_id": "d8467", "text": "def validate_email(email):\n    \"\"\"\n    Validates an email address\n    Source: Himanshu Shankar (https://github.com/iamhssingh)\n    Parameters\n    ----------\n    email: str\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    from django.core.validators import validate_email\n    from django.core.exceptions import ValidationError\n    try:\n        validate_email(email)\n        return True\n    except ValidationError:\n        return False", "title": ""}
{"_id": "d8468", "text": "def _update_fontcolor(self, fontcolor):\n        \"\"\"Updates text font color button\n\n        Parameters\n        ----------\n\n        fontcolor: Integer\n        \\tText color in integer RGB format\n\n        \"\"\"\n\n        textcolor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n        textcolor.SetRGB(fontcolor)\n\n        self.textcolor_choice.SetColour(textcolor)", "title": ""}
{"_id": "d8469", "text": "def get_codeblock(language, text):\n    \"\"\" Generates rst codeblock for given text and language \"\"\"\n    rst = \"\\n\\n.. code-block:: \" + language + \"\\n\\n\"\n    for line in text.splitlines():\n        rst += \"\\t\" + line + \"\\n\"\n\n    rst += \"\\n\"\n    return rst", "title": ""}
{"_id": "d8470", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d8471", "text": "def format(x, format):\n    \"\"\"Uses http://www.cplusplus.com/reference/string/to_string/ for formatting\"\"\"\n    # don't change the dtype, otherwise for each block the dtype may be different (string length)\n    sl = vaex.strings.format(x, format)\n    return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)", "title": ""}
{"_id": "d8472", "text": "def xor(a, b):\n        \"\"\"Bitwise xor on equal length bytearrays.\"\"\"\n        return bytearray(i ^ j for i, j in zip(a, b))", "title": ""}
{"_id": "d8473", "text": "def isetdiff_flags(list1, list2):\n    \"\"\"\n    move to util_iter\n    \"\"\"\n    set2 = set(list2)\n    return (item not in set2 for item in list1)", "title": ""}
{"_id": "d8474", "text": "def _extract_node_text(node):\n    \"\"\"Extract text from a given lxml node.\"\"\"\n\n    texts = map(\n        six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n    )\n    return \" \".join(text for text in texts if text)", "title": ""}
{"_id": "d8475", "text": "def is_same_file (filename1, filename2):\n    \"\"\"Check if filename1 and filename2 point to the same file object.\n    There can be false negatives, ie. the result is False, but it is\n    the same file anyway. Reason is that network filesystems can create\n    different paths to the same physical file.\n    \"\"\"\n    if filename1 == filename2:\n        return True\n    if os.name == 'posix':\n        return os.path.samefile(filename1, filename2)\n    return is_same_filename(filename1, filename2)", "title": ""}
{"_id": "d8476", "text": "def getYamlDocument(filePath):\n    \"\"\"\n    Return a yaml file's contents as a dictionary\n    \"\"\"\n    with open(filePath) as stream:\n        doc = yaml.load(stream)\n        return doc", "title": ""}
{"_id": "d8477", "text": "def allclose(a, b):\n    \"\"\"\n    Test that a and b are close and match in shape.\n\n    Parameters\n    ----------\n    a : ndarray\n        First array to check\n\n    b : ndarray\n        First array to check\n    \"\"\"\n    from numpy import allclose\n    return (a.shape == b.shape) and allclose(a, b)", "title": ""}
{"_id": "d8478", "text": "def _ParseYamlFromFile(filedesc):\n  \"\"\"Parses given YAML file.\"\"\"\n  content = filedesc.read()\n  return yaml.Parse(content) or collections.OrderedDict()", "title": ""}
{"_id": "d8479", "text": "def compare(string1, string2):\n    \"\"\"Compare two strings while protecting against timing attacks\n\n    :param str string1: the first string\n    :param str string2: the second string\n\n    :returns: True if the strings are equal, False if not\n    :rtype: :obj:`bool`\n    \"\"\"\n    if len(string1) != len(string2):\n        return False\n    result = True\n    for c1, c2 in izip(string1, string2):\n        result &= c1 == c2\n    return result", "title": ""}
{"_id": "d8480", "text": "def prox_zero(X, step):\n    \"\"\"Proximal operator to project onto zero\n    \"\"\"\n    return np.zeros(X.shape, dtype=X.dtype)", "title": ""}
{"_id": "d8481", "text": "def compare(string1, string2):\n    \"\"\"Compare two strings while protecting against timing attacks\n\n    :param str string1: the first string\n    :param str string2: the second string\n\n    :returns: True if the strings are equal, False if not\n    :rtype: :obj:`bool`\n    \"\"\"\n    if len(string1) != len(string2):\n        return False\n    result = True\n    for c1, c2 in izip(string1, string2):\n        result &= c1 == c2\n    return result", "title": ""}
{"_id": "d8482", "text": "def are_equal_xml(a_xml, b_xml):\n    \"\"\"Normalize and compare XML documents for equality. The document may or may not be\n    a DataONE type.\n\n    Args:\n      a_xml: str\n      b_xml: str\n        XML documents to compare for equality.\n\n    Returns:\n      bool: ``True`` if the XML documents are semantically equivalent.\n\n    \"\"\"\n    a_dom = xml.dom.minidom.parseString(a_xml)\n    b_dom = xml.dom.minidom.parseString(b_xml)\n    return are_equal_elements(a_dom.documentElement, b_dom.documentElement)", "title": ""}
{"_id": "d8483", "text": "def register():\n    \"\"\"\n    Calls the shots, based on signals\n    \"\"\"\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)", "title": ""}
{"_id": "d8484", "text": "def compare(string1, string2):\n    \"\"\"Compare two strings while protecting against timing attacks\n\n    :param str string1: the first string\n    :param str string2: the second string\n\n    :returns: True if the strings are equal, False if not\n    :rtype: :obj:`bool`\n    \"\"\"\n    if len(string1) != len(string2):\n        return False\n    result = True\n    for c1, c2 in izip(string1, string2):\n        result &= c1 == c2\n    return result", "title": ""}
{"_id": "d8485", "text": "def quit(self):\n        \"\"\"\n        Closes the browser and shuts down the WebKitGTKDriver executable\n        that is started when starting the WebKitGTKDriver\n        \"\"\"\n        try:\n            RemoteWebDriver.quit(self)\n        except http_client.BadStatusLine:\n            pass\n        finally:\n            self.service.stop()", "title": ""}
{"_id": "d8486", "text": "def valid_uuid(value):\n    \"\"\" Check if value is a valid UUID. \"\"\"\n\n    try:\n        uuid.UUID(value, version=4)\n        return True\n    except (TypeError, ValueError, AttributeError):\n        return False", "title": ""}
{"_id": "d8487", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d8488", "text": "def is_type(value):\n        \"\"\"Determine if value is an instance or subclass of the class Type.\"\"\"\n        if isinstance(value, type):\n            return issubclass(value, Type)\n        return isinstance(value, Type)", "title": ""}
{"_id": "d8489", "text": "def askopenfilename(**kwargs):\n    \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n    try:\n        from Tkinter import Tk\n        import tkFileDialog as filedialog\n    except ImportError:\n        from tkinter import Tk, filedialog\n    root = Tk()\n    root.withdraw()\n    root.update()\n    filenames = filedialog.askopenfilename(**kwargs)\n    root.destroy()\n    return filenames", "title": ""}
{"_id": "d8490", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d8491", "text": "def to_str(s):\n    \"\"\"\n    Convert bytes and non-string into Python 3 str\n    \"\"\"\n    if isinstance(s, bytes):\n        s = s.decode('utf-8')\n    elif not isinstance(s, str):\n        s = str(s)\n    return s", "title": ""}
{"_id": "d8492", "text": "def shannon_entropy(p):\n    \"\"\"Calculates shannon entropy in bits.\n\n    Parameters\n    ----------\n    p : np.array\n        array of probabilities\n\n    Returns\n    -------\n    shannon entropy in bits\n    \"\"\"\n    return -np.sum(np.where(p!=0, p * np.log2(p), 0))", "title": ""}
{"_id": "d8493", "text": "def sort_fn_list(fn_list):\n    \"\"\"Sort input filename list by datetime\n    \"\"\"\n    dt_list = get_dt_list(fn_list)\n    fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]\n    return fn_list_sort", "title": ""}
{"_id": "d8494", "text": "def _concatenate_virtual_arrays(arrs, cols=None, scaling=None):\n    \"\"\"Return a virtual concatenate of several NumPy arrays.\"\"\"\n    return None if not len(arrs) else ConcatenatedArrays(arrs, cols,\n                                                         scaling=scaling)", "title": ""}
{"_id": "d8495", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d8496", "text": "def update(packages, env=None, user=None):\n    \"\"\"\n    Update conda packages in a conda env\n\n    Attributes\n    ----------\n        packages: list of packages comma delimited\n    \"\"\"\n    packages = ' '.join(packages.split(','))\n    cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user)\n    return _execcmd(cmd, user=user)", "title": ""}
{"_id": "d8497", "text": "def yum_install(self, packages, ignore_error=False):\n        \"\"\"Install some packages on the remote host.\n\n        :param packages: ist of packages to install.\n        \"\"\"\n        return self.run('yum install -y --quiet ' + ' '.join(packages), ignore_error=ignore_error, retry=5)", "title": ""}
{"_id": "d8498", "text": "def config_parser_to_dict(config_parser):\n    \"\"\"\n    Convert a ConfigParser to a dictionary.\n    \"\"\"\n    response = {}\n\n    for section in config_parser.sections():\n        for option in config_parser.options(section):\n            response.setdefault(section, {})[option] = config_parser.get(section, option)\n\n    return response", "title": ""}
{"_id": "d8499", "text": "def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE,\ncontent=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for forbidden access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=403)", "title": ""}
{"_id": "d8500", "text": "def items(self, section_name):\n        \"\"\":return: list((option, value), ...) pairs of all items in the given section\"\"\"\n        return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']", "title": ""}
{"_id": "d8501", "text": "def version_jar(self):\n\t\t\"\"\"\n\t\tSpecial case of version() when the executable is a JAR file.\n\t\t\"\"\"\n\t\tcmd = config.get_command('java')\n\t\tcmd.append('-jar')\n\t\tcmd += self.cmd\n\t\tself.version(cmd=cmd, path=self.cmd[0])", "title": ""}
{"_id": "d8502", "text": "def _is_already_configured(configuration_details):\n    \"\"\"Returns `True` when alias already in shell config.\"\"\"\n    path = Path(configuration_details.path).expanduser()\n    with path.open('r') as shell_config:\n        return configuration_details.content in shell_config.read()", "title": ""}
{"_id": "d8503", "text": "def get_month_start_end_day():\n    \"\"\"\n    Get the month start date a nd end date\n    \"\"\"\n    t = date.today()\n    n = mdays[t.month]\n    return (date(t.year, t.month, 1), date(t.year, t.month, n))", "title": ""}
{"_id": "d8504", "text": "def pass_from_pipe(cls):\n        \"\"\"Return password from pipe if not on TTY, else False.\n        \"\"\"\n        is_pipe = not sys.stdin.isatty()\n        return is_pipe and cls.strip_last_newline(sys.stdin.read())", "title": ""}
{"_id": "d8505", "text": "def count(lines):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  words = [w for l in lines for w in l.strip().split()]\n  return Counter(words)", "title": ""}
{"_id": "d8506", "text": "def as_list(callable):\n    \"\"\"Convert a scalar validator in a list validator\"\"\"\n    @wraps(callable)\n    def wrapper(value_iter):\n        return [callable(value) for value in value_iter]\n\n    return wrapper", "title": ""}
{"_id": "d8507", "text": "def top(n, width=WIDTH, style=STYLE):\n    \"\"\"Prints the top row of a table\"\"\"\n    return hrule(n, width, linestyle=STYLES[style].top)", "title": ""}
{"_id": "d8508", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d8509", "text": "def get_from_human_key(self, key):\n        \"\"\"Return the key (aka database value) of a human key (aka Python identifier).\"\"\"\n        if key in self._identifier_map:\n            return self._identifier_map[key]\n        raise KeyError(key)", "title": ""}
{"_id": "d8510", "text": "def obj_to_string(obj, top=True):\n    \"\"\"\n    Turn an arbitrary object into a unicode string. If complex (dict/list/tuple), will be json-encoded.\n    \"\"\"\n    obj = prepare_for_json_encoding(obj)\n    if type(obj) == six.text_type:\n        return obj\n    return json.dumps(obj)", "title": ""}
{"_id": "d8511", "text": "def get_oauth_token():\n    \"\"\"Retrieve a simple OAuth Token for use with the local http client.\"\"\"\n    url = \"{0}/token\".format(DEFAULT_ORIGIN[\"Origin\"])\n    r = s.get(url=url)\n    return r.json()[\"t\"]", "title": ""}
{"_id": "d8512", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d8513", "text": "def typename(obj):\n    \"\"\"Returns the type of obj as a string. More descriptive and specific than\n    type(obj), and safe for any object, unlike __class__.\"\"\"\n    if hasattr(obj, '__class__'):\n        return getattr(obj, '__class__').__name__\n    else:\n        return type(obj).__name__", "title": ""}
{"_id": "d8514", "text": "def unit_ball_L2(shape):\n  \"\"\"A tensorflow variable tranfomed to be constrained in a L2 unit ball.\n\n  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n  they are strong attacks. We are not yet confident in this code.\n  \"\"\"\n  x = tf.Variable(tf.zeros(shape))\n  return constrain_L2(x)", "title": ""}
{"_id": "d8515", "text": "def _get_session():\n    \"\"\"Return (and memoize) a database session\"\"\"\n    session = getattr(g, '_session', None)\n    if session is None:\n        session = g._session = db.session()\n    return session", "title": ""}
{"_id": "d8516", "text": "def comma_delimited_to_list(list_param):\n    \"\"\"Convert comma-delimited list / string into a list of strings\n\n    :param list_param: Comma-delimited string\n    :type list_param: str | unicode\n    :return: A list of strings\n    :rtype: list\n    \"\"\"\n    if isinstance(list_param, list):\n        return list_param\n    if isinstance(list_param, str):\n        return list_param.split(',')\n    else:\n        return []", "title": ""}
{"_id": "d8517", "text": "def _MakeExecutable(self, metadata_script):\n    \"\"\"Add executable permissions to a file.\n\n    Args:\n      metadata_script: string, the path to the executable file.\n    \"\"\"\n    mode = os.stat(metadata_script).st_mode\n    os.chmod(metadata_script, mode | stat.S_IEXEC)", "title": ""}
{"_id": "d8518", "text": "def circ_permutation(items):\n    \"\"\"Calculate the circular permutation for a given list of items.\"\"\"\n    permutations = []\n    for i in range(len(items)):\n        permutations.append(items[i:] + items[:i])\n    return permutations", "title": ""}
{"_id": "d8519", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d8520", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d8521", "text": "def fill_document(doc):\n    \"\"\"Add a section, a subsection and some text to the document.\n\n    :param doc: the document\n    :type doc: :class:`pylatex.document.Document` instance\n    \"\"\"\n    with doc.create(Section('A section')):\n        doc.append('Some regular text and some ')\n        doc.append(italic('italic text. '))\n\n        with doc.create(Subsection('A subsection')):\n            doc.append('Also some crazy characters: $&#{}')", "title": ""}
{"_id": "d8522", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d8523", "text": "def build_code(self, lang, body):\n        \"\"\"Wrap text with markdown specific flavour.\"\"\"\n        self.out.append(\"```\" + lang)\n        self.build_markdown(lang, body)\n        self.out.append(\"```\")", "title": ""}
{"_id": "d8524", "text": "def default_diff(latest_config, current_config):\n    \"\"\"Determine if two revisions have actually changed.\"\"\"\n    # Pop off the fields we don't care about:\n    pop_no_diff_fields(latest_config, current_config)\n\n    diff = DeepDiff(\n        latest_config,\n        current_config,\n        ignore_order=True\n    )\n    return diff", "title": ""}
{"_id": "d8525", "text": "def add_noise(Y, sigma):\n    \"\"\"Adds noise to Y\"\"\"\n    return Y + np.random.normal(0, sigma, Y.shape)", "title": ""}
{"_id": "d8526", "text": "def check_create_folder(filename):\n    \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n    os.makedirs(os.path.dirname(filename), exist_ok=True)", "title": ""}
{"_id": "d8527", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d8528", "text": "def from_json_str(cls, json_str):\n    \"\"\"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.\n    \"\"\"\n    return cls.from_json(json.loads(json_str, cls=JsonDecoder))", "title": ""}
{"_id": "d8529", "text": "def load_model_from_package(name, **overrides):\n    \"\"\"Load a model from an installed package.\"\"\"\n    cls = importlib.import_module(name)\n    return cls.load(**overrides)", "title": ""}
{"_id": "d8530", "text": "def save_image(pdf_path, img_path, page_num):\n    \"\"\"\n\n    Creates images for a page of the input pdf document and saves it\n    at img_path.\n\n    :param pdf_path: path to pdf to create images for.\n    :param img_path: path where to save the images.\n    :param page_num: page number to create image from in the pdf file.\n    :return:\n    \"\"\"\n    pdf_img = Image(filename=\"{}[{}]\".format(pdf_path, page_num))\n    with pdf_img.convert(\"png\") as converted:\n        # Set white background.\n        converted.background_color = Color(\"white\")\n        converted.alpha_channel = \"remove\"\n        converted.save(filename=img_path)", "title": ""}
{"_id": "d8531", "text": "def types(self):\n        \"\"\"\n        Return a list of all the variable types that exist in the\n        Variables object.\n        \"\"\"\n        output = set()\n        for var in self.values():\n            if var.has_value():\n                output.update(var.types())\n        return list(output)", "title": ""}
{"_id": "d8532", "text": "def index():\n    \"\"\" Display productpage with normal user and test user buttons\"\"\"\n    global productpage\n\n    table = json2html.convert(json = json.dumps(productpage),\n                              table_attributes=\"class=\\\"table table-condensed table-bordered table-hover\\\"\")\n\n    return render_template('index.html', serviceTable=table)", "title": ""}
{"_id": "d8533", "text": "def send_request(self, *args, **kwargs):\n        \"\"\"Wrapper for session.request\n        Handle connection reset error even from pyopenssl\n        \"\"\"\n        try:\n            return self.session.request(*args, **kwargs)\n        except ConnectionError:\n            self.session.close()\n            return self.session.request(*args, **kwargs)", "title": ""}
{"_id": "d8534", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d8535", "text": "def transformer_ae_a3():\n  \"\"\"Set of hyperparameters.\"\"\"\n  hparams = transformer_ae_base()\n  hparams.batch_size = 4096\n  hparams.layer_prepostprocess_dropout = 0.3\n  hparams.optimizer = \"Adafactor\"\n  hparams.learning_rate = 0.25\n  hparams.learning_rate_warmup_steps = 10000\n  return hparams", "title": ""}
{"_id": "d8536", "text": "def csv_to_dicts(file, header=None):\n    \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n    with open(file) as csvfile:\n        return [row for row in csv.DictReader(csvfile, fieldnames=header)]", "title": ""}
{"_id": "d8537", "text": "def vec_angle(a, b):\n    \"\"\"\n    Calculate angle between two vectors\n    \"\"\"\n    cosang = np.dot(a, b)\n    sinang = fast_norm(np.cross(a, b))\n    return np.arctan2(sinang, cosang)", "title": ""}
{"_id": "d8538", "text": "def _ram_buffer(self):\n        \"\"\"Setup the RAM buffer from the C++ code.\"\"\"\n        # get the address of the RAM\n        address = _LIB.Memory(self._env)\n        # create a buffer from the contents of the address location\n        buffer_ = ctypes.cast(address, ctypes.POINTER(RAM_VECTOR)).contents\n        # create a NumPy array from the buffer\n        return np.frombuffer(buffer_, dtype='uint8')", "title": ""}
{"_id": "d8539", "text": "def create_rot2d(angle):\n    \"\"\"Create 2D rotation matrix\"\"\"\n    ca = math.cos(angle)\n    sa = math.sin(angle)\n    return np.array([[ca, -sa], [sa, ca]])", "title": ""}
{"_id": "d8540", "text": "def _monitor_callback_wrapper(callback):\n    \"\"\"A wrapper for the user-defined handle.\"\"\"\n    def callback_handle(name, array, _):\n        \"\"\" ctypes function \"\"\"\n        callback(name, array)\n    return callback_handle", "title": ""}
{"_id": "d8541", "text": "def experiment_property(prop):\n    \"\"\"Get a property of the experiment by name.\"\"\"\n    exp = experiment(session)\n    p = getattr(exp, prop)\n    return success_response(field=prop, data=p, request_type=prop)", "title": ""}
{"_id": "d8542", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d8543", "text": "def cumsum(inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1, len(newlist)):\n        newlist[i] = newlist[i] + newlist[i - 1]\n    return newlist", "title": ""}
{"_id": "d8544", "text": "def mouse_out(self):\n        \"\"\"\n        Performs a mouse out the element.\n\n        Currently works only on Chrome driver.\n        \"\"\"\n        self.scroll_to()\n        ActionChains(self.parent.driver).move_by_offset(0, 0).click().perform()", "title": ""}
{"_id": "d8545", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d8546", "text": "def compose(*funcs):\n    \"\"\"compose a list of functions\"\"\"\n    return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)", "title": ""}
{"_id": "d8547", "text": "def downcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n    return [ tt.lower() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d8548", "text": "def transform(self, df):\n        \"\"\"\n        Transforms a DataFrame in place. Computes all outputs of the DataFrame.\n\n        Args:\n            df (pandas.DataFrame): DataFrame to transform.\n        \"\"\"\n        for name, function in self.outputs:\n            df[name] = function(df)", "title": ""}
{"_id": "d8549", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d8550", "text": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d8551", "text": "def hex_to_hsv(color):\n    \"\"\"\n    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')\n    \"\"\"\n    color = normalize(color)\n    color = color[1:]\n    # color=tuple(ord(c)/255.0 for c in color.decode('hex'))\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)", "title": ""}
{"_id": "d8552", "text": "def enbw(wnd):\n  \"\"\" Equivalent Noise Bandwidth in bins (Processing Gain reciprocal). \"\"\"\n  return sum(el ** 2 for el in wnd) / sum(wnd) ** 2 * len(wnd)", "title": ""}
{"_id": "d8553", "text": "def _join(verb):\n    \"\"\"\n    Join helper\n    \"\"\"\n    data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n    # Preserve x groups\n    if isinstance(verb.x, GroupedDataFrame):\n        data.plydata_groups = list(verb.x.plydata_groups)\n    return data", "title": ""}
{"_id": "d8554", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d8555", "text": "def sort_data(data, cols):\n    \"\"\"Sort `data` rows and order columns\"\"\"\n    return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "title": ""}
{"_id": "d8556", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d8557", "text": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "title": ""}
{"_id": "d8558", "text": "def adapt_array(arr):\n    \"\"\"\n    Adapts a Numpy array into an ARRAY string to put into the database.\n\n    Parameters\n    ----------\n    arr: array\n        The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n    Returns\n    -------\n    ARRAY\n            The adapted array object\n\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr), out.seek(0)\n    return buffer(out.read())", "title": ""}
{"_id": "d8559", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d8560", "text": "def __init__(self, collection, index_type_obj):\n        \"\"\"\n            Constructs wrapper for general index creation and deletion\n\n            :param collection Collection\n            :param index_type_obj BaseIndex Object of a index sub-class\n        \"\"\"\n\n        self.collection = collection\n        self.index_type_obj = index_type_obj", "title": ""}
{"_id": "d8561", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d8562", "text": "def setup(app):\n    \"\"\"Allow this package to be used as Sphinx extension.\n    This is also called from the top-level ``__init__.py``.\n\n    :type app: sphinx.application.Sphinx\n    \"\"\"\n    from .patches import patch_django_for_autodoc\n\n    # When running, make sure Django doesn't execute querysets\n    patch_django_for_autodoc()\n\n    # Generate docstrings for Django model fields\n    # Register the docstring processor with sphinx\n    app.connect('autodoc-process-docstring', improve_model_docstring)\n\n    # influence skip rules\n    app.connect(\"autodoc-skip-member\", autodoc_skip)", "title": ""}
{"_id": "d8563", "text": "def _possibly_convert_objects(values):\n    \"\"\"Convert arrays of datetime.datetime and datetime.timedelta objects into\n    datetime64 and timedelta64, according to the pandas convention.\n    \"\"\"\n    return np.asarray(pd.Series(values.ravel())).reshape(values.shape)", "title": ""}
{"_id": "d8564", "text": "def get_ctype(rtype, cfunc, *args):\n    \"\"\" 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\n    \"\"\"\n    val_p = backend.ffi.new(rtype)\n    args = args + (val_p,)\n    cfunc(*args)\n    return val_p[0]", "title": ""}
{"_id": "d8565", "text": "def convertDatetime(t):\n    \"\"\"\n    Converts the specified datetime object into its appropriate protocol\n    value. This is the number of milliseconds from the epoch.\n    \"\"\"\n    epoch = datetime.datetime.utcfromtimestamp(0)\n    delta = t - epoch\n    millis = delta.total_seconds() * 1000\n    return int(millis)", "title": ""}
{"_id": "d8566", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d8567", "text": "def timestamp_to_datetime(timestamp):\n    \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n    from datetime import datetime, timedelta\n    obj = datetime.fromtimestamp(timestamp[0])\n    return obj + timedelta(microseconds=int(timestamp[1]))", "title": ""}
{"_id": "d8568", "text": "def lambda_from_file(python_file):\n    \"\"\"\n    Reads a python file and returns a awslambda.Code object\n    :param python_file:\n    :return:\n    \"\"\"\n    lambda_function = []\n    with open(python_file, 'r') as f:\n        lambda_function.extend(f.read().splitlines())\n\n    return awslambda.Code(ZipFile=(Join('\\n', lambda_function)))", "title": ""}
{"_id": "d8569", "text": "def datetime_to_ms(dt):\n    \"\"\"\n    Converts a datetime to a millisecond accuracy timestamp\n    \"\"\"\n    seconds = calendar.timegm(dt.utctimetuple())\n    return seconds * 1000 + int(dt.microsecond / 1000)", "title": ""}
{"_id": "d8570", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d8571", "text": "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()", "title": ""}
{"_id": "d8572", "text": "def coords_string_parser(self, coords):\n        \"\"\"Pareses the address string into coordinates to match address_to_coords return object\"\"\"\n\n        lat, lon = coords.split(',')\n        return {\"lat\": lat.strip(), \"lon\": lon.strip(), \"bounds\": {}}", "title": ""}
{"_id": "d8573", "text": "def ToDatetime(self):\n    \"\"\"Converts Timestamp to datetime.\"\"\"\n    return datetime.utcfromtimestamp(\n        self.seconds + self.nanos / float(_NANOS_PER_SECOND))", "title": ""}
{"_id": "d8574", "text": "def _linearInterpolationTransformMatrix(matrix1, matrix2, value):\n    \"\"\" Linear, 'oldstyle' interpolation of the transform matrix.\"\"\"\n    return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))", "title": ""}
{"_id": "d8575", "text": "def _DateToEpoch(date):\n  \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n  tz_zero = datetime.datetime.utcfromtimestamp(0)\n  diff_sec = int((date - tz_zero).total_seconds())\n  return diff_sec * 1000000", "title": ""}
{"_id": "d8576", "text": "def each_img(dir_path):\n    \"\"\"\n    Iterates through each image in the given directory. (not recursive)\n    :param dir_path: Directory path where images files are present\n    :return: Iterator to iterate through image files\n    \"\"\"\n    for fname in os.listdir(dir_path):\n        if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'):\n            yield fname", "title": ""}
{"_id": "d8577", "text": "def datetime_to_timezone(date, tz=\"UTC\"):\n    \"\"\" convert naive datetime to timezone-aware datetime \"\"\"\n    if not date.tzinfo:\n        date = date.replace(tzinfo=timezone(get_timezone()))\n    return date.astimezone(timezone(tz))", "title": ""}
{"_id": "d8578", "text": "def get_all_files(folder):\n    \"\"\"\n    Generator that loops through all absolute paths of the files within folder\n\n    Parameters\n    ----------\n    folder: str\n    Root folder start point for recursive search.\n\n    Yields\n    ------\n    fpath: str\n    Absolute path of one file in the folders\n    \"\"\"\n    for path, dirlist, filelist in os.walk(folder):\n        for fn in filelist:\n            yield op.join(path, fn)", "title": ""}
{"_id": "d8579", "text": "def now_time(str=False):\n    \"\"\"Get the current time.\"\"\"\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()", "title": ""}
{"_id": "d8580", "text": "def resize_by_area(img, size):\n  \"\"\"image resize function used by quite a few image problems.\"\"\"\n  return tf.to_int64(\n      tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))", "title": ""}
{"_id": "d8581", "text": "def _iterable_to_varargs_method(func):\n    \"\"\"decorator to convert a method taking a iterable to a *args one\"\"\"\n    def wrapped(self, *args, **kwargs):\n        return func(self, args, **kwargs)\n    return wrapped", "title": ""}
{"_id": "d8582", "text": "def decode_bytes(string):\n    \"\"\" Decodes a given base64 string into bytes.\n\n    :param str string: The string to decode\n    :return: The decoded bytes\n    :rtype: bytes\n    \"\"\"\n\n    if is_string_type(type(string)):\n        string = bytes(string, \"utf-8\")\n    return base64.decodebytes(string)", "title": ""}
{"_id": "d8583", "text": "def recursively_update(d, d2):\n  \"\"\"dict.update but which merges child dicts (dict2 takes precedence where there's conflict).\"\"\"\n  for k, v in d2.items():\n    if k in d:\n      if isinstance(v, dict):\n        recursively_update(d[k], v)\n        continue\n    d[k] = v", "title": ""}
{"_id": "d8584", "text": "def val_to_bin(edges, x):\n    \"\"\"Convert axis coordinate to bin index.\"\"\"\n    ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n    return ibin", "title": ""}
{"_id": "d8585", "text": "def __deepcopy__(self, memo):\n        \"\"\"Improve deepcopy speed.\"\"\"\n        return type(self)(value=self._value, enum_ref=self.enum_ref)", "title": ""}
{"_id": "d8586", "text": "def print_bintree(tree, indent='  '):\n    \"\"\"print a binary tree\"\"\"\n    for n in sorted(tree.keys()):\n        print \"%s%s\" % (indent * depth(n,tree), n)", "title": ""}
{"_id": "d8587", "text": "def def_linear(fun):\n    \"\"\"Flags that a function is linear wrt all args\"\"\"\n    defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:\n                  fun(*subval(args, argnum, g), **kwargs))", "title": ""}
{"_id": "d8588", "text": "def abs_img(img):\n    \"\"\" Return an image with the binarised version of the data of `img`.\"\"\"\n    bool_img = np.abs(read_img(img).get_data())\n    return bool_img.astype(int)", "title": ""}
{"_id": "d8589", "text": "def exec_function(ast, globals_map):\n    \"\"\"Execute a python code object in the given environment.\n\n    Args:\n      globals_map: Dictionary to use as the globals context.\n    Returns:\n      locals_map: Dictionary of locals from the environment after execution.\n    \"\"\"\n    locals_map = globals_map\n    exec ast in globals_map, locals_map\n    return locals_map", "title": ""}
{"_id": "d8590", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d8591", "text": "def input_int_default(question=\"\", default=0):\n    \"\"\"A function that works for both, Python 2.x and Python 3.x.\n       It asks the user for input and returns it as a string.\n    \"\"\"\n    answer = input_string(question)\n    if answer == \"\" or answer == \"yes\":\n        return default\n    else:\n        return int(answer)", "title": ""}
{"_id": "d8592", "text": "def make_file_read_only(file_path):\n    \"\"\"\n    Removes the write permissions for the given file for owner, groups and others.\n\n    :param file_path: The file whose privileges are revoked.\n    :raise FileNotFoundError: If the given file does not exist.\n    \"\"\"\n    old_permissions = os.stat(file_path).st_mode\n    os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)", "title": ""}
{"_id": "d8593", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d8594", "text": "def download_file_from_bucket(self, bucket, file_path, key):\n        \"\"\" Download file from S3 Bucket \"\"\"\n        with open(file_path, 'wb') as data:\n            self.__s3.download_fileobj(bucket, key, data)\n            return file_path", "title": ""}
{"_id": "d8595", "text": "def safe_delete(filename):\n  \"\"\"Delete a file safely. If it's not present, no-op.\"\"\"\n  try:\n    os.unlink(filename)\n  except OSError as e:\n    if e.errno != errno.ENOENT:\n      raise", "title": ""}
{"_id": "d8596", "text": "def split_into_words(s):\n  \"\"\"Split a sentence into list of words.\"\"\"\n  s = re.sub(r\"\\W+\", \" \", s)\n  s = re.sub(r\"[_0-9]+\", \" \", s)\n  return s.split()", "title": ""}
{"_id": "d8597", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d8598", "text": "def url(self, action, **kwargs):\n        \"\"\" Construct and return the URL for a specific API service. \"\"\"\n        # TODO : should be static method ?\n        return self.URLS['BASE'] % self.URLS[action] % kwargs", "title": ""}
{"_id": "d8599", "text": "def backward_delete_word(self, e): # (Control-Rubout)\n        u\"\"\"Delete the character behind the cursor. A numeric argument means\n        to kill the characters instead of deleting them.\"\"\"\n        self.l_buffer.backward_delete_word(self.argument_reset)\n        self.finalize()", "title": ""}
{"_id": "d8600", "text": "def clean_all(self, args):\n        \"\"\"Delete all build components; the package cache, package builds,\n        bootstrap builds and distributions.\"\"\"\n        self.clean_dists(args)\n        self.clean_builds(args)\n        self.clean_download_cache(args)", "title": ""}
{"_id": "d8601", "text": "def __delitem__(self, key):\n\t\t\"\"\"Remove item with given key from the mapping.\n\n\t\tRuns in O(n), unless removing last item, then in O(1).\n\t\t\"\"\"\n\t\tindex, value = self._dict.pop(key)\n\t\tkey2, value2 = self._list.pop(index)\n\t\tassert key == key2\n\t\tassert value is value2\n\n\t\tself._fix_indices_after_delete(index)", "title": ""}
{"_id": "d8602", "text": "def restore_button_state(self):\n        \"\"\"Helper to restore button state.\"\"\"\n        self.parent.pbnNext.setEnabled(self.next_button_state)\n        self.parent.pbnBack.setEnabled(self.back_button_state)", "title": ""}
{"_id": "d8603", "text": "def remove_this_tlink(self,tlink_id):\n        \"\"\"\n        Removes the tlink for the given tlink identifier\n        @type tlink_id: string\n        @param tlink_id: the tlink identifier to be removed\n        \"\"\"\n        for tlink in self.get_tlinks():\n            if tlink.get_id() == tlink_id:\n                self.node.remove(tlink.get_node())\n                break", "title": ""}
{"_id": "d8604", "text": "def _int64_feature(value):\n  \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))", "title": ""}
{"_id": "d8605", "text": "def get_tri_area(pts):\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d8606", "text": "def _sanitize(text):\n    \"\"\"Return sanitized Eidos text field for human readability.\"\"\"\n    d = {'-LRB-': '(', '-RRB-': ')'}\n    return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text)", "title": ""}
{"_id": "d8607", "text": "def normalized_distance(self, image):\n        \"\"\"Calculates the distance of a given image to the\n        original image.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            The image that should be compared to the original image.\n\n        Returns\n        -------\n        :class:`Distance`\n            The distance between the given image and the original image.\n\n        \"\"\"\n        return self.__distance(\n            self.__original_image_for_distance,\n            image,\n            bounds=self.bounds())", "title": ""}
{"_id": "d8608", "text": "def _remove_from_index(index, obj):\n    \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n    try:\n        index.value_map[indexed_value(index, obj)].remove(obj.id)\n    except KeyError:\n        pass", "title": ""}
{"_id": "d8609", "text": "def _distance(coord1, coord2):\n    \"\"\"\n    Return the distance between two points, `coord1` and `coord2`. These\n    parameters are assumed to be (x, y) tuples.\n    \"\"\"\n    xdist = coord1[0] - coord2[0]\n    ydist = coord1[1] - coord2[1]\n    return sqrt(xdist*xdist + ydist*ydist)", "title": ""}
{"_id": "d8610", "text": "def _decode(self, obj, context):\n        \"\"\"\n        Get the python representation of the obj\n        \"\"\"\n        return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode(\"utf8\")", "title": ""}
{"_id": "d8611", "text": "def tpr(y, z):\n    \"\"\"True positive rate `tp / (tp + fn)`\n    \"\"\"\n    tp, tn, fp, fn = contingency_table(y, z)\n    return tp / (tp + fn)", "title": ""}
{"_id": "d8612", "text": "def is_descriptor_class(desc, include_abstract=False):\n    r\"\"\"Check calculatable descriptor class or not.\n\n    Returns:\n        bool\n\n    \"\"\"\n    return (\n        isinstance(desc, type)\n        and issubclass(desc, Descriptor)\n        and (True if include_abstract else not inspect.isabstract(desc))\n    )", "title": ""}
{"_id": "d8613", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d8614", "text": "def terminate(self):\n        \"\"\"Terminate all workers and threads.\"\"\"\n        for t in self._threads:\n            t.quit()\n        self._thread = []\n        self._workers = []", "title": ""}
{"_id": "d8615", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d8616", "text": "def determine_interactive(self):\n\t\t\"\"\"Determine whether we're in an interactive shell.\n\t\tSets interactivity off if appropriate.\n\t\tcf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):\n\t\t\t\tself.interactive = 0\n\t\t\t\treturn False\n\t\texcept Exception:\n\t\t\tself.interactive = 0\n\t\t\treturn False\n\t\tif self.interactive == 0:\n\t\t\treturn False\n\t\treturn True", "title": ""}
{"_id": "d8617", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d8618", "text": "def set_terminate_listeners(stream):\n    \"\"\"Die on SIGTERM or SIGINT\"\"\"\n\n    def stop(signum, frame):\n        terminate(stream.listener)\n\n    # Installs signal handlers for handling SIGINT and SIGTERM\n    # gracefully.\n    signal.signal(signal.SIGINT, stop)\n    signal.signal(signal.SIGTERM, stop)", "title": ""}
{"_id": "d8619", "text": "def matches(self, s):\n    \"\"\"Whether the pattern matches anywhere in the string s.\"\"\"\n    regex_matches = self.compiled_regex.search(s) is not None\n    return not regex_matches if self.inverted else regex_matches", "title": ""}
{"_id": "d8620", "text": "def timed_call(func, *args, log_level='DEBUG', **kwargs):\n    \"\"\"Logs a function's run time\n\n    :param func: The function to run\n    :param args: The args to pass to the function\n    :param kwargs: The keyword args to pass to the function\n    :param log_level: The log level at which to print the run time\n    :return: The function's return value\n    \"\"\"\n    start = time()\n    r = func(*args, **kwargs)\n    t = time() - start\n    log(log_level, \"Call to '{}' took {:0.6f}s\".format(func.__name__, t))\n    return r", "title": ""}
{"_id": "d8621", "text": "def is_unix_like(platform=None):\n    \"\"\"Returns whether the given platform is a Unix-like platform with the usual\n    Unix filesystem. When the parameter is omitted, it defaults to ``sys.platform``\n    \"\"\"\n    platform = platform or sys.platform\n    platform = platform.lower()\n    return platform.startswith(\"linux\") or platform.startswith(\"darwin\") or \\\n            platform.startswith(\"cygwin\")", "title": ""}
{"_id": "d8622", "text": "def calculate_size(name, data_list):\n    \"\"\" Calculates the request payload size\"\"\"\n    data_size = 0\n    data_size += calculate_size_str(name)\n    data_size += INT_SIZE_IN_BYTES\n    for data_list_item in data_list:\n        data_size += calculate_size_data(data_list_item)\n    return data_size", "title": ""}
{"_id": "d8623", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d8624", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d8625", "text": "def get_file_extension_type(filename):\n    \"\"\"\n    Return the group associated to the file\n    :param filename:\n    :return: str\n    \"\"\"\n    ext = get_file_extension(filename)\n    if ext:\n        for name, group in EXTENSIONS.items():\n            if ext in group:\n                return name\n    return \"OTHER\"", "title": ""}
{"_id": "d8626", "text": "def register(self, target):\n        \"\"\"Registers url_rules on the blueprint\n        \"\"\"\n        for rule, options in self.url_rules:\n            target.add_url_rule(rule, self.name, self.dispatch_request, **options)", "title": ""}
{"_id": "d8627", "text": "def check_hash_key(query_on, key):\n    \"\"\"Only allows == against query_on.hash_key\"\"\"\n    return (\n        isinstance(key, BaseCondition) and\n        (key.operation == \"==\") and\n        (key.column is query_on.hash_key)\n    )", "title": ""}
{"_id": "d8628", "text": "def load_files(files):\n    \"\"\"Load and execute a python file.\"\"\"\n\n    for py_file in files:\n        LOG.debug(\"exec %s\", py_file)\n        execfile(py_file, globals(), locals())", "title": ""}
{"_id": "d8629", "text": "def _uptime_syllable():\n    \"\"\"Returns uptime in seconds or None, on Syllable.\"\"\"\n    global __boottime\n    try:\n        __boottime = os.stat('/dev/pty/mst/pty0').st_mtime\n        return time.time() - __boottime\n    except (NameError, OSError):\n        return None", "title": ""}
{"_id": "d8630", "text": "def typescript_compile(source):\n    \"\"\"Compiles the given ``source`` from TypeScript to ES5 using TypescriptServices.js\"\"\"\n    with open(TS_COMPILER, 'r') as tsservices_js:\n        return evaljs(\n            (tsservices_js.read(),\n             'ts.transpile(dukpy.tscode, {options});'.format(options=TSC_OPTIONS)),\n            tscode=source\n        )", "title": ""}
{"_id": "d8631", "text": "def __contains__(self, key):\n        \"\"\"\n        Invoked when determining whether a specific key is in the dictionary\n        using `key in d`.\n\n        The key is looked up case-insensitively.\n        \"\"\"\n        k = self._real_key(key)\n        return k in self._data", "title": ""}
{"_id": "d8632", "text": "def sort_func(self, key):\n        \"\"\"Sorting logic for `Quantity` objects.\"\"\"\n        if key == self._KEYS.VALUE:\n            return 'aaa'\n        if key == self._KEYS.SOURCE:\n            return 'zzz'\n        return key", "title": ""}
{"_id": "d8633", "text": "def __call__(self, func, *args, **kwargs):\n        \"\"\"Shorcut for self.run.\"\"\"\n        return self.run(func, *args, **kwargs)", "title": ""}
{"_id": "d8634", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d8635", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d8636", "text": "def __init__(self):\n        \"\"\"Initialize the state of the object\"\"\"\n        self.state = self.STATE_INITIALIZING\n        self.state_start = time.time()", "title": ""}
{"_id": "d8637", "text": "def clean_dict_keys(d):\n    \"\"\"Convert all keys of the dict 'd' to (ascii-)strings.\n\n    :Raises: UnicodeEncodeError\n    \"\"\"\n    new_d = {}\n    for (k, v) in d.iteritems():\n        new_d[str(k)] = v\n    return new_d", "title": ""}
{"_id": "d8638", "text": "def redirect(view=None, url=None, **kwargs):\n    \"\"\"Redirects to the specified view or url\n    \"\"\"\n    if view:\n        if url:\n            kwargs[\"url\"] = url\n        url = flask.url_for(view, **kwargs)\n    current_context.exit(flask.redirect(url))", "title": ""}
{"_id": "d8639", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d8640", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d8641", "text": "def is_break_tag(self, el):\n        \"\"\"Check if tag is an element we should break on.\"\"\"\n\n        name = el.name\n        return name in self.break_tags or name in self.user_break_tags", "title": ""}
{"_id": "d8642", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d8643", "text": "def ignored_regions(source):\n    \"\"\"Return ignored regions like strings and comments in `source` \"\"\"\n    return [(match.start(), match.end()) for match in _str.finditer(source)]", "title": ""}
{"_id": "d8644", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d8645", "text": "def install_plugin(username, repo):\n    \"\"\"Installs a Blended plugin from GitHub\"\"\"\n    print(\"Installing plugin from \" + username + \"/\" + repo)\n\n    pip.main(['install', '-U', \"git+git://github.com/\" +\n              username + \"/\" + repo + \".git\"])", "title": ""}
{"_id": "d8646", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d8647", "text": "def to_camel_case(text):\n    \"\"\"Convert to camel case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    split = text.split('_')\n    return split[0] + \"\".join(x.title() for x in split[1:])", "title": ""}
{"_id": "d8648", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d8649", "text": "def serialize_json_string(self, value):\n        \"\"\"\n        Tries to load an encoded json string back into an object\n        :param json_string:\n        :return:\n        \"\"\"\n\n        # Check if the value might be a json string\n        if not isinstance(value, six.string_types):\n            return value\n\n        # Make sure it starts with a brace\n        if not value.startswith('{') or value.startswith('['):\n            return value\n\n        # Try to load the string\n        try:\n            return json.loads(value)\n        except:\n            return value", "title": ""}
{"_id": "d8650", "text": "def str2bytes(x):\n  \"\"\"Convert input argument to bytes\"\"\"\n  if type(x) is bytes:\n    return x\n  elif type(x) is str:\n    return bytes([ ord(i) for i in x ])\n  else:\n    return str2bytes(str(x))", "title": ""}
{"_id": "d8651", "text": "def dict_to_querystring(dictionary):\n    \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\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]", "title": ""}
{"_id": "d8652", "text": "def run_cmd(command, verbose=True, shell='/bin/bash'):\n    \"\"\"internal helper function to run shell commands and get output\"\"\"\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 full output including empty lines\n        return output\n    return [line for line in output if line.strip()]", "title": ""}
{"_id": "d8653", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d8654", "text": "def set_terminate_listeners(stream):\n    \"\"\"Die on SIGTERM or SIGINT\"\"\"\n\n    def stop(signum, frame):\n        terminate(stream.listener)\n\n    # Installs signal handlers for handling SIGINT and SIGTERM\n    # gracefully.\n    signal.signal(signal.SIGINT, stop)\n    signal.signal(signal.SIGTERM, stop)", "title": ""}
{"_id": "d8655", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d8656", "text": "def _cal_dist2center(X, center):\n    \"\"\" Calculate the SSE to the cluster center\n    \"\"\"\n    dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')\n    return(np.sum(dmemb2cen))", "title": ""}
{"_id": "d8657", "text": "def update(self, params):\n        \"\"\"Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device.\n        \"\"\"\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "title": ""}
{"_id": "d8658", "text": "def gauss_box_model(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5):\n    \"\"\"Integrate a Gaussian profile.\"\"\"\n    z = (x - mean) / stddev\n    z2 = z + hpix / stddev\n    z1 = z - hpix / stddev\n    return amplitude * (norm.cdf(z2) - norm.cdf(z1))", "title": ""}
{"_id": "d8659", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d8660", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d8661", "text": "def filter_dict_by_key(d, keys):\n    \"\"\"Filter the dict *d* to remove keys not in *keys*.\"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d8662", "text": "def swap(self):\n        \"\"\"Return the box (for horizontal graphs)\"\"\"\n        self.xmin, self.ymin = self.ymin, self.xmin\n        self.xmax, self.ymax = self.ymax, self.xmax", "title": ""}
{"_id": "d8663", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d8664", "text": "def get_number(s, cast=int):\n    \"\"\"\n    Try to get a number out of a string, and cast it.\n    \"\"\"\n    import string\n    d = \"\".join(x for x in str(s) if x in string.digits)\n    return cast(d)", "title": ""}
{"_id": "d8665", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d8666", "text": "def plot3d_init(fignum):\n    \"\"\"\n    initializes 3D plot\n    \"\"\"\n    from mpl_toolkits.mplot3d import Axes3D\n    fig = plt.figure(fignum)\n    ax = fig.add_subplot(111, projection='3d')\n    return ax", "title": ""}
{"_id": "d8667", "text": "def safe_dump_all(documents, stream=None, **kwds):\n    \"\"\"\n    Serialize a sequence of Python objects into a YAML stream.\n    Produce only basic YAML tags.\n    If stream is None, return the produced string instead.\n    \"\"\"\n    return dump_all(documents, stream, Dumper=SafeDumper, **kwds)", "title": ""}
{"_id": "d8668", "text": "def _update_index_on_df(df, index_names):\n    \"\"\"Helper function to restore index information after collection. Doesn't\n    use self so we can serialize this.\"\"\"\n    if index_names:\n        df = df.set_index(index_names)\n        # Remove names from unnamed indexes\n        index_names = _denormalize_index_names(index_names)\n        df.index.names = index_names\n    return df", "title": ""}
{"_id": "d8669", "text": "async def vc_check(ctx: commands.Context):  # pylint: disable=unused-argument\n    \"\"\"\n    Check for whether VC is available in this bot.\n    \"\"\"\n\n    if not discord.voice_client.has_nacl:\n        raise commands.CheckFailure(\"voice cannot be used because PyNaCl is not loaded\")\n\n    if not discord.opus.is_loaded():\n        raise commands.CheckFailure(\"voice cannot be used because libopus is not loaded\")\n\n    return True", "title": ""}
{"_id": "d8670", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d8671", "text": "def _render_table(data, fields=None):\n  \"\"\" Helper to render a list of dictionaries as an HTML display object. \"\"\"\n  return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))", "title": ""}
{"_id": "d8672", "text": "def exec_function(ast, globals_map):\n    \"\"\"Execute a python code object in the given environment.\n\n    Args:\n      globals_map: Dictionary to use as the globals context.\n    Returns:\n      locals_map: Dictionary of locals from the environment after execution.\n    \"\"\"\n    locals_map = globals_map\n    exec ast in globals_map, locals_map\n    return locals_map", "title": ""}
{"_id": "d8673", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d8674", "text": "def logger(message, level=10):\n    \"\"\"Handle logging.\"\"\"\n    logging.getLogger(__name__).log(level, str(message))", "title": ""}
{"_id": "d8675", "text": "def parse_value(self, value):\n        \"\"\"Cast value to `bool`.\"\"\"\n        parsed = super(BoolField, self).parse_value(value)\n        return bool(parsed) if parsed is not None else None", "title": ""}
{"_id": "d8676", "text": "def na_if(series, *values):\n    \"\"\"\n    If values in a series match a specified value, change them to `np.nan`.\n\n    Args:\n        series: Series or vector, often symbolic.\n        *values: Value(s) to convert to `np.nan` in the series.\n    \"\"\"\n\n    series = pd.Series(series)\n    series[series.isin(values)] = np.nan\n    return series", "title": ""}
{"_id": "d8677", "text": "def set_cursor_position(self, position):\n        \"\"\"Set cursor position\"\"\"\n        position = self.get_position(position)\n        cursor = self.textCursor()\n        cursor.setPosition(position)\n        self.setTextCursor(cursor)\n        self.ensureCursorVisible()", "title": ""}
{"_id": "d8678", "text": "def glr_path_static():\n    \"\"\"Returns path to packaged static files\"\"\"\n    return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))", "title": ""}
{"_id": "d8679", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d8680", "text": "def get_header(request, header_service):\n    \"\"\"Return request's 'X_POLYAXON_...:' header, as a bytestring.\n\n    Hide some test client ickyness where the header can be unicode.\n    \"\"\"\n    service = request.META.get('HTTP_{}'.format(header_service), b'')\n    if isinstance(service, str):\n        # Work around django test client oddness\n        service = service.encode(HTTP_HEADER_ENCODING)\n    return service", "title": ""}
{"_id": "d8681", "text": "def string_to_float_list(string_var):\n        \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n        try:\n            return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n        except:\n            return [float(s) for s in string_var.strip('[').strip(']').split(',')]", "title": ""}
{"_id": "d8682", "text": "def __del__(self):\n        \"\"\"Cleanup any active connections and free all DDEML resources.\"\"\"\n        if self._hConv:\n            DDE.Disconnect(self._hConv)\n        if self._idInst:\n            DDE.Uninitialize(self._idInst)", "title": ""}
{"_id": "d8683", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d8684", "text": "def format_doc_text(text):\n    \"\"\"\n    A very thin wrapper around textwrap.fill to consistently wrap documentation text\n    for display in a command line environment. The text is wrapped to 99 characters with an\n    indentation depth of 4 spaces. Each line is wrapped independently in order to preserve\n    manually added line breaks.\n\n    :param text: The text to format, it is cleaned by inspect.cleandoc.\n    :return: The formatted doc text.\n    \"\"\"\n\n    return '\\n'.join(\n        textwrap.fill(line, width=99, initial_indent='    ', subsequent_indent='    ')\n        for line in inspect.cleandoc(text).splitlines())", "title": ""}
{"_id": "d8685", "text": "def adapt_array(arr):\n    \"\"\"\n    http://stackoverflow.com/a/31312102/190597 (SoulNibbler)\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr)\n    out.seek(0)\n    return sqlite3.Binary(out.read())", "title": ""}
{"_id": "d8686", "text": "def prepare(doc):\n    \"\"\"Sets the caption_found and plot_found variables to False.\"\"\"\n    doc.caption_found = False\n    doc.plot_found = False\n    doc.listings_counter = 0", "title": ""}
{"_id": "d8687", "text": "def _renamer(self, tre):\n        \"\"\" renames newick from numbers to sample names\"\"\"\n        ## get the tre with numbered tree tip labels\n        names = tre.get_leaves()\n\n        ## replace numbered names with snames\n        for name in names:\n            name.name = self.samples[int(name.name)]\n\n        ## return with only topology and leaf labels\n        return tre.write(format=9)", "title": ""}
{"_id": "d8688", "text": "def comment (self, s, **args):\n        \"\"\"Write DOT comment.\"\"\"\n        self.write(u\"// \")\n        self.writeln(s=s, **args)", "title": ""}
{"_id": "d8689", "text": "def to_str(obj):\n    \"\"\"Attempts to convert given object to a string object\n    \"\"\"\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)", "title": ""}
{"_id": "d8690", "text": "def OnRootView(self, event):\n        \"\"\"Reset view to the root of the tree\"\"\"\n        self.adapter, tree, rows = self.RootNode()\n        self.squareMap.SetModel(tree, self.adapter)\n        self.RecordHistory()\n        self.ConfigureViewTypeChoices()", "title": ""}
{"_id": "d8691", "text": "def _to_corrected_pandas_type(dt):\n    \"\"\"\n    When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n    This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n    \"\"\"\n    import numpy as np\n    if type(dt) == ByteType:\n        return np.int8\n    elif type(dt) == ShortType:\n        return np.int16\n    elif type(dt) == IntegerType:\n        return np.int32\n    elif type(dt) == FloatType:\n        return np.float32\n    else:\n        return None", "title": ""}
{"_id": "d8692", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d8693", "text": "def to_utc(self, dt):\n        \"\"\"Convert any timestamp to UTC (with tzinfo).\"\"\"\n        if dt.tzinfo is None:\n            return dt.replace(tzinfo=self.utc)\n        return dt.astimezone(self.utc)", "title": ""}
{"_id": "d8694", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d8695", "text": "def _init_glyph(self, plot, mapping, properties):\n        \"\"\"\n        Returns a Bokeh glyph object.\n        \"\"\"\n        properties = mpl_to_bokeh(properties)\n        plot_method = self._plot_methods.get('batched' if self.batched else 'single')\n        if isinstance(plot_method, tuple):\n            # Handle alternative plot method for flipped axes\n            plot_method = plot_method[int(self.invert_axes)]\n        renderer = getattr(plot, plot_method)(**dict(properties, **mapping))\n        return renderer, renderer.glyph", "title": ""}
{"_id": "d8696", "text": "def pylog(self, *args, **kwargs):\n        \"\"\"Display all available logging information.\"\"\"\n        printerr(self.name, args, kwargs, traceback.format_exc())", "title": ""}
{"_id": "d8697", "text": "def _is_already_configured(configuration_details):\n    \"\"\"Returns `True` when alias already in shell config.\"\"\"\n    path = Path(configuration_details.path).expanduser()\n    with path.open('r') as shell_config:\n        return configuration_details.content in shell_config.read()", "title": ""}
{"_id": "d8698", "text": "def safe_dump(data, stream=None, **kwds):\n    \"\"\"implementation of safe dumper using Ordered Dict Yaml Dumper\"\"\"\n    return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)", "title": ""}
{"_id": "d8699", "text": "def duplicated_rows(df, col_name):\n    \"\"\" Return a DataFrame with the duplicated values of the column `col_name`\n    in `df`.\"\"\"\n    _check_cols(df, [col_name])\n\n    dups = df[pd.notnull(df[col_name]) & df.duplicated(subset=[col_name])]\n    return dups", "title": ""}
{"_id": "d8700", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d8701", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d8702", "text": "def _add_params_docstring(params):\n    \"\"\" Add params to doc string\n    \"\"\"\n    p_string = \"\\nAccepts the following paramters: \\n\"\n    for param in params:\n         p_string += \"name: %s, required: %s, description: %s \\n\" % (param['name'], param['required'], param['description'])\n    return p_string", "title": ""}
{"_id": "d8703", "text": "def _request_limit_reached(exception):\n    \"\"\" Checks if exception was raised because of too many executed requests. (This is a temporal solution and\n    will be changed in later package versions.)\n\n    :param exception: Exception raised during download\n    :type exception: Exception\n    :return: True if exception is caused because too many requests were executed at once and False otherwise\n    :rtype: bool\n    \"\"\"\n    return isinstance(exception, requests.HTTPError) and \\\n        exception.response.status_code == requests.status_codes.codes.TOO_MANY_REQUESTS", "title": ""}
{"_id": "d8704", "text": "def _basic_field_data(field, obj):\n    \"\"\"Returns ``obj.field`` data as a dict\"\"\"\n    value = field.value_from_object(obj)\n    return {Field.TYPE: FieldType.VAL, Field.VALUE: value}", "title": ""}
{"_id": "d8705", "text": "def ensure_us_time_resolution(val):\n    \"\"\"Convert val out of numpy time, for use in to_dict.\n    Needed because of numpy bug GH#7619\"\"\"\n    if np.issubdtype(val.dtype, np.datetime64):\n        val = val.astype('datetime64[us]')\n    elif np.issubdtype(val.dtype, np.timedelta64):\n        val = val.astype('timedelta64[us]')\n    return val", "title": ""}
{"_id": "d8706", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d8707", "text": "def full(self):\n        \"\"\"Return True if the queue is full\"\"\"\n        if not self.size: return False\n        return len(self.pq) == (self.size + self.removed_count)", "title": ""}
{"_id": "d8708", "text": "def update_index(index):\n    \"\"\"Re-index every document in a named index.\"\"\"\n    logger.info(\"Updating search index: '%s'\", index)\n    client = get_client()\n    responses = []\n    for model in get_index_models(index):\n        logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n        objects = model.objects.get_search_queryset(index).iterator()\n        actions = bulk_actions(objects, index=index, action=\"index\")\n        response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n        responses.append(response)\n    return responses", "title": ""}
{"_id": "d8709", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d8710", "text": "def determine_types(self):\n        \"\"\" Determine ES type names from request data.\n\n        In particular `request.matchdict['collections']` is used to\n        determine types names. Its value is comma-separated sequence\n        of collection names under which views have been registered.\n        \"\"\"\n        from nefertari.elasticsearch import ES\n        collections = self.get_collections()\n        resources = self.get_resources(collections)\n        models = set([res.view.Model for res in resources])\n        es_models = [mdl for mdl in models if mdl\n                     and getattr(mdl, '_index_enabled', False)]\n        types = [ES.src2type(mdl.__name__) for mdl in es_models]\n        return types", "title": ""}
{"_id": "d8711", "text": "def determine_types(self):\n        \"\"\" Determine ES type names from request data.\n\n        In particular `request.matchdict['collections']` is used to\n        determine types names. Its value is comma-separated sequence\n        of collection names under which views have been registered.\n        \"\"\"\n        from nefertari.elasticsearch import ES\n        collections = self.get_collections()\n        resources = self.get_resources(collections)\n        models = set([res.view.Model for res in resources])\n        es_models = [mdl for mdl in models if mdl\n                     and getattr(mdl, '_index_enabled', False)]\n        types = [ES.src2type(mdl.__name__) for mdl in es_models]\n        return types", "title": ""}
{"_id": "d8712", "text": "def is_vector(inp):\n    \"\"\" 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\n    \"\"\"\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", "title": ""}
{"_id": "d8713", "text": "def lines(input):\n    \"\"\"Remove comments and empty lines\"\"\"\n    for raw_line in input:\n        line = raw_line.strip()\n        if line and not line.startswith('#'):\n            yield strip_comments(line)", "title": ""}
{"_id": "d8714", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d8715", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d8716", "text": "def _writable_dir(path):\n    \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n    return os.path.isdir(path) and os.access(path, os.W_OK)", "title": ""}
{"_id": "d8717", "text": "def mutating_method(func):\n    \"\"\"Decorator for methods that are allowed to modify immutable objects\"\"\"\n    def wrapper(self, *__args, **__kwargs):\n        old_mutable = self._mutable\n        self._mutable = True\n        try:\n            # Call the wrapped function\n            return func(self, *__args, **__kwargs)\n        finally:\n            self._mutable = old_mutable\n    return wrapper", "title": ""}
{"_id": "d8718", "text": "def required_header(header):\n    \"\"\"Function that verify if the header parameter is a essential header\n\n    :param header:  A string represented a header\n    :returns:       A boolean value that represent if the header is required\n    \"\"\"\n    if header in IGNORE_HEADERS:\n        return False\n\n    if header.startswith('HTTP_') or header == 'CONTENT_TYPE':\n        return True\n\n    return False", "title": ""}
{"_id": "d8719", "text": "def write_enum(fo, datum, schema):\n    \"\"\"An enum is encoded by a int, representing the zero-based position of\n    the symbol in the schema.\"\"\"\n    index = schema['symbols'].index(datum)\n    write_int(fo, index)", "title": ""}
{"_id": "d8720", "text": "def __is__(cls, s):\n        \"\"\"Test if string matches this argument's format.\"\"\"\n        return s.startswith(cls.delims()[0]) and s.endswith(cls.delims()[1])", "title": ""}
{"_id": "d8721", "text": "def _dump_enum(self, e, top=''):\n        \"\"\"Dump single enum type.\n        \n        Keyword arguments:\n        top -- top namespace\n        \"\"\"\n        self._print()\n        self._print('enum {} {{'.format(e.name))\n        self.defines.append('{}.{}'.format(top,e.name))\n        \n        self.tabs+=1\n        for v in e.value:\n            self._print('{} = {};'.format(v.name, v.number))\n        self.tabs-=1\n        self._print('}')", "title": ""}
{"_id": "d8722", "text": "def describe_enum_value(enum_value):\n    \"\"\"Build descriptor for Enum instance.\n\n    Args:\n      enum_value: Enum value to provide descriptor for.\n\n    Returns:\n      Initialized EnumValueDescriptor instance describing the Enum instance.\n    \"\"\"\n    enum_value_descriptor = EnumValueDescriptor()\n    enum_value_descriptor.name = six.text_type(enum_value.name)\n    enum_value_descriptor.number = enum_value.number\n    return enum_value_descriptor", "title": ""}
{"_id": "d8723", "text": "def set_value(self, value):\n        \"\"\"Set value of the checkbox.\n\n        Parameters\n        ----------\n        value : bool\n            value for the checkbox\n\n        \"\"\"\n        if value:\n            self.setChecked(Qt.Checked)\n        else:\n            self.setChecked(Qt.Unchecked)", "title": ""}
{"_id": "d8724", "text": "def get_enum_from_name(self, enum_name):\n        \"\"\"\n            Return an enum from a name\n        Args:\n            enum_name (str): name of the enum\n        Returns:\n            Enum\n        \"\"\"\n        return next((e for e in self.enums if e.name == enum_name), None)", "title": ""}
{"_id": "d8725", "text": "def is_defined(self, objtxt, force_import=False):\n        \"\"\"Return True if object is defined\"\"\"\n        return self.interpreter.is_defined(objtxt, force_import)", "title": ""}
{"_id": "d8726", "text": "def Value(self, name):\n    \"\"\"Returns the value coresponding to the given enum name.\"\"\"\n    if name in self._enum_type.values_by_name:\n      return self._enum_type.values_by_name[name].number\n    raise ValueError('Enum %s has no value defined for name %s' % (\n        self._enum_type.name, name))", "title": ""}
{"_id": "d8727", "text": "def starts_with_prefix_in_list(text, prefixes):\n    \"\"\"\n    Return True if the given string starts with one of the prefixes in the given list, otherwise\n    return False.\n\n    Arguments:\n        text (str): Text to check for prefixes.\n        prefixes (list): List of prefixes to check for.\n\n    Returns:\n        bool: True if the given text starts with any of the given prefixes, otherwise False.\n    \"\"\"\n    for prefix in prefixes:\n        if text.startswith(prefix):\n            return True\n    return False", "title": ""}
{"_id": "d8728", "text": "def unpack_out(self, name):\n        return self.parse(\"\"\"\n            $enum = $enum_class($value.value)\n            \"\"\", enum_class=self._import_type(), value=name)[\"enum\"]", "title": ""}
{"_id": "d8729", "text": "def _validate_pos(df):\n    \"\"\"Validates the returned positional object\n    \"\"\"\n    assert isinstance(df, pd.DataFrame)\n    assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n    assert df.position.dtype == np.dtype(\"int64\")\n    assert df.strand.dtype == np.dtype(\"O\")\n    assert df.seqname.dtype == np.dtype(\"O\")\n    return df", "title": ""}
{"_id": "d8730", "text": "def sed(match, replacement, path, modifiers=\"\"):\n    \"\"\"\n    Perform sed text substitution.\n    \"\"\"\n    cmd = \"sed -r -i 's/%s/%s/%s' %s\" % (match, replacement, modifiers, path)\n\n    process = Subprocess(cmd, shell=True)\n    ret, out, err = process.run(timeout=60)\n    if ret:\n        raise SubprocessError(\"Sed command failed!\")", "title": ""}
{"_id": "d8731", "text": "def is_json_file(filename, show_warnings = False):\n    \"\"\"Check configuration file type is JSON\n    Return a boolean indicating wheather the file is JSON format or not\n    \"\"\"\n    try:\n        config_dict = load_config(filename, file_type = \"json\")\n        is_json = True\n    except:\n        is_json = False\n    return(is_json)", "title": ""}
{"_id": "d8732", "text": "def euler(self):\n        \"\"\"TODO DEPRECATE THIS?\"\"\"\n        e_xyz = transformations.euler_from_matrix(self.rotation, 'sxyz')\n        return np.array([180.0 / np.pi * a for a in e_xyz])", "title": ""}
{"_id": "d8733", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d8734", "text": "def run(self):\n        \"\"\"Run the event loop.\"\"\"\n        self.signal_init()\n        self.listen_init()\n        self.logger.info('starting')\n        self.loop.start()", "title": ""}
{"_id": "d8735", "text": "def is_delimiter(line):\n    \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n    return bool(line) and line[0] in punctuation and line[0]*len(line) == line", "title": ""}
{"_id": "d8736", "text": "def set_locale(request):\n    \"\"\"Return locale from GET lang param or automatically.\"\"\"\n    return request.query.get('lang', app.ps.babel.select_locale_by_request(request))", "title": ""}
{"_id": "d8737", "text": "def check_auth(username, pwd):\n    \"\"\"This function is called to check if a username /\n    password combination is valid.\n    \"\"\"\n    cfg = get_current_config()\n    return username == cfg[\"dashboard_httpauth\"].split(\n        \":\")[0] and pwd == cfg[\"dashboard_httpauth\"].split(\":\")[1]", "title": ""}
{"_id": "d8738", "text": "def current_zipfile():\n    \"\"\"A function to vend the current zipfile, if any\"\"\"\n    if zipfile.is_zipfile(sys.argv[0]):\n        fd = open(sys.argv[0], \"rb\")\n        return zipfile.ZipFile(fd)", "title": ""}
{"_id": "d8739", "text": "def chmod(f):\n    \"\"\" change mod to writeable \"\"\"\n    try:\n        os.chmod(f, S_IWRITE)  # windows (cover all)\n    except Exception as e:\n        pass\n    try:\n        os.chmod(f, 0o777)  # *nix\n    except Exception as e:\n        pass", "title": ""}
{"_id": "d8740", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d8741", "text": "def __exit__(self, type, value, traceback):\n        \"\"\"When the `with` statement ends.\"\"\"\n\n        if not self.asarfile:\n            return\n\n        self.asarfile.close()\n        self.asarfile = None", "title": ""}
{"_id": "d8742", "text": "def accel_next(self, *args):\n        \"\"\"Callback to go to the next tab. Called by the accel key.\n        \"\"\"\n        if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n            self.get_notebook().set_current_page(0)\n        else:\n            self.get_notebook().next_page()\n        return True", "title": ""}
{"_id": "d8743", "text": "def __exit__(self, type, value, traceback):\n        \"\"\"When the `with` statement ends.\"\"\"\n\n        if not self.asarfile:\n            return\n\n        self.asarfile.close()\n        self.asarfile = None", "title": ""}
{"_id": "d8744", "text": "def paste(cmd=paste_cmd, stdout=PIPE):\n    \"\"\"Returns system clipboard contents.\n    \"\"\"\n    return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')", "title": ""}
{"_id": "d8745", "text": "def restore_scrollbar_position(self):\n        \"\"\"Restoring scrollbar position after main window is visible\"\"\"\n        scrollbar_pos = self.get_option('scrollbar_position', None)\n        if scrollbar_pos is not None:\n            self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)", "title": ""}
{"_id": "d8746", "text": "def osx_clipboard_get():\n    \"\"\" Get the clipboard's text on OS X.\n    \"\"\"\n    p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n        stdout=subprocess.PIPE)\n    text, stderr = p.communicate()\n    # Text comes in with old Mac \\r line endings. Change them to \\n.\n    text = text.replace('\\r', '\\n')\n    return text", "title": ""}
{"_id": "d8747", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d8748", "text": "def close_all_but_this(self):\n        \"\"\"Close all files but the current one\"\"\"\n        self.close_all_right()\n        for i in range(0, self.get_stack_count()-1  ):\n            self.close_file(0)", "title": ""}
{"_id": "d8749", "text": "def percentile(values, k):\n    \"\"\"Find the percentile of a list of values.\n\n    :param list values: The list of values to find the percentile of\n    :param int k: The percentile to find\n    :rtype: float or int\n\n    \"\"\"\n    if not values:\n        return None\n    values.sort()\n    index = (len(values) * (float(k) / 100)) - 1\n    return values[int(math.ceil(index))]", "title": ""}
{"_id": "d8750", "text": "def unlock(self):\n    \"\"\"Closes the session to the database.\"\"\"\n    if not hasattr(self, 'session'):\n      raise RuntimeError('Error detected! The session that you want to close does not exist any more!')\n    logger.debug(\"Closed database session of '%s'\" % self._database)\n    self.session.close()\n    del self.session", "title": ""}
{"_id": "d8751", "text": "def apply_to_field_if_exists(effect, field_name, fn, default):\n    \"\"\"\n    Apply function to specified field of effect if it is not None,\n    otherwise return default.\n    \"\"\"\n    value = getattr(effect, field_name, None)\n    if value is None:\n        return default\n    else:\n        return fn(value)", "title": ""}
{"_id": "d8752", "text": "def fuzzy_get_tuple(dict_obj, approximate_key, dict_keys=None, key_and_value=False, similarity=0.6, default=None):\n    \"\"\"Find the closest matching key and/or value in a dictionary (must have all string keys!)\"\"\"\n    return fuzzy_get(dict(('|'.join(str(k2) for k2 in k), v) for (k, v) in viewitems(dict_obj)),\n                     '|'.join(str(k) for k in approximate_key), dict_keys=dict_keys,\n                     key_and_value=key_and_value, similarity=similarity, default=default)", "title": ""}
{"_id": "d8753", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d8754", "text": "def calc_list_average(l):\n    \"\"\"\n    Calculates the average value of a list of numbers\n    Returns a float\n    \"\"\"\n    total = 0.0\n    for value in l:\n        total += value\n    return total / len(l)", "title": ""}
{"_id": "d8755", "text": "def get_typecast_value(self, value, type):\n    \"\"\" 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.\n    \"\"\"\n\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", "title": ""}
{"_id": "d8756", "text": "def get_scalar_product(self, other):\n        \"\"\"Returns the scalar product of this vector with the given\n        other vector.\"\"\"\n        return self.x*other.x+self.y*other.y", "title": ""}
{"_id": "d8757", "text": "def get_long_description():\n    \"\"\"Convert the README file into the long description.\n    \"\"\"\n    with open(path.join(root_path, 'README.md'), encoding='utf-8') as f:\n        long_description = f.read()\n    return long_description", "title": ""}
{"_id": "d8758", "text": "def list2string (inlist,delimit=' '):\n    \"\"\"\nConverts a 1D list to a single long string for file output, using\nthe string.join function.\n\nUsage:   list2string (inlist,delimit=' ')\nReturns: the string created from inlist\n\"\"\"\n    stringlist = [makestr(_) for _ in inlist]\n    return string.join(stringlist,delimit)", "title": ""}
{"_id": "d8759", "text": "def get_best_encoding(stream):\n    \"\"\"Returns the default stream encoding if not found.\"\"\"\n    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n    if is_ascii_encoding(rv):\n        return 'utf-8'\n    return rv", "title": ""}
{"_id": "d8760", "text": "def _float_almost_equal(float1, float2, places=7):\n    \"\"\"Return True if two numbers are equal up to the\n    specified number of \"places\" after the decimal point.\n    \"\"\"\n\n    if round(abs(float2 - float1), places) == 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d8761", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d8762", "text": "def is_int(string):\n    \"\"\"\n    Checks if a string is an integer. If the string value is an integer\n    return True, otherwise return False. \n    \n    Args:\n        string: a string to test.\n\n    Returns: \n        boolean\n    \"\"\"\n    try:\n        a = float(string)\n        b = int(a)\n    except ValueError:\n        return False\n    else:\n        return a == b", "title": ""}
{"_id": "d8763", "text": "def main(argv=None):\n    \"\"\"Main command line interface.\"\"\"\n\n    if argv is None:\n        argv = sys.argv[1:]\n\n    cli = CommandLineTool()\n    return cli.run(argv)", "title": ""}
{"_id": "d8764", "text": "def compare(string1, string2):\n    \"\"\"Compare two strings while protecting against timing attacks\n\n    :param str string1: the first string\n    :param str string2: the second string\n\n    :returns: True if the strings are equal, False if not\n    :rtype: :obj:`bool`\n    \"\"\"\n    if len(string1) != len(string2):\n        return False\n    result = True\n    for c1, c2 in izip(string1, string2):\n        result &= c1 == c2\n    return result", "title": ""}
{"_id": "d8765", "text": "def _maybe_fill(arr, fill_value=np.nan):\n    \"\"\"\n    if we have a compatible fill_value and arr dtype, then fill\n    \"\"\"\n    if _isna_compat(arr, fill_value):\n        arr.fill(fill_value)\n    return arr", "title": ""}
{"_id": "d8766", "text": "def intersect(d1, d2):\n    \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n    return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "title": ""}
{"_id": "d8767", "text": "def make_code_from_py(filename):\n    \"\"\"Get source from `filename` and make a code object of it.\"\"\"\n    # Open the source file.\n    try:\n        source_file = open_source(filename)\n    except IOError:\n        raise NoSource(\"No file to run: %r\" % filename)\n\n    try:\n        source = source_file.read()\n    finally:\n        source_file.close()\n\n    # We have the source.  `compile` still needs the last line to be clean,\n    # so make sure it is, then compile a code object from it.\n    if not source or source[-1] != '\\n':\n        source += '\\n'\n    code = compile(source, filename, \"exec\")\n\n    return code", "title": ""}
{"_id": "d8768", "text": "def __init__(self):\n    \"\"\"Initializes a filter object.\"\"\"\n    super(FilterObject, self).__init__()\n    self._filter_expression = None\n    self._matcher = None", "title": ""}
{"_id": "d8769", "text": "def dist(x1, x2, axis=0):\n    \"\"\"Return the distance between two points.\n\n    Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances.\n    \"\"\"\n    return np.linalg.norm(x2 - x1, axis=axis)", "title": ""}
{"_id": "d8770", "text": "def __init__(self, function):\n\t\t\"\"\"function: to be called with each stream element as its\n\t\tonly argument\n\t\t\"\"\"\n\t\tsuper(filter, self).__init__()\n\t\tself.function = function", "title": ""}
{"_id": "d8771", "text": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "title": ""}
{"_id": "d8772", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d8773", "text": "def tpr(y, z):\n    \"\"\"True positive rate `tp / (tp + fn)`\n    \"\"\"\n    tp, tn, fp, fn = contingency_table(y, z)\n    return tp / (tp + fn)", "title": ""}
{"_id": "d8774", "text": "def join_cols(cols):\n    \"\"\"Join list of columns into a string for a SQL query\"\"\"\n    return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols", "title": ""}
{"_id": "d8775", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d8776", "text": "def vectorize(values):\n    \"\"\"\n    Takes a value or list of values and returns a single result, joined by \",\"\n    if necessary.\n    \"\"\"\n    if isinstance(values, list):\n        return ','.join(str(v) for v in values)\n    return values", "title": ""}
{"_id": "d8777", "text": "def figsize(x=8, y=7., aspect=1.):\n    \"\"\" manually set the default figure size of plots\n    ::Arguments::\n        x (float): x-axis size\n        y (float): y-axis size\n        aspect (float): aspect ratio scalar\n    \"\"\"\n    # update rcparams with adjusted figsize params\n    mpl.rcParams.update({'figure.figsize': (x*aspect, y)})", "title": ""}
{"_id": "d8778", "text": "def convert_time_string(date_str):\n    \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n    dt, _, _ = date_str.partition(\".\")\n    dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n    return dt", "title": ""}
{"_id": "d8779", "text": "def parse_fixed_width(types, lines):\n    \"\"\"Parse a fixed width line.\"\"\"\n    values = []\n    line = []\n    for width, parser in types:\n        if not line:\n            line = lines.pop(0).replace('\\n', '')\n\n        values.append(parser(line[:width]))\n        line = line[width:]\n\n    return values", "title": ""}
{"_id": "d8780", "text": "def mean_cl_boot(series, n_samples=1000, confidence_interval=0.95,\n                 random_state=None):\n    \"\"\"\n    Bootstrapped mean with confidence limits\n    \"\"\"\n    return bootstrap_statistics(series, np.mean,\n                                n_samples=n_samples,\n                                confidence_interval=confidence_interval,\n                                random_state=random_state)", "title": ""}
{"_id": "d8781", "text": "def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):\n    \"\"\"webargs error handler that uses Flask-RESTful's abort function to return\n    a JSON error response to the client.\n    \"\"\"\n    abort(error_status_code, errors=err.messages)", "title": ""}
{"_id": "d8782", "text": "def list_apis(awsclient):\n    \"\"\"List APIs in account.\"\"\"\n    client_api = awsclient.get_client('apigateway')\n\n    apis = client_api.get_rest_apis()['items']\n\n    for api in apis:\n        print(json2table(api))", "title": ""}
{"_id": "d8783", "text": "def handleFlaskPostRequest(flaskRequest, endpoint):\n    \"\"\"\n    Handles the specified flask request for one of the POST URLS\n    Invokes the specified endpoint to generate a response.\n    \"\"\"\n    if flaskRequest.method == \"POST\":\n        return handleHttpPost(flaskRequest, endpoint)\n    elif flaskRequest.method == \"OPTIONS\":\n        return handleHttpOptions()\n    else:\n        raise exceptions.MethodNotAllowedException()", "title": ""}
{"_id": "d8784", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d8785", "text": "def checkbox_uncheck(self, force_check=False):\n        \"\"\"\n        Wrapper to uncheck a checkbox\n        \"\"\"\n        if self.get_attribute('checked'):\n            self.click(force_click=force_check)", "title": ""}
{"_id": "d8786", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d8787", "text": "def static_url(path, absolute=False):\n    \"\"\" Shorthand for returning a URL for the requested static file.\n\n    Arguments:\n\n    path -- the path to the file (relative to the static files directory)\n    absolute -- whether the link should be absolute or relative\n    \"\"\"\n\n    if os.sep != '/':\n        path = '/'.join(path.split(os.sep))\n\n    return flask.url_for('static', filename=path, _external=absolute)", "title": ""}
{"_id": "d8788", "text": "def get_site_name(request):\n    \"\"\"Return the domain:port part of the URL without scheme.\n    Eg: facebook.com, 127.0.0.1:8080, etc.\n    \"\"\"\n    urlparts = request.urlparts\n    return ':'.join([urlparts.hostname, str(urlparts.port)])", "title": ""}
{"_id": "d8789", "text": "def index():\n    \"\"\" Display productpage with normal user and test user buttons\"\"\"\n    global productpage\n\n    table = json2html.convert(json = json.dumps(productpage),\n                              table_attributes=\"class=\\\"table table-condensed table-bordered table-hover\\\"\")\n\n    return render_template('index.html', serviceTable=table)", "title": ""}
{"_id": "d8790", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d8791", "text": "def jsonify(resource):\n    \"\"\"Return a Flask ``Response`` object containing a\n    JSON representation of *resource*.\n\n    :param resource: The resource to act as the basis of the response\n    \"\"\"\n\n    response = flask.jsonify(resource.to_dict())\n    response = add_link_headers(response, resource.links())\n    return response", "title": ""}
{"_id": "d8792", "text": "def copy(string, **kwargs):\n    \"\"\"Copy given string into system clipboard.\"\"\"\n    window = Tk()\n    window.withdraw()\n    window.clipboard_clear()\n    window.clipboard_append(string)\n    window.destroy()\n    return", "title": ""}
{"_id": "d8793", "text": "def set_header(self, name, value):\n        \"\"\" Create a new response header, replacing any previously defined\n            headers with the same name. \"\"\"\n        self._headers[_hkey(name)] = [_hval(value)]", "title": ""}
{"_id": "d8794", "text": "def sample_correlations(self):\n        \"\"\"Returns an `ExpMatrix` containing all pairwise sample correlations.\n\n        Returns\n        -------\n        `ExpMatrix`\n            The sample correlation matrix.\n\n        \"\"\"\n        C = np.corrcoef(self.X.T)\n        corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)\n        return corr_matrix", "title": ""}
{"_id": "d8795", "text": "def end(self):\n        \"\"\"End of the Glances server session.\"\"\"\n        if not self.args.disable_autodiscover:\n            self.autodiscover_client.close()\n        self.server.end()", "title": ""}
{"_id": "d8796", "text": "def scatterplot_matrix(df, features, downsample_frac=None, figsize=(15, 15)):\n    \"\"\"\n    Plot a scatterplot matrix for a list of features, colored by target value.\n\n    Example: `scatterplot_matrix(X, X.columns.tolist(), downsample_frac=0.01)`\n\n    Args:\n        df: Pandas dataframe containing the target column (named 'target').\n        features: The list of features to include in the correlation plot.\n        downsample_frac: Dataframe downsampling rate (0.1 to include 10% of the dataset).\n        figsize: The size of the plot.\n    \"\"\"\n\n    if downsample_frac:\n        df = df.sample(frac=downsample_frac)\n\n    plt.figure(figsize=figsize)\n    sns.pairplot(df[features], hue='target')\n    plt.show()", "title": ""}
{"_id": "d8797", "text": "def handle_exception(error):\n        \"\"\"Simple method for handling exceptions raised by `PyBankID`.\n\n        :param flask_pybankid.FlaskPyBankIDError error: The exception to handle.\n        :return: The exception represented as a dictionary.\n        :rtype: dict\n\n        \"\"\"\n        response = jsonify(error.to_dict())\n        response.status_code = error.status_code\n        return response", "title": ""}
{"_id": "d8798", "text": "def count(data, axis=None):\n    \"\"\"Count the number of non-NA in this array along the given axis or axes\n    \"\"\"\n    return np.sum(np.logical_not(isnull(data)), axis=axis)", "title": ""}
{"_id": "d8799", "text": "def dispatch(self):\n    \"\"\"Wraps the dispatch method to add session support.\"\"\"\n    try:\n      webapp2.RequestHandler.dispatch(self)\n    finally:\n      self.session_store.save_sessions(self.response)", "title": ""}
{"_id": "d8800", "text": "def count(data, axis=None):\n    \"\"\"Count the number of non-NA in this array along the given axis or axes\n    \"\"\"\n    return np.sum(np.logical_not(isnull(data)), axis=axis)", "title": ""}
{"_id": "d8801", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d8802", "text": "def cover(session):\n    \"\"\"Run the final coverage report.\n    This outputs the coverage report aggregating coverage from the unit\n    test runs (not system test runs), and then erases coverage data.\n    \"\"\"\n    session.interpreter = 'python3.6'\n    session.install('coverage', 'pytest-cov')\n    session.run('coverage', 'report', '--show-missing', '--fail-under=100')\n    session.run('coverage', 'erase')", "title": ""}
{"_id": "d8803", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d8804", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d8805", "text": "def flatten(nested, containers=(list, tuple)):\n    \"\"\" Flatten a nested list by yielding its scalar items.\n    \"\"\"\n    for item in nested:\n        if hasattr(item, \"next\") or isinstance(item, containers):\n            for subitem in flatten(item):\n                yield subitem\n        else:\n            yield item", "title": ""}
{"_id": "d8806", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d8807", "text": "def get_mac_dot_app_dir(directory):\n    \"\"\"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\n    \"\"\"\n    return os.path.dirname(os.path.dirname(os.path.dirname(directory)))", "title": ""}
{"_id": "d8808", "text": "def _crop_list_to_size(l, size):\n    \"\"\"Make a list a certain size\"\"\"\n    for x in range(size - len(l)):\n        l.append(False)\n    for x in range(len(l) - size):\n        l.pop()\n    return l", "title": ""}
{"_id": "d8809", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d8810", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d8811", "text": "def _closeResources(self):\n        \"\"\" Closes the root Dataset.\n        \"\"\"\n        logger.info(\"Closing: {}\".format(self._fileName))\n        self._h5Group.close()\n        self._h5Group = None", "title": ""}
{"_id": "d8812", "text": "def software_fibonacci(n):\n    \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n    a, b = 0, 1\n    for i in range(n):\n        a, b = b, a + b\n    return a", "title": ""}
{"_id": "d8813", "text": "def flush(self):\n        \"\"\" Force commit changes to the file and stdout \"\"\"\n        if not self.nostdout:\n            self.stdout.flush()\n        if self.file is not None:\n            self.file.flush()", "title": ""}
{"_id": "d8814", "text": "def stringify_col(df, col_name):\n    \"\"\"\n    Take a dataframe and string-i-fy a column of values.\n    Turn nan/None into \"\" and all other values into strings.\n\n    Parameters\n    ----------\n    df : dataframe\n    col_name : string\n    \"\"\"\n    df = df.copy()\n    df[col_name] = df[col_name].fillna(\"\")\n    df[col_name] = df[col_name].astype(str)\n    return df", "title": ""}
{"_id": "d8815", "text": "def go_to_background():\n    \"\"\" Daemonize the running process. \"\"\"\n    try:\n        if os.fork():\n            sys.exit()\n    except OSError as errmsg:\n        LOGGER.error('Fork failed: {0}'.format(errmsg))\n        sys.exit('Fork failed')", "title": ""}
{"_id": "d8816", "text": "def create_app():\n    \"\"\"Create a Qt application.\"\"\"\n    global QT_APP\n    QT_APP = QApplication.instance()\n    if QT_APP is None:  # pragma: no cover\n        QT_APP = QApplication(sys.argv)\n    return QT_APP", "title": ""}
{"_id": "d8817", "text": "def go_to_background():\n    \"\"\" Daemonize the running process. \"\"\"\n    try:\n        if os.fork():\n            sys.exit()\n    except OSError as errmsg:\n        LOGGER.error('Fork failed: {0}'.format(errmsg))\n        sys.exit('Fork failed')", "title": ""}
{"_id": "d8818", "text": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "title": ""}
{"_id": "d8819", "text": "def fixed(ctx, number, decimals=2, no_commas=False):\n    \"\"\"\n    Formats the given number in decimal format using a period and commas\n    \"\"\"\n    value = _round(ctx, number, decimals)\n    format_str = '{:f}' if no_commas else '{:,f}'\n    return format_str.format(value)", "title": ""}
{"_id": "d8820", "text": "def _make_index(df, cols=META_IDX):\n    \"\"\"Create an index from the columns of a dataframe\"\"\"\n    return pd.MultiIndex.from_tuples(\n        pd.unique(list(zip(*[df[col] for col in cols]))), names=tuple(cols))", "title": ""}
{"_id": "d8821", "text": "def string_format_func(s):\n\t\"\"\"\n\tFunction used internally to format string data for output to XML.\n\tEscapes back-slashes and quotes, and wraps the resulting string in\n\tquotes.\n\t\"\"\"\n\treturn u\"\\\"%s\\\"\" % unicode(s).replace(u\"\\\\\", u\"\\\\\\\\\").replace(u\"\\\"\", u\"\\\\\\\"\")", "title": ""}
{"_id": "d8822", "text": "def map_parameters(cls, params):\n        \"\"\"Maps parameters to form field names\"\"\"\n\n        d = {}\n        for k, v in six.iteritems(params):\n            d[cls.FIELD_MAP.get(k.lower(), k)] = v\n        return d", "title": ""}
{"_id": "d8823", "text": "def position(self, x, y, text):\n        \"\"\"\n            ANSI Escape sequences\n            http://ascii-table.com/ansi-escape-sequences.php\n        \"\"\"\n        sys.stdout.write(\"\\x1b7\\x1b[%d;%df%s\\x1b8\" % (x, y, text))\n        sys.stdout.flush()", "title": ""}
{"_id": "d8824", "text": "def RunSphinxAPIDoc(_):\n  \"\"\"Runs sphinx-apidoc to auto-generate documentation.\"\"\"\n  current_directory = os.path.abspath(os.path.dirname(__file__))\n  module = os.path.join(current_directory, '..', 'plaso')\n  api_directory = os.path.join(current_directory, 'sources', 'api')\n  apidoc.main(['-o', api_directory, module, '--force'])", "title": ""}
{"_id": "d8825", "text": "def none(self):\n        \"\"\"\n        Returns an empty QuerySet.\n        \"\"\"\n        return EmptyQuerySet(model=self.model, using=self._using, connection=self._connection)", "title": ""}
{"_id": "d8826", "text": "def ucamel_method(func):\n    \"\"\"\n    Decorator to ensure the given snake_case method is also written in\n    UpperCamelCase in the given namespace. That was mainly written to\n    avoid confusion when using wxPython and its UpperCamelCaseMethods.\n    \"\"\"\n    frame_locals = inspect.currentframe().f_back.f_locals\n    frame_locals[snake2ucamel(func.__name__)] = func\n    return func", "title": ""}
{"_id": "d8827", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d8828", "text": "def ucamel_method(func):\n    \"\"\"\n    Decorator to ensure the given snake_case method is also written in\n    UpperCamelCase in the given namespace. That was mainly written to\n    avoid confusion when using wxPython and its UpperCamelCaseMethods.\n    \"\"\"\n    frame_locals = inspect.currentframe().f_back.f_locals\n    frame_locals[snake2ucamel(func.__name__)] = func\n    return func", "title": ""}
{"_id": "d8829", "text": "def sqliteRowsToDicts(sqliteRows):\n    \"\"\"\n    Unpacks sqlite rows as returned by fetchall\n    into an array of simple dicts.\n\n    :param sqliteRows: array of rows returned from fetchall DB call\n    :return:  array of dicts, keyed by the column names.\n    \"\"\"\n    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "title": ""}
{"_id": "d8830", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d8831", "text": "def nb_to_python(nb_path):\n    \"\"\"convert notebook to python script\"\"\"\n    exporter = python.PythonExporter()\n    output, resources = exporter.from_filename(nb_path)\n    return output", "title": ""}
{"_id": "d8832", "text": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "title": ""}
{"_id": "d8833", "text": "def comment (self, s, **args):\n        \"\"\"Write GML comment.\"\"\"\n        self.writeln(s=u'comment \"%s\"' % s, **args)", "title": ""}
{"_id": "d8834", "text": "def circ_permutation(items):\n    \"\"\"Calculate the circular permutation for a given list of items.\"\"\"\n    permutations = []\n    for i in range(len(items)):\n        permutations.append(items[i:] + items[:i])\n    return permutations", "title": ""}
{"_id": "d8835", "text": "def check_hash_key(query_on, key):\n    \"\"\"Only allows == against query_on.hash_key\"\"\"\n    return (\n        isinstance(key, BaseCondition) and\n        (key.operation == \"==\") and\n        (key.column is query_on.hash_key)\n    )", "title": ""}
{"_id": "d8836", "text": "def generate_device_id(steamid):\n    \"\"\"Generate Android device id\n\n    :param steamid: Steam ID\n    :type steamid: :class:`.SteamID`, :class:`int`\n    :return: android device id\n    :rtype: str\n    \"\"\"\n    h = hexlify(sha1_hash(str(steamid).encode('ascii'))).decode('ascii')\n    return \"android:%s-%s-%s-%s-%s\" % (h[:8], h[8:12], h[12:16], h[16:20], h[20:32])", "title": ""}
{"_id": "d8837", "text": "def __init__(self, token, editor=None):\n        \"\"\"Create a GistAPI object\n\n        Arguments:\n            token: an authentication token\n            editor: path to the editor to use when editing a gist\n\n        \"\"\"\n        self.token = token\n        self.editor = editor\n        self.session = requests.Session()", "title": ""}
{"_id": "d8838", "text": "def generate_id(self):\n        \"\"\"Generate a fresh id\"\"\"\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())", "title": ""}
{"_id": "d8839", "text": "def create_db(app, appbuilder):\n    \"\"\"\n        Create all your database objects (SQLAlchemy specific).\n    \"\"\"\n    from flask_appbuilder.models.sqla import Base\n\n    _appbuilder = import_application(app, appbuilder)\n    engine = _appbuilder.get_session.get_bind(mapper=None, clause=None)\n    Base.metadata.create_all(engine)\n    click.echo(click.style(\"DB objects created\", fg=\"green\"))", "title": ""}
{"_id": "d8840", "text": "def get_incomplete_path(filename):\n  \"\"\"Returns a temporary filename based on filename.\"\"\"\n  random_suffix = \"\".join(\n      random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n  return filename + \".incomplete\" + random_suffix", "title": ""}
{"_id": "d8841", "text": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "title": ""}
{"_id": "d8842", "text": "def generate_hash(self, length=30):\n        \"\"\" Generate random string of given length \"\"\"\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", "title": ""}
{"_id": "d8843", "text": "def ensure_hbounds(self):\n        \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "title": ""}
{"_id": "d8844", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d8845", "text": "def lon_lat_bins(bb, coord_bin_width):\n    \"\"\"\n    Define bin edges for disaggregation histograms.\n\n    Given bins data as provided by :func:`collect_bin_data`, this function\n    finds edges of histograms, taking into account maximum and minimum values\n    of magnitude, distance and coordinates as well as requested sizes/numbers\n    of bins.\n    \"\"\"\n    west, south, east, north = bb\n    west = numpy.floor(west / coord_bin_width) * coord_bin_width\n    east = numpy.ceil(east / coord_bin_width) * coord_bin_width\n    lon_extent = get_longitudinal_extent(west, east)\n    lon_bins, _, _ = npoints_between(\n        west, 0, 0, east, 0, 0,\n        numpy.round(lon_extent / coord_bin_width + 1))\n    lat_bins = coord_bin_width * numpy.arange(\n        int(numpy.floor(south / coord_bin_width)),\n        int(numpy.ceil(north / coord_bin_width) + 1))\n    return lon_bins, lat_bins", "title": ""}
{"_id": "d8846", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d8847", "text": "def int_to_date(date):\n    \"\"\"\n    Convert an int of form yyyymmdd to a python date object.\n    \"\"\"\n\n    year = date // 10**4\n    month = date % 10**4 // 10**2\n    day = date % 10**2\n\n    return datetime.date(year, month, day)", "title": ""}
{"_id": "d8848", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d8849", "text": "def __round_time(self, dt):\n    \"\"\"Round a datetime object to a multiple of a timedelta\n    dt : datetime.datetime object, default now.\n    \"\"\"\n    round_to = self._resolution.total_seconds()\n    seconds  = (dt - dt.min).seconds\n    rounding = (seconds + round_to / 2) // round_to * round_to\n    return dt + timedelta(0, rounding - seconds, -dt.microsecond)", "title": ""}
{"_id": "d8850", "text": "def get_font_list():\n    \"\"\"Returns a sorted list of all system font names\"\"\"\n\n    font_map = pangocairo.cairo_font_map_get_default()\n    font_list = [f.get_name() for f in font_map.list_families()]\n    font_list.sort()\n\n    return font_list", "title": ""}
{"_id": "d8851", "text": "def to_utc(self, dt):\n        \"\"\"Convert any timestamp to UTC (with tzinfo).\"\"\"\n        if dt.tzinfo is None:\n            return dt.replace(tzinfo=self.utc)\n        return dt.astimezone(self.utc)", "title": ""}
{"_id": "d8852", "text": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "title": ""}
{"_id": "d8853", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d8854", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d8855", "text": "def object_to_json(obj):\n    \"\"\"Convert object that cannot be natively serialized by python to JSON representation.\"\"\"\n    if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):\n        return obj.isoformat()\n    return str(obj)", "title": ""}
{"_id": "d8856", "text": "def get_pid_list():\n    \"\"\"Returns a list of PIDs currently running on the system.\"\"\"\n    pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]\n    return pids", "title": ""}
{"_id": "d8857", "text": "def method(func):\n    \"\"\"Wrap a function as a method.\"\"\"\n    attr = abc.abstractmethod(func)\n    attr.__imethod__ = True\n    return attr", "title": ""}
{"_id": "d8858", "text": "def getRect(self):\n\t\t\"\"\"\n\t\tReturns the window bounds as a tuple of (x,y,w,h)\n\t\t\"\"\"\n\t\treturn (self.x, self.y, self.w, self.h)", "title": ""}
{"_id": "d8859", "text": "def validate_args(**args):\n\t\"\"\"\n\tfunction to check if input query is not None \n\tand set missing arguments to default value\n\t\"\"\"\n\tif not args['query']:\n\t\tprint(\"\\nMissing required query argument.\")\n\t\tsys.exit()\n\n\tfor key in DEFAULTS:\n\t\tif key not in args:\n\t\t\targs[key] = DEFAULTS[key]\n\n\treturn args", "title": ""}
{"_id": "d8860", "text": "def get_body_size(params, boundary):\n    \"\"\"Returns the number of bytes that the multipart/form-data encoding\n    of ``params`` will be.\"\"\"\n    size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))\n    return size + len(boundary) + 6", "title": ""}
{"_id": "d8861", "text": "def input_int_default(question=\"\", default=0):\n    \"\"\"A function that works for both, Python 2.x and Python 3.x.\n       It asks the user for input and returns it as a string.\n    \"\"\"\n    answer = input_string(question)\n    if answer == \"\" or answer == \"yes\":\n        return default\n    else:\n        return int(answer)", "title": ""}
{"_id": "d8862", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d8863", "text": "def get_default_args(func):\n    \"\"\"\n    returns a dictionary of arg_name:default_values for the input function\n    \"\"\"\n    args, varargs, keywords, defaults = getargspec_no_self(func)\n    return dict(zip(args[-len(defaults):], defaults))", "title": ""}
{"_id": "d8864", "text": "def c_array(ctype, values):\n    \"\"\"Convert a python string to c array.\"\"\"\n    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):\n        return (ctype * len(values)).from_buffer_copy(values)\n    return (ctype * len(values))(*values)", "title": ""}
{"_id": "d8865", "text": "def get_shape(self):\n\t\t\"\"\"\n\t\tReturn a tuple of this array's dimensions.  This is done by\n\t\tquerying the Dim children.  Note that once it has been\n\t\tcreated, it is also possible to examine an Array object's\n\t\t.array attribute directly, and doing that is much faster.\n\t\t\"\"\"\n\t\treturn tuple(int(c.pcdata) for c in self.getElementsByTagName(ligolw.Dim.tagName))[::-1]", "title": ""}
{"_id": "d8866", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d8867", "text": "def dist(x1, x2, axis=0):\n    \"\"\"Return the distance between two points.\n\n    Set axis=1 if x1 is a vector and x2 a matrix to get a vector of distances.\n    \"\"\"\n    return np.linalg.norm(x2 - x1, axis=axis)", "title": ""}
{"_id": "d8868", "text": "def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False):\n        \"\"\"Apply a delaunay 2D filter along the best fitting plane. This\n        extracts the grid's points and perfoms the triangulation on those alone.\n        \"\"\"\n        return PolyData(self.points).delaunay_2d(tol=tol, alpha=alpha, offset=offset, bound=bound)", "title": ""}
{"_id": "d8869", "text": "def parse_domain(url):\n    \"\"\" parse the domain from the url \"\"\"\n    domain_match = lib.DOMAIN_REGEX.match(url)\n    if domain_match:\n        return domain_match.group()", "title": ""}
{"_id": "d8870", "text": "def close_all():\n    \"\"\"Close all open/active plotters\"\"\"\n    for key, p in _ALL_PLOTTERS.items():\n        p.close()\n    _ALL_PLOTTERS.clear()\n    return True", "title": ""}
{"_id": "d8871", "text": "def _DateToEpoch(date):\n  \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n  tz_zero = datetime.datetime.utcfromtimestamp(0)\n  diff_sec = int((date - tz_zero).total_seconds())\n  return diff_sec * 1000000", "title": ""}
{"_id": "d8872", "text": "def forget_canvas(canvas):\n    \"\"\" Forget about the given canvas. Used by the canvas when closed.\n    \"\"\"\n    cc = [c() for c in canvasses if c() is not None]\n    while canvas in cc:\n        cc.remove(canvas)\n    canvasses[:] = [weakref.ref(c) for c in cc]", "title": ""}
{"_id": "d8873", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d8874", "text": "def __delitem__(self, key):\n        \"\"\"Remove a variable from this dataset.\n        \"\"\"\n        del self._variables[key]\n        self._coord_names.discard(key)", "title": ""}
{"_id": "d8875", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d8876", "text": "def find_first_number(ll):\n    \"\"\" Returns nr of first entry parseable to float in ll, None otherwise\"\"\"\n    for nr, entry in enumerate(ll):\n        try:\n            float(entry)\n        except (ValueError, TypeError) as e:\n            pass\n        else:\n            return nr\n    return None", "title": ""}
{"_id": "d8877", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d8878", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d8879", "text": "def get_own_ip():\n    \"\"\"Get the host's ip number.\n    \"\"\"\n    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    try:\n        sock.connect((\"8.8.8.8\", 80))\n    except socket.gaierror:\n        ip_ = \"127.0.0.1\"\n    else:\n        ip_ = sock.getsockname()[0]\n    finally:\n        sock.close()\n    return ip_", "title": ""}
{"_id": "d8880", "text": "def load_feature(fname, language):\n    \"\"\" Load and parse a feature file. \"\"\"\n\n    fname = os.path.abspath(fname)\n    feat = parse_file(fname, language)\n    return feat", "title": ""}
{"_id": "d8881", "text": "def get_java_path():\n  \"\"\"Get the path of java executable\"\"\"\n  java_home = os.environ.get(\"JAVA_HOME\")\n  return os.path.join(java_home, BIN_DIR, \"java\")", "title": ""}
{"_id": "d8882", "text": "def is_collection(obj):\n    \"\"\"Tests if an object is a collection.\"\"\"\n\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n\n    if isinstance(obj, basestring):\n        val = False\n\n    return val", "title": ""}
{"_id": "d8883", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d8884", "text": "def cell_ends_with_code(lines):\n    \"\"\"Is the last line of the cell a line with code?\"\"\"\n    if not lines:\n        return False\n    if not lines[-1].strip():\n        return False\n    if lines[-1].startswith('#'):\n        return False\n    return True", "title": ""}
{"_id": "d8885", "text": "def get_last_id(self, cur, table='reaction'):\n        \"\"\"\n        Get the id of the last written row in table\n\n        Parameters\n        ----------\n        cur: database connection().cursor() object\n        table: str\n            'reaction', 'publication', 'publication_system', 'reaction_system'\n\n        Returns: id\n        \"\"\"\n        cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n                    .format(table))\n        result = cur.fetchone()\n        if result is not None:\n            id = result[0]\n        else:\n            id = 0\n        return id", "title": ""}
{"_id": "d8886", "text": "def _get_column_types(self, data):\n        \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n        columns = list(zip_longest(*data))\n        return [self._get_column_type(column) for column in columns]", "title": ""}
{"_id": "d8887", "text": "def get_table_pos(self, tablename):\n        \"\"\"\n        :param str tablename: Name of table to get position of.\n        :return: Upper left (row, col) coordinate of the named table.\n        \"\"\"\n        _table, (row, col) = self.__tables[tablename]\n        return (row, col)", "title": ""}
{"_id": "d8888", "text": "def now(timezone=None):\n    \"\"\"\n    Return a naive datetime object for the given ``timezone``. A ``timezone``\n    is any pytz- like or datetime.tzinfo-like timezone object. If no timezone\n    is given, then UTC is assumed.\n\n    This method is best used with pytz installed::\n\n        pip install pytz\n    \"\"\"\n    d = datetime.datetime.utcnow()\n    if not timezone:\n        return d\n\n    return to_timezone(d, timezone).replace(tzinfo=None)", "title": ""}
{"_id": "d8889", "text": "def l2_norm(arr):\n    \"\"\"\n    The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n    dot product of the vector.\n    \"\"\"\n    arr = np.asarray(arr)\n    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "title": ""}
{"_id": "d8890", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d8891", "text": "def array_size(x, axis):\n  \"\"\"Calculate the size of `x` along `axis` dimensions only.\"\"\"\n  axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)\n  return max(numpy.prod(axis_shape), 1)", "title": ""}
{"_id": "d8892", "text": "def parse_text_to_dict(self, txt):\n        \"\"\" \n        takes a string and parses via NLP, ready for mapping\n        \"\"\"\n        op = {}\n        print('TODO - import NLP, split into verbs / nouns')\n        op['nouns'] = txt\n        op['verbs'] = txt\n        \n        return op", "title": ""}
{"_id": "d8893", "text": "def get_idx_rect(index_list):\n    \"\"\"Extract the boundaries from a list of indexes\"\"\"\n    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\n    return ( min(rows), max(rows), min(cols), max(cols) )", "title": ""}
{"_id": "d8894", "text": "def get_list_dimensions(_list):\n    \"\"\"\n    Takes a nested list and returns the size of each dimension followed\n    by the element type in the list\n    \"\"\"\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []", "title": ""}
{"_id": "d8895", "text": "def download_file_from_bucket(self, bucket, file_path, key):\n        \"\"\" Download file from S3 Bucket \"\"\"\n        with open(file_path, 'wb') as data:\n            self.__s3.download_fileobj(bucket, key, data)\n            return file_path", "title": ""}
{"_id": "d8896", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d8897", "text": "def get_previous_month(self):\n        \"\"\"Returns date range for the previous full month.\"\"\"\n        end = utils.get_month_start() - relativedelta(days=1)\n        end = utils.to_datetime(end)\n        start = utils.get_month_start(end)\n        return start, end", "title": ""}
{"_id": "d8898", "text": "def off(self):\n        \"\"\"Turn off curses\"\"\"\n        self.win.keypad(0)\n        curses.nocbreak()\n        curses.echo()\n        try:\n            curses.curs_set(1)\n        except:\n            pass\n        curses.endwin()", "title": ""}
{"_id": "d8899", "text": "def gday_of_year(self):\n        \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n        return (self.date - dt.date(self.date.year, 1, 1)).days", "title": ""}
{"_id": "d8900", "text": "def send_text(self, text):\n        \"\"\"Send a plain text message to the room.\"\"\"\n        return self.client.api.send_message(self.room_id, text)", "title": ""}
{"_id": "d8901", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d8902", "text": "def me(self):\n        \"\"\"Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.\"\"\"\n        return self.guild.me if self.guild is not None else self.bot.user", "title": ""}
{"_id": "d8903", "text": "def get_shape(self):\n\t\t\"\"\"\n\t\tReturn a tuple of this array's dimensions.  This is done by\n\t\tquerying the Dim children.  Note that once it has been\n\t\tcreated, it is also possible to examine an Array object's\n\t\t.array attribute directly, and doing that is much faster.\n\t\t\"\"\"\n\t\treturn tuple(int(c.pcdata) for c in self.getElementsByTagName(ligolw.Dim.tagName))[::-1]", "title": ""}
{"_id": "d8904", "text": "async def join(self, ctx, *, channel: discord.VoiceChannel):\n        \"\"\"Joins a voice channel\"\"\"\n\n        if ctx.voice_client is not None:\n            return await ctx.voice_client.move_to(channel)\n\n        await channel.connect()", "title": ""}
{"_id": "d8905", "text": "def _lookup_parent(self, cls):\n        \"\"\"Lookup a transitive parent object that is an instance\n            of a given class.\"\"\"\n        codeobj = self.parent\n        while codeobj is not None and not isinstance(codeobj, cls):\n            codeobj = codeobj.parent\n        return codeobj", "title": ""}
{"_id": "d8906", "text": "def _columns_for_table(table_name):\n    \"\"\"\n    Return all of the columns registered for a given table.\n\n    Parameters\n    ----------\n    table_name : str\n\n    Returns\n    -------\n    columns : dict of column wrappers\n        Keys will be column names.\n\n    \"\"\"\n    return {cname: col\n            for (tname, cname), col in _COLUMNS.items()\n            if tname == table_name}", "title": ""}
{"_id": "d8907", "text": "def _run_cmd_get_output(cmd):\n    \"\"\"Runs a shell command, returns console output.\n\n    Mimics python3's subprocess.getoutput\n    \"\"\"\n    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n    out, err = process.communicate()\n    return out or err", "title": ""}
{"_id": "d8908", "text": "def _run_cmd_get_output(cmd):\n    \"\"\"Runs a shell command, returns console output.\n\n    Mimics python3's subprocess.getoutput\n    \"\"\"\n    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n    out, err = process.communicate()\n    return out or err", "title": ""}
{"_id": "d8909", "text": "def cpp_prog_builder(build_context, target):\n    \"\"\"Build a C++ binary executable\"\"\"\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)", "title": ""}
{"_id": "d8910", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d8911", "text": "def method_header(method_name, nogil=False, idx_as_arg=False):\n    \"\"\"Returns the Cython method header for methods without arguments except\n    `self`.\"\"\"\n    if not config.FASTCYTHON:\n        nogil = False\n    header = 'cpdef inline void %s(self' % method_name\n    header += ', int idx)' if idx_as_arg else ')'\n    header += ' nogil:' if nogil else ':'\n    return header", "title": ""}
{"_id": "d8912", "text": "def grandparent_path(self):\n        \"\"\" return grandparent's path string \"\"\"\n        return os.path.basename(os.path.join(self.path, '../..'))", "title": ""}
{"_id": "d8913", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d8914", "text": "def grandparent_path(self):\n        \"\"\" return grandparent's path string \"\"\"\n        return os.path.basename(os.path.join(self.path, '../..'))", "title": ""}
{"_id": "d8915", "text": "def bulk_query(self, query, *multiparams):\n        \"\"\"Bulk insert or update.\"\"\"\n\n        with self.get_connection() as conn:\n            conn.bulk_query(query, *multiparams)", "title": ""}
{"_id": "d8916", "text": "def read(filename):\n    \"\"\"Read and return `filename` in root dir of project and return string\"\"\"\n    return codecs.open(os.path.join(__DIR__, filename), 'r').read()", "title": ""}
{"_id": "d8917", "text": "def match_aspect_to_viewport(self):\n        \"\"\"Updates Camera.aspect to match the viewport's aspect ratio.\"\"\"\n        viewport = self.viewport\n        self.aspect = float(viewport.width) / viewport.height", "title": ""}
{"_id": "d8918", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d8919", "text": "def paint_cube(self, x, y):\n        \"\"\"\n        Paints a cube at a certain position a color.\n\n        Parameters\n        ----------\n        x: int\n            Horizontal position of the upper left corner of the cube.\n        y: int\n            Vertical position of the upper left corner of the cube.\n\n        \"\"\"\n        # get the color\n        color = self.next_color()\n        # calculate the position\n        cube_pos = [x, y, x + self.cube_size, y + self.cube_size]\n        # draw the cube\n        draw = ImageDraw.Draw(im=self.image)\n        draw.rectangle(xy=cube_pos, fill=color)", "title": ""}
{"_id": "d8920", "text": "def get_memory_usage():\n    \"\"\"Gets RAM memory usage\n\n    :return: MB of memory used by this process\n    \"\"\"\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info().rss\n    return mem / (1024 * 1024)", "title": ""}
{"_id": "d8921", "text": "def dict_to_querystring(dictionary):\n    \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\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]", "title": ""}
{"_id": "d8922", "text": "def extract_module_locals(depth=0):\n    \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n    f = sys._getframe(depth + 1)\n    global_ns = f.f_globals\n    module = sys.modules[global_ns['__name__']]\n    return (module, f.f_locals)", "title": ""}
{"_id": "d8923", "text": "def set_property(self, key, value):\n        \"\"\"\n        Update only one property in the dict\n        \"\"\"\n        self.properties[key] = value\n        self.sync_properties()", "title": ""}
{"_id": "d8924", "text": "def __absolute__(self, uri):\n        \"\"\" Get the absolute uri for a file\n\n        :param uri: URI of the resource to be retrieved\n        :return: Absolute Path\n        \"\"\"\n        return op.abspath(op.join(self.__path__, uri))", "title": ""}
{"_id": "d8925", "text": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "title": ""}
{"_id": "d8926", "text": "def read_corpus(file_name):\n    \"\"\"\n    Read and return the data from a corpus json file.\n    \"\"\"\n    with io.open(file_name, encoding='utf-8') as data_file:\n        return yaml.load(data_file)", "title": ""}
{"_id": "d8927", "text": "def _delete_whitespace(self):\n        \"\"\"Delete all whitespace from the end of the line.\"\"\"\n        while isinstance(self._lines[-1], (self._Space, self._LineBreak,\n                                           self._Indent)):\n            del self._lines[-1]", "title": ""}
{"_id": "d8928", "text": "def disassemble_file(filename, outstream=None):\n    \"\"\"\n    disassemble Python byte-code file (.pyc)\n\n    If given a Python source file (\".py\") file, we'll\n    try to find the corresponding compiled object.\n    \"\"\"\n    filename = check_object_path(filename)\n    (version, timestamp, magic_int, co, is_pypy,\n     source_size) = load_module(filename)\n    if type(co) == list:\n        for con in co:\n            disco(version, con, outstream)\n    else:\n        disco(version, co, outstream, is_pypy=is_pypy)\n    co = None", "title": ""}
{"_id": "d8929", "text": "def percentile_index(a, q):\n    \"\"\"\n    Returns the index of the value at the Qth percentile in array a.\n    \"\"\"\n    return np.where(\n        a==np.percentile(a, q, interpolation='nearest')\n    )[0][0]", "title": ""}
{"_id": "d8930", "text": "def find_mapping(es_url, index):\n    \"\"\" Find the mapping given an index \"\"\"\n\n    mapping = None\n\n    backend = find_perceval_backend(es_url, index)\n\n    if backend:\n        mapping = backend.get_elastic_mappings()\n\n    if mapping:\n        logging.debug(\"MAPPING FOUND:\\n%s\", json.dumps(json.loads(mapping['items']), indent=True))\n    return mapping", "title": ""}
{"_id": "d8931", "text": "def get_value(key, obj, default=missing):\n    \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n    if isinstance(key, int):\n        return _get_value_for_key(key, obj, default)\n    return _get_value_for_keys(key.split('.'), obj, default)", "title": ""}
{"_id": "d8932", "text": "def get_model_index_properties(instance, index):\n    \"\"\"Return the list of properties specified for a model in an index.\"\"\"\n    mapping = get_index_mapping(index)\n    doc_type = instance._meta.model_name.lower()\n    return list(mapping[\"mappings\"][doc_type][\"properties\"].keys())", "title": ""}
{"_id": "d8933", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d8934", "text": "def scan(client, query=None, scroll='5m', raise_on_error=True,\n         preserve_order=False, size=1000, **kwargs):\n    \"\"\"\n    Simple abstraction on top of the\n    :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that\n    yields all hits as returned by underlining scroll requests.\n    By default scan does not return results in any pre-determined order. To\n    have a standard order in the returned documents (either by score or\n    explicit sort definition) when scrolling, use ``preserve_order=True``. This\n    may be an expensive operation and will negate the performance benefits of\n    using ``scan``.\n    :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n    :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api\n    :arg scroll: Specify how long a consistent view of the index should be\n        maintained for scrolled search\n    :arg raise_on_error: raises an exception (``ScanError``) if an error is\n        encountered (some shards fail to execute). By default we raise.\n    :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will\n        cause the scroll to paginate with preserving the order. Note that this\n        can be an extremely expensive operation and can easily lead to\n        unpredictable results, use with caution.\n    :arg size: size (per shard) of the batch send at each iteration.\n    Any additional keyword arguments will be passed to the initial\n    :meth:`~elasticsearch.Elasticsearch.search` call::\n        scan(es,\n            query={\"query\": {\"match\": {\"title\": \"python\"}}},\n            index=\"orders-*\",\n            doc_type=\"books\"\n        )\n    \"\"\"\n    if not preserve_order:\n        kwargs['search_type'] = 'scan'\n    # initial search\n    resp = client.search(body=query, scroll=scroll, size=size, **kwargs)\n\n    scroll_id = resp.get('_scroll_id')\n    if scroll_id is None:\n        return\n\n    first_run = True\n    while True:\n        # if we didn't set search_type to scan initial search contains data\n        if preserve_order and first_run:\n            first_run = False\n        else:\n            resp = client.scroll(scroll_id, scroll=scroll)\n\n        for hit in resp['hits']['hits']:\n            yield hit\n\n        # check if we have any errrors\n        if resp[\"_shards\"][\"failed\"]:\n            logger.warning(\n                'Scroll request has failed on %d shards out of %d.',\n                resp['_shards']['failed'], resp['_shards']['total']\n            )\n            if raise_on_error:\n                raise ScanError(\n                    'Scroll request has failed on %d shards out of %d.' %\n                    (resp['_shards']['failed'], resp['_shards']['total'])\n                )\n\n        scroll_id = resp.get('_scroll_id')\n        # end of scroll\n        if scroll_id is None or not resp['hits']['hits']:\n            break", "title": ""}
{"_id": "d8935", "text": "def get_var(self, name):\n        \"\"\" Returns the variable set with the given name.\n        \"\"\"\n        for var in self.vars:\n            if var.name == name:\n                return var\n        else:\n            raise ValueError", "title": ""}
{"_id": "d8936", "text": "def disable_stdout_buffering():\n    \"\"\"This turns off stdout buffering so that outputs are immediately\n    materialized and log messages show up before the program exits\"\"\"\n    stdout_orig = sys.stdout\n    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n    # NOTE(brandyn): This removes the original stdout\n    return stdout_orig", "title": ""}
{"_id": "d8937", "text": "def _get_var_from_string(item):\n    \"\"\" Get resource variable. \"\"\"\n    modname, varname = _split_mod_var_names(item)\n    if modname:\n        mod = __import__(modname, globals(), locals(), [varname], -1)\n        return getattr(mod, varname)\n    else:\n        return globals()[varname]", "title": ""}
{"_id": "d8938", "text": "def adjust_bounding_box(bbox):\n    \"\"\"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.\n    \"\"\"\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", "title": ""}
{"_id": "d8939", "text": "def var(series):\n    \"\"\"\n    Returns the variance of values in a series.\n\n    Args:\n        series (pandas.Series): column to summarize.\n    \"\"\"\n    if np.issubdtype(series.dtype, np.number):\n        return series.var()\n    else:\n        return np.nan", "title": ""}
{"_id": "d8940", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d8941", "text": "def get_nt_system_uid():\n    \"\"\"Get the MachineGuid from\n    HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Cryptography\\MachineGuid\n    \"\"\"\n    try:\n        import _winreg as winreg\n    except ImportError:\n        import winreg\n    lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\n    try:\n        key = winreg.OpenKey(lm, r\"Software\\Microsoft\\Cryptography\")\n        try:\n            return winreg.QueryValueEx(key, \"MachineGuid\")[0]\n        finally:\n            key.Close()\n    finally:\n        lm.Close()", "title": ""}
{"_id": "d8942", "text": "def quote(s, unsafe='/'):\n    \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n    encoded value as the value.\"\"\"\n    res = s.replace('%', '%25')\n    for c in unsafe:\n        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n    return res", "title": ""}
{"_id": "d8943", "text": "def _gevent_patch():\n    \"\"\"Patch the modules with gevent\n\n    :return: Default is GEVENT. If it not supports gevent then return MULTITHREAD\n    :rtype: int\n    \"\"\"\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()  # Must patch before get_photos_info\n        return GEVENT", "title": ""}
{"_id": "d8944", "text": "def get_value(self, context):\n        \"\"\"Run python eval on the input string.\"\"\"\n        if self.value:\n            return expressions.eval_string(self.value, context)\n        else:\n            # Empty input raises cryptic EOF syntax err, this more human\n            # friendly\n            raise ValueError('!py string expression is empty. It must be a '\n                             'valid python expression instead.')", "title": ""}
{"_id": "d8945", "text": "def _spawn(self, func, *args, **kwargs):\n        \"\"\"Spawn a handler function.\n\n        Spawns the supplied ``func`` with ``*args`` and ``**kwargs``\n        as a gevent greenlet.\n\n        :param func: A callable to call.\n        :param args: Arguments to ``func``.\n        :param kwargs: Keyword arguments to ``func``.\n        \"\"\"\n        gevent.spawn(func, *args, **kwargs)", "title": ""}
{"_id": "d8946", "text": "def get_code_language(self):\n        \"\"\"\n        This is largely copied from bokeh.sphinxext.bokeh_plot.run\n        \"\"\"\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\"]", "title": ""}
{"_id": "d8947", "text": "def set(self):\n        \"\"\"Set the color as current OpenGL color\n        \"\"\"\n        glColor4f(self.r, self.g, self.b, self.a)", "title": ""}
{"_id": "d8948", "text": "def version_triple(tag):\n    \"\"\"\n    returns: a triple of integers from a version tag\n    \"\"\"\n    groups = re.match(r'v?(\\d+)\\.(\\d+)\\.(\\d+)', tag).groups()\n    return tuple(int(n) for n in groups)", "title": ""}
{"_id": "d8949", "text": "def get_file_md5sum(path):\n    \"\"\"Calculate the MD5 hash for a file.\"\"\"\n    with open(path, 'rb') as fh:\n        h = str(hashlib.md5(fh.read()).hexdigest())\n    return h", "title": ""}
{"_id": "d8950", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d8951", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d8952", "text": "def _listify(collection):\n        \"\"\"This is a workaround where Collections are no longer iterable\n        when using JPype.\"\"\"\n        new_list = []\n        for index in range(len(collection)):\n            new_list.append(collection[index])\n        return new_list", "title": ""}
{"_id": "d8953", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d8954", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d8955", "text": "def url_to_image(url):\n    \"\"\"\n    Fetch an image from url and convert it into a Pillow Image object\n    \"\"\"\n    r = requests.get(url)\n    image = StringIO(r.content)\n    return image", "title": ""}
{"_id": "d8956", "text": "def file_matches(filename, patterns):\n    \"\"\"Does this filename match any of the patterns?\"\"\"\n    return any(fnmatch.fnmatch(filename, pat) for pat in patterns)", "title": ""}
{"_id": "d8957", "text": "def wget(url):\n    \"\"\"\n    Download the page into a string\n    \"\"\"\n    import urllib.parse\n    request = urllib.request.urlopen(url)\n    filestring = request.read()\n    return filestring", "title": ""}
{"_id": "d8958", "text": "def fill_nulls(self, col: str):\n        \"\"\"\n        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\")``\n        \"\"\"\n        n = [None, \"\"]\n        try:\n            self.df[col] = self.df[col].replace(n, nan)\n        except Exception as e:\n            self.err(e)", "title": ""}
{"_id": "d8959", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d8960", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d8961", "text": "def title(msg):\n    \"\"\"Sets the title of the console window.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "title": ""}
{"_id": "d8962", "text": "def _maybe_fill(arr, fill_value=np.nan):\n    \"\"\"\n    if we have a compatible fill_value and arr dtype, then fill\n    \"\"\"\n    if _isna_compat(arr, fill_value):\n        arr.fill(fill_value)\n    return arr", "title": ""}
{"_id": "d8963", "text": "def hamming(s, t):\n    \"\"\"\n    Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.\n\n    :param s: string 1\n    :type s: str\n    :param t: string 2\n    :type s: str\n    :return: Hamming distance\n    :rtype: float\n    \"\"\"\n    if len(s) != len(t):\n        raise ValueError('Hamming distance needs strings of equal length.')\n    return sum(s_ != t_ for s_, t_ in zip(s, t))", "title": ""}
{"_id": "d8964", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d8965", "text": "def double_sha256(data):\n    \"\"\"A standard compound hash.\"\"\"\n    return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())", "title": ""}
{"_id": "d8966", "text": "def get_abi3_suffix():\n    \"\"\"Return the file extension for an abi3-compliant Extension()\"\"\"\n    for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION):\n        if '.abi3' in suffix:  # Unix\n            return suffix\n        elif suffix == '.pyd':  # Windows\n            return suffix", "title": ""}
{"_id": "d8967", "text": "def np_hash(a):\n    \"\"\"Return a hash of a NumPy array.\"\"\"\n    if a is None:\n        return hash(None)\n    # Ensure that hashes are equal whatever the ordering in memory (C or\n    # Fortran)\n    a = np.ascontiguousarray(a)\n    # Compute the digest and return a decimal int\n    return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)", "title": ""}
{"_id": "d8968", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d8969", "text": "def get_h5file(file_path, mode='r'):\n    \"\"\" Return the h5py.File given its file path.\n\n    Parameters\n    ----------\n    file_path: string\n        HDF5 file path\n\n    mode: string\n        r   Readonly, file must exist\n        r+  Read/write, file must exist\n        w   Create file, truncate if exists\n        w-  Create file, fail if exists\n        a   Read/write if exists, create otherwise (default)\n\n    Returns\n    -------\n    h5file: h5py.File\n    \"\"\"\n    if not op.exists(file_path):\n        raise IOError('Could not find file {}.'.format(file_path))\n\n    try:\n        h5file = h5py.File(file_path, mode=mode)\n    except:\n        raise\n    else:\n        return h5file", "title": ""}
{"_id": "d8970", "text": "def findMax(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMax(arr, out)\n    return out", "title": ""}
{"_id": "d8971", "text": "def osx_clipboard_get():\n    \"\"\" Get the clipboard's text on OS X.\n    \"\"\"\n    p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n        stdout=subprocess.PIPE)\n    text, stderr = p.communicate()\n    # Text comes in with old Mac \\r line endings. Change them to \\n.\n    text = text.replace('\\r', '\\n')\n    return text", "title": ""}
{"_id": "d8972", "text": "def median(data):\n    \"\"\"Calculate the median of a list.\"\"\"\n    data.sort()\n    num_values = len(data)\n    half = num_values // 2\n    if num_values % 2:\n        return data[half]\n    return 0.5 * (data[half-1] + data[half])", "title": ""}
{"_id": "d8973", "text": "def _mean_dict(dict_list):\n    \"\"\"Compute the mean value across a list of dictionaries\n    \"\"\"\n    return {k: np.array([d[k] for d in dict_list]).mean()\n            for k in dict_list[0].keys()}", "title": ""}
{"_id": "d8974", "text": "def uniquify_list(L):\n    \"\"\"Same order unique list using only a list compression.\"\"\"\n    return [e for i, e in enumerate(L) if L.index(e) == i]", "title": ""}
{"_id": "d8975", "text": "def distance_matrix(trains1, trains2, cos, tau):\n    \"\"\"\n    Return the *bipartite* (rectangular) distance matrix between the observations in the first and the second list.\n\n    Convenience function; equivalent to ``dissimilarity_matrix(trains1, trains2, cos, tau, \"distance\")``. Refer to :func:`pymuvr.dissimilarity_matrix` for full documentation.\n    \"\"\"\n    return dissimilarity_matrix(trains1, trains2, cos, tau, \"distance\")", "title": ""}
{"_id": "d8976", "text": "def fit_gaussian(x, y, yerr, p0):\n    \"\"\" Fit a Gaussian to the data \"\"\"\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", "title": ""}
{"_id": "d8977", "text": "def save_partial(self, obj):\n        \"\"\"Partial objects do not serialize correctly in python2.x -- this fixes the bugs\"\"\"\n        self.save_reduce(_genpartial, (obj.func, obj.args, obj.keywords))", "title": ""}
{"_id": "d8978", "text": "def _none_value(self):\n        \"\"\"Get an appropriate \"null\" value for this field's type. This\n        is used internally when setting the field to None.\n        \"\"\"\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''", "title": ""}
{"_id": "d8979", "text": "def perform_permissions_check(self, user, obj, perms):\n        \"\"\" Performs the permission check. \"\"\"\n        return self.request.forum_permission_handler.can_download_files(obj, user)", "title": ""}
{"_id": "d8980", "text": "def safe_quotes(text, escape_single_quotes=False):\n    \"\"\"htmlify string\"\"\"\n    if isinstance(text, str):\n        safe_text = text.replace('\"', \"&quot;\")\n        if escape_single_quotes:\n            safe_text = safe_text.replace(\"'\", \"&#92;'\")\n        return safe_text.replace('True', 'true')\n    return text", "title": ""}
{"_id": "d8981", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d8982", "text": "def serialize(self):\n        \"\"\"Serialize the query to a structure using the query DSL.\"\"\"\n        data = {'doc': self.doc}\n        if isinstance(self.query, Query):\n            data['query'] = self.query.serialize()\n        return data", "title": ""}
{"_id": "d8983", "text": "def we_are_in_lyon():\n    \"\"\"Check if we are on a Lyon machine\"\"\"\n    import socket\n    try:\n        hostname = socket.gethostname()\n        ip = socket.gethostbyname(hostname)\n    except socket.gaierror:\n        return False\n    return ip.startswith(\"134.158.\")", "title": ""}
{"_id": "d8984", "text": "def glr_path_static():\n    \"\"\"Returns path to packaged static files\"\"\"\n    return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))", "title": ""}
{"_id": "d8985", "text": "def check_if_branch_exist(db, root_hash, key_prefix):\n    \"\"\"\n    Given a key prefix, return whether this prefix is\n    the prefix of an existing key in the trie.\n    \"\"\"\n    validate_is_bytes(key_prefix)\n\n    return _check_if_branch_exist(db, root_hash, encode_to_bin(key_prefix))", "title": ""}
{"_id": "d8986", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d8987", "text": "def is_valid_image_extension(file_path):\n    \"\"\"is_valid_image_extension.\"\"\"\n    valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']\n    _, extension = os.path.splitext(file_path)\n    return extension.lower() in valid_extensions", "title": ""}
{"_id": "d8988", "text": "def min_values(args):\n    \"\"\" Return possible range for min function. \"\"\"\n    return Interval(min(x.low for x in args), min(x.high for x in args))", "title": ""}
{"_id": "d8989", "text": "def has_value_name(self, name):\n        \"\"\"Check if this `enum` has a particular name among its values.\n\n        :param name: Enumeration value name\n        :type name: str\n        :rtype: True if there is an enumeration value with the given name\n        \"\"\"\n        for val, _ in self._values:\n            if val == name:\n                return True\n        return False", "title": ""}
{"_id": "d8990", "text": "def best(self):\n        \"\"\"\n        Returns the element with the highest probability.\n        \"\"\"\n        b = (-1e999999, None)\n        for k, c in iteritems(self.counts):\n            b = max(b, (c, k))\n        return b[1]", "title": ""}
{"_id": "d8991", "text": "def is_callable(*p):\n    \"\"\" True if all the args are functions and / or subroutines\n    \"\"\"\n    import symbols\n    return all(isinstance(x, symbols.FUNCTION) for x in p)", "title": ""}
{"_id": "d8992", "text": "def ensure_dtype_float(x, default=np.float64):\n    r\"\"\"Makes sure that x is type of float\n\n    \"\"\"\n    if isinstance(x, np.ndarray):\n        if x.dtype.kind == 'f':\n            return x\n        elif x.dtype.kind == 'i':\n            return x.astype(default)\n        else:\n            raise TypeError('x is of type '+str(x.dtype)+' that cannot be converted to float')\n    else:\n        raise TypeError('x is not an array')", "title": ""}
{"_id": "d8993", "text": "def get_file_extension_type(filename):\n    \"\"\"\n    Return the group associated to the file\n    :param filename:\n    :return: str\n    \"\"\"\n    ext = get_file_extension(filename)\n    if ext:\n        for name, group in EXTENSIONS.items():\n            if ext in group:\n                return name\n    return \"OTHER\"", "title": ""}
{"_id": "d8994", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d8995", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d8996", "text": "def go_to_background():\n    \"\"\" Daemonize the running process. \"\"\"\n    try:\n        if os.fork():\n            sys.exit()\n    except OSError as errmsg:\n        LOGGER.error('Fork failed: {0}'.format(errmsg))\n        sys.exit('Fork failed')", "title": ""}
{"_id": "d8997", "text": "def get_file_md5sum(path):\n    \"\"\"Calculate the MD5 hash for a file.\"\"\"\n    with open(path, 'rb') as fh:\n        h = str(hashlib.md5(fh.read()).hexdigest())\n    return h", "title": ""}
{"_id": "d8998", "text": "def go_to_background():\n    \"\"\" Daemonize the running process. \"\"\"\n    try:\n        if os.fork():\n            sys.exit()\n    except OSError as errmsg:\n        LOGGER.error('Fork failed: {0}'.format(errmsg))\n        sys.exit('Fork failed')", "title": ""}
{"_id": "d8999", "text": "def generate_uuid():\n    \"\"\"Generate a UUID.\"\"\"\n    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)\n    return r_uuid.decode().replace('=', '')", "title": ""}
{"_id": "d9000", "text": "def to_json(data):\n    \"\"\"Return data as a JSON string.\"\"\"\n    return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)", "title": ""}
{"_id": "d9001", "text": "def check_color(cls, raw_image):\n        \"\"\"\n        Just check if raw_image is completely white.\n        http://stackoverflow.com/questions/14041562/python-pil-detect-if-an-image-is-completely-black-or-white\n        \"\"\"\n        # sum(img.convert(\"L\").getextrema()) in (0, 2)\n        extrema = raw_image.convert(\"L\").getextrema()\n        if extrema == (255, 255): # all white\n            raise cls.MonoImageException", "title": ""}
{"_id": "d9002", "text": "def __str__(self):\n    \"\"\"Returns a pretty-printed string for this object.\"\"\"\n    return 'Output name: \"%s\" watts: %d type: \"%s\" id: %d' % (\n        self._name, self._watts, self._output_type, self._integration_id)", "title": ""}
{"_id": "d9003", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d9004", "text": "def safe_format(s, **kwargs):\n  \"\"\"\n  :type s str\n  \"\"\"\n  return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))", "title": ""}
{"_id": "d9005", "text": "def download_json(local_filename, url, clobber=False):\n    \"\"\"Download the given JSON file, and pretty-print before we output it.\"\"\"\n    with open(local_filename, 'w') as json_file:\n        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))", "title": ""}
{"_id": "d9006", "text": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d9007", "text": "def _pad(self):\n    \"\"\"Pads the output with an amount of indentation appropriate for the number of open element.\n\n    This method does nothing if the indent value passed to the constructor is falsy.\n    \"\"\"\n    if self._indent:\n      self.whitespace(self._indent * len(self._open_elements))", "title": ""}
{"_id": "d9008", "text": "def start(self):\n        \"\"\"\n        Starts the loop. Calling a running loop is an error.\n        \"\"\"\n        assert not self.has_started(), \"called start() on an active GeventLoop\"\n        self._stop_event = Event()\n        # note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves\n        self._greenlet = gevent.spawn(self._loop)", "title": ""}
{"_id": "d9009", "text": "def give_str(self):\n        \"\"\"\n            Give string representation of the callable.\n        \"\"\"\n        args = self._args[:]\n        kwargs = self._kwargs\n        return self._give_str(args, kwargs)", "title": ""}
{"_id": "d9010", "text": "def handle_whitespace(text):\n    r\"\"\"Handles whitespace cleanup.\n\n    Tabs are \"smartly\" retabbed (see sub_retab). Lines that contain\n    only whitespace are truncated to a single newline.\n    \"\"\"\n    text = re_retab.sub(sub_retab, text)\n    text = re_whitespace.sub('', text).strip()\n    return text", "title": ""}
{"_id": "d9011", "text": "def gday_of_year(self):\n        \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n        return (self.date - dt.date(self.date.year, 1, 1)).days", "title": ""}
{"_id": "d9012", "text": "def imflip(img, direction='horizontal'):\n    \"\"\"Flip an image horizontally or vertically.\n\n    Args:\n        img (ndarray): Image to be flipped.\n        direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n    Returns:\n        ndarray: The flipped image.\n    \"\"\"\n    assert direction in ['horizontal', 'vertical']\n    if direction == 'horizontal':\n        return np.flip(img, axis=1)\n    else:\n        return np.flip(img, axis=0)", "title": ""}
{"_id": "d9013", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d9014", "text": "def robust_int(v):\n    \"\"\"Parse an int robustly, ignoring commas and other cruft. \"\"\"\n\n    if isinstance(v, int):\n        return v\n\n    if isinstance(v, float):\n        return int(v)\n\n    v = str(v).replace(',', '')\n\n    if not v:\n        return None\n\n    return int(v)", "title": ""}
{"_id": "d9015", "text": "def user_exists(username):\n    \"\"\"Check if a user exists\"\"\"\n    try:\n        pwd.getpwnam(username)\n        user_exists = True\n    except KeyError:\n        user_exists = False\n    return user_exists", "title": ""}
{"_id": "d9016", "text": "def top_level(url, fix_protocol=True):\n    \"\"\"Extract the top level domain from an URL.\"\"\"\n    ext = tld.get_tld(url, fix_protocol=fix_protocol)\n    toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(\n        ext)[0] + ext\n    return toplevel", "title": ""}
{"_id": "d9017", "text": "def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y):\n    \"\"\"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)\n    \"\"\"\n    return image_transform(\n        X,\n        cv2.GaussianBlur,\n        ksize=(ksize_width, ksize_height),\n        sigmaX=sigma_x,\n        sigmaY=sigma_y\n    )", "title": ""}
{"_id": "d9018", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d9019", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d9020", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d9021", "text": "def gen_api_key(username):\n    \"\"\"\n    Create a random API key for a user\n    :param username:\n    :return: Hex encoded SHA512 random string\n    \"\"\"\n    salt = str(os.urandom(64)).encode('utf-8')\n    return hash_password(username, salt)", "title": ""}
{"_id": "d9022", "text": "def normalize(data):\n    \"\"\"Normalize the data to be in the [0, 1] range.\n\n    :param data:\n    :return: normalized data\n    \"\"\"\n    out_data = data.copy()\n\n    for i, sample in enumerate(out_data):\n        out_data[i] /= sum(out_data[i])\n\n    return out_data", "title": ""}
{"_id": "d9023", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d9024", "text": "def restart_program():\n    \"\"\"\n    DOES NOT WORK WELL WITH MOPIDY\n    Hack from\n    https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program\n    to support updating the settings, since mopidy is not able to do that yet\n    Restarts the current program\n    Note: this function does not return. Any cleanup action (like\n    saving data) must be done before calling this function\n    \"\"\"\n\n    python = sys.executable\n    os.execl(python, python, * sys.argv)", "title": ""}
{"_id": "d9025", "text": "def generate_hash(self, length=30):\n        \"\"\" Generate random string of given length \"\"\"\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", "title": ""}
{"_id": "d9026", "text": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"React to a docstring event and append contracts to it.\"\"\"\n    # pylint: disable=unused-argument\n    # pylint: disable=too-many-arguments\n    lines.extend(_format_contracts(what=what, obj=obj))", "title": ""}
{"_id": "d9027", "text": "def get_average_color(colors):\n    \"\"\"Calculate the average color from the list of colors, where each color\n    is a 3-tuple of (r, g, b) values.\n    \"\"\"\n    c = reduce(color_reducer, colors)\n    total = len(colors)\n    return tuple(v / total for v in c)", "title": ""}
{"_id": "d9028", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d9029", "text": "def get_numbers(s):\n    \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n    result = map(int, re.findall(r'[0-9]+', unicode(s)))\n    return result + [1] * (2 - len(result))", "title": ""}
{"_id": "d9030", "text": "def get_var(self, name):\n        \"\"\" Returns the variable set with the given name.\n        \"\"\"\n        for var in self.vars:\n            if var.name == name:\n                return var\n        else:\n            raise ValueError", "title": ""}
{"_id": "d9031", "text": "def get_numbers(s):\n    \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n    result = map(int, re.findall(r'[0-9]+', unicode(s)))\n    return result + [1] * (2 - len(result))", "title": ""}
{"_id": "d9032", "text": "def __gzip(filename):\n\t\t\"\"\" Compress a file returning the new filename (.gz)\n\t\t\"\"\"\n\t\tzipname = filename + '.gz'\n\t\tfile_pointer = open(filename,'rb')\n\t\tzip_pointer = gzip.open(zipname,'wb')\n\t\tzip_pointer.writelines(file_pointer)\n\t\tfile_pointer.close()\n\t\tzip_pointer.close()\n\t\treturn zipname", "title": ""}
{"_id": "d9033", "text": "def caller_locals():\n    \"\"\"Get the local variables in the caller's frame.\"\"\"\n    import inspect\n    frame = inspect.currentframe()\n    try:\n        return frame.f_back.f_back.f_locals\n    finally:\n        del frame", "title": ""}
{"_id": "d9034", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d9035", "text": "def get_single_item(d):\n    \"\"\"Get an item from a dict which contains just one item.\"\"\"\n    assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)\n    return next(six.iteritems(d))", "title": ""}
{"_id": "d9036", "text": "def type_converter(text):\n    \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n    if text.isdigit():\n        return int(text), int\n\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE", "title": ""}
{"_id": "d9037", "text": "def find_console_handler(logger):\n    \"\"\"Return a stream handler, if it exists.\"\"\"\n    for handler in logger.handlers:\n        if (isinstance(handler, logging.StreamHandler) and\n                handler.stream == sys.stderr):\n            return handler", "title": ""}
{"_id": "d9038", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d9039", "text": "def calc_list_average(l):\n    \"\"\"\n    Calculates the average value of a list of numbers\n    Returns a float\n    \"\"\"\n    total = 0.0\n    for value in l:\n        total += value\n    return total / len(l)", "title": ""}
{"_id": "d9040", "text": "def is_readable(fp, size=1):\n    \"\"\"\n    Check if the file-like object is readable.\n\n    :param fp: file-like object\n    :param size: byte size\n    :return: bool\n    \"\"\"\n    read_size = len(fp.read(size))\n    fp.seek(-read_size, 1)\n    return read_size == size", "title": ""}
{"_id": "d9041", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d9042", "text": "def get_last_modified_timestamp(self):\n        \"\"\"\n        Looks at the files in a git root directory and grabs the last modified timestamp\n        \"\"\"\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", "title": ""}
{"_id": "d9043", "text": "def get_base_dir():\n    \"\"\"\n    Return the base directory\n    \"\"\"\n    return os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]", "title": ""}
{"_id": "d9044", "text": "def get_neg_infinity(dtype):\n    \"\"\"Return an appropriate positive infinity for this dtype.\n\n    Parameters\n    ----------\n    dtype : np.dtype\n\n    Returns\n    -------\n    fill_value : positive infinity value corresponding to this dtype.\n    \"\"\"\n    if issubclass(dtype.type, (np.floating, np.integer)):\n        return -np.inf\n\n    if issubclass(dtype.type, np.complexfloating):\n        return -np.inf - 1j * np.inf\n\n    return NINF", "title": ""}
{"_id": "d9045", "text": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "title": ""}
{"_id": "d9046", "text": "def __repr__(self):\n    \"\"\"Returns a stringified representation of this object.\"\"\"\n    return str({'name': self._name, 'watts': self._watts,\n                'type': self._output_type, 'id': self._integration_id})", "title": ""}
{"_id": "d9047", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d9048", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d9049", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d9050", "text": "def inpaint(self):\n        \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n        import inpaint\n        filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n        self.raster_data = np.ma.masked_invalid(filled)", "title": ""}
{"_id": "d9051", "text": "def filter_contour(imageFile, opFile):\n    \"\"\" convert an image by applying a contour \"\"\"\n    im = Image.open(imageFile)\n    im1 = im.filter(ImageFilter.CONTOUR)\n    im1.save(opFile)", "title": ""}
{"_id": "d9052", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d9053", "text": "def bbox(img):\n    \"\"\"Find the bounding box around nonzero elements in the given array\n\n    Copied from https://stackoverflow.com/a/31402351/5703449 .\n\n    Returns:\n        rowmin, rowmax, colmin, colmax\n    \"\"\"\n    rows = np.any(img, axis=1)\n    cols = np.any(img, axis=0)\n    rmin, rmax = np.where(rows)[0][[0, -1]]\n    cmin, cmax = np.where(cols)[0][[0, -1]]\n\n    return rmin, rmax, cmin, cmax", "title": ""}
{"_id": "d9054", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d9055", "text": "def get_week_start_end_day():\n    \"\"\"\n    Get the week start date and end date\n    \"\"\"\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))", "title": ""}
{"_id": "d9056", "text": "def printdict(adict):\n    \"\"\"printdict\"\"\"\n    dlist = list(adict.keys())\n    dlist.sort()\n    for i in range(0, len(dlist)):\n        print(dlist[i], adict[dlist[i]])", "title": ""}
{"_id": "d9057", "text": "def _get_session():\n    \"\"\"Return (and memoize) a database session\"\"\"\n    session = getattr(g, '_session', None)\n    if session is None:\n        session = g._session = db.session()\n    return session", "title": ""}
{"_id": "d9058", "text": "def redirect_output(fileobj):\n    \"\"\"Redirect standard out to file.\"\"\"\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old", "title": ""}
{"_id": "d9059", "text": "def _nth(arr, n):\n    \"\"\"\n    Return the nth value of array\n\n    If it is missing return NaN\n    \"\"\"\n    try:\n        return arr.iloc[n]\n    except (KeyError, IndexError):\n        return np.nan", "title": ""}
{"_id": "d9060", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d9061", "text": "def remove_ext(fname):\n    \"\"\"Removes the extension from a filename\n    \"\"\"\n    bn = os.path.basename(fname)\n    return os.path.splitext(bn)[0]", "title": ""}
{"_id": "d9062", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d9063", "text": "def _file_type(self, field):\n        \"\"\" Returns file type for given file field.\n        \n        Args:\n            field (str): File field\n\n        Returns:\n            string. File type\n        \"\"\"\n        type = mimetypes.guess_type(self._files[field])[0]\n        return type.encode(\"utf-8\") if isinstance(type, unicode) else str(type)", "title": ""}
{"_id": "d9064", "text": "def save_pdf(path):\n  \"\"\"\n  Saves a pdf of the current matplotlib figure.\n\n  :param path: str, filepath to save to\n  \"\"\"\n\n  pp = PdfPages(path)\n  pp.savefig(pyplot.gcf())\n  pp.close()", "title": ""}
{"_id": "d9065", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d9066", "text": "def download_file(save_path, file_url):\n    \"\"\" Download file from http url link \"\"\"\n\n    r = requests.get(file_url)  # create HTTP response object\n\n    with open(save_path, 'wb') as f:\n        f.write(r.content)\n\n    return save_path", "title": ""}
{"_id": "d9067", "text": "def get_X0(X):\n    \"\"\" Return zero-th element of a one-element data container.\n    \"\"\"\n    if pandas_available and isinstance(X, pd.DataFrame):\n        assert len(X) == 1\n        x = np.array(X.iloc[0])\n    else:\n        x, = X\n    return x", "title": ""}
{"_id": "d9068", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d9069", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d9070", "text": "def enable_proxy(self, host, port):\n        \"\"\"Enable a default web proxy\"\"\"\n\n        self.proxy = [host, _number(port)]\n        self.proxy_enabled = True", "title": ""}
{"_id": "d9071", "text": "def __getitem__(self, index):\n    \"\"\"Get the item at the given index.\n\n    Index is a tuple of (row, col)\n    \"\"\"\n    row, col = index\n    return self.rows[row][col]", "title": ""}
{"_id": "d9072", "text": "def onkeyup(self, key, keycode, ctrl, shift, alt):\n        \"\"\"Called when user types and releases a key. \n        The widget should be able to receive the focus in order to emit the event.\n        Assign a 'tabindex' attribute to make it focusable.\n        \n        Args:\n            key (str): the character value\n            keycode (str): the numeric char code\n        \"\"\"\n        return (key, keycode, ctrl, shift, alt)", "title": ""}
{"_id": "d9073", "text": "def on_train_end(self, logs):\n        \"\"\" Print training time at end of training \"\"\"\n        duration = timeit.default_timer() - self.train_start\n        print('done, took {:.3f} seconds'.format(duration))", "title": ""}
{"_id": "d9074", "text": "def extract_keywords_from_text(self, text):\n        \"\"\"Method to extract keywords from the text provided.\n\n        :param text: Text to extract keywords from, provided as a string.\n        \"\"\"\n        sentences = nltk.tokenize.sent_tokenize(text)\n        self.extract_keywords_from_sentences(sentences)", "title": ""}
{"_id": "d9075", "text": "def pause():\n\t\"\"\"Tell iTunes to pause\"\"\"\n\n\tif not settings.platformCompatible():\n\t\treturn False\n\n\t(output, error) = subprocess.Popen([\"osascript\", \"-e\", PAUSE], stdout=subprocess.PIPE).communicate()", "title": ""}
{"_id": "d9076", "text": "def postprocessor(prediction):\n    \"\"\"Map prediction tensor to labels.\"\"\"\n    prediction = prediction.data.numpy()[0]\n    top_predictions = prediction.argsort()[-3:][::-1]\n    return [labels[prediction] for prediction in top_predictions]", "title": ""}
{"_id": "d9077", "text": "def insort_no_dup(lst, item):\n    \"\"\"\n    If item is not in lst, add item to list at its sorted position\n    \"\"\"\n    import bisect\n    ix = bisect.bisect_left(lst, item)\n    if lst[ix] != item: \n        lst[ix:ix] = [item]", "title": ""}
{"_id": "d9078", "text": "def PopTask(self):\n    \"\"\"Retrieves and removes the first task from the heap.\n\n    Returns:\n      Task: the task or None if the heap is empty.\n    \"\"\"\n    try:\n      _, task = heapq.heappop(self._heap)\n\n    except IndexError:\n      return None\n    self._task_identifiers.remove(task.identifier)\n    return task", "title": ""}
{"_id": "d9079", "text": "def stop(self):\n        \"\"\"Stop the progress bar.\"\"\"\n        if self._progressing:\n            self._progressing = False\n            self._thread.join()", "title": ""}
{"_id": "d9080", "text": "def size_on_disk(self):\n        \"\"\"\n        :return: size of the entire schema in bytes\n        \"\"\"\n        return int(self.connection.query(\n            \"\"\"\n            SELECT SUM(data_length + index_length)\n            FROM information_schema.tables WHERE table_schema='{db}'\n            \"\"\".format(db=self.database)).fetchone()[0])", "title": ""}
{"_id": "d9081", "text": "def yvals(self):\n        \"\"\"All y values\"\"\"\n        return [\n            val[1] for serie in self.series for val in serie.values\n            if val[1] is not None\n        ]", "title": ""}
{"_id": "d9082", "text": "def adapt_array(arr):\n    \"\"\"\n    Adapts a Numpy array into an ARRAY string to put into the database.\n\n    Parameters\n    ----------\n    arr: array\n        The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n    Returns\n    -------\n    ARRAY\n            The adapted array object\n\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr), out.seek(0)\n    return buffer(out.read())", "title": ""}
{"_id": "d9083", "text": "def list_all(dev: Device):\n    \"\"\"List all available API calls.\"\"\"\n    for name, service in dev.services.items():\n        click.echo(click.style(\"\\nService %s\" % name, bold=True))\n        for method in service.methods:\n            click.echo(\"  %s\" % method.name)", "title": ""}
{"_id": "d9084", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d9085", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d9086", "text": "def clean(some_string, uppercase=False):\n    \"\"\"\n    helper to clean up an input string\n    \"\"\"\n    if uppercase:\n        return some_string.strip().upper()\n    else:\n        return some_string.strip().lower()", "title": ""}
{"_id": "d9087", "text": "def best(self):\n        \"\"\"\n        Returns the element with the highest probability.\n        \"\"\"\n        b = (-1e999999, None)\n        for k, c in iteritems(self.counts):\n            b = max(b, (c, k))\n        return b[1]", "title": ""}
{"_id": "d9088", "text": "def add_arrow(self, x1, y1, x2, y2, **kws):\n        \"\"\"add arrow to plot\"\"\"\n        self.panel.add_arrow(x1, y1, x2, y2, **kws)", "title": ""}
{"_id": "d9089", "text": "def timestamp_to_microseconds(timestamp):\n    \"\"\"Convert a timestamp string into a microseconds value\n    :param timestamp\n    :return time in microseconds\n    \"\"\"\n    timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX)\n    epoch_time_secs = calendar.timegm(timestamp_str.timetuple())\n    epoch_time_mus = epoch_time_secs * 1e6 + timestamp_str.microsecond\n    return epoch_time_mus", "title": ""}
{"_id": "d9090", "text": "def __gzip(filename):\n\t\t\"\"\" Compress a file returning the new filename (.gz)\n\t\t\"\"\"\n\t\tzipname = filename + '.gz'\n\t\tfile_pointer = open(filename,'rb')\n\t\tzip_pointer = gzip.open(zipname,'wb')\n\t\tzip_pointer.writelines(file_pointer)\n\t\tfile_pointer.close()\n\t\tzip_pointer.close()\n\t\treturn zipname", "title": ""}
{"_id": "d9091", "text": "def yesno(prompt):\n    \"\"\"Returns True if user answers 'y' \"\"\"\n    prompt += \" [y/n]\"\n    a = \"\"\n    while a not in [\"y\", \"n\"]:\n        a = input(prompt).lower()\n\n    return a == \"y\"", "title": ""}
{"_id": "d9092", "text": "def _nth(arr, n):\n    \"\"\"\n    Return the nth value of array\n\n    If it is missing return NaN\n    \"\"\"\n    try:\n        return arr.iloc[n]\n    except (KeyError, IndexError):\n        return np.nan", "title": ""}
{"_id": "d9093", "text": "def _prepare_proxy(self, conn):\n        \"\"\"\n        Establish tunnel connection early, because otherwise httplib\n        would improperly set Host: header to proxy's IP:port.\n        \"\"\"\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n        conn.connect()", "title": ""}
{"_id": "d9094", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d9095", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d9096", "text": "def last_day(year=_year, month=_month):\n    \"\"\"\n    get the current month's last day\n    :param year:  default to current year\n    :param month:  default to current month\n    :return: month's last day\n    \"\"\"\n    last_day = calendar.monthrange(year, month)[1]\n    return datetime.date(year=year, month=month, day=last_day)", "title": ""}
{"_id": "d9097", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d9098", "text": "def iter_with_last(iterable):\n    \"\"\"\n    :return: generator of tuples (isLastFlag, item)\n    \"\"\"\n    # Ensure it's an iterator and get the first field\n    iterable = iter(iterable)\n    prev = next(iterable)\n    for item in iterable:\n        # Lag by one item so I know I'm not at the end\n        yield False, prev\n        prev = item\n    # Last item\n    yield True, prev", "title": ""}
{"_id": "d9099", "text": "def datetime_to_year_quarter(dt):\n    \"\"\"\n    Args:\n        dt: a datetime\n    Returns:\n        tuple of the datetime's year and quarter\n    \"\"\"\n    year = dt.year\n    quarter = int(math.ceil(float(dt.month)/3))\n    return (year, quarter)", "title": ""}
{"_id": "d9100", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d9101", "text": "def _aggr_mean(inList):\n  \"\"\" Returns mean of non-None elements of the list\n  \"\"\"\n  aggrSum = 0\n  nonNone = 0\n  for elem in inList:\n    if elem != SENTINEL_VALUE_FOR_MISSING_DATA:\n      aggrSum += elem\n      nonNone += 1\n  if nonNone != 0:\n    return aggrSum / nonNone\n  else:\n    return None", "title": ""}
{"_id": "d9102", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d9103", "text": "def find_last_sublist(list_, sublist):\n    \"\"\"Given a list, find the last occurance of a sublist within it.\n\n    Returns:\n        Index where the sublist starts, or None if there is no match.\n    \"\"\"\n    for i in reversed(range(len(list_) - len(sublist) + 1)):\n        if list_[i] == sublist[0] and list_[i:i + len(sublist)] == sublist:\n            return i\n    return None", "title": ""}
{"_id": "d9104", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d9105", "text": "def get_last_or_frame_exception():\n    \"\"\"Intended to be used going into post mortem routines.  If\n    sys.last_traceback is set, we will return that and assume that\n    this is what post-mortem will want. If sys.last_traceback has not\n    been set, then perhaps we *about* to raise an error and are\n    fielding an exception. So assume that sys.exc_info()[2]\n    is where we want to look.\"\"\"\n\n    try:\n        if inspect.istraceback(sys.last_traceback):\n            # We do have a traceback so prefer that.\n            return sys.last_type, sys.last_value, sys.last_traceback\n    except AttributeError:\n        pass\n    return sys.exc_info()", "title": ""}
{"_id": "d9106", "text": "def is_integer(obj):\n    \"\"\"Is this an integer.\n\n    :param object obj:\n    :return:\n    \"\"\"\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))", "title": ""}
{"_id": "d9107", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d9108", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d9109", "text": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "title": ""}
{"_id": "d9110", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d9111", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d9112", "text": "def get_table_columns(dbconn, tablename):\n    \"\"\"\n    Return a list of tuples specifying the column name and type\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n    info = cur.fetchall()\n    cols = [(i[1], i[2]) for i in info]\n    return cols", "title": ""}
{"_id": "d9113", "text": "def readline( file, skip_blank=False ):\n    \"\"\"Read a line from provided file, skipping any blank or comment lines\"\"\"\n    while 1:\n        line = file.readline()\n        #print \"every line: %r\" % line\n        if not line: return None \n        if line[0] != '#' and not ( skip_blank and line.isspace() ):\n            return line", "title": ""}
{"_id": "d9114", "text": "def last(self):\n        \"\"\"Get the last object in file.\"\"\"\n        # End of file\n        self.__file.seek(0, 2)\n\n        # Get the last struct\n        data = self.get(self.length - 1)\n\n        return data", "title": ""}
{"_id": "d9115", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d9116", "text": "def get_last_id(self, cur, table='reaction'):\n        \"\"\"\n        Get the id of the last written row in table\n\n        Parameters\n        ----------\n        cur: database connection().cursor() object\n        table: str\n            'reaction', 'publication', 'publication_system', 'reaction_system'\n\n        Returns: id\n        \"\"\"\n        cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n                    .format(table))\n        result = cur.fetchone()\n        if result is not None:\n            id = result[0]\n        else:\n            id = 0\n        return id", "title": ""}
{"_id": "d9117", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d9118", "text": "def datatype(dbtype, description, cursor):\n    \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n    dt = cursor.db.introspection.get_field_type(dbtype, description)\n    if type(dt) is tuple:\n        return dt[0]\n    else:\n        return dt", "title": ""}
{"_id": "d9119", "text": "def border(self):\n        \"\"\"Region formed by taking border elements.\n\n        :returns: :class:`jicimagelib.region.Region`\n        \"\"\"\n\n        border_array = self.bitmap - self.inner.bitmap\n        return Region(border_array)", "title": ""}
{"_id": "d9120", "text": "def _visual_width(line):\n    \"\"\"Get the the number of columns required to display a string\"\"\"\n\n    return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, \"\", line))", "title": ""}
{"_id": "d9121", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d9122", "text": "def display_pil_image(im):\n   \"\"\"Displayhook function for PIL Images, rendered as PNG.\"\"\"\n   from IPython.core import display\n   b = BytesIO()\n   im.save(b, format='png')\n   data = b.getvalue()\n\n   ip_img = display.Image(data=data, format='png', embed=True)\n   return ip_img._repr_png_()", "title": ""}
{"_id": "d9123", "text": "def getWindowPID(self, hwnd):\n        \"\"\" Gets the process ID that the specified window belongs to \"\"\"\n        pid = ctypes.c_ulong()\n        ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))\n        return int(pid.value)", "title": ""}
{"_id": "d9124", "text": "def set_font_size(self, size):\n        \"\"\"Convenience method for just changing font size.\"\"\"\n        if self.font.font_size == size:\n            pass\n        else:\n            self.font._set_size(size)", "title": ""}
{"_id": "d9125", "text": "def predecessors(self, node, graph=None):\n        \"\"\" Returns a list of all predecessors of the given node \"\"\"\n        if graph is None:\n            graph = self.graph\n        return [key for key in graph if node in graph[key]]", "title": ""}
{"_id": "d9126", "text": "def indent(self):\n        \"\"\"\n        Begins an indented block. Must be used in a 'with' code block.\n        All calls to the logger inside of the block will be indented.\n        \"\"\"\n        blk = IndentBlock(self, self._indent)\n        self._indent += 1\n        return blk", "title": ""}
{"_id": "d9127", "text": "def unique_element(ll):\n    \"\"\" returns unique elements from a list preserving the original order \"\"\"\n    seen = {}\n    result = []\n    for item in ll:\n        if item in seen:\n            continue\n        seen[item] = 1\n        result.append(item)\n    return result", "title": ""}
{"_id": "d9128", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d9129", "text": "def hstrlen(self, name, key):\n        \"\"\"\n        Return the number of bytes stored in the value of ``key``\n        within hash ``name``\n        \"\"\"\n        with self.pipe as pipe:\n            return pipe.hstrlen(self.redis_key(name), key)", "title": ""}
{"_id": "d9130", "text": "def _index_range(self, version, symbol, from_version=None, **kwargs):\n        \"\"\"\n        Tuple describing range to read from the ndarray - closed:open\n        \"\"\"\n        from_index = None\n        if from_version:\n            from_index = from_version['up_to']\n        return from_index, None", "title": ""}
{"_id": "d9131", "text": "def upload_file(token, channel_name, file_name):\n    \"\"\" upload file to a channel \"\"\"\n\n    slack = Slacker(token)\n\n    slack.files.upload(file_name, channels=channel_name)", "title": ""}
{"_id": "d9132", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d9133", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d9134", "text": "def loads(cls, s):\n        \"\"\"\n        Load an instance of this class from YAML.\n\n        \"\"\"\n        with closing(StringIO(s)) as fileobj:\n            return cls.load(fileobj)", "title": ""}
{"_id": "d9135", "text": "def heappush_max(heap, item):\n    \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n    heap.append(item)\n    _siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d9136", "text": "def hamming_distance(str1, str2):\n    \"\"\"Calculate the Hamming distance between two bit strings\n\n    Args:\n        str1 (str): First string.\n        str2 (str): Second string.\n    Returns:\n        int: Distance between strings.\n    Raises:\n        VisualizationError: Strings not same length\n    \"\"\"\n    if len(str1) != len(str2):\n        raise VisualizationError('Strings not same length.')\n    return sum(s1 != s2 for s1, s2 in zip(str1, str2))", "title": ""}
{"_id": "d9137", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d9138", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d9139", "text": "def init_checks_registry():\n    \"\"\"Register all globally visible functions.\n\n    The first argument name is either 'physical_line' or 'logical_line'.\n    \"\"\"\n    mod = inspect.getmodule(register_check)\n    for (name, function) in inspect.getmembers(mod, inspect.isfunction):\n        register_check(function)", "title": ""}
{"_id": "d9140", "text": "def hash_iterable(it):\n\t\"\"\"Perform a O(1) memory hash of an iterable of arbitrary length.\n\n\thash(tuple(it)) creates a temporary tuple containing all values from it\n\twhich could be a problem if it is large.\n\n\tSee discussion at:\n\thttps://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ\n\t\"\"\"\n\thash_value = hash(type(it))\n\tfor value in it:\n\t\thash_value = hash((hash_value, value))\n\treturn hash_value", "title": ""}
{"_id": "d9141", "text": "def _module_name_from_previous_frame(num_frames_back):\n    \"\"\"\n    Returns the module name associated with a frame `num_frames_back` in the\n    call stack. This function adds 1 to account for itself, so `num_frames_back`\n    should be given relative to the caller.\n    \"\"\"\n    frm = inspect.stack()[num_frames_back + 1]\n    return inspect.getmodule(frm[0]).__name__", "title": ""}
{"_id": "d9142", "text": "def _multilingual(function, *args, **kwargs):\n    \"\"\" Returns the value from the function with the given name in the given language module.\n        By default, language=\"en\".\n    \"\"\"\n    return getattr(_module(kwargs.pop(\"language\", \"en\")), function)(*args, **kwargs)", "title": ""}
{"_id": "d9143", "text": "def infer_dtype_from(val, pandas_dtype=False):\n    \"\"\"\n    interpret the dtype from a scalar or array. This is a convenience\n    routines to infer dtype from a scalar or an array\n\n    Parameters\n    ----------\n    pandas_dtype : bool, default False\n        whether to infer dtype including pandas extension types.\n        If False, scalar/array belongs to pandas extension types is inferred as\n        object\n    \"\"\"\n    if is_scalar(val):\n        return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype)\n    return infer_dtype_from_array(val, pandas_dtype=pandas_dtype)", "title": ""}
{"_id": "d9144", "text": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "title": ""}
{"_id": "d9145", "text": "def safe_int(val, default=None):\n    \"\"\"\n    Returns int() of val if val is not convertable to int use default\n    instead\n\n    :param val:\n    :param default:\n    \"\"\"\n\n    try:\n        val = int(val)\n    except (ValueError, TypeError):\n        val = default\n\n    return val", "title": ""}
{"_id": "d9146", "text": "def allele_clusters(dists, t=0.025):\n    \"\"\"Flat clusters from distance matrix\n\n    Args:\n        dists (numpy.array): pdist distance matrix\n        t (float): fcluster (tree cutting) distance threshold\n\n    Returns:\n        dict of lists: cluster number to list of indices of distances in cluster\n    \"\"\"\n    clusters = fcluster(linkage(dists), 0.025, criterion='distance')\n    cluster_idx = defaultdict(list)\n    for idx, cl in enumerate(clusters):\n        cluster_idx[cl].append(idx)\n    return cluster_idx", "title": ""}
{"_id": "d9147", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d9148", "text": "def get_file_size(filename):\n    \"\"\"\n    Get the file size of a given file\n\n    :param filename: string: pathname of a file\n    :return: human readable filesize\n    \"\"\"\n    if os.path.isfile(filename):\n        return convert_size(os.path.getsize(filename))\n    return None", "title": ""}
{"_id": "d9149", "text": "def nearest_intersection_idx(a, b):\n    \"\"\"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.\n\n    \"\"\"\n    # Difference in the two y-value sets\n    difference = a - b\n\n    # Determine the point just before the intersection of the lines\n    # Will return multiple points for multiple intersections\n    sign_change_idx, = np.nonzero(np.diff(np.sign(difference)))\n\n    return sign_change_idx", "title": ""}
{"_id": "d9150", "text": "def magnitude(X):\n    \"\"\"Magnitude of a complex matrix.\"\"\"\n    r = np.real(X)\n    i = np.imag(X)\n    return np.sqrt(r * r + i * i);", "title": ""}
{"_id": "d9151", "text": "def ip_address_list(ips):\n    \"\"\" IP address range validation and expansion. \"\"\"\n    # first, try it as a single IP address\n    try:\n        return ip_address(ips)\n    except ValueError:\n        pass\n    # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it\n    return list(ipaddress.ip_network(u(ips)).hosts())", "title": ""}
{"_id": "d9152", "text": "def write_file(filename, content):\n    \"\"\"Create the file with the given content\"\"\"\n    print 'Generating {0}'.format(filename)\n    with open(filename, 'wb') as out_f:\n        out_f.write(content)", "title": ""}
{"_id": "d9153", "text": "def get_truetype(value):\n    \"\"\"Convert a string to a pythonized parameter.\"\"\"\n    if value in [\"true\", \"True\", \"y\", \"Y\", \"yes\"]:\n        return True\n    if value in [\"false\", \"False\", \"n\", \"N\", \"no\"]:\n        return False\n    if value.isdigit():\n        return int(value)\n    return str(value)", "title": ""}
{"_id": "d9154", "text": "def get_previous_month(self):\n        \"\"\"Returns date range for the previous full month.\"\"\"\n        end = utils.get_month_start() - relativedelta(days=1)\n        end = utils.to_datetime(end)\n        start = utils.get_month_start(end)\n        return start, end", "title": ""}
{"_id": "d9155", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d9156", "text": "def isPackage(file_path):\n    \"\"\"\n    Determine whether or not a given path is a (sub)package or not.\n    \"\"\"\n    return (os.path.isdir(file_path) and\n            os.path.isfile(os.path.join(file_path, '__init__.py')))", "title": ""}
{"_id": "d9157", "text": "def poke_array(self, store, name, elemtype, elements, container, visited, _stack):\n        \"\"\"abstract method\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d9158", "text": "def read_stdin():\n    \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n    if sys.stdin.isatty() and sys.stdout.isatty():\n        print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n    return sys.stdin.read()", "title": ""}
{"_id": "d9159", "text": "def fixed(ctx, number, decimals=2, no_commas=False):\n    \"\"\"\n    Formats the given number in decimal format using a period and commas\n    \"\"\"\n    value = _round(ctx, number, decimals)\n    format_str = '{:f}' if no_commas else '{:,f}'\n    return format_str.format(value)", "title": ""}
{"_id": "d9160", "text": "def __sub__(self, other):\n\t\t\"\"\"\n\t\tReturn a Cache containing the entries of self that are not in other.\n\t\t\"\"\"\n\t\treturn self.__class__([elem for elem in self if elem not in other])", "title": ""}
{"_id": "d9161", "text": "def add_ul(text, ul):\n    \"\"\"Adds an unordered list to the readme\"\"\"\n    text += \"\\n\"\n    for li in ul:\n        text += \"- \" + li + \"\\n\"\n    text += \"\\n\"\n\n    return text", "title": ""}
{"_id": "d9162", "text": "def find_all(self, string, callback):\n\t\t\"\"\"\n\t\tWrapper on iter method, callback gets an iterator result\n\t\t\"\"\"\n\t\tfor index, output in self.iter(string):\n\t\t\tcallback(index, output)", "title": ""}
{"_id": "d9163", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d9164", "text": "def getFunction(self):\n        \"\"\"Called by remote workers. Useful to populate main module globals()\n        for interactive shells. Retrieves the serialized function.\"\"\"\n        return functionFactory(\n            self.code,\n            self.name,\n            self.defaults,\n            self.globals,\n            self.imports,\n        )", "title": ""}
{"_id": "d9165", "text": "def __reversed__(self):\n        \"\"\"\n        Return a reversed iterable over the items in the dictionary. Items are\n        iterated over in their reverse sort order.\n\n        Iterating views while adding or deleting entries in the dictionary may\n        raise a RuntimeError or fail to iterate over all entries.\n        \"\"\"\n        _dict = self._dict\n        return iter((key, _dict[key]) for key in reversed(self._list))", "title": ""}
{"_id": "d9166", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d9167", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d9168", "text": "def _openResources(self):\n        \"\"\" Uses numpy.load to open the underlying file\n        \"\"\"\n        arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n        check_is_an_array(arr)\n        self._array = arr", "title": ""}
{"_id": "d9169", "text": "def _skip_frame(self):\n        \"\"\"Skip a single frame from the trajectory\"\"\"\n        size = self.read_size()\n        for i in range(size+1):\n            line = self._f.readline()\n            if len(line) == 0:\n                raise StopIteration", "title": ""}
{"_id": "d9170", "text": "def get_hline():\n    \"\"\" gets a horiztonal line \"\"\"\n    return Window(\n        width=LayoutDimension.exact(1),\n        height=LayoutDimension.exact(1),\n        content=FillControl('-', token=Token.Line))", "title": ""}
{"_id": "d9171", "text": "def txt_line_iterator(path):\n  \"\"\"Iterate through lines of file.\"\"\"\n  with tf.gfile.Open(path) as f:\n    for line in f:\n      yield line.strip()", "title": ""}
{"_id": "d9172", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d9173", "text": "def load(file_object):\n  \"\"\"\n  Deserializes Java primitive data and objects serialized by ObjectOutputStream\n  from a file-like object.\n  \"\"\"\n  marshaller = JavaObjectUnmarshaller(file_object)\n  marshaller.add_transformer(DefaultObjectTransformer())\n  return marshaller.readObject()", "title": ""}
{"_id": "d9174", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d9175", "text": "def enable_proxy(self, host, port):\n        \"\"\"Enable a default web proxy\"\"\"\n\n        self.proxy = [host, _number(port)]\n        self.proxy_enabled = True", "title": ""}
{"_id": "d9176", "text": "def json_dumps(self, obj):\n        \"\"\"Serializer for consistency\"\"\"\n        return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))", "title": ""}
{"_id": "d9177", "text": "def java_version():\n    \"\"\"Call java and return version information.\n\n    :return unicode: Java version string\n    \"\"\"\n    result = subprocess.check_output(\n        [c.JAVA, '-version'], stderr=subprocess.STDOUT\n    )\n    first_line = result.splitlines()[0]\n    return first_line.decode()", "title": ""}
{"_id": "d9178", "text": "def json_get_data(filename):\n    \"\"\"Get data from json file\n    \"\"\"\n    with open(filename) as fp:\n        json_data = json.load(fp)\n        return json_data\n\n    return False", "title": ""}
{"_id": "d9179", "text": "def respond_redirect(self, location='/'):\n\t\t\"\"\"\n\t\tRespond to the client with a 301 message and redirect them with\n\t\ta Location header.\n\n\t\t:param str location: The new location to redirect the client to.\n\t\t\"\"\"\n\t\tself.send_response(301)\n\t\tself.send_header('Content-Length', 0)\n\t\tself.send_header('Location', location)\n\t\tself.end_headers()\n\t\treturn", "title": ""}
{"_id": "d9180", "text": "def _timestamp_to_json_row(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\n\n    This version returns floating-point seconds value used in row data.\n    \"\"\"\n    if isinstance(value, datetime.datetime):\n        value = _microseconds_from_datetime(value) * 1e-6\n    return value", "title": ""}
{"_id": "d9181", "text": "def _screen(self, s, newline=False):\n        \"\"\"Print something on screen when self.verbose == True\"\"\"\n        if self.verbose:\n            if newline:\n                print(s)\n            else:\n                print(s, end=' ')", "title": ""}
{"_id": "d9182", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d9183", "text": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n    \"\"\"\n    Returns the last `n` rows in the table\n    \"\"\"\n    return fetch(dbconn, tablename, n, uuid, end=True)", "title": ""}
{"_id": "d9184", "text": "def save_keras_definition(keras_model, path):\n    \"\"\"\n    Save a Keras model definition to JSON with given path\n    \"\"\"\n    model_json = keras_model.to_json()\n    with open(path, \"w\") as json_file:\n        json_file.write(model_json)", "title": ""}
{"_id": "d9185", "text": "def fields(self):\n        \"\"\"Returns the list of field names of the model.\"\"\"\n        return (self.attributes.values() + self.lists.values()\n                + self.references.values())", "title": ""}
{"_id": "d9186", "text": "def param (self, param, kwargs, default_value=False):\n        \"\"\"gets a param from kwargs, or uses a default_value. if found, it's\n        removed from kwargs\"\"\"\n        if param in kwargs:\n            value= kwargs[param]\n            del kwargs[param]\n        else:\n            value= default_value\n        setattr (self, param, value)", "title": ""}
{"_id": "d9187", "text": "def Proxy(f):\n  \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n\n  return Wrapped", "title": ""}
{"_id": "d9188", "text": "def l2_norm(arr):\n    \"\"\"\n    The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n    dot product of the vector.\n    \"\"\"\n    arr = np.asarray(arr)\n    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "title": ""}
{"_id": "d9189", "text": "def SegmentMin(a, ids):\n    \"\"\"\n    Segmented min op.\n    \"\"\"\n    func = lambda idxs: np.amin(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d9190", "text": "def l2_norm(arr):\n    \"\"\"\n    The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n    dot product of the vector.\n    \"\"\"\n    arr = np.asarray(arr)\n    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "title": ""}
{"_id": "d9191", "text": "def prefix_list(self, prefix, values):\n        \"\"\"\n        Add a prefix to a list of values.\n        \"\"\"\n        return list(map(lambda value: prefix + \" \" + value, values))", "title": ""}
{"_id": "d9192", "text": "def make_lambda(call):\n    \"\"\"Wrap an AST Call node to lambda expression node.\n    call: ast.Call node\n    \"\"\"\n    empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n    return ast.Lambda(args=empty_args, body=call)", "title": ""}
{"_id": "d9193", "text": "def add_suffix(fullname, suffix):\n    \"\"\" Add suffix to a full file name\"\"\"\n    name, ext = os.path.splitext(fullname)\n    return name + '_' + suffix + ext", "title": ""}
{"_id": "d9194", "text": "def _sort_lambda(sortedby='cpu_percent',\n                 sortedby_secondary='memory_percent'):\n    \"\"\"Return a sort lambda function for the sortedbykey\"\"\"\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", "title": ""}
{"_id": "d9195", "text": "def put(self, entity):\n    \"\"\"Registers entity to put to datastore.\n\n    Args:\n      entity: an entity or model instance to put.\n    \"\"\"\n    actual_entity = _normalize_entity(entity)\n    if actual_entity is None:\n      return self.ndb_put(entity)\n    self.puts.append(actual_entity)", "title": ""}
{"_id": "d9196", "text": "def make_lambda(call):\n    \"\"\"Wrap an AST Call node to lambda expression node.\n    call: ast.Call node\n    \"\"\"\n    empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n    return ast.Lambda(args=empty_args, body=call)", "title": ""}
{"_id": "d9197", "text": "def _elapsed(self):\n        \"\"\" Returns elapsed time at update. \"\"\"\n        self.last_time = time.time()\n        return self.last_time - self.start", "title": ""}
{"_id": "d9198", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d9199", "text": "def __add__(self,other):\n        \"\"\"\n            If the number of columns matches, we can concatenate two LabeldMatrices\n            with the + operator.\n        \"\"\"\n        assert self.matrix.shape[1] == other.matrix.shape[1]\n        return LabeledMatrix(np.concatenate([self.matrix,other.matrix],axis=0),self.labels)", "title": ""}
{"_id": "d9200", "text": "def levenshtein_distance_metric(a, b):\n    \"\"\" 1 - farthest apart (same number of words, all diff). 0 - same\"\"\"\n    return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1)))", "title": ""}
{"_id": "d9201", "text": "def indent(txt, spacing=4):\n    \"\"\"\n    Indent given text using custom spacing, default is set to 4.\n    \"\"\"\n    return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))", "title": ""}
{"_id": "d9202", "text": "def limitReal(x, max_denominator=1000000):\n    \"\"\"Creates an pysmt Real constant from x.\n\n    Args:\n        x (number): A number to be cast to a pysmt constant.\n        max_denominator (int, optional): The maximum size of the denominator.\n            Default 1000000.\n\n    Returns:\n        A Real constant with the given value and the denominator limited.\n\n    \"\"\"\n    f = Fraction(x).limit_denominator(max_denominator)\n    return Real((f.numerator, f.denominator))", "title": ""}
{"_id": "d9203", "text": "def inverseHistogram(hist, bin_range):\n    \"\"\"sample data from given histogram and min, max values within range\n\n    Returns:\n        np.array: data that would create the same histogram as given\n    \"\"\"\n    data = hist.astype(float) / np.min(hist[np.nonzero(hist)])\n    new_data = np.empty(shape=np.sum(data, dtype=int))\n    i = 0\n    xvals = np.linspace(bin_range[0], bin_range[1], len(data))\n    for d, x in zip(data, xvals):\n        new_data[i:i + d] = x\n        i += int(d)\n    return new_data", "title": ""}
{"_id": "d9204", "text": "def _listify(collection):\n        \"\"\"This is a workaround where Collections are no longer iterable\n        when using JPype.\"\"\"\n        new_list = []\n        for index in range(len(collection)):\n            new_list.append(collection[index])\n        return new_list", "title": ""}
{"_id": "d9205", "text": "def to_bipartite_matrix(A):\n    \"\"\"Returns the adjacency matrix of a bipartite graph whose biadjacency\n    matrix is `A`.\n\n    `A` must be a NumPy array.\n\n    If `A` has **m** rows and **n** columns, then the returned matrix has **m +\n    n** rows and columns.\n\n    \"\"\"\n    m, n = A.shape\n    return four_blocks(zeros(m, m), A, A.T, zeros(n, n))", "title": ""}
{"_id": "d9206", "text": "def dedupe_list(l):\n    \"\"\"Remove duplicates from a list preserving the order.\n\n    We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n    the order, which hinders testability and does not work for lists with\n    unhashable elements.\n    \"\"\"\n    result = []\n\n    for el in l:\n        if el not in result:\n            result.append(el)\n\n    return result", "title": ""}
{"_id": "d9207", "text": "def _distance(coord1, coord2):\n    \"\"\"\n    Return the distance between two points, `coord1` and `coord2`. These\n    parameters are assumed to be (x, y) tuples.\n    \"\"\"\n    xdist = coord1[0] - coord2[0]\n    ydist = coord1[1] - coord2[1]\n    return sqrt(xdist*xdist + ydist*ydist)", "title": ""}
{"_id": "d9208", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d9209", "text": "def floor(self):\n    \"\"\"Round `x` and `y` down to integers.\"\"\"\n    return Point(int(math.floor(self.x)), int(math.floor(self.y)))", "title": ""}
{"_id": "d9210", "text": "def get_inputs_from_cm(index, cm):\n    \"\"\"Return indices of inputs to the node with the given index.\"\"\"\n    return tuple(i for i in range(cm.shape[0]) if cm[i][index])", "title": ""}
{"_id": "d9211", "text": "def _make_cmd_list(cmd_list):\n    \"\"\"\n    Helper function to easily create the proper json formated string from a list of strs\n    :param cmd_list: list of strings\n    :return: str json formatted\n    \"\"\"\n    cmd = ''\n    for i in cmd_list:\n        cmd = cmd + '\"' + i + '\",'\n    cmd = cmd[:-1]\n    return cmd", "title": ""}
{"_id": "d9212", "text": "def linedelimited (inlist,delimiter):\n    \"\"\"\nReturns a string composed of elements in inlist, with each element\nseparated by 'delimiter.'  Used by function writedelimited.  Use '\\t'\nfor tab-delimiting.\n\nUsage:   linedelimited (inlist,delimiter)\n\"\"\"\n    outstr = ''\n    for item in inlist:\n        if type(item) != StringType:\n            item = str(item)\n        outstr = outstr + item + delimiter\n    outstr = outstr[0:-1]\n    return outstr", "title": ""}
{"_id": "d9213", "text": "def vsh(cmd, *args, **kw):\n    \"\"\" Execute a command installed into the active virtualenv.\n    \"\"\"\n    args = '\" \"'.join(i.replace('\"', r'\\\"') for i in args)\n    easy.sh('\"%s\" \"%s\"' % (venv_bin(cmd), args))", "title": ""}
{"_id": "d9214", "text": "def _top(self):\n        \"\"\" g \"\"\"\n        # Goto top of the list\n        self.top.body.focus_position = 2 if self.compact is False else 0\n        self.top.keypress(self.size, \"\")", "title": ""}
{"_id": "d9215", "text": "def _help():\n    \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n    statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n    print statement.strip()", "title": ""}
{"_id": "d9216", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d9217", "text": "def safe_int_conv(number):\n    \"\"\"Safely convert a single number to integer.\"\"\"\n    try:\n        return int(np.array(number).astype(int, casting='safe'))\n    except TypeError:\n        raise ValueError('cannot safely convert {} to integer'.format(number))", "title": ""}
{"_id": "d9218", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d9219", "text": "def get_number(s, cast=int):\n    \"\"\"\n    Try to get a number out of a string, and cast it.\n    \"\"\"\n    import string\n    d = \"\".join(x for x in str(s) if x in string.digits)\n    return cast(d)", "title": ""}
{"_id": "d9220", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d9221", "text": "def update_screen(self):\n        \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n        self.clock.tick(self.FPS)\n        pygame.display.update()", "title": ""}
{"_id": "d9222", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d9223", "text": "def str_to_num(str_value):\n        \"\"\"Convert str_value to an int or a float, depending on the\n        numeric value represented by str_value.\n\n        \"\"\"\n        str_value = str(str_value)\n        try:\n            return int(str_value)\n        except ValueError:\n            return float(str_value)", "title": ""}
{"_id": "d9224", "text": "def items(self):\n    \"\"\"Return a list of the (name, value) pairs of the enum.\n\n    These are returned in the order they were defined in the .proto file.\n    \"\"\"\n    return [(value_descriptor.name, value_descriptor.number)\n            for value_descriptor in self._enum_type.values]", "title": ""}
{"_id": "d9225", "text": "def resize_image_to_fit_width(image, dest_w):\n    \"\"\"\n    Resize and image to fit the passed in width, keeping the aspect ratio the same\n\n    :param image: PIL.Image\n    :param dest_w: The desired width\n    \"\"\"\n    scale_factor = dest_w / image.size[0]\n    dest_h = image.size[1] * scale_factor\n    \n    scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)\n\n    return scaled_image", "title": ""}
{"_id": "d9226", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d9227", "text": "def to_snake_case(name):\n    \"\"\" Given a name in camelCase return in snake_case \"\"\"\n    s1 = FIRST_CAP_REGEX.sub(r'\\1_\\2', name)\n    return ALL_CAP_REGEX.sub(r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d9228", "text": "def decode_example(self, example):\n    \"\"\"Reconstruct the image from the tf example.\"\"\"\n    img = tf.image.decode_image(\n        example, channels=self._shape[-1], dtype=tf.uint8)\n    img.set_shape(self._shape)\n    return img", "title": ""}
{"_id": "d9229", "text": "def stringc(text, color):\n    \"\"\"\n    Return a string with terminal colors.\n    \"\"\"\n    if has_colors:\n        text = str(text)\n\n        return \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"\n    else:\n        return text", "title": ""}
{"_id": "d9230", "text": "def loads(s, model=None, parser=None):\n    \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n    with StringIO(s) as f:\n        return load(f, model=model, parser=parser)", "title": ""}
{"_id": "d9231", "text": "def _check_and_convert_bools(self):\n        \"\"\"Replace boolean variables by the characters 'F'/'T'\n        \"\"\"\n        replacements = {\n            True: 'T',\n            False: 'F',\n        }\n\n        for key in self.bools:\n            if isinstance(self[key], bool):\n                self[key] = replacements[self[key]]", "title": ""}
{"_id": "d9232", "text": "def info(self, text):\n\t\t\"\"\" Ajout d'un message de log de type INFO \"\"\"\n\t\tself.logger.info(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d9233", "text": "def robust_int(v):\n    \"\"\"Parse an int robustly, ignoring commas and other cruft. \"\"\"\n\n    if isinstance(v, int):\n        return v\n\n    if isinstance(v, float):\n        return int(v)\n\n    v = str(v).replace(',', '')\n\n    if not v:\n        return None\n\n    return int(v)", "title": ""}
{"_id": "d9234", "text": "def logger(message, level=10):\n    \"\"\"Handle logging.\"\"\"\n    logging.getLogger(__name__).log(level, str(message))", "title": ""}
{"_id": "d9235", "text": "def lower_ext(abspath):\n    \"\"\"Convert file extension to lowercase.\n    \"\"\"\n    fname, ext = os.path.splitext(abspath)\n    return fname + ext.lower()", "title": ""}
{"_id": "d9236", "text": "def write(self, text):\n        \"\"\"Write text. An additional attribute terminator with a value of\n           None is added to the logging record to indicate that StreamHandler\n           should not add a newline.\"\"\"\n        self.logger.log(self.loglevel, text, extra={'terminator': None})", "title": ""}
{"_id": "d9237", "text": "def _maybe_cast_to_float64(da):\n    \"\"\"Cast DataArrays to np.float64 if they are of type np.float32.\n\n    Parameters\n    ----------\n    da : xr.DataArray\n        Input DataArray\n\n    Returns\n    -------\n    DataArray\n    \"\"\"\n    if da.dtype == np.float32:\n        logging.warning('Datapoints were stored using the np.float32 datatype.'\n                        'For accurate reduction operations using bottleneck, '\n                        'datapoints are being cast to the np.float64 datatype.'\n                        ' For more information see: https://github.com/pydata/'\n                        'xarray/issues/1346')\n        return da.astype(np.float64)\n    else:\n        return da", "title": ""}
{"_id": "d9238", "text": "def set_executable(filename):\n    \"\"\"Set the exectuable bit on the given filename\"\"\"\n    st = os.stat(filename)\n    os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d9239", "text": "def dict_self(self):\n        \"\"\"Return the self object attributes not inherited as dict.\"\"\"\n        return {k: v for k, v in self.__dict__.items() if k in FSM_ATTRS}", "title": ""}
{"_id": "d9240", "text": "def writefile(openedfile, newcontents):\n    \"\"\"Set the contents of a file.\"\"\"\n    openedfile.seek(0)\n    openedfile.truncate()\n    openedfile.write(newcontents)", "title": ""}
{"_id": "d9241", "text": "def to_snake_case(text):\n    \"\"\"Convert to snake case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d9242", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d9243", "text": "def _extract_node_text(node):\n    \"\"\"Extract text from a given lxml node.\"\"\"\n\n    texts = map(\n        six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n    )\n    return \" \".join(text for text in texts if text)", "title": ""}
{"_id": "d9244", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d9245", "text": "def paste(cmd=paste_cmd, stdout=PIPE):\n    \"\"\"Returns system clipboard contents.\n    \"\"\"\n    return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')", "title": ""}
{"_id": "d9246", "text": "def autoconvert(string):\n    \"\"\"Try to convert variables into datatypes.\"\"\"\n    for fn in (boolify, int, float):\n        try:\n            return fn(string)\n        except ValueError:\n            pass\n    return string", "title": ""}
{"_id": "d9247", "text": "def closeEvent(self, event):\n        \"\"\" Called when closing this window.\n        \"\"\"\n        logger.debug(\"closeEvent\")\n        self.argosApplication.saveSettingsIfNeeded()\n        self.finalize()\n        self.argosApplication.removeMainWindow(self)\n        event.accept()\n        logger.debug(\"closeEvent accepted\")", "title": ""}
{"_id": "d9248", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d9249", "text": "def cumsum(inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1, len(newlist)):\n        newlist[i] = newlist[i] + newlist[i - 1]\n    return newlist", "title": ""}
{"_id": "d9250", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d9251", "text": "def is_valid_file(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.exists(arg):\n        parser.error(\"The file %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d9252", "text": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    l = [v.strip() for v in value.split(',')]\n    if len(l) == 1:\n        l = value.split()\n    return l", "title": ""}
{"_id": "d9253", "text": "def task_property_present_predicate(service, task, prop):\n    \"\"\" True if the json_element passed is present for the task specified.\n    \"\"\"\n    try:\n        response = get_service_task(service, task)\n    except Exception as e:\n        pass\n\n    return (response is not None) and (prop in response)", "title": ""}
{"_id": "d9254", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d9255", "text": "def _replace_file(path, content):\n  \"\"\"Writes a file if it doesn't already exist with the same content.\n\n  This is useful because cargo uses timestamps to decide whether to compile things.\"\"\"\n  if os.path.exists(path):\n    with open(path, 'r') as f:\n      if content == f.read():\n        print(\"Not overwriting {} because it is unchanged\".format(path), file=sys.stderr)\n        return\n\n  with open(path, 'w') as f:\n    f.write(content)", "title": ""}
{"_id": "d9256", "text": "def purge_duplicates(list_in):\n    \"\"\"Remove duplicates from list while preserving order.\n\n    Parameters\n    ----------\n    list_in: Iterable\n\n    Returns\n    -------\n    list\n        List of first occurences in order\n    \"\"\"\n    _list = []\n    for item in list_in:\n        if item not in _list:\n            _list.append(item)\n    return _list", "title": ""}
{"_id": "d9257", "text": "def get_tree_type(tree):\n    \"\"\"\n    returns the type of the (sub)tree: Root, Nucleus or Satellite\n\n    Parameters\n    ----------\n    tree : nltk.tree.ParentedTree\n        a tree representing a rhetorical structure (or a part of it)\n    \"\"\"\n    tree_type = tree.label()\n    assert tree_type in SUBTREE_TYPES, \"tree_type: {}\".format(tree_type)\n    return tree_type", "title": ""}
{"_id": "d9258", "text": "def from_json(s):\n    \"\"\"Given a JSON-encoded message, build an object.\n\n    \"\"\"\n    d = json.loads(s)\n    sbp = SBP.from_json_dict(d)\n    return sbp", "title": ""}
{"_id": "d9259", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d9260", "text": "def set_interface(interface, name=''):\n    \"\"\"\n    don't want to bother with a dsn? Use this method to make an interface available\n    \"\"\"\n    global interfaces\n\n    if not interface: raise ValueError('interface is empty')\n\n    # close down the interface before we discard it\n    if name in interfaces:\n        interfaces[name].close()\n\n    interfaces[name] = interface", "title": ""}
{"_id": "d9261", "text": "def _is_one_arg_pos_call(call):\n    \"\"\"Is this a call with exactly 1 argument,\n    where that argument is positional?\n    \"\"\"\n    return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords", "title": ""}
{"_id": "d9262", "text": "def _varargs_to_iterable_method(func):\n    \"\"\"decorator to convert a *args method to one taking a iterable\"\"\"\n    def wrapped(self, iterable, **kwargs):\n        return func(self, *iterable, **kwargs)\n    return wrapped", "title": ""}
{"_id": "d9263", "text": "def is_defined(self, objtxt, force_import=False):\n        \"\"\"Return True if object is defined\"\"\"\n        return self.interpreter.is_defined(objtxt, force_import)", "title": ""}
{"_id": "d9264", "text": "def _iterPoints(self, **kwargs):\n        \"\"\"\n        Subclasses may override this method.\n        \"\"\"\n        points = self.points\n        count = len(points)\n        index = 0\n        while count:\n            yield points[index]\n            count -= 1\n            index += 1", "title": ""}
{"_id": "d9265", "text": "def safe_quotes(text, escape_single_quotes=False):\n    \"\"\"htmlify string\"\"\"\n    if isinstance(text, str):\n        safe_text = text.replace('\"', \"&quot;\")\n        if escape_single_quotes:\n            safe_text = safe_text.replace(\"'\", \"&#92;'\")\n        return safe_text.replace('True', 'true')\n    return text", "title": ""}
{"_id": "d9266", "text": "def stdin_readable():\n    \"\"\"Determine whether stdin has any data to read.\"\"\"\n    if not WINDOWS:\n        try:\n            return bool(select([sys.stdin], [], [], 0)[0])\n        except Exception:\n            logger.log_exc()\n    try:\n        return not sys.stdin.isatty()\n    except Exception:\n        logger.log_exc()\n    return False", "title": ""}
{"_id": "d9267", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d9268", "text": "def random_filename(path=None):\n    \"\"\"Make a UUID-based file name which is extremely unlikely\n    to exist already.\"\"\"\n    filename = uuid4().hex\n    if path is not None:\n        filename = os.path.join(path, filename)\n    return filename", "title": ""}
{"_id": "d9269", "text": "def _begins_with_one_of(sentence, parts_of_speech):\n    \"\"\"Return True if the sentence or fragment begins with one of the parts of\n    speech in the list, else False\"\"\"\n    doc = nlp(sentence)\n    if doc[0].tag_ in parts_of_speech:\n        return True\n    return False", "title": ""}
{"_id": "d9270", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d9271", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d9272", "text": "def is_element_present(self, strategy, locator):\n        \"\"\"Checks whether an element is present.\n\n        :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`.\n        :param locator: Location of target element.\n        :type strategy: str\n        :type locator: str\n        :return: ``True`` if element is present, else ``False``.\n        :rtype: bool\n\n        \"\"\"\n        return self.driver_adapter.is_element_present(strategy, locator, root=self.root)", "title": ""}
{"_id": "d9273", "text": "def OnDoubleClick(self, event):\n        \"\"\"Double click on a given square in the map\"\"\"\n        node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())\n        if node:\n            wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) )", "title": ""}
{"_id": "d9274", "text": "def _internet_on(address):\n    \"\"\"\n    Check to see if the internet is on by pinging a set address.\n    :param address: the IP or address to hit\n    :return: a boolean - true if can be reached, false if not.\n    \"\"\"\n    try:\n        urllib2.urlopen(address, timeout=1)\n        return True\n    except urllib2.URLError as err:\n        return False", "title": ""}
{"_id": "d9275", "text": "def asMaskedArray(self):\n        \"\"\" Creates converts to a masked array\n        \"\"\"\n        return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)", "title": ""}
{"_id": "d9276", "text": "def _is_readable(self, obj):\n        \"\"\"Check if the argument is a readable file-like object.\"\"\"\n        try:\n            read = getattr(obj, 'read')\n        except AttributeError:\n            return False\n        else:\n            return is_method(read, max_arity=1)", "title": ""}
{"_id": "d9277", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d9278", "text": "def stopwatch_now():\n    \"\"\"Get a timevalue for interval comparisons\n\n    When possible it is a monotonic clock to prevent backwards time issues.\n    \"\"\"\n    if six.PY2:\n        now = time.time()\n    else:\n        now = time.monotonic()\n    return now", "title": ""}
{"_id": "d9279", "text": "def v_normalize(v):\n    \"\"\"\n    Normalizes the given vector.\n    \n    The vector given may have any number of dimensions.\n    \"\"\"\n    vmag = v_magnitude(v)\n    return [ v[i]/vmag  for i in range(len(v)) ]", "title": ""}
{"_id": "d9280", "text": "def _validate_pos(df):\n    \"\"\"Validates the returned positional object\n    \"\"\"\n    assert isinstance(df, pd.DataFrame)\n    assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n    assert df.position.dtype == np.dtype(\"int64\")\n    assert df.strand.dtype == np.dtype(\"O\")\n    assert df.seqname.dtype == np.dtype(\"O\")\n    return df", "title": ""}
{"_id": "d9281", "text": "def set_title(self, title, **kwargs):\n        \"\"\"Sets the title on the underlying matplotlib AxesSubplot.\"\"\"\n        ax = self.get_axes()\n        ax.set_title(title, **kwargs)", "title": ""}
{"_id": "d9282", "text": "def autoconvert(string):\n    \"\"\"Try to convert variables into datatypes.\"\"\"\n    for fn in (boolify, int, float):\n        try:\n            return fn(string)\n        except ValueError:\n            pass\n    return string", "title": ""}
{"_id": "d9283", "text": "def _axes(self):\n        \"\"\"Set the _force_vertical flag when rendering axes\"\"\"\n        self.view._force_vertical = True\n        super(HorizontalGraph, self)._axes()\n        self.view._force_vertical = False", "title": ""}
{"_id": "d9284", "text": "def load_library(version):\n    \"\"\"\n    Load the correct module according to the version\n\n    :type version: ``str``\n    :param version: the version of the library to be loaded (e.g. '2.6')\n    :rtype: module object\n    \"\"\"\n    check_version(version)\n    module_name = SUPPORTED_LIBRARIES[version]\n    lib = sys.modules.get(module_name)\n    if lib is None:\n        lib = importlib.import_module(module_name)\n    return lib", "title": ""}
{"_id": "d9285", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d9286", "text": "def assert_exactly_one_true(bool_list):\n    \"\"\"This method asserts that only one value of the provided list is True.\n\n    :param bool_list: List of booleans to check\n    :return: True if only one value is True, False otherwise\n    \"\"\"\n    assert isinstance(bool_list, list)\n    counter = 0\n    for item in bool_list:\n        if item:\n            counter += 1\n    return counter == 1", "title": ""}
{"_id": "d9287", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d9288", "text": "def _IsDirectory(parent, item):\n  \"\"\"Helper that returns if parent/item is a directory.\"\"\"\n  return tf.io.gfile.isdir(os.path.join(parent, item))", "title": ""}
{"_id": "d9289", "text": "def set_axis_options(self, row, column, text):\n        \"\"\"Set additionnal options as plain text.\"\"\"\n\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_axis_options(text)", "title": ""}
{"_id": "d9290", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d9291", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d9292", "text": "def remove(self, entry):\n        \"\"\"Removes an entry\"\"\"\n        try:\n            list = self.cache[entry.key]\n            list.remove(entry)\n        except:\n            pass", "title": ""}
{"_id": "d9293", "text": "def max_values(args):\n    \"\"\" Return possible range for max function. \"\"\"\n    return Interval(max(x.low for x in args), max(x.high for x in args))", "title": ""}
{"_id": "d9294", "text": "def detach_all(self):\n        \"\"\"\n        Detach from all tracked classes and objects.\n        Restore the original constructors and cleanse the tracking lists.\n        \"\"\"\n        self.detach_all_classes()\n        self.objects.clear()\n        self.index.clear()\n        self._keepalive[:] = []", "title": ""}
{"_id": "d9295", "text": "def get_file_md5sum(path):\n    \"\"\"Calculate the MD5 hash for a file.\"\"\"\n    with open(path, 'rb') as fh:\n        h = str(hashlib.md5(fh.read()).hexdigest())\n    return h", "title": ""}
{"_id": "d9296", "text": "def _clear_dir(dirName):\n    \"\"\" Remove a directory and it contents. Ignore any failures.\n    \"\"\"\n    # If we got here, clear dir  \n    for fname in os.listdir(dirName):\n        try:\n            os.remove( os.path.join(dirName, fname) )\n        except Exception:\n            pass\n    try:\n        os.rmdir(dirName)\n    except Exception:\n        pass", "title": ""}
{"_id": "d9297", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d9298", "text": "def stoplog(self):\n        \"\"\" Stop logging.\n    \n        @return: 1 on success and 0 on error\n        @rtype: integer\n        \"\"\"\n        if self._file_logger:\n            self.logger.removeHandler(_file_logger)\n            self._file_logger = None\n        return 1", "title": ""}
{"_id": "d9299", "text": "def SegmentMin(a, ids):\n    \"\"\"\n    Segmented min op.\n    \"\"\"\n    func = lambda idxs: np.amin(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d9300", "text": "def clear():\n    \"\"\"Clears the console.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        call(\"cls\", shell=True)\n    else:\n        call(\"clear\", shell=True)", "title": ""}
{"_id": "d9301", "text": "def _get_minidom_tag_value(station, tag_name):\n    \"\"\"get a value from a tag (if it exists)\"\"\"\n    tag = station.getElementsByTagName(tag_name)[0].firstChild\n    if tag:\n        return tag.nodeValue\n\n    return None", "title": ""}
{"_id": "d9302", "text": "def close_all():\n    r\"\"\"Close all opened windows.\"\"\"\n\n    # Windows can be closed by releasing all references to them so they can be\n    # garbage collected. May not be necessary to call close().\n    global _qtg_windows\n    for window in _qtg_windows:\n        window.close()\n    _qtg_windows = []\n\n    global _qtg_widgets\n    for widget in _qtg_widgets:\n        widget.close()\n    _qtg_widgets = []\n\n    global _plt_figures\n    for fig in _plt_figures:\n        _, plt, _ = _import_plt()\n        plt.close(fig)\n    _plt_figures = []", "title": ""}
{"_id": "d9303", "text": "def __setitem__(self, _ignored, return_value):\n        \"\"\"Item assignment sets the return value and removes any side effect\"\"\"\n        self.mock.return_value = return_value\n        self.mock.side_effect = None", "title": ""}
{"_id": "d9304", "text": "def close(self):\n        \"\"\"Closes the serial port.\"\"\"\n        if self.pyb and self.pyb.serial:\n            self.pyb.serial.close()\n        self.pyb = None", "title": ""}
{"_id": "d9305", "text": "def finish():\n    \"\"\"Print warning about interrupt and empty the job queue.\"\"\"\n    out.warn(\"Interrupted!\")\n    for t in threads:\n        t.stop()\n    jobs.clear()\n    out.warn(\"Waiting for download threads to finish.\")", "title": ""}
{"_id": "d9306", "text": "def requests_post(url, data=None, json=None, **kwargs):\n    \"\"\"Requests-mock requests.post wrapper.\"\"\"\n    return requests_request('post', url, data=data, json=json, **kwargs)", "title": ""}
{"_id": "d9307", "text": "def from_pairs_to_array_values(pairs):\n    \"\"\"\n        Like from pairs but combines duplicate key values into arrays\n    :param pairs:\n    :return:\n    \"\"\"\n    result = {}\n    for pair in pairs:\n        result[pair[0]] = concat(prop_or([], pair[0], result), [pair[1]])\n    return result", "title": ""}
{"_id": "d9308", "text": "def getFunction(self):\n        \"\"\"Called by remote workers. Useful to populate main module globals()\n        for interactive shells. Retrieves the serialized function.\"\"\"\n        return functionFactory(\n            self.code,\n            self.name,\n            self.defaults,\n            self.globals,\n            self.imports,\n        )", "title": ""}
{"_id": "d9309", "text": "def compare(string1, string2):\n    \"\"\"Compare two strings while protecting against timing attacks\n\n    :param str string1: the first string\n    :param str string2: the second string\n\n    :returns: True if the strings are equal, False if not\n    :rtype: :obj:`bool`\n    \"\"\"\n    if len(string1) != len(string2):\n        return False\n    result = True\n    for c1, c2 in izip(string1, string2):\n        result &= c1 == c2\n    return result", "title": ""}
{"_id": "d9310", "text": "def _construct_from_json(self, rec):\n        \"\"\" Construct this Dagobah instance from a JSON document. \"\"\"\n\n        self.delete()\n\n        for required_key in ['dagobah_id', 'created_jobs']:\n            setattr(self, required_key, rec[required_key])\n\n        for job_json in rec.get('jobs', []):\n            self._add_job_from_spec(job_json)\n\n        self.commit(cascade=True)", "title": ""}
{"_id": "d9311", "text": "def benchmark(store, n=10000):\n    \"\"\"\n    Iterates over all of the referreds, and then iterates over all of the\n    referrers that refer to each one.\n\n    Fairly item instantiation heavy.\n    \"\"\"\n    R = Referrer\n\n    for referred in store.query(Referred):\n        for _reference in store.query(R, R.reference == referred):\n            pass", "title": ""}
{"_id": "d9312", "text": "def beautify(string, *args, **kwargs):\n\t\"\"\"\n\t\tConvenient interface to the ecstasy package.\n\n\t\tArguments:\n\t\t\tstring (str): The string to beautify with ecstasy.\n\t\t\targs (list): The positional arguments.\n\t\t\tkwargs (dict): The keyword ('always') arguments.\n\t\"\"\"\n\n\tparser = Parser(args, kwargs)\n\treturn parser.beautify(string)", "title": ""}
{"_id": "d9313", "text": "def wrap_count(method):\n    \"\"\"\n    Returns number of wraps around given method.\n    \"\"\"\n    number = 0\n    while hasattr(method, '__aspects_orig'):\n        number += 1\n        method = method.__aspects_orig\n    return number", "title": ""}
{"_id": "d9314", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d9315", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d9316", "text": "def a2s(a):\n    \"\"\"\n     convert 3,3 a matrix to 6 element \"s\" list  (see Tauxe 1998)\n    \"\"\"\n    s = np.zeros((6,), 'f')  # make the a matrix\n    for i in range(3):\n        s[i] = a[i][i]\n    s[3] = a[0][1]\n    s[4] = a[1][2]\n    s[5] = a[0][2]\n    return s", "title": ""}
{"_id": "d9317", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d9318", "text": "def _convert_to_array(array_like, dtype):\n        \"\"\"\n        Convert Matrix attributes which are array-like or buffer to array.\n        \"\"\"\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)", "title": ""}
{"_id": "d9319", "text": "def def_linear(fun):\n    \"\"\"Flags that a function is linear wrt all args\"\"\"\n    defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:\n                  fun(*subval(args, argnum, g), **kwargs))", "title": ""}
{"_id": "d9320", "text": "def _kw(keywords):\n    \"\"\"Turn list of keywords into dictionary.\"\"\"\n    r = {}\n    for k, v in keywords:\n        r[k] = v\n    return r", "title": ""}
{"_id": "d9321", "text": "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n    \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n    return maybe_list and any(is_multiline(item) for item in maybe_list)", "title": ""}
{"_id": "d9322", "text": "def add(self, name, desc, func=None, args=None, krgs=None):\n        \"\"\"Add a menu entry.\"\"\"\n        self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))", "title": ""}
{"_id": "d9323", "text": "def combine(self, a, b):\n        \"\"\"A generator that combines two iterables.\"\"\"\n\n        for l in (a, b):\n            for x in l:\n                yield x", "title": ""}
{"_id": "d9324", "text": "def to_json(data):\n    \"\"\"Return data as a JSON string.\"\"\"\n    return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)", "title": ""}
{"_id": "d9325", "text": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "title": ""}
{"_id": "d9326", "text": "def _heapify_max(x):\n    \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n    n = len(x)\n    for i in reversed(range(n//2)):\n        _siftup_max(x, i)", "title": ""}
{"_id": "d9327", "text": "def kill_mprocess(process):\n    \"\"\"kill process\n    Args:\n        process - Popen object for process\n    \"\"\"\n    if process and proc_alive(process):\n        process.terminate()\n        process.communicate()\n    return not proc_alive(process)", "title": ""}
{"_id": "d9328", "text": "def zoom_out(self):\n        \"\"\"Decrease zoom factor and redraw TimeLine\"\"\"\n        index = self._zoom_factors.index(self._zoom_factor)\n        if index == 0:\n            # Already zoomed out all the way\n            return\n        self._zoom_factor = self._zoom_factors[index - 1]\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        self.draw_timeline()", "title": ""}
{"_id": "d9329", "text": "def initialize_worker(self, process_num=None):\n        \"\"\"\n        reinitialize consumer for process in multiprocesing\n        \"\"\"\n        self.initialize(self.grid, self.num_of_paths, self.seed)", "title": ""}
{"_id": "d9330", "text": "def _unique_id(self, prefix):\n        \"\"\"\n        Generate a unique (within the graph) identifer\n        internal to graph generation.\n        \"\"\"\n        _id = self._id_gen\n        self._id_gen += 1\n        return prefix + str(_id)", "title": ""}
{"_id": "d9331", "text": "def compute(args):\n    x, y, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot(x, y, params)", "title": ""}
{"_id": "d9332", "text": "def get_distance_matrix(x):\n    \"\"\"Get distance matrix given a matrix. Used in testing.\"\"\"\n    square = nd.sum(x ** 2.0, axis=1, keepdims=True)\n    distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))\n    return nd.sqrt(distance_square)", "title": ""}
{"_id": "d9333", "text": "def compute_capture(args):\n    x, y, w, h, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot_capture(x, y, w, h, params)", "title": ""}
{"_id": "d9334", "text": "def _cell(x):\n    \"\"\"translate an array x into a MATLAB cell array\"\"\"\n    x_no_none = [i if i is not None else \"\" for i in x]\n    return array(x_no_none, dtype=np_object)", "title": ""}
{"_id": "d9335", "text": "def finish():\n    \"\"\"Print warning about interrupt and empty the job queue.\"\"\"\n    out.warn(\"Interrupted!\")\n    for t in threads:\n        t.stop()\n    jobs.clear()\n    out.warn(\"Waiting for download threads to finish.\")", "title": ""}
{"_id": "d9336", "text": "def array_dim(arr):\n    \"\"\"Return the size of a multidimansional array.\n    \"\"\"\n    dim = []\n    while True:\n        try:\n            dim.append(len(arr))\n            arr = arr[0]\n        except TypeError:\n            return dim", "title": ""}
{"_id": "d9337", "text": "def connect_mysql(host, port, user, password, database):\n    \"\"\"Connect to MySQL with retries.\"\"\"\n    return pymysql.connect(\n        host=host, port=port,\n        user=user, passwd=password,\n        db=database\n    )", "title": ""}
{"_id": "d9338", "text": "def tick(self):\n        \"\"\"Add one tick to progress bar\"\"\"\n        self.current += 1\n        if self.current == self.factor:\n            sys.stdout.write('+')\n            sys.stdout.flush()\n            self.current = 0", "title": ""}
{"_id": "d9339", "text": "def connect_mysql(host, port, user, password, database):\n    \"\"\"Connect to MySQL with retries.\"\"\"\n    return pymysql.connect(\n        host=host, port=port,\n        user=user, passwd=password,\n        db=database\n    )", "title": ""}
{"_id": "d9340", "text": "def doc_to_html(doc, doc_format=\"ROBOT\"):\n    \"\"\"Convert documentation to HTML\"\"\"\n    from robot.libdocpkg.htmlwriter import DocToHtml\n    return DocToHtml(doc_format)(doc)", "title": ""}
{"_id": "d9341", "text": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "title": ""}
{"_id": "d9342", "text": "def setdefault(obj, field, default):\n    \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n    setattr(obj, field, getattr(obj, field, default))", "title": ""}
{"_id": "d9343", "text": "def maskIndex(self):\n        \"\"\" 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.\n        \"\"\"\n        if isinstance(self.mask, bool):\n            return np.full(self.data.shape, self.mask, dtype=np.bool)\n        else:\n            return self.mask", "title": ""}
{"_id": "d9344", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d9345", "text": "def last_item(array):\n    \"\"\"Returns the last item of an array in a list or an empty list.\"\"\"\n    if array.size == 0:\n        # work around for https://github.com/numpy/numpy/issues/5195\n        return []\n\n    indexer = (slice(-1, None),) * array.ndim\n    return np.ravel(array[indexer]).tolist()", "title": ""}
{"_id": "d9346", "text": "def ratio_and_percentage(current, total, time_remaining):\n    \"\"\"Returns the progress ratio and percentage.\"\"\"\n    return \"{} / {} ({}% completed)\".format(current, total, int(current / total * 100))", "title": ""}
{"_id": "d9347", "text": "def _attrprint(d, delimiter=', '):\n    \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n    return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))", "title": ""}
{"_id": "d9348", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d9349", "text": "def _bytes_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, bytes):\n        value = base64.standard_b64encode(value).decode(\"ascii\")\n    return value", "title": ""}
{"_id": "d9350", "text": "def cli(env, identifier):\n    \"\"\"Delete an image.\"\"\"\n\n    image_mgr = SoftLayer.ImageManager(env.client)\n    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')\n\n    image_mgr.delete_image(image_id)", "title": ""}
{"_id": "d9351", "text": "def bytes_to_str(s, encoding='utf-8'):\n    \"\"\"Returns a str if a bytes object is given.\"\"\"\n    if six.PY3 and isinstance(s, bytes):\n        return s.decode(encoding)\n    return s", "title": ""}
{"_id": "d9352", "text": "def remove_last_line(self):\n        \"\"\"Removes the last line of the document.\"\"\"\n        editor = self._editor\n        text_cursor = editor.textCursor()\n        text_cursor.movePosition(text_cursor.End, text_cursor.MoveAnchor)\n        text_cursor.select(text_cursor.LineUnderCursor)\n        text_cursor.removeSelectedText()\n        text_cursor.deletePreviousChar()\n        editor.setTextCursor(text_cursor)", "title": ""}
{"_id": "d9353", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d9354", "text": "def stats(self):\n        \"\"\" shotcut to pull out useful info for interactive use \"\"\"\n        printDebug(\"Classes.....: %d\" % len(self.all_classes))\n        printDebug(\"Properties..: %d\" % len(self.all_properties))", "title": ""}
{"_id": "d9355", "text": "def pdf(x, mu, std):\n    \"\"\"Probability density function (normal distribution)\"\"\"\n    return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))", "title": ""}
{"_id": "d9356", "text": "def on_mouse_motion(self, x, y, dx, dy):\n        \"\"\"\n        Pyglet specific mouse motion callback.\n        Forwards and traslates the event to the example\n        \"\"\"\n        # Screen coordinates relative to the lower-left corner\n        # so we have to flip the y axis to make this consistent with\n        # other window libraries\n        self.example.mouse_position_event(x, self.buffer_height - y)", "title": ""}
{"_id": "d9357", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d9358", "text": "def _namematcher(regex):\n    \"\"\"Checks if a target name matches with an input regular expression.\"\"\"\n\n    matcher = re_compile(regex)\n\n    def match(target):\n        target_name = getattr(target, '__name__', '')\n        result = matcher.match(target_name)\n        return result\n\n    return match", "title": ""}
{"_id": "d9359", "text": "def normalize(im, invert=False, scale=None, dtype=np.float64):\n    \"\"\"\n    Normalize a field to a (min, max) exposure range, default is (0, 255).\n    (min, max) exposure values. Invert the image if requested.\n    \"\"\"\n    if dtype not in {np.float16, np.float32, np.float64}:\n        raise ValueError('dtype must be numpy.float16, float32, or float64.')\n    out = im.astype('float').copy()\n\n    scale = scale or (0.0, 255.0)\n    l, u = (float(i) for i in scale)\n    out = (out - l) / (u - l)\n    if invert:\n        out = -out + (out.max() + out.min())\n    return out.astype(dtype)", "title": ""}
{"_id": "d9360", "text": "def read_key(suppress=False):\n    \"\"\"\n    Blocks until a keyboard event happens, then returns that event's name or,\n    if missing, its scan code.\n    \"\"\"\n    event = read_event(suppress)\n    return event.name or event.scan_code", "title": ""}
{"_id": "d9361", "text": "def normalize(self, string):\n        \"\"\"Normalize the string according to normalization list\"\"\"\n        return ''.join([self._normalize.get(x, x) for x in nfd(string)])", "title": ""}
{"_id": "d9362", "text": "def is_string(val):\n    \"\"\"Determines whether the passed value is a string, safe for 2/3.\"\"\"\n    try:\n        basestring\n    except NameError:\n        return isinstance(val, str)\n    return isinstance(val, basestring)", "title": ""}
{"_id": "d9363", "text": "def ComplementEquivalence(*args, **kwargs):\n    \"\"\"Change x != y to not(x == y).\"\"\"\n    return ast.Complement(\n        ast.Equivalence(*args, **kwargs), **kwargs)", "title": ""}
{"_id": "d9364", "text": "def test_for_image(self, cat, img):\n        \"\"\"Tests if image img in category cat exists\"\"\"\n        return self.test_for_category(cat) and img in self.items[cat]", "title": ""}
{"_id": "d9365", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d9366", "text": "def issorted(list_, op=operator.le):\n    \"\"\"\n    Determines if a list is sorted\n\n    Args:\n        list_ (list):\n        op (func): sorted operation (default=operator.le)\n\n    Returns:\n        bool : True if the list is sorted\n    \"\"\"\n    return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))", "title": ""}
{"_id": "d9367", "text": "def other_ind(self):\n        \"\"\"last row or column of square A\"\"\"\n        return np.full(self.n_min, self.size - 1, dtype=np.int)", "title": ""}
{"_id": "d9368", "text": "def incidence(boundary):\n    \"\"\"\n    given an Nxm matrix containing boundary info between simplices,\n    compute indidence info matrix\n    not very reusable; should probably not be in this lib\n    \"\"\"\n    return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1])", "title": ""}
{"_id": "d9369", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d9370", "text": "def ratio_and_percentage(current, total, time_remaining):\n    \"\"\"Returns the progress ratio and percentage.\"\"\"\n    return \"{} / {} ({}% completed)\".format(current, total, int(current / total * 100))", "title": ""}
{"_id": "d9371", "text": "def fit_gaussian(samples, ddof=0):\n    \"\"\"Calculates the mean and the standard deviation of the given samples.\n\n    Args:\n        samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all\n            values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension.\n        ddof (int): the difference degrees of freedom in the std calculation. See numpy.\n    \"\"\"\n    if len(samples.shape) == 1:\n        return np.mean(samples), np.std(samples, ddof=ddof)\n    return np.mean(samples, axis=1), np.std(samples, axis=1, ddof=ddof)", "title": ""}
{"_id": "d9372", "text": "def computeFactorial(n):\n    \"\"\"\n    computes factorial of n\n    \"\"\"\n    sleep_walk(10)\n    ret = 1\n    for i in range(n):\n        ret = ret * (i + 1)\n    return ret", "title": ""}
{"_id": "d9373", "text": "def get_distance_matrix(x):\n    \"\"\"Get distance matrix given a matrix. Used in testing.\"\"\"\n    square = nd.sum(x ** 2.0, axis=1, keepdims=True)\n    distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))\n    return nd.sqrt(distance_square)", "title": ""}
{"_id": "d9374", "text": "def wrap(string, length, indent):\n    \"\"\" Wrap a string at a line length \"\"\"\n    newline = \"\\n\" + \" \" * indent\n    return newline.join((string[i : i + length] for i in range(0, len(string), length)))", "title": ""}
{"_id": "d9375", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d9376", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d9377", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d9378", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d9379", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d9380", "text": "def _Enum(docstring, *names):\n  \"\"\"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.\n  \"\"\"\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)", "title": ""}
{"_id": "d9381", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d9382", "text": "def sorted_product_set(array_a, array_b):\n  \"\"\"Compute the product set of array_a and array_b and sort it.\"\"\"\n  return np.sort(\n      np.concatenate(\n          [array_a[i] * array_b for i in xrange(len(array_a))], axis=0)\n  )[::-1]", "title": ""}
{"_id": "d9383", "text": "def _xls2col_widths(self, worksheet, tab):\n        \"\"\"Updates col_widths in code_array\"\"\"\n\n        for col in xrange(worksheet.ncols):\n            try:\n                xls_width = worksheet.colinfo_map[col].width\n                pys_width = self.xls_width2pys_width(xls_width)\n                self.code_array.col_widths[col, tab] = pys_width\n\n            except KeyError:\n                pass", "title": ""}
{"_id": "d9384", "text": "def _tostr(self,obj):\n        \"\"\" converts a object to list, if object is a list, it creates a\n            comma seperated string.\n        \"\"\"\n        if not obj:\n            return ''\n        if isinstance(obj, list):\n            return ', '.join(map(self._tostr, obj))\n        return str(obj)", "title": ""}
{"_id": "d9385", "text": "def iterlists(self):\n        \"\"\"Like :meth:`items` but returns an iterator.\"\"\"\n        for key, values in dict.iteritems(self):\n            yield key, list(values)", "title": ""}
{"_id": "d9386", "text": "def delete_connection():\n    \"\"\"\n    Stop and destroy Bloomberg connection\n    \"\"\"\n    if _CON_SYM_ in globals():\n        con = globals().pop(_CON_SYM_)\n        if not getattr(con, '_session').start(): con.stop()", "title": ""}
{"_id": "d9387", "text": "def PopAttributeContainer(self):\n    \"\"\"Pops a serialized attribute container from the list.\n\n    Returns:\n      bytes: serialized attribute container data.\n    \"\"\"\n    try:\n      serialized_data = self._list.pop(0)\n      self.data_size -= len(serialized_data)\n      return serialized_data\n\n    except IndexError:\n      return None", "title": ""}
{"_id": "d9388", "text": "def _ignore_comments(lines_enum):\n    \"\"\"\n    Strips comments and filter empty lines.\n    \"\"\"\n    for line_number, line in lines_enum:\n        line = COMMENT_RE.sub('', line)\n        line = line.strip()\n        if line:\n            yield line_number, line", "title": ""}
{"_id": "d9389", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d9390", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d9391", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d9392", "text": "def ip_address_list(ips):\n    \"\"\" IP address range validation and expansion. \"\"\"\n    # first, try it as a single IP address\n    try:\n        return ip_address(ips)\n    except ValueError:\n        pass\n    # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it\n    return list(ipaddress.ip_network(u(ips)).hosts())", "title": ""}
{"_id": "d9393", "text": "def delete(self):\n        \"\"\"Remove this object.\"\"\"\n        self._client.remove_object(self._instance, self._bucket, self.name)", "title": ""}
{"_id": "d9394", "text": "def set_timeout(scope, timeout):\n    \"\"\"\n    Defines the time after which Exscript fails if it does not receive a\n    prompt from the remote host.\n\n    :type  timeout: int\n    :param timeout: The timeout in seconds.\n    \"\"\"\n    conn = scope.get('__connection__')\n    conn.set_timeout(int(timeout[0]))\n    return True", "title": ""}
{"_id": "d9395", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d9396", "text": "def _fill_array_from_list(the_list, the_array):\n        \"\"\"Fill an `array` from a `list`\"\"\"\n        for i, val in enumerate(the_list):\n            the_array[i] = val\n        return the_array", "title": ""}
{"_id": "d9397", "text": "def add_suffix(fullname, suffix):\n    \"\"\" Add suffix to a full file name\"\"\"\n    name, ext = os.path.splitext(fullname)\n    return name + '_' + suffix + ext", "title": ""}
{"_id": "d9398", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d9399", "text": "def lock_file(f, block=False):\n    \"\"\"\n    If block=False (the default), die hard and fast if another process has\n    already grabbed the lock for this file.\n\n    If block=True, wait for the lock to be released, then continue.\n    \"\"\"\n    try:\n        flags = fcntl.LOCK_EX\n        if not block:\n            flags |= fcntl.LOCK_NB\n        fcntl.flock(f.fileno(), flags)\n    except IOError as e:\n        if e.errno in (errno.EACCES, errno.EAGAIN):\n            raise SystemExit(\"ERROR: %s is locked by another process.\" %\n                             f.name)\n        raise", "title": ""}
{"_id": "d9400", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d9401", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d9402", "text": "def rpc_fix_code_with_black(self, source, directory):\n        \"\"\"Formats Python code to conform to the PEP 8 style guide.\n\n        \"\"\"\n        source = get_source(source)\n        return fix_code_with_black(source, directory)", "title": ""}
{"_id": "d9403", "text": "def set(self):\n        \"\"\"Set the color as current OpenGL color\n        \"\"\"\n        glColor4f(self.r, self.g, self.b, self.a)", "title": ""}
{"_id": "d9404", "text": "def warn_deprecated(message, stacklevel=2):  # pragma: no cover\n    \"\"\"Warn deprecated.\"\"\"\n\n    warnings.warn(\n        message,\n        category=DeprecationWarning,\n        stacklevel=stacklevel\n    )", "title": ""}
{"_id": "d9405", "text": "def _genTex2D(self):\n        \"\"\"Generate an empty texture in OpenGL\"\"\"\n        for face in range(6):\n            gl.glTexImage2D(self.target0 + face, 0, self.internal_fmt, self.width, self.height, 0,\n                            self.pixel_fmt, gl.GL_UNSIGNED_BYTE, 0)", "title": ""}
{"_id": "d9406", "text": "def cursor_up(self, count=1):\n        \"\"\" (for multiline edit). Move cursor to the previous line.  \"\"\"\n        original_column = self.preferred_column or self.document.cursor_position_col\n        self.cursor_position += self.document.get_cursor_up_position(\n            count=count, preferred_column=original_column)\n\n        # Remember the original column for the next up/down movement.\n        self.preferred_column = original_column", "title": ""}
{"_id": "d9407", "text": "def _get_pattern(self, pys_style):\n        \"\"\"Returns xlwt.pattern for pyspread style\"\"\"\n\n        # Return None if there is no bgcolor\n        if \"bgcolor\" not in pys_style:\n            return\n\n        pattern = xlwt.Pattern()\n        pattern.pattern = xlwt.Pattern.SOLID_PATTERN\n\n        bgcolor = wx.Colour()\n        bgcolor.SetRGB(pys_style[\"bgcolor\"])\n        pattern.pattern_fore_colour = self.color2idx(*bgcolor.Get())\n\n        return pattern", "title": ""}
{"_id": "d9408", "text": "def shutdown():\n    \"\"\"Manually shutdown the async API.\n\n    Cancels all related tasks and all the socket transportation.\n    \"\"\"\n    global handler, transport, protocol\n    if handler is not None:\n        handler.close()\n        transport.close()\n        handler = None\n        transport = None\n        protocol = None", "title": ""}
{"_id": "d9409", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d9410", "text": "def get_order(self):\n        \"\"\"\n        Return a list of dicionaries. See `set_order`.\n        \"\"\"\n        return [dict(reverse=r[0], key=r[1]) for r in self.get_model()]", "title": ""}
{"_id": "d9411", "text": "def impad_to_multiple(img, divisor, pad_val=0):\n    \"\"\"Pad an image to ensure each edge to be multiple to some number.\n\n    Args:\n        img (ndarray): Image to be padded.\n        divisor (int): Padded image edges will be multiple to divisor.\n        pad_val (number or sequence): Same as :func:`impad`.\n\n    Returns:\n        ndarray: The padded image.\n    \"\"\"\n    pad_h = int(np.ceil(img.shape[0] / divisor)) * divisor\n    pad_w = int(np.ceil(img.shape[1] / divisor)) * divisor\n    return impad(img, (pad_h, pad_w), pad_val)", "title": ""}
{"_id": "d9412", "text": "def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"A quick and dirty way to get a unique string\"\"\"\n    return ''.join(random.choice(chars) for x in xrange(size))", "title": ""}
{"_id": "d9413", "text": "def entropy(string):\n    \"\"\"Compute entropy on the string\"\"\"\n    p, lns = Counter(string), float(len(string))\n    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())", "title": ""}
{"_id": "d9414", "text": "def generate_nonce():\n        \"\"\" Generate nonce number \"\"\"\n        nonce = ''.join([str(randint(0, 9)) for i in range(8)])\n        return HMAC(\n            nonce.encode(),\n            \"secret\".encode(),\n            sha1\n        ).hexdigest()", "title": ""}
{"_id": "d9415", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d9416", "text": "def daterange(start_date, end_date):\n    \"\"\"\n    Yield one date per day from starting date to ending date.\n\n    Args:\n        start_date (date): starting date.\n        end_date (date): ending date.\n\n    Yields:\n        date: a date for each day within the range.\n    \"\"\"\n    for n in range(int((end_date - start_date).days)):\n        yield start_date + timedelta(n)", "title": ""}
{"_id": "d9417", "text": "def parse_datetime(dt_str):\n    \"\"\"Parse datetime.\"\"\"\n    date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n    dt_str = dt_str.replace(\"Z\", \" +0000\")\n    return datetime.datetime.strptime(dt_str, date_format)", "title": ""}
{"_id": "d9418", "text": "def visit_BoolOp(self, node):\n        \"\"\" Return type may come from any boolop operand. \"\"\"\n        return sum((self.visit(value) for value in node.values), [])", "title": ""}
{"_id": "d9419", "text": "def _parse_response(self, response):\n        \"\"\"\n        Parse http raw respone into python\n        dictionary object.\n        \n        :param str response: http response\n        :returns: response dict\n        :rtype: dict\n        \"\"\"\n\n        response_dict = {}\n        for line in response.splitlines():\n            key, value = response.split(\"=\", 1)\n            response_dict[key] = value\n        return response_dict", "title": ""}
{"_id": "d9420", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d9421", "text": "def parse_timestamp(timestamp):\n    \"\"\"Parse ISO8601 timestamps given by github API.\"\"\"\n    dt = dateutil.parser.parse(timestamp)\n    return dt.astimezone(dateutil.tz.tzutc())", "title": ""}
{"_id": "d9422", "text": "def _get_os_environ_dict(keys):\n  \"\"\"Return a dictionary of key/values from os.environ.\"\"\"\n  return {k: os.environ.get(k, _UNDEFINED) for k in keys}", "title": ""}
{"_id": "d9423", "text": "def rfc3339_to_datetime(data):\n    \"\"\"convert a rfc3339 date representation into a Python datetime\"\"\"\n    try:\n        ts = time.strptime(data, '%Y-%m-%d')\n        return date(*ts[:3])\n    except ValueError:\n        pass\n\n    try:\n        dt, _, tz = data.partition('Z')\n        if tz:\n            tz = offset(tz)\n        else:\n            tz = offset('00:00')\n        if '.' in dt and dt.rsplit('.', 1)[-1].isdigit():\n            ts = time.strptime(dt, '%Y-%m-%dT%H:%M:%S.%f')\n        else:\n            ts = time.strptime(dt, '%Y-%m-%dT%H:%M:%S')\n        return datetime(*ts[:6], tzinfo=tz)\n    except ValueError:\n        raise ValueError('date-time {!r} is not a valid rfc3339 date representation'.format(data))", "title": ""}
{"_id": "d9424", "text": "def timedcall(executable_function, *args):\n    \"\"\"!\n    @brief Executes specified method or function with measuring of execution time.\n    \n    @param[in] executable_function (pointer): Pointer to function or method.\n    @param[in] args (*): Arguments of called function or method.\n    \n    @return (tuple) Execution time and result of execution of function or method (execution_time, result_execution).\n    \n    \"\"\"\n    \n    time_start = time.clock();\n    result = executable_function(*args);\n    time_end = time.clock();\n    \n    return (time_end - time_start, result);", "title": ""}
{"_id": "d9425", "text": "def _ParseYamlFromFile(filedesc):\n  \"\"\"Parses given YAML file.\"\"\"\n  content = filedesc.read()\n  return yaml.Parse(content) or collections.OrderedDict()", "title": ""}
{"_id": "d9426", "text": "def get_first_lang():\n    \"\"\"Get the first lang of Accept-Language Header.\n    \"\"\"\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", "title": ""}
{"_id": "d9427", "text": "def from_pystr_to_cstr(data):\n    \"\"\"Convert a list of Python str to C pointer\n\n    Parameters\n    ----------\n    data : list\n        list of str\n    \"\"\"\n\n    if not isinstance(data, list):\n        raise NotImplementedError\n    pointers = (ctypes.c_char_p * len(data))()\n    if PY3:\n        data = [bytes(d, 'utf-8') for d in data]\n    else:\n        data = [d.encode('utf-8') if isinstance(d, unicode) else d  # pylint: disable=undefined-variable\n                for d in data]\n    pointers[:] = data\n    return pointers", "title": ""}
{"_id": "d9428", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d9429", "text": "def osx_clipboard_get():\n    \"\"\" Get the clipboard's text on OS X.\n    \"\"\"\n    p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n        stdout=subprocess.PIPE)\n    text, stderr = p.communicate()\n    # Text comes in with old Mac \\r line endings. Change them to \\n.\n    text = text.replace('\\r', '\\n')\n    return text", "title": ""}
{"_id": "d9430", "text": "def get_mouse_location(self):\n        \"\"\"\n        Get the current mouse location (coordinates and screen number).\n\n        :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields\n        \"\"\"\n        x = ctypes.c_int(0)\n        y = ctypes.c_int(0)\n        screen_num = ctypes.c_int(0)\n        _libxdo.xdo_get_mouse_location(\n            self._xdo, ctypes.byref(x), ctypes.byref(y),\n            ctypes.byref(screen_num))\n        return mouse_location(x.value, y.value, screen_num.value)", "title": ""}
{"_id": "d9431", "text": "def get_parent_dir(name):\n    \"\"\"Get the parent directory of a filename.\"\"\"\n    parent_dir = os.path.dirname(os.path.dirname(name))\n    if parent_dir:\n        return parent_dir\n    return os.path.abspath('.')", "title": ""}
{"_id": "d9432", "text": "def get_mouse_location(self):\n        \"\"\"\n        Get the current mouse location (coordinates and screen number).\n\n        :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields\n        \"\"\"\n        x = ctypes.c_int(0)\n        y = ctypes.c_int(0)\n        screen_num = ctypes.c_int(0)\n        _libxdo.xdo_get_mouse_location(\n            self._xdo, ctypes.byref(x), ctypes.byref(y),\n            ctypes.byref(screen_num))\n        return mouse_location(x.value, y.value, screen_num.value)", "title": ""}
{"_id": "d9433", "text": "def set_trace():\n    \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n    # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n    pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "title": ""}
{"_id": "d9434", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d9435", "text": "def dimensions(path):\n    \"\"\"Get width and height of a PDF\"\"\"\n    pdf = PdfFileReader(path)\n    size = pdf.getPage(0).mediaBox\n    return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d9436", "text": "def get_from_human_key(self, key):\n        \"\"\"Return the key (aka database value) of a human key (aka Python identifier).\"\"\"\n        if key in self._identifier_map:\n            return self._identifier_map[key]\n        raise KeyError(key)", "title": ""}
{"_id": "d9437", "text": "def dimensions(path):\n    \"\"\"Get width and height of a PDF\"\"\"\n    pdf = PdfFileReader(path)\n    size = pdf.getPage(0).mediaBox\n    return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d9438", "text": "def round_to_float(number, precision):\n    \"\"\"Round a float to a precision\"\"\"\n    rounded = Decimal(str(floor((number + precision / 2) // precision))\n                      ) * Decimal(str(precision))\n    return float(rounded)", "title": ""}
{"_id": "d9439", "text": "def percentile(values, k):\n    \"\"\"Find the percentile of a list of values.\n\n    :param list values: The list of values to find the percentile of\n    :param int k: The percentile to find\n    :rtype: float or int\n\n    \"\"\"\n    if not values:\n        return None\n    values.sort()\n    index = (len(values) * (float(k) / 100)) - 1\n    return values[int(math.ceil(index))]", "title": ""}
{"_id": "d9440", "text": "def document(schema):\n    \"\"\"Print a documented teleport version of the schema.\"\"\"\n    teleport_schema = from_val(schema)\n    return json.dumps(teleport_schema, sort_keys=True, indent=2)", "title": ""}
{"_id": "d9441", "text": "def get_closest_index(myList, myNumber):\n    \"\"\"\n    Assumes myList is sorted. Returns closest value to myNumber.\n    If two numbers are equally close, return the smallest number.\n\n    Parameters\n    ----------\n    myList : array\n        The list in which to find the closest value to myNumber\n    myNumber : float\n        The number to find the closest to in MyList\n\n    Returns\n    -------\n    closest_values_index : int\n        The index in the array of the number closest to myNumber in myList\n    \"\"\"\n    closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n    return closest_values_index", "title": ""}
{"_id": "d9442", "text": "def getScreenDims(self):\n        \"\"\"returns a tuple that contains (screen_width,screen_height)\n        \"\"\"\n        width = ale_lib.getScreenWidth(self.obj)\n        height = ale_lib.getScreenHeight(self.obj)\n        return (width,height)", "title": ""}
{"_id": "d9443", "text": "def on_stop(self):\n        \"\"\"\n        stop publisher\n        \"\"\"\n        LOGGER.debug(\"zeromq.Publisher.on_stop\")\n        self.zmqsocket.close()\n        self.zmqcontext.destroy()", "title": ""}
{"_id": "d9444", "text": "def strip_spaces(x):\n    \"\"\"\n    Strips spaces\n    :param x:\n    :return:\n    \"\"\"\n    x = x.replace(b' ', b'')\n    x = x.replace(b'\\t', b'')\n    return x", "title": ""}
{"_id": "d9445", "text": "def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to be padded.\n\n        Returns:\n            PIL Image: Padded image.\n        \"\"\"\n        return F.pad(img, self.padding, self.fill, self.padding_mode)", "title": ""}
{"_id": "d9446", "text": "def get_substring_idxs(substr, string):\n    \"\"\"\n    Return a list of indexes of substr. If substr not found, list is\n    empty.\n\n    Arguments:\n        substr (str): Substring to match.\n        string (str): String to match in.\n\n    Returns:\n        list of int: Start indices of substr.\n    \"\"\"\n    return [match.start() for match in re.finditer(substr, string)]", "title": ""}
{"_id": "d9447", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d9448", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d9449", "text": "def add_matplotlib_cmap(cm, name=None):\n    \"\"\"Add a matplotlib colormap.\"\"\"\n    global cmaps\n    cmap = matplotlib_to_ginga_cmap(cm, name=name)\n    cmaps[cmap.name] = cmap", "title": ""}
{"_id": "d9450", "text": "def accuracy(self):\n        \"\"\"Calculates accuracy\n\n        :return: Accuracy\n        \"\"\"\n        true_pos = self.matrix[0][0]\n        false_pos = self.matrix[1][0]\n        false_neg = self.matrix[0][1]\n        true_neg = self.matrix[1][1]\n\n        num = 1.0 * (true_pos + true_neg)\n        den = true_pos + true_neg + false_pos + false_neg\n\n        return divide(num, den)", "title": ""}
{"_id": "d9451", "text": "def stackplot(marray, seconds=None, start_time=None, ylabels=None):\n    \"\"\"\n    will plot a stack of traces one above the other assuming\n    marray.shape = numRows, numSamples\n    \"\"\"\n    tarray = np.transpose(marray)\n    stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)\n    plt.show()", "title": ""}
{"_id": "d9452", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d9453", "text": "def asyncStarCmap(asyncCallable, iterable):\n    \"\"\"itertools.starmap for deferred callables using cooperative multitasking\n    \"\"\"\n    results = []\n    yield coopStar(asyncCallable, results.append, iterable)\n    returnValue(results)", "title": ""}
{"_id": "d9454", "text": "def size_on_disk(self):\n        \"\"\"\n        :return: size of the entire schema in bytes\n        \"\"\"\n        return int(self.connection.query(\n            \"\"\"\n            SELECT SUM(data_length + index_length)\n            FROM information_schema.tables WHERE table_schema='{db}'\n            \"\"\".format(db=self.database)).fetchone()[0])", "title": ""}
{"_id": "d9455", "text": "def _ReturnConnection(self):\n\t\t\"\"\"\n\t\tReturns a connection back to the pool\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 9/7/2008\n\t\t\"\"\"\n\t\tif self.conn is not None:\n\t\t\tif self.connInfo.commitOnEnd is True or self.commitOnEnd is True:\n\t\t\t\tself.conn.Commit()\n\t\t\t\t\t\n\t\t\tPool().returnConnection(self.conn)\n\t\t\tself.conn = None", "title": ""}
{"_id": "d9456", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d9457", "text": "def git_tag(tag):\n    \"\"\"Tags the current version.\"\"\"\n    print('Tagging \"{}\"'.format(tag))\n    msg = '\"Released version {}\"'.format(tag)\n    Popen(['git', 'tag', '-s', '-m', msg, tag]).wait()", "title": ""}
{"_id": "d9458", "text": "def end_index(self):\n        \"\"\"\n        Returns the 1-based index of the last object on this page,\n        relative to total objects found (hits).\n        \"\"\"\n        return ((self.number - 1) * self.paginator.per_page +\n            len(self.object_list))", "title": ""}
{"_id": "d9459", "text": "def make_post_request(self, url, auth, json_payload):\n        \"\"\"This function executes the request with the provided\n        json payload and return the json response\"\"\"\n        response = requests.post(url, auth=auth, json=json_payload)\n        return response.json()", "title": ""}
{"_id": "d9460", "text": "def display_len(text):\n    \"\"\"\n    Get the display length of a string. This can differ from the character\n    length if the string contains wide characters.\n    \"\"\"\n    text = unicodedata.normalize('NFD', text)\n    return sum(char_width(char) for char in text)", "title": ""}
{"_id": "d9461", "text": "def get_pg_connection(host, user, port, password, database, ssl={}):\n    \"\"\" PostgreSQL connection \"\"\"\n\n    return psycopg2.connect(host=host,\n                            user=user,\n                            port=port,\n                            password=password,\n                            dbname=database,\n                            sslmode=ssl.get('sslmode', None),\n                            sslcert=ssl.get('sslcert', None),\n                            sslkey=ssl.get('sslkey', None),\n                            sslrootcert=ssl.get('sslrootcert', None),\n                            )", "title": ""}
{"_id": "d9462", "text": "def get_from_headers(request, key):\n    \"\"\"Try to read a value named ``key`` from the headers.\n    \"\"\"\n    value = request.headers.get(key)\n    return to_native(value)", "title": ""}
{"_id": "d9463", "text": "def pprint_for_ordereddict():\n    \"\"\"\n    Context manager that causes pprint() to print OrderedDict objects as nicely\n    as standard Python dictionary objects.\n    \"\"\"\n    od_saved = OrderedDict.__repr__\n    try:\n        OrderedDict.__repr__ = dict.__repr__\n        yield\n    finally:\n        OrderedDict.__repr__ = od_saved", "title": ""}
{"_id": "d9464", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d9465", "text": "def csvpretty(csvfile: csvfile=sys.stdin):\n    \"\"\" Pretty print a CSV file. \"\"\"\n    shellish.tabulate(csv.reader(csvfile))", "title": ""}
{"_id": "d9466", "text": "def uniquify_list(L):\n    \"\"\"Same order unique list using only a list compression.\"\"\"\n    return [e for i, e in enumerate(L) if L.index(e) == i]", "title": ""}
{"_id": "d9467", "text": "def unique_element(ll):\n    \"\"\" returns unique elements from a list preserving the original order \"\"\"\n    seen = {}\n    result = []\n    for item in ll:\n        if item in seen:\n            continue\n        seen[item] = 1\n        result.append(item)\n    return result", "title": ""}
{"_id": "d9468", "text": "def pp_xml(body):\n    \"\"\"Pretty print format some XML so it's readable.\"\"\"\n    pretty = xml.dom.minidom.parseString(body)\n    return pretty.toprettyxml(indent=\"  \")", "title": ""}
{"_id": "d9469", "text": "def get_mi_vec(slab):\n    \"\"\"\n    Convenience function which returns the unit vector aligned\n    with the miller index.\n    \"\"\"\n    mvec = np.cross(slab.lattice.matrix[0], slab.lattice.matrix[1])\n    return mvec / np.linalg.norm(mvec)", "title": ""}
{"_id": "d9470", "text": "def print_param_values(self_):\n        \"\"\"Print the values of all this object's Parameters.\"\"\"\n        self = self_.self\n        for name,val in self.param.get_param_values():\n            print('%s.%s = %s' % (self.name,name,val))", "title": ""}
{"_id": "d9471", "text": "def get_week_start_end_day():\n    \"\"\"\n    Get the week start date and end date\n    \"\"\"\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))", "title": ""}
{"_id": "d9472", "text": "def raw_print(*args, **kw):\n    \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()", "title": ""}
{"_id": "d9473", "text": "def get_screen_resolution(self):\n        \"\"\"Return the screen resolution of the primary screen.\"\"\"\n        widget = QDesktopWidget()\n        geometry = widget.availableGeometry(widget.primaryScreen())\n        return geometry.width(), geometry.height()", "title": ""}
{"_id": "d9474", "text": "def info(txt):\n    \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d9475", "text": "def stringc(text, color):\n    \"\"\"\n    Return a string with terminal colors.\n    \"\"\"\n    if has_colors:\n        text = str(text)\n\n        return \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"\n    else:\n        return text", "title": ""}
{"_id": "d9476", "text": "def _format_json(data, theme):\n    \"\"\"Pretty print a dict as a JSON, with colors if pygments is present.\"\"\"\n    output = json.dumps(data, indent=2, sort_keys=True)\n\n    if pygments and sys.stdout.isatty():\n        style = get_style_by_name(theme)\n        formatter = Terminal256Formatter(style=style)\n        return pygments.highlight(output, JsonLexer(), formatter)\n\n    return output", "title": ""}
{"_id": "d9477", "text": "def move_page_bottom(self):\n        \"\"\"\n        Move the cursor to the last item on the page.\n        \"\"\"\n        self.nav.page_index = self.content.range[1]\n        self.nav.cursor_index = 0\n        self.nav.inverted = True", "title": ""}
{"_id": "d9478", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d9479", "text": "def empty_tree(input_list):\n    \"\"\"Recursively iterate through values in nested lists.\"\"\"\n    for item in input_list:\n        if not isinstance(item, list) or not empty_tree(item):\n            return False\n    return True", "title": ""}
{"_id": "d9480", "text": "def wait_for_url(url, timeout=DEFAULT_TIMEOUT):\n    \"\"\"\n    Return True if connection to the host and port specified in url\n    is successful within the timeout.\n\n    @param url: str: connection url for a TCP service\n    @param timeout: int: length of time in seconds to try to connect before giving up\n    @raise RuntimeError: if no port is given or can't be guessed via the scheme\n    @return: bool\n    \"\"\"\n    service = ServiceURL(url, timeout)\n    return service.wait()", "title": ""}
{"_id": "d9481", "text": "def print_float(self, value, decimal_digits=2, justify_right=True):\n        \"\"\"Print a numeric value to the display.  If value is negative\n        it will be printed with a leading minus sign.  Decimal digits is the\n        desired number of digits after the decimal point.\n        \"\"\"\n        format_string = '{{0:0.{0}F}}'.format(decimal_digits)\n        self.print_number_str(format_string.format(value), justify_right)", "title": ""}
{"_id": "d9482", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d9483", "text": "def _stream_docker_logs(self):\n        \"\"\"Stream stdout and stderr from the task container to this\n        process's stdout and stderr, respectively.\n        \"\"\"\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()", "title": ""}
{"_id": "d9484", "text": "def test3():\n    \"\"\"Test the multiprocess\n    \"\"\"\n    import time\n    \n    p = MVisionProcess()\n    p.start()\n    time.sleep(5)\n    p.stop()", "title": ""}
{"_id": "d9485", "text": "def _tuple_repr(data):\n    \"\"\"Return a repr() for a list/tuple\"\"\"\n    if len(data) == 1:\n        return \"(%s,)\" % rpr(data[0])\n    else:\n        return \"(%s)\" % \", \".join([rpr(x) for x in data])", "title": ""}
{"_id": "d9486", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d9487", "text": "def pprint(o, stream=None, indent=1, width=80, depth=None):\n    \"\"\"Pretty-print a Python o to a stream [default is sys.stdout].\"\"\"\n    printer = PrettyPrinter(\n        stream=stream, indent=indent, width=width, depth=depth)\n    printer.pprint(o)", "title": ""}
{"_id": "d9488", "text": "def get_highlighted_code(name, code, type='terminal'):\n    \"\"\"\n    If pygments are available on the system\n    then returned output is colored. Otherwise\n    unchanged content is returned.\n    \"\"\"\n    import logging\n    try:\n        import pygments\n        pygments\n    except ImportError:\n        return code\n    from pygments import highlight\n    from pygments.lexers import guess_lexer_for_filename, ClassNotFound\n    from pygments.formatters import TerminalFormatter\n\n    try:\n        lexer = guess_lexer_for_filename(name, code)\n        formatter = TerminalFormatter()\n        content = highlight(code, lexer, formatter)\n    except ClassNotFound:\n        logging.debug(\"Couldn't guess Lexer, will not use pygments.\")\n        content = code\n    return content", "title": ""}
{"_id": "d9489", "text": "def to_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case. For example, \"some_var\" would become \"someVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.lstrip('_').split('_')\n    return parts[0] + ''.join([i.title() for i in parts[1:]])", "title": ""}
{"_id": "d9490", "text": "def version_triple(tag):\n    \"\"\"\n    returns: a triple of integers from a version tag\n    \"\"\"\n    groups = re.match(r'v?(\\d+)\\.(\\d+)\\.(\\d+)', tag).groups()\n    return tuple(int(n) for n in groups)", "title": ""}
{"_id": "d9491", "text": "def kill_mprocess(process):\n    \"\"\"kill process\n    Args:\n        process - Popen object for process\n    \"\"\"\n    if process and proc_alive(process):\n        process.terminate()\n        process.communicate()\n    return not proc_alive(process)", "title": ""}
{"_id": "d9492", "text": "def detect(filename, include_confidence=False):\n    \"\"\"\n    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)\n    \"\"\"\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", "title": ""}
{"_id": "d9493", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d9494", "text": "def average_price(quantity_1, price_1, quantity_2, price_2):\n    \"\"\"Calculates the average price between two asset states.\"\"\"\n    return (quantity_1 * price_1 + quantity_2 * price_2) / \\\n            (quantity_1 + quantity_2)", "title": ""}
{"_id": "d9495", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d9496", "text": "def tick(self):\n        \"\"\"Add one tick to progress bar\"\"\"\n        self.current += 1\n        if self.current == self.factor:\n            sys.stdout.write('+')\n            sys.stdout.flush()\n            self.current = 0", "title": ""}
{"_id": "d9497", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d9498", "text": "def _set_property(self, val, *args):\n        \"\"\"Private method that sets the value currently of the property\"\"\"\n        val = UserClassAdapter._set_property(self, val, *args)\n        if val:\n            Adapter._set_property(self, val, *args)\n        return val", "title": ""}
{"_id": "d9499", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d9500", "text": "def lazy_property(function):\n    \"\"\"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).\n    \"\"\"\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", "title": ""}
{"_id": "d9501", "text": "def incr(self, key, incr_by=1):\n        \"\"\"Increment the key by the given amount.\"\"\"\n        return self.database.hincrby(self.key, key, incr_by)", "title": ""}
{"_id": "d9502", "text": "def read_proto_object(fobj, klass):\n    \"\"\"Read a block of data and parse using the given protobuf object.\"\"\"\n    log.debug('%s chunk', klass.__name__)\n    obj = klass()\n    obj.ParseFromString(read_block(fobj))\n    log.debug('Header: %s', str(obj))\n    return obj", "title": ""}
{"_id": "d9503", "text": "def load(filename):\n    \"\"\"\n    Load the state from the given file, moving to the file's directory during\n    load (temporarily, moving back after loaded)\n\n    Parameters\n    ----------\n    filename : string\n        name of the file to open, should be a .pkl file\n    \"\"\"\n    path, name = os.path.split(filename)\n    path = path or '.'\n\n    with util.indir(path):\n        return pickle.load(open(name, 'rb'))", "title": ""}
{"_id": "d9504", "text": "def _prepare_proxy(self, conn):\n        \"\"\"\n        Establish tunnel connection early, because otherwise httplib\n        would improperly set Host: header to proxy's IP:port.\n        \"\"\"\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n        conn.connect()", "title": ""}
{"_id": "d9505", "text": "def best(self):\n        \"\"\"\n        Returns the element with the highest probability.\n        \"\"\"\n        b = (-1e999999, None)\n        for k, c in iteritems(self.counts):\n            b = max(b, (c, k))\n        return b[1]", "title": ""}
{"_id": "d9506", "text": "def map(cls, iterable, func, *a, **kw):\n    \"\"\"\n    Iterable-first replacement of Python's built-in `map()` function.\n    \"\"\"\n\n    return cls(func(x, *a, **kw) for x in iterable)", "title": ""}
{"_id": "d9507", "text": "def indent(self, message):\n        \"\"\"\n        Sets the indent for standardized output\n        :param message: (str)\n        :return: (str)\n        \"\"\"\n        indent = self.indent_char * self.indent_size\n        return indent + message", "title": ""}
{"_id": "d9508", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d9509", "text": "def assert_called_once(_mock_self):\n        \"\"\"assert that the mock was called only once.\n        \"\"\"\n        self = _mock_self\n        if not self.call_count == 1:\n            msg = (\"Expected '%s' to have been called once. Called %s times.\" %\n                   (self._mock_name or 'mock', self.call_count))\n            raise AssertionError(msg)", "title": ""}
{"_id": "d9510", "text": "def unique_inverse(item_list):\n    \"\"\"\n    Like np.unique(item_list, return_inverse=True)\n    \"\"\"\n    import utool as ut\n    unique_items = ut.unique(item_list)\n    inverse = list_alignment(unique_items, item_list)\n    return unique_items, inverse", "title": ""}
{"_id": "d9511", "text": "def generate_random_string(chars=7):\n    \"\"\"\n\n    :param chars:\n    :return:\n    \"\"\"\n    return u\"\".join(random.sample(string.ascii_letters * 2 + string.digits, chars))", "title": ""}
{"_id": "d9512", "text": "def omnihash(obj):\n    \"\"\" recursively hash unhashable objects \"\"\"\n    if isinstance(obj, set):\n        return hash(frozenset(omnihash(e) for e in obj))\n    elif isinstance(obj, (tuple, list)):\n        return hash(tuple(omnihash(e) for e in obj))\n    elif isinstance(obj, dict):\n        return hash(frozenset((k, omnihash(v)) for k, v in obj.items()))\n    else:\n        return hash(obj)", "title": ""}
{"_id": "d9513", "text": "def cli_command_quit(self, msg):\n        \"\"\"\\\n        kills the child and exits\n        \"\"\"\n        if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:\n            self.sprocess.proc.kill()\n        else:\n            sys.exit(0)", "title": ""}
{"_id": "d9514", "text": "def positive_integer(anon, obj, field, val):\n    \"\"\"\n    Returns a random positive integer (for a Django PositiveIntegerField)\n    \"\"\"\n    return anon.faker.positive_integer(field=field)", "title": ""}
{"_id": "d9515", "text": "def kill_process_children(pid):\n    \"\"\"Find and kill child processes of a process.\n\n    :param pid: PID of parent process (process ID)\n    :return: Nothing\n    \"\"\"\n    if sys.platform == \"darwin\":\n        kill_process_children_osx(pid)\n    elif sys.platform == \"linux\":\n        kill_process_children_unix(pid)\n    else:\n        pass", "title": ""}
{"_id": "d9516", "text": "def positive_integer(anon, obj, field, val):\n    \"\"\"\n    Returns a random positive integer (for a Django PositiveIntegerField)\n    \"\"\"\n    return anon.faker.positive_integer(field=field)", "title": ""}
{"_id": "d9517", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d9518", "text": "def is_integer(obj):\n    \"\"\"Is this an integer.\n\n    :param object obj:\n    :return:\n    \"\"\"\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))", "title": ""}
{"_id": "d9519", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d9520", "text": "def _get_column_types(self, data):\n        \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n        columns = list(zip_longest(*data))\n        return [self._get_column_type(column) for column in columns]", "title": ""}
{"_id": "d9521", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d9522", "text": "def get_var_type(self, name):\n        \"\"\"\n        Return type string, compatible with numpy.\n        \"\"\"\n        name = create_string_buffer(name)\n        type_ = create_string_buffer(MAXSTRLEN)\n        self.library.get_var_type.argtypes = [c_char_p, c_char_p]\n        self.library.get_var_type(name, type_)\n        return type_.value", "title": ""}
{"_id": "d9523", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d9524", "text": "def paginate(self, request, offset=0, limit=None):\n        \"\"\"Paginate queryset.\"\"\"\n        return self.collection.offset(offset).limit(limit), self.collection.count()", "title": ""}
{"_id": "d9525", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d9526", "text": "def _load_data(filepath):\n  \"\"\"Loads the images and latent values into Numpy arrays.\"\"\"\n  with h5py.File(filepath, \"r\") as h5dataset:\n    image_array = np.array(h5dataset[\"images\"])\n    # The 'label' data set in the hdf5 file actually contains the float values\n    # and not the class labels.\n    values_array = np.array(h5dataset[\"labels\"])\n  return image_array, values_array", "title": ""}
{"_id": "d9527", "text": "def get_mnist(data_type=\"train\", location=\"/tmp/mnist\"):\n    \"\"\"\n    Get mnist dataset with features and label as ndarray.\n    Data would be downloaded automatically if it doesn't present at the specific location.\n\n    :param data_type: \"train\" for training data and \"test\" for testing data.\n    :param location: Location to store mnist dataset.\n    :return: (features: ndarray, label: ndarray)\n    \"\"\"\n    X, Y = mnist.read_data_sets(location, data_type)\n    return X, Y + 1", "title": ""}
{"_id": "d9528", "text": "def file_to_str(fname):\n    \"\"\"\n    Read a file into a string\n    PRE: fname is a small file (to avoid hogging memory and its discontents)\n    \"\"\"\n    data = None\n    # rU = read with Universal line terminator\n    with open(fname, 'rU') as fd:\n        data = fd.read()\n    return data", "title": ""}
{"_id": "d9529", "text": "def load_graph_from_rdf(fname):\n    \"\"\" reads an RDF file into a graph \"\"\"\n    print(\"reading RDF from \" + fname + \"....\")\n    store = Graph()\n    store.parse(fname, format=\"n3\")\n    print(\"Loaded \" + str(len(store)) + \" tuples\")\n    return store", "title": ""}
{"_id": "d9530", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d9531", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d9532", "text": "def map(cls, iterable, func, *a, **kw):\n    \"\"\"\n    Iterable-first replacement of Python's built-in `map()` function.\n    \"\"\"\n\n    return cls(func(x, *a, **kw) for x in iterable)", "title": ""}
{"_id": "d9533", "text": "def read(fname):\n    \"\"\"Quick way to read a file content.\"\"\"\n    content = None\n    with open(os.path.join(here, fname)) as f:\n        content = f.read()\n    return content", "title": ""}
{"_id": "d9534", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d9535", "text": "def INIT_LIST_EXPR(self, cursor):\n        \"\"\"Returns a list of literal values.\"\"\"\n        values = [self.parse_cursor(child)\n                  for child in list(cursor.get_children())]\n        return values", "title": ""}
{"_id": "d9536", "text": "def read_stdin():\n    \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n    if sys.stdin.isatty() and sys.stdout.isatty():\n        print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n    return sys.stdin.read()", "title": ""}
{"_id": "d9537", "text": "def _generate_plane(normal, origin):\n    \"\"\" Returns a vtk.vtkPlane \"\"\"\n    plane = vtk.vtkPlane()\n    plane.SetNormal(normal[0], normal[1], normal[2])\n    plane.SetOrigin(origin[0], origin[1], origin[2])\n    return plane", "title": ""}
{"_id": "d9538", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d9539", "text": "def run(self, forever=True):\n        \"\"\"start the bot\"\"\"\n        loop = self.create_connection()\n        self.add_signal_handlers()\n        if forever:\n            loop.run_forever()", "title": ""}
{"_id": "d9540", "text": "def ReadTif(tifFile):\n        \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n        img = Image.open(tifFile)\n        img = np.array(img)\n        return img", "title": ""}
{"_id": "d9541", "text": "def cleanup(self):\n        \"\"\"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.\n\n        \"\"\"\n\n        for instance in self.context:\n            del(instance)\n\n        for plugin in self.plugins:\n            del(plugin)", "title": ""}
{"_id": "d9542", "text": "def compute_depth(self):\n        \"\"\"\n        Recursively computes true depth of the subtree. Should only\n        be needed for debugging. Unless something is wrong, the\n        depth field should reflect the correct depth of the subtree.\n        \"\"\"\n        left_depth = self.left_node.compute_depth() if self.left_node else 0\n        right_depth = self.right_node.compute_depth() if self.right_node else 0\n        return 1 + max(left_depth, right_depth)", "title": ""}
{"_id": "d9543", "text": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "title": ""}
{"_id": "d9544", "text": "def redirect_output(fileobj):\n    \"\"\"Redirect standard out to file.\"\"\"\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old", "title": ""}
{"_id": "d9545", "text": "def convert_to_yaml(\n        name, value, indentation, indexOfColon, show_multi_line_character):\n    \"\"\"converts a value list into yaml syntax\n    :param name: name of object (example: phone)\n    :type name: str\n    :param value: object contents\n    :type value: str, list(str), list(list(str))\n    :param indentation: indent all by number of spaces\n    :type indentation: int\n    :param indexOfColon: use to position : at the name string (-1 for no space)\n    :type indexOfColon: int\n    :param show_multi_line_character: option to hide \"|\"\n    :type show_multi_line_character: boolean\n    :returns: yaml formatted string array of name, value pair\n    :rtype: list(str)\n    \"\"\"\n    strings = []\n    if isinstance(value, list):\n        # special case for single item lists:\n        if len(value) == 1 \\\n                and isinstance(value[0], str):\n            # value = [\"string\"] should not be converted to\n            # name:\n            #   - string\n            # but to \"name: string\" instead\n            value = value[0]\n        elif len(value) == 1 \\\n                and isinstance(value[0], list) \\\n                and len(value[0]) == 1 \\\n                and isinstance(value[0][0], str):\n            # same applies to value = [[\"string\"]]\n            value = value[0][0]\n    if isinstance(value, str):\n        strings.append(\"%s%s%s: %s\" % (\n            ' ' * indentation, name, ' ' * (indexOfColon-len(name)),\n            indent_multiline_string(value, indentation+4,\n                                    show_multi_line_character)))\n    elif isinstance(value, list):\n        strings.append(\"%s%s%s: \" % (\n            ' ' * indentation, name, ' ' * (indexOfColon-len(name))))\n        for outer in value:\n            # special case for single item sublists\n            if isinstance(outer, list) \\\n                    and len(outer) == 1 \\\n                    and isinstance(outer[0], str):\n                # outer = [\"string\"] should not be converted to\n                # -\n                #   - string\n                # but to \"- string\" instead\n                outer = outer[0]\n            if isinstance(outer, str):\n                strings.append(\"%s- %s\" % (\n                    ' ' * (indentation+4), indent_multiline_string(\n                        outer, indentation+8, show_multi_line_character)))\n            elif isinstance(outer, list):\n                strings.append(\"%s- \" % (' ' * (indentation+4)))\n                for inner in outer:\n                    if isinstance(inner, str):\n                        strings.append(\"%s- %s\" % (\n                            ' ' * (indentation+8), indent_multiline_string(\n                                inner, indentation+12,\n                                show_multi_line_character)))\n    return strings", "title": ""}
{"_id": "d9546", "text": "def __exit__(self, *args):\n        \"\"\"Redirect stdout back to the original stdout.\"\"\"\n        sys.stdout = self._orig\n        self._devnull.close()", "title": ""}
{"_id": "d9547", "text": "def main(idle):\n    \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n    while True:\n\n        LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n        time.sleep(idle)", "title": ""}
{"_id": "d9548", "text": "def disable_stdout_buffering():\n    \"\"\"This turns off stdout buffering so that outputs are immediately\n    materialized and log messages show up before the program exits\"\"\"\n    stdout_orig = sys.stdout\n    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n    # NOTE(brandyn): This removes the original stdout\n    return stdout_orig", "title": ""}
{"_id": "d9549", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d9550", "text": "def _internal_kv_get(key):\n    \"\"\"Fetch the value of a binary key.\"\"\"\n\n    worker = ray.worker.get_global_worker()\n    if worker.mode == ray.worker.LOCAL_MODE:\n        return _local.get(key)\n\n    return worker.redis_client.hget(key, \"value\")", "title": ""}
{"_id": "d9551", "text": "def comment (self, s, **args):\n        \"\"\"Write DOT comment.\"\"\"\n        self.write(u\"// \")\n        self.writeln(s=s, **args)", "title": ""}
{"_id": "d9552", "text": "def rpop(self, key):\n        \"\"\"Emulate lpop.\"\"\"\n        redis_list = self._get_list(key, 'RPOP')\n\n        if self._encode(key) not in self.redis:\n            return None\n\n        try:\n            value = redis_list.pop()\n            if len(redis_list) == 0:\n                self.delete(key)\n            return value\n        except (IndexError):\n            # Redis returns nil if popping from an empty list\n            return None", "title": ""}
{"_id": "d9553", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d9554", "text": "def exists(self):\n        \"\"\"\n        Returns true if the job is still running or zero-os still knows about this job ID\n\n        After a job is finished, a job remains on zero-os for max of 5min where you still can read the job result\n        after the 5 min is gone, the job result is no more fetchable\n        :return: bool\n        \"\"\"\n        r = self._client._redis\n        flag = '{}:flag'.format(self._queue)\n        return bool(r.exists(flag))", "title": ""}
{"_id": "d9555", "text": "def disable(self):\n        \"\"\"\n        Disable the button, if in non-expert mode;\n        unset its activity flag come-what-may.\n        \"\"\"\n        if not self._expert:\n            self.config(state='disable')\n        self._active = False", "title": ""}
{"_id": "d9556", "text": "def __setitem__(self, field, value):\n        \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n        return self._client.hset(self.key_prefix, field, self._dumps(value))", "title": ""}
{"_id": "d9557", "text": "def normalize_matrix(matrix):\n  \"\"\"Fold all values of the matrix into [0, 1].\"\"\"\n  abs_matrix = np.abs(matrix.copy())\n  return abs_matrix / abs_matrix.max()", "title": ""}
{"_id": "d9558", "text": "def construct_from_string(cls, string):\n        \"\"\"\n        Construction from a string, raise a TypeError if not\n        possible\n        \"\"\"\n        if string == cls.name:\n            return cls()\n        raise TypeError(\"Cannot construct a '{}' from \"\n                        \"'{}'\".format(cls, string))", "title": ""}
{"_id": "d9559", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d9560", "text": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "title": ""}
{"_id": "d9561", "text": "def colorbar(height, length, colormap):\n    \"\"\"Return the channels of a colorbar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.colorize(cbar)", "title": ""}
{"_id": "d9562", "text": "def parse_domain(url):\n    \"\"\" parse the domain from the url \"\"\"\n    domain_match = lib.DOMAIN_REGEX.match(url)\n    if domain_match:\n        return domain_match.group()", "title": ""}
{"_id": "d9563", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d9564", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d9565", "text": "def add_str(window, line_num, str):\n    \"\"\" attempt to draw str on screen and ignore errors if they occur \"\"\"\n    try:\n        window.addstr(line_num, 0, str)\n    except curses.error:\n        pass", "title": ""}
{"_id": "d9566", "text": "def _cached_search_compile(pattern, re_verbose, re_version, pattern_type):\n    \"\"\"Cached search compile.\"\"\"\n\n    return _bregex_parse._SearchParser(pattern, re_verbose, re_version).parse()", "title": ""}
{"_id": "d9567", "text": "def parse_path(path):\n    \"\"\"Parse path string.\"\"\"\n    version, project = path[1:].split('/')\n    return dict(version=int(version), project=project)", "title": ""}
{"_id": "d9568", "text": "def _match_space_at_line(line):\n    \"\"\"Return a re.match object if an empty comment was found on line.\"\"\"\n    regex = re.compile(r\"^{0}$\".format(_MDL_COMMENT))\n    return regex.match(line)", "title": ""}
{"_id": "d9569", "text": "def commajoin_as_strings(iterable):\n    \"\"\" Join the given iterable with ',' \"\"\"\n    return _(u',').join((six.text_type(i) for i in iterable))", "title": ""}
{"_id": "d9570", "text": "def CleanseComments(line):\n  \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n  Args:\n    line: A line of C++ source.\n\n  Returns:\n    The line with single-line comments removed.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1 and not IsCppString(line[:commentpos]):\n    line = line[:commentpos].rstrip()\n  # get rid of /* ... */\n  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "title": ""}
{"_id": "d9571", "text": "def colorize(string, color, *args, **kwargs):\n    \"\"\"\n    Implements string formatting along with color specified in colorama.Fore\n    \"\"\"\n    string = string.format(*args, **kwargs)\n    return color + string + colorama.Fore.RESET", "title": ""}
{"_id": "d9572", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d9573", "text": "def compute_gradient(self):\n        \"\"\"Compute the gradient of the current model using the training set\n        \"\"\"\n        delta = self.predict(self.X) - self.y\n        return delta.dot(self.X) / len(self.X)", "title": ""}
{"_id": "d9574", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d9575", "text": "def a2s(a):\n    \"\"\"\n     convert 3,3 a matrix to 6 element \"s\" list  (see Tauxe 1998)\n    \"\"\"\n    s = np.zeros((6,), 'f')  # make the a matrix\n    for i in range(3):\n        s[i] = a[i][i]\n    s[3] = a[0][1]\n    s[4] = a[1][2]\n    s[5] = a[0][2]\n    return s", "title": ""}
{"_id": "d9576", "text": "def make_file_read_only(file_path):\n    \"\"\"\n    Removes the write permissions for the given file for owner, groups and others.\n\n    :param file_path: The file whose privileges are revoked.\n    :raise FileNotFoundError: If the given file does not exist.\n    \"\"\"\n    old_permissions = os.stat(file_path).st_mode\n    os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)", "title": ""}
{"_id": "d9577", "text": "def comment (self, s, **args):\n        \"\"\"Write DOT comment.\"\"\"\n        self.write(u\"// \")\n        self.writeln(s=s, **args)", "title": ""}
{"_id": "d9578", "text": "def rm_keys_from_dict(d, keys):\n    \"\"\"\n    Given a dictionary and a key list, remove any data in the dictionary with the given keys.\n\n    :param dict d: Metadata\n    :param list keys: Keys to be removed\n    :return dict d: Metadata\n    \"\"\"\n    # Loop for each key given\n    for key in keys:\n        # Is the key in the dictionary?\n        if key in d:\n            try:\n                d.pop(key, None)\n            except KeyError:\n                # Not concerned with an error. Keep going.\n                pass\n    return d", "title": ""}
{"_id": "d9579", "text": "def to_pydatetime(self):\n        \"\"\"\n        Converts datetimeoffset object into Python's datetime.datetime object\n        @return: time zone aware datetime.datetime\n        \"\"\"\n        dt = datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())\n        from .tz import FixedOffsetTimezone\n        return dt.replace(tzinfo=_utc).astimezone(FixedOffsetTimezone(self._offset))", "title": ""}
{"_id": "d9580", "text": "def remove_elements(target, indices):\n    \"\"\"Remove multiple elements from a list and return result.\n    This implementation is faster than the alternative below.\n    Also note the creation of a new list to avoid altering the\n    original. We don't have any current use for the original\n    intact list, but may in the future...\"\"\"\n\n    copied = list(target)\n\n    for index in reversed(indices):\n        del copied[index]\n    return copied", "title": ""}
{"_id": "d9581", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d9582", "text": "def abfIDfromFname(fname):\n    \"\"\"given a filename, return the ABFs ID string.\"\"\"\n    fname=os.path.abspath(fname)\n    basename=os.path.basename(fname)\n    return os.path.splitext(basename)[0]", "title": ""}
{"_id": "d9583", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d9584", "text": "def __delitem__(self, resource):\n        \"\"\"Remove resource instance from internal cache\"\"\"\n        self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None)", "title": ""}
{"_id": "d9585", "text": "def clean(some_string, uppercase=False):\n    \"\"\"\n    helper to clean up an input string\n    \"\"\"\n    if uppercase:\n        return some_string.strip().upper()\n    else:\n        return some_string.strip().lower()", "title": ""}
{"_id": "d9586", "text": "def cleanwrap(func):\n    \"\"\" Wrapper for Zotero._cleanup\n    \"\"\"\n\n    def enc(self, *args, **kwargs):\n        \"\"\" Send each item to _cleanup() \"\"\"\n        return (func(self, item, **kwargs) for item in args)\n\n    return enc", "title": ""}
{"_id": "d9587", "text": "def dict_merge(set1, set2):\n    \"\"\"Joins two dictionaries.\"\"\"\n    return dict(list(set1.items()) + list(set2.items()))", "title": ""}
{"_id": "d9588", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d9589", "text": "def dictmerge(x, y):\n    \"\"\"\n    merge two dictionaries\n    \"\"\"\n    z = x.copy()\n    z.update(y)\n    return z", "title": ""}
{"_id": "d9590", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d9591", "text": "def remove_from_lib(self, name):\n        \"\"\" Remove an object from the bin folder. \"\"\"\n        self.__remove_path(os.path.join(self.root_dir, \"lib\", name))", "title": ""}
{"_id": "d9592", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d9593", "text": "def slugify(string):\n    \"\"\"\n    Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n    \"\"\"\n    string = re.sub('[^\\w .-]', '', string)\n    string = string.replace(\" \", \"-\")\n    return string", "title": ""}
{"_id": "d9594", "text": "def multiply(self, number):\n        \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n        return self.from_list([x * number for x in self.to_list()])", "title": ""}
{"_id": "d9595", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d9596", "text": "def get_property(self, filename):\n        \"\"\"Opens the file and reads the value\"\"\"\n\n        with open(self.filepath(filename)) as f:\n            return f.read().strip()", "title": ""}
{"_id": "d9597", "text": "def remove_bad(string):\n    \"\"\"\n    remove problem characters from string\n    \"\"\"\n    remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n    for c in remove:\n        string = string.replace(c, '_')\n    return string", "title": ""}
{"_id": "d9598", "text": "def get_member(thing_obj, member_string):\n    \"\"\"Get a member from an object by (string) name\"\"\"\n    mems = {x[0]: x[1] for x in inspect.getmembers(thing_obj)}\n    if member_string in mems:\n        return mems[member_string]", "title": ""}
{"_id": "d9599", "text": "def print_latex(o):\n    \"\"\"A function to generate the latex representation of sympy\n    expressions.\"\"\"\n    if can_print_latex(o):\n        s = latex(o, mode='plain')\n        s = s.replace('\\\\dag','\\\\dagger')\n        s = s.strip('$')\n        return '$$%s$$' % s\n    # Fallback to the string printer\n    return None", "title": ""}
{"_id": "d9600", "text": "def get_code(module):\n    \"\"\"\n    Compile and return a Module's code object.\n    \"\"\"\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()", "title": ""}
{"_id": "d9601", "text": "def unsort_vector(data, indices_of_increasing):\n    \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n    return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])", "title": ""}
{"_id": "d9602", "text": "def fopenat(base_fd, path):\n    \"\"\"\n    Does openat read-only, then does fdopen to get a file object\n    \"\"\"\n\n    return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')", "title": ""}
{"_id": "d9603", "text": "def stringify_col(df, col_name):\n    \"\"\"\n    Take a dataframe and string-i-fy a column of values.\n    Turn nan/None into \"\" and all other values into strings.\n\n    Parameters\n    ----------\n    df : dataframe\n    col_name : string\n    \"\"\"\n    df = df.copy()\n    df[col_name] = df[col_name].fillna(\"\")\n    df[col_name] = df[col_name].astype(str)\n    return df", "title": ""}
{"_id": "d9604", "text": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "title": ""}
{"_id": "d9605", "text": "def quote(s, unsafe='/'):\n    \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n    encoded value as the value.\"\"\"\n    res = s.replace('%', '%25')\n    for c in unsafe:\n        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n    return res", "title": ""}
{"_id": "d9606", "text": "def fopenat(base_fd, path):\n    \"\"\"\n    Does openat read-only, then does fdopen to get a file object\n    \"\"\"\n\n    return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')", "title": ""}
{"_id": "d9607", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d9608", "text": "def read_proto_object(fobj, klass):\n    \"\"\"Read a block of data and parse using the given protobuf object.\"\"\"\n    log.debug('%s chunk', klass.__name__)\n    obj = klass()\n    obj.ParseFromString(read_block(fobj))\n    log.debug('Header: %s', str(obj))\n    return obj", "title": ""}
{"_id": "d9609", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d9610", "text": "def __init__(self, find, subcon):\n        \"\"\"Initialize.\"\"\"\n        Subconstruct.__init__(self, subcon)\n        self.find = find", "title": ""}
{"_id": "d9611", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d9612", "text": "def clean_error(err):\n    \"\"\"\n    Take stderr bytes returned from MicroPython and attempt to create a\n    non-verbose error message.\n    \"\"\"\n    if err:\n        decoded = err.decode('utf-8')\n        try:\n            return decoded.split('\\r\\n')[-2]\n        except Exception:\n            return decoded\n    return 'There was an error.'", "title": ""}
{"_id": "d9613", "text": "def fmt_subst(regex, subst):\n    \"\"\"Replace regex with string.\"\"\"\n    return lambda text: re.sub(regex, subst, text) if text else text", "title": ""}
{"_id": "d9614", "text": "def _gzip(self, response):\n        \"\"\"Apply gzip compression to a response.\"\"\"\n        bytesio = six.BytesIO()\n        with gzip.GzipFile(fileobj=bytesio, mode='w') as gz:\n            gz.write(response)\n        return bytesio.getvalue()", "title": ""}
{"_id": "d9615", "text": "def replace_tab_indent(s, replace=\"    \"):\n    \"\"\"\n    :param str s: string with tabs\n    :param str replace: e.g. 4 spaces\n    :rtype: str\n    \"\"\"\n    prefix = get_indent_prefix(s)\n    return prefix.replace(\"\\t\", replace) + s[len(prefix):]", "title": ""}
{"_id": "d9616", "text": "def convert_time_string(date_str):\n    \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n    dt, _, _ = date_str.partition(\".\")\n    dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n    return dt", "title": ""}
{"_id": "d9617", "text": "def get(key, default=None):\n    \"\"\" return the key from the request\n    \"\"\"\n    data = get_form() or get_query_string()\n    return data.get(key, default)", "title": ""}
{"_id": "d9618", "text": "def stringToDate(fmt=\"%Y-%m-%d\"):\n    \"\"\"returns a function to convert a string to a datetime.date instance\n    using the formatting string fmt as in time.strftime\"\"\"\n    import time\n    import datetime\n    def conv_func(s):\n        return datetime.date(*time.strptime(s,fmt)[:3])\n    return conv_func", "title": ""}
{"_id": "d9619", "text": "def _get_url(url):\n    \"\"\"Retrieve requested URL\"\"\"\n    try:\n        data = HTTP_SESSION.get(url, stream=True)\n        data.raise_for_status()\n    except requests.exceptions.RequestException as exc:\n        raise FetcherException(exc)\n\n    return data", "title": ""}
{"_id": "d9620", "text": "def eval_script(self, expr):\n    \"\"\" Evaluates a piece of Javascript in the context of the current page and\n    returns its value. \"\"\"\n    ret = self.conn.issue_command(\"Evaluate\", expr)\n    return json.loads(\"[%s]\" % ret)[0]", "title": ""}
{"_id": "d9621", "text": "def set_basic_auth(self, username, password):\n        \"\"\"\n        Set authenatication.\n        \"\"\"\n        from requests.auth import HTTPBasicAuth\n        self.auth = HTTPBasicAuth(username, password)\n        return self", "title": ""}
{"_id": "d9622", "text": "def set_json_item(key, value):\n    \"\"\" manipulate json data on the fly\n    \"\"\"\n    data = get_json()\n    data[key] = value\n\n    request = get_request()\n    request[\"BODY\"] = json.dumps(data)", "title": ""}
{"_id": "d9623", "text": "def localeselector():\n    \"\"\"Default locale selector used in abilian applications.\"\"\"\n    # if a user is logged in, use the locale from the user settings\n    user = getattr(g, \"user\", None)\n    if user is not None:\n        locale = getattr(user, \"locale\", None)\n        if locale:\n            return locale\n\n    # Otherwise, try to guess the language from the user accept header the browser\n    # transmits.  By default we support en/fr. The best match wins.\n    return request.accept_languages.best_match(\n        current_app.config[\"BABEL_ACCEPT_LANGUAGES\"]\n    )", "title": ""}
{"_id": "d9624", "text": "def xml(cls, res, *args, **kwargs):\n        \"\"\"Parses XML from a response.\"\"\"\n        return parse_xml(res.text, *args, **kwargs)", "title": ""}
{"_id": "d9625", "text": "def _iter_response(self, url, params=None):\n        \"\"\"Return an enumerable that iterates through a multi-page API request\"\"\"\n        if params is None:\n            params = {}\n        params['page_number'] = 1\n\n        # Last page lists itself as next page\n        while True:\n            response = self._request(url, params)\n\n            for item in response['result_data']:\n                yield item\n\n            # Last page lists itself as next page\n            if response['service_meta']['next_page_number'] == params['page_number']:\n                break\n\n            params['page_number'] += 1", "title": ""}
{"_id": "d9626", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d9627", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d9628", "text": "def load_from_file(cls, filename_prefix):\n    \"\"\"Extracts list of subwords from file.\"\"\"\n    filename = cls._filename(filename_prefix)\n    lines, _ = cls._read_lines_from_file(filename)\n    # Strip wrapping single quotes\n    vocab_list = [line[1:-1] for line in lines]\n    return cls(vocab_list=vocab_list)", "title": ""}
{"_id": "d9629", "text": "def _wait_for_response(self):\n\t\t\"\"\"\n\t\tWait until the user accepted or rejected the request\n\t\t\"\"\"\n\t\twhile not self.server.response_code:\n\t\t\ttime.sleep(2)\n\t\ttime.sleep(5)\n\t\tself.server.shutdown()", "title": ""}
{"_id": "d9630", "text": "def plot_and_save(self, **kwargs):\n        \"\"\"Used when the plot method defined does not create a figure nor calls save_plot\n        Then the plot method has to use self.fig\"\"\"\n        self.fig = pyplot.figure()\n        self.plot()\n        self.axes = pyplot.gca()\n        self.save_plot(self.fig, self.axes, **kwargs)\n        pyplot.close(self.fig)", "title": ""}
{"_id": "d9631", "text": "def set_json_item(key, value):\n    \"\"\" manipulate json data on the fly\n    \"\"\"\n    data = get_json()\n    data[key] = value\n\n    request = get_request()\n    request[\"BODY\"] = json.dumps(data)", "title": ""}
{"_id": "d9632", "text": "def request(method, url, **kwargs):\n    \"\"\"\n    Wrapper for the `requests.request()` function.\n    It accepts the same arguments as the original, plus an optional `retries`\n    that overrides the default retry mechanism.\n    \"\"\"\n    retries = kwargs.pop('retries', None)\n    with Session(retries=retries) as session:\n        return session.request(method=method, url=url, **kwargs)", "title": ""}
{"_id": "d9633", "text": "def parse_cookies(self, req, name, field):\n        \"\"\"Pull the value from the cookiejar.\"\"\"\n        return core.get_value(req.COOKIES, name, field)", "title": ""}
{"_id": "d9634", "text": "def read_stdin():\n    \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n    if sys.stdin.isatty() and sys.stdout.isatty():\n        print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n    return sys.stdin.read()", "title": ""}
{"_id": "d9635", "text": "def handle_errors(resp):\n    \"\"\"raise a descriptive exception on a \"bad request\" response\"\"\"\n    if resp.status_code == 400:\n        raise ApiException(json.loads(resp.content).get('message'))\n    return resp", "title": ""}
{"_id": "d9636", "text": "def _dump_enum(self, e, top=''):\n        \"\"\"Dump single enum type.\n        \n        Keyword arguments:\n        top -- top namespace\n        \"\"\"\n        self._print()\n        self._print('enum {} {{'.format(e.name))\n        self.defines.append('{}.{}'.format(top,e.name))\n        \n        self.tabs+=1\n        for v in e.value:\n            self._print('{} = {};'.format(v.name, v.number))\n        self.tabs-=1\n        self._print('}')", "title": ""}
{"_id": "d9637", "text": "async def handle(self, record):\n        \"\"\"\n        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.\n        \"\"\"\n        if (not self.disabled) and self.filter(record):\n            await self.callHandlers(record)", "title": ""}
{"_id": "d9638", "text": "def __print_table(table):\n        \"\"\"Print a list in tabular format\n        Based on https://stackoverflow.com/a/8356620\"\"\"\n\n        col_width = [max(len(x) for x in col) for col in zip(*table)]\n        print(\"| \" + \" | \".join(\"{:{}}\".format(x, col_width[i])\n                                for i, x in enumerate(table[0])) + \" |\")\n        print(\"| \" + \" | \".join(\"{:{}}\".format('-' * col_width[i], col_width[i])\n                                for i, x in enumerate(table[0])) + \" |\")\n        for line in table[1:]:\n            print(\"| \" + \" | \".join(\"{:{}}\".format(x, col_width[i])\n                                    for i, x in enumerate(line)) + \" |\")", "title": ""}
{"_id": "d9639", "text": "def index(m, val):\n    \"\"\"\n    Return the indices of all the ``val`` in ``m``\n    \"\"\"\n    mm = np.array(m)\n    idx_tuple = np.where(mm == val)\n    idx = idx_tuple[0].tolist()\n\n    return idx", "title": ""}
{"_id": "d9640", "text": "def _get_column_types(self, data):\n        \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n        columns = list(zip_longest(*data))\n        return [self._get_column_type(column) for column in columns]", "title": ""}
{"_id": "d9641", "text": "def get_substring_idxs(substr, string):\n    \"\"\"\n    Return a list of indexes of substr. If substr not found, list is\n    empty.\n\n    Arguments:\n        substr (str): Substring to match.\n        string (str): String to match in.\n\n    Returns:\n        list of int: Start indices of substr.\n    \"\"\"\n    return [match.start() for match in re.finditer(substr, string)]", "title": ""}
{"_id": "d9642", "text": "def typename(obj):\n    \"\"\"Returns the type of obj as a string. More descriptive and specific than\n    type(obj), and safe for any object, unlike __class__.\"\"\"\n    if hasattr(obj, '__class__'):\n        return getattr(obj, '__class__').__name__\n    else:\n        return type(obj).__name__", "title": ""}
{"_id": "d9643", "text": "def call_out(command):\n  \"\"\"\n  Run the given command (with shell=False) and return a tuple of\n  (int returncode, str output). Strip the output of enclosing whitespace.\n  \"\"\"\n  # start external command process\n  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n  # get outputs\n  out, _ = p.communicate()\n\n  return p.returncode, out.strip()", "title": ""}
{"_id": "d9644", "text": "def print_item_with_children(ac, classes, level):\n    \"\"\" Print the given item and all children items \"\"\"\n    print_row(ac.id, ac.name, f\"{ac.allocation:,.2f}\", level)\n    print_children_recursively(classes, ac, level + 1)", "title": ""}
{"_id": "d9645", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d9646", "text": "def print_failure_message(message):\n    \"\"\"Print a message indicating failure in red color to STDERR.\n\n    :param message: the message to print\n    :type message: :class:`str`\n    \"\"\"\n    try:\n        import colorama\n\n        print(colorama.Fore.RED + message + colorama.Fore.RESET,\n              file=sys.stderr)\n    except ImportError:\n        print(message, file=sys.stderr)", "title": ""}
{"_id": "d9647", "text": "def MultiArgMax(x):\n  \"\"\"\n  Get tuple (actually a generator) of indices where the max value of\n  array x occurs. Requires that x have a max() method, as x.max()\n  (in the case of NumPy) is much faster than max(x).\n  For a simpler, faster argmax when there is only a single maximum entry,\n  or when knowing only the first index where the maximum occurs,\n  call argmax() on a NumPy array.\n\n  :param x: Any sequence that has a max() method.\n  :returns: Generator with the indices where the max value occurs.\n  \"\"\"\n  m = x.max()\n  return (i for i, v in enumerate(x) if v == m)", "title": ""}
{"_id": "d9648", "text": "def register_view(self, view):\n        \"\"\"Register callbacks for button press events and selection changed\"\"\"\n        super(ListViewController, self).register_view(view)\n        self.tree_view.connect('button_press_event', self.mouse_click)", "title": ""}
{"_id": "d9649", "text": "def rewindbody(self):\n        \"\"\"Rewind the file to the start of the body (if seekable).\"\"\"\n        if not self.seekable:\n            raise IOError, \"unseekable file\"\n        self.fp.seek(self.startofbody)", "title": ""}
{"_id": "d9650", "text": "def _trim(self, somestr):\n        \"\"\" Trim left-right given string \"\"\"\n        tmp = RE_LSPACES.sub(\"\", somestr)\n        tmp = RE_TSPACES.sub(\"\", tmp)\n        return str(tmp)", "title": ""}
{"_id": "d9651", "text": "def copy_user_agent_from_driver(self):\n        \"\"\" 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.\n        \"\"\"\n        selenium_user_agent = self.driver.execute_script(\"return navigator.userAgent;\")\n        self.headers.update({\"user-agent\": selenium_user_agent})", "title": ""}
{"_id": "d9652", "text": "def movingaverage(arr, window):\n    \"\"\"\n    Calculates the moving average (\"rolling mean\") of an array\n    of a certain window size.\n    \"\"\"\n    m = np.ones(int(window)) / int(window)\n    return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')", "title": ""}
{"_id": "d9653", "text": "def raise_(exception=ABSENT, *args, **kwargs):\n    \"\"\"Raise (or re-raises) an exception.\n\n    :param exception: Exception object to raise, or an exception class.\n                      In the latter case, remaining arguments are passed\n                      to the exception's constructor.\n                      If omitted, the currently handled exception is re-raised.\n    \"\"\"\n    if exception is ABSENT:\n        raise\n    else:\n        if inspect.isclass(exception):\n            raise exception(*args, **kwargs)\n        else:\n            if args or kwargs:\n                raise TypeError(\"can't pass arguments along with \"\n                                \"exception object to raise_()\")\n            raise exception", "title": ""}
{"_id": "d9654", "text": "def rotateImage(image, angle):\n    \"\"\"\n        rotates a 2d array to a multiple of 90 deg.\n        0 = default\n        1 = 90 deg. cw\n        2 = 180 deg.\n        3 = 90 deg. ccw\n    \"\"\"\n    image = [list(row) for row in image]\n\n    for n in range(angle % 4):\n        image = list(zip(*image[::-1]))\n\n    return image", "title": ""}
{"_id": "d9655", "text": "def rand_elem(seq, n=None):\n    \"\"\"returns a random element from seq n times. If n is None, it continues indefinitly\"\"\"\n    return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))", "title": ""}
{"_id": "d9656", "text": "def round_to_float(number, precision):\n    \"\"\"Round a float to a precision\"\"\"\n    rounded = Decimal(str(floor((number + precision / 2) // precision))\n                      ) * Decimal(str(precision))\n    return float(rounded)", "title": ""}
{"_id": "d9657", "text": "def round_to_float(number, precision):\n    \"\"\"Round a float to a precision\"\"\"\n    rounded = Decimal(str(floor((number + precision / 2) // precision))\n                      ) * Decimal(str(precision))\n    return float(rounded)", "title": ""}
{"_id": "d9658", "text": "def load_data(filename):\n    \"\"\"\n    :rtype : numpy matrix\n    \"\"\"\n    data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n    return data.as_matrix()", "title": ""}
{"_id": "d9659", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d9660", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d9661", "text": "def call_and_exit(self, cmd, shell=True):\n        \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n        sys.exit(subprocess.call(cmd, shell=shell))", "title": ""}
{"_id": "d9662", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d9663", "text": "def get_pull_request(project, num, auth=False):\n    \"\"\"get pull request info  by number\n    \"\"\"\n    url = \"https://api.github.com/repos/{project}/pulls/{num}\".format(project=project, num=num)\n    if auth:\n        header = make_auth_header()\n    else:\n        header = None\n    response = requests.get(url, headers=header)\n    response.raise_for_status()\n    return json.loads(response.text, object_hook=Obj)", "title": ""}
{"_id": "d9664", "text": "def unpickle_file(picklefile, **kwargs):\n    \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)", "title": ""}
{"_id": "d9665", "text": "def test():  # pragma: no cover\n    \"\"\"Execute the unit tests on an installed copy of unyt.\n\n    Note that this function requires pytest to run. If pytest is not\n    installed this function will raise ImportError.\n    \"\"\"\n    import pytest\n    import os\n\n    pytest.main([os.path.dirname(os.path.abspath(__file__))])", "title": ""}
{"_id": "d9666", "text": "def html_to_text(content):\n    \"\"\" Converts html content to plain text \"\"\"\n    text = None\n    h2t = html2text.HTML2Text()\n    h2t.ignore_links = False\n    text = h2t.handle(content)\n    return text", "title": ""}
{"_id": "d9667", "text": "def list_blobs(self, prefix=''):\n    \"\"\"Lists names of all blobs by their prefix.\"\"\"\n    return [b.name for b in self.bucket.list_blobs(prefix=prefix)]", "title": ""}
{"_id": "d9668", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d9669", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d9670", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d9671", "text": "def save(self, *args, **kwargs):\n        \"\"\"Saves an animation\n\n        A wrapper around :meth:`matplotlib.animation.Animation.save`\n        \"\"\"\n        self.timeline.index -= 1  # required for proper starting point for save\n        self.animation.save(*args, **kwargs)", "title": ""}
{"_id": "d9672", "text": "def lengths_offsets(value):\n    \"\"\"Split the given comma separated value to multiple integer values. \"\"\"\n    values = []\n    for item in value.split(','):\n        item = int(item)\n        values.append(item)\n    return values", "title": ""}
{"_id": "d9673", "text": "def deserialize_ndarray_npy(d):\n    \"\"\"\n    Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's\n    :obj:`save` function.\n\n    Args:\n        d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created\n            using :obj:`numpy.save`.\n\n    Returns:\n        An :obj:`ndarray` object.\n    \"\"\"\n    with io.BytesIO() as f:\n        f.write(json.loads(d['npy']).encode('latin-1'))\n        f.seek(0)\n        return np.load(f)", "title": ""}
{"_id": "d9674", "text": "def created_today(self):\n        \"\"\"Return True if created today.\"\"\"\n        if self.datetime.date() == datetime.today().date():\n            return True\n        return False", "title": ""}
{"_id": "d9675", "text": "def adapt_array(arr):\n    \"\"\"\n    Adapts a Numpy array into an ARRAY string to put into the database.\n\n    Parameters\n    ----------\n    arr: array\n        The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n    Returns\n    -------\n    ARRAY\n            The adapted array object\n\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr), out.seek(0)\n    return buffer(out.read())", "title": ""}
{"_id": "d9676", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d9677", "text": "def adapt_array(arr):\n    \"\"\"\n    Adapts a Numpy array into an ARRAY string to put into the database.\n\n    Parameters\n    ----------\n    arr: array\n        The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n    Returns\n    -------\n    ARRAY\n            The adapted array object\n\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr), out.seek(0)\n    return buffer(out.read())", "title": ""}
{"_id": "d9678", "text": "def delete_all_eggs(self):\n        \"\"\" delete all the eggs in the directory specified \"\"\"\n        path_to_delete = os.path.join(self.egg_directory, \"lib\", \"python\")\n        if os.path.exists(path_to_delete):\n            shutil.rmtree(path_to_delete)", "title": ""}
{"_id": "d9679", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d9680", "text": "def pop():\n        \"\"\"Remove instance from instance list\"\"\"\n        pid = os.getpid()\n        thread = threading.current_thread()\n        Wdb._instances.pop((pid, thread))", "title": ""}
{"_id": "d9681", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d9682", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d9683", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d9684", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d9685", "text": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "title": ""}
{"_id": "d9686", "text": "def remove_dups(seq):\n    \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d9687", "text": "def plot_target(target, ax):\n    \"\"\"Ajoute la target au plot\"\"\"\n    ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)", "title": ""}
{"_id": "d9688", "text": "def kill(self):\n        \"\"\"Kill the browser.\n\n        This is useful when the browser is stuck.\n        \"\"\"\n        if self.process:\n            self.process.kill()\n            self.process.wait()", "title": ""}
{"_id": "d9689", "text": "def _unjsonify(x, isattributes=False):\n    \"\"\"Convert JSON string to an ordered defaultdict.\"\"\"\n    if isattributes:\n        obj = json.loads(x)\n        return dict_class(obj)\n    return json.loads(x)", "title": ""}
{"_id": "d9690", "text": "def delete_s3_bucket(client, resource):\n    \"\"\"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`\n    \"\"\"\n\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()", "title": ""}
{"_id": "d9691", "text": "def escape_link(url):\n    \"\"\"Remove dangerous URL schemes like javascript: and escape afterwards.\"\"\"\n    lower_url = url.lower().strip('\\x00\\x1a \\n\\r\\t')\n    for scheme in _scheme_blacklist:\n        if lower_url.startswith(scheme):\n            return ''\n    return escape(url, quote=True, smart_amp=False)", "title": ""}
{"_id": "d9692", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d9693", "text": "async def send_files_preconf(filepaths, config_path=CONFIG_PATH):\n    \"\"\"Send files using the config.ini settings.\n\n    Args:\n        filepaths (list(str)): A list of filepaths.\n    \"\"\"\n    config = read_config(config_path)\n    subject = \"PDF files from pdfebc\"\n    message = \"\"\n    await send_with_attachments(subject, message, filepaths, config)", "title": ""}
{"_id": "d9694", "text": "def remove_item(self, item):\n        \"\"\"\n        Remove (and un-index) an object\n\n        :param item: object to remove\n        :type item: alignak.objects.item.Item\n        :return: None\n        \"\"\"\n        self.unindex_item(item)\n        self.items.pop(item.uuid, None)", "title": ""}
{"_id": "d9695", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d9696", "text": "def _sanitize(text):\n    \"\"\"Return sanitized Eidos text field for human readability.\"\"\"\n    d = {'-LRB-': '(', '-RRB-': ')'}\n    return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text)", "title": ""}
{"_id": "d9697", "text": "def time2seconds(t):\n    \"\"\"Returns seconds since 0h00.\"\"\"\n    return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6", "title": ""}
{"_id": "d9698", "text": "def strip_querystring(url):\n    \"\"\"Remove the querystring from the end of a URL.\"\"\"\n    p = six.moves.urllib.parse.urlparse(url)\n    return p.scheme + \"://\" + p.netloc + p.path", "title": ""}
{"_id": "d9699", "text": "def dict_from_object(obj: object):\n    \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n    # If object is a dict instance, no need to convert.\n    return (obj if isinstance(obj, dict)\n            else {attr: getattr(obj, attr)\n                  for attr in dir(obj) if not attr.startswith('_')})", "title": ""}
{"_id": "d9700", "text": "def format_screen(strng):\n    \"\"\"Format a string for screen printing.\n\n    This removes some latex-type format codes.\"\"\"\n    # Paragraph continue\n    par_re = re.compile(r'\\\\$',re.MULTILINE)\n    strng = par_re.sub('',strng)\n    return strng", "title": ""}
{"_id": "d9701", "text": "def count_rows(self, table_name):\n        \"\"\"Return the number of entries in a table by counting them.\"\"\"\n        self.table_must_exist(table_name)\n        query = \"SELECT COUNT (*) FROM `%s`\" % table_name.lower()\n        self.own_cursor.execute(query)\n        return int(self.own_cursor.fetchone()[0])", "title": ""}
{"_id": "d9702", "text": "def log_normalize(data):\n    \"\"\"Perform log transform log(x + 1).\n    \n    Parameters\n    ----------\n    data : array_like\n    \n    \"\"\"\n    if sp.issparse(data):\n        data = data.copy()\n        data.data = np.log2(data.data + 1)\n        return data\n\n    return np.log2(data.astype(np.float64) + 1)", "title": ""}
{"_id": "d9703", "text": "def scroll_element_into_view(self):\n        \"\"\"Scroll element into view\n\n        :returns: page element instance\n        \"\"\"\n        x = self.web_element.location['x']\n        y = self.web_element.location['y']\n        self.driver.execute_script('window.scrollTo({0}, {1})'.format(x, y))\n        return self", "title": ""}
{"_id": "d9704", "text": "def _replace(self, data, replacements):\n        \"\"\"\n        Given a list of 2-tuples (find, repl) this function performs all\n        replacements on the input and returns the result.\n        \"\"\"\n        for find, repl in replacements:\n            data = data.replace(find, repl)\n        return data", "title": ""}
{"_id": "d9705", "text": "async def send(self, data):\n        \"\"\" Add data to send queue. \"\"\"\n        self.writer.write(data)\n        await self.writer.drain()", "title": ""}
{"_id": "d9706", "text": "def reset(self):\n        \"\"\"Reset the instance\n\n        - reset rows and header\n        \"\"\"\n\n        self._hline_string = None\n        self._row_size = None\n        self._header = []\n        self._rows = []", "title": ""}
{"_id": "d9707", "text": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    l = [v.strip() for v in value.split(',')]\n    if len(l) == 1:\n        l = value.split()\n    return l", "title": ""}
{"_id": "d9708", "text": "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)", "title": ""}
{"_id": "d9709", "text": "def get_serializable_data_for_fields(model):\n    \"\"\"\n    Return a serialised version of the model's fields which exist as local database\n    columns (i.e. excluding m2m and incoming foreign key relations)\n    \"\"\"\n    pk_field = model._meta.pk\n    # If model is a child via multitable inheritance, use parent's pk\n    while pk_field.remote_field and pk_field.remote_field.parent_link:\n        pk_field = pk_field.remote_field.model._meta.pk\n\n    obj = {'pk': get_field_value(pk_field, model)}\n\n    for field in model._meta.fields:\n        if field.serialize:\n            obj[field.name] = get_field_value(field, model)\n\n    return obj", "title": ""}
{"_id": "d9710", "text": "def restart_program():\n    \"\"\"\n    DOES NOT WORK WELL WITH MOPIDY\n    Hack from\n    https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program\n    to support updating the settings, since mopidy is not able to do that yet\n    Restarts the current program\n    Note: this function does not return. Any cleanup action (like\n    saving data) must be done before calling this function\n    \"\"\"\n\n    python = sys.executable\n    os.execl(python, python, * sys.argv)", "title": ""}
{"_id": "d9711", "text": "def RemoveMethod(self, function):\n        \"\"\"\n        Removes the specified function's MethodWrapper from the\n        added_methods list, so we don't re-bind it when making a clone.\n        \"\"\"\n        self.added_methods = [dm for dm in self.added_methods if not dm.method is function]", "title": ""}
{"_id": "d9712", "text": "def read_key(self, key, bucket_name=None):\n        \"\"\"\n        Reads a key from S3\n\n        :param key: S3 key that will point to the file\n        :type key: str\n        :param bucket_name: Name of the bucket in which the file is stored\n        :type bucket_name: str\n        \"\"\"\n\n        obj = self.get_key(key, bucket_name)\n        return obj.get()['Body'].read().decode('utf-8')", "title": ""}
{"_id": "d9713", "text": "def ylim(self, low, high, index=1):\n        \"\"\"Set yaxis limits.\n\n        Parameters\n        ----------\n        low : number\n        high : number\n        index : int, optional\n\n        Returns\n        -------\n        Chart\n\n        \"\"\"\n        self.layout['yaxis' + str(index)]['range'] = [low, high]\n        return self", "title": ""}
{"_id": "d9714", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d9715", "text": "def copy_default_data_file(filename, module=None):\n    \"\"\"Copies file from default data directory to local directory.\"\"\"\n    if module is None:\n        module = __get_filetypes_module()\n    fullpath = get_default_data_path(filename, module=module)\n    shutil.copy(fullpath, \".\")", "title": ""}
{"_id": "d9716", "text": "def set_logging_config(log_level, handlers):\n    \"\"\"Set python logging library config.\n\n    Run this ONCE at the start of your process. It formats the python logging\n    module's output.\n    Defaults logging level to INFO = 20)\n    \"\"\"\n    logging.basicConfig(\n        format='%(asctime)s %(levelname)s:%(name)s:%(funcName)s: %(message)s',\n        datefmt='%Y-%m-%d %H:%M:%S',\n        level=log_level,\n        handlers=handlers)", "title": ""}
{"_id": "d9717", "text": "def move_back(self, dt):\n        \"\"\" If called after an update, the sprite can move back\n        \"\"\"\n        self._position = self._old_position\n        self.rect.topleft = self._position\n        self.feet.midbottom = self.rect.midbottom", "title": ""}
{"_id": "d9718", "text": "def get_local_image(self, src):\n        \"\"\"\\\n        returns the bytes of the image file on disk\n        \"\"\"\n        return ImageUtils.store_image(self.fetcher, self.article.link_hash, src, self.config)", "title": ""}
{"_id": "d9719", "text": "def rotateImage(image, angle):\n    \"\"\"\n        rotates a 2d array to a multiple of 90 deg.\n        0 = default\n        1 = 90 deg. cw\n        2 = 180 deg.\n        3 = 90 deg. ccw\n    \"\"\"\n    image = [list(row) for row in image]\n\n    for n in range(angle % 4):\n        image = list(zip(*image[::-1]))\n\n    return image", "title": ""}
{"_id": "d9720", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d9721", "text": "def rotateImage(image, angle):\n    \"\"\"\n        rotates a 2d array to a multiple of 90 deg.\n        0 = default\n        1 = 90 deg. cw\n        2 = 180 deg.\n        3 = 90 deg. ccw\n    \"\"\"\n    image = [list(row) for row in image]\n\n    for n in range(angle % 4):\n        image = list(zip(*image[::-1]))\n\n    return image", "title": ""}
{"_id": "d9722", "text": "def reseed_random(seed):\n    \"\"\"Reseed factory.fuzzy's random generator.\"\"\"\n    r = random.Random(seed)\n    random_internal_state = r.getstate()\n    set_random_state(random_internal_state)", "title": ""}
{"_id": "d9723", "text": "def price_rounding(price, decimals=2):\n    \"\"\"Takes a decimal price and rounds to a number of decimal places\"\"\"\n    try:\n        exponent = D('.' + decimals * '0')\n    except InvalidOperation:\n        # Currencies with no decimal places, ex. JPY, HUF\n        exponent = D()\n    return price.quantize(exponent, rounding=ROUND_UP)", "title": ""}
{"_id": "d9724", "text": "def __run(self):\n    \"\"\"Hacked run function, which installs the trace.\"\"\"\n    sys.settrace(self.globaltrace)\n    self.__run_backup()\n    self.run = self.__run_backup", "title": ""}
{"_id": "d9725", "text": "def round_data(filter_data):\n    \"\"\" round the data\"\"\"\n    for index, _ in enumerate(filter_data):\n        filter_data[index][0] = round(filter_data[index][0] / 100.0) * 100.0\n    return filter_data", "title": ""}
{"_id": "d9726", "text": "def _sha1_for_file(filename):\n    \"\"\"Return sha1 for contents of filename.\"\"\"\n    with open(filename, \"rb\") as fileobj:\n        contents = fileobj.read()\n        return hashlib.sha1(contents).hexdigest()", "title": ""}
{"_id": "d9727", "text": "def image_load_time(self):\n        \"\"\"\n        Returns aggregate image load time for all pages.\n        \"\"\"\n        load_times = self.get_load_times('image')\n        return round(mean(load_times), self.decimal_precision)", "title": ""}
{"_id": "d9728", "text": "def _go_to_line(editor, line):\n    \"\"\"\n    Move cursor to this line in the current buffer.\n    \"\"\"\n    b = editor.application.current_buffer\n    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "title": ""}
{"_id": "d9729", "text": "def main(idle):\n    \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n    while True:\n\n        LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n        time.sleep(idle)", "title": ""}
{"_id": "d9730", "text": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n    \"\"\"\n    Returns the last `n` rows in the table\n    \"\"\"\n    return fetch(dbconn, tablename, n, uuid, end=True)", "title": ""}
{"_id": "d9731", "text": "def test():  # pragma: no cover\n    \"\"\"Execute the unit tests on an installed copy of unyt.\n\n    Note that this function requires pytest to run. If pytest is not\n    installed this function will raise ImportError.\n    \"\"\"\n    import pytest\n    import os\n\n    pytest.main([os.path.dirname(os.path.abspath(__file__))])", "title": ""}
{"_id": "d9732", "text": "def pprint(self, seconds):\n        \"\"\"\n        Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n        :param seconds:  The time in seconds.\n        \"\"\"\n        return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))", "title": ""}
{"_id": "d9733", "text": "def update_token_tempfile(token):\n    \"\"\"\n    Example of function for token update\n    \"\"\"\n    with open(tmp, 'w') as f:\n        f.write(json.dumps(token, indent=4))", "title": ""}
{"_id": "d9734", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d9735", "text": "def download_file(save_path, file_url):\n    \"\"\" Download file from http url link \"\"\"\n\n    r = requests.get(file_url)  # create HTTP response object\n\n    with open(save_path, 'wb') as f:\n        f.write(r.content)\n\n    return save_path", "title": ""}
{"_id": "d9736", "text": "def string_to_int( s ):\n  \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n  result = 0\n  for c in s:\n    if not isinstance(c, int): c = ord( c )\n    result = 256 * result + c\n  return result", "title": ""}
{"_id": "d9737", "text": "def write_wave(path, audio, sample_rate):\n    \"\"\"Writes a .wav file.\n\n    Takes path, PCM audio data, and sample rate.\n    \"\"\"\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)", "title": ""}
{"_id": "d9738", "text": "def singleton_per_scope(_cls, _scope=None, _renew=False, *args, **kwargs):\n    \"\"\"Instanciate a singleton per scope.\"\"\"\n\n    result = None\n\n    singletons = SINGLETONS_PER_SCOPES.setdefault(_scope, {})\n\n    if _renew or _cls not in singletons:\n        singletons[_cls] = _cls(*args, **kwargs)\n\n    result = singletons[_cls]\n\n    return result", "title": ""}
{"_id": "d9739", "text": "def array_bytes(array):\n    \"\"\" Estimates the memory of the supplied array in bytes \"\"\"\n    return np.product(array.shape)*np.dtype(array.dtype).itemsize", "title": ""}
{"_id": "d9740", "text": "def functions(self):\n        \"\"\"\n        A list of functions declared or defined in this module.\n        \"\"\"\n        return [v for v in self.globals.values()\n                if isinstance(v, values.Function)]", "title": ""}
{"_id": "d9741", "text": "def skip(self, n):\n        \"\"\"Skip the specified number of elements in the list.\n\n        If the number skipped is greater than the number of elements in\n        the list, hasNext() becomes false and available() returns zero\n        as there are no more elements to retrieve.\n\n        arg:    n (cardinal): the number of elements to skip\n        *compliance: mandatory -- This method must be implemented.*\n\n        \"\"\"\n        try:\n            self._iter_object.skip(n)\n        except AttributeError:\n            for i in range(0, n):\n                self.next()", "title": ""}
{"_id": "d9742", "text": "def getcolslice(self, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1):\n        \"\"\"Get a slice from a table column holding arrays.\n        (see :func:`table.getcolslice`)\"\"\"\n        return self._table.getcolslice(self._column, blc, trc, inc, startrow, nrow, rowincr)", "title": ""}
{"_id": "d9743", "text": "def is_full_slice(obj, l):\n    \"\"\"\n    We have a full length slice.\n    \"\"\"\n    return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and\n            obj.step is None)", "title": ""}
{"_id": "d9744", "text": "def compare(dicts):\n    \"\"\"Compare by iteration\"\"\"\n\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\n    return common_members", "title": ""}
{"_id": "d9745", "text": "def shutdown(self):\n        \"\"\"close socket, immediately.\"\"\"\n        if self.sock:\n            self.sock.close()\n            self.sock = None\n            self.connected = False", "title": ""}
{"_id": "d9746", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d9747", "text": "def run(context, port):\n    \"\"\" Run the Webserver/SocketIO and app\n    \"\"\"\n    global ctx\n    ctx = context\n    app.run(port=port)", "title": ""}
{"_id": "d9748", "text": "def region_from_segment(image, segment):\n    \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n    x, y, w, h = segment\n    return image[y:y + h, x:x + w]", "title": ""}
{"_id": "d9749", "text": "def MatrixSolve(a, rhs, adj):\n    \"\"\"\n    Matrix solve op.\n    \"\"\"\n    return np.linalg.solve(a if not adj else _adjoint(a), rhs),", "title": ""}
{"_id": "d9750", "text": "def rand_elem(seq, n=None):\n    \"\"\"returns a random element from seq n times. If n is None, it continues indefinitly\"\"\"\n    return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))", "title": ""}
{"_id": "d9751", "text": "def sortlevel(self, level=None, ascending=True, sort_remaining=None):\n        \"\"\"\n        For internal compatibility with with the Index API.\n\n        Sort the Index. This is for compat with MultiIndex\n\n        Parameters\n        ----------\n        ascending : boolean, default True\n            False to sort in descending order\n\n        level, sort_remaining are compat parameters\n\n        Returns\n        -------\n        Index\n        \"\"\"\n        return self.sort_values(return_indexer=True, ascending=ascending)", "title": ""}
{"_id": "d9752", "text": "def set_default(self_,param_name,value):\n        \"\"\"\n        Set the default value of param_name.\n\n        Equivalent to setting param_name on the class.\n        \"\"\"\n        cls = self_.cls\n        setattr(cls,param_name,value)", "title": ""}
{"_id": "d9753", "text": "def _write_separator(self):\n        \"\"\"\n        Inserts a horizontal (commented) line tot the generated code.\n        \"\"\"\n        tmp = self._page_width - ((4 * self.__indent_level) + 2)\n        self._write_line('# ' + ('-' * tmp))", "title": ""}
{"_id": "d9754", "text": "def run_test(func, fobj):\n    \"\"\"Run func with argument fobj and measure execution time.\n    @param  func:   function for test\n    @param  fobj:   data for test\n    @return:        execution time\n    \"\"\"\n    gc.disable()\n    try:\n        begin = time.time()\n        func(fobj)\n        end = time.time()\n    finally:\n        gc.enable()\n    return end - begin", "title": ""}
{"_id": "d9755", "text": "def visit_Str(self, node):\n        \"\"\" Set the pythonic string type. \"\"\"\n        self.result[node] = self.builder.NamedType(pytype_to_ctype(str))", "title": ""}
{"_id": "d9756", "text": "def as_tuple(self, value):\n        \"\"\"Utility function which converts lists to tuples.\"\"\"\n        if isinstance(value, list):\n            value = tuple(value)\n        return value", "title": ""}
{"_id": "d9757", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d9758", "text": "def write_color(string, name, style='normal', when='auto'):\n    \"\"\" Write the given colored string to standard out. \"\"\"\n    write(color(string, name, style, when))", "title": ""}
{"_id": "d9759", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d9760", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d9761", "text": "def partition(a, sz): \n    \"\"\"splits iterables a in equal parts of size sz\"\"\"\n    return [a[i:i+sz] for i in range(0, len(a), sz)]", "title": ""}
{"_id": "d9762", "text": "def get_var(name, factory=None):\n    \"\"\"Gets a global variable given its name.\n\n    If factory is not None and the variable is not set, factory\n    is a callable that will set the variable.\n\n    If not set, returns None.\n    \"\"\"\n    if name not in _VARS and factory is not None:\n        _VARS[name] = factory()\n    return _VARS.get(name)", "title": ""}
{"_id": "d9763", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d9764", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d9765", "text": "def parse_prefix(identifier):\n    \"\"\"\n    Parse identifier such as a|c|le|d|li|re|or|AT4G00480.1 and return\n    tuple of prefix string (separated at '|') and suffix (AGI identifier)\n    \"\"\"\n    pf, id = (), identifier\n    if \"|\" in identifier:\n        pf, id = tuple(identifier.split('|')[:-1]), identifier.split('|')[-1]\n\n    return pf, id", "title": ""}
{"_id": "d9766", "text": "def covstr(s):\n  \"\"\" convert string to int or float. \"\"\"\n  try:\n    ret = int(s)\n  except ValueError:\n    ret = float(s)\n  return ret", "title": ""}
{"_id": "d9767", "text": "def split_len(s, length):\n    \"\"\"split string *s* into list of strings no longer than *length*\"\"\"\n    return [s[i:i+length] for i in range(0, len(s), length)]", "title": ""}
{"_id": "d9768", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d9769", "text": "def set_ylim(self, xlims, dx, xscale, reverse=False):\n        \"\"\"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.\n\n        \"\"\"\n        self._set_axis_limits('y', xlims, dx, xscale, reverse)\n        return", "title": ""}
{"_id": "d9770", "text": "def compile(expr, params=None):\n    \"\"\"\n    Force compilation of expression for the SQLite target\n    \"\"\"\n    from ibis.sql.alchemy import to_sqlalchemy\n\n    return to_sqlalchemy(expr, dialect.make_context(params=params))", "title": ""}
{"_id": "d9771", "text": "def set_left_to_right(self):\n        \"\"\"Set text direction left to right.\"\"\"\n        self.displaymode |= LCD_ENTRYLEFT\n        self.write8(LCD_ENTRYMODESET | self.displaymode)", "title": ""}
{"_id": "d9772", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d9773", "text": "def get_shape(img):\n    \"\"\"Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple\n    \"\"\"\n    if hasattr(img, 'shape'):\n        shape = img.shape\n    else:\n        shape = img.get_data().shape\n    return shape", "title": ""}
{"_id": "d9774", "text": "def locked_delete(self):\n        \"\"\"Delete credentials from the SQLAlchemy datastore.\"\"\"\n        filters = {self.key_name: self.key_value}\n        self.session.query(self.model_class).filter_by(**filters).delete()", "title": ""}
{"_id": "d9775", "text": "def show(self, title=''):\n        \"\"\"\n        Display Bloch sphere and corresponding data sets.\n        \"\"\"\n        self.render(title=title)\n        if self.fig:\n            plt.show(self.fig)", "title": ""}
{"_id": "d9776", "text": "def sqliteRowsToDicts(sqliteRows):\n    \"\"\"\n    Unpacks sqlite rows as returned by fetchall\n    into an array of simple dicts.\n\n    :param sqliteRows: array of rows returned from fetchall DB call\n    :return:  array of dicts, keyed by the column names.\n    \"\"\"\n    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "title": ""}
{"_id": "d9777", "text": "def print_error(msg):\n    \"\"\" Print an error message \"\"\"\n    if IS_POSIX:\n        print(u\"%s[ERRO] %s%s\" % (ANSI_ERROR, msg, ANSI_END))\n    else:\n        print(u\"[ERRO] %s\" % (msg))", "title": ""}
{"_id": "d9778", "text": "def Softsign(a):\n    \"\"\"\n    Softsign op.\n    \"\"\"\n    return np.divide(a, np.add(np.abs(a), 1)),", "title": ""}
{"_id": "d9779", "text": "def progressbar(total, pos, msg=\"\"):\n    \"\"\"\n    Given a total and a progress position, output a progress bar\n    to stderr. It is important to not output anything else while\n    using this, as it relies soley on the behavior of carriage\n    return (\\\\r).\n\n    Can also take an optioal message to add after the\n    progressbar. It must not contain newlines.\n\n    The progress bar will look something like this:\n\n    [099/500][=========...............................] ETA: 13:36:59\n\n    Of course, the ETA part should be supplied be the calling\n    function.\n    \"\"\"\n    width = get_terminal_size()[0] - 40\n    rel_pos = int(float(pos) / total * width)\n    bar = ''.join([\"=\" * rel_pos, \".\" * (width - rel_pos)])\n\n    # Determine how many digits in total (base 10)\n    digits_total = len(str(total))\n    fmt_width = \"%0\" + str(digits_total) + \"d\"\n    fmt = \"\\r[\" + fmt_width + \"/\" + fmt_width + \"][%s] %s\"\n\n    progress_stream.write(fmt % (pos, total, bar, msg))", "title": ""}
{"_id": "d9780", "text": "def intty(cls):\n        \"\"\" Check if we are in a tty. \"\"\"\n        # XXX: temporary hack until we can detect if we are in a pipe or not\n        return True\n\n        if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():\n            return True\n\n        return False", "title": ""}
{"_id": "d9781", "text": "def get_grid_spatial_dimensions(self, variable):\n        \"\"\"Returns (width, height) for the given variable\"\"\"\n\n        data = self.open_dataset(self.service).variables[variable.variable]\n        dimensions = list(data.dimensions)\n        return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.index(variable.y_dimension)]", "title": ""}
{"_id": "d9782", "text": "def extract_module_locals(depth=0):\n    \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n    f = sys._getframe(depth + 1)\n    global_ns = f.f_globals\n    module = sys.modules[global_ns['__name__']]\n    return (module, f.f_locals)", "title": ""}
{"_id": "d9783", "text": "def show(self, title=''):\n        \"\"\"\n        Display Bloch sphere and corresponding data sets.\n        \"\"\"\n        self.render(title=title)\n        if self.fig:\n            plt.show(self.fig)", "title": ""}
{"_id": "d9784", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d9785", "text": "def info(docgraph):\n    \"\"\"print node and edge statistics of a document graph\"\"\"\n    print networkx.info(docgraph), '\\n'\n    node_statistics(docgraph)\n    print\n    edge_statistics(docgraph)", "title": ""}
{"_id": "d9786", "text": "def _std(self,x):\n        \"\"\"\n        Compute standard deviation with ddof degrees of freedom\n        \"\"\"\n        return np.nanstd(x.values,ddof=self._ddof)", "title": ""}
{"_id": "d9787", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d9788", "text": "def circstd(dts, axis=2):\n    \"\"\"Circular standard deviation\"\"\"\n    R = np.abs(np.exp(1.0j * dts).mean(axis=axis))\n    return np.sqrt(-2.0 * np.log(R))", "title": ""}
{"_id": "d9789", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d9790", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d9791", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d9792", "text": "def _stdout_raw(self, s):\n        \"\"\"Writes the string to stdout\"\"\"\n        print(s, end='', file=sys.stdout)\n        sys.stdout.flush()", "title": ""}
{"_id": "d9793", "text": "def stop(pid):\n    \"\"\"Shut down a specific process.\n\n    Args:\n      pid: the pid of the process to shutdown.\n    \"\"\"\n    if psutil.pid_exists(pid):\n      try:\n        p = psutil.Process(pid)\n        p.kill()\n      except Exception:\n        pass", "title": ""}
{"_id": "d9794", "text": "def stop_containers(self):\n        \"\"\" Stops all containers used by this instance of the backend.\n        \"\"\"\n        while len(self._containers):\n            container = self._containers.pop()\n            try:\n                container.kill(signal.SIGKILL)\n            except docker.errors.APIError:  # probably doesn't exist anymore\n                pass", "title": ""}
{"_id": "d9795", "text": "def getcolslice(self, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1):\n        \"\"\"Get a slice from a table column holding arrays.\n        (see :func:`table.getcolslice`)\"\"\"\n        return self._table.getcolslice(self._column, blc, trc, inc, startrow, nrow, rowincr)", "title": ""}
{"_id": "d9796", "text": "def unit_ball_L2(shape):\n  \"\"\"A tensorflow variable tranfomed to be constrained in a L2 unit ball.\n\n  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n  they are strong attacks. We are not yet confident in this code.\n  \"\"\"\n  x = tf.Variable(tf.zeros(shape))\n  return constrain_L2(x)", "title": ""}
{"_id": "d9797", "text": "def smooth_array(array, amount=1):\n    \"\"\"\n\n    Returns the nearest-neighbor (+/- amount) smoothed array.\n    This does not modify the array or slice off the funny end points.\n\n    \"\"\"\n    if amount==0: return array\n\n    # we have to store the old values in a temp array to keep the\n    # smoothing from affecting the smoothing\n    new_array = _n.array(array)\n\n    for n in range(len(array)):\n        new_array[n] = smooth(array, n, amount)\n\n    return new_array", "title": ""}
{"_id": "d9798", "text": "def s3(ctx, bucket_name, data_file, region):\n    \"\"\"Use the S3 SWAG backend.\"\"\"\n    if not ctx.data_file:\n        ctx.data_file = data_file\n\n    if not ctx.bucket_name:\n        ctx.bucket_name = bucket_name\n\n    if not ctx.region:\n        ctx.region = region\n\n    ctx.type = 's3'", "title": ""}
{"_id": "d9799", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d9800", "text": "def sort_by_name(self):\n        \"\"\"Sort list elements by name.\"\"\"\n        super(JSSObjectList, self).sort(key=lambda k: k.name)", "title": ""}
{"_id": "d9801", "text": "def _serialize_json(obj, fp):\n    \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n    json.dump(obj, fp, indent=4, default=serialize)", "title": ""}
{"_id": "d9802", "text": "def get_distance(F, x):\n    \"\"\"Helper function for margin-based loss. Return a distance matrix given a matrix.\"\"\"\n    n = x.shape[0]\n\n    square = F.sum(x ** 2.0, axis=1, keepdims=True)\n    distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose()))\n\n    # Adding identity to make sqrt work.\n    return F.sqrt(distance_square + F.array(np.identity(n)))", "title": ""}
{"_id": "d9803", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d9804", "text": "def chunked(l, n):\n    \"\"\"Chunk one big list into few small lists.\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d9805", "text": "def escapePathForShell(path):\n\t\t\"\"\"\n\t\tEscapes a filesystem path for use as a command-line argument\n\t\t\"\"\"\n\t\tif platform.system() == 'Windows':\n\t\t\treturn '\"{}\"'.format(path.replace('\"', '\"\"'))\n\t\telse:\n\t\t\treturn shellescape.quote(path)", "title": ""}
{"_id": "d9806", "text": "def chunks(iterable, size=1):\n    \"\"\"Splits iterator in chunks.\"\"\"\n    iterator = iter(iterable)\n\n    for element in iterator:\n        yield chain([element], islice(iterator, size - 1))", "title": ""}
{"_id": "d9807", "text": "def hamming(s, t):\n    \"\"\"\n    Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.\n\n    :param s: string 1\n    :type s: str\n    :param t: string 2\n    :type s: str\n    :return: Hamming distance\n    :rtype: float\n    \"\"\"\n    if len(s) != len(t):\n        raise ValueError('Hamming distance needs strings of equal length.')\n    return sum(s_ != t_ for s_, t_ in zip(s, t))", "title": ""}
{"_id": "d9808", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d9809", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d9810", "text": "def _escape(s):\n    \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n    e = s\n    e = e.replace('\\\\', '\\\\\\\\')\n    e = e.replace('\\n', '\\\\n')\n    e = e.replace('\\r', '\\\\r')\n    e = e.replace(\"'\", \"\\\\'\")\n    e = e.replace('\"', '\\\\\"')\n    return e", "title": ""}
{"_id": "d9811", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d9812", "text": "def normalize_array(lst):\n    \"\"\"Normalizes list\n\n    :param lst: Array of floats\n    :return: Normalized (in [0, 1]) input array\n    \"\"\"\n    np_arr = np.array(lst)\n    x_normalized = np_arr / np_arr.max(axis=0)\n    return list(x_normalized)", "title": ""}
{"_id": "d9813", "text": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "title": ""}
{"_id": "d9814", "text": "def pause(msg=\"Press Enter to Continue...\"):\n    \"\"\"press to continue\"\"\"\n    print('\\n' + Fore.YELLOW + msg + Fore.RESET, end='')\n    input()", "title": ""}
{"_id": "d9815", "text": "def schunk(string, size):\n    \"\"\"Splits string into n sized chunks.\"\"\"\n    return [string[i:i+size] for i in range(0, len(string), size)]", "title": ""}
{"_id": "d9816", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d9817", "text": "def format_doc_text(text):\n    \"\"\"\n    A very thin wrapper around textwrap.fill to consistently wrap documentation text\n    for display in a command line environment. The text is wrapped to 99 characters with an\n    indentation depth of 4 spaces. Each line is wrapped independently in order to preserve\n    manually added line breaks.\n\n    :param text: The text to format, it is cleaned by inspect.cleandoc.\n    :return: The formatted doc text.\n    \"\"\"\n\n    return '\\n'.join(\n        textwrap.fill(line, width=99, initial_indent='    ', subsequent_indent='    ')\n        for line in inspect.cleandoc(text).splitlines())", "title": ""}
{"_id": "d9818", "text": "def terminate(self):\n        \"\"\"Terminate the pool immediately.\"\"\"\n        if self._pool is not None:\n            self._pool.terminate()\n            self._pool.join()\n            self._pool = None", "title": ""}
{"_id": "d9819", "text": "def c_str(string):\n    \"\"\"\"Convert a python string to C string.\"\"\"\n    if not isinstance(string, str):\n        string = string.decode('ascii')\n    return ctypes.c_char_p(string.encode('utf-8'))", "title": ""}
{"_id": "d9820", "text": "def clean_strings(iterable):\n    \"\"\"\n    Take a list of strings and clear whitespace \n    on each one. If a value in the list is not a \n    string pass it through untouched.\n\n    Args:\n        iterable: mixed list\n\n    Returns: \n        mixed list\n    \"\"\"\n    retval = []\n    for val in iterable:\n        try:\n            retval.append(val.strip())\n        except(AttributeError):\n            retval.append(val)\n    return retval", "title": ""}
{"_id": "d9821", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d9822", "text": "def set_xlimits(self, row, column, min=None, max=None):\n        \"\"\"Set x-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_xlimits(min, max)", "title": ""}
{"_id": "d9823", "text": "def transpose(table):\n    \"\"\"\n    transpose matrix\n    \"\"\"\n    t = []\n    for i in range(0, len(table[0])):\n        t.append([row[i] for row in table])\n    return t", "title": ""}
{"_id": "d9824", "text": "def execute_in_background(self):\n        \"\"\"Executes a (shell) command in the background\n\n        :return: the process' pid\n        \"\"\"\n        # http://stackoverflow.com/questions/1605520\n        args = shlex.split(self.cmd)\n        p = Popen(args)\n        return p.pid", "title": ""}
{"_id": "d9825", "text": "def standard_input():\n    \"\"\"Generator that yields lines from standard input.\"\"\"\n    with click.get_text_stream(\"stdin\") as stdin:\n        while stdin.readable():\n            line = stdin.readline()\n            if line:\n                yield line.strip().encode(\"utf-8\")", "title": ""}
{"_id": "d9826", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d9827", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d9828", "text": "def datetime64_to_datetime(dt):\n    \"\"\" convert numpy's datetime64 to datetime \"\"\"\n    dt64 = np.datetime64(dt)\n    ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')\n    return datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d9829", "text": "def is_admin(self):\n        \"\"\"Is the user a system administrator\"\"\"\n        return self.role == self.roles.administrator.value and self.state == State.approved", "title": ""}
{"_id": "d9830", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d9831", "text": "def is_enum_type(type_):\n    \"\"\" Checks if the given type is an enum type.\n\n    :param type_: The type to check\n    :return: True if the type is a enum type, otherwise False\n    :rtype: bool\n    \"\"\"\n\n    return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))", "title": ""}
{"_id": "d9832", "text": "def is_valid_email(email):\n    \"\"\"\n    Check if email is valid\n    \"\"\"\n    pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n    return bool(pattern.match(email))", "title": ""}
{"_id": "d9833", "text": "def get_memory(self, mode):\n        \"\"\"Return a smt bit vector that represents a memory location.\n        \"\"\"\n        mem = {\n            \"pre\": self._translator.get_memory_init(),\n            \"post\": self._translator.get_memory_curr(),\n        }\n\n        return mem[mode]", "title": ""}
{"_id": "d9834", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d9835", "text": "def exit(exit_code=0):\n  r\"\"\"A function to support exiting from exit hooks.\n\n  Could also be used to exit from the calling scripts in a thread safe manner.\n  \"\"\"\n  core.processExitHooks()\n\n  if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook\n    sys.stderr.flush()\n    sys.stdout.flush()\n    os._exit(exit_code) #pylint: disable=W0212\n\n  sys.exit(exit_code)", "title": ""}
{"_id": "d9836", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d9837", "text": "def issorted(list_, op=operator.le):\n    \"\"\"\n    Determines if a list is sorted\n\n    Args:\n        list_ (list):\n        op (func): sorted operation (default=operator.le)\n\n    Returns:\n        bool : True if the list is sorted\n    \"\"\"\n    return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))", "title": ""}
{"_id": "d9838", "text": "def read_stdin():\n    \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n    if sys.stdin.isatty() and sys.stdout.isatty():\n        print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n    return sys.stdin.read()", "title": ""}
{"_id": "d9839", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d9840", "text": "def main(argv=None):\n  \"\"\"Run a Tensorflow model on the Iris dataset.\"\"\"\n  args = parse_arguments(sys.argv if argv is None else argv)\n\n  tf.logging.set_verbosity(tf.logging.INFO)\n  learn_runner.run(\n      experiment_fn=get_experiment_fn(args),\n      output_dir=args.job_dir)", "title": ""}
{"_id": "d9841", "text": "def row_to_dict(row):\n    \"\"\"Convert a table row to a dictionary.\"\"\"\n    o = {}\n    for colname in row.colnames:\n\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\n    return o", "title": ""}
{"_id": "d9842", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d9843", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d9844", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d9845", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d9846", "text": "def make_slice_strings(cls, slice_key):\n        \"\"\"\n        Converts the given slice key to start and size query parts.\n        \"\"\"\n        start = slice_key.start\n        size = slice_key.stop - start\n        return (str(start), str(size))", "title": ""}
{"_id": "d9847", "text": "def is_callable_tag(tag):\n    \"\"\" Determine whether :tag: is a valid callable string tag.\n\n    String is assumed to be valid callable if it starts with '{{'\n    and ends with '}}'.\n\n    :param tag: String name of tag.\n    \"\"\"\n    return (isinstance(tag, six.string_types) and\n            tag.strip().startswith('{{') and\n            tag.strip().endswith('}}'))", "title": ""}
{"_id": "d9848", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d9849", "text": "def is_unix_style(flags):\n    \"\"\"Check if we should use Unix style.\"\"\"\n\n    return (util.platform() != \"windows\" or (not bool(flags & REALPATH) and get_case(flags))) and not flags & _FORCEWIN", "title": ""}
{"_id": "d9850", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d9851", "text": "def afx_small():\n  \"\"\"Small transformer model with small batch size for fast step times.\"\"\"\n  hparams = transformer.transformer_tpu()\n  hparams.filter_size = 1024\n  hparams.num_heads = 4\n  hparams.num_hidden_layers = 3\n  hparams.batch_size = 512\n  return hparams", "title": ""}
{"_id": "d9852", "text": "def _array2cstr(arr):\n    \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())", "title": ""}
{"_id": "d9853", "text": "def get_example_features(example):\n  \"\"\"Returns the non-sequence features from the provided example.\"\"\"\n  return (example.features.feature if isinstance(example, tf.train.Example)\n          else example.context.feature)", "title": ""}
{"_id": "d9854", "text": "def _to_java_object_rdd(rdd):\n    \"\"\" Return a 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.\n    \"\"\"\n    rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n    return rdd.ctx._jvm.org.apache.spark.mllib.api.python.SerDe.pythonToJava(rdd._jrdd, True)", "title": ""}
{"_id": "d9855", "text": "def _is_path(s):\n    \"\"\"Return whether an object is a path.\"\"\"\n    if isinstance(s, string_types):\n        try:\n            return op.exists(s)\n        except (OSError, ValueError):\n            return False\n    else:\n        return False", "title": ""}
{"_id": "d9856", "text": "def _safe_db(num, den):\n    \"\"\"Properly handle the potential +Inf db SIR instead of raising a\n    RuntimeWarning.\n    \"\"\"\n    if den == 0:\n        return np.inf\n    return 10 * np.log10(num / den)", "title": ""}
{"_id": "d9857", "text": "def hasattrs(object, *names):\n    \"\"\"\n    Takes in an object and a variable length amount of named attributes,\n    and checks to see if the object has each property. If any of the\n    attributes are missing, this returns false.\n\n    :param object: an object that may or may not contain the listed attributes\n    :param names: a variable amount of attribute names to check for\n    :return: True if the object contains each named attribute, false otherwise\n    \"\"\"\n    for name in names:\n        if not hasattr(object, name):\n            return False\n    return True", "title": ""}
{"_id": "d9858", "text": "def log(x):\n    \"\"\"\n    Natural logarithm\n    \"\"\"\n    if isinstance(x, UncertainFunction):\n        mcpts = np.log(x._mcpts)\n        return UncertainFunction(mcpts)\n    else:\n        return np.log(x)", "title": ""}
{"_id": "d9859", "text": "def isnumber(*args):\n    \"\"\"Checks if value is an integer, long integer or float.\n\n    NOTE: Treats booleans as numbers, where True=1 and False=0.\n    \"\"\"\n    return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))", "title": ""}
{"_id": "d9860", "text": "def update_screen(self):\n        \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n        self.clock.tick(self.FPS)\n        pygame.display.update()", "title": ""}
{"_id": "d9861", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d9862", "text": "def test(nose_argsuments):\n    \"\"\" Run application tests \"\"\"\n    from nose import run\n\n    params = ['__main__', '-c', 'nose.ini']\n    params.extend(nose_argsuments)\n    run(argv=params)", "title": ""}
{"_id": "d9863", "text": "def transformer_tpu_1b():\n  \"\"\"Hparams for machine translation with ~1.1B parameters.\"\"\"\n  hparams = transformer_tpu()\n  hparams.hidden_size = 2048\n  hparams.filter_size = 8192\n  hparams.num_hidden_layers = 8\n  # smaller batch size to avoid OOM\n  hparams.batch_size = 1024\n  hparams.activation_dtype = \"bfloat16\"\n  hparams.weight_dtype = \"bfloat16\"\n  # maximize number of parameters relative to computation by not sharing.\n  hparams.shared_embedding_and_softmax_weights = False\n  return hparams", "title": ""}
{"_id": "d9864", "text": "def test():\n    \"\"\"Test program for telnetlib.\n\n    Usage: python telnetlib.py [-d] ... [host [port]]\n\n    Default host is localhost; default port is 23.\n\n    \"\"\"\n    debuglevel = 0\n    while sys.argv[1:] and sys.argv[1] == '-d':\n        debuglevel = debuglevel + 1\n        del sys.argv[1]\n    host = 'localhost'\n    if sys.argv[1:]:\n        host = sys.argv[1]\n    port = 0\n    if sys.argv[2:]:\n        portstr = sys.argv[2]\n        try:\n            port = int(portstr)\n        except ValueError:\n            port = socket.getservbyname(portstr, 'tcp')\n    tn = Telnet()\n    tn.set_debuglevel(debuglevel)\n    tn.open(host, port)\n    tn.interact()\n    tn.close()", "title": ""}
{"_id": "d9865", "text": "def assert_valid_input(cls, tag):\n        \"\"\"Check if valid input tag or document.\"\"\"\n\n        # Fail on unexpected types.\n        if not cls.is_tag(tag):\n            raise TypeError(\"Expected a BeautifulSoup 'Tag', but instead recieved type {}\".format(type(tag)))", "title": ""}
{"_id": "d9866", "text": "def str_is_well_formed(xml_str):\n    \"\"\"\n  Args:\n    xml_str : str\n      DataONE API XML doc.\n\n  Returns:\n    bool: **True** if XML doc is well formed.\n  \"\"\"\n    try:\n        str_to_etree(xml_str)\n    except xml.etree.ElementTree.ParseError:\n        return False\n    else:\n        return True", "title": ""}
{"_id": "d9867", "text": "def url_syntax_check(url):  # pragma: no cover\n    \"\"\"\n    Check the syntax of the given URL.\n\n    :param url: The URL to check the syntax for.\n    :type url: str\n\n    :return: The syntax validity.\n    :rtype: bool\n\n    .. warning::\n        If an empty or a non-string :code:`url` is given, we return :code:`None`.\n    \"\"\"\n\n    if url and isinstance(url, str):\n        # The given URL is not empty nor None.\n        # and\n        # * The given URL is a string.\n\n        # We silently load the configuration.\n        load_config(True)\n\n        return Check(url).is_url_valid()\n\n    # We return None, there is nothing to check.\n    return None", "title": ""}
{"_id": "d9868", "text": "def reseed_random(seed):\n    \"\"\"Reseed factory.fuzzy's random generator.\"\"\"\n    r = random.Random(seed)\n    random_internal_state = r.getstate()\n    set_random_state(random_internal_state)", "title": ""}
{"_id": "d9869", "text": "def write_fits(data, header, file_name):\n    \"\"\"\n    Combine data and a fits header to write a fits file.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        The data to be written.\n\n    header : astropy.io.fits.hduheader\n        The header for the fits file.\n\n    file_name : string\n        The file to write\n\n    Returns\n    -------\n    None\n    \"\"\"\n    hdu = fits.PrimaryHDU(data)\n    hdu.header = header\n    hdulist = fits.HDUList([hdu])\n    hdulist.writeto(file_name, overwrite=True)\n    logging.info(\"Wrote {0}\".format(file_name))\n    return", "title": ""}
{"_id": "d9870", "text": "def stop(self):\n    \"\"\" Stops the playing thread and close \"\"\"\n    with self.lock:\n      self.halting = True\n      self.go.clear()", "title": ""}
{"_id": "d9871", "text": "def _save_file(self, filename, contents):\n        \"\"\"write the html file contents to disk\"\"\"\n        with open(filename, 'w') as f:\n            f.write(contents)", "title": ""}
{"_id": "d9872", "text": "def shutdown(self):\n        \"\"\"\n        shutdown: to be run by atexit handler. All open connection are closed.\n        \"\"\"\n        self.run_clean_thread = False\n        self.cleanup(True)\n        if self.cleaner_thread.isAlive():\n            self.cleaner_thread.join()", "title": ""}
{"_id": "d9873", "text": "def part(z, s):\n    r\"\"\"Get the real or imaginary part of a complex number.\"\"\"\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", "title": ""}
{"_id": "d9874", "text": "def convert_tstamp(response):\n\t\"\"\"\n\tConvert a Stripe API timestamp response (unix epoch) to a native datetime.\n\n\t:rtype: datetime\n\t\"\"\"\n\tif response is None:\n\t\t# Allow passing None to convert_tstamp()\n\t\treturn response\n\n\t# Overrides the set timezone to UTC - I think...\n\ttz = timezone.utc if settings.USE_TZ else None\n\n\treturn datetime.datetime.fromtimestamp(response, tz)", "title": ""}
{"_id": "d9875", "text": "def printheader(h=None):\n    \"\"\"Print the header for the CSV table.\"\"\"\n    writer = csv.writer(sys.stdout)\n    writer.writerow(header_fields(h))", "title": ""}
{"_id": "d9876", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d9877", "text": "def date_to_timestamp(date):\n    \"\"\"\n        date to unix timestamp in milliseconds\n    \"\"\"\n    date_tuple = date.timetuple()\n    timestamp = calendar.timegm(date_tuple) * 1000\n    return timestamp", "title": ""}
{"_id": "d9878", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d9879", "text": "def current_offset(local_tz=None):\n    \"\"\"\n    Returns current utcoffset for a timezone. Uses\n    DEFAULT_LOCAL_TZ by default. That value can be\n    changed at runtime using the func below.\n    \"\"\"\n    if local_tz is None:\n        local_tz = DEFAULT_LOCAL_TZ\n    dt = local_tz.localize(datetime.now())\n    return dt.utcoffset()", "title": ""}
{"_id": "d9880", "text": "def delete(self, id):\n        \"\"\"\n        Deletes an \"object\" (line, triangle, image, etc) from the drawing.\n\n        :param int id:\n            The id of the object.\n        \"\"\"\n        if id in self._images.keys():\n            del self._images[id]\n        self.tk.delete(id)", "title": ""}
{"_id": "d9881", "text": "def _format_title_string(self, title_string):\n        \"\"\" format mpv's title \"\"\"\n        return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix))", "title": ""}
{"_id": "d9882", "text": "def SegmentMax(a, ids):\n    \"\"\"\n    Segmented max op.\n    \"\"\"\n    func = lambda idxs: np.amax(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d9883", "text": "def on_source_directory_chooser_clicked(self):\n        \"\"\"Autoconnect slot activated when tbSourceDir is clicked.\"\"\"\n\n        title = self.tr('Set the source directory for script and scenario')\n        self.choose_directory(self.source_directory, title)", "title": ""}
{"_id": "d9884", "text": "def call_on_if_def(obj, attr_name, callable, default, *args, **kwargs):\n    \"\"\"Calls the provided callable on the provided attribute of ``obj`` if it is defined.\n\n    If not, returns default.\n    \"\"\"\n    try:\n        attr = getattr(obj, attr_name)\n    except AttributeError:\n        return default\n    else:\n        return callable(attr, *args, **kwargs)", "title": ""}
{"_id": "d9885", "text": "def set_scrollregion(self, event=None):\n        \"\"\" Set the scroll region on the canvas\"\"\"\n        self.canvas.configure(scrollregion=self.canvas.bbox('all'))", "title": ""}
{"_id": "d9886", "text": "def column_exists(cr, table, column):\n    \"\"\" Check whether a certain column exists \"\"\"\n    cr.execute(\n        'SELECT count(attname) FROM pg_attribute '\n        'WHERE attrelid = '\n        '( SELECT oid FROM pg_class WHERE relname = %s ) '\n        'AND attname = %s',\n        (table, column))\n    return cr.fetchone()[0] == 1", "title": ""}
{"_id": "d9887", "text": "def on_source_directory_chooser_clicked(self):\n        \"\"\"Autoconnect slot activated when tbSourceDir is clicked.\"\"\"\n\n        title = self.tr('Set the source directory for script and scenario')\n        self.choose_directory(self.source_directory, title)", "title": ""}
{"_id": "d9888", "text": "def check_create_folder(filename):\n    \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n    os.makedirs(os.path.dirname(filename), exist_ok=True)", "title": ""}
{"_id": "d9889", "text": "def restore_scrollbar_position(self):\n        \"\"\"Restoring scrollbar position after main window is visible\"\"\"\n        scrollbar_pos = self.get_option('scrollbar_position', None)\n        if scrollbar_pos is not None:\n            self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)", "title": ""}
{"_id": "d9890", "text": "def matching_line(lines, keyword):\n    \"\"\" Returns the first matching line in a list of lines.\n    @see match()\n    \"\"\"\n    for line in lines:\n        matching = match(line,keyword)\n        if matching != None:\n            return matching\n    return None", "title": ""}
{"_id": "d9891", "text": "def __grid_widgets(self):\n        \"\"\"Places all the child widgets in the appropriate positions.\"\"\"\n        scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n        self._canvas.grid(row=0, column=1, sticky=\"nswe\")\n        self._scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")", "title": ""}
{"_id": "d9892", "text": "def _if(ctx, logical_test, value_if_true=0, value_if_false=False):\n    \"\"\"\n    Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE\n    \"\"\"\n    return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false", "title": ""}
{"_id": "d9893", "text": "def multidict_to_dict(d):\n    \"\"\"\n    Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with\n    list values\n    :param d: a MultiDict or MultiValueDict instance\n    :return: a dict instance\n    \"\"\"\n    return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))", "title": ""}
{"_id": "d9894", "text": "def form_valid(self, form):\n        \"\"\"Security check complete. Log the user in.\"\"\"\n        auth_login(self.request, form.get_user())\n        return HttpResponseRedirect(self.get_success_url())", "title": ""}
{"_id": "d9895", "text": "def normalize_array(lst):\n    \"\"\"Normalizes list\n\n    :param lst: Array of floats\n    :return: Normalized (in [0, 1]) input array\n    \"\"\"\n    np_arr = np.array(lst)\n    x_normalized = np_arr / np_arr.max(axis=0)\n    return list(x_normalized)", "title": ""}
{"_id": "d9896", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d9897", "text": "def convert_timestamp(timestamp):\n    \"\"\"\n    Converts bokehJS timestamp to datetime64.\n    \"\"\"\n    datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)\n    return np.datetime64(datetime.replace(tzinfo=None))", "title": ""}
{"_id": "d9898", "text": "def region_from_segment(image, segment):\n    \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n    x, y, w, h = segment\n    return image[y:y + h, x:x + w]", "title": ""}
{"_id": "d9899", "text": "def __run(self):\n    \"\"\"Hacked run function, which installs the trace.\"\"\"\n    sys.settrace(self.globaltrace)\n    self.__run_backup()\n    self.run = self.__run_backup", "title": ""}
{"_id": "d9900", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d9901", "text": "def format_exc(*exc_info):\n    \"\"\"Show exception with traceback.\"\"\"\n    typ, exc, tb = exc_info or sys.exc_info()\n    error = traceback.format_exception(typ, exc, tb)\n    return \"\".join(error)", "title": ""}
{"_id": "d9902", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d9903", "text": "def str_traceback(error, tb):\n    \"\"\"Returns a string representation of the traceback.\n    \"\"\"\n    if not isinstance(tb, types.TracebackType):\n        return tb\n\n    return ''.join(traceback.format_exception(error.__class__, error, tb))", "title": ""}
{"_id": "d9904", "text": "def stepBy(self, steps):\n        \"\"\"steps value up/down by a single step. Single step is defined in singleStep().\n\n        Args:\n            steps (int): positiv int steps up, negativ steps down\n        \"\"\"\n        self.setValue(self.value() + steps*self.singleStep())", "title": ""}
{"_id": "d9905", "text": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "title": ""}
{"_id": "d9906", "text": "def _match_space_at_line(line):\n    \"\"\"Return a re.match object if an empty comment was found on line.\"\"\"\n    regex = re.compile(r\"^{0}$\".format(_MDL_COMMENT))\n    return regex.match(line)", "title": ""}
{"_id": "d9907", "text": "def min_depth(self, root):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: int\n    \"\"\"\n    if root is None:\n        return 0\n    if root.left is not None or root.right is not None:\n        return max(self.minDepth(root.left), self.minDepth(root.right))+1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1", "title": ""}
{"_id": "d9908", "text": "def is_filelike(ob):\n    \"\"\"Check for filelikeness of an object.\n\n    Needed to distinguish it from file names.\n    Returns true if it has a read or a write method.\n    \"\"\"\n    if hasattr(ob, 'read') and callable(ob.read):\n        return True\n\n    if hasattr(ob, 'write') and callable(ob.write):\n        return True\n\n    return False", "title": ""}
{"_id": "d9909", "text": "def handle_whitespace(text):\n    r\"\"\"Handles whitespace cleanup.\n\n    Tabs are \"smartly\" retabbed (see sub_retab). Lines that contain\n    only whitespace are truncated to a single newline.\n    \"\"\"\n    text = re_retab.sub(sub_retab, text)\n    text = re_whitespace.sub('', text).strip()\n    return text", "title": ""}
{"_id": "d9910", "text": "def simple_generate(cls, create, **kwargs):\n        \"\"\"Generate a new instance.\n\n        The instance will be either 'built' or 'created'.\n\n        Args:\n            create (bool): whether to 'build' or 'create' the instance.\n\n        Returns:\n            object: the generated instance\n        \"\"\"\n        strategy = enums.CREATE_STRATEGY if create else enums.BUILD_STRATEGY\n        return cls.generate(strategy, **kwargs)", "title": ""}
{"_id": "d9911", "text": "def s3(ctx, bucket_name, data_file, region):\n    \"\"\"Use the S3 SWAG backend.\"\"\"\n    if not ctx.data_file:\n        ctx.data_file = data_file\n\n    if not ctx.bucket_name:\n        ctx.bucket_name = bucket_name\n\n    if not ctx.region:\n        ctx.region = region\n\n    ctx.type = 's3'", "title": ""}
{"_id": "d9912", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d9913", "text": "def __init__(self, scope, parent):\n        \"\"\"Constructor for try block structures.\n\n        Args:\n            scope (CodeEntity): The program scope where this object belongs.\n            parent (CodeEntity): This object's parent in the program tree.\n        \"\"\"\n        CodeStatement.__init__(self, scope, parent)\n        self.body = CodeBlock(scope, self, explicit=True)\n        self.catches = []\n        self.finally_body = CodeBlock(scope, self, explicit=True)", "title": ""}
{"_id": "d9914", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d9915", "text": "def eintr_retry(exc_type, f, *args, **kwargs):\n    \"\"\"Calls a function.  If an error of the given exception type with\n    interrupted system call (EINTR) occurs calls the function again.\n    \"\"\"\n    while True:\n        try:\n            return f(*args, **kwargs)\n        except exc_type as exc:\n            if exc.errno != EINTR:\n                raise\n        else:\n            break", "title": ""}
{"_id": "d9916", "text": "def fval(self, instance):\n        \"\"\"return the raw value that this property is holding internally for instance\"\"\"\n        try:\n            val = instance.__dict__[self.instance_field_name]\n        except KeyError as e:\n            #raise AttributeError(str(e))\n            val = None\n\n        return val", "title": ""}
{"_id": "d9917", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d9918", "text": "def  make_html_code( self, lines ):\n        \"\"\" convert a code sequence to HTML \"\"\"\n        line = code_header + '\\n'\n        for l in lines:\n            line = line + html_quote( l ) + '\\n'\n\n        return line + code_footer", "title": ""}
{"_id": "d9919", "text": "def _tuple_repr(data):\n    \"\"\"Return a repr() for a list/tuple\"\"\"\n    if len(data) == 1:\n        return \"(%s,)\" % rpr(data[0])\n    else:\n        return \"(%s)\" % \", \".join([rpr(x) for x in data])", "title": ""}
{"_id": "d9920", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d9921", "text": "def ver_to_tuple(value):\n    \"\"\"\n    Convert version like string to a tuple of integers.\n    \"\"\"\n    return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "title": ""}
{"_id": "d9922", "text": "def is_full_slice(obj, l):\n    \"\"\"\n    We have a full length slice.\n    \"\"\"\n    return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and\n            obj.step is None)", "title": ""}
{"_id": "d9923", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d9924", "text": "def one_hot2string(arr, vocab):\n    \"\"\"Convert a one-hot encoded array back to string\n    \"\"\"\n    tokens = one_hot2token(arr)\n    indexToLetter = _get_index_dict(vocab)\n\n    return [''.join([indexToLetter[x] for x in row]) for row in tokens]", "title": ""}
{"_id": "d9925", "text": "def __init__(self, name, flag, **kwargs):\n    \"\"\"\n    Argument class constructor, should be used inside a class that inherits the BaseAction class.\n\n    :param name(str): the optional argument name to be used with two slahes (--cmd)\n    :param flag(str): a short flag for the argument (-c)\n    :param \\*\\*kwargs: all keywords arguments supported for argparse actions.\n    \"\"\"\n    self.name = name\n    self.flag = flag\n    self.options = kwargs", "title": ""}
{"_id": "d9926", "text": "def stringify_dict_contents(dct):\n    \"\"\"Turn dict keys and values into native strings.\"\"\"\n    return {\n        str_if_nested_or_str(k): str_if_nested_or_str(v)\n        for k, v in dct.items()\n    }", "title": ""}
{"_id": "d9927", "text": "def _to_java_object_rdd(rdd):\n    \"\"\" 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.\n    \"\"\"\n    rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n    return rdd.ctx._jvm.org.apache.spark.ml.python.MLSerDe.pythonToJava(rdd._jrdd, True)", "title": ""}
{"_id": "d9928", "text": "def run_func(self, func_path, *func_args, **kwargs):\n        \"\"\"Run a function in Matlab and return the result.\n\n        Parameters\n        ----------\n        func_path: str\n            Name of function to run or a path to an m-file.\n        func_args: object, optional\n            Function args to send to the function.\n        nargout: int, optional\n            Desired number of return arguments.\n        kwargs:\n            Keyword arguments are passed to Matlab in the form [key, val] so\n            that matlab.plot(x, y, '--', LineWidth=2) would be translated into\n            plot(x, y, '--', 'LineWidth', 2)\n\n        Returns\n        -------\n        Result dictionary with keys: 'message', 'result', and 'success'\n        \"\"\"\n        if not self.started:\n            raise ValueError('Session not started, use start()')\n\n        nargout = kwargs.pop('nargout', 1)\n        func_args += tuple(item for pair in zip(kwargs.keys(), kwargs.values())\n                           for item in pair)\n        dname = os.path.dirname(func_path)\n        fname = os.path.basename(func_path)\n        func_name, ext = os.path.splitext(fname)\n        if ext and not ext == '.m':\n            raise TypeError('Need to give path to .m file')\n        return self._json_response(cmd='eval',\n                                   func_name=func_name,\n                                   func_args=func_args or '',\n                                   dname=dname,\n                                   nargout=nargout)", "title": ""}
{"_id": "d9929", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d9930", "text": "def fixpath(path):\n    \"\"\"Uniformly format a path.\"\"\"\n    return os.path.normpath(os.path.realpath(os.path.expanduser(path)))", "title": ""}
{"_id": "d9931", "text": "def _npiter(arr):\n    \"\"\"Wrapper for iterating numpy array\"\"\"\n    for a in np.nditer(arr, flags=[\"refs_ok\"]):\n        c = a.item()\n        if c is not None:\n            yield c", "title": ""}
{"_id": "d9932", "text": "def search_script_directory(self, path):\n        \"\"\"\n        Recursively loop through a directory to find all python\n        script files. When one is found, it is analyzed for import statements\n        :param path: string\n        :return: generator\n        \"\"\"\n        for subdir, dirs, files in os.walk(path):\n            for file_name in files:\n                if file_name.endswith(\".py\"):\n                    self.search_script_file(subdir, file_name)", "title": ""}
{"_id": "d9933", "text": "def parse_parameter(value):\n    \"\"\"\n    @return: The best approximation of a type of the given value.\n    \"\"\"\n    if any((isinstance(value, float), isinstance(value, int), isinstance(value, bool))):\n        return value\n\n    try:\n        return int(value)\n    except ValueError:\n        try:\n            return float(value)\n        except ValueError:\n            if value in string_aliases.true_boolean_aliases:\n                return True\n            elif value in string_aliases.false_boolean_aliases:\n                return False\n            else:\n                return str(value)", "title": ""}
{"_id": "d9934", "text": "def get_substring_idxs(substr, string):\n    \"\"\"\n    Return a list of indexes of substr. If substr not found, list is\n    empty.\n\n    Arguments:\n        substr (str): Substring to match.\n        string (str): String to match in.\n\n    Returns:\n        list of int: Start indices of substr.\n    \"\"\"\n    return [match.start() for match in re.finditer(substr, string)]", "title": ""}
{"_id": "d9935", "text": "def is_type(value):\n        \"\"\"Determine if value is an instance or subclass of the class Type.\"\"\"\n        if isinstance(value, type):\n            return issubclass(value, Type)\n        return isinstance(value, Type)", "title": ""}
{"_id": "d9936", "text": "def query_sum(queryset, field):\n    \"\"\"\n    Let the DBMS perform a sum on a queryset\n    \"\"\"\n    return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']", "title": ""}
{"_id": "d9937", "text": "def to_pascal_case(s):\n    \"\"\"Transform underscore separated string to pascal case\n\n    \"\"\"\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())", "title": ""}
{"_id": "d9938", "text": "def unique_items(seq):\n    \"\"\"Return the unique items from iterable *seq* (in order).\"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d9939", "text": "def wireshark(pktlist, *args):\n    \"\"\"Run wireshark on a list of packets\"\"\"\n    fname = get_temp_file()\n    wrpcap(fname, pktlist)\n    subprocess.Popen([conf.prog.wireshark, \"-r\", fname] + list(args))", "title": ""}
{"_id": "d9940", "text": "def step_impl06(context):\n    \"\"\"Prepare test for singleton property.\n\n    :param context: test context.\n    \"\"\"\n    store = context.SingleStore\n    context.st_1 = store()\n    context.st_2 = store()\n    context.st_3 = store()", "title": ""}
{"_id": "d9941", "text": "def jac(x,a):\n    \"\"\" Jacobian matrix given Christophe's suggestion of f \"\"\"\n    return (x-a) / np.sqrt(((x-a)**2).sum(1))[:,np.newaxis]", "title": ""}
{"_id": "d9942", "text": "def autobuild_python_test(path):\n    \"\"\"Add pytest unit tests to be built as part of build/test/output.\"\"\"\n\n    env = Environment(tools=[])\n    target = env.Command(['build/test/output/pytest.log'], [path],\n                         action=env.Action(run_pytest, \"Running python unit tests\"))\n    env.AlwaysBuild(target)", "title": ""}
{"_id": "d9943", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d9944", "text": "def raises_regex(self, expected_exception, expected_regexp):\n        \"\"\"\n        Ensures preceding predicates (specifically, :meth:`called_with()`) result in *expected_exception* being raised,\n        and the string representation of *expected_exception* must match regular expression *expected_regexp*.\n        \"\"\"\n        return unittest_case.assertRaisesRegexp(expected_exception, expected_regexp, self._orig_subject,\n                                                *self._args, **self._kwargs)", "title": ""}
{"_id": "d9945", "text": "def compressBuffer(buffer):\n    \"\"\"\n    Note that this code compresses into a buffer held in memory, rather\n    than a disk file. This is done through the use of cStringIO.StringIO().\n    \"\"\"\n    # http://jython.xhaus.com/http-compression-in-python-and-jython/\n    zbuf = cStringIO.StringIO()\n    zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)\n    zfile.write(buffer)\n    zfile.close()\n    return zbuf.getvalue()", "title": ""}
{"_id": "d9946", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d9947", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d9948", "text": "def import_js(path, lib_name, globals):\n    \"\"\"Imports from javascript source file.\n      globals is your globals()\"\"\"\n    with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:\n        js = f.read()\n    e = EvalJs()\n    e.execute(js)\n    var = e.context['var']\n    globals[lib_name] = var.to_python()", "title": ""}
{"_id": "d9949", "text": "def import_path(self):\n    \"\"\"The full remote import path as used in import statements in `.go` source files.\"\"\"\n    return os.path.join(self.remote_root, self.pkg) if self.pkg else self.remote_root", "title": ""}
{"_id": "d9950", "text": "def sbatch_template(self):\n        \"\"\":return Jinja sbatch template for the current tag\"\"\"\n        template = self.sbatch_template_str\n        if template.startswith('#!'):\n            # script is embedded in YAML\n            return jinja_environment.from_string(template)\n        return jinja_environment.get_template(template)", "title": ""}
{"_id": "d9951", "text": "def __init__(self,operand,operator,**args):\n        \"\"\"\n        Accepts a NumberGenerator operand, an operator, and\n        optional arguments to be provided to the operator when calling\n        it on the operand.\n        \"\"\"\n        # Note that it's currently not possible to set\n        # parameters in the superclass when creating an instance,\n        # because **args is used by this class itself.\n        super(UnaryOperator,self).__init__()\n\n        self.operand=operand\n        self.operator=operator\n        self.args=args", "title": ""}
{"_id": "d9952", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d9953", "text": "def vectorize(values):\n    \"\"\"\n    Takes a value or list of values and returns a single result, joined by \",\"\n    if necessary.\n    \"\"\"\n    if isinstance(values, list):\n        return ','.join(str(v) for v in values)\n    return values", "title": ""}
{"_id": "d9954", "text": "def update(self, params):\n        \"\"\"Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device.\n        \"\"\"\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "title": ""}
{"_id": "d9955", "text": "def index():\n    \"\"\" Display productpage with normal user and test user buttons\"\"\"\n    global productpage\n\n    table = json2html.convert(json = json.dumps(productpage),\n                              table_attributes=\"class=\\\"table table-condensed table-bordered table-hover\\\"\")\n\n    return render_template('index.html', serviceTable=table)", "title": ""}
{"_id": "d9956", "text": "def set_property(self, key, value):\n        \"\"\"\n        Update only one property in the dict\n        \"\"\"\n        self.properties[key] = value\n        self.sync_properties()", "title": ""}
{"_id": "d9957", "text": "def _spawn_kafka_consumer_thread(self):\n        \"\"\"Spawns a kafka continuous consumer thread\"\"\"\n        self.logger.debug(\"Spawn kafka consumer thread\"\"\")\n        self._consumer_thread = Thread(target=self._consumer_loop)\n        self._consumer_thread.setDaemon(True)\n        self._consumer_thread.start()", "title": ""}
{"_id": "d9958", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d9959", "text": "def timeit(method):\n    \"\"\"\n    A Python decorator for printing out the execution time for a function.\n\n    Adapted from:\n    www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods\n    \"\"\"\n    def timed(*args, **kw):\n        time_start = time.time()\n        result = method(*args, **kw)\n        time_end = time.time()\n        print('timeit: %r %2.2f sec (%r, %r) ' % (method.__name__, time_end-time_start, str(args)[:20], kw))\n        return result\n\n    return timed", "title": ""}
{"_id": "d9960", "text": "def server(self):\n        \"\"\"Returns the size of remote files\n        \"\"\"\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 \" \"", "title": ""}
{"_id": "d9961", "text": "async def stop(self):\n        \"\"\"Stop the current task process.\n\n        Starts with SIGTERM, gives the process 1 second to terminate, then kills it\n        \"\"\"\n        # negate pid so that signals apply to process group\n        pgid = -self.process.pid\n        try:\n            os.kill(pgid, signal.SIGTERM)\n            await asyncio.sleep(1)\n            os.kill(pgid, signal.SIGKILL)\n        except (OSError, ProcessLookupError):\n            return", "title": ""}
{"_id": "d9962", "text": "def escape(s):\n    \"\"\"Escape a URL including any /.\"\"\"\n    if not isinstance(s, bytes):\n        s = s.encode('utf-8')\n    return quote(s, safe='~')", "title": ""}
{"_id": "d9963", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d9964", "text": "def get_url_args(url):\n    \"\"\" Returns a dictionary from a URL params \"\"\"\n    url_data = urllib.parse.urlparse(url)\n    arg_dict = urllib.parse.parse_qs(url_data.query)\n    return arg_dict", "title": ""}
{"_id": "d9965", "text": "def kill_all(self, kill_signal, kill_shell=False):\n        \"\"\"Kill all running processes.\"\"\"\n        for key in self.processes.keys():\n            self.kill_process(key, kill_signal, kill_shell)", "title": ""}
{"_id": "d9966", "text": "def updateFromKwargs(self, properties, kwargs, collector, **unused):\n        \"\"\"Primary entry point to turn 'kwargs' into 'properties'\"\"\"\n        properties[self.name] = self.getFromKwargs(kwargs)", "title": ""}
{"_id": "d9967", "text": "def dumps(obj):\n    \"\"\"Outputs json with formatting edits + object handling.\"\"\"\n    return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)", "title": ""}
{"_id": "d9968", "text": "def notin(arg, values):\n    \"\"\"\n    Like isin, but checks whether this expression's value(s) are not\n    contained in the passed values. See isin docs for full usage.\n    \"\"\"\n    op = ops.NotContains(arg, values)\n    return op.to_expr()", "title": ""}
{"_id": "d9969", "text": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "title": ""}
{"_id": "d9970", "text": "def _letter_map(word):\n    \"\"\"Creates a map of letter use in a word.\n\n    Args:\n        word: a string to create a letter map from\n\n    Returns:\n        a dictionary of {letter: integer count of letter in word}\n    \"\"\"\n\n    lmap = {}\n    for letter in word:\n        try:\n            lmap[letter] += 1\n        except KeyError:\n            lmap[letter] = 1\n    return lmap", "title": ""}
{"_id": "d9971", "text": "def decode_unicode_string(string):\n    \"\"\"\n    Decode string encoded by `unicode_string`\n    \"\"\"\n    if string.startswith('[BASE64-DATA]') and string.endswith('[/BASE64-DATA]'):\n        return base64.b64decode(string[len('[BASE64-DATA]'):-len('[/BASE64-DATA]')])\n    return string", "title": ""}
{"_id": "d9972", "text": "def set_ylimits(self, row, column, min=None, max=None):\n        \"\"\"Set y-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_ylimits(min, max)", "title": ""}
{"_id": "d9973", "text": "def generate_uuid():\n    \"\"\"Generate a UUID.\"\"\"\n    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)\n    return r_uuid.decode().replace('=', '')", "title": ""}
{"_id": "d9974", "text": "def _match_space_at_line(line):\n    \"\"\"Return a re.match object if an empty comment was found on line.\"\"\"\n    regex = re.compile(r\"^{0}$\".format(_MDL_COMMENT))\n    return regex.match(line)", "title": ""}
{"_id": "d9975", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d9976", "text": "def get_ip_address(ifname):\n    \"\"\" Hack to get IP address from the interface \"\"\"\n    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n    return socket.inet_ntoa(fcntl.ioctl(\n        s.fileno(),\n        0x8915,  # SIOCGIFADDR\n        struct.pack('256s', ifname[:15])\n    )[20:24])", "title": ""}
{"_id": "d9977", "text": "def is_valid(data):\n        \"\"\"\n        Checks if the input data is a Swagger document\n\n        :param dict data: Data to be validated\n        :return: True, if data is a Swagger\n        \"\"\"\n        return bool(data) and \\\n            isinstance(data, dict) and \\\n            bool(data.get(\"swagger\")) and \\\n            isinstance(data.get('paths'), dict)", "title": ""}
{"_id": "d9978", "text": "def symlink(source, destination):\n    \"\"\"Create a symbolic link\"\"\"\n    log(\"Symlinking {} as {}\".format(source, destination))\n    cmd = [\n        'ln',\n        '-sf',\n        source,\n        destination,\n    ]\n    subprocess.check_call(cmd)", "title": ""}
{"_id": "d9979", "text": "def _check_list_len(row, length):\n        \"\"\"\n        Sanity check for csv parser\n        :param row\n        :param length\n        :return:None\n        \"\"\"\n        if len(row) != length:\n            raise Exception(\n                \"row length does not match expected length of \" +\n                str(length) + \"\\nrow: \" + str(row))", "title": ""}
{"_id": "d9980", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d9981", "text": "def getprop(self, prop_name):\n        \"\"\"Get a property of the device.\n\n        This is a convenience wrapper for \"adb shell getprop xxx\".\n\n        Args:\n            prop_name: A string that is the name of the property to get.\n\n        Returns:\n            A string that is the value of the property, or None if the property\n            doesn't exist.\n        \"\"\"\n        return self.shell(\n            ['getprop', prop_name],\n            timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode('utf-8').strip()", "title": ""}
{"_id": "d9982", "text": "def dedupe_list(l):\n    \"\"\"Remove duplicates from a list preserving the order.\n\n    We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n    the order, which hinders testability and does not work for lists with\n    unhashable elements.\n    \"\"\"\n    result = []\n\n    for el in l:\n        if el not in result:\n            result.append(el)\n\n    return result", "title": ""}
{"_id": "d9983", "text": "def add_input_variable(self, var):\n        \"\"\"Adds the argument variable as one of the input variable\"\"\"\n        assert(isinstance(var, Variable))\n        self.input_variable_list.append(var)", "title": ""}
{"_id": "d9984", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d9985", "text": "def dot_v2(vec1, vec2):\n    \"\"\"Return the dot product of two vectors\"\"\"\n\n    return vec1.x * vec2.x + vec1.y * vec2.y", "title": ""}
{"_id": "d9986", "text": "def open_json(file_name):\n    \"\"\"\n    returns json contents as string\n    \"\"\"\n    with open(file_name, \"r\") as json_data:\n        data = json.load(json_data)\n        return data", "title": ""}
{"_id": "d9987", "text": "def dot_v2(vec1, vec2):\n    \"\"\"Return the dot product of two vectors\"\"\"\n\n    return vec1.x * vec2.x + vec1.y * vec2.y", "title": ""}
{"_id": "d9988", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d9989", "text": "def check_alert(self, text):\n    \"\"\"\n    Assert an alert is showing with the given text.\n    \"\"\"\n\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        # PhantomJS is kinda poor\n        pass", "title": ""}
{"_id": "d9990", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d9991", "text": "def size(self):\n        \"\"\"Return the viewable size of the Table as @tuple (x,y)\"\"\"\n        width = max(\n            map(lambda x: x.size()[0], self.sections.itervalues()))\n\n        height = sum(\n            map(lambda x: x.size()[1], self.sections.itervalues()))\n\n        return width, height", "title": ""}
{"_id": "d9992", "text": "def should_skip_logging(func):\n    \"\"\"\n    Should we skip logging for this handler?\n\n    \"\"\"\n    disabled = strtobool(request.headers.get(\"x-request-nolog\", \"false\"))\n    return disabled or getattr(func, SKIP_LOGGING, False)", "title": ""}
{"_id": "d9993", "text": "def world_to_view(v):\n    \"\"\"world coords to view coords; v an eu.Vector2, returns (float, float)\"\"\"\n    return v.x * config.scale_x, v.y * config.scale_y", "title": ""}
{"_id": "d9994", "text": "def lognorm(x, mu, sigma=1.0):\n    \"\"\" Log-normal function from scipy \"\"\"\n    return stats.lognorm(sigma, scale=mu).pdf(x)", "title": ""}
{"_id": "d9995", "text": "def rm(venv_name):\n    \"\"\" Removes the venv by name \"\"\"\n    inenv = InenvManager()\n    venv = inenv.get_venv(venv_name)\n    click.confirm(\"Delete dir {}\".format(venv.path))\n    shutil.rmtree(venv.path)", "title": ""}
{"_id": "d9996", "text": "def setAsApplication(myappid):\n    \"\"\"\n    Tells Windows this is an independent application with an unique icon on task bar.\n\n    id is an unique string to identify this application, like: 'mycompany.myproduct.subproduct.version'\n    \"\"\"\n\n    if os.name == 'nt':\n        import ctypes\n        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)", "title": ""}
{"_id": "d9997", "text": "def _disable_venv(self, env):\n        \"\"\"\n        Disable virtualenv and venv in the environment.\n        \"\"\"\n        venv = env.pop('VIRTUAL_ENV', None)\n        if venv:\n            venv_path, sep, env['PATH'] = env['PATH'].partition(os.pathsep)", "title": ""}
{"_id": "d9998", "text": "def _convert_to_array(array_like, dtype):\n        \"\"\"\n        Convert Matrix attributes which are array-like or buffer to array.\n        \"\"\"\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)", "title": ""}
{"_id": "d9999", "text": "def unique_everseen(seq):\n    \"\"\"Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d10000", "text": "def submit_by_selector(self, selector):\n    \"\"\"Submit the form matching the CSS selector.\"\"\"\n    elem = find_element_by_jquery(world.browser, selector)\n    elem.submit()", "title": ""}
{"_id": "d10001", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d10002", "text": "def click(self):\n        \"\"\"Click the element\n\n        :returns: page element instance\n        \"\"\"\n        try:\n            self.wait_until_clickable().web_element.click()\n        except StaleElementReferenceException:\n            # Retry if element has changed\n            self.web_element.click()\n        return self", "title": ""}
{"_id": "d10003", "text": "def make_unique_ngrams(s, n):\n    \"\"\"Make a set of unique n-grams from a string.\"\"\"\n    return set(s[i:i + n] for i in range(len(s) - n + 1))", "title": ""}
{"_id": "d10004", "text": "def is_webdriver_ios(webdriver):\n        \"\"\"\n        Check if a web driver if mobile.\n\n        Args:\n            webdriver (WebDriver): Selenium webdriver.\n\n        \"\"\"\n        browser = webdriver.capabilities['browserName']\n\n        if (browser == u('iPhone') or \n            browser == u('iPad')):\n            return True\n        else:\n            return False", "title": ""}
{"_id": "d10005", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d10006", "text": "def start(self):\n        \"\"\"Create a background thread for httpd and serve 'forever'\"\"\"\n        self._process = threading.Thread(target=self._background_runner)\n        self._process.start()", "title": ""}
{"_id": "d10007", "text": "def commajoin_as_strings(iterable):\n    \"\"\" Join the given iterable with ',' \"\"\"\n    return _(u',').join((six.text_type(i) for i in iterable))", "title": ""}
{"_id": "d10008", "text": "def disconnect(self):\n        \"\"\"\n        Closes the connection.\n        \"\"\"\n        self.logger.debug('Close connection...')\n\n        self.auto_reconnect = False\n\n        if self.websocket is not None:\n            self.websocket.close()", "title": ""}
{"_id": "d10009", "text": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "title": ""}
{"_id": "d10010", "text": "def settimeout(self, timeout):\n        \"\"\"\n        Set the timeout to the websocket.\n\n        timeout: timeout time(second).\n        \"\"\"\n        self.sock_opt.timeout = timeout\n        if self.sock:\n            self.sock.settimeout(timeout)", "title": ""}
{"_id": "d10011", "text": "def select_random(engine, table_or_columns, limit=5):\n    \"\"\"\n    Randomly select some rows from table.\n    \"\"\"\n    s = select(table_or_columns).order_by(func.random()).limit(limit)\n    return engine.execute(s).fetchall()", "title": ""}
{"_id": "d10012", "text": "def _ws_on_close(self, ws: websocket.WebSocketApp):\n        \"\"\"Callback for closing the websocket connection\n\n        Args:\n            ws: websocket connection (now closed)\n        \"\"\"\n        self.connected = False\n        self.logger.error('Websocket closed')\n        self._reconnect_websocket()", "title": ""}
{"_id": "d10013", "text": "def classnameify(s):\n  \"\"\"\n  Makes a classname\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))", "title": ""}
{"_id": "d10014", "text": "def _file_exists(path, filename):\n  \"\"\"Checks if the filename exists under the path.\"\"\"\n  return os.path.isfile(os.path.join(path, filename))", "title": ""}
{"_id": "d10015", "text": "def top(n, width=WIDTH, style=STYLE):\n    \"\"\"Prints the top row of a table\"\"\"\n    return hrule(n, width, linestyle=STYLES[style].top)", "title": ""}
{"_id": "d10016", "text": "def join_field(path):\n    \"\"\"\n    RETURN field SEQUENCE AS STRING\n    \"\"\"\n    output = \".\".join([f.replace(\".\", \"\\\\.\") for f in path if f != None])\n    return output if output else \".\"", "title": ""}
{"_id": "d10017", "text": "def create_widget(self):\n        \"\"\" Create the toolkit widget for the proxy object.\n        \"\"\"\n        d = self.declaration\n        button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect\n        self.widget = UIButton(buttonWithType=button_type)", "title": ""}
{"_id": "d10018", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d10019", "text": "def atom_criteria(*params):\n    \"\"\"An auxiliary function to construct a dictionary of Criteria\"\"\"\n    result = {}\n    for index, param in enumerate(params):\n        if param is None:\n            continue\n        elif isinstance(param, int):\n            result[index] = HasAtomNumber(param)\n        else:\n            result[index] = param\n    return result", "title": ""}
{"_id": "d10020", "text": "def normalize_path(filename):\n    \"\"\"Normalize a file/dir name for comparison purposes\"\"\"\n    return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))", "title": ""}
{"_id": "d10021", "text": "def show(config):\n    \"\"\"Show revision list\"\"\"\n    with open(config, 'r'):\n        main.show(yaml.load(open(config)))", "title": ""}
{"_id": "d10022", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d10023", "text": "def x_values_ref(self, series):\n        \"\"\"\n        The Excel worksheet reference to the X values for this chart (not\n        including the column label).\n        \"\"\"\n        top_row = self.series_table_row_offset(series) + 2\n        bottom_row = top_row + len(series) - 1\n        return \"Sheet1!$A$%d:$A$%d\" % (top_row, bottom_row)", "title": ""}
{"_id": "d10024", "text": "def asyncStarCmap(asyncCallable, iterable):\n    \"\"\"itertools.starmap for deferred callables using cooperative multitasking\n    \"\"\"\n    results = []\n    yield coopStar(asyncCallable, results.append, iterable)\n    returnValue(results)", "title": ""}
{"_id": "d10025", "text": "def sample_colormap(cmap_name, n_samples):\n    \"\"\"\n    Sample a colormap from matplotlib\n    \"\"\"\n    colors = []\n    colormap = cm.cmap_d[cmap_name]\n    for i in np.linspace(0, 1, n_samples):\n        colors.append(colormap(i))\n\n    return colors", "title": ""}
{"_id": "d10026", "text": "def write_dict_to_yaml(dictionary, path, **kwargs):\n    \"\"\"\n    Writes a dictionary to a yaml file\n    :param dictionary:  the dictionary to be written\n    :param path: the absolute path of the target yaml file\n    :param kwargs: optional additional parameters for dumper\n    \"\"\"\n    with open(path, 'w') as f:\n        yaml.dump(dictionary, f, indent=4, **kwargs)", "title": ""}
{"_id": "d10027", "text": "def page_guiref(arg_s=None):\n    \"\"\"Show a basic reference about the GUI Console.\"\"\"\n    from IPython.core import page\n    page.page(gui_reference, auto_html=True)", "title": ""}
{"_id": "d10028", "text": "def write_fits(self, fitsfile):\n        \"\"\"Write the ROI model to a FITS file.\"\"\"\n\n        tab = self.create_table()\n        hdu_data = fits.table_to_hdu(tab)\n        hdus = [fits.PrimaryHDU(), hdu_data]\n        fits_utils.write_hdus(hdus, fitsfile)", "title": ""}
{"_id": "d10029", "text": "def md_to_text(content):\n    \"\"\" Converts markdown content to text \"\"\"\n    text = None\n    html = markdown.markdown(content)\n    if html:\n        text = html_to_text(content)\n    return text", "title": ""}
{"_id": "d10030", "text": "def imp_print(self, text, end):\n\t\t\"\"\"Directly send utf8 bytes to stdout\"\"\"\n\t\tsys.stdout.write((text + end).encode(\"utf-8\"))", "title": ""}
{"_id": "d10031", "text": "def intersect(d1, d2):\n    \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n    return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "title": ""}
{"_id": "d10032", "text": "def cleanup_nodes(doc):\n    \"\"\"\n    Remove text nodes containing only whitespace\n    \"\"\"\n    for node in doc.documentElement.childNodes:\n        if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():\n            doc.documentElement.removeChild(node)\n    return doc", "title": ""}
{"_id": "d10033", "text": "def intersect(d1, d2):\n    \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n    return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "title": ""}
{"_id": "d10034", "text": "def validate(self, xml_input):\n        \"\"\"\n        This method validate the parsing and schema, return a boolean\n        \"\"\"\n        parsed_xml = etree.parse(self._handle_xml(xml_input))\n        try:\n            return self.xmlschema.validate(parsed_xml)\n        except AttributeError:\n            raise CannotValidate('Set XSD to validate the XML')", "title": ""}
{"_id": "d10035", "text": "def load_data(filename):\n    \"\"\"\n    :rtype : numpy matrix\n    \"\"\"\n    data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n    return data.as_matrix()", "title": ""}
{"_id": "d10036", "text": "def print_yaml(o):\n    \"\"\"Pretty print an object as YAML.\"\"\"\n    print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))", "title": ""}
{"_id": "d10037", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d10038", "text": "def _digits(minval, maxval):\n    \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n    if minval == maxval:\n        return 3\n    else:\n        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "title": ""}
{"_id": "d10039", "text": "def print_yaml(o):\n    \"\"\"Pretty print an object as YAML.\"\"\"\n    print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))", "title": ""}
{"_id": "d10040", "text": "def heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "title": ""}
{"_id": "d10041", "text": "def softmax(xs):\n    \"\"\"Stable implementation of the softmax function.\"\"\"\n    ys = xs - np.max(xs)\n    exps = np.exp(ys)\n    return exps / exps.sum(axis=0)", "title": ""}
{"_id": "d10042", "text": "def get_indentation(line):\n    \"\"\"Return leading whitespace.\"\"\"\n    if line.strip():\n        non_whitespace_index = len(line) - len(line.lstrip())\n        return line[:non_whitespace_index]\n    else:\n        return ''", "title": ""}
{"_id": "d10043", "text": "def read_bytes(fo, writer_schema=None, reader_schema=None):\n    \"\"\"Bytes are encoded as a long followed by that many bytes of data.\"\"\"\n    size = read_long(fo)\n    return fo.read(size)", "title": ""}
{"_id": "d10044", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d10045", "text": "def included_length(self):\n        \"\"\"Surveyed length, not including \"excluded\" shots\"\"\"\n        return sum([shot.length for shot in self.shots if shot.is_included])", "title": ""}
{"_id": "d10046", "text": "def load_streams(chunks):\n    \"\"\"\n    Given a gzipped stream of data, yield streams of decompressed data.\n    \"\"\"\n    chunks = peekable(chunks)\n    while chunks:\n        if six.PY3:\n            dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)\n        else:\n            dc = zlib.decompressobj(zlib.MAX_WBITS | 16)\n        yield load_stream(dc, chunks)\n        if dc.unused_data:\n            chunks = peekable(itertools.chain((dc.unused_data,), chunks))", "title": ""}
{"_id": "d10047", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d10048", "text": "def compress(data, **kwargs):\n    \"\"\"zlib.compress(data, **kwargs)\n    \n    \"\"\" + zopfli.__COMPRESSOR_DOCSTRING__  + \"\"\"\n    Returns:\n      String containing a zlib container\n    \"\"\"\n    kwargs['gzip_mode'] = 0\n    return zopfli.zopfli.compress(data, **kwargs)", "title": ""}
{"_id": "d10049", "text": "def memory_usage(method):\n  \"\"\"Log memory usage before and after a method.\"\"\"\n  def wrapper(*args, **kwargs):\n    logging.info('Memory before method %s is %s.',\n                 method.__name__, runtime.memory_usage().current())\n    result = method(*args, **kwargs)\n    logging.info('Memory after method %s is %s',\n                 method.__name__, runtime.memory_usage().current())\n    return result\n  return wrapper", "title": ""}
{"_id": "d10050", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d10051", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d10052", "text": "def input_int_default(question=\"\", default=0):\n    \"\"\"A function that works for both, Python 2.x and Python 3.x.\n       It asks the user for input and returns it as a string.\n    \"\"\"\n    answer = input_string(question)\n    if answer == \"\" or answer == \"yes\":\n        return default\n    else:\n        return int(answer)", "title": ""}
{"_id": "d10053", "text": "def listunion(ListOfLists):\n    \"\"\"\n    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`.\n\n    \"\"\"\n    u = []\n    for s in ListOfLists:\n        if s != None:\n            u.extend(s)\n    return u", "title": ""}
{"_id": "d10054", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d10055", "text": "def dict_merge(set1, set2):\n    \"\"\"Joins two dictionaries.\"\"\"\n    return dict(list(set1.items()) + list(set2.items()))", "title": ""}
{"_id": "d10056", "text": "def asynchronous(function, event):\n    \"\"\"\n    Runs the function asynchronously taking care of exceptions.\n    \"\"\"\n    thread = Thread(target=synchronous, args=(function, event))\n    thread.daemon = True\n    thread.start()", "title": ""}
{"_id": "d10057", "text": "def dictmerge(x, y):\n    \"\"\"\n    merge two dictionaries\n    \"\"\"\n    z = x.copy()\n    z.update(y)\n    return z", "title": ""}
{"_id": "d10058", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d10059", "text": "def upsert_single(db, collection, object, match_params=None):\n        \"\"\"\n        Wrapper for pymongo.update_one()\n        :param db: db connection\n        :param collection: collection to update\n        :param object: the modifications to apply\n        :param match_params: a query that matches the documents to update\n        :return: id of updated document\n        \"\"\"\n        return str(db[collection].update_one(match_params, {\"$set\": object}, upsert=True).upserted_id)", "title": ""}
{"_id": "d10060", "text": "def bin_to_int(string):\n    \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n    if isinstance(string, str):\n        return struct.unpack(\"b\", string)[0]\n    else:\n        return struct.unpack(\"b\", bytes([string]))[0]", "title": ""}
{"_id": "d10061", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d10062", "text": "def is_valid_folder(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.isdir(arg):\n        parser.error(\"The folder %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d10063", "text": "def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y):\n    \"\"\"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)\n    \"\"\"\n    return image_transform(\n        X,\n        cv2.GaussianBlur,\n        ksize=(ksize_width, ksize_height),\n        sigmaX=sigma_x,\n        sigmaY=sigma_y\n    )", "title": ""}
{"_id": "d10064", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d10065", "text": "def set_slug(apps, schema_editor, class_name):\n    \"\"\"\n    Create a slug for each Work already in the DB.\n    \"\"\"\n    Cls = apps.get_model('spectator_events', class_name)\n\n    for obj in Cls.objects.all():\n        obj.slug = generate_slug(obj.pk)\n        obj.save(update_fields=['slug'])", "title": ""}
{"_id": "d10066", "text": "def moving_average(a, n):\n    \"\"\"Moving average over one-dimensional array.\n\n    Parameters\n    ----------\n    a : np.ndarray\n        One-dimensional array.\n    n : int\n        Number of entries to average over. n=2 means averaging over the currrent\n        the previous entry.\n\n    Returns\n    -------\n    An array view storing the moving average.\n    \"\"\"\n    ret = np.cumsum(a, dtype=float)\n    ret[n:] = ret[n:] - ret[:-n]\n    return ret[n - 1:] / n", "title": ""}
{"_id": "d10067", "text": "def sigterm(self, signum, frame):\n        \"\"\"\n        These actions will be done after SIGTERM.\n        \"\"\"\n        self.logger.warning(\"Caught signal %s. Stopping daemon.\" % signum)\n        sys.exit(0)", "title": ""}
{"_id": "d10068", "text": "def go_to_parent_directory(self):\n        \"\"\"Go to parent directory\"\"\"\n        self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))", "title": ""}
{"_id": "d10069", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d10070", "text": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "title": ""}
{"_id": "d10071", "text": "def is_enum_type(type_):\n    \"\"\" Checks if the given type is an enum type.\n\n    :param type_: The type to check\n    :return: True if the type is a enum type, otherwise False\n    :rtype: bool\n    \"\"\"\n\n    return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))", "title": ""}
{"_id": "d10072", "text": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "title": ""}
{"_id": "d10073", "text": "def count_words(file):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  c = Counter()\n  with open(file, 'r') as f:\n    for l in f:\n      words = l.strip().split()\n      c.update(words)\n  return c", "title": ""}
{"_id": "d10074", "text": "def setdefault(obj, field, default):\n    \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n    setattr(obj, field, getattr(obj, field, default))", "title": ""}
{"_id": "d10075", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d10076", "text": "def init_rotating_logger(level, logfile, max_files, max_bytes):\n  \"\"\"Initializes a rotating logger\n\n  It also makes sure that any StreamHandler is removed, so as to avoid stdout/stderr\n  constipation issues\n  \"\"\"\n  logging.basicConfig()\n\n  root_logger = logging.getLogger()\n  log_format = \"[%(asctime)s] [%(levelname)s] %(filename)s: %(message)s\"\n\n  root_logger.setLevel(level)\n  handler = RotatingFileHandler(logfile, maxBytes=max_bytes, backupCount=max_files)\n  handler.setFormatter(logging.Formatter(fmt=log_format, datefmt=date_format))\n  root_logger.addHandler(handler)\n\n  for handler in root_logger.handlers:\n    root_logger.debug(\"Associated handlers - \" + str(handler))\n    if isinstance(handler, logging.StreamHandler):\n      root_logger.debug(\"Removing StreamHandler: \" + str(handler))\n      root_logger.handlers.remove(handler)", "title": ""}
{"_id": "d10077", "text": "def word_matches(s1, s2, n=3):\n    \"\"\"\n        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\n    \"\"\"\n    return __matches(s1, s2, word_ngrams, n=n)", "title": ""}
{"_id": "d10078", "text": "def write(self, text):\n        \"\"\"Write text. An additional attribute terminator with a value of\n           None is added to the logging record to indicate that StreamHandler\n           should not add a newline.\"\"\"\n        self.logger.log(self.loglevel, text, extra={'terminator': None})", "title": ""}
{"_id": "d10079", "text": "def _executemany(self, cursor, query, parameters):\n        \"\"\"The function is mostly useful for commands that update the database:\n           any result set returned by the query is discarded.\"\"\"\n        try:\n            self._log(query)\n            cursor.executemany(query, parameters)\n        except OperationalError as e:  # pragma: no cover\n            logging.error('Error connecting to PostgreSQL on %s, e', self.host, e)\n            self.close()\n            raise", "title": ""}
{"_id": "d10080", "text": "def _bytes_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, bytes):\n        value = base64.standard_b64encode(value).decode(\"ascii\")\n    return value", "title": ""}
{"_id": "d10081", "text": "async def readline(self):\n        \"\"\"\n        This is an asyncio adapted version of pyserial read.\n        It provides a non-blocking read and returns a line of data read.\n\n        :return: A line of data\n        \"\"\"\n        future = asyncio.Future()\n        data_available = False\n        while True:\n            if not data_available:\n                if not self.my_serial.inWaiting():\n                    await asyncio.sleep(self.sleep_tune)\n                else:\n                    data_available = True\n                    data = self.my_serial.readline()\n                    future.set_result(data)\n            else:\n                if not future.done():\n                    await asyncio.sleep(self.sleep_tune)\n                else:\n                    return future.result()", "title": ""}
{"_id": "d10082", "text": "def parse_date(s):\n    \"\"\"Fast %Y-%m-%d parsing.\"\"\"\n    try:\n        return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10]))\n    except ValueError:  # other accepted format used in one-day data set\n        return datetime.datetime.strptime(s, '%d %B %Y').date()", "title": ""}
{"_id": "d10083", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d10084", "text": "def read_string(buff, byteorder='big'):\n    \"\"\"Read a string from a file-like object.\"\"\"\n    length = read_numeric(USHORT, buff, byteorder)\n    return buff.read(length).decode('utf-8')", "title": ""}
{"_id": "d10085", "text": "def _normalize_abmn(abmn):\n    \"\"\"return a normalized version of abmn\n    \"\"\"\n    abmn_2d = np.atleast_2d(abmn)\n    abmn_normalized = np.hstack((\n        np.sort(abmn_2d[:, 0:2], axis=1),\n        np.sort(abmn_2d[:, 2:4], axis=1),\n    ))\n    return abmn_normalized", "title": ""}
{"_id": "d10086", "text": "def disable_stdout_buffering():\n    \"\"\"This turns off stdout buffering so that outputs are immediately\n    materialized and log messages show up before the program exits\"\"\"\n    stdout_orig = sys.stdout\n    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n    # NOTE(brandyn): This removes the original stdout\n    return stdout_orig", "title": ""}
{"_id": "d10087", "text": "def denorm(self,arr):\n        \"\"\"Reverse the normalization done to a batch of images.\n\n        Arguments:\n            arr: of shape/size (N,3,sz,sz)\n        \"\"\"\n        if type(arr) is not np.ndarray: arr = to_np(arr)\n        if len(arr.shape)==3: arr = arr[None]\n        return self.transform.denorm(np.rollaxis(arr,1,4))", "title": ""}
{"_id": "d10088", "text": "def pick_unused_port(self):\n    \"\"\" Pick an unused port. There is a slight chance that this wont work. \"\"\"\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.bind(('127.0.0.1', 0))\n    _, port = s.getsockname()\n    s.close()\n    return port", "title": ""}
{"_id": "d10089", "text": "def is_gzipped_fastq(file_name):\n    \"\"\"\n    Determine whether indicated file appears to be a gzipped FASTQ.\n\n    :param str file_name: Name/path of file to check as gzipped FASTQ.\n    :return bool: Whether indicated file appears to be in gzipped FASTQ format.\n    \"\"\"\n    _, ext = os.path.splitext(file_name)\n    return file_name.endswith(\".fastq.gz\") or file_name.endswith(\".fq.gz\")", "title": ""}
{"_id": "d10090", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d10091", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d10092", "text": "def safe_unicode(string):\n    \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n    if not PY3:\n        uni = string.replace(u'\\u2019', \"'\")\n        return uni.encode('utf-8')\n        \n    return string", "title": ""}
{"_id": "d10093", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d10094", "text": "def check_str(obj):\n        \"\"\" Returns a string for various input types \"\"\"\n        if isinstance(obj, str):\n            return obj\n        if isinstance(obj, float):\n            return str(int(obj))\n        else:\n            return str(obj)", "title": ""}
{"_id": "d10095", "text": "def get_incomplete_path(filename):\n  \"\"\"Returns a temporary filename based on filename.\"\"\"\n  random_suffix = \"\".join(\n      random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n  return filename + \".incomplete\" + random_suffix", "title": ""}
{"_id": "d10096", "text": "def iso_to_datetime(date):\n    \"\"\" Convert ISO 8601 time format to datetime format\n\n    This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.\n    ``datetime.datetime(2017,9,14,0,0)``\n\n    :param date: date in ISO 8601 format\n    :type date: str\n    :return: datetime instance\n    :rtype: datetime\n    \"\"\"\n    chunks = list(map(int, date.split('T')[0].split('-')))\n    return datetime.datetime(chunks[0], chunks[1], chunks[2])", "title": ""}
{"_id": "d10097", "text": "def _to_array(value):\n    \"\"\"As a convenience, turn Python lists and tuples into NumPy arrays.\"\"\"\n    if isinstance(value, (tuple, list)):\n        return array(value)\n    elif isinstance(value, (float, int)):\n        return np.float64(value)\n    else:\n        return value", "title": ""}
{"_id": "d10098", "text": "def unique_deps(deps):\n    \"\"\"Remove duplicities from deps list of the lists\"\"\"\n    deps.sort()\n    return list(k for k, _ in itertools.groupby(deps))", "title": ""}
{"_id": "d10099", "text": "def is_float_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy float array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy float array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.floating)", "title": ""}
{"_id": "d10100", "text": "def _get_all_constants():\n    \"\"\"\n    Get list of all uppercase, non-private globals (doesn't start with ``_``).\n\n    Returns:\n        list: Uppercase names defined in `globals()` (variables from this \\\n              module).\n    \"\"\"\n    return [\n        key for key in globals().keys()\n        if all([\n            not key.startswith(\"_\"),          # publicly accesible\n            key.upper() == key,               # uppercase\n            type(globals()[key]) in _ALLOWED  # and with type from _ALLOWED\n        ])\n    ]", "title": ""}
{"_id": "d10101", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d10102", "text": "def find_one(cls, *args, **kw):\n\t\t\"\"\"Get a single document from the collection this class is bound to.\n\t\t\n\t\tAdditional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional\n\t\tparameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword\n\t\targuments passed along with minor transformation.\n\t\t\n\t\tAutomatically calls `to_mongo` with the retrieved data.\n\t\t\n\t\thttps://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one\n\t\t\"\"\"\n\t\t\n\t\tif len(args) == 1 and not isinstance(args[0], Filter):\n\t\t\targs = (getattr(cls, cls.__pk__) == args[0], )\n\t\t\n\t\tDoc, collection, query, options = cls._prepare_find(*args, **kw)\n\t\tresult = Doc.from_mongo(collection.find_one(query, **options))\n\t\t\n\t\treturn result", "title": ""}
{"_id": "d10103", "text": "def _config_parse(self):\n        \"\"\"Replacer oslo_config.cfg.ConfigParser.parse for in-memory cfg.\"\"\"\n        res = super(cfg.ConfigParser, self).parse(Backend._config_string_io)\n        return res", "title": ""}
{"_id": "d10104", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d10105", "text": "def gen_random_string(str_len):\n    \"\"\" generate random string with specified length\n    \"\"\"\n    return ''.join(\n        random.choice(string.ascii_letters + string.digits) for _ in range(str_len))", "title": ""}
{"_id": "d10106", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d10107", "text": "def gen_random_string(str_len):\n    \"\"\" generate random string with specified length\n    \"\"\"\n    return ''.join(\n        random.choice(string.ascii_letters + string.digits) for _ in range(str_len))", "title": ""}
{"_id": "d10108", "text": "def one_hot_encoding(input_tensor, num_labels):\n    \"\"\" One-hot encode labels from input \"\"\"\n    xview = input_tensor.view(-1, 1).to(torch.long)\n\n    onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)\n    onehot.scatter_(1, xview, 1)\n    return onehot.view(list(input_tensor.shape) + [-1])", "title": ""}
{"_id": "d10109", "text": "def runiform(lower, upper, size=None):\n    \"\"\"\n    Random uniform variates.\n    \"\"\"\n    return np.random.uniform(lower, upper, size)", "title": ""}
{"_id": "d10110", "text": "def rpc_fix_code(self, source, directory):\n        \"\"\"Formats Python code to conform to the PEP 8 style guide.\n\n        \"\"\"\n        source = get_source(source)\n        return fix_code(source, directory)", "title": ""}
{"_id": "d10111", "text": "def overlap(intv1, intv2):\n    \"\"\"Overlaping of two intervals\"\"\"\n    return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))", "title": ""}
{"_id": "d10112", "text": "def created_today(self):\n        \"\"\"Return True if created today.\"\"\"\n        if self.datetime.date() == datetime.today().date():\n            return True\n        return False", "title": ""}
{"_id": "d10113", "text": "def items(cls):\n        \"\"\"\n        All values for this enum\n        :return: list of tuples\n\n        \"\"\"\n        return [\n            cls.PRECIPITATION,\n            cls.WIND,\n            cls.TEMPERATURE,\n            cls.PRESSURE\n        ]", "title": ""}
{"_id": "d10114", "text": "def log(logger, level, message):\n    \"\"\"Logs message to stderr if logging isn't initialized.\"\"\"\n\n    if logger.parent.name != 'root':\n        logger.log(level, message)\n    else:\n        print(message, file=sys.stderr)", "title": ""}
{"_id": "d10115", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d10116", "text": "def read_string_from_file(path, encoding=\"utf8\"):\n  \"\"\"\n  Read entire contents of file into a string.\n  \"\"\"\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value", "title": ""}
{"_id": "d10117", "text": "def filechunk(f, chunksize):\n    \"\"\"Iterator that allow for piecemeal processing of a file.\"\"\"\n    while True:\n        chunk = tuple(itertools.islice(f, chunksize))\n        if not chunk:\n            return\n        yield np.loadtxt(iter(chunk), dtype=np.float64)", "title": ""}
{"_id": "d10118", "text": "def read_string_from_file(path, encoding=\"utf8\"):\n  \"\"\"\n  Read entire contents of file into a string.\n  \"\"\"\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value", "title": ""}
{"_id": "d10119", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d10120", "text": "def read_string_from_file(path, encoding=\"utf8\"):\n  \"\"\"\n  Read entire contents of file into a string.\n  \"\"\"\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value", "title": ""}
{"_id": "d10121", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d10122", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d10123", "text": "def count_words(file):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  c = Counter()\n  with open(file, 'r') as f:\n    for l in f:\n      words = l.strip().split()\n      c.update(words)\n  return c", "title": ""}
{"_id": "d10124", "text": "def Output(self):\n    \"\"\"Output all sections of the page.\"\"\"\n    self.Open()\n    self.Header()\n    self.Body()\n    self.Footer()", "title": ""}
{"_id": "d10125", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d10126", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d10127", "text": "def read(fname):\n    \"\"\"Quick way to read a file content.\"\"\"\n    content = None\n    with open(os.path.join(here, fname)) as f:\n        content = f.read()\n    return content", "title": ""}
{"_id": "d10128", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d10129", "text": "def h5ToDict(h5, readH5pyDataset=True):\n    \"\"\" Read a hdf5 file into a dictionary \"\"\"\n    h = h5py.File(h5, \"r\")\n    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n    if readH5pyDataset: h.close()\n    return ret", "title": ""}
{"_id": "d10130", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d10131", "text": "def _load_data(filepath):\n  \"\"\"Loads the images and latent values into Numpy arrays.\"\"\"\n  with h5py.File(filepath, \"r\") as h5dataset:\n    image_array = np.array(h5dataset[\"images\"])\n    # The 'label' data set in the hdf5 file actually contains the float values\n    # and not the class labels.\n    values_array = np.array(h5dataset[\"labels\"])\n  return image_array, values_array", "title": ""}
{"_id": "d10132", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d10133", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d10134", "text": "def _loadfilepath(self, filepath, **kwargs):\n        \"\"\"This loads a geojson file into a geojson python\n        dictionary using the json module.\n        \n        Note: to load with a different text encoding use the encoding argument.\n        \"\"\"\n        with open(filepath, \"r\") as f:\n            data = json.load(f, **kwargs)\n        return data", "title": ""}
{"_id": "d10135", "text": "def parse_querystring(self, req, name, field):\n        \"\"\"Pull a querystring value from the request.\"\"\"\n        return core.get_value(req.args, name, field)", "title": ""}
{"_id": "d10136", "text": "def _or(ctx, *logical):\n    \"\"\"\n    Returns TRUE if any argument is TRUE\n    \"\"\"\n    for arg in logical:\n        if conversions.to_boolean(arg, ctx):\n            return True\n    return False", "title": ""}
{"_id": "d10137", "text": "def rrmdir(directory):\n    \"\"\"\n    Recursivly delete a directory\n\n    :param directory: directory to remove\n    \"\"\"\n    for root, dirs, files in os.walk(directory, topdown=False):\n        for name in files:\n            os.remove(os.path.join(root, name))\n        for name in dirs:\n            os.rmdir(os.path.join(root, name))\n    os.rmdir(directory)", "title": ""}
{"_id": "d10138", "text": "def extract_all(zipfile, dest_folder):\n    \"\"\"\n    reads the zip file, determines compression\n    and unzips recursively until source files \n    are extracted \n    \"\"\"\n    z = ZipFile(zipfile)\n    print(z)\n    z.extract(dest_folder)", "title": ""}
{"_id": "d10139", "text": "def imp_print(self, text, end):\n\t\t\"\"\"Directly send utf8 bytes to stdout\"\"\"\n\t\tsys.stdout.write((text + end).encode(\"utf-8\"))", "title": ""}
{"_id": "d10140", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d10141", "text": "def create_env(env_file):\n    \"\"\"Create environ dictionary from current os.environ and\n    variables got from given `env_file`\"\"\"\n\n    environ = {}\n    with open(env_file, 'r') as f:\n        for line in f.readlines():\n            line = line.rstrip(os.linesep)\n            if '=' not in line:\n                continue\n            if line.startswith('#'):\n                continue\n            key, value = line.split('=', 1)\n            environ[key] = parse_value(value)\n    return environ", "title": ""}
{"_id": "d10142", "text": "def disable_stdout_buffering():\n    \"\"\"This turns off stdout buffering so that outputs are immediately\n    materialized and log messages show up before the program exits\"\"\"\n    stdout_orig = sys.stdout\n    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n    # NOTE(brandyn): This removes the original stdout\n    return stdout_orig", "title": ""}
{"_id": "d10143", "text": "def make_lambda(call):\n    \"\"\"Wrap an AST Call node to lambda expression node.\n    call: ast.Call node\n    \"\"\"\n    empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n    return ast.Lambda(args=empty_args, body=call)", "title": ""}
{"_id": "d10144", "text": "def DeleteIndex(self, index):\n        \"\"\"\n        Remove a spent coin based on its index.\n\n        Args:\n            index (int):\n        \"\"\"\n        to_remove = None\n        for i in self.Items:\n            if i.index == index:\n                to_remove = i\n\n        if to_remove:\n            self.Items.remove(to_remove)", "title": ""}
{"_id": "d10145", "text": "def parse(self, s):\n        \"\"\"\n        Parses a date string formatted like ``YYYY-MM-DD``.\n        \"\"\"\n        return datetime.datetime.strptime(s, self.date_format).date()", "title": ""}
{"_id": "d10146", "text": "def delete_entry(self, key):\n        \"\"\"Delete an object from the redis table\"\"\"\n        pipe = self.client.pipeline()\n        pipe.srem(self.keys_container, key)\n        pipe.delete(key)\n        pipe.execute()", "title": ""}
{"_id": "d10147", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d10148", "text": "def _accumulate(sequence, func):\n    \"\"\"\n    Python2 accumulate implementation taken from\n    https://docs.python.org/3/library/itertools.html#itertools.accumulate\n    \"\"\"\n    iterator = iter(sequence)\n    total = next(iterator)\n    yield total\n    for element in iterator:\n        total = func(total, element)\n        yield total", "title": ""}
{"_id": "d10149", "text": "def strip_columns(tab):\n    \"\"\"Strip whitespace from string columns.\"\"\"\n    for colname in tab.colnames:\n        if tab[colname].dtype.kind in ['S', 'U']:\n            tab[colname] = np.core.defchararray.strip(tab[colname])", "title": ""}
{"_id": "d10150", "text": "def StreamWrite(stream, *obj):\n    \"\"\"Writes Python object to Skype application stream.\"\"\"\n    stream.Write(base64.encodestring(pickle.dumps(obj)))", "title": ""}
{"_id": "d10151", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d10152", "text": "def dict_jsonp(param):\n    \"\"\"Convert the parameter into a dictionary before calling jsonp, if it's not already one\"\"\"\n    if not isinstance(param, dict):\n        param = dict(param)\n    return jsonp(param)", "title": ""}
{"_id": "d10153", "text": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "title": ""}
{"_id": "d10154", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d10155", "text": "def __normalize_list(self, msg):\n        \"\"\"Split message to list by commas and trim whitespace.\"\"\"\n        if isinstance(msg, list):\n            msg = \"\".join(msg)\n        return list(map(lambda x: x.strip(), msg.split(\",\")))", "title": ""}
{"_id": "d10156", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d10157", "text": "def filter_lines_from_comments(lines):\n    \"\"\" Filter the lines from comments and non code 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", "title": ""}
{"_id": "d10158", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d10159", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d10160", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d10161", "text": "def parse_timestamp(timestamp):\n    \"\"\"Parse ISO8601 timestamps given by github API.\"\"\"\n    dt = dateutil.parser.parse(timestamp)\n    return dt.astimezone(dateutil.tz.tzutc())", "title": ""}
{"_id": "d10162", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d10163", "text": "def highlight_region(plt, start_x, end_x):\n  \"\"\"\n  Highlight a region on the chart between the specified start and end x-co-ordinates.\n  param pyplot plt: matplotlibk pyplot which contains the charts to be highlighted\n  param string start_x : epoch time millis\n  param string end_x : epoch time millis\n  \"\"\"\n  start_x = convert_to_mdate(start_x)\n  end_x = convert_to_mdate(end_x)\n  plt.axvspan(start_x, end_x, color=CONSTANTS.HIGHLIGHT_COLOR, alpha=CONSTANTS.HIGHLIGHT_ALPHA)", "title": ""}
{"_id": "d10164", "text": "def unique(transactions):\n    \"\"\" Remove any duplicate entries. \"\"\"\n    seen = set()\n    # TODO: Handle comments\n    return [x for x in transactions if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d10165", "text": "def compute_boxplot(self, series):\n        \"\"\"\n        Compute boxplot for given pandas Series.\n        \"\"\"\n        from matplotlib.cbook import boxplot_stats\n        series = series[series.notnull()]\n        if len(series.values) == 0:\n            return {}\n        elif not is_numeric_dtype(series):\n            return self.non_numeric_stats(series)\n        stats = boxplot_stats(list(series.values))[0]\n        stats['count'] = len(series.values)\n        stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n        return stats", "title": ""}
{"_id": "d10166", "text": "def uncomment_line(line, prefix):\n    \"\"\"Remove prefix (and space) from line\"\"\"\n    if not prefix:\n        return line\n    if line.startswith(prefix + ' '):\n        return line[len(prefix) + 1:]\n    if line.startswith(prefix):\n        return line[len(prefix):]\n    return line", "title": ""}
{"_id": "d10167", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d10168", "text": "def strip_spaces(x):\n    \"\"\"\n    Strips spaces\n    :param x:\n    :return:\n    \"\"\"\n    x = x.replace(b' ', b'')\n    x = x.replace(b'\\t', b'')\n    return x", "title": ""}
{"_id": "d10169", "text": "def pop (self, key):\n        \"\"\"Remove key from dict and return value.\"\"\"\n        if key in self._keys:\n            self._keys.remove(key)\n        super(ListDict, self).pop(key)", "title": ""}
{"_id": "d10170", "text": "def draw_tree(t, df, size=10, ratio=0.6, precision=0):\n    \"\"\" Draws a representation of a random forest in IPython.\n    Parameters:\n    -----------\n    t: The tree you wish to draw\n    df: The data used to train the tree. This is used to get the names of the features.\n    \"\"\"\n    s=export_graphviz(t, out_file=None, feature_names=df.columns, filled=True,\n                      special_characters=True, rotate=True, precision=precision)\n    IPython.display.display(graphviz.Source(re.sub('Tree {',\n       f'Tree {{ size={size}; ratio={ratio}', s)))", "title": ""}
{"_id": "d10171", "text": "def remove_last_entry(self):\n        \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n        self.current_beat -= 1.0 / self.bar[-1][1]\n        self.bar = self.bar[:-1]\n        return self.current_beat", "title": ""}
{"_id": "d10172", "text": "def confusion_matrix(self):\n        \"\"\"Confusion matrix plot\n        \"\"\"\n        return plot.confusion_matrix(self.y_true, self.y_pred,\n                                     self.target_names, ax=_gen_ax())", "title": ""}
{"_id": "d10173", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d10174", "text": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Like `pretty` but print to stdout.\n    \"\"\"\n    printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    sys.stdout.write(newline)\n    sys.stdout.flush()", "title": ""}
{"_id": "d10175", "text": "def distinct(l):\n    \"\"\"\n    Return a list where the duplicates have been removed.\n\n    Args:\n        l (list): the list to filter.\n\n    Returns:\n        list: the same list without duplicates.\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return (_ for _ in l if not (_ in seen or seen_add(_)))", "title": ""}
{"_id": "d10176", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d10177", "text": "def _breakRemNewlines(tag):\n\t\"\"\"non-recursively break spaces and remove newlines in the tag\"\"\"\n\tfor i,c in enumerate(tag.contents):\n\t\tif type(c) != bs4.element.NavigableString:\n\t\t\tcontinue\n\t\tc.replace_with(re.sub(r' {2,}', ' ', c).replace('\\n',''))", "title": ""}
{"_id": "d10178", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d10179", "text": "def text_cleanup(data, key, last_type):\n    \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data", "title": ""}
{"_id": "d10180", "text": "def __repr__(self):\n        \"\"\"Return string representation of object.\"\"\"\n        return str(self.__class__) + '(' + ', '.join([list.__repr__(d) for d in self.data]) + ')'", "title": ""}
{"_id": "d10181", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d10182", "text": "def print_err(*args, end='\\n'):\n    \"\"\"Similar to print, but prints to stderr.\n    \"\"\"\n    print(*args, end=end, file=sys.stderr)\n    sys.stderr.flush()", "title": ""}
{"_id": "d10183", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d10184", "text": "def prnt(self):\n        \"\"\"\n        Prints DB data representation of the object.\n        \"\"\"\n        print(\"= = = =\\n\\n%s object key: \\033[32m%s\\033[0m\" % (self.__class__.__name__, self.key))\n        pprnt(self._data or self.clean_value())", "title": ""}
{"_id": "d10185", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d10186", "text": "def EnumValueName(self, enum, value):\n    \"\"\"Returns the string name of an enum value.\n\n    This is just a small helper method to simplify a common operation.\n\n    Args:\n      enum: string name of the Enum.\n      value: int, value of the enum.\n\n    Returns:\n      string name of the enum value.\n\n    Raises:\n      KeyError if either the Enum doesn't exist or the value is not a valid\n        value for the enum.\n    \"\"\"\n    return self.enum_types_by_name[enum].values_by_number[value].name", "title": ""}
{"_id": "d10187", "text": "def replace_list(items, match, replacement):\n    \"\"\"Replaces occurrences of a match string in a given list of strings and returns\n    a list of new strings. The match string can be a regex expression.\n\n    Args:\n        items (list):       the list of strings to modify.\n        match (str):        the search expression.\n        replacement (str):  the string to replace with.\n    \"\"\"\n    return [replace(item, match, replacement) for item in items]", "title": ""}
{"_id": "d10188", "text": "def get_unique_indices(df, axis=1):\n    \"\"\"\n\n    :param df:\n    :param axis:\n    :return:\n    \"\"\"\n    return dict(zip(df.columns.names, dif.columns.levels))", "title": ""}
{"_id": "d10189", "text": "def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):\n    \"\"\"Replace month strings occurrences with month number.\"\"\"\n    num, abbr = get_month_from_date_str(date_str, lang)\n    return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE)", "title": ""}
{"_id": "d10190", "text": "def get_subplot_at(self, row, column):\n        \"\"\"Return the subplot at row, column position.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        idx = row * self.columns + column\n        return self.subplots[idx]", "title": ""}
{"_id": "d10191", "text": "def slugify(string):\n    \"\"\"\n    Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n    \"\"\"\n    string = re.sub('[^\\w .-]', '', string)\n    string = string.replace(\" \", \"-\")\n    return string", "title": ""}
{"_id": "d10192", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d10193", "text": "def request_type(self):\n        \"\"\"Retrieve the type of the request, by fetching it from\n        `xenon.proto.xenon_pb2`.\"\"\"\n        if self.static and not self.uses_request:\n            return getattr(xenon_pb2, 'Empty')\n\n        if not self.uses_request:\n            return None\n\n        return getattr(xenon_pb2, self.request_name)", "title": ""}
{"_id": "d10194", "text": "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)", "title": ""}
{"_id": "d10195", "text": "def peak_memory_usage():\n    \"\"\"Return peak memory usage in MB\"\"\"\n    if sys.platform.startswith('win'):\n        p = psutil.Process()\n        return p.memory_info().peak_wset / 1024 / 1024\n\n    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n    factor_mb = 1 / 1024\n    if sys.platform == 'darwin':\n        factor_mb = 1 / (1024 * 1024)\n    return mem * factor_mb", "title": ""}
{"_id": "d10196", "text": "def cmd_reindex():\n    \"\"\"Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.\n\n    The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until\n    the rename succeeds.\n    \"\"\"\n    db = connect(args.database)\n    for idx in args.indexes:\n        pg_reindex(db, idx)", "title": ""}
{"_id": "d10197", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d10198", "text": "def make_2d(ary):\n    \"\"\"Convert any array into a 2d numpy array.\n\n    In case the array is already more than 2 dimensional, will ravel the\n    dimensions after the first.\n    \"\"\"\n    dim_0, *_ = np.atleast_1d(ary).shape\n    return ary.reshape(dim_0, -1, order=\"F\")", "title": ""}
{"_id": "d10199", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d10200", "text": "def _check_for_int(x):\n    \"\"\"\n    This is a compatibility function that takes a C{float} and converts it to an\n    C{int} if the values are equal.\n    \"\"\"\n    try:\n        y = int(x)\n    except (OverflowError, ValueError):\n        pass\n    else:\n        # There is no way in AMF0 to distinguish between integers and floats\n        if x == x and y == x:\n            return y\n\n    return x", "title": ""}
{"_id": "d10201", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d10202", "text": "def _serialize_json(obj, fp):\n    \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n    json.dump(obj, fp, indent=4, default=serialize)", "title": ""}
{"_id": "d10203", "text": "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location", "title": ""}
{"_id": "d10204", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d10205", "text": "def get_item_from_queue(Q, timeout=0.01):\n    \"\"\" Attempts to retrieve an item from the queue Q. If Q is\n        empty, None is returned.\n\n        Blocks for 'timeout' seconds in case the queue is empty,\n        so don't use this method for speedy retrieval of multiple\n        items (use get_all_from_queue for that).\n    \"\"\"\n    try:\n        item = Q.get(True, 0.01)\n    except Queue.Empty:\n        return None\n\n    return item", "title": ""}
{"_id": "d10206", "text": "def vec(self):\n        \"\"\":obj:`numpy.ndarray` : Vector representation for this camera.\n        \"\"\"\n        return np.r_[self.fx, self.fy, self.cx, self.cy, self.skew, self.height, self.width]", "title": ""}
{"_id": "d10207", "text": "def help_for_command(command):\n    \"\"\"Get the help text (signature + docstring) for a command (function).\"\"\"\n    help_text = pydoc.text.document(command)\n    # remove backspaces\n    return re.subn('.\\\\x08', '', help_text)[0]", "title": ""}
{"_id": "d10208", "text": "def kindex(matrix, k):\n    \"\"\" Returns indices to select the kth nearest neighbour\"\"\"\n\n    ix = (np.arange(len(matrix)), matrix.argsort(axis=0)[k])\n    return ix", "title": ""}
{"_id": "d10209", "text": "def check_permission_safety(path):\n    \"\"\"Check if the file at the given path is safe to use as a state file.\n\n    This checks that group and others have no permissions on the file and that the current user is\n    the owner.\n    \"\"\"\n    f_stats = os.stat(path)\n    return (f_stats.st_mode & (stat.S_IRWXG | stat.S_IRWXO)) == 0 and f_stats.st_uid == os.getuid()", "title": ""}
{"_id": "d10210", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d10211", "text": "def timestamp_to_datetime(timestamp):\n    \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n    from datetime import datetime, timedelta\n    obj = datetime.fromtimestamp(timestamp[0])\n    return obj + timedelta(microseconds=int(timestamp[1]))", "title": ""}
{"_id": "d10212", "text": "def reduce_fn(x):\n    \"\"\"\n    Aggregation function to get the first non-zero value.\n    \"\"\"\n    values = x.values if pd and isinstance(x, pd.Series) else x\n    for v in values:\n        if not is_nan(v):\n            return v\n    return np.NaN", "title": ""}
{"_id": "d10213", "text": "def array_dim(arr):\n    \"\"\"Return the size of a multidimansional array.\n    \"\"\"\n    dim = []\n    while True:\n        try:\n            dim.append(len(arr))\n            arr = arr[0]\n        except TypeError:\n            return dim", "title": ""}
{"_id": "d10214", "text": "def unique_items(seq):\n    \"\"\"Return the unique items from iterable *seq* (in order).\"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d10215", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d10216", "text": "def render_template(content, context):\n    \"\"\" renders context aware template \"\"\"\n    rendered = Template(content).render(Context(context))\n    return rendered", "title": ""}
{"_id": "d10217", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d10218", "text": "def _get_env(self, env_var):\n        \"\"\"Helper to read an environment variable\n        \"\"\"\n        value = os.environ.get(env_var)\n        if not value:\n            raise ValueError('Missing environment variable:%s' % env_var)\n        return value", "title": ""}
{"_id": "d10219", "text": "def stringc(text, color):\n    \"\"\"\n    Return a string with terminal colors.\n    \"\"\"\n    if has_colors:\n        text = str(text)\n\n        return \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"\n    else:\n        return text", "title": ""}
{"_id": "d10220", "text": "def is_int(value):\n    \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n    if isinstance(value, bool):\n        return False\n    try:\n        int(value)\n        return True\n    except (ValueError, TypeError):\n        return False", "title": ""}
{"_id": "d10221", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d10222", "text": "def get_uniques(l):\n    \"\"\" Returns a list with no repeated elements.\n    \"\"\"\n    result = []\n\n    for i in l:\n        if i not in result:\n            result.append(i)\n\n    return result", "title": ""}
{"_id": "d10223", "text": "def md5_hash_file(fh):\n    \"\"\"Return the md5 hash of the given file-object\"\"\"\n    md5 = hashlib.md5()\n    while True:\n        data = fh.read(8192)\n        if not data:\n            break\n        md5.update(data)\n    return md5.hexdigest()", "title": ""}
{"_id": "d10224", "text": "def create(parallel):\n    \"\"\"Create a queue based on the provided parallel arguments.\n\n    TODO Startup/tear-down. Currently using default queue for testing\n    \"\"\"\n    queue = {k: v for k, v in parallel.items() if k in [\"queue\", \"cores_per_job\", \"mem\"]}\n    yield queue", "title": ""}
{"_id": "d10225", "text": "def format_exc(limit=None):\n    \"\"\"Like print_exc() but return a string. Backport for Python 2.3.\"\"\"\n    try:\n        etype, value, tb = sys.exc_info()\n        return ''.join(traceback.format_exception(etype, value, tb, limit))\n    finally:\n        etype = value = tb = None", "title": ""}
{"_id": "d10226", "text": "def create_rot2d(angle):\n    \"\"\"Create 2D rotation matrix\"\"\"\n    ca = math.cos(angle)\n    sa = math.sin(angle)\n    return np.array([[ca, -sa], [sa, ca]])", "title": ""}
{"_id": "d10227", "text": "def is_valid_email(email):\n    \"\"\"\n    Check if email is valid\n    \"\"\"\n    pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n    return bool(pattern.match(email))", "title": ""}
{"_id": "d10228", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d10229", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d10230", "text": "def price_rounding(price, decimals=2):\n    \"\"\"Takes a decimal price and rounds to a number of decimal places\"\"\"\n    try:\n        exponent = D('.' + decimals * '0')\n    except InvalidOperation:\n        # Currencies with no decimal places, ex. JPY, HUF\n        exponent = D()\n    return price.quantize(exponent, rounding=ROUND_UP)", "title": ""}
{"_id": "d10231", "text": "def is_iterable(value):\n    \"\"\"must be an iterable (list, array, tuple)\"\"\"\n    return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "title": ""}
{"_id": "d10232", "text": "def getYamlDocument(filePath):\n    \"\"\"\n    Return a yaml file's contents as a dictionary\n    \"\"\"\n    with open(filePath) as stream:\n        doc = yaml.load(stream)\n        return doc", "title": ""}
{"_id": "d10233", "text": "def pp_xml(body):\n    \"\"\"Pretty print format some XML so it's readable.\"\"\"\n    pretty = xml.dom.minidom.parseString(body)\n    return pretty.toprettyxml(indent=\"  \")", "title": ""}
{"_id": "d10234", "text": "def safe_execute_script(driver, script):\n    \"\"\" When executing a script that contains a jQuery command,\n        it's important that the jQuery library has been loaded first.\n        This method will load jQuery if it wasn't already loaded. \"\"\"\n    try:\n        driver.execute_script(script)\n    except Exception:\n        # The likely reason this fails is because: \"jQuery is not defined\"\n        activate_jquery(driver)  # It's a good thing we can define it here\n        driver.execute_script(script)", "title": ""}
{"_id": "d10235", "text": "def create_rot2d(angle):\n    \"\"\"Create 2D rotation matrix\"\"\"\n    ca = math.cos(angle)\n    sa = math.sin(angle)\n    return np.array([[ca, -sa], [sa, ca]])", "title": ""}
{"_id": "d10236", "text": "def callPlaybook(self, playbook, ansibleArgs, wait=True, tags=[\"all\"]):\n        \"\"\"\n        Run a playbook.\n\n        :param playbook: An Ansible playbook to run.\n        :param ansibleArgs: Arguments to pass to the playbook.\n        :param wait: Wait for the play to finish if true.\n        :param tags: Control tags for the play.\n        \"\"\"\n        playbook = os.path.join(self.playbooks, playbook)  # Path to playbook being executed\n        verbosity = \"-vvvvv\" if logger.isEnabledFor(logging.DEBUG) else \"-v\"\n        command = [\"ansible-playbook\", verbosity, \"--tags\", \",\".join(tags), \"--extra-vars\"]\n        command.append(\" \".join([\"=\".join(i) for i in ansibleArgs.items()]))  # Arguments being passed to playbook\n        command.append(playbook)\n\n        logger.debug(\"Executing Ansible call `%s`\", \" \".join(command))\n        p = subprocess.Popen(command)\n        if wait:\n            p.communicate()\n            if p.returncode != 0:\n                # FIXME: parse error codes\n                raise RuntimeError(\"Ansible reported an error when executing playbook %s\" % playbook)", "title": ""}
{"_id": "d10237", "text": "def _get_all_constants():\n    \"\"\"\n    Get list of all uppercase, non-private globals (doesn't start with ``_``).\n\n    Returns:\n        list: Uppercase names defined in `globals()` (variables from this \\\n              module).\n    \"\"\"\n    return [\n        key for key in globals().keys()\n        if all([\n            not key.startswith(\"_\"),          # publicly accesible\n            key.upper() == key,               # uppercase\n            type(globals()[key]) in _ALLOWED  # and with type from _ALLOWED\n        ])\n    ]", "title": ""}
{"_id": "d10238", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d10239", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d10240", "text": "def set(self, f):\n        \"\"\"Call a function after a delay, unless another function is set\n        in the meantime.\"\"\"\n        self.stop()\n        self._create_timer(f)\n        self.start()", "title": ""}
{"_id": "d10241", "text": "def next(self):\n        \"\"\"Get the next value in the page.\"\"\"\n        item = six.next(self._item_iter)\n        result = self._item_to_value(self._parent, item)\n        # Since we've successfully got the next value from the\n        # iterator, we update the number of remaining.\n        self._remaining -= 1\n        return result", "title": ""}
{"_id": "d10242", "text": "def test():  # pragma: no cover\n    \"\"\"Execute the unit tests on an installed copy of unyt.\n\n    Note that this function requires pytest to run. If pytest is not\n    installed this function will raise ImportError.\n    \"\"\"\n    import pytest\n    import os\n\n    pytest.main([os.path.dirname(os.path.abspath(__file__))])", "title": ""}
{"_id": "d10243", "text": "def _to_json(self):\n        \"\"\" Gets a dict of this object's properties so that it can be used to send a dump to the client \"\"\"\n        return dict(( (k, v) for k, v in self.__dict__.iteritems() if k != 'server'))", "title": ""}
{"_id": "d10244", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d10245", "text": "def test():        \n    \"\"\"Local test.\"\"\"\n    from spyder.utils.qthelpers import qapplication\n    app = qapplication()\n    dlg = ProjectDialog(None)\n    dlg.show()\n    sys.exit(app.exec_())", "title": ""}
{"_id": "d10246", "text": "def title(self):\n        \"\"\" The title of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.title", "title": ""}
{"_id": "d10247", "text": "def get_key(self, key, bucket_name=None):\n        \"\"\"\n        Returns a boto3.s3.Object\n\n        :param key: the path to the key\n        :type key: str\n        :param bucket_name: the name of the bucket\n        :type bucket_name: str\n        \"\"\"\n        if not bucket_name:\n            (bucket_name, key) = self.parse_s3_url(key)\n\n        obj = self.get_resource_type('s3').Object(bucket_name, key)\n        obj.load()\n        return obj", "title": ""}
{"_id": "d10248", "text": "def add_matplotlib_cmap(cm, name=None):\n    \"\"\"Add a matplotlib colormap.\"\"\"\n    global cmaps\n    cmap = matplotlib_to_ginga_cmap(cm, name=name)\n    cmaps[cmap.name] = cmap", "title": ""}
{"_id": "d10249", "text": "def download_file(save_path, file_url):\n    \"\"\" Download file from http url link \"\"\"\n\n    r = requests.get(file_url)  # create HTTP response object\n\n    with open(save_path, 'wb') as f:\n        f.write(r.content)\n\n    return save_path", "title": ""}
{"_id": "d10250", "text": "def _encode_bool(name, value, dummy0, dummy1):\n    \"\"\"Encode a python boolean (True/False).\"\"\"\n    return b\"\\x08\" + name + (value and b\"\\x01\" or b\"\\x00\")", "title": ""}
{"_id": "d10251", "text": "def save_json(object, handle, indent=2):\n    \"\"\"Save object as json on CNS.\"\"\"\n    obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder)\n    handle.write(obj_json)", "title": ""}
{"_id": "d10252", "text": "def extend(self, iterable):\n        \"\"\"Extend the list by appending all the items in the given list.\"\"\"\n        return super(Collection, self).extend(\n            self._ensure_iterable_is_valid(iterable))", "title": ""}
{"_id": "d10253", "text": "def _text_to_graphiz(self, text):\n        \"\"\"create a graphviz graph from text\"\"\"\n        dot = Source(text, format='svg')\n        return dot.pipe().decode('utf-8')", "title": ""}
{"_id": "d10254", "text": "def _load_mod_ui_libraries(self, path):\n        \"\"\"\n        :param Path path:\n        \"\"\"\n        path = path / Path('mod')\n        sys.path.append(str(path))", "title": ""}
{"_id": "d10255", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d10256", "text": "def update(self, **kwargs):\n    \"\"\"Creates or updates a property for the instance for each parameter.\"\"\"\n    for key, value in kwargs.items():\n      setattr(self, key, value)", "title": ""}
{"_id": "d10257", "text": "def get_screen_resolution(self):\n        \"\"\"Return the screen resolution of the primary screen.\"\"\"\n        widget = QDesktopWidget()\n        geometry = widget.availableGeometry(widget.primaryScreen())\n        return geometry.width(), geometry.height()", "title": ""}
{"_id": "d10258", "text": "def get_adjacent_matrix(self):\n        \"\"\"Get adjacency matrix.\n\n        Returns:\n            :param adj: adjacency matrix\n            :type adj: np.ndarray\n        \"\"\"\n        edges = self.edges\n        num_edges = len(edges) + 1\n        adj = np.zeros([num_edges, num_edges])\n\n        for k in range(num_edges - 1):\n            adj[edges[k].L, edges[k].R] = 1\n            adj[edges[k].R, edges[k].L] = 1\n\n        return adj", "title": ""}
{"_id": "d10259", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d10260", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d10261", "text": "def get_last(self, table=None):\n        \"\"\"Just the last entry.\"\"\"\n        if table is None: table = self.main_table\n        query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n        return self.own_cursor.execute(query).fetchone()", "title": ""}
{"_id": "d10262", "text": "def find_model_by_table_name(name):\n    \"\"\"Find a model reference by its table name\"\"\"\n\n    for model in ModelBase._decl_class_registry.values():\n        if hasattr(model, '__table__') and model.__table__.fullname == name:\n            return model\n    return None", "title": ""}
{"_id": "d10263", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d10264", "text": "def calculate_bounding_box_from_image(im, curr_page):\n    \"\"\"This function uses a PIL routine to get the bounding box of the rendered\n    image.\"\"\"\n    xMax, y_max = im.size\n    bounding_box = im.getbbox() # note this uses ltrb convention\n    if not bounding_box:\n        #print(\"\\nWarning: could not calculate a bounding box for this page.\"\n        #      \"\\nAn empty page is assumed.\", file=sys.stderr)\n        bounding_box = (xMax/2, y_max/2, xMax/2, y_max/2)\n\n    bounding_box = list(bounding_box) # make temporarily mutable\n\n    # Compensate for reversal of the image y convention versus PDF.\n    bounding_box[1] = y_max - bounding_box[1]\n    bounding_box[3] = y_max - bounding_box[3]\n\n    full_page_box = curr_page.mediaBox # should have been set already to chosen box\n\n    # Convert pixel units to PDF's bp units.\n    convert_x = float(full_page_box.getUpperRight_x()\n                     - full_page_box.getLowerLeft_x()) / xMax\n    convert_y = float(full_page_box.getUpperRight_y()\n                     - full_page_box.getLowerLeft_y()) / y_max\n\n    # Get final box; note conversion to lower-left point, upper-right point format.\n    final_box = [\n        bounding_box[0] * convert_x,\n        bounding_box[3] * convert_y,\n        bounding_box[2] * convert_x,\n        bounding_box[1] * convert_y]\n\n    return final_box", "title": ""}
{"_id": "d10265", "text": "def na_if(series, *values):\n    \"\"\"\n    If values in a series match a specified value, change them to `np.nan`.\n\n    Args:\n        series: Series or vector, often symbolic.\n        *values: Value(s) to convert to `np.nan` in the series.\n    \"\"\"\n\n    series = pd.Series(series)\n    series[series.isin(values)] = np.nan\n    return series", "title": ""}
{"_id": "d10266", "text": "def angle(x0, y0, x1, y1):\n    \"\"\" Returns the angle between two points.\n    \"\"\"\n    return degrees(atan2(y1-y0, x1-x0))", "title": ""}
{"_id": "d10267", "text": "def server(request):\n    \"\"\"\n    Respond to requests for the server's primary web page.\n    \"\"\"\n    return direct_to_template(\n        request,\n        'server/index.html',\n        {'user_url': getViewURL(request, idPage),\n         'server_xrds_url': getViewURL(request, idpXrds),\n         })", "title": ""}
{"_id": "d10268", "text": "def ansi(color, text):\n    \"\"\"Wrap text in an ansi escape sequence\"\"\"\n    code = COLOR_CODES[color]\n    return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)", "title": ""}
{"_id": "d10269", "text": "def uncomment_line(line, prefix):\n    \"\"\"Remove prefix (and space) from line\"\"\"\n    if not prefix:\n        return line\n    if line.startswith(prefix + ' '):\n        return line[len(prefix) + 1:]\n    if line.startswith(prefix):\n        return line[len(prefix):]\n    return line", "title": ""}
{"_id": "d10270", "text": "def _set_axis_limits(self, which, lims, d, scale, reverse=False):\n        \"\"\"Private method for setting axis limits.\n\n        Sets the axis limits on each axis for an individual plot.\n\n        Args:\n            which (str): The indicator of which part of the plots\n                to adjust. This currently handles `x` and `y`.\n            lims (len-2 list of floats): The limits for the axis.\n            d (float): Amount to increment by between the limits.\n            scale (str): Scale of the axis. Either `log` or `lin`.\n            reverse (bool, optional): If True, reverse the axis tick marks. Default is False.\n\n        \"\"\"\n        setattr(self.limits, which + 'lims', lims)\n        setattr(self.limits, 'd' + which, d)\n        setattr(self.limits, which + 'scale', scale)\n\n        if reverse:\n            setattr(self.limits, 'reverse_' + which + '_axis', True)\n        return", "title": ""}
{"_id": "d10271", "text": "def __add__(self, other):\n        \"\"\"Merges two with identical columns.\"\"\"\n\n        new_table = copy.copy(self)\n        for row in other:\n            new_table.Append(row)\n\n        return new_table", "title": ""}
{"_id": "d10272", "text": "def map(cls, iterable, func, *a, **kw):\n    \"\"\"\n    Iterable-first replacement of Python's built-in `map()` function.\n    \"\"\"\n\n    return cls(func(x, *a, **kw) for x in iterable)", "title": ""}
{"_id": "d10273", "text": "def transform(self, df):\n        \"\"\"\n        Transforms a DataFrame in place. Computes all outputs of the DataFrame.\n\n        Args:\n            df (pandas.DataFrame): DataFrame to transform.\n        \"\"\"\n        for name, function in self.outputs:\n            df[name] = function(df)", "title": ""}
{"_id": "d10274", "text": "def content_type(self, data):\n        \"\"\"The Content-Type header value for this request.\"\"\"\n        self._content_type = str(data)\n        self.add_header('Content-Type', str(data))", "title": ""}
{"_id": "d10275", "text": "def peekiter(iterable):\n    \"\"\"Return first row and also iterable with same items as original\"\"\"\n    it = iter(iterable)\n    one = next(it)\n\n    def gen():\n        \"\"\"Generator that returns first and proxy other items from source\"\"\"\n        yield one\n        while True:\n            yield next(it)\n    return (one, gen())", "title": ""}
{"_id": "d10276", "text": "def monthly(date=datetime.date.today()):\n    \"\"\"\n    Take a date object and return the first day of the month.\n    \"\"\"\n    return datetime.date(date.year, date.month, 1)", "title": ""}
{"_id": "d10277", "text": "def set_default(self, section, option,\n                    default):\n        \"\"\"If the option did not exist, create a default value.\"\"\"\n        if not self.parser.has_option(section, option):\n            self.parser.set(section, option, default)", "title": ""}
{"_id": "d10278", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d10279", "text": "def set_subparsers_args(self, *args, **kwargs):\n        \"\"\"\n        Sets args and kwargs that are passed when creating a subparsers group\n        in an argparse.ArgumentParser i.e. when calling\n        argparser.ArgumentParser.add_subparsers\n        \"\"\"\n        self.subparsers_args = args\n        self.subparsers_kwargs = kwargs", "title": ""}
{"_id": "d10280", "text": "def softplus(attrs, inputs, proto_obj):\n    \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs", "title": ""}
{"_id": "d10281", "text": "def cli_parse(parser):\n    \"\"\"Add method specific options to CLI parser.\n\n    Parameters\n    ----------\n    parser : argparse object\n\n    Returns\n    ----------\n    Updated argparse object\n    \"\"\"\n    parser.add_argument('-n', '--samples', type=int, required=True,\n                        help='Number of Samples')\n    return parser", "title": ""}
{"_id": "d10282", "text": "def enable_proxy(self, host, port):\n        \"\"\"Enable a default web proxy\"\"\"\n\n        self.proxy = [host, _number(port)]\n        self.proxy_enabled = True", "title": ""}
{"_id": "d10283", "text": "def args_update(self):\n        \"\"\"Update the argparser namespace with any data from configuration file.\"\"\"\n        for key, value in self._config_data.items():\n            setattr(self._default_args, key, value)", "title": ""}
{"_id": "d10284", "text": "def with_headers(self, headers):\n        \"\"\"Sets multiple headers on the request and returns the request itself.\n\n        Keyword arguments:\n        headers -- a dict-like object which contains the headers to set.\n        \"\"\"\n        for key, value in headers.items():\n            self.with_header(key, value)\n        return self", "title": ""}
{"_id": "d10285", "text": "def find_nearest_index(arr, value):\n    \"\"\"For a given value, the function finds the nearest value\n    in the array and returns its index.\"\"\"\n    arr = np.array(arr)\n    index = (abs(arr-value)).argmin()\n    return index", "title": ""}
{"_id": "d10286", "text": "def _set_axis_limits(self, which, lims, d, scale, reverse=False):\n        \"\"\"Private method for setting axis limits.\n\n        Sets the axis limits on each axis for an individual plot.\n\n        Args:\n            which (str): The indicator of which part of the plots\n                to adjust. This currently handles `x` and `y`.\n            lims (len-2 list of floats): The limits for the axis.\n            d (float): Amount to increment by between the limits.\n            scale (str): Scale of the axis. Either `log` or `lin`.\n            reverse (bool, optional): If True, reverse the axis tick marks. Default is False.\n\n        \"\"\"\n        setattr(self.limits, which + 'lims', lims)\n        setattr(self.limits, 'd' + which, d)\n        setattr(self.limits, which + 'scale', scale)\n\n        if reverse:\n            setattr(self.limits, 'reverse_' + which + '_axis', True)\n        return", "title": ""}
{"_id": "d10287", "text": "def to_dicts(recarray):\n    \"\"\"convert record array to a dictionaries\"\"\"\n    for rec in recarray:\n        yield dict(zip(recarray.dtype.names, rec.tolist()))", "title": ""}
{"_id": "d10288", "text": "def mark(self, lineno, count=1):\n        \"\"\"Mark a given source line as executed count times.\n\n        Multiple calls to mark for the same lineno add up.\n        \"\"\"\n        self.sourcelines[lineno] = self.sourcelines.get(lineno, 0) + count", "title": ""}
{"_id": "d10289", "text": "def asMaskedArray(self):\n        \"\"\" Creates converts to a masked array\n        \"\"\"\n        return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)", "title": ""}
{"_id": "d10290", "text": "def title(msg):\n    \"\"\"Sets the title of the console window.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "title": ""}
{"_id": "d10291", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d10292", "text": "def distance_to_line(a, b, p):\n    \"\"\"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\n    \"\"\"\n    return distance(closest_point(a, b, p), p)", "title": ""}
{"_id": "d10293", "text": "def to_dicts(recarray):\n    \"\"\"convert record array to a dictionaries\"\"\"\n    for rec in recarray:\n        yield dict(zip(recarray.dtype.names, rec.tolist()))", "title": ""}
{"_id": "d10294", "text": "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig", "title": ""}
{"_id": "d10295", "text": "def _openResources(self):\n        \"\"\" Uses numpy.load to open the underlying file\n        \"\"\"\n        arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n        check_is_an_array(arr)\n        self._array = arr", "title": ""}
{"_id": "d10296", "text": "def page_guiref(arg_s=None):\n    \"\"\"Show a basic reference about the GUI Console.\"\"\"\n    from IPython.core import page\n    page.page(gui_reference, auto_html=True)", "title": ""}
{"_id": "d10297", "text": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "title": ""}
{"_id": "d10298", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d10299", "text": "def yn_prompt(msg, default=True):\n    \"\"\"\n    Prompts the user for yes or no.\n    \"\"\"\n    ret = custom_prompt(msg, [\"y\", \"n\"], \"y\" if default else \"n\")\n    if ret == \"y\":\n        return True\n    return False", "title": ""}
{"_id": "d10300", "text": "def colorize(string, color, *args, **kwargs):\n    \"\"\"\n    Implements string formatting along with color specified in colorama.Fore\n    \"\"\"\n    string = string.format(*args, **kwargs)\n    return color + string + colorama.Fore.RESET", "title": ""}
{"_id": "d10301", "text": "def toggle_pause(self):\n        \"\"\"Toggle pause mode\"\"\"\n        self.controller.playing = not self.controller.playing\n        self.music.toggle_pause()", "title": ""}
{"_id": "d10302", "text": "def get_combined_size(tiles):\n    \"\"\"Calculate combined size of tiles.\"\"\"\n    # TODO: Refactor calculating layout to avoid repetition.\n    columns, rows = calc_columns_rows(len(tiles))\n    tile_size = tiles[0].image.size\n    return (tile_size[0] * columns, tile_size[1] * rows)", "title": ""}
{"_id": "d10303", "text": "def exit(self):\n        \"\"\"Handle interactive exit.\n\n        This method calls the ask_exit callback.\"\"\"\n        if self.confirm_exit:\n            if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):\n                self.ask_exit()\n        else:\n            self.ask_exit()", "title": ""}
{"_id": "d10304", "text": "def _skip_frame(self):\n        \"\"\"Skip a single frame from the trajectory\"\"\"\n        size = self.read_size()\n        for i in range(size+1):\n            line = self._f.readline()\n            if len(line) == 0:\n                raise StopIteration", "title": ""}
{"_id": "d10305", "text": "def assert_iter(**kw):\n    \"\"\"\n    Asserts if a given values implements a valid iterable interface.\n\n    Arguments:\n        **kw (mixed): value to check if it is an iterable.\n\n    Raises:\n        TypeError: if assertion fails.\n    \"\"\"\n    for name, value in kw.items():\n        if not isiter(value):\n            raise TypeError(\n                'paco: {} must be an iterable object'.format(name))", "title": ""}
{"_id": "d10306", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d10307", "text": "def tokenize(self, s):\n        \"\"\"Return a list of token strings from the given sentence.\n\n        :param string s: The sentence string to tokenize.\n        :rtype: iter(str)\n        \"\"\"\n        return [s[start:end] for start, end in self.span_tokenize(s)]", "title": ""}
{"_id": "d10308", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d10309", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d10310", "text": "def StringIO(*args, **kwargs):\n    \"\"\"StringIO constructor shim for the async wrapper.\"\"\"\n    raw = sync_io.StringIO(*args, **kwargs)\n    return AsyncStringIOWrapper(raw)", "title": ""}
{"_id": "d10311", "text": "def unsort_vector(data, indices_of_increasing):\n    \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n    return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])", "title": ""}
{"_id": "d10312", "text": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "title": ""}
{"_id": "d10313", "text": "def insort_no_dup(lst, item):\n    \"\"\"\n    If item is not in lst, add item to list at its sorted position\n    \"\"\"\n    import bisect\n    ix = bisect.bisect_left(lst, item)\n    if lst[ix] != item: \n        lst[ix:ix] = [item]", "title": ""}
{"_id": "d10314", "text": "def _resizeColumnsToContents(self, header, data, limit_ms):\n        \"\"\"Resize all the colummns to its contents.\"\"\"\n        max_col = data.model().columnCount()\n        if limit_ms is None:\n            max_col_ms = None\n        else:\n            max_col_ms = limit_ms / max(1, max_col)\n        for col in range(max_col):\n            self._resizeColumnToContents(header, data, col, max_col_ms)", "title": ""}
{"_id": "d10315", "text": "def indent(txt, spacing=4):\n    \"\"\"\n    Indent given text using custom spacing, default is set to 4.\n    \"\"\"\n    return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))", "title": ""}
{"_id": "d10316", "text": "def _load_autoreload_magic(self):\n        \"\"\"Load %autoreload magic.\"\"\"\n        from IPython.core.getipython import get_ipython\n        try:\n            get_ipython().run_line_magic('reload_ext', 'autoreload')\n            get_ipython().run_line_magic('autoreload', '2')\n        except Exception:\n            pass", "title": ""}
{"_id": "d10317", "text": "def lspearmanr(x,y):\n    \"\"\"\nCalculates a Spearman rank-order correlation coefficient.  Taken\nfrom Heiman's Basic Statistics for the Behav. Sci (1st), p.192.\n\nUsage:   lspearmanr(x,y)      where x and y are equal-length lists\nReturns: Spearman's r, two-tailed p-value\n\"\"\"\n    TINY = 1e-30\n    if len(x) != len(y):\n        raise ValueError('Input values not paired in spearmanr.  Aborting.')\n    n = len(x)\n    rankx = rankdata(x)\n    ranky = rankdata(y)\n    dsq = sumdiffsquared(rankx,ranky)\n    rs = 1 - 6*dsq / float(n*(n**2-1))\n    t = rs * math.sqrt((n-2) / ((rs+1.0)*(1.0-rs)))\n    df = n-2\n    probrs = betai(0.5*df,0.5,df/(df+t*t))  # t already a float\n# probability values for rs are from part 2 of the spearman function in\n# Numerical Recipies, p.510.  They are close to tables, but not exact. (?)\n    return rs, probrs", "title": ""}
{"_id": "d10318", "text": "def _mean_dict(dict_list):\n    \"\"\"Compute the mean value across a list of dictionaries\n    \"\"\"\n    return {k: np.array([d[k] for d in dict_list]).mean()\n            for k in dict_list[0].keys()}", "title": ""}
{"_id": "d10319", "text": "def _split_python(python):\n    \"\"\"Split Python source into chunks.\n\n    Chunks are separated by at least two return lines. The break must not\n    be followed by a space. Also, long Python strings spanning several lines\n    are not splitted.\n\n    \"\"\"\n    python = _preprocess(python)\n    if not python:\n        return []\n    lexer = PythonSplitLexer()\n    lexer.read(python)\n    return lexer.chunks", "title": ""}
{"_id": "d10320", "text": "def average(arr):\n  \"\"\"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\n\n  \"\"\"\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))", "title": ""}
{"_id": "d10321", "text": "def split_len(s, length):\n    \"\"\"split string *s* into list of strings no longer than *length*\"\"\"\n    return [s[i:i+length] for i in range(0, len(s), length)]", "title": ""}
{"_id": "d10322", "text": "def stack_template_url(bucket_name, blueprint, endpoint):\n    \"\"\"Produces an s3 url for a given blueprint.\n\n    Args:\n        bucket_name (string): The name of the S3 bucket where the resulting\n            templates are stored.\n        blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint\n            object to create the URL to.\n        endpoint (string): The s3 endpoint used for the bucket.\n\n    Returns:\n        string: S3 URL.\n    \"\"\"\n    key_name = stack_template_key_name(blueprint)\n    return \"%s/%s/%s\" % (endpoint, bucket_name, key_name)", "title": ""}
{"_id": "d10323", "text": "def split_into_words(s):\n  \"\"\"Split a sentence into list of words.\"\"\"\n  s = re.sub(r\"\\W+\", \" \", s)\n  s = re.sub(r\"[_0-9]+\", \" \", s)\n  return s.split()", "title": ""}
{"_id": "d10324", "text": "def get_api_url(self, lambda_name, stage_name):\n        \"\"\"\n        Given a lambda_name and stage_name, return a valid API URL.\n        \"\"\"\n        api_id = self.get_api_id(lambda_name)\n        if api_id:\n            return \"https://{}.execute-api.{}.amazonaws.com/{}\".format(api_id, self.boto_session.region_name, stage_name)\n        else:\n            return None", "title": ""}
{"_id": "d10325", "text": "def create_all(self, check_first: bool = True):\n        \"\"\"Create the empty database (tables).\n\n        :param bool check_first: Defaults to True, don't issue CREATEs for tables already present\n         in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.create_all`\n        \"\"\"\n        self._metadata.create_all(self.engine, checkfirst=check_first)", "title": ""}
{"_id": "d10326", "text": "def extent(self):\n        \"\"\"Helper for matplotlib imshow\"\"\"\n        return (\n            self.intervals[1].pix1 - 0.5,\n            self.intervals[1].pix2 - 0.5,\n            self.intervals[0].pix1 - 0.5,\n            self.intervals[0].pix2 - 0.5,\n        )", "title": ""}
{"_id": "d10327", "text": "def _heapreplace_max(heap, item):\n    \"\"\"Maxheap version of a heappop followed by a heappush.\"\"\"\n    returnitem = heap[0]    # raises appropriate IndexError if heap is empty\n    heap[0] = item\n    _siftup_max(heap, 0)\n    return returnitem", "title": ""}
{"_id": "d10328", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d10329", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d10330", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d10331", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d10332", "text": "def encode_ndarray(obj):\n    \"\"\"Write a numpy array and its shape to base64 buffers\"\"\"\n    shape = obj.shape\n    if len(shape) == 1:\n        shape = (1, obj.shape[0])\n    if obj.flags.c_contiguous:\n        obj = obj.T\n    elif not obj.flags.f_contiguous:\n        obj = asfortranarray(obj.T)\n    else:\n        obj = obj.T\n    try:\n        data = obj.astype(float64).tobytes()\n    except AttributeError:\n        data = obj.astype(float64).tostring()\n\n    data = base64.b64encode(data).decode('utf-8')\n    return data, shape", "title": ""}
{"_id": "d10333", "text": "def stackplot(marray, seconds=None, start_time=None, ylabels=None):\n    \"\"\"\n    will plot a stack of traces one above the other assuming\n    marray.shape = numRows, numSamples\n    \"\"\"\n    tarray = np.transpose(marray)\n    stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)\n    plt.show()", "title": ""}
{"_id": "d10334", "text": "def apply_caching(response):\n    \"\"\"Applies the configuration's http headers to all responses\"\"\"\n    for k, v in config.get('HTTP_HEADERS').items():\n        response.headers[k] = v\n    return response", "title": ""}
{"_id": "d10335", "text": "def slugify_filename(filename):\n    \"\"\" Slugify filename \"\"\"\n    name, ext = os.path.splitext(filename)\n    slugified = get_slugified_name(name)\n    return slugified + ext", "title": ""}
{"_id": "d10336", "text": "def to_bytes(self):\n\t\t\"\"\"Convert the entire image to bytes.\n\t\t\n\t\t:rtype: bytes\n\t\t\"\"\"\n\t\tchunks = [PNG_SIGN]\n\t\tchunks.extend(c[1] for c in self.chunks)\n\t\treturn b\"\".join(chunks)", "title": ""}
{"_id": "d10337", "text": "async def _send_plain_text(self, request: Request, stack: Stack):\n        \"\"\"\n        Sends plain text using `_send_text()`.\n        \"\"\"\n\n        await self._send_text(request, stack, None)", "title": ""}
{"_id": "d10338", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d10339", "text": "def circstd(dts, axis=2):\n    \"\"\"Circular standard deviation\"\"\"\n    R = np.abs(np.exp(1.0j * dts).mean(axis=axis))\n    return np.sqrt(-2.0 * np.log(R))", "title": ""}
{"_id": "d10340", "text": "def _get_bokeh_html(self, chart_obj):\n        \"\"\"\n        Get the html for a Bokeh chart\n        \"\"\"\n        global bokeh_renderer\n        try:\n            renderer = bokeh_renderer\n            p = renderer.get_plot(chart_obj).state\n            script, div = components(p)\n            return script + \"\\n\" + div\n\n        except Exception as e:\n            self.err(e, self._get_bokeh_html,\n                     \"Can not get html from the Bokeh rendering engine\")", "title": ""}
{"_id": "d10341", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d10342", "text": "def is_static(*p):\n    \"\"\" A static value (does not change at runtime)\n    which is known at compile time\n    \"\"\"\n    return all(is_CONST(x) or\n               is_number(x) or\n               is_const(x)\n               for x in p)", "title": ""}
{"_id": "d10343", "text": "def _check_and_convert_bools(self):\n        \"\"\"Replace boolean variables by the characters 'F'/'T'\n        \"\"\"\n        replacements = {\n            True: 'T',\n            False: 'F',\n        }\n\n        for key in self.bools:\n            if isinstance(self[key], bool):\n                self[key] = replacements[self[key]]", "title": ""}
{"_id": "d10344", "text": "def describe_unique_1d(series):\n    \"\"\"Compute summary statistics of a unique (`S_TYPE_UNIQUE`) variable (a Series).\n\n    Parameters\n    ----------\n    series : Series\n        The variable to describe.\n\n    Returns\n    -------\n    Series\n        The description of the variable as a Series with index being stats keys.\n    \"\"\"\n    return pd.Series([base.S_TYPE_UNIQUE], index=['type'], name=series.name)", "title": ""}
{"_id": "d10345", "text": "def needs_update(self, cache_key):\n    \"\"\"Check if the given cached item is invalid.\n\n    :param cache_key: A CacheKey object (as returned by CacheKeyGenerator.key_for().\n    :returns: True if the cached version of the item is out of date.\n    \"\"\"\n    if not self.cacheable(cache_key):\n      # An uncacheable CacheKey is always out of date.\n      return True\n\n    return self._read_sha(cache_key) != cache_key.hash", "title": ""}
{"_id": "d10346", "text": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "title": ""}
{"_id": "d10347", "text": "def delete_item(self, item):\n        \"\"\"Delete an object in DynamoDB.\n\n        :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.delete_item`.\n        :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.\n        \"\"\"\n        try:\n            self.dynamodb_client.delete_item(**item)\n        except botocore.exceptions.ClientError as error:\n            handle_constraint_violation(error)", "title": ""}
{"_id": "d10348", "text": "def polygon_from_points(points):\n    \"\"\"\n    Constructs a numpy-compatible polygon from a page representation.\n    \"\"\"\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", "title": ""}
{"_id": "d10349", "text": "def sync_s3(self):\n        \"\"\"Walk the media/static directories and syncs files to S3\"\"\"\n        bucket, key = self.open_s3()\n        for directory in self.DIRECTORIES:\n            for root, dirs, files in os.walk(directory):\n                self.upload_s3((bucket, key, self.AWS_BUCKET_NAME, directory), root, files, dirs)", "title": ""}
{"_id": "d10350", "text": "def set_user_password(environment, parameter, password):\n    \"\"\"\n    Sets a user's password in the keyring storage\n    \"\"\"\n    username = '%s:%s' % (environment, parameter)\n    return password_set(username, password)", "title": ""}
{"_id": "d10351", "text": "def start():\n    \"\"\"Starts the web server.\"\"\"\n    global app\n    bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n               debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n               quiet=conf.WebQuiet)", "title": ""}
{"_id": "d10352", "text": "def __str__(self):\n        \"\"\"Executes self.function to convert LazyString instance to a real\n        str.\"\"\"\n        if not hasattr(self, '_str'):\n            self._str=self.function(*self.args, **self.kwargs)\n        return self._str", "title": ""}
{"_id": "d10353", "text": "def attr_cache_clear(self):\n        node = extract_node(\"\"\"def cache_clear(self): pass\"\"\")\n        return BoundMethod(proxy=node, bound=self._instance.parent.scope())", "title": ""}
{"_id": "d10354", "text": "def loads(s, model=None, parser=None):\n    \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n    with StringIO(s) as f:\n        return load(f, model=model, parser=parser)", "title": ""}
{"_id": "d10355", "text": "def __call__(self, obj, *arg, **kw):\n        \"\"\"\n        Call the unbound method.\n        \n        We essentially build a bound method and call that. This ensures that\n        the code for managing observers is invoked in the same was as it would\n        be for a bound method.\n        \"\"\"\n        bound_method = self._manager.__get__(obj, obj.__class__)\n        return bound_method(*arg, **kw)", "title": ""}
{"_id": "d10356", "text": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    l = [v.strip() for v in value.split(',')]\n    if len(l) == 1:\n        l = value.split()\n    return l", "title": ""}
{"_id": "d10357", "text": "def xml_str_to_dict(s):\n    \"\"\" Transforms an XML string it to python-zimbra dict format\n\n    For format, see:\n      https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n    :param: a string, containing XML\n    :returns: a dict, with python-zimbra format\n    \"\"\"\n    xml = minidom.parseString(s)\n    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)", "title": ""}
{"_id": "d10358", "text": "def WriteManyToPath(objs, filepath):\n  \"\"\"Serializes and writes given Python objects to a multi-document YAML file.\n\n  Args:\n    objs: An iterable of Python objects to serialize.\n    filepath: A path to the file into which the object is to be written.\n  \"\"\"\n  with io.open(filepath, mode=\"w\", encoding=\"utf-8\") as filedesc:\n    WriteManyToFile(objs, filedesc)", "title": ""}
{"_id": "d10359", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d10360", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d10361", "text": "def _accumulate(sequence, func):\n    \"\"\"\n    Python2 accumulate implementation taken from\n    https://docs.python.org/3/library/itertools.html#itertools.accumulate\n    \"\"\"\n    iterator = iter(sequence)\n    total = next(iterator)\n    yield total\n    for element in iterator:\n        total = func(total, element)\n        yield total", "title": ""}
{"_id": "d10362", "text": "def to_bytes(self):\n\t\t\"\"\"Convert the entire image to bytes.\n\t\t\n\t\t:rtype: bytes\n\t\t\"\"\"\n\t\tchunks = [PNG_SIGN]\n\t\tchunks.extend(c[1] for c in self.chunks)\n\t\treturn b\"\".join(chunks)", "title": ""}
{"_id": "d10363", "text": "def xeval(source, optimize=True):\n    \"\"\"Compiles to native Python bytecode and runs program, returning the\n    topmost value on the stack.\n\n    Args:\n        optimize: Whether to optimize the code after parsing it.\n\n    Returns:\n        None: If the stack is empty\n        obj: If the stack contains a single value\n        [obj, obj, ...]: If the stack contains many values\n    \"\"\"\n    native = xcompile(source, optimize=optimize)\n    return native()", "title": ""}
{"_id": "d10364", "text": "def _accumulate(sequence, func):\n    \"\"\"\n    Python2 accumulate implementation taken from\n    https://docs.python.org/3/library/itertools.html#itertools.accumulate\n    \"\"\"\n    iterator = iter(sequence)\n    total = next(iterator)\n    yield total\n    for element in iterator:\n        total = func(total, element)\n        yield total", "title": ""}
{"_id": "d10365", "text": "def _convert_to_array(array_like, dtype):\n        \"\"\"\n        Convert Matrix attributes which are array-like or buffer to array.\n        \"\"\"\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)", "title": ""}
{"_id": "d10366", "text": "def add_swagger(app, json_route, html_route):\n    \"\"\"\n    a convenience method for both adding a swagger.json route,\n    as well as adding a page showing the html documentation\n    \"\"\"\n    app.router.add_route('GET', json_route, create_swagger_json_handler(app))\n    add_swagger_api_route(app, html_route, json_route)", "title": ""}
{"_id": "d10367", "text": "def get_bound(pts):\n    \"\"\"Compute a minimal rectangle that covers all the points.\"\"\"\n    (x0, y0, x1, y1) = (INF, INF, -INF, -INF)\n    for (x, y) in pts:\n        x0 = min(x0, x)\n        y0 = min(y0, y)\n        x1 = max(x1, x)\n        y1 = max(y1, y)\n    return (x0, y0, x1, y1)", "title": ""}
{"_id": "d10368", "text": "def lazy_reverse_binmap(f, xs):\n    \"\"\"\n    Same as lazy_binmap, except the parameters are flipped for the binary function\n    \"\"\"\n    return (f(y, x) for x, y in zip(xs, xs[1:]))", "title": ""}
{"_id": "d10369", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d10370", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d10371", "text": "def qrot(vector, quaternion):\n    \"\"\"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\n\n    \"\"\"\n    t = 2 * np.cross(quaternion[1:], vector)\n    v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t)\n    return v_rot", "title": ""}
{"_id": "d10372", "text": "def _render_table(data, fields=None):\n  \"\"\" Helper to render a list of dictionaries as an HTML display object. \"\"\"\n  return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))", "title": ""}
{"_id": "d10373", "text": "def to_pascal_case(s):\n    \"\"\"Transform underscore separated string to pascal case\n\n    \"\"\"\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())", "title": ""}
{"_id": "d10374", "text": "def hkm_fc(fdata, Nmax, m, s):\n    \"\"\" Assume fdata has even rows\"\"\"\n\n    f = fdata[:, m]\n    L1 = f.size\n    MM = int(L1 / 2)\n    Q = s.size\n\n    ff = np.zeros(Q, dtype=np.complex128)\n    for n in xrange(MM, L1):\n        ff[n] = f[n - MM]\n\n    for n in xrange(0, MM):\n        ff[n] = f[n + MM]\n\n    # For larger problems, this speeds things up pretty good.\n    F = np.fft.fft(ff)\n    S = np.fft.fft(s)\n    out = 4 * np.pi * np.fft.ifft(F * S)\n\n    return out[0:Nmax + 1]", "title": ""}
{"_id": "d10375", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d10376", "text": "def get_server(address=None):\n        \"\"\"Return an SMTP servername guess from outgoing email address.\"\"\"\n        if address:\n            domain = address.split(\"@\")[1]\n            try:\n                return SMTP_SERVERS[domain]\n            except KeyError:\n                return (\"smtp.\" + domain, 465)\n        return (None, None)", "title": ""}
{"_id": "d10377", "text": "def close(*args, **kwargs):\n    r\"\"\"Close last created figure, alias to ``plt.close()``.\"\"\"\n    _, plt, _ = _import_plt()\n    plt.close(*args, **kwargs)", "title": ""}
{"_id": "d10378", "text": "def tf2():\n  \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n  Returns:\n    The root module of a TF-2.0 API, if available.\n\n  Raises:\n    ImportError: if a TF-2.0 API is not available.\n  \"\"\"\n  # Import the `tf` compat API from this file and check if it's already TF 2.0.\n  if tf.__version__.startswith('2.'):\n    return tf\n  elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n    # As a fallback, try `tensorflow.compat.v2` if it's defined.\n    return tf.compat.v2\n  raise ImportError('cannot import tensorflow 2.0 API')", "title": ""}
{"_id": "d10379", "text": "def call_out(command):\n  \"\"\"\n  Run the given command (with shell=False) and return a tuple of\n  (int returncode, str output). Strip the output of enclosing whitespace.\n  \"\"\"\n  # start external command process\n  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n  # get outputs\n  out, _ = p.communicate()\n\n  return p.returncode, out.strip()", "title": ""}
{"_id": "d10380", "text": "def _int64_feature(value):\n  \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))", "title": ""}
{"_id": "d10381", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d10382", "text": "def timeout_thread_handler(timeout, stop_event):\n    \"\"\"A background thread to kill the process if it takes too long.\n\n    Args:\n        timeout (float): The number of seconds to wait before killing\n            the process.\n        stop_event (Event): An optional event to cleanly stop the background\n            thread if required during testing.\n    \"\"\"\n\n    stop_happened = stop_event.wait(timeout)\n    if stop_happened is False:\n        print(\"Killing program due to %f second timeout\" % timeout)\n\n    os._exit(2)", "title": ""}
{"_id": "d10383", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d10384", "text": "def reraise(error):\n    \"\"\"Re-raises the error that was processed by prepare_for_reraise earlier.\"\"\"\n    if hasattr(error, \"_type_\"):\n        six.reraise(type(error), error, error._traceback)\n    raise error", "title": ""}
{"_id": "d10385", "text": "def signal_handler(signal_name, frame):\n    \"\"\"Quit signal handler.\"\"\"\n    sys.stdout.flush()\n    print(\"\\nSIGINT in frame signal received. Quitting...\")\n    sys.stdout.flush()\n    sys.exit(0)", "title": ""}
{"_id": "d10386", "text": "def filter(self, func):\n        \"\"\"Returns a SndRcv list filtered by a truth function\"\"\"\n        return self.__class__( [ i for i in self.res if func(*i) ], name='filtered %s'%self.listname)", "title": ""}
{"_id": "d10387", "text": "def is_SYMBOL(token, *symbols):\n    \"\"\" Returns True if ALL of the given argument are AST nodes\n    of the given token (e.g. 'BINARY')\n    \"\"\"\n    from symbols.symbol_ import Symbol\n    assert all(isinstance(x, Symbol) for x in symbols)\n    for sym in symbols:\n        if sym.token != token:\n            return False\n\n    return True", "title": ""}
{"_id": "d10388", "text": "def format_float(value): # not used\n    \"\"\"Modified form of the 'g' format specifier.\n    \"\"\"\n    string = \"{:g}\".format(value).replace(\"e+\", \"e\")\n    string = re.sub(\"e(-?)0*(\\d+)\", r\"e\\1\\2\", string)\n    return string", "title": ""}
{"_id": "d10389", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d10390", "text": "def norm_slash(name):\n    \"\"\"Normalize path slashes.\"\"\"\n\n    if isinstance(name, str):\n        return name.replace('/', \"\\\\\") if not is_case_sensitive() else name\n    else:\n        return name.replace(b'/', b\"\\\\\") if not is_case_sensitive() else name", "title": ""}
{"_id": "d10391", "text": "def wrap(text, indent='    '):\n    \"\"\"Wrap text to terminal width with default indentation\"\"\"\n    wrapper = textwrap.TextWrapper(\n        width=int(os.environ.get('COLUMNS', 80)),\n        initial_indent=indent,\n        subsequent_indent=indent\n    )\n    return '\\n'.join(wrapper.wrap(text))", "title": ""}
{"_id": "d10392", "text": "def _check_and_convert_bools(self):\n        \"\"\"Replace boolean variables by the characters 'F'/'T'\n        \"\"\"\n        replacements = {\n            True: 'T',\n            False: 'F',\n        }\n\n        for key in self.bools:\n            if isinstance(self[key], bool):\n                self[key] = replacements[self[key]]", "title": ""}
{"_id": "d10393", "text": "def get_feature_order(dataset, features):\n    \"\"\" Returns a list with the order that features requested appear in\n    dataset \"\"\"\n    all_features = dataset.get_feature_names()\n\n    i = [all_features.index(f) for f in features]\n\n    return i", "title": ""}
{"_id": "d10394", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d10395", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d10396", "text": "def date_to_timestamp(date):\n    \"\"\"\n        date to unix timestamp in milliseconds\n    \"\"\"\n    date_tuple = date.timetuple()\n    timestamp = calendar.timegm(date_tuple) * 1000\n    return timestamp", "title": ""}
{"_id": "d10397", "text": "def _update_plot(self, _):\n        \"\"\"Callback to redraw the plot to reflect the new parameter values.\"\"\"\n        # Since all sliders call this same callback without saying who they are\n        # I need to update the values for all parameters. This can be\n        # circumvented by creating a seperate callback function for each\n        # parameter.\n        for param in self.model.params:\n            param.value = self._sliders[param].val\n        for indep_var, dep_var in self._projections:\n            self._update_specific_plot(indep_var, dep_var)", "title": ""}
{"_id": "d10398", "text": "def _maybe_pandas_data(data, feature_names, feature_types):\n    \"\"\" Extract internal data from pd.DataFrame for DMatrix data \"\"\"\n\n    if not isinstance(data, DataFrame):\n        return data, feature_names, feature_types\n\n    data_dtypes = data.dtypes\n    if not all(dtype.name in PANDAS_DTYPE_MAPPER for dtype in data_dtypes):\n        bad_fields = [data.columns[i] for i, dtype in\n                      enumerate(data_dtypes) if dtype.name not in PANDAS_DTYPE_MAPPER]\n\n        msg = \"\"\"DataFrame.dtypes for data must be int, float or bool.\n                Did not expect the data types in fields \"\"\"\n        raise ValueError(msg + ', '.join(bad_fields))\n\n    if feature_names is None:\n        if isinstance(data.columns, MultiIndex):\n            feature_names = [\n                ' '.join([str(x) for x in i])\n                for i in data.columns\n            ]\n        else:\n            feature_names = data.columns.format()\n\n    if feature_types is None:\n        feature_types = [PANDAS_DTYPE_MAPPER[dtype.name] for dtype in data_dtypes]\n\n    data = data.values.astype('float')\n\n    return data, feature_names, feature_types", "title": ""}
{"_id": "d10399", "text": "def _update_index_on_df(df, index_names):\n    \"\"\"Helper function to restore index information after collection. Doesn't\n    use self so we can serialize this.\"\"\"\n    if index_names:\n        df = df.set_index(index_names)\n        # Remove names from unnamed indexes\n        index_names = _denormalize_index_names(index_names)\n        df.index.names = index_names\n    return df", "title": ""}
{"_id": "d10400", "text": "def impute_data(self,x):\n        \"\"\"Imputes data set containing Nan values\"\"\"\n        imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n        return imp.fit_transform(x)", "title": ""}
{"_id": "d10401", "text": "def convert_from_missing_indexer_tuple(indexer, axes):\n    \"\"\"\n    create a filtered indexer that doesn't have any missing indexers\n    \"\"\"\n\n    def get_indexer(_i, _idx):\n        return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else\n                _idx)\n\n    return tuple(get_indexer(_i, _idx) for _i, _idx in enumerate(indexer))", "title": ""}
{"_id": "d10402", "text": "def _is_root():\n    \"\"\"Checks if the user is rooted.\"\"\"\n    import os\n    import ctypes\n    try:\n        return os.geteuid() == 0\n    except AttributeError:\n        return ctypes.windll.shell32.IsUserAnAdmin() != 0\n    return False", "title": ""}
{"_id": "d10403", "text": "def scopes_as(self, new_scopes):\n        \"\"\"Replace my :attr:`scopes` for the duration of the with block.\n\n        My global scope is not replaced.\n\n        Args:\n            new_scopes (list of dict-likes): The new :attr:`scopes` to use.\n        \"\"\"\n        old_scopes, self.scopes = self.scopes, new_scopes\n        yield\n        self.scopes = old_scopes", "title": ""}
{"_id": "d10404", "text": "def get_mnist(data_type=\"train\", location=\"/tmp/mnist\"):\n    \"\"\"\n    Get mnist dataset with features and label as ndarray.\n    Data would be downloaded automatically if it doesn't present at the specific location.\n\n    :param data_type: \"train\" for training data and \"test\" for testing data.\n    :param location: Location to store mnist dataset.\n    :return: (features: ndarray, label: ndarray)\n    \"\"\"\n    X, Y = mnist.read_data_sets(location, data_type)\n    return X, Y + 1", "title": ""}
{"_id": "d10405", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d10406", "text": "def convert_str_to_datetime(df, *, column: str, format: str):\n    \"\"\"\n    Convert string column into datetime column\n\n    ---\n\n    ### Parameters\n\n    *mandatory :*\n    - `column` (*str*): name of the column to format\n    - `format` (*str*): current format of the values (see [available formats](\n    https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))\n    \"\"\"\n    df[column] = pd.to_datetime(df[column], format=format)\n    return df", "title": ""}
{"_id": "d10407", "text": "def is_datetime_like(dtype):\n    \"\"\"Check if a dtype is a subclass of the numpy datetime types\n    \"\"\"\n    return (np.issubdtype(dtype, np.datetime64) or\n            np.issubdtype(dtype, np.timedelta64))", "title": ""}
{"_id": "d10408", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d10409", "text": "def any_of(value, *args):\n    \"\"\" At least one of the items in value should match \"\"\"\n\n    if len(args):\n        value = (value,) + args\n\n    return ExpectationAny(value)", "title": ""}
{"_id": "d10410", "text": "def dict_to_querystring(dictionary):\n    \"\"\"Converts a dict to a querystring suitable to be appended to a URL.\"\"\"\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]", "title": ""}
{"_id": "d10411", "text": "def check_create_folder(filename):\n    \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n    os.makedirs(os.path.dirname(filename), exist_ok=True)", "title": ""}
{"_id": "d10412", "text": "def round_float(f, digits, rounding=ROUND_HALF_UP):\n    \"\"\"\n    Accurate float rounding from http://stackoverflow.com/a/15398691.\n    \"\"\"\n    return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits),\n                                    rounding=rounding)", "title": ""}
{"_id": "d10413", "text": "def raise_for_not_ok_status(response):\n    \"\"\"\n    Raises a `requests.exceptions.HTTPError` if the response has a non-200\n    status code.\n    \"\"\"\n    if response.code != OK:\n        raise HTTPError('Non-200 response code (%s) for url: %s' % (\n            response.code, uridecode(response.request.absoluteURI)))\n\n    return response", "title": ""}
{"_id": "d10414", "text": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    l = [v.strip() for v in value.split(',')]\n    if len(l) == 1:\n        l = value.split()\n    return l", "title": ""}
{"_id": "d10415", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d10416", "text": "def serialize_json_string(self, value):\n        \"\"\"\n        Tries to load an encoded json string back into an object\n        :param json_string:\n        :return:\n        \"\"\"\n\n        # Check if the value might be a json string\n        if not isinstance(value, six.string_types):\n            return value\n\n        # Make sure it starts with a brace\n        if not value.startswith('{') or value.startswith('['):\n            return value\n\n        # Try to load the string\n        try:\n            return json.loads(value)\n        except:\n            return value", "title": ""}
{"_id": "d10417", "text": "def is_http_running_on(port):\n  \"\"\" Check if an http server runs on a given port.\n\n  Args:\n    The port to check.\n  Returns:\n    True if it is used by an http server. False otherwise.\n  \"\"\"\n  try:\n    conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n    conn.connect()\n    conn.close()\n    return True\n  except Exception:\n    return False", "title": ""}
{"_id": "d10418", "text": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    l = [v.strip() for v in value.split(',')]\n    if len(l) == 1:\n        l = value.split()\n    return l", "title": ""}
{"_id": "d10419", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d10420", "text": "def multidict_to_dict(d):\n    \"\"\"\n    Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with\n    list values\n    :param d: a MultiDict or MultiValueDict instance\n    :return: a dict instance\n    \"\"\"\n    return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))", "title": ""}
{"_id": "d10421", "text": "def is_file(path):\n    \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n    try:\n        return path.expanduser().absolute().is_file()\n    except AttributeError:\n        return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))", "title": ""}
{"_id": "d10422", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d10423", "text": "def is_delimiter(line):\n    \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n    return bool(line) and line[0] in punctuation and line[0]*len(line) == line", "title": ""}
{"_id": "d10424", "text": "def visit_Str(self, node):\n        \"\"\" Set the pythonic string type. \"\"\"\n        self.result[node] = self.builder.NamedType(pytype_to_ctype(str))", "title": ""}
{"_id": "d10425", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d10426", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d10427", "text": "def are_in_interval(s, l, r, border = 'included'):\n        \"\"\"\n        Checks whether all number in the sequence s lie inside the interval formed by\n        l and r.\n        \"\"\"\n        return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s])", "title": ""}
{"_id": "d10428", "text": "def peak_memory_usage():\n    \"\"\"Return peak memory usage in MB\"\"\"\n    if sys.platform.startswith('win'):\n        p = psutil.Process()\n        return p.memory_info().peak_wset / 1024 / 1024\n\n    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n    factor_mb = 1 / 1024\n    if sys.platform == 'darwin':\n        factor_mb = 1 / (1024 * 1024)\n    return mem * factor_mb", "title": ""}
{"_id": "d10429", "text": "def contains_case_insensitive(adict, akey):\n    \"\"\"Check if key is in adict. The search is case insensitive.\"\"\"\n    for key in adict:\n        if key.lower() == akey.lower():\n            return True\n    return False", "title": ""}
{"_id": "d10430", "text": "def uniquify_list(L):\n    \"\"\"Same order unique list using only a list compression.\"\"\"\n    return [e for i, e in enumerate(L) if L.index(e) == i]", "title": ""}
{"_id": "d10431", "text": "def is_complex(dtype):\n  \"\"\"Returns whether this is a complex floating point type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_complex'):\n    return dtype.is_complex\n  return np.issubdtype(np.dtype(dtype), np.complex)", "title": ""}
{"_id": "d10432", "text": "def datetime_to_timestamp(dt):\n    \"\"\"Convert a UTC datetime to a Unix timestamp\"\"\"\n    delta = dt - datetime.utcfromtimestamp(0)\n    return delta.seconds + delta.days * 24 * 3600", "title": ""}
{"_id": "d10433", "text": "def exists(self):\n        \"\"\"\n        Performs an existence check on the remote database.\n\n        :returns: Boolean True if the database exists, False otherwise\n        \"\"\"\n        resp = self.r_session.head(self.database_url)\n        if resp.status_code not in [200, 404]:\n            resp.raise_for_status()\n\n        return resp.status_code == 200", "title": ""}
{"_id": "d10434", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d10435", "text": "def is_readable_dir(path):\n  \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n  return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d10436", "text": "def update_index(index):\n    \"\"\"Re-index every document in a named index.\"\"\"\n    logger.info(\"Updating search index: '%s'\", index)\n    client = get_client()\n    responses = []\n    for model in get_index_models(index):\n        logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n        objects = model.objects.get_search_queryset(index).iterator()\n        actions = bulk_actions(objects, index=index, action=\"index\")\n        response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n        responses.append(response)\n    return responses", "title": ""}
{"_id": "d10437", "text": "def is_valid_email(email):\n    \"\"\"\n    Check if email is valid\n    \"\"\"\n    pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n    return bool(pattern.match(email))", "title": ""}
{"_id": "d10438", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d10439", "text": "def readable(path):\n    \"\"\"Test whether a path exists and is readable.  Returns None for\n    broken symbolic links or a failing stat() and False if\n    the file exists but does not have read permission. True is returned\n    if the file is readable.\"\"\"\n    try:\n        st = os.stat(path)\n        return 0 != st.st_mode & READABLE_MASK\n    except os.error:\n        return None\n    return True", "title": ""}
{"_id": "d10440", "text": "def Timestamp(year, month, day, hour, minute, second):\n    \"\"\"Constructs an object holding a datetime/timestamp value.\"\"\"\n    return datetime.datetime(year, month, day, hour, minute, second)", "title": ""}
{"_id": "d10441", "text": "def is_collection(obj):\n    \"\"\"Tests if an object is a collection.\"\"\"\n\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n\n    if isinstance(obj, basestring):\n        val = False\n\n    return val", "title": ""}
{"_id": "d10442", "text": "def xmltreefromfile(filename):\n    \"\"\"Internal function to read an XML file\"\"\"\n    try:\n        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n    except TypeError:\n        return ElementTree.parse(filename, ElementTree.XMLParser())", "title": ""}
{"_id": "d10443", "text": "def is_file(path):\n    \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n    try:\n        return path.expanduser().absolute().is_file()\n    except AttributeError:\n        return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))", "title": ""}
{"_id": "d10444", "text": "def h5ToDict(h5, readH5pyDataset=True):\n    \"\"\" Read a hdf5 file into a dictionary \"\"\"\n    h = h5py.File(h5, \"r\")\n    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n    if readH5pyDataset: h.close()\n    return ret", "title": ""}
{"_id": "d10445", "text": "def information(filename):\n    \"\"\"Returns the file exif\"\"\"\n    check_if_this_file_exist(filename)\n    filename = os.path.abspath(filename)\n    result = get_json(filename)\n    result = result[0]\n    return result", "title": ""}
{"_id": "d10446", "text": "def imagemagick(color_count, img, magick_command):\n    \"\"\"Call Imagemagick to generate a scheme.\"\"\"\n    flags = [\"-resize\", \"25%\", \"-colors\", str(color_count),\n             \"-unique-colors\", \"txt:-\"]\n    img += \"[0]\"\n\n    return subprocess.check_output([*magick_command, img, *flags]).splitlines()", "title": ""}
{"_id": "d10447", "text": "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n    \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n    return maybe_list and any(is_multiline(item) for item in maybe_list)", "title": ""}
{"_id": "d10448", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d10449", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d10450", "text": "def one_hot_encoding(input_tensor, num_labels):\n    \"\"\" One-hot encode labels from input \"\"\"\n    xview = input_tensor.view(-1, 1).to(torch.long)\n\n    onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)\n    onehot.scatter_(1, xview, 1)\n    return onehot.view(list(input_tensor.shape) + [-1])", "title": ""}
{"_id": "d10451", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d10452", "text": "def delete(args):\n    \"\"\"\n    Delete a river by name\n    \"\"\"\n    m = RiverManager(args.hosts)\n    m.delete(args.name)", "title": ""}
{"_id": "d10453", "text": "def exists(self):\n    \"\"\" Checks if the item exists. \"\"\"\n    try:\n      return self.metadata is not None\n    except datalab.utils.RequestException:\n      return False\n    except Exception as e:\n      raise e", "title": ""}
{"_id": "d10454", "text": "def generate(env):\n    \"\"\"Add Builders and construction variables for SGI MIPS C++ to an Environment.\"\"\"\n\n    cplusplus.generate(env)\n\n    env['CXX']         = 'CC'\n    env['CXXFLAGS']    = SCons.Util.CLVar('-LANG:std')\n    env['SHCXX']       = '$CXX'\n    env['SHOBJSUFFIX'] = '.o'\n    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1", "title": ""}
{"_id": "d10455", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d10456", "text": "def is_serializable(obj):\n    \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool\n    \"\"\"\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')", "title": ""}
{"_id": "d10457", "text": "def camel_case(self, snake_case):\n        \"\"\" Convert snake case to camel case \"\"\"\n        components = snake_case.split('_')\n        return components[0] + \"\".join(x.title() for x in components[1:])", "title": ""}
{"_id": "d10458", "text": "def is_sequence(obj):\n    \"\"\"Check if `obj` is a sequence, but not a string or bytes.\"\"\"\n    return isinstance(obj, Sequence) and not (\n        isinstance(obj, str) or BinaryClass.is_valid_type(obj))", "title": ""}
{"_id": "d10459", "text": "def is_valid_file(parser,arg):\n\t\"\"\"verify the validity of the given file. Never trust the End-User\"\"\"\n\tif not os.path.exists(arg):\n       \t\tparser.error(\"File %s not found\"%arg)\n\telse:\n\t       \treturn arg", "title": ""}
{"_id": "d10460", "text": "def is_http_running_on(port):\n  \"\"\" Check if an http server runs on a given port.\n\n  Args:\n    The port to check.\n  Returns:\n    True if it is used by an http server. False otherwise.\n  \"\"\"\n  try:\n    conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n    conn.connect()\n    conn.close()\n    return True\n  except Exception:\n    return False", "title": ""}
{"_id": "d10461", "text": "def is_nullable_list(val, vtype):\n    \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n    return (isinstance(val, list) and\n            any(isinstance(v, vtype) for v in val) and\n            all((isinstance(v, vtype) or v is None) for v in val))", "title": ""}
{"_id": "d10462", "text": "def __validate_email(self, email):\n        \"\"\"Checks if a string looks like an email address\"\"\"\n\n        e = re.match(self.EMAIL_ADDRESS_REGEX, email, re.UNICODE)\n        if e:\n            return email\n        else:\n            error = \"Invalid email address: \" + str(email)\n            msg = self.GRIMOIRELAB_INVALID_FORMAT % {'error': error}\n            raise InvalidFormatError(cause=msg)", "title": ""}
{"_id": "d10463", "text": "def isCommaList(inputFilelist):\n    \"\"\"Return True if the input is a comma separated list of names.\"\"\"\n    if isinstance(inputFilelist, int) or isinstance(inputFilelist, np.int32):\n        ilist = str(inputFilelist)\n    else:\n        ilist = inputFilelist\n    if \",\" in ilist:\n        return True\n    return False", "title": ""}
{"_id": "d10464", "text": "def conv2d(x_input, w_matrix):\n    \"\"\"conv2d returns a 2d convolution layer with full stride.\"\"\"\n    return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')", "title": ""}
{"_id": "d10465", "text": "def is_float(value):\n    \"\"\"must be a float\"\"\"\n    return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "title": ""}
{"_id": "d10466", "text": "def _run_once(self):\n    \"\"\"Run once, should be called only from loop()\"\"\"\n    try:\n      self.do_wait()\n      self._execute_wakeup_tasks()\n      self._trigger_timers()\n    except Exception as e:\n      Log.error(\"Error occured during _run_once(): \" + str(e))\n      Log.error(traceback.format_exc())\n      self.should_exit = True", "title": ""}
{"_id": "d10467", "text": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "title": ""}
{"_id": "d10468", "text": "def _check_model(obj, models=None):\n    \"\"\"Checks object if it's a peewee model and unique.\"\"\"\n    return isinstance(obj, type) and issubclass(obj, pw.Model) and hasattr(obj, '_meta')", "title": ""}
{"_id": "d10469", "text": "def get_category(self):\n        \"\"\"Get the category of the item.\n\n        :return: the category of the item.\n        :returntype: `unicode`\"\"\"\n        var = self.xmlnode.prop(\"category\")\n        if not var:\n            var = \"?\"\n        return var.decode(\"utf-8\")", "title": ""}
{"_id": "d10470", "text": "def check(text):\n    \"\"\"Check the text.\"\"\"\n    err = \"misc.currency\"\n    msg = u\"Incorrect use of symbols in {}.\"\n\n    symbols = [\n        \"\\$[\\d]* ?(?:dollars|usd|us dollars)\"\n    ]\n\n    return existence_check(text, symbols, err, msg)", "title": ""}
{"_id": "d10471", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d10472", "text": "def watched_extension(extension):\n    \"\"\"Return True if the given extension is one of the watched extensions\"\"\"\n    for ext in hamlpy.VALID_EXTENSIONS:\n        if extension.endswith('.' + ext):\n            return True\n    return False", "title": ""}
{"_id": "d10473", "text": "def issuperset(self, other):\n        \"\"\"Report whether this RangeSet contains another set.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issuperset(self, other)", "title": ""}
{"_id": "d10474", "text": "def contains_geometric_info(var):\n    \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)", "title": ""}
{"_id": "d10475", "text": "def _get_example_length(example):\n  \"\"\"Returns the maximum length between the example inputs and targets.\"\"\"\n  length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0])\n  return length", "title": ""}
{"_id": "d10476", "text": "def binary_stdout():\n    \"\"\"\n    A sys.stdout that accepts bytes.\n    \"\"\"\n\n    # First there is a Python3 issue.\n    try:\n        stdout = sys.stdout.buffer\n    except AttributeError:\n        # Probably Python 2, where bytes are strings.\n        stdout = sys.stdout\n\n    # On Windows the C runtime file orientation needs changing.\n    if sys.platform == \"win32\":\n        import msvcrt\n        import os\n        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n\n    return stdout", "title": ""}
{"_id": "d10477", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d10478", "text": "def chunked(l, n):\n    \"\"\"Chunk one big list into few small lists.\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d10479", "text": "def vowels(self):\n        \"\"\"\n        Return a new IPAString, containing only the vowels in the current string.\n\n        :rtype: IPAString\n        \"\"\"\n        return IPAString(ipa_chars=[c for c in self.ipa_chars if c.is_vowel])", "title": ""}
{"_id": "d10480", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d10481", "text": "def write_fits(self, fitsfile):\n        \"\"\"Write the ROI model to a FITS file.\"\"\"\n\n        tab = self.create_table()\n        hdu_data = fits.table_to_hdu(tab)\n        hdus = [fits.PrimaryHDU(), hdu_data]\n        fits_utils.write_hdus(hdus, fitsfile)", "title": ""}
{"_id": "d10482", "text": "def ExpireObject(self, key):\n    \"\"\"Expire a specific object from cache.\"\"\"\n    node = self._hash.pop(key, None)\n    if node:\n      self._age.Unlink(node)\n      self.KillObject(node.data)\n\n      return node.data", "title": ""}
{"_id": "d10483", "text": "def close_all_but_this(self):\n        \"\"\"Close all files but the current one\"\"\"\n        self.close_all_right()\n        for i in range(0, self.get_stack_count()-1  ):\n            self.close_file(0)", "title": ""}
{"_id": "d10484", "text": "def line_count(fn):\n    \"\"\" Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)\n    \"\"\"\n\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "title": ""}
{"_id": "d10485", "text": "def do_exit(self, arg):\n        \"\"\"Exit the shell session.\"\"\"\n\n        if self.current:\n            self.current.close()\n        self.resource_manager.close()\n        del self.resource_manager\n        return True", "title": ""}
{"_id": "d10486", "text": "def socket_close(self):\n        \"\"\"Close our socket.\"\"\"\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET", "title": ""}
{"_id": "d10487", "text": "def WriteToPath(obj, filepath):\n  \"\"\"Serializes and writes given Python object to the specified YAML file.\n\n  Args:\n    obj: A Python object to serialize.\n    filepath: A path to the file into which the object is to be written.\n  \"\"\"\n  with io.open(filepath, mode=\"w\", encoding=\"utf-8\") as filedesc:\n    WriteToFile(obj, filedesc)", "title": ""}
{"_id": "d10488", "text": "def __exit__(self, *args):\n        \"\"\"\n        Cleanup any necessary opened files\n        \"\"\"\n\n        if self._output_file_handle:\n            self._output_file_handle.close()\n            self._output_file_handle = None", "title": ""}
{"_id": "d10489", "text": "def _write_separator(self):\n        \"\"\"\n        Inserts a horizontal (commented) line tot the generated code.\n        \"\"\"\n        tmp = self._page_width - ((4 * self.__indent_level) + 2)\n        self._write_line('# ' + ('-' * tmp))", "title": ""}
{"_id": "d10490", "text": "def write_line(self, line, count=1):\n        \"\"\"writes the line and count newlines after the line\"\"\"\n        self.write(line)\n        self.write_newlines(count)", "title": ""}
{"_id": "d10491", "text": "def linear_variogram_model(m, d):\n    \"\"\"Linear model, m is [slope, nugget]\"\"\"\n    slope = float(m[0])\n    nugget = float(m[1])\n    return slope * d + nugget", "title": ""}
{"_id": "d10492", "text": "def disable_wx(self):\n        \"\"\"Disable event loop integration with wxPython.\n\n        This merely sets PyOS_InputHook to NULL.\n        \"\"\"\n        if self._apps.has_key(GUI_WX):\n            self._apps[GUI_WX]._in_event_loop = False\n        self.clear_inputhook()", "title": ""}
{"_id": "d10493", "text": "def direct2dDistance(self, point):\n        \"\"\"consider the distance between two mapPoints, ignoring all terrain, pathing issues\"\"\"\n        if not isinstance(point, MapPoint): return 0.0\n        return  ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula", "title": ""}
{"_id": "d10494", "text": "def set_icon(self, bmp):\n        \"\"\"Sets main window icon to given wx.Bitmap\"\"\"\n\n        _icon = wx.EmptyIcon()\n        _icon.CopyFromBitmap(bmp)\n        self.SetIcon(_icon)", "title": ""}
{"_id": "d10495", "text": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d10496", "text": "def _update_fontcolor(self, fontcolor):\n        \"\"\"Updates text font color button\n\n        Parameters\n        ----------\n\n        fontcolor: Integer\n        \\tText color in integer RGB format\n\n        \"\"\"\n\n        textcolor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n        textcolor.SetRGB(fontcolor)\n\n        self.textcolor_choice.SetColour(textcolor)", "title": ""}
{"_id": "d10497", "text": "def printcsv(csvdiffs):\n    \"\"\"print the csv\"\"\"\n    for row in csvdiffs:\n        print(','.join([str(cell) for cell in row]))", "title": ""}
{"_id": "d10498", "text": "def disable_wx(self):\n        \"\"\"Disable event loop integration with wxPython.\n\n        This merely sets PyOS_InputHook to NULL.\n        \"\"\"\n        if self._apps.has_key(GUI_WX):\n            self._apps[GUI_WX]._in_event_loop = False\n        self.clear_inputhook()", "title": ""}
{"_id": "d10499", "text": "def from_json(cls, s):\n        \"\"\"\n        Restores the object from the given JSON.\n\n        :param s: the JSON string to parse\n        :type s: str\n        :return: the\n        \"\"\"\n        d = json.loads(s)\n        return get_dict_handler(d[\"type\"])(d)", "title": ""}
{"_id": "d10500", "text": "def _update_bordercolor(self, bordercolor):\n        \"\"\"Updates background color\"\"\"\n\n        border_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVEBORDER)\n        border_color.SetRGB(bordercolor)\n\n        self.linecolor_choice.SetColour(border_color)", "title": ""}
{"_id": "d10501", "text": "def point_in_multipolygon(point, multipoly):\n    \"\"\"\n    valid whether the point is located in a mulitpolygon (donut polygon is not supported)\n\n    Keyword arguments:\n    point      -- point geojson object\n    multipoly  -- multipolygon geojson object\n\n    if(point inside multipoly) return true else false\n    \"\"\"\n    coords_array = [multipoly['coordinates']] if multipoly[\n        'type'] == \"MultiPolygon\" else multipoly['coordinates']\n\n    for coords in coords_array:\n        if _point_in_polygon(point, coords):\n            return True\n\n    return False", "title": ""}
{"_id": "d10502", "text": "def c2s(self,p=[0,0]):\n        \"\"\"Convert from canvas to screen coordinates\"\"\"\n\n        return((p[0]-self.canvasx(self.cx1),p[1]-self.canvasy(self.cy1)))", "title": ""}
{"_id": "d10503", "text": "def to_binary(s, encoding='utf8'):\n    \"\"\"Portable cast function.\n\n    In python 2 the ``str`` function which is used to coerce objects to bytes does not\n    accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n    :param s: object to be converted to binary_type\n    :return: binary_type instance, representing s.\n    \"\"\"\n    if PY3:  # pragma: no cover\n        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n    return binary_type(s)", "title": ""}
{"_id": "d10504", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d10505", "text": "def combinations(l):\n    \"\"\"Pure-Python implementation of itertools.combinations(l, 2).\"\"\"\n    result = []\n    for x in xrange(len(l) - 1):\n        ls = l[x + 1:]\n        for y in ls:\n            result.append((l[x], y))\n    return result", "title": ""}
{"_id": "d10506", "text": "def str_is_well_formed(xml_str):\n    \"\"\"\n  Args:\n    xml_str : str\n      DataONE API XML doc.\n\n  Returns:\n    bool: **True** if XML doc is well formed.\n  \"\"\"\n    try:\n        str_to_etree(xml_str)\n    except xml.etree.ElementTree.ParseError:\n        return False\n    else:\n        return True", "title": ""}
{"_id": "d10507", "text": "def listunion(ListOfLists):\n    \"\"\"\n    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`.\n\n    \"\"\"\n    u = []\n    for s in ListOfLists:\n        if s != None:\n            u.extend(s)\n    return u", "title": ""}
{"_id": "d10508", "text": "def xml_str_to_dict(s):\n    \"\"\" Transforms an XML string it to python-zimbra dict format\n\n    For format, see:\n      https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n    :param: a string, containing XML\n    :returns: a dict, with python-zimbra format\n    \"\"\"\n    xml = minidom.parseString(s)\n    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)", "title": ""}
{"_id": "d10509", "text": "async def result_processor(tasks):\n    \"\"\"An async result aggregator that combines all the results\n       This gets executed in unsync.loop and unsync.thread\"\"\"\n    output = {}\n    for task in tasks:\n        num, res = await task\n        output[num] = res\n    return output", "title": ""}
{"_id": "d10510", "text": "def print_yaml(o):\n    \"\"\"Pretty print an object as YAML.\"\"\"\n    print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))", "title": ""}
{"_id": "d10511", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d10512", "text": "def prox_zero(X, step):\n    \"\"\"Proximal operator to project onto zero\n    \"\"\"\n    return np.zeros(X.shape, dtype=X.dtype)", "title": ""}
{"_id": "d10513", "text": "def compare(dicts):\n    \"\"\"Compare by iteration\"\"\"\n\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\n    return common_members", "title": ""}
{"_id": "d10514", "text": "def replace_sys_args(new_args):\n    \"\"\"Temporarily replace sys.argv with current arguments\n\n    Restores sys.argv upon exit of the context manager.\n    \"\"\"\n    # Replace sys.argv arguments\n    # for module import\n    old_args = sys.argv\n    sys.argv = new_args\n    try:\n        yield\n    finally:\n        sys.argv = old_args", "title": ""}
{"_id": "d10515", "text": "def _single_page_pdf(page):\n    \"\"\"Construct a single page PDF from the provided page in memory\"\"\"\n    pdf = Pdf.new()\n    pdf.pages.append(page)\n    bio = BytesIO()\n    pdf.save(bio)\n    bio.seek(0)\n    return bio.read()", "title": ""}
{"_id": "d10516", "text": "def export(defn):\n    \"\"\"Decorator to explicitly mark functions that are exposed in a lib.\"\"\"\n    globals()[defn.__name__] = defn\n    __all__.append(defn.__name__)\n    return defn", "title": ""}
{"_id": "d10517", "text": "def trim(self):\n        \"\"\"Clear not used counters\"\"\"\n        for key, value in list(iteritems(self.counters)):\n            if value.empty():\n                del self.counters[key]", "title": ""}
{"_id": "d10518", "text": "def np2str(value):\n    \"\"\"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\n\n    \"\"\"\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            # python 3 - was scalar numpy array of bytes\n            # otherwise python 2 - scalar numpy array of 'str'\n            value = value.decode()\n        return value\n    else:\n        raise ValueError(\"Array is not a string type or is larger than 1\")", "title": ""}
{"_id": "d10519", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d10520", "text": "def askopenfilename(**kwargs):\n    \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n    try:\n        from Tkinter import Tk\n        import tkFileDialog as filedialog\n    except ImportError:\n        from tkinter import Tk, filedialog\n    root = Tk()\n    root.withdraw()\n    root.update()\n    filenames = filedialog.askopenfilename(**kwargs)\n    root.destroy()\n    return filenames", "title": ""}
{"_id": "d10521", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d10522", "text": "def register_blueprints(app):\n    \"\"\"Register Flask blueprints.\"\"\"\n    app.register_blueprint(public.public_bp)\n    app.register_blueprint(genes.genes_bp)\n    app.register_blueprint(cases.cases_bp)\n    app.register_blueprint(login.login_bp)\n    app.register_blueprint(variants.variants_bp)\n    app.register_blueprint(panels.panels_bp)\n    app.register_blueprint(dashboard.dashboard_bp)\n    app.register_blueprint(api.api_bp)\n    app.register_blueprint(alignviewers.alignviewers_bp)\n    app.register_blueprint(phenotypes.hpo_bp)\n    app.register_blueprint(institutes.overview)", "title": ""}
{"_id": "d10523", "text": "def _clone_properties(self):\n    \"\"\"Internal helper to clone self._properties if necessary.\"\"\"\n    cls = self.__class__\n    if self._properties is cls._properties:\n      self._properties = dict(cls._properties)", "title": ""}
{"_id": "d10524", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d10525", "text": "def correlation(df, rowvar=False):\n    \"\"\"\n    Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``\n\n    Input data is masked to ignore NaNs when calculating correlations. Data is returned as\n    a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to\n    both axes.\n\n    :param df: Pandas DataFrame\n    :return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations\n    \"\"\"\n\n    # Create a correlation matrix for all correlations\n    # of the columns (filled with na for all values)\n    df = df.copy()\n    maskv = np.ma.masked_where(np.isnan(df.values), df.values)\n    cdf = np.ma.corrcoef(maskv, rowvar=False)\n    cdf = pd.DataFrame(np.array(cdf))\n    cdf.columns = df.columns\n    cdf.index = df.columns\n    cdf = cdf.sort_index(level=0, axis=1)\n    cdf = cdf.sort_index(level=0)\n    return cdf", "title": ""}
{"_id": "d10526", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d10527", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d10528", "text": "def write_color(string, name, style='normal', when='auto'):\n    \"\"\" Write the given colored string to standard out. \"\"\"\n    write(color(string, name, style, when))", "title": ""}
{"_id": "d10529", "text": "def first_sunday(self, year, month):\n        \"\"\"Get the first sunday of a month.\"\"\"\n        date = datetime(year, month, 1, 0)\n        days_until_sunday = 6 - date.weekday()\n\n        return date + timedelta(days=days_until_sunday)", "title": ""}
{"_id": "d10530", "text": "def _get_column_by_db_name(cls, name):\n        \"\"\"\n        Returns the column, mapped by db_field name\n        \"\"\"\n        return cls._columns.get(cls._db_map.get(name, name))", "title": ""}
{"_id": "d10531", "text": "def get_number(s, cast=int):\n    \"\"\"\n    Try to get a number out of a string, and cast it.\n    \"\"\"\n    import string\n    d = \"\".join(x for x in str(s) if x in string.digits)\n    return cast(d)", "title": ""}
{"_id": "d10532", "text": "def get_by(self, name):\n    \"\"\"get element by name\"\"\"\n    return next((item for item in self if item.name == name), None)", "title": ""}
{"_id": "d10533", "text": "def comma_delimited_to_list(list_param):\n    \"\"\"Convert comma-delimited list / string into a list of strings\n\n    :param list_param: Comma-delimited string\n    :type list_param: str | unicode\n    :return: A list of strings\n    :rtype: list\n    \"\"\"\n    if isinstance(list_param, list):\n        return list_param\n    if isinstance(list_param, str):\n        return list_param.split(',')\n    else:\n        return []", "title": ""}
{"_id": "d10534", "text": "def other_ind(self):\n        \"\"\"last row or column of square A\"\"\"\n        return np.full(self.n_min, self.size - 1, dtype=np.int)", "title": ""}
{"_id": "d10535", "text": "def from_rectangle(box):\n        \"\"\" Create a vector randomly within the given rectangle. \"\"\"\n        x = box.left + box.width * random.uniform(0, 1)\n        y = box.bottom + box.height * random.uniform(0, 1)\n        return Vector(x, y)", "title": ""}
{"_id": "d10536", "text": "def s3(ctx, bucket_name, data_file, region):\n    \"\"\"Use the S3 SWAG backend.\"\"\"\n    if not ctx.data_file:\n        ctx.data_file = data_file\n\n    if not ctx.bucket_name:\n        ctx.bucket_name = bucket_name\n\n    if not ctx.region:\n        ctx.region = region\n\n    ctx.type = 's3'", "title": ""}
{"_id": "d10537", "text": "def load(self, name):\n        \"\"\"Loads and returns foreign library.\"\"\"\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)", "title": ""}
{"_id": "d10538", "text": "def get_system_cpu_times():\n    \"\"\"Return system CPU times as a namedtuple.\"\"\"\n    user, nice, system, idle = _psutil_osx.get_system_cpu_times()\n    return _cputimes_ntuple(user, nice, system, idle)", "title": ""}
{"_id": "d10539", "text": "def to_comment(value):\n  \"\"\"\n  Builds a comment.\n  \"\"\"\n  if value is None:\n    return\n  if len(value.split('\\n')) == 1:\n    return \"* \" + value\n  else:\n    return '\\n'.join([' * ' + l for l in value.split('\\n')[:-1]])", "title": ""}
{"_id": "d10540", "text": "def init():\n    \"\"\"\n    Execute init tasks for all components (virtualenv, pip).\n    \"\"\"\n    print(yellow(\"# Setting up environment...\\n\", True))\n    virtualenv.init()\n    virtualenv.update_requirements()\n    print(green(\"\\n# DONE.\", True))\n    print(green(\"Type \") + green(\"activate\", True) + green(\" to enable your virtual environment.\"))", "title": ""}
{"_id": "d10541", "text": "def _convert(tup, dictlist):\n    \"\"\"\n    :param tup: a list of tuples\n    :param di: a dictionary converted from tup\n    :return: dictionary\n    \"\"\"\n    di = {}\n    for a, b in tup:\n        di.setdefault(a, []).append(b)\n    for key, val in di.items():\n        dictlist.append((key, val))\n    return dictlist", "title": ""}
{"_id": "d10542", "text": "def init_mq(self):\n        \"\"\"Init connection and consumer with openstack mq.\"\"\"\n        mq = self.init_connection()\n        self.init_consumer(mq)\n        return mq.connection", "title": ""}
{"_id": "d10543", "text": "def create_path(path):\n    \"\"\"Creates a absolute path in the file system.\n\n    :param path: The path to be created\n    \"\"\"\n    import os\n    if not os.path.exists(path):\n        os.makedirs(path)", "title": ""}
{"_id": "d10544", "text": "def token(name):\n    \"\"\"Marker for a token\n\n    :param str name: Name of tokenizer\n    \"\"\"\n\n    def wrap(f):\n        tokenizers.append((name, f))\n        return f\n\n    return wrap", "title": ""}
{"_id": "d10545", "text": "def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"A quick and dirty way to get a unique string\"\"\"\n    return ''.join(random.choice(chars) for x in xrange(size))", "title": ""}
{"_id": "d10546", "text": "def __call__(self, r):\n        \"\"\"Update the request headers.\"\"\"\n        r.headers['Authorization'] = 'JWT {jwt}'.format(jwt=self.token)\n        return r", "title": ""}
{"_id": "d10547", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d10548", "text": "def add_column(connection, column):\n    \"\"\"\n    Add a column to the current table.\n    \"\"\"\n    stmt = alembic.ddl.base.AddColumn(_State.table.name, column)\n    connection.execute(stmt)\n    _State.reflect_metadata()", "title": ""}
{"_id": "d10549", "text": "def check_create_folder(filename):\n    \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n    os.makedirs(os.path.dirname(filename), exist_ok=True)", "title": ""}
{"_id": "d10550", "text": "def unit_ball_L_inf(shape, precondition=True):\n  \"\"\"A tensorflow variable tranfomed to be constrained in a L_inf unit ball.\n\n  Note that this code also preconditions the gradient to go in the L_inf\n  direction of steepest descent.\n\n  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n  they are strong attacks. We are not yet confident in this code.\n  \"\"\"\n  x = tf.Variable(tf.zeros(shape))\n  if precondition:\n    return constrain_L_inf_precondition(x)\n  else:\n    return constrain_L_inf(x)", "title": ""}
{"_id": "d10551", "text": "def _make_cmd_list(cmd_list):\n    \"\"\"\n    Helper function to easily create the proper json formated string from a list of strs\n    :param cmd_list: list of strings\n    :return: str json formatted\n    \"\"\"\n    cmd = ''\n    for i in cmd_list:\n        cmd = cmd + '\"' + i + '\",'\n    cmd = cmd[:-1]\n    return cmd", "title": ""}
{"_id": "d10552", "text": "def save_to_16bit_wave_file(fname, sig, rate):\n  \"\"\"\n  Save a given signal ``sig`` to file ``fname`` as a 16-bit one-channel wave\n  with the given ``rate`` sample rate.\n  \"\"\"\n  with closing(wave.open(fname, \"wb\")) as wave_file:\n    wave_file.setnchannels(1)\n    wave_file.setsampwidth(2)\n    wave_file.setframerate(rate)\n    for chunk in chunks((clip(sig) * 2 ** 15).map(int), dfmt=\"h\", padval=0):\n      wave_file.writeframes(chunk)", "title": ""}
{"_id": "d10553", "text": "def to_bytes_or_none(value):\n    \"\"\"Converts C char arrays to bytes and C NULL values to None.\"\"\"\n    if value == ffi.NULL:\n        return None\n    elif isinstance(value, ffi.CData):\n        return ffi.string(value)\n    else:\n        raise ValueError('Value must be char[] or NULL')", "title": ""}
{"_id": "d10554", "text": "def save_image(pdf_path, img_path, page_num):\n    \"\"\"\n\n    Creates images for a page of the input pdf document and saves it\n    at img_path.\n\n    :param pdf_path: path to pdf to create images for.\n    :param img_path: path where to save the images.\n    :param page_num: page number to create image from in the pdf file.\n    :return:\n    \"\"\"\n    pdf_img = Image(filename=\"{}[{}]\".format(pdf_path, page_num))\n    with pdf_img.convert(\"png\") as converted:\n        # Set white background.\n        converted.background_color = Color(\"white\")\n        converted.alpha_channel = \"remove\"\n        converted.save(filename=img_path)", "title": ""}
{"_id": "d10555", "text": "def load(self, name):\n        \"\"\"Loads and returns foreign library.\"\"\"\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)", "title": ""}
{"_id": "d10556", "text": "def append(self, item):\n        \"\"\" append item and print it to stdout \"\"\"\n        print(item)\n        super(MyList, self).append(item)", "title": ""}
{"_id": "d10557", "text": "def cfloat32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n        return np.fromiter(cptr, dtype=np.float32, count=length)\n    else:\n        raise RuntimeError('Expected float pointer')", "title": ""}
{"_id": "d10558", "text": "def concat(cls, iterables):\n    \"\"\"\n    Similar to #itertools.chain.from_iterable().\n    \"\"\"\n\n    def generator():\n      for it in iterables:\n        for element in it:\n          yield element\n    return cls(generator())", "title": ""}
{"_id": "d10559", "text": "def c_str(string):\n    \"\"\"\"Convert a python string to C string.\"\"\"\n    if not isinstance(string, str):\n        string = string.decode('ascii')\n    return ctypes.c_char_p(string.encode('utf-8'))", "title": ""}
{"_id": "d10560", "text": "def struct2dict(struct):\n    \"\"\"convert a ctypes structure to a dictionary\"\"\"\n    return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}", "title": ""}
{"_id": "d10561", "text": "def add_text_to_image(fname, txt, opFilename):\n    \"\"\" convert an image by adding text \"\"\"\n    ft = ImageFont.load(\"T://user//dev//src//python//_AS_LIB//timR24.pil\")\n    #wh = ft.getsize(txt)\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)", "title": ""}
{"_id": "d10562", "text": "def c_str(string):\n    \"\"\"\"Convert a python string to C string.\"\"\"\n    if not isinstance(string, str):\n        string = string.decode('ascii')\n    return ctypes.c_char_p(string.encode('utf-8'))", "title": ""}
{"_id": "d10563", "text": "def managepy(cmd, extra=None):\n    \"\"\"Run manage.py using this component's specific Django settings\"\"\"\n\n    extra = extra.split() if extra else []\n    run_django_cli(['invoke', cmd] + extra)", "title": ""}
{"_id": "d10564", "text": "def add_str(window, line_num, str):\n    \"\"\" attempt to draw str on screen and ignore errors if they occur \"\"\"\n    try:\n        window.addstr(line_num, 0, str)\n    except curses.error:\n        pass", "title": ""}
{"_id": "d10565", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d10566", "text": "def add_str(window, line_num, str):\n    \"\"\" attempt to draw str on screen and ignore errors if they occur \"\"\"\n    try:\n        window.addstr(line_num, 0, str)\n    except curses.error:\n        pass", "title": ""}
{"_id": "d10567", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d10568", "text": "def glob_by_extensions(directory, extensions):\n    \"\"\" Returns files matched by all extensions in the extensions list \"\"\"\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", "title": ""}
{"_id": "d10569", "text": "def del_Unnamed(df):\n    \"\"\"\n    Deletes all the unnamed columns\n\n    :param df: pandas dataframe\n    \"\"\"\n    cols_del=[c for c in df.columns if 'Unnamed' in c]\n    return df.drop(cols_del,axis=1)", "title": ""}
{"_id": "d10570", "text": "def load(self):\n\t\t\"\"\"Load the noise texture data into the current texture unit\"\"\"\n\t\tglTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16, \n\t\t\tself.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA, \n\t\t\tGL_UNSIGNED_SHORT, ctypes.byref(self.data))", "title": ""}
{"_id": "d10571", "text": "def is_iterable(value):\n    \"\"\"must be an iterable (list, array, tuple)\"\"\"\n    return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "title": ""}
{"_id": "d10572", "text": "def make_table_map(table, headers):\n    \"\"\"Create a function to map from rows with the structure of the headers to the structure of the table.\"\"\"\n\n    header_parts = {}\n    for i, h in enumerate(headers):\n        header_parts[h] = 'row[{}]'.format(i)\n\n    body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(c.name, 'None') for c in table.columns))\n    header_code = 'lambda row: [{}]'.format(\n        ','.join(header_parts.get(c.name, \"'{}'\".format(c.name)) for c in table.columns))\n\n    return eval(header_code), eval(body_code)", "title": ""}
{"_id": "d10573", "text": "def datetime_delta_to_ms(delta):\n    \"\"\"\n    Given a datetime.timedelta object, return the delta in milliseconds\n    \"\"\"\n    delta_ms = delta.days * 24 * 60 * 60 * 1000\n    delta_ms += delta.seconds * 1000\n    delta_ms += delta.microseconds / 1000\n    delta_ms = int(delta_ms)\n    return delta_ms", "title": ""}
{"_id": "d10574", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d10575", "text": "def isoformat(dt):\n    \"\"\"Return an ISO-8601 formatted string from the provided datetime object\"\"\"\n    if not isinstance(dt, datetime.datetime):\n        raise TypeError(\"Must provide datetime.datetime object to isoformat\")\n\n    if dt.tzinfo is None:\n        raise ValueError(\"naive datetime objects are not allowed beyond the library boundaries\")\n\n    return dt.isoformat().replace(\"+00:00\", \"Z\")", "title": ""}
{"_id": "d10576", "text": "def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT):\n        \"\"\"Convert unix timestamp to human readable date/time string\"\"\"\n        return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)", "title": ""}
{"_id": "d10577", "text": "def findMax(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMax(arr, out)\n    return out", "title": ""}
{"_id": "d10578", "text": "async def iso(self, source):\n        \"\"\"Convert to timestamp.\"\"\"\n        from datetime import datetime\n        unix_timestamp = int(source)\n        return datetime.fromtimestamp(unix_timestamp).isoformat()", "title": ""}
{"_id": "d10579", "text": "def barray(iterlines):\n    \"\"\"\n    Array of bytes\n    \"\"\"\n    lst = [line.encode('utf-8') for line in iterlines]\n    arr = numpy.array(lst)\n    return arr", "title": ""}
{"_id": "d10580", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d10581", "text": "def to_camel_case(snake_case_name):\n    \"\"\"\n    Converts snake_cased_names to CamelCaseNames.\n\n    :param snake_case_name: The name you'd like to convert from.\n    :type snake_case_name: string\n\n    :returns: A converted string\n    :rtype: string\n    \"\"\"\n    bits = snake_case_name.split('_')\n    return ''.join([bit.capitalize() for bit in bits])", "title": ""}
{"_id": "d10582", "text": "def convert_tstamp(response):\n\t\"\"\"\n\tConvert a Stripe API timestamp response (unix epoch) to a native datetime.\n\n\t:rtype: datetime\n\t\"\"\"\n\tif response is None:\n\t\t# Allow passing None to convert_tstamp()\n\t\treturn response\n\n\t# Overrides the set timezone to UTC - I think...\n\ttz = timezone.utc if settings.USE_TZ else None\n\n\treturn datetime.datetime.fromtimestamp(response, tz)", "title": ""}
{"_id": "d10583", "text": "def cric__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n    model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)\n\n    # we want to explain the raw probability outputs of the trees\n    model.predict = lambda X: model.predict_proba(X)[:,1]\n    \n    return model", "title": ""}
{"_id": "d10584", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d10585", "text": "def cric__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n    model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)\n\n    # we want to explain the raw probability outputs of the trees\n    model.predict = lambda X: model.predict_proba(X)[:,1]\n    \n    return model", "title": ""}
{"_id": "d10586", "text": "def get_ips(self, instance_id):\n        \"\"\"Retrieves all IP addresses associated to a given instance.\n\n        :return: tuple (IPs)\n        \"\"\"\n        instance = self._load_instance(instance_id)\n        IPs = sum(instance.networks.values(), [])\n        return IPs", "title": ""}
{"_id": "d10587", "text": "def attribute(func):\n    \"\"\"Wrap a function as an attribute.\"\"\"\n    attr = abc.abstractmethod(func)\n    attr.__iattribute__ = True\n    attr = _property(attr)\n    return attr", "title": ""}
{"_id": "d10588", "text": "def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key):\n    \"\"\"Creates an AWS Chalice project for deployment to AWS Lambda.\"\"\"\n    from canari.commands.create_aws_lambda import create_aws_lambda\n    create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key)", "title": ""}
{"_id": "d10589", "text": "def map_wrap(f):\n    \"\"\"Wrap standard function to easily pass into 'map' processing.\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d10590", "text": "def get_api_url(self, lambda_name, stage_name):\n        \"\"\"\n        Given a lambda_name and stage_name, return a valid API URL.\n        \"\"\"\n        api_id = self.get_api_id(lambda_name)\n        if api_id:\n            return \"https://{}.execute-api.{}.amazonaws.com/{}\".format(api_id, self.boto_session.region_name, stage_name)\n        else:\n            return None", "title": ""}
{"_id": "d10591", "text": "def _iterable_to_varargs_method(func):\n    \"\"\"decorator to convert a method taking a iterable to a *args one\"\"\"\n    def wrapped(self, *args, **kwargs):\n        return func(self, args, **kwargs)\n    return wrapped", "title": ""}
{"_id": "d10592", "text": "def _aws_get_instance_by_tag(region, name, tag, raw):\n    \"\"\"Get all instances matching a tag.\"\"\"\n    client = boto3.session.Session().client('ec2', region)\n    matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', [])\n    instances = []\n    [[instances.append(_aws_instance_from_dict(region, instance, raw))  # pylint: disable=expression-not-assigned\n      for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation]\n    return instances", "title": ""}
{"_id": "d10593", "text": "def visit_Str(self, node):\n        \"\"\" Set the pythonic string type. \"\"\"\n        self.result[node] = self.builder.NamedType(pytype_to_ctype(str))", "title": ""}
{"_id": "d10594", "text": "def _remove_duplicate_files(xs):\n    \"\"\"Remove files specified multiple times in a list.\n    \"\"\"\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", "title": ""}
{"_id": "d10595", "text": "def standardize():\n    \"\"\"\n    return variant standarize function\n    \"\"\"\n\n    def f(G, bim):\n        G_out = standardize_snps(G)\n        return G_out, bim\n\n    return f", "title": ""}
{"_id": "d10596", "text": "def setdefault(obj, field, default):\n    \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n    setattr(obj, field, getattr(obj, field, default))", "title": ""}
{"_id": "d10597", "text": "def _merge_maps(m1, m2):\n    \"\"\"merge two Mapping objects, keeping the type of the first mapping\"\"\"\n    return type(m1)(chain(m1.items(), m2.items()))", "title": ""}
{"_id": "d10598", "text": "def remove_examples_all():\n    \"\"\"remove arduino/examples/all directory.\n\n    :rtype: None\n\n    \"\"\"\n    d = examples_all_dir()\n    if d.exists():\n        log.debug('remove %s', d)\n        d.rmtree()\n    else:\n        log.debug('nothing to remove: %s', d)", "title": ""}
{"_id": "d10599", "text": "def __get_xml_text(root):\n    \"\"\" Return the text for the given root node (xml.dom.minidom). \"\"\"\n    txt = \"\"\n    for e in root.childNodes:\n        if (e.nodeType == e.TEXT_NODE):\n            txt += e.data\n    return txt", "title": ""}
{"_id": "d10600", "text": "def __delitem__(self, resource):\n        \"\"\"Remove resource instance from internal cache\"\"\"\n        self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None)", "title": ""}
{"_id": "d10601", "text": "def get_object_as_string(obj):\n    \"\"\"\n    Converts any object to JSON-like readable format, ready to be printed for debugging purposes\n    :param obj: Any object\n    :return: string\n    \"\"\"\n    if isinstance(obj, str):\n        return obj\n    if isinstance(obj, list):\n        return '\\r\\n\\;'.join([get_object_as_string(item) for item in obj])\n    attrs = vars(obj)\n    as_string = ', '.join(\"%s: %s\" % item for item in attrs.items())\n    return as_string", "title": ""}
{"_id": "d10602", "text": "def highpass(cutoff):\n  \"\"\"\n  This strategy uses an exponential approximation for cut-off frequency\n  calculation, found by matching the one-pole Laplace lowpass filter\n  and mirroring the resulting filter to get a highpass.\n  \"\"\"\n  R = thub(exp(cutoff - pi), 2)\n  return (1 - R) / (1 + R * z ** -1)", "title": ""}
{"_id": "d10603", "text": "def intToBin(i):\n    \"\"\" Integer to two bytes \"\"\"\n    # devide in two parts (bytes)\n    i1 = i % 256\n    i2 = int(i / 256)\n    # make string (little endian)\n    return chr(i1) + chr(i2)", "title": ""}
{"_id": "d10604", "text": "def _gaps_from(intervals):\n    \"\"\"\n    From a list of intervals extract\n    a list of sorted gaps in the form of [(g,i)]\n    where g is the size of the ith gap.\n    \"\"\"\n    sliding_window = zip(intervals, intervals[1:])\n    gaps = [b[0] - a[1] for a, b in sliding_window]\n    return gaps", "title": ""}
{"_id": "d10605", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d10606", "text": "def isroutine(object):\n    \"\"\"Return true if the object is any kind of function or method.\"\"\"\n    return (isbuiltin(object)\n            or isfunction(object)\n            or ismethod(object)\n            or ismethoddescriptor(object))", "title": ""}
{"_id": "d10607", "text": "def compute_boxplot(self, series):\n        \"\"\"\n        Compute boxplot for given pandas Series.\n        \"\"\"\n        from matplotlib.cbook import boxplot_stats\n        series = series[series.notnull()]\n        if len(series.values) == 0:\n            return {}\n        elif not is_numeric_dtype(series):\n            return self.non_numeric_stats(series)\n        stats = boxplot_stats(list(series.values))[0]\n        stats['count'] = len(series.values)\n        stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n        return stats", "title": ""}
{"_id": "d10608", "text": "def kill_mprocess(process):\n    \"\"\"kill process\n    Args:\n        process - Popen object for process\n    \"\"\"\n    if process and proc_alive(process):\n        process.terminate()\n        process.communicate()\n    return not proc_alive(process)", "title": ""}
{"_id": "d10609", "text": "def inFocus(self):\n        \"\"\"Set GUI on-top flag\"\"\"\n        previous_flags = self.window.flags()\n        self.window.setFlags(previous_flags |\n                             QtCore.Qt.WindowStaysOnTopHint)", "title": ""}
{"_id": "d10610", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d10611", "text": "def __pop_top_frame(self):\n        \"\"\"Pops the top frame off the frame stack.\"\"\"\n        popped = self.__stack.pop()\n        if self.__stack:\n            self.__stack[-1].process_subframe(popped)", "title": ""}
{"_id": "d10612", "text": "def machine_info():\n    \"\"\"Retrieve core and memory information for the current machine.\n    \"\"\"\n    import psutil\n    BYTES_IN_GIG = 1073741824.0\n    free_bytes = psutil.virtual_memory().total\n    return [{\"memory\": float(\"%.1f\" % (free_bytes / BYTES_IN_GIG)), \"cores\": multiprocessing.cpu_count(),\n             \"name\": socket.gethostname()}]", "title": ""}
{"_id": "d10613", "text": "def code(self):\n    \"\"\"Returns the code object for this BUILD file.\"\"\"\n    return compile(self.source(), self.full_path, 'exec', flags=0, dont_inherit=True)", "title": ""}
{"_id": "d10614", "text": "def read_string(buff, byteorder='big'):\n    \"\"\"Read a string from a file-like object.\"\"\"\n    length = read_numeric(USHORT, buff, byteorder)\n    return buff.read(length).decode('utf-8')", "title": ""}
{"_id": "d10615", "text": "def connect(host, port, username, password):\n        \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n        # Instantiate ftplib client\n        session = ftplib.FTP()\n\n        # Connect to host without auth\n        session.connect(host, port)\n\n        # Authenticate connection\n        session.login(username, password)\n        return session", "title": ""}
{"_id": "d10616", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d10617", "text": "def barray(iterlines):\n    \"\"\"\n    Array of bytes\n    \"\"\"\n    lst = [line.encode('utf-8') for line in iterlines]\n    arr = numpy.array(lst)\n    return arr", "title": ""}
{"_id": "d10618", "text": "def itervalues(d, **kw):\n    \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n    if not PY2:\n        return iter(d.values(**kw))\n    return d.itervalues(**kw)", "title": ""}
{"_id": "d10619", "text": "def ungzip_data(input_data):\n    \"\"\"Return a string of data after gzip decoding\n\n    :param the input gziped data\n    :return  the gzip decoded data\"\"\"\n    buf = StringIO(input_data)\n    f = gzip.GzipFile(fileobj=buf)\n    return f", "title": ""}
{"_id": "d10620", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d10621", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d10622", "text": "def is_set(self, key):\n        \"\"\"Return True if variable is a set\"\"\"\n        data = self.model.get_data()\n        return isinstance(data[key], set)", "title": ""}
{"_id": "d10623", "text": "def is_static(*p):\n    \"\"\" A static value (does not change at runtime)\n    which is known at compile time\n    \"\"\"\n    return all(is_CONST(x) or\n               is_number(x) or\n               is_const(x)\n               for x in p)", "title": ""}
{"_id": "d10624", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d10625", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d10626", "text": "def setdefaults(dct, defaults):\n    \"\"\"Given a target dct and a dict of {key:default value} pairs,\n    calls setdefault for all of those pairs.\"\"\"\n    for key in defaults:\n        dct.setdefault(key, defaults[key])\n\n    return dct", "title": ""}
{"_id": "d10627", "text": "def inh(table):\n    \"\"\"\n    inverse hyperbolic sine transformation\n    \"\"\"\n    t = []\n    for i in table:\n        t.append(np.ndarray.tolist(np.arcsinh(i)))\n    return t", "title": ""}
{"_id": "d10628", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d10629", "text": "def find_dist_to_centroid(cvects, idx_list, weights=None):\n    \"\"\" Find the centroid for a set of vectors\n\n    Parameters\n    ----------\n    cvects : ~numpy.ndarray(3,nsrc) with directional cosine (i.e., x,y,z component) values\n\n    idx_list : [int,...]\n      list of the source indices in the cluster\n\n    weights : ~numpy.ndarray(nsrc) with the weights to use.  None for equal weighting\n\n    returns (np.ndarray(nsrc)) distances to the centroid (in degrees)\n    \"\"\"\n    centroid = find_centroid(cvects, idx_list, weights)\n    dist_vals = np.degrees(np.arccos((centroid * cvects.T[idx_list]).sum(1)))\n    return dist_vals, centroid", "title": ""}
{"_id": "d10630", "text": "def vector_distance(a, b):\n    \"\"\"The Euclidean distance between two vectors.\"\"\"\n    a = np.array(a)\n    b = np.array(b)\n    return np.linalg.norm(a - b)", "title": ""}
{"_id": "d10631", "text": "async def connect(self):\n        \"\"\"\n        Connects to the voice channel associated with this Player.\n        \"\"\"\n        await self.node.join_voice_channel(self.channel.guild.id, self.channel.id)", "title": ""}
{"_id": "d10632", "text": "def median_date(dt_list):\n    \"\"\"Calcuate median datetime from datetime list\n    \"\"\"\n    #dt_list_sort = sorted(dt_list)\n    idx = len(dt_list)/2\n    if len(dt_list) % 2 == 0:\n        md = mean_date([dt_list[idx-1], dt_list[idx]])\n    else:\n        md = dt_list[idx]\n    return md", "title": ""}
{"_id": "d10633", "text": "def _get_printable_columns(columns, row):\n    \"\"\"Return only the part of the row which should be printed.\n    \"\"\"\n    if not columns:\n        return row\n\n    # Extract the column values, in the order specified.\n    return tuple(row[c] for c in columns)", "title": ""}
{"_id": "d10634", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d10635", "text": "def release(self):\n        \"\"\"\n        Releases this resource back to the pool it came from.\n        \"\"\"\n        if self.errored:\n            self.pool.delete_resource(self)\n        else:\n            self.pool.release(self)", "title": ""}
{"_id": "d10636", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d10637", "text": "def dist_sq(self, other):\n    \"\"\"Distance squared to some other point.\"\"\"\n    dx = self.x - other.x\n    dy = self.y - other.y\n    return dx**2 + dy**2", "title": ""}
{"_id": "d10638", "text": "def map_wrap(f):\n    \"\"\"Wrap standard function to easily pass into 'map' processing.\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d10639", "text": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "title": ""}
{"_id": "d10640", "text": "def launch_server():\n    \"\"\"Launches the django server at 127.0.0.1:8000\n    \"\"\"\n    print(os.path.dirname(os.path.abspath(__file__)))\n    cur_dir = os.getcwd()\n    path = os.path.dirname(os.path.abspath(__file__))\n    run = True\n    os.chdir(path)\n    os.system('python manage.py runserver --nostatic')\n    os.chdir(cur_dir)", "title": ""}
{"_id": "d10641", "text": "def add_range(self, sequence, begin, end):\n    \"\"\"Add a read_range primitive\"\"\"\n    sequence.parser_tree = parsing.Range(self.value(begin).strip(\"'\"),\n                                         self.value(end).strip(\"'\"))\n    return True", "title": ""}
{"_id": "d10642", "text": "def url(viewname, *args, **kwargs):\n    \"\"\"Helper for Django's ``reverse`` in templates.\"\"\"\n    return reverse(viewname, args=args, kwargs=kwargs)", "title": ""}
{"_id": "d10643", "text": "def _image_field(self):\n        \"\"\"\n        Try to automatically detect an image field\n        \"\"\"\n        for field in self.model._meta.fields:\n            if isinstance(field, ImageField):\n                return field.name", "title": ""}
{"_id": "d10644", "text": "def __init__(self, function):\n\t\t\"\"\"function: to be called with each stream element as its\n\t\tonly argument\n\t\t\"\"\"\n\t\tsuper(takewhile, self).__init__()\n\t\tself.function = function", "title": ""}
{"_id": "d10645", "text": "def set_locale(request):\n    \"\"\"Return locale from GET lang param or automatically.\"\"\"\n    return request.query.get('lang', app.ps.babel.select_locale_by_request(request))", "title": ""}
{"_id": "d10646", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d10647", "text": "def static_urls_js():\n    \"\"\"\n    Add global variables to JavaScript about the location and latest version of\n    transpiled files.\n    Usage::\n        {% static_urls_js %}\n    \"\"\"\n    if apps.is_installed('django.contrib.staticfiles'):\n        from django.contrib.staticfiles.storage import staticfiles_storage\n        static_base_url = staticfiles_storage.base_url\n    else:\n        static_base_url = PrefixNode.handle_simple(\"STATIC_URL\")\n    transpile_base_url = urljoin(static_base_url, 'js/transpile/')\n    return {\n        'static_base_url': static_base_url,\n        'transpile_base_url': transpile_base_url,\n        'version': LAST_RUN['version']\n    }", "title": ""}
{"_id": "d10648", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d10649", "text": "def is_rfc2822(instance: str):\n    \"\"\"Validates RFC2822 format\"\"\"\n    if not isinstance(instance, str):\n        return True\n    return email.utils.parsedate(instance) is not None", "title": ""}
{"_id": "d10650", "text": "def replace(s, replace):\n    \"\"\"Replace multiple values in a string\"\"\"\n    for r in replace:\n        s = s.replace(*r)\n    return s", "title": ""}
{"_id": "d10651", "text": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"React to a docstring event and append contracts to it.\"\"\"\n    # pylint: disable=unused-argument\n    # pylint: disable=too-many-arguments\n    lines.extend(_format_contracts(what=what, obj=obj))", "title": ""}
{"_id": "d10652", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d10653", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d10654", "text": "def us2mc(string):\n    \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)", "title": ""}
{"_id": "d10655", "text": "def downsample_with_striding(array, factor):\n    \"\"\"Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x.\n    \"\"\"\n    return array[tuple(np.s_[::f] for f in factor)]", "title": ""}
{"_id": "d10656", "text": "def cache(self):\n        \"\"\"Memoize access to the cache backend.\"\"\"\n        if self._cache is None:\n            self._cache = django_cache.get_cache(self.cache_name)\n        return self._cache", "title": ""}
{"_id": "d10657", "text": "def _add_line_segment(self, x, y):\n        \"\"\"Add a |_LineSegment| operation to the drawing sequence.\"\"\"\n        self._drawing_operations.append(_LineSegment.new(self, x, y))", "title": ""}
{"_id": "d10658", "text": "def update(kernel=False):\n    \"\"\"\n    Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.\n\n    Exclude *kernel* upgrades by default.\n    \"\"\"\n    manager = MANAGER\n    cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}}\n    cmd = cmds[manager][kernel]\n    run_as_root(\"%(manager)s %(cmd)s\" % locals())", "title": ""}
{"_id": "d10659", "text": "def qr(self,text):\n        \"\"\" Print QR Code for the provided string \"\"\"\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        # Convert the RGB image in printable image\n        self._convert_image(im)", "title": ""}
{"_id": "d10660", "text": "def to_list(var):\n    \"\"\"Checks if given value is a list, tries to convert, if it is not.\"\"\"\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", "title": ""}
{"_id": "d10661", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d10662", "text": "def string_to_list(string, sep=\",\", filter_empty=False):\n    \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n    return [value.strip() for value in string.split(sep)\n            if (not filter_empty or value)]", "title": ""}
{"_id": "d10663", "text": "def delete_index(index):\n    \"\"\"Delete index entirely (removes all documents and mapping).\"\"\"\n    logger.info(\"Deleting search index: '%s'\", index)\n    client = get_client()\n    return client.indices.delete(index=index)", "title": ""}
{"_id": "d10664", "text": "def angle_to_cartesian(lon, lat):\n    \"\"\"Convert spherical coordinates to cartesian unit vectors.\"\"\"\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", "title": ""}
{"_id": "d10665", "text": "def can_elasticsearch(record):\n    \"\"\"Check if a given record is indexed.\n\n    :param record: A record object.\n    :returns: If the record is indexed returns `True`, otherwise `False`.\n    \"\"\"\n    search = request._methodview.search_class()\n    search = search.get_record(str(record.id))\n    return search.count() == 1", "title": ""}
{"_id": "d10666", "text": "def comma_converter(float_string):\n    \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n    trans_table = maketrans(b',', b'.')\n    return float(float_string.translate(trans_table))", "title": ""}
{"_id": "d10667", "text": "def raw(self):\n        \"\"\"\n        Build query and passes to `Elasticsearch`, then returns the raw\n        format returned.\n        \"\"\"\n        es = self.get_es()\n\n        params = dict(self.query_params)\n        mlt_fields = self.mlt_fields or params.pop('mlt_fields', [])\n\n        body = self.s.build_search() if self.s else ''\n\n        hits = es.mlt(\n            index=self.index, doc_type=self.doctype, id=self.id,\n            mlt_fields=mlt_fields, body=body, **params)\n\n        log.debug(hits)\n\n        return hits", "title": ""}
{"_id": "d10668", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d10669", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d10670", "text": "def push(h, x):\n    \"\"\"Push a new value into heap.\"\"\"\n    h.push(x)\n    up(h, h.size()-1)", "title": ""}
{"_id": "d10671", "text": "def validate_email(email):\n    \"\"\"\n    Validates an email address\n    Source: Himanshu Shankar (https://github.com/iamhssingh)\n    Parameters\n    ----------\n    email: str\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    from django.core.validators import validate_email\n    from django.core.exceptions import ValidationError\n    try:\n        validate_email(email)\n        return True\n    except ValidationError:\n        return False", "title": ""}
{"_id": "d10672", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d10673", "text": "def email_user(self, subject, message, from_email=None):\n        \"\"\" Send an email to this User.\"\"\"\n        send_mail(subject, message, from_email, [self.email])", "title": ""}
{"_id": "d10674", "text": "def update_scale(self, value):\n        \"\"\" updates the scale of all actors in the plotter \"\"\"\n        self.plotter.set_scale(self.x_slider_group.value,\n                               self.y_slider_group.value,\n                               self.z_slider_group.value)", "title": ""}
{"_id": "d10675", "text": "def pass_from_pipe(cls):\n        \"\"\"Return password from pipe if not on TTY, else False.\n        \"\"\"\n        is_pipe = not sys.stdin.isatty()\n        return is_pipe and cls.strip_last_newline(sys.stdin.read())", "title": ""}
{"_id": "d10676", "text": "def as_tuple(self, value):\n        \"\"\"Utility function which converts lists to tuples.\"\"\"\n        if isinstance(value, list):\n            value = tuple(value)\n        return value", "title": ""}
{"_id": "d10677", "text": "def selectin(table, field, value, complement=False):\n    \"\"\"Select rows where the given field is a member of the given value.\"\"\"\n\n    return select(table, field, lambda v: v in value,\n                  complement=complement)", "title": ""}
{"_id": "d10678", "text": "def move_datetime_year(dt, direction, num_shifts):\n    \"\"\"\n    Move datetime 1 year in the chosen direction.\n    unit is a no-op, to keep the API the same as the day case\n    \"\"\"\n    delta = relativedelta(years=+num_shifts)\n    return _move_datetime(dt, direction, delta)", "title": ""}
{"_id": "d10679", "text": "def quote(s, unsafe='/'):\n    \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n    encoded value as the value.\"\"\"\n    res = s.replace('%', '%25')\n    for c in unsafe:\n        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n    return res", "title": ""}
{"_id": "d10680", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d10681", "text": "def escapePathForShell(path):\n\t\t\"\"\"\n\t\tEscapes a filesystem path for use as a command-line argument\n\t\t\"\"\"\n\t\tif platform.system() == 'Windows':\n\t\t\treturn '\"{}\"'.format(path.replace('\"', '\"\"'))\n\t\telse:\n\t\t\treturn shellescape.quote(path)", "title": ""}
{"_id": "d10682", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d10683", "text": "def is_punctuation(text):\n    \"\"\"Check if given string is a punctuation\"\"\"\n    return not (text.lower() in config.AVRO_VOWELS or\n                text.lower() in config.AVRO_CONSONANTS)", "title": ""}
{"_id": "d10684", "text": "def getpackagepath():\n    \"\"\"\n     *Get the root path for this python package - used in unit testing code*\n    \"\"\"\n    moduleDirectory = os.path.dirname(__file__)\n    packagePath = os.path.dirname(__file__) + \"/../\"\n\n    return packagePath", "title": ""}
{"_id": "d10685", "text": "def is_json_file(filename, show_warnings = False):\n    \"\"\"Check configuration file type is JSON\n    Return a boolean indicating wheather the file is JSON format or not\n    \"\"\"\n    try:\n        config_dict = load_config(filename, file_type = \"json\")\n        is_json = True\n    except:\n        is_json = False\n    return(is_json)", "title": ""}
{"_id": "d10686", "text": "def full(self):\n        \"\"\"Return True if the queue is full\"\"\"\n        if not self.size: return False\n        return len(self.pq) == (self.size + self.removed_count)", "title": ""}
{"_id": "d10687", "text": "def prepare_query_params(**kwargs):\n    \"\"\"\n    Prepares given parameters to be used in querystring.\n    \"\"\"\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    ]", "title": ""}
{"_id": "d10688", "text": "def is_non_empty_string(input_string):\n    \"\"\"\n    Validate if non empty string\n\n    :param input_string: Input is a *str*.\n    :return: True if input is string and non empty.\n       Raise :exc:`Exception` otherwise.\n    \"\"\"\n    try:\n        if not input_string.strip():\n            raise ValueError()\n    except AttributeError as error:\n        raise TypeError(error)\n\n    return True", "title": ""}
{"_id": "d10689", "text": "def _expand(self, str, local_vars={}):\n        \"\"\"Expand $vars in a string.\"\"\"\n        return ninja_syntax.expand(str, self.vars, local_vars)", "title": ""}
{"_id": "d10690", "text": "def register_extension_class(ext, base, *args, **kwargs):\n    \"\"\"Instantiate the given extension class and register as a public attribute of the given base.\n\n    README: The expected protocol here is to instantiate the given extension and pass the base\n    object as the first positional argument, then unpack args and kwargs as additional arguments to\n    the extension's constructor.\n    \"\"\"\n    ext_instance = ext.plugin(base, *args, **kwargs)\n    setattr(base, ext.name.lstrip('_'), ext_instance)", "title": ""}
{"_id": "d10691", "text": "def is_readable(filename):\n    \"\"\"Check if file is a regular file and is readable.\"\"\"\n    return os.path.isfile(filename) and os.access(filename, os.R_OK)", "title": ""}
{"_id": "d10692", "text": "def flattened_nested_key_indices(nested_dict):\n    \"\"\"\n    Combine the outer and inner keys of nested dictionaries into a single\n    ordering.\n    \"\"\"\n    outer_keys, inner_keys = collect_nested_keys(nested_dict)\n    combined_keys = list(sorted(set(outer_keys + inner_keys)))\n    return {k: i for (i, k) in enumerate(combined_keys)}", "title": ""}
{"_id": "d10693", "text": "def is_sequence(obj):\n    \"\"\"Check if `obj` is a sequence, but not a string or bytes.\"\"\"\n    return isinstance(obj, Sequence) and not (\n        isinstance(obj, str) or BinaryClass.is_valid_type(obj))", "title": ""}
{"_id": "d10694", "text": "def extract_keywords_from_text(self, text):\n        \"\"\"Method to extract keywords from the text provided.\n\n        :param text: Text to extract keywords from, provided as a string.\n        \"\"\"\n        sentences = nltk.tokenize.sent_tokenize(text)\n        self.extract_keywords_from_sentences(sentences)", "title": ""}
{"_id": "d10695", "text": "def is_nullable_list(val, vtype):\n    \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n    return (isinstance(val, list) and\n            any(isinstance(v, vtype) for v in val) and\n            all((isinstance(v, vtype) or v is None) for v in val))", "title": ""}
{"_id": "d10696", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d10697", "text": "def is_number(obj):\n    \"\"\"Check if obj is number.\"\"\"\n    return isinstance(obj, (int, float, np.int_, np.float_))", "title": ""}
{"_id": "d10698", "text": "def ffmpeg_works():\n  \"\"\"Tries to encode images with ffmpeg to check if it 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", "title": ""}
{"_id": "d10699", "text": "def inside_softimage():\n    \"\"\"Returns a boolean indicating if the code is executed 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", "title": ""}
{"_id": "d10700", "text": "def copyFile(input, output, replace=None):\n    \"\"\"Copy a file whole from input to output.\"\"\"\n\n    _found = findFile(output)\n    if not _found or (_found and replace):\n        shutil.copy2(input, output)", "title": ""}
{"_id": "d10701", "text": "def is_file(path):\n    \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n    try:\n        return path.expanduser().absolute().is_file()\n    except AttributeError:\n        return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))", "title": ""}
{"_id": "d10702", "text": "def get_remote_content(filepath):\n        \"\"\" A handy wrapper to get a remote file content \"\"\"\n        with hide('running'):\n            temp = BytesIO()\n            get(filepath, temp)\n            content = temp.getvalue().decode('utf-8')\n        return content.strip()", "title": ""}
{"_id": "d10703", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d10704", "text": "def create_movie(fig, update_figure, filename, title, fps=15, dpi=100):\n    \"\"\"Helps us to create a movie.\"\"\"\n    FFMpegWriter = manimation.writers['ffmpeg']\n    metadata     = dict(title=title)\n    writer       = FFMpegWriter(fps=fps, metadata=metadata)\n\n    with writer.saving(fig, filename, dpi):\n        t = 0\n        while True:\n            if update_figure(t):\n                writer.grab_frame()\n                t += 1\n            else:\n                break", "title": ""}
{"_id": "d10705", "text": "def any_contains_any(strings, candidates):\n    \"\"\"Whether any of the strings contains any of the candidates.\"\"\"\n    for string in strings:\n        for c in candidates:\n            if c in string:\n                return True", "title": ""}
{"_id": "d10706", "text": "def log_magnitude_spectrum(frames):\n    \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))", "title": ""}
{"_id": "d10707", "text": "def is_symbol(string):\n    \"\"\"\n    Return true if the string is a mathematical symbol.\n    \"\"\"\n    return (\n        is_int(string) or is_float(string) or\n        is_constant(string) or is_unary(string) or\n        is_binary(string) or\n        (string == '(') or (string == ')')\n    )", "title": ""}
{"_id": "d10708", "text": "def log_magnitude_spectrum(frames):\n    \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))", "title": ""}
{"_id": "d10709", "text": "def check_empty_dict(GET_dict):\n    \"\"\"\n    Returns True if the GET querstring contains on values, but it can contain\n    empty keys.\n    This is better than doing not bool(request.GET) as an empty key will return\n    True\n    \"\"\"\n    empty = True\n    for k, v in GET_dict.items():\n        # Don't disable on p(age) or 'all' GET param\n        if v and k != 'p' and k != 'all':\n            empty = False\n    return empty", "title": ""}
{"_id": "d10710", "text": "def log_magnitude_spectrum(frames):\n    \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))", "title": ""}
{"_id": "d10711", "text": "def is_lazy_iterable(obj):\n    \"\"\"\n    Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n    \"\"\"\n    return isinstance(obj,\n        (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))", "title": ""}
{"_id": "d10712", "text": "def rfft2d_freqs(h, w):\n    \"\"\"Computes 2D spectrum frequencies.\"\"\"\n\n    fy = np.fft.fftfreq(h)[:, None]\n    # when we have an odd input dimension we need to keep one additional\n    # frequency and later cut off 1 pixel\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)", "title": ""}
{"_id": "d10713", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d10714", "text": "def load(cls,filename):\n        \"\"\"Load from stored files\"\"\"\n        filename = cls.correct_file_extension(filename)\n        with open(filename,'rb') as f:\n            return pickle.load(f)", "title": ""}
{"_id": "d10715", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d10716", "text": "def lower_ext(abspath):\n    \"\"\"Convert file extension to lowercase.\n    \"\"\"\n    fname, ext = os.path.splitext(abspath)\n    return fname + ext.lower()", "title": ""}
{"_id": "d10717", "text": "def get_free_memory_win():\n    \"\"\"Return current free memory on the machine for windows.\n\n    Warning : this script is really not robust\n    Return in MB unit\n    \"\"\"\n    stat = MEMORYSTATUSEX()\n    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n    return int(stat.ullAvailPhys / 1024 / 1024)", "title": ""}
{"_id": "d10718", "text": "def file_writelines_flush_sync(path, lines):\n    \"\"\"\n    Fill file at @path with @lines then flush all buffers\n    (Python and system buffers)\n    \"\"\"\n    fp = open(path, 'w')\n    try:\n        fp.writelines(lines)\n        flush_sync_file_object(fp)\n    finally:\n        fp.close()", "title": ""}
{"_id": "d10719", "text": "def service_available(service_name):\n    \"\"\"Determine whether a system service is available\"\"\"\n    try:\n        subprocess.check_output(\n            ['service', service_name, 'status'],\n            stderr=subprocess.STDOUT).decode('UTF-8')\n    except subprocess.CalledProcessError as e:\n        return b'unrecognized service' not in e.output\n    else:\n        return True", "title": ""}
{"_id": "d10720", "text": "def last(self):\n        \"\"\"Get the last object in file.\"\"\"\n        # End of file\n        self.__file.seek(0, 2)\n\n        # Get the last struct\n        data = self.get(self.length - 1)\n\n        return data", "title": ""}
{"_id": "d10721", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d10722", "text": "def selectin(table, field, value, complement=False):\n    \"\"\"Select rows where the given field is a member of the given value.\"\"\"\n\n    return select(table, field, lambda v: v in value,\n                  complement=complement)", "title": ""}
{"_id": "d10723", "text": "def example_write_file_to_disk_if_changed():\n    \"\"\" Try to remove all comments from a file, and save it if changes were made. \"\"\"\n    my_file = FileAsObj('/tmp/example_file.txt')\n    my_file.rm(my_file.egrep('^#'))\n    if my_file.changed:\n        my_file.save()", "title": ""}
{"_id": "d10724", "text": "def cleanLines(source, lineSep=os.linesep):\n    \"\"\"\n    :param source: some iterable source (list, file, etc)\n    :param lineSep: string of separators (chars) that must be removed\n    :return: list of non empty lines with removed separators\n    \"\"\"\n    stripped = (line.strip(lineSep) for line in source)\n    return (line for line in stripped if len(line) != 0)", "title": ""}
{"_id": "d10725", "text": "def cmp_contents(filename1, filename2):\n    \"\"\" Returns True if contents of the files are the same\n\n    Parameters\n    ----------\n    filename1 : str\n        filename of first file to compare\n    filename2 : str\n        filename of second file to compare\n\n    Returns\n    -------\n    tf : bool\n        True if binary contents of `filename1` is same as binary contents of\n        `filename2`, False otherwise.\n    \"\"\"\n    with open_readable(filename1, 'rb') as fobj:\n        contents1 = fobj.read()\n    with open_readable(filename2, 'rb') as fobj:\n        contents2 = fobj.read()\n    return contents1 == contents2", "title": ""}
{"_id": "d10726", "text": "def _removeStopwords(text_list):\n    \"\"\"\n    Removes stopwords contained in a list of words.\n\n    :param text_string: A list of strings.\n    :type text_string: list.\n\n    :returns: The input ``text_list`` with stopwords removed.\n    :rtype: list\n    \"\"\"\n\n    output_list = []\n\n    for word in text_list:\n        if word.lower() not in _stopwords:\n            output_list.append(word)\n\n    return output_list", "title": ""}
{"_id": "d10727", "text": "def boxes_intersect(box1, box2):\n    \"\"\"Determines if two rectangles, each input as a tuple\n        (xmin, xmax, ymin, ymax), intersect.\"\"\"\n    xmin1, xmax1, ymin1, ymax1 = box1\n    xmin2, xmax2, ymin2, ymax2 = box2\n    if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \\\n            interval_intersection_width(ymin1, ymax1, ymin2, ymax2):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d10728", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d10729", "text": "def is_archlinux():\n    \"\"\"return True if the current distribution is running on debian like OS.\"\"\"\n    if platform.system().lower() == 'linux':\n        if platform.linux_distribution() == ('', '', ''):\n            # undefined distribution. Fixed in python 3.\n            if os.path.exists('/etc/arch-release'):\n                return True\n    return False", "title": ""}
{"_id": "d10730", "text": "def __exit__(self, type, value, traceback):\n        \"\"\"When the `with` statement ends.\"\"\"\n\n        if not self.asarfile:\n            return\n\n        self.asarfile.close()\n        self.asarfile = None", "title": ""}
{"_id": "d10731", "text": "def local_minima(img, min_distance = 4):\n    r\"\"\"\n    Returns all local minima from an image.\n    \n    Parameters\n    ----------\n    img : array_like\n        The image.\n    min_distance : integer\n        The minimal distance between the minimas in voxels. If it is less, only the lower minima is returned.\n    \n    Returns\n    -------\n    indices : sequence\n        List of all minima indices.\n    values : sequence\n        List of all minima values.\n    \"\"\"\n    # @TODO: Write a unittest for this.\n    fits = numpy.asarray(img)\n    minfits = minimum_filter(fits, size=min_distance) # default mode is reflect\n    minima_mask = fits == minfits\n    good_indices = numpy.transpose(minima_mask.nonzero())\n    good_fits = fits[minima_mask]\n    order = good_fits.argsort()\n    return good_indices[order], good_fits[order]", "title": ""}
{"_id": "d10732", "text": "def on_source_directory_chooser_clicked(self):\n        \"\"\"Autoconnect slot activated when tbSourceDir is clicked.\"\"\"\n\n        title = self.tr('Set the source directory for script and scenario')\n        self.choose_directory(self.source_directory, title)", "title": ""}
{"_id": "d10733", "text": "def monthly(date=datetime.date.today()):\n    \"\"\"\n    Take a date object and return the first day of the month.\n    \"\"\"\n    return datetime.date(date.year, date.month, 1)", "title": ""}
{"_id": "d10734", "text": "def revnet_164_cifar():\n  \"\"\"Tiny hparams suitable for CIFAR/etc.\"\"\"\n  hparams = revnet_cifar_base()\n  hparams.bottleneck = True\n  hparams.num_channels = [16, 32, 64]\n  hparams.num_layers_per_block = [8, 8, 8]\n  return hparams", "title": ""}
{"_id": "d10735", "text": "def type(self):\n        \"\"\"Returns type of the data for the given FeatureType.\"\"\"\n        if self is FeatureType.TIMESTAMP:\n            return list\n        if self is FeatureType.BBOX:\n            return BBox\n        return dict", "title": ""}
{"_id": "d10736", "text": "def _clear(self):\n        \"\"\"Resets all assigned data for the current message.\"\"\"\n        self._finished = False\n        self._measurement = None\n        self._message = None\n        self._message_body = None", "title": ""}
{"_id": "d10737", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d10738", "text": "def free(self):\n        \"\"\"Free the underlying C array\"\"\"\n        if self._ptr is None:\n            return\n        Gauged.array_free(self.ptr)\n        FloatArray.ALLOCATIONS -= 1\n        self._ptr = None", "title": ""}
{"_id": "d10739", "text": "def check_empty_dict(GET_dict):\n    \"\"\"\n    Returns True if the GET querstring contains on values, but it can contain\n    empty keys.\n    This is better than doing not bool(request.GET) as an empty key will return\n    True\n    \"\"\"\n    empty = True\n    for k, v in GET_dict.items():\n        # Don't disable on p(age) or 'all' GET param\n        if v and k != 'p' and k != 'all':\n            empty = False\n    return empty", "title": ""}
{"_id": "d10740", "text": "def do_exit(self, arg):\n        \"\"\"Exit the shell session.\"\"\"\n\n        if self.current:\n            self.current.close()\n        self.resource_manager.close()\n        del self.resource_manager\n        return True", "title": ""}
{"_id": "d10741", "text": "def handleFlaskPostRequest(flaskRequest, endpoint):\n    \"\"\"\n    Handles the specified flask request for one of the POST URLS\n    Invokes the specified endpoint to generate a response.\n    \"\"\"\n    if flaskRequest.method == \"POST\":\n        return handleHttpPost(flaskRequest, endpoint)\n    elif flaskRequest.method == \"OPTIONS\":\n        return handleHttpOptions()\n    else:\n        raise exceptions.MethodNotAllowedException()", "title": ""}
{"_id": "d10742", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d10743", "text": "def home():\n    \"\"\"Temporary helper function to link to the API routes\"\"\"\n    return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \\\n        HTTPStatus.OK", "title": ""}
{"_id": "d10744", "text": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "title": ""}
{"_id": "d10745", "text": "def _has_fr_route(self):\n        \"\"\"Encapsulating the rules for whether the request was to a Flask endpoint\"\"\"\n        # 404's, 405's, which might not have a url_rule\n        if self._should_use_fr_error_handler():\n            return True\n        # for all other errors, just check if FR dispatched the route\n        if not request.url_rule:\n            return False\n        return self.owns_endpoint(request.url_rule.endpoint)", "title": ""}
{"_id": "d10746", "text": "def palettebar(height, length, colormap):\n    \"\"\"Return the channels of a palettebar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.palettize(cbar)", "title": ""}
{"_id": "d10747", "text": "def __call__(self, r):\n        \"\"\"Update the request headers.\"\"\"\n        r.headers['Authorization'] = 'JWT {jwt}'.format(jwt=self.token)\n        return r", "title": ""}
{"_id": "d10748", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d10749", "text": "def do_restart(self, line):\n        \"\"\"Request that the Outstation perform a cold restart. Command syntax is: restart\"\"\"\n        self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)", "title": ""}
{"_id": "d10750", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d10751", "text": "def flatten(nested):\n    \"\"\" Return a flatten version of the nested argument \"\"\"\n    flat_return = list()\n\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\n    __inner_flat(nested,flat_return)\n\n    return flat_return", "title": ""}
{"_id": "d10752", "text": "def clear():\n    \"\"\"Clears the console.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        call(\"cls\", shell=True)\n    else:\n        call(\"clear\", shell=True)", "title": ""}
{"_id": "d10753", "text": "def flatten(nested):\n    \"\"\" Return a flatten version of the nested argument \"\"\"\n    flat_return = list()\n\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\n    __inner_flat(nested,flat_return)\n\n    return flat_return", "title": ""}
{"_id": "d10754", "text": "def test(ctx, all=False, verbose=False):\n    \"\"\"Run the tests.\"\"\"\n    cmd = 'tox' if all else 'py.test'\n    if verbose:\n        cmd += ' -v'\n    return ctx.run(cmd, pty=True).return_code", "title": ""}
{"_id": "d10755", "text": "def _euclidean_dist(vector_a, vector_b):\n    \"\"\"\n    :param vector_a:    A list of numbers.\n    :param vector_b:    A list of numbers.\n    :returns:           The euclidean distance between the two vectors.\n    \"\"\"\n    dist = 0\n    for (x, y) in zip(vector_a, vector_b):\n        dist += (x-y)*(x-y)\n    return math.sqrt(dist)", "title": ""}
{"_id": "d10756", "text": "def flatten(lis):\n    \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n    new_lis = []\n    for item in lis:\n        if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n            new_lis.extend(flatten(item))\n        else:\n            new_lis.append(item)\n    return new_lis", "title": ""}
{"_id": "d10757", "text": "def is_iter_non_string(obj):\n    \"\"\"test if object is a list or tuple\"\"\"\n    if isinstance(obj, list) or isinstance(obj, tuple):\n        return True\n    return False", "title": ""}
{"_id": "d10758", "text": "def imflip(img, direction='horizontal'):\n    \"\"\"Flip an image horizontally or vertically.\n\n    Args:\n        img (ndarray): Image to be flipped.\n        direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n    Returns:\n        ndarray: The flipped image.\n    \"\"\"\n    assert direction in ['horizontal', 'vertical']\n    if direction == 'horizontal':\n        return np.flip(img, axis=1)\n    else:\n        return np.flip(img, axis=0)", "title": ""}
{"_id": "d10759", "text": "def compare(a, b):\n    \"\"\"\n     Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))\n    \"\"\"\n    s=0\n    for i in range(len(a)):\n        s=s+abs(a[i]-b[i])\n    return s", "title": ""}
{"_id": "d10760", "text": "def enable_writes(self):\n        \"\"\"Restores the state of the batched queue for writing.\"\"\"\n        self.write_buffer = []\n        self.flush_lock = threading.RLock()\n        self.flush_thread = FlushThread(self.max_batch_time,\n                                        self._flush_writes)", "title": ""}
{"_id": "d10761", "text": "def is_int(string):\n    \"\"\"\n    Checks if a string is an integer. If the string value is an integer\n    return True, otherwise return False. \n    \n    Args:\n        string: a string to test.\n\n    Returns: \n        boolean\n    \"\"\"\n    try:\n        a = float(string)\n        b = int(a)\n    except ValueError:\n        return False\n    else:\n        return a == b", "title": ""}
{"_id": "d10762", "text": "def enable_writes(self):\n        \"\"\"Restores the state of the batched queue for writing.\"\"\"\n        self.write_buffer = []\n        self.flush_lock = threading.RLock()\n        self.flush_thread = FlushThread(self.max_batch_time,\n                                        self._flush_writes)", "title": ""}
{"_id": "d10763", "text": "def compressBuffer(buffer):\n    \"\"\"\n    Note that this code compresses into a buffer held in memory, rather\n    than a disk file. This is done through the use of cStringIO.StringIO().\n    \"\"\"\n    # http://jython.xhaus.com/http-compression-in-python-and-jython/\n    zbuf = cStringIO.StringIO()\n    zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)\n    zfile.write(buffer)\n    zfile.close()\n    return zbuf.getvalue()", "title": ""}
{"_id": "d10764", "text": "def setLib(self, lib):\n        \"\"\" Copy the lib items into our font. \"\"\"\n        for name, item in lib.items():\n            self.font.lib[name] = item", "title": ""}
{"_id": "d10765", "text": "def EvalPoissonPmf(k, lam):\n    \"\"\"Computes the Poisson PMF.\n\n    k: number of events\n    lam: parameter lambda in events per unit time\n\n    returns: float probability\n    \"\"\"\n    # don't use the scipy function (yet).  for lam=0 it returns NaN;\n    # should be 0.0\n    # return scipy.stats.poisson.pmf(k, lam)\n\n    return lam ** k * math.exp(-lam) / math.factorial(k)", "title": ""}
{"_id": "d10766", "text": "def tf2():\n  \"\"\"Provide the root module of a TF-2.0 API for use within TensorBoard.\n\n  Returns:\n    The root module of a TF-2.0 API, if available.\n\n  Raises:\n    ImportError: if a TF-2.0 API is not available.\n  \"\"\"\n  # Import the `tf` compat API from this file and check if it's already TF 2.0.\n  if tf.__version__.startswith('2.'):\n    return tf\n  elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):\n    # As a fallback, try `tensorflow.compat.v2` if it's defined.\n    return tf.compat.v2\n  raise ImportError('cannot import tensorflow 2.0 API')", "title": ""}
{"_id": "d10767", "text": "def _eager_tasklet(tasklet):\n  \"\"\"Decorator to turn tasklet to run eagerly.\"\"\"\n\n  @utils.wrapping(tasklet)\n  def eager_wrapper(*args, **kwds):\n    fut = tasklet(*args, **kwds)\n    _run_until_rpc()\n    return fut\n\n  return eager_wrapper", "title": ""}
{"_id": "d10768", "text": "def tpr(y, z):\n    \"\"\"True positive rate `tp / (tp + fn)`\n    \"\"\"\n    tp, tn, fp, fn = contingency_table(y, z)\n    return tp / (tp + fn)", "title": ""}
{"_id": "d10769", "text": "def copy(self):\n        \"\"\"Return a copy of this list with each element copied to new memory\n        \"\"\"\n        out = type(self)()\n        for series in self:\n            out.append(series.copy())\n        return out", "title": ""}
{"_id": "d10770", "text": "def connect(host, port, username, password):\n        \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n        # Instantiate ftplib client\n        session = ftplib.FTP()\n\n        # Connect to host without auth\n        session.connect(host, port)\n\n        # Authenticate connection\n        session.login(username, password)\n        return session", "title": ""}
{"_id": "d10771", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d10772", "text": "def connect(host, port, username, password):\n        \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n        # Instantiate ftplib client\n        session = ftplib.FTP()\n\n        # Connect to host without auth\n        session.connect(host, port)\n\n        # Authenticate connection\n        session.login(username, password)\n        return session", "title": ""}
{"_id": "d10773", "text": "def __len__(self):\n        \"\"\" This will equal 124 for the V1 database. \"\"\"\n        length = 0\n        for typ, siz, _ in self.format:\n            length += siz\n        return length", "title": ""}
{"_id": "d10774", "text": "def computeDelaunayTriangulation(points):\n    \"\"\" Takes a list of point objects (which must have x and y fields).\n        Returns a list of 3-tuples: the indices of the points that form a\n        Delaunay triangle.\n    \"\"\"\n    siteList = SiteList(points)\n    context  = Context()\n    context.triangulate = True\n    voronoi(siteList,context)\n    return context.triangles", "title": ""}
{"_id": "d10775", "text": "def serialize(self, value):\n        \"\"\"Takes a datetime object and returns a string\"\"\"\n        if isinstance(value, str):\n            return value\n        return value.strftime(DATETIME_FORMAT)", "title": ""}
{"_id": "d10776", "text": "def wrap_count(method):\n    \"\"\"\n    Returns number of wraps around given method.\n    \"\"\"\n    number = 0\n    while hasattr(method, '__aspects_orig'):\n        number += 1\n        method = method.__aspects_orig\n    return number", "title": ""}
{"_id": "d10777", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d10778", "text": "def GetIndentLevel(line):\n  \"\"\"Return the number of leading spaces in line.\n\n  Args:\n    line: A string to check.\n\n  Returns:\n    An integer count of leading spaces, possibly zero.\n  \"\"\"\n  indent = Match(r'^( *)\\S', line)\n  if indent:\n    return len(indent.group(1))\n  else:\n    return 0", "title": ""}
{"_id": "d10779", "text": "def fmt_sz(intval):\n    \"\"\" Format a byte sized value.\n    \"\"\"\n    try:\n        return fmt.human_size(intval)\n    except (ValueError, TypeError):\n        return \"N/A\".rjust(len(fmt.human_size(0)))", "title": ""}
{"_id": "d10780", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d10781", "text": "def csvpretty(csvfile: csvfile=sys.stdin):\n    \"\"\" Pretty print a CSV file. \"\"\"\n    shellish.tabulate(csv.reader(csvfile))", "title": ""}
{"_id": "d10782", "text": "def count(data, axis=None):\n    \"\"\"Count the number of non-NA in this array along the given axis or axes\n    \"\"\"\n    return np.sum(np.logical_not(isnull(data)), axis=axis)", "title": ""}
{"_id": "d10783", "text": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "title": ""}
{"_id": "d10784", "text": "def count(lines):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  words = [w for l in lines for w in l.strip().split()]\n  return Counter(words)", "title": ""}
{"_id": "d10785", "text": "def align_file_position(f, size):\n    \"\"\" Align the position in the file to the next block of specified size \"\"\"\n    align = (size - 1) - (f.tell() % size)\n    f.seek(align, 1)", "title": ""}
{"_id": "d10786", "text": "def get_area(self):\n        \"\"\"Calculate area of bounding box.\"\"\"\n        return (self.p2.x-self.p1.x)*(self.p2.y-self.p1.y)", "title": ""}
{"_id": "d10787", "text": "def connect(host, port, username, password):\n        \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n        # Instantiate ftplib client\n        session = ftplib.FTP()\n\n        # Connect to host without auth\n        session.connect(host, port)\n\n        # Authenticate connection\n        session.login(username, password)\n        return session", "title": ""}
{"_id": "d10788", "text": "def test_python_java_rt():\n    \"\"\" Run Python test cases against Java runtime classes. \"\"\"\n    sub_env = {'PYTHONPATH': _build_dir()}\n\n    log.info('Executing Python unit tests (against Java runtime classes)...')\n    return jpyutil._execute_python_scripts(python_java_rt_tests,\n                                           env=sub_env)", "title": ""}
{"_id": "d10789", "text": "def __call__(self, func, *args, **kwargs):\n        \"\"\"Shorcut for self.run.\"\"\"\n        return self.run(func, *args, **kwargs)", "title": ""}
{"_id": "d10790", "text": "def touch():\n    \"\"\"Create new bucket.\"\"\"\n    from .models import Bucket\n    bucket = Bucket.create()\n    db.session.commit()\n    click.secho(str(bucket), fg='green')", "title": ""}
{"_id": "d10791", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d10792", "text": "def print(*a):\n    \"\"\" print just one that returns what you give it instead of None \"\"\"\n    try:\n        _print(*a)\n        return a[0] if len(a) == 1 else a\n    except:\n        _print(*a)", "title": ""}
{"_id": "d10793", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d10794", "text": "def _callable_once(func):\n    \"\"\" Returns a function that is only callable once; any other call will do nothing \"\"\"\n\n    def once(*args, **kwargs):\n        if not once.called:\n            once.called = True\n            return func(*args, **kwargs)\n\n    once.called = False\n    return once", "title": ""}
{"_id": "d10795", "text": "def random_letters(n):\n    \"\"\"\n    Generate a random string from a-zA-Z\n    :param n: length of the string\n    :return: the random string\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(n))", "title": ""}
{"_id": "d10796", "text": "def _iterable_to_varargs_method(func):\n    \"\"\"decorator to convert a method taking a iterable to a *args one\"\"\"\n    def wrapped(self, *args, **kwargs):\n        return func(self, args, **kwargs)\n    return wrapped", "title": ""}
{"_id": "d10797", "text": "def finish_plot():\n    \"\"\"Helper for plotting.\"\"\"\n    plt.legend()\n    plt.grid(color='0.7')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.show()", "title": ""}
{"_id": "d10798", "text": "def calculate_month(birth_date):\n    \"\"\"\n    Calculates and returns a month number basing on PESEL standard.\n    \"\"\"\n    year = int(birth_date.strftime('%Y'))\n    month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20\n\n    return month", "title": ""}
{"_id": "d10799", "text": "def _dump_spec(spec):\n    \"\"\"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.\n    \"\"\"\n    with open(\"spec.yaml\", \"w\") as f:\n        yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False)", "title": ""}
{"_id": "d10800", "text": "def sent2features(sentence, template):\n    \"\"\" extract features in a sentence\n\n    :type sentence: list of token, each token is a list of tag\n    \"\"\"\n    return [word2features(sentence, i, template) for i in range(len(sentence))]", "title": ""}
{"_id": "d10801", "text": "def AddAccuracy(model, softmax, label):\n    \"\"\"Adds an accuracy op to the model\"\"\"\n    accuracy = brew.accuracy(model, [softmax, label], \"accuracy\")\n    return accuracy", "title": ""}
{"_id": "d10802", "text": "def get_selection_owner(self, selection):\n        \"\"\"Return the window that owns selection (an atom), or X.NONE if\n        there is no owner for the selection. Can raise BadAtom.\"\"\"\n        r = request.GetSelectionOwner(display = self.display,\n                                      selection = selection)\n        return r.owner", "title": ""}
{"_id": "d10803", "text": "def _single_page_pdf(page):\n    \"\"\"Construct a single page PDF from the provided page in memory\"\"\"\n    pdf = Pdf.new()\n    pdf.pages.append(page)\n    bio = BytesIO()\n    pdf.save(bio)\n    bio.seek(0)\n    return bio.read()", "title": ""}
{"_id": "d10804", "text": "def setup(self, pin, mode, pull_up_down=PUD_OFF):\n        \"\"\"Set the input or output mode for a specified pin.  Mode should be\n        either OUTPUT or INPUT.\n        \"\"\"\n        self.rpi_gpio.setup(pin, self._dir_mapping[mode],\n                            pull_up_down=self._pud_mapping[pull_up_down])", "title": ""}
{"_id": "d10805", "text": "def direct2dDistance(self, point):\n        \"\"\"consider the distance between two mapPoints, ignoring all terrain, pathing issues\"\"\"\n        if not isinstance(point, MapPoint): return 0.0\n        return  ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula", "title": ""}
{"_id": "d10806", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d10807", "text": "def LinSpace(start, stop, num):\n    \"\"\"\n    Linspace op.\n    \"\"\"\n    return np.linspace(start, stop, num=num, dtype=np.float32),", "title": ""}
{"_id": "d10808", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d10809", "text": "def write_property(fh, key, value):\n  \"\"\"\n    Write a single property to the file in Java properties format.\n\n    :param fh: a writable file-like object\n    :param key: the key to write\n    :param value: the value to write\n  \"\"\"\n  if key is COMMENT:\n    write_comment(fh, value)\n    return\n\n  _require_string(key, 'keys')\n  _require_string(value, 'values')\n\n  fh.write(_escape_key(key))\n  fh.write(b'=')\n  fh.write(_escape_value(value))\n  fh.write(b'\\n')", "title": ""}
{"_id": "d10810", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d10811", "text": "def ruler_line(self, widths, linetype='-'):\n        \"\"\"Generates a ruler line for separating rows from each other\"\"\"\n        cells = []\n        for w in widths:\n            cells.append(linetype * (w+2))\n        return '+' + '+'.join(cells) + '+'", "title": ""}
{"_id": "d10812", "text": "def smooth_gaussian(image, sigma=1):\n    \"\"\"Returns Gaussian smoothed image.\n\n    :param image: numpy array or :class:`jicimagelib.image.Image`\n    :param sigma: standard deviation\n    :returns: :class:`jicimagelib.image.Image`\n    \"\"\"\n    return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode=\"nearest\")", "title": ""}
{"_id": "d10813", "text": "def _trim(image):\n    \"\"\"Trim a PIL image and remove white space.\"\"\"\n    background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n    diff = PIL.ImageChops.difference(image, background)\n    diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n    bbox = diff.getbbox()\n    if bbox:\n        image = image.crop(bbox)\n    return image", "title": ""}
{"_id": "d10814", "text": "def gauss_box_model(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5):\n    \"\"\"Integrate a Gaussian profile.\"\"\"\n    z = (x - mean) / stddev\n    z2 = z + hpix / stddev\n    z1 = z - hpix / stddev\n    return amplitude * (norm.cdf(z2) - norm.cdf(z1))", "title": ""}
{"_id": "d10815", "text": "def smooth_gaussian(image, sigma=1):\n    \"\"\"Returns Gaussian smoothed image.\n\n    :param image: numpy array or :class:`jicimagelib.image.Image`\n    :param sigma: standard deviation\n    :returns: :class:`jicimagelib.image.Image`\n    \"\"\"\n    return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode=\"nearest\")", "title": ""}
{"_id": "d10816", "text": "def cumsum(inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1, len(newlist)):\n        newlist[i] = newlist[i] + newlist[i - 1]\n    return newlist", "title": ""}
{"_id": "d10817", "text": "def cov_to_correlation(cov):\n    \"\"\"Compute the correlation matrix given the covariance matrix.\n\n    Parameters\n    ----------\n    cov : `~numpy.ndarray`\n        N x N matrix of covariances among N parameters.\n\n    Returns\n    -------\n    corr : `~numpy.ndarray`\n        N x N matrix of correlations among N parameters.\n    \"\"\"\n    err = np.sqrt(np.diag(cov))\n    errinv = np.ones_like(err) * np.nan\n    m = np.isfinite(err) & (err != 0)\n    errinv[m] = 1. / err[m]\n    corr = np.array(cov)\n    return corr * np.outer(errinv, errinv)", "title": ""}
{"_id": "d10818", "text": "def string_format_func(s):\n\t\"\"\"\n\tFunction used internally to format string data for output to XML.\n\tEscapes back-slashes and quotes, and wraps the resulting string in\n\tquotes.\n\t\"\"\"\n\treturn u\"\\\"%s\\\"\" % unicode(s).replace(u\"\\\\\", u\"\\\\\\\\\").replace(u\"\\\"\", u\"\\\\\\\"\")", "title": ""}
{"_id": "d10819", "text": "def directory_files(path):\n    \"\"\"Yield directory file names.\"\"\"\n\n    for entry in os.scandir(path):\n        if not entry.name.startswith('.') and entry.is_file():\n            yield entry.name", "title": ""}
{"_id": "d10820", "text": "def imdecode(image_path):\n    \"\"\"Return BGR image read by opencv\"\"\"\n    import os\n    assert os.path.exists(image_path), image_path + ' not found'\n    im = cv2.imread(image_path)\n    return im", "title": ""}
{"_id": "d10821", "text": "def save_image(pdf_path, img_path, page_num):\n    \"\"\"\n\n    Creates images for a page of the input pdf document and saves it\n    at img_path.\n\n    :param pdf_path: path to pdf to create images for.\n    :param img_path: path where to save the images.\n    :param page_num: page number to create image from in the pdf file.\n    :return:\n    \"\"\"\n    pdf_img = Image(filename=\"{}[{}]\".format(pdf_path, page_num))\n    with pdf_img.convert(\"png\") as converted:\n        # Set white background.\n        converted.background_color = Color(\"white\")\n        converted.alpha_channel = \"remove\"\n        converted.save(filename=img_path)", "title": ""}
{"_id": "d10822", "text": "def intersect(self, other):\n        \"\"\" Return a new :class:`DataFrame` containing rows only in\n        both this frame and another frame.\n\n        This is equivalent to `INTERSECT` in SQL.\n        \"\"\"\n        return DataFrame(self._jdf.intersect(other._jdf), self.sql_ctx)", "title": ""}
{"_id": "d10823", "text": "def random_int(self, min=0, max=9999, step=1):\n        \"\"\"\n        Returns a random integer between two values.\n\n        :param min: lower bound value (inclusive; default=0)\n        :param max: upper bound value (inclusive; default=9999)\n        :param step: range step (default=1)\n        :returns: random integer between min and max\n        \"\"\"\n        return self.generator.random.randrange(min, max + 1, step)", "title": ""}
{"_id": "d10824", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d10825", "text": "def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"Generate random id numbers.\"\"\"\n    return \"\".join(random.choice(chars) for x in range(size))", "title": ""}
{"_id": "d10826", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d10827", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d10828", "text": "def _parse(self, date_str, format='%Y-%m-%d'):\n        \"\"\"\n        helper function for parsing FRED date string into datetime\n        \"\"\"\n        rv = pd.to_datetime(date_str, format=format)\n        if hasattr(rv, 'to_pydatetime'):\n            rv = rv.to_pydatetime()\n        return rv", "title": ""}
{"_id": "d10829", "text": "def get_colors(img):\n    \"\"\"\n    Returns a list of all the image's colors.\n    \"\"\"\n    w, h = img.size\n    return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]", "title": ""}
{"_id": "d10830", "text": "def save_hdf(self,filename,path=''):\n        \"\"\"Saves all relevant data to .h5 file; so state can be restored.\n        \"\"\"\n        self.dataframe.to_hdf(filename,'{}/df'.format(path))", "title": ""}
{"_id": "d10831", "text": "def get_month_start_end_day():\n    \"\"\"\n    Get the month start date a nd end date\n    \"\"\"\n    t = date.today()\n    n = mdays[t.month]\n    return (date(t.year, t.month, 1), date(t.year, t.month, n))", "title": ""}
{"_id": "d10832", "text": "def batchify(data, batch_size):\n    \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n    nbatch = data.shape[0] // batch_size\n    data = data[:nbatch * batch_size]\n    data = data.reshape((batch_size, nbatch)).T\n    return data", "title": ""}
{"_id": "d10833", "text": "def bounding_box(img):\n    r\"\"\"\n    Return the bounding box incorporating all non-zero values in the image.\n    \n    Parameters\n    ----------\n    img : array_like\n        An array containing non-zero objects.\n        \n    Returns\n    -------\n    bbox : a list of slicer objects defining the bounding box\n    \"\"\"\n    locations = numpy.argwhere(img)\n    mins = locations.min(0)\n    maxs = locations.max(0) + 1\n    return [slice(x, y) for x, y in zip(mins, maxs)]", "title": ""}
{"_id": "d10834", "text": "def string_to_date(value):\n    \"\"\"\n    Return a Python date that corresponds to the specified string\n    representation.\n\n    @param value: string representation of a date.\n\n    @return: an instance ``datetime.datetime`` represented by the string.\n    \"\"\"\n    if isinstance(value, datetime.date):\n        return value\n\n    return dateutil.parser.parse(value).date()", "title": ""}
{"_id": "d10835", "text": "def dict_from_object(obj: object):\n    \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n    # If object is a dict instance, no need to convert.\n    return (obj if isinstance(obj, dict)\n            else {attr: getattr(obj, attr)\n                  for attr in dir(obj) if not attr.startswith('_')})", "title": ""}
{"_id": "d10836", "text": "def to_pydatetime(self):\n        \"\"\"\n        Converts datetimeoffset object into Python's datetime.datetime object\n        @return: time zone aware datetime.datetime\n        \"\"\"\n        dt = datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())\n        from .tz import FixedOffsetTimezone\n        return dt.replace(tzinfo=_utc).astimezone(FixedOffsetTimezone(self._offset))", "title": ""}
{"_id": "d10837", "text": "def getcoef(self):\n        \"\"\"Get final coefficient map array.\"\"\"\n\n        global mp_Z_Y1\n        return np.swapaxes(mp_Z_Y1, 0, self.xstep.cri.axisK+1)[0]", "title": ""}
{"_id": "d10838", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d10839", "text": "def isoformat(dt):\n    \"\"\"Return an ISO-8601 formatted string from the provided datetime object\"\"\"\n    if not isinstance(dt, datetime.datetime):\n        raise TypeError(\"Must provide datetime.datetime object to isoformat\")\n\n    if dt.tzinfo is None:\n        raise ValueError(\"naive datetime objects are not allowed beyond the library boundaries\")\n\n    return dt.isoformat().replace(\"+00:00\", \"Z\")", "title": ""}
{"_id": "d10840", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d10841", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d10842", "text": "def find_largest_contig(contig_lengths_dict):\n    \"\"\"\n    Determine the largest contig for each strain\n    :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n    :return: longest_contig_dict: dictionary of strain name: longest contig\n    \"\"\"\n    # Initialise the dictionary\n    longest_contig_dict = dict()\n    for file_name, contig_lengths in contig_lengths_dict.items():\n        # As the list is sorted in descending order, the largest contig is the first entry in the list\n        longest_contig_dict[file_name] = contig_lengths[0]\n    return longest_contig_dict", "title": ""}
{"_id": "d10843", "text": "def __next__(self, reward, ask_id, lbl):\n        \"\"\"For Python3 compatibility of generator.\"\"\"\n        return self.next(reward, ask_id, lbl)", "title": ""}
{"_id": "d10844", "text": "def setDictDefaults (d, defaults):\n  \"\"\"Sets all defaults for the given dictionary to those contained in a\n  second defaults dictionary.  This convenience method calls:\n\n    d.setdefault(key, value)\n\n  for each key and value in the given defaults dictionary.\n  \"\"\"\n  for key, val in defaults.items():\n    d.setdefault(key, val)\n\n  return d", "title": ""}
{"_id": "d10845", "text": "def get_field_by_name(self, name):\n        \"\"\"\n        the field member matching name, or None if no such field is found\n        \"\"\"\n\n        for f in self.fields:\n            if f.get_name() == name:\n                return f\n        return None", "title": ""}
{"_id": "d10846", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d10847", "text": "def get_remote_content(filepath):\n        \"\"\" A handy wrapper to get a remote file content \"\"\"\n        with hide('running'):\n            temp = BytesIO()\n            get(filepath, temp)\n            content = temp.getvalue().decode('utf-8')\n        return content.strip()", "title": ""}
{"_id": "d10848", "text": "def isnumber(*args):\n    \"\"\"Checks if value is an integer, long integer or float.\n\n    NOTE: Treats booleans as numbers, where True=1 and False=0.\n    \"\"\"\n    return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))", "title": ""}
{"_id": "d10849", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d10850", "text": "def __eq__(self, other):\n        \"\"\"Determine if two objects are equal.\"\"\"\n        return isinstance(other, self.__class__) \\\n            and self._freeze() == other._freeze()", "title": ""}
{"_id": "d10851", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d10852", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d10853", "text": "def _rank(self, ranking, n):\n    \"\"\" return the first n sentences with highest ranking \"\"\"\n    return nlargest(n, ranking, key=ranking.get)", "title": ""}
{"_id": "d10854", "text": "def delete(self, mutagen_file):\n        \"\"\"Remove all images from the file.\n        \"\"\"\n        for cover_tag in self.TAG_NAMES.values():\n            try:\n                del mutagen_file[cover_tag]\n            except KeyError:\n                pass", "title": ""}
{"_id": "d10855", "text": "def get_image_dimension(self, url):\n        \"\"\"\n        Return a tuple that contains (width, height)\n        Pass in a url to an image and find out its size without loading the whole file\n        If the image wxh could not be found, the tuple will contain `None` values\n        \"\"\"\n        w_h = (None, None)\n        try:\n            if url.startswith('//'):\n                url = 'http:' + url\n            data = requests.get(url).content\n            im = Image.open(BytesIO(data))\n\n            w_h = im.size\n        except Exception:\n            logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n        return w_h", "title": ""}
{"_id": "d10856", "text": "def delete_index(index):\n    \"\"\"Delete index entirely (removes all documents and mapping).\"\"\"\n    logger.info(\"Deleting search index: '%s'\", index)\n    client = get_client()\n    return client.indices.delete(index=index)", "title": ""}
{"_id": "d10857", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d10858", "text": "def pop(self):\n        \"\"\"\n        return the last stack element and delete it from the list\n        \"\"\"\n        if not self.empty():\n            val = self.stack[-1]\n            del self.stack[-1]\n            return val", "title": ""}
{"_id": "d10859", "text": "def remove_last_entry(self):\n        \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n        self.current_beat -= 1.0 / self.bar[-1][1]\n        self.bar = self.bar[:-1]\n        return self.current_beat", "title": ""}
{"_id": "d10860", "text": "def translate_index_to_position(self, index):\n        \"\"\"\n        Given an index for the text, return the corresponding (row, col) tuple.\n        (0-based. Returns (0, 0) for index=0.)\n        \"\"\"\n        # Find start of this line.\n        row, row_index = self._find_line_start_index(index)\n        col = index - row_index\n\n        return row, col", "title": ""}
{"_id": "d10861", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d10862", "text": "def get_inputs_from_cm(index, cm):\n    \"\"\"Return indices of inputs to the node with the given index.\"\"\"\n    return tuple(i for i in range(cm.shape[0]) if cm[i][index])", "title": ""}
{"_id": "d10863", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d10864", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d10865", "text": "def detach_all(self):\n        \"\"\"\n        Detach from all tracked classes and objects.\n        Restore the original constructors and cleanse the tracking lists.\n        \"\"\"\n        self.detach_all_classes()\n        self.objects.clear()\n        self.index.clear()\n        self._keepalive[:] = []", "title": ""}
{"_id": "d10866", "text": "def tail(self, n=10):\n        \"\"\"\n        Get an SArray that contains the last n elements in the SArray.\n\n        Parameters\n        ----------\n        n : int\n            The number of elements to fetch\n\n        Returns\n        -------\n        out : SArray\n            A new SArray which contains the last n rows of the current SArray.\n        \"\"\"\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.tail(n))", "title": ""}
{"_id": "d10867", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d10868", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d10869", "text": "def clean_out_dir(directory):\n    \"\"\"\n    Delete all the files and subdirectories in a directory.\n    \"\"\"\n    if not isinstance(directory, path):\n        directory = path(directory)\n    for file_path in directory.files():\n        file_path.remove()\n    for dir_path in directory.dirs():\n        dir_path.rmtree()", "title": ""}
{"_id": "d10870", "text": "def paste(cmd=paste_cmd, stdout=PIPE):\n    \"\"\"Returns system clipboard contents.\n    \"\"\"\n    return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')", "title": ""}
{"_id": "d10871", "text": "def generate(env):\n    \"\"\"Add Builders and construction variables for SGI MIPS C++ to an Environment.\"\"\"\n\n    cplusplus.generate(env)\n\n    env['CXX']         = 'CC'\n    env['CXXFLAGS']    = SCons.Util.CLVar('-LANG:std')\n    env['SHCXX']       = '$CXX'\n    env['SHOBJSUFFIX'] = '.o'\n    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1", "title": ""}
{"_id": "d10872", "text": "def _get_item_position(self, idx):\n        \"\"\"Return a tuple of (start, end) indices of an item from its index.\"\"\"\n        start = 0 if idx == 0 else self._index[idx - 1] + 1\n        end = self._index[idx]\n        return start, end", "title": ""}
{"_id": "d10873", "text": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n    \"\"\"\n    http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n    \"\"\"\n    fft = np.fft.fft(data)\n    # n = len(data)\n    # timestep = 1.0 / fs\n    # freq = np.fft.fftfreq(n, d=timestep)\n    bp = fft.copy()\n\n    # Zero out fft coefficients\n    # bp[10:-10] = 0\n\n    # Normalise\n    # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n    bp *= fft.dot(fft) / bp.dot(bp)\n\n    # must multipy by 2 to get the correct amplitude\n    ibp = 12 * np.fft.ifft(bp)\n    return ibp", "title": ""}
{"_id": "d10874", "text": "def get_memory_usage():\n    \"\"\"Gets RAM memory usage\n\n    :return: MB of memory used by this process\n    \"\"\"\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info().rss\n    return mem / (1024 * 1024)", "title": ""}
{"_id": "d10875", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d10876", "text": "def memory():\n    \"\"\"Determine memory specifications of the machine.\n\n    Returns\n    -------\n    mem_info : dictonary\n        Holds the current values for the total, free and used memory of the system.\n    \"\"\"\n\n    mem_info = dict()\n\n    for k, v in psutil.virtual_memory()._asdict().items():\n           mem_info[k] = int(v)\n           \n    return mem_info", "title": ""}
{"_id": "d10877", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d10878", "text": "def memory_usage(self, deep=False):\n        \"\"\"\n        Memory usage of my 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        Notes\n        -----\n        Memory usage does not include memory consumed by elements that\n        are not components of the array if deep=False\n\n        See Also\n        --------\n        numpy.ndarray.nbytes\n        \"\"\"\n        return self._codes.nbytes + self.dtype.categories.memory_usage(\n            deep=deep)", "title": ""}
{"_id": "d10879", "text": "def get_creation_datetime(filepath):\n    \"\"\"\n    Get the date that a file was created.\n\n    Parameters\n    ----------\n    filepath : str\n\n    Returns\n    -------\n    creation_datetime : datetime.datetime or None\n    \"\"\"\n    if platform.system() == 'Windows':\n        return datetime.fromtimestamp(os.path.getctime(filepath))\n    else:\n        stat = os.stat(filepath)\n        try:\n            return datetime.fromtimestamp(stat.st_birthtime)\n        except AttributeError:\n            # We're probably on Linux. No easy way to get creation dates here,\n            # so we'll settle for when its content was last modified.\n            return None", "title": ""}
{"_id": "d10880", "text": "def get_closest_index(myList, myNumber):\n    \"\"\"\n    Assumes myList is sorted. Returns closest value to myNumber.\n    If two numbers are equally close, return the smallest number.\n\n    Parameters\n    ----------\n    myList : array\n        The list in which to find the closest value to myNumber\n    myNumber : float\n        The number to find the closest to in MyList\n\n    Returns\n    -------\n    closest_values_index : int\n        The index in the array of the number closest to myNumber in myList\n    \"\"\"\n    closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n    return closest_values_index", "title": ""}
{"_id": "d10881", "text": "def resize_by_area(img, size):\n  \"\"\"image resize function used by quite a few image problems.\"\"\"\n  return tf.to_int64(\n      tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))", "title": ""}
{"_id": "d10882", "text": "def bbox(img):\n    \"\"\"Find the bounding box around nonzero elements in the given array\n\n    Copied from https://stackoverflow.com/a/31402351/5703449 .\n\n    Returns:\n        rowmin, rowmax, colmin, colmax\n    \"\"\"\n    rows = np.any(img, axis=1)\n    cols = np.any(img, axis=0)\n    rmin, rmax = np.where(rows)[0][[0, -1]]\n    cmin, cmax = np.where(cols)[0][[0, -1]]\n\n    return rmin, rmax, cmin, cmax", "title": ""}
{"_id": "d10883", "text": "def load_object_by_name(object_name):\n    \"\"\"Load an object from a module by name\"\"\"\n    mod_name, attr = object_name.rsplit('.', 1)\n    mod = import_module(mod_name)\n    return getattr(mod, attr)", "title": ""}
{"_id": "d10884", "text": "def block(seed):\n    \"\"\" 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\n    \"\"\"\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)", "title": ""}
{"_id": "d10885", "text": "def get_object_or_child_by_type(self, *types):\n        \"\"\" Get object if child already been read or get child.\n\n        Use this method for fast access to objects in case of static configurations.\n\n        :param types: requested object types.\n        :return: all children of the specified types.\n        \"\"\"\n\n        objects = self.get_objects_or_children_by_type(*types)\n        return objects[0] if any(objects) else None", "title": ""}
{"_id": "d10886", "text": "def dfs_recursive(graph, node, seen):\n    \"\"\"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|)`\n    \"\"\"\n    seen[node] = True\n    for neighbor in graph[node]:\n        if not seen[neighbor]:\n            dfs_recursive(graph, neighbor, seen)", "title": ""}
{"_id": "d10887", "text": "def _lookup_parent(self, cls):\n        \"\"\"Lookup a transitive parent object that is an instance\n            of a given class.\"\"\"\n        codeobj = self.parent\n        while codeobj is not None and not isinstance(codeobj, cls):\n            codeobj = codeobj.parent\n        return codeobj", "title": ""}
{"_id": "d10888", "text": "def dict_to_html_attrs(dict_):\n    \"\"\"\n    Banana banana\n    \"\"\"\n    res = ' '.join('%s=\"%s\"' % (k, v) for k, v in dict_.items())\n    return res", "title": ""}
{"_id": "d10889", "text": "def get_parent_dir(name):\n    \"\"\"Get the parent directory of a filename.\"\"\"\n    parent_dir = os.path.dirname(os.path.dirname(name))\n    if parent_dir:\n        return parent_dir\n    return os.path.abspath('.')", "title": ""}
{"_id": "d10890", "text": "def get_parent_var(name, global_ok=False, default=None, skip_frames=0):\n    \"\"\"\n    Directly gets a variable from a parent frame-scope.\n\n    Returns\n    --------\n    Any\n        The content of the variable found by the given name, or None.\n    \"\"\"\n\n    scope = get_parent_scope_from_var(name, global_ok=global_ok, skip_frames=skip_frames + 1)\n\n    if not scope:\n        return default\n\n    if name in scope.locals:\n        return scope.locals.get(name, default)\n\n    return scope.globals.get(name, default)", "title": ""}
{"_id": "d10891", "text": "def make_coord_dict(coord):\n    \"\"\"helper function to make a dict from a coordinate for logging\"\"\"\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    )", "title": ""}
{"_id": "d10892", "text": "def screen_to_latlon(self, x, y):\n        \"\"\"\n        Return the latitude and longitude corresponding to a screen point\n        :param x: screen x\n        :param y: screen y\n        :return: latitude and longitude at x,y\n        \"\"\"\n        xtile = 1. * x / TILE_SIZE + self.xtile\n        ytile = 1. * y / TILE_SIZE + self.ytile\n        return self.num2deg(xtile, ytile, self.zoom)", "title": ""}
{"_id": "d10893", "text": "def softplus(attrs, inputs, proto_obj):\n    \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs", "title": ""}
{"_id": "d10894", "text": "def round_to_float(number, precision):\n    \"\"\"Round a float to a precision\"\"\"\n    rounded = Decimal(str(floor((number + precision / 2) // precision))\n                      ) * Decimal(str(precision))\n    return float(rounded)", "title": ""}
{"_id": "d10895", "text": "def int2str(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from integers to strings\"\"\"\n    return NumConv(radix, alphabet).int2str(num)", "title": ""}
{"_id": "d10896", "text": "def get_querystring(uri):\n    \"\"\"Get Querystring information from uri.\n\n    :param uri: uri\n    :return: querystring info or {}\n    \"\"\"\n    parts = urlparse.urlsplit(uri)\n    return urlparse.parse_qs(parts.query)", "title": ""}
{"_id": "d10897", "text": "def me(self):\n        \"\"\"Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.\"\"\"\n        return self.guild.me if self.guild is not None else self.bot.user", "title": ""}
{"_id": "d10898", "text": "def border(self):\n        \"\"\"Region formed by taking border elements.\n\n        :returns: :class:`jicimagelib.region.Region`\n        \"\"\"\n\n        border_array = self.bitmap - self.inner.bitmap\n        return Region(border_array)", "title": ""}
{"_id": "d10899", "text": "def __get_registry_key(self, key):\n        \"\"\" Read currency from windows registry \"\"\"\n        import winreg\n\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", "title": ""}
{"_id": "d10900", "text": "def skip_connection_distance(a, b):\n    \"\"\"The distance between two skip-connections.\"\"\"\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))", "title": ""}
{"_id": "d10901", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d10902", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d10903", "text": "def clean_axis(axis):\n    \"\"\"Remove ticks, tick labels, and frame from axis\"\"\"\n    axis.get_xaxis().set_ticks([])\n    axis.get_yaxis().set_ticks([])\n    for spine in list(axis.spines.values()):\n        spine.set_visible(False)", "title": ""}
{"_id": "d10904", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d10905", "text": "def remove_last_entry(self):\n        \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n        self.current_beat -= 1.0 / self.bar[-1][1]\n        self.bar = self.bar[:-1]\n        return self.current_beat", "title": ""}
{"_id": "d10906", "text": "def check_attribute_exists(instance):\n    \"\"\" Additional check for the dimension model, to ensure that attributes\n    given as the key and label attribute on the dimension exist. \"\"\"\n    attributes = instance.get('attributes', {}).keys()\n    if instance.get('key_attribute') not in attributes:\n        return False\n    label_attr = instance.get('label_attribute')\n    if label_attr and label_attr not in attributes:\n        return False\n    return True", "title": ""}
{"_id": "d10907", "text": "def get_image_dimension(self, url):\n        \"\"\"\n        Return a tuple that contains (width, height)\n        Pass in a url to an image and find out its size without loading the whole file\n        If the image wxh could not be found, the tuple will contain `None` values\n        \"\"\"\n        w_h = (None, None)\n        try:\n            if url.startswith('//'):\n                url = 'http:' + url\n            data = requests.get(url).content\n            im = Image.open(BytesIO(data))\n\n            w_h = im.size\n        except Exception:\n            logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n        return w_h", "title": ""}
{"_id": "d10908", "text": "def _full_analysis_mp_alias(br_obj, analysis_set, output_directory, unique_name, verbose, quick_plots):\n    \"\"\"\n    Alias for instance method that allows the method to be called in a\n    multiprocessing pool. Needed as multiprocessing does not otherwise work\n    on object instance methods.\n    \"\"\"\n    return (br_obj, unique_name, br_obj.full_analysis(analysis_set, output_directory, verbose = verbose, compile_pdf = verbose, quick_plots = quick_plots))", "title": ""}
{"_id": "d10909", "text": "def _check_and_convert_bools(self):\n        \"\"\"Replace boolean variables by the characters 'F'/'T'\n        \"\"\"\n        replacements = {\n            True: 'T',\n            False: 'F',\n        }\n\n        for key in self.bools:\n            if isinstance(self[key], bool):\n                self[key] = replacements[self[key]]", "title": ""}
{"_id": "d10910", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d10911", "text": "def test3():\n    \"\"\"Test the multiprocess\n    \"\"\"\n    import time\n    \n    p = MVisionProcess()\n    p.start()\n    time.sleep(5)\n    p.stop()", "title": ""}
{"_id": "d10912", "text": "def _size_36():\n    \"\"\" returns the rows, columns of terminal \"\"\"\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", "title": ""}
{"_id": "d10913", "text": "def __exit__(self, *args):\n        \"\"\"\n        Cleanup any necessary opened files\n        \"\"\"\n\n        if self._output_file_handle:\n            self._output_file_handle.close()\n            self._output_file_handle = None", "title": ""}
{"_id": "d10914", "text": "def dot_v3(v, w):\n    \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n    return sum([x * y for x, y in zip(v, w)])", "title": ""}
{"_id": "d10915", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d10916", "text": "def dot(self, w):\n        \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n        return sum([x * y for x, y in zip(self, w)])", "title": ""}
{"_id": "d10917", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d10918", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d10919", "text": "def find_largest_contig(contig_lengths_dict):\n    \"\"\"\n    Determine the largest contig for each strain\n    :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n    :return: longest_contig_dict: dictionary of strain name: longest contig\n    \"\"\"\n    # Initialise the dictionary\n    longest_contig_dict = dict()\n    for file_name, contig_lengths in contig_lengths_dict.items():\n        # As the list is sorted in descending order, the largest contig is the first entry in the list\n        longest_contig_dict[file_name] = contig_lengths[0]\n    return longest_contig_dict", "title": ""}
{"_id": "d10920", "text": "def line_segment(X0, X1):\n    r\"\"\"\n    Calculate the voxel coordinates of a straight line between the two given\n    end points\n\n    Parameters\n    ----------\n    X0 and X1 : array_like\n        The [x, y] or [x, y, z] coordinates of the start and end points of\n        the line.\n\n    Returns\n    -------\n    coords : list of lists\n        A list of lists containing the X, Y, and Z coordinates of all voxels\n        that should be drawn between the start and end points to create a solid\n        line.\n    \"\"\"\n    X0 = sp.around(X0).astype(int)\n    X1 = sp.around(X1).astype(int)\n    if len(X0) == 3:\n        L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]], [X1[2]-X0[2]]])) + 1\n        x = sp.rint(sp.linspace(X0[0], X1[0], L)).astype(int)\n        y = sp.rint(sp.linspace(X0[1], X1[1], L)).astype(int)\n        z = sp.rint(sp.linspace(X0[2], X1[2], L)).astype(int)\n        return [x, y, z]\n    else:\n        L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]]])) + 1\n        x = sp.rint(sp.linspace(X0[0], X1[0], L)).astype(int)\n        y = sp.rint(sp.linspace(X0[1], X1[1], L)).astype(int)\n        return [x, y]", "title": ""}
{"_id": "d10921", "text": "def _draw_lines_internal(self, coords, colour, bg):\n        \"\"\"Helper to draw lines connecting a set of nodes that are scaled for the Screen.\"\"\"\n        for i, (x, y) in enumerate(coords):\n            if i == 0:\n                self._screen.move(x, y)\n            else:\n                self._screen.draw(x, y, colour=colour, bg=bg, thin=True)", "title": ""}
{"_id": "d10922", "text": "def get_size(self, m):\n        \"\"\"\n        Return the 2-D size of a Jacobian matrix in tuple\n        \"\"\"\n        nrow, ncol = 0, 0\n        if m[0] == 'F':\n            nrow = self.n\n        elif m[0] == 'G':\n            nrow = self.m\n\n        if m[1] == 'x':\n            ncol = self.n\n        elif m[1] == 'y':\n            ncol = self.m\n\n        return nrow, ncol", "title": ""}
{"_id": "d10923", "text": "def experiment_property(prop):\n    \"\"\"Get a property of the experiment by name.\"\"\"\n    exp = experiment(session)\n    p = getattr(exp, prop)\n    return success_response(field=prop, data=p, request_type=prop)", "title": ""}
{"_id": "d10924", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d10925", "text": "def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to be padded.\n\n        Returns:\n            PIL Image: Padded image.\n        \"\"\"\n        return F.pad(img, self.padding, self.fill, self.padding_mode)", "title": ""}
{"_id": "d10926", "text": "def get_user_name():\n    \"\"\"Get user name provide by operating system\n    \"\"\"\n\n    if sys.platform == 'win32':\n        #user = os.getenv('USERPROFILE')\n        user = os.getenv('USERNAME')\n    else:\n        user = os.getenv('LOGNAME')\n\n    return user", "title": ""}
{"_id": "d10927", "text": "def copy_and_update(dictionary, update):\n    \"\"\"Returns an updated copy of the dictionary without modifying the original\"\"\"\n    newdict = dictionary.copy()\n    newdict.update(update)\n    return newdict", "title": ""}
{"_id": "d10928", "text": "def convert_2_utc(self, datetime_, timezone):\n        \"\"\"convert to datetime to UTC offset.\"\"\"\n\n        datetime_ = self.tz_mapper[timezone].localize(datetime_)\n        return datetime_.astimezone(pytz.UTC)", "title": ""}
{"_id": "d10929", "text": "def remove_accent_string(string):\n    \"\"\"\n    Remove all accent from a whole string.\n    \"\"\"\n    return utils.join([add_accent_char(c, Accent.NONE) for c in string])", "title": ""}
{"_id": "d10930", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d10931", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d10932", "text": "def get_enum_from_name(self, enum_name):\n        \"\"\"\n            Return an enum from a name\n        Args:\n            enum_name (str): name of the enum\n        Returns:\n            Enum\n        \"\"\"\n        return next((e for e in self.enums if e.name == enum_name), None)", "title": ""}
{"_id": "d10933", "text": "def replace_one(self, replacement):\n        \"\"\"Replace one entire document matching the selector criteria.\n\n        :Parameters:\n          - `replacement` (dict): the replacement document\n        \"\"\"\n        self.__bulk.add_replace(self.__selector, replacement, upsert=True,\n                                collation=self.__collation)", "title": ""}
{"_id": "d10934", "text": "def get_closest_index(myList, myNumber):\n    \"\"\"\n    Assumes myList is sorted. Returns closest value to myNumber.\n    If two numbers are equally close, return the smallest number.\n\n    Parameters\n    ----------\n    myList : array\n        The list in which to find the closest value to myNumber\n    myNumber : float\n        The number to find the closest to in MyList\n\n    Returns\n    -------\n    closest_values_index : int\n        The index in the array of the number closest to myNumber in myList\n    \"\"\"\n    closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n    return closest_values_index", "title": ""}
{"_id": "d10935", "text": "def most_common(items):\n    \"\"\"\n    Wanted functionality from Counters (new in Python 2.7).\n    \"\"\"\n    counts = {}\n    for i in items:\n        counts.setdefault(i, 0)\n        counts[i] += 1\n    return max(six.iteritems(counts), key=operator.itemgetter(1))", "title": ""}
{"_id": "d10936", "text": "def getSystemVariable(self, remote, name):\n        \"\"\"Get single system variable from CCU / Homegear\"\"\"\n        if self._server is not None:\n            return self._server.getSystemVariable(remote, name)", "title": ""}
{"_id": "d10937", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d10938", "text": "def get_week_start_end_day():\n    \"\"\"\n    Get the week start date and end date\n    \"\"\"\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))", "title": ""}
{"_id": "d10939", "text": "def is_valid_email(email):\n    \"\"\"\n    Check if email is valid\n    \"\"\"\n    pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n    return bool(pattern.match(email))", "title": ""}
{"_id": "d10940", "text": "def title(self):\n        \"\"\" The title of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.title", "title": ""}
{"_id": "d10941", "text": "def fill_document(doc):\n    \"\"\"Add a section, a subsection and some text to the document.\n\n    :param doc: the document\n    :type doc: :class:`pylatex.document.Document` instance\n    \"\"\"\n    with doc.create(Section('A section')):\n        doc.append('Some regular text and some ')\n        doc.append(italic('italic text. '))\n\n        with doc.create(Subsection('A subsection')):\n            doc.append('Also some crazy characters: $&#{}')", "title": ""}
{"_id": "d10942", "text": "def count(lines):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  words = [w for l in lines for w in l.strip().split()]\n  return Counter(words)", "title": ""}
{"_id": "d10943", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d10944", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d10945", "text": "def norm_vec(vector):\n    \"\"\"Normalize the length of a vector to one\"\"\"\n    assert len(vector) == 3\n    v = np.array(vector)\n    return v/np.sqrt(np.sum(v**2))", "title": ""}
{"_id": "d10946", "text": "def _uptime_syllable():\n    \"\"\"Returns uptime in seconds or None, on Syllable.\"\"\"\n    global __boottime\n    try:\n        __boottime = os.stat('/dev/pty/mst/pty0').st_mtime\n        return time.time() - __boottime\n    except (NameError, OSError):\n        return None", "title": ""}
{"_id": "d10947", "text": "def commit(self, session=None):\n        \"\"\"Merge modified objects into parent transaction.\n\n        Once commited a transaction object is not usable anymore\n\n        :param:session: current sqlalchemy Session\n        \"\"\"\n        if self.__cleared:\n            return\n\n        if self._parent:\n            # nested transaction\n            self._commit_parent()\n        else:\n            self._commit_repository()\n        self._clear()", "title": ""}
{"_id": "d10948", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d10949", "text": "def save_dot(self, fd):\n        \"\"\" Saves a representation of the case in the Graphviz DOT language.\n        \"\"\"\n        from pylon.io import DotWriter\n        DotWriter(self).write(fd)", "title": ""}
{"_id": "d10950", "text": "def get_month_start(day=None):\n    \"\"\"Returns the first day of the given month.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(day=1)", "title": ""}
{"_id": "d10951", "text": "def sav_to_pandas_rpy2(input_file):\n    \"\"\"\n    SPSS .sav files to Pandas DataFrame through Rpy2\n\n    :param input_file: string\n\n    :return:\n    \"\"\"\n    import pandas.rpy.common as com\n\n    w = com.robj.r('foreign::read.spss(\"%s\", to.data.frame=TRUE)' % input_file)\n    return com.convert_robj(w)", "title": ""}
{"_id": "d10952", "text": "def fit_linear(X, y):\n    \"\"\"\n    Uses OLS to fit the regression.\n    \"\"\"\n    model = linear_model.LinearRegression()\n    model.fit(X, y)\n    return model", "title": ""}
{"_id": "d10953", "text": "def tab(self, output):\n        \"\"\"Output data in excel-compatible tab-delimited format\"\"\"\n        import csv\n        csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab)\n        csvwriter.writerows(output)", "title": ""}
{"_id": "d10954", "text": "def underscore(text):\n    \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n    return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()", "title": ""}
{"_id": "d10955", "text": "def extract_keywords_from_text(self, text):\n        \"\"\"Method to extract keywords from the text provided.\n\n        :param text: Text to extract keywords from, provided as a string.\n        \"\"\"\n        sentences = nltk.tokenize.sent_tokenize(text)\n        self.extract_keywords_from_sentences(sentences)", "title": ""}
{"_id": "d10956", "text": "def input(self,pin):\n        \"\"\"Read the specified pin and return HIGH/true if the pin is pulled high,\n        or LOW/false if pulled low.\n        \"\"\"\n        return self.mraa_gpio.Gpio.read(self.mraa_gpio.Gpio(pin))", "title": ""}
{"_id": "d10957", "text": "def _extract_node_text(node):\n    \"\"\"Extract text from a given lxml node.\"\"\"\n\n    texts = map(\n        six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n    )\n    return \" \".join(text for text in texts if text)", "title": ""}
{"_id": "d10958", "text": "def get_builder_toplevel(self, builder):\n        \"\"\"Get the toplevel widget from a gtk.Builder file.\n\n        The main view implementation first searches for the widget named as\n        self.toplevel_name (which defaults to \"main\". If this is missing, or not\n        a gtk.Window, the first toplevel window found in the gtk.Builder is\n        used.\n        \"\"\"\n        toplevel = builder.get_object(self.toplevel_name)\n        if not gobject.type_is_a(toplevel, gtk.Window):\n            toplevel = None\n        if toplevel is None:\n            toplevel = get_first_builder_window(builder)\n        return toplevel", "title": ""}
{"_id": "d10959", "text": "def dot_product(self, other):\n        \"\"\" Return the dot product of the given vectors. \"\"\"\n        return self.x * other.x + self.y * other.y", "title": ""}
{"_id": "d10960", "text": "def _unzip_handle(handle):\n    \"\"\"Transparently unzip the file handle\"\"\"\n    if isinstance(handle, basestring):\n        handle = _gzip_open_filename(handle)\n    else:\n        handle = _gzip_open_handle(handle)\n    return handle", "title": ""}
{"_id": "d10961", "text": "def peekiter(iterable):\n    \"\"\"Return first row and also iterable with same items as original\"\"\"\n    it = iter(iterable)\n    one = next(it)\n\n    def gen():\n        \"\"\"Generator that returns first and proxy other items from source\"\"\"\n        yield one\n        while True:\n            yield next(it)\n    return (one, gen())", "title": ""}
{"_id": "d10962", "text": "def help_for_command(command):\n    \"\"\"Get the help text (signature + docstring) for a command (function).\"\"\"\n    help_text = pydoc.text.document(command)\n    # remove backspaces\n    return re.subn('.\\\\x08', '', help_text)[0]", "title": ""}
{"_id": "d10963", "text": "def main():\n    usage=\"\"\"\nUserspace ioctl example\n\n\"\"\" + Fuse.fusage\n    server = FiocFS(version=\"%prog \" + fuse.__version__,\n                     usage=usage,\n                     dash_s_do='setsingle')\n\n    server.parse(errex=1)\n    server.main()", "title": ""}
{"_id": "d10964", "text": "def hclust_linearize(U):\n    \"\"\"Sorts the rows of a matrix by hierarchical clustering.\n\n    Parameters:\n        U (ndarray) : matrix of data\n\n    Returns:\n        prm (ndarray) : permutation of the rows\n    \"\"\"\n\n    from scipy.cluster import hierarchy\n    Z = hierarchy.ward(U)\n    return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))", "title": ""}
{"_id": "d10965", "text": "def searchlast(self,n=10):\n        \"\"\"Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.\"\"\"            \n        solutions = deque([], n)\n        for solution in self:\n            solutions.append(solution)\n        return solutions", "title": ""}
{"_id": "d10966", "text": "def check_empty_dict(GET_dict):\n    \"\"\"\n    Returns True if the GET querstring contains on values, but it can contain\n    empty keys.\n    This is better than doing not bool(request.GET) as an empty key will return\n    True\n    \"\"\"\n    empty = True\n    for k, v in GET_dict.items():\n        # Don't disable on p(age) or 'all' GET param\n        if v and k != 'p' and k != 'all':\n            empty = False\n    return empty", "title": ""}
{"_id": "d10967", "text": "def _get_background_color(self):\n        \"\"\"Returns background color rgb tuple of right line\"\"\"\n\n        color = self.cell_attributes[self.key][\"bgcolor\"]\n        return tuple(c / 255.0 for c in color_pack2rgb(color))", "title": ""}
{"_id": "d10968", "text": "def clean_float(v):\n    \"\"\"Remove commas from a float\"\"\"\n\n    if v is None or not str(v).strip():\n        return None\n\n    return float(str(v).replace(',', ''))", "title": ""}
{"_id": "d10969", "text": "def _dictfetchall(self, cursor):\n        \"\"\" Return all rows from a cursor as a dict. \"\"\"\n        columns = [col[0] for col in cursor.description]\n        return [\n            dict(zip(columns, row))\n            for row in cursor.fetchall()\n        ]", "title": ""}
{"_id": "d10970", "text": "def fast_exit(code):\n    \"\"\"Exit without garbage collection, this speeds up exit by about 10ms for\n    things like bash completion.\n    \"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(code)", "title": ""}
{"_id": "d10971", "text": "def fft_freqs(n_fft, fs):\n    \"\"\"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.\n    \"\"\"\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)", "title": ""}
{"_id": "d10972", "text": "def report_stdout(host, stdout):\n    \"\"\"Take a stdout 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 stdout: the std out of that process\n    :type stdout: paramiko.channel.Channel\n    \"\"\"\n    lines = stdout.readlines()\n    if lines:\n        print(\"STDOUT from {host}:\".format(host=host))\n        for line in lines:\n            print(line.rstrip(), file=sys.stdout)", "title": ""}
{"_id": "d10973", "text": "def load_config(filename=\"logging.ini\", *args, **kwargs):\n    \"\"\"\n    Load logger config from file\n    \n    Keyword arguments:\n    filename -- configuration filename (Default: \"logging.ini\")\n    *args -- options passed to fileConfig\n    **kwargs -- options passed to fileConfigg\n    \n    \"\"\"\n    logging.config.fileConfig(filename, *args, **kwargs)", "title": ""}
{"_id": "d10974", "text": "def sed(match, replacement, path, modifiers=\"\"):\n    \"\"\"\n    Perform sed text substitution.\n    \"\"\"\n    cmd = \"sed -r -i 's/%s/%s/%s' %s\" % (match, replacement, modifiers, path)\n\n    process = Subprocess(cmd, shell=True)\n    ret, out, err = process.run(timeout=60)\n    if ret:\n        raise SubprocessError(\"Sed command failed!\")", "title": ""}
{"_id": "d10975", "text": "def _multiline_width(multiline_s, line_width_fn=len):\n    \"\"\"Visible width of a potentially multiline content.\"\"\"\n    return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "title": ""}
{"_id": "d10976", "text": "def unique(iterable):\n    \"\"\"Filter out duplicate items from an iterable\"\"\"\n    seen = set()\n    for item in iterable:\n        if item not in seen:\n            seen.add(item)\n            yield item", "title": ""}
{"_id": "d10977", "text": "def is_running(self):\n        \"\"\"Returns a bool determining if the process is in a running state or\n        not\n\n        :rtype: bool\n\n        \"\"\"\n        return self.state in [self.STATE_IDLE, self.STATE_ACTIVE,\n                              self.STATE_SLEEPING]", "title": ""}
{"_id": "d10978", "text": "def argmax(l,f=None):\n    \"\"\"http://stackoverflow.com/questions/5098580/implementing-argmax-in-python\"\"\"\n    if f:\n        l = [f(i) for i in l]\n    return max(enumerate(l), key=lambda x:x[1])[0]", "title": ""}
{"_id": "d10979", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d10980", "text": "def find_largest_contig(contig_lengths_dict):\n    \"\"\"\n    Determine the largest contig for each strain\n    :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n    :return: longest_contig_dict: dictionary of strain name: longest contig\n    \"\"\"\n    # Initialise the dictionary\n    longest_contig_dict = dict()\n    for file_name, contig_lengths in contig_lengths_dict.items():\n        # As the list is sorted in descending order, the largest contig is the first entry in the list\n        longest_contig_dict[file_name] = contig_lengths[0]\n    return longest_contig_dict", "title": ""}
{"_id": "d10981", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d10982", "text": "def get_median(temp_list):\n    \"\"\"Return median\n    \"\"\"\n    num = len(temp_list)\n    temp_list.sort()\n    print(temp_list)\n    if num % 2 == 0:\n        median = (temp_list[int(num/2)] + temp_list[int(num/2) - 1]) / 2\n    else:\n        median = temp_list[int(num/2)]\n    return median", "title": ""}
{"_id": "d10983", "text": "def num_leaves(tree):\n    \"\"\"Determine the number of leaves in a tree\"\"\"\n    if tree.is_leaf:\n        return 1\n    else:\n        return num_leaves(tree.left_child) + num_leaves(tree.right_child)", "title": ""}
{"_id": "d10984", "text": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "title": ""}
{"_id": "d10985", "text": "def most_even(number, group):\n    \"\"\"Divide a number into a list of numbers as even as possible.\"\"\"\n    count, rest = divmod(number, group)\n    counts = zip_longest([count] * group, [1] * rest, fillvalue=0)\n    chunks = [sum(one) for one in counts]\n    logging.debug('chunks: %s', chunks)\n    return chunks", "title": ""}
{"_id": "d10986", "text": "def count(self):\n        \"\"\"\n        Returns the number of widgets currently displayed (takes child splits\n        into account).\n        \"\"\"\n        c = self.main_tab_widget.count()\n        for child in self.child_splitters:\n            c += child.count()\n        return c", "title": ""}
{"_id": "d10987", "text": "def socket_close(self):\n        \"\"\"Close our socket.\"\"\"\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET", "title": ""}
{"_id": "d10988", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d10989", "text": "def url_fix_common_typos (url):\n    \"\"\"Fix common typos in given URL like forgotten colon.\"\"\"\n    if url.startswith(\"http//\"):\n        url = \"http://\" + url[6:]\n    elif url.startswith(\"https//\"):\n        url = \"https://\" + url[7:]\n    return url", "title": ""}
{"_id": "d10990", "text": "def _initialize_id(self):\n        \"\"\"Initializes the id of the instance.\"\"\"\n        self.id = str(self.db.incr(self._key['id']))", "title": ""}
{"_id": "d10991", "text": "def call_alias(self, alias, rest=''):\n        \"\"\"Call an alias given its name and the rest of the line.\"\"\"\n        cmd = self.transform_alias(alias, rest)\n        try:\n            self.shell.system(cmd)\n        except:\n            self.shell.showtraceback()", "title": ""}
{"_id": "d10992", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d10993", "text": "def delete_all_from_db():\n    \"\"\"Clear the database.\n\n    Used for testing and debugging.\n\n    \"\"\"\n    # The models.CASCADE property is set on all ForeignKey fields, so tables can\n    # be deleted in any order without breaking constraints.\n    for model in django.apps.apps.get_models():\n        model.objects.all().delete()", "title": ""}
{"_id": "d10994", "text": "def version():\n    \"\"\"\n    View the current version of the CLI.\n    \"\"\"\n    import pkg_resources\n    version = pkg_resources.require(PROJECT_NAME)[0].version\n    floyd_logger.info(version)", "title": ""}
{"_id": "d10995", "text": "def remove_columns(self, data, columns):\n        \"\"\" This method removes columns in data\n\n        :param data: original Pandas dataframe\n        :param columns: list of columns to remove\n        :type data: pandas.DataFrame\n        :type columns: list of strings\n\n        :returns: Pandas dataframe with removed columns\n        :rtype: pandas.DataFrame\n        \"\"\"\n\n        for column in columns:\n            if column in data.columns:\n                data = data.drop(column, axis=1)\n\n        return data", "title": ""}
{"_id": "d10996", "text": "def safe_delete(filename):\n  \"\"\"Delete a file safely. If it's not present, no-op.\"\"\"\n  try:\n    os.unlink(filename)\n  except OSError as e:\n    if e.errno != errno.ENOENT:\n      raise", "title": ""}
{"_id": "d10997", "text": "def go_to_background():\n    \"\"\" Daemonize the running process. \"\"\"\n    try:\n        if os.fork():\n            sys.exit()\n    except OSError as errmsg:\n        LOGGER.error('Fork failed: {0}'.format(errmsg))\n        sys.exit('Fork failed')", "title": ""}
{"_id": "d10998", "text": "def entropy(string):\n    \"\"\"Compute entropy on the string\"\"\"\n    p, lns = Counter(string), float(len(string))\n    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())", "title": ""}
{"_id": "d10999", "text": "def __is_bound_method(method):\n    \"\"\"Return ``True`` if the `method` is a bound method (attached to an class\n    instance.\n\n    Args:\n        method: A method or function type object.\n    \"\"\"\n    if not(hasattr(method, \"__func__\") and hasattr(method, \"__self__\")):\n        return False\n\n    # Bound methods have a __self__ attribute pointing to the owner instance\n    return six.get_method_self(method) is not None", "title": ""}
{"_id": "d11000", "text": "def static_method(cls, f):\n        \"\"\"Decorator which dynamically binds static methods to the model for later use.\"\"\"\n        setattr(cls, f.__name__, staticmethod(f))\n        return f", "title": ""}
{"_id": "d11001", "text": "def format_time(time):\n    \"\"\" Formats the given time into HH:MM:SS \"\"\"\n    h, r = divmod(time / 1000, 3600)\n    m, s = divmod(r, 60)\n\n    return \"%02d:%02d:%02d\" % (h, m, s)", "title": ""}
{"_id": "d11002", "text": "def string_to_date(value):\n    \"\"\"\n    Return a Python date that corresponds to the specified string\n    representation.\n\n    @param value: string representation of a date.\n\n    @return: an instance ``datetime.datetime`` represented by the string.\n    \"\"\"\n    if isinstance(value, datetime.date):\n        return value\n\n    return dateutil.parser.parse(value).date()", "title": ""}
{"_id": "d11003", "text": "def data_directory():\n    \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")", "title": ""}
{"_id": "d11004", "text": "def fromtimestamp(cls, timestamp):\n    \"\"\"Returns a datetime object of a given timestamp (in local tz).\"\"\"\n    d = cls.utcfromtimestamp(timestamp)\n    return d.astimezone(localtz())", "title": ""}
{"_id": "d11005", "text": "def get_list_dimensions(_list):\n    \"\"\"\n    Takes a nested list and returns the size of each dimension followed\n    by the element type in the list\n    \"\"\"\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []", "title": ""}
{"_id": "d11006", "text": "def _is_leap_year(year):\n    \"\"\"Determine if a year is leap year.\n\n    Parameters\n    ----------\n    year : numeric\n\n    Returns\n    -------\n    isleap : array of bools\n    \"\"\"\n    isleap = ((np.mod(year, 4) == 0) &\n              ((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0)))\n    return isleap", "title": ""}
{"_id": "d11007", "text": "def glob_by_extensions(directory, extensions):\n    \"\"\" Returns files matched by all extensions in the extensions list \"\"\"\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", "title": ""}
{"_id": "d11008", "text": "def xor_bytes(a, b):\n    \"\"\"\n    Calculate the byte wise exclusive of of two :class:`bytes` objects\n    of the same length.\n    \"\"\"\n    assert len(a) == len(b)\n    return bytes(map(operator.xor, a, b))", "title": ""}
{"_id": "d11009", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d11010", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d11011", "text": "def get_memory_usage():\n    \"\"\"Gets RAM memory usage\n\n    :return: MB of memory used by this process\n    \"\"\"\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info().rss\n    return mem / (1024 * 1024)", "title": ""}
{"_id": "d11012", "text": "def unit_key_from_name(name):\n  \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n  result = name\n\n  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n    result = result.replace(old, new)\n\n  # Collapse redundant underscores and convert to uppercase.\n  result = re.sub(r'_+', '_', result.upper())\n\n  return result", "title": ""}
{"_id": "d11013", "text": "def get_method_from_module(module_path, method_name):\n    \"\"\" from a valid python module path, get the run method name passed \"\"\"\n    top_module = __import__(module_path)\n\n    module = top_module\n    # we tunnel down until we find the module we want\n    for submodule_name in module_path.split('.')[1:]:\n        module = getattr(module, submodule_name)\n\n    assert hasattr(module, method_name), \\\n        \"unable to find method {0} from module {1}. does the method exist?\".format(method_name, module_path)\n    return getattr(module, method_name)", "title": ""}
{"_id": "d11014", "text": "def hex_to_hsv(color):\n    \"\"\"\n    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')\n    \"\"\"\n    color = normalize(color)\n    color = color[1:]\n    # color=tuple(ord(c)/255.0 for c in color.decode('hex'))\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)", "title": ""}
{"_id": "d11015", "text": "def type(self):\n        \"\"\"Returns type of the data for the given FeatureType.\"\"\"\n        if self is FeatureType.TIMESTAMP:\n            return list\n        if self is FeatureType.BBOX:\n            return BBox\n        return dict", "title": ""}
{"_id": "d11016", "text": "def match_files(files, pattern: Pattern):\n    \"\"\"Yields file name if matches a regular expression pattern.\"\"\"\n\n    for name in files:\n        if re.match(pattern, name):\n            yield name", "title": ""}
{"_id": "d11017", "text": "def grandparent_path(self):\n        \"\"\" return grandparent's path string \"\"\"\n        return os.path.basename(os.path.join(self.path, '../..'))", "title": ""}
{"_id": "d11018", "text": "def positive_integer(anon, obj, field, val):\n    \"\"\"\n    Returns a random positive integer (for a Django PositiveIntegerField)\n    \"\"\"\n    return anon.faker.positive_integer(field=field)", "title": ""}
{"_id": "d11019", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d11020", "text": "def get_latex_table(self, parameters=None, transpose=False, caption=None,\n                        label=\"tab:model_params\", hlines=True, blank_fill=\"--\"):  # pragma: no cover\n        \"\"\" Generates a LaTeX table from parameter summaries.\n\n        Parameters\n        ----------\n        parameters : list[str], optional\n            A list of what parameters to include in the table. By default, includes all parameters\n        transpose : bool, optional\n            Defaults to False, which gives each column as a parameter, each chain (framework)\n            as a row. You can swap it so that you have a parameter each row and a framework\n            each column by setting this to True\n        caption : str, optional\n            If you want to generate a caption for the table through Python, use this.\n            Defaults to an empty string\n        label : str, optional\n            If you want to generate a label for the table through Python, use this.\n            Defaults to an empty string\n        hlines : bool, optional\n            Inserts ``\\\\hline`` before and after the header, and at the end of table.\n        blank_fill : str, optional\n            If a framework does not have a particular parameter, will fill that cell of\n            the table with this string.\n\n        Returns\n        -------\n        str\n            the LaTeX table.\n        \"\"\"\n        if parameters is None:\n            parameters = self.parent._all_parameters\n        for p in parameters:\n            assert isinstance(p, str), \\\n                \"Generating a LaTeX table requires all parameters have labels\"\n        num_parameters = len(parameters)\n        num_chains = len(self.parent.chains)\n        fit_values = self.get_summary(squeeze=False)\n        if label is None:\n            label = \"\"\n        if caption is None:\n            caption = \"\"\n\n        end_text = \" \\\\\\\\ \\n\"\n        if transpose:\n            column_text = \"c\" * (num_chains + 1)\n        else:\n            column_text = \"c\" * (num_parameters + 1)\n\n        center_text = \"\"\n        hline_text = \"\\\\hline\\n\"\n        if hlines:\n            center_text += hline_text + \"\\t\\t\"\n        if transpose:\n            center_text += \" & \".join([\"Parameter\"] + [c.name for c in self.parent.chains]) + end_text\n            if hlines:\n                center_text += \"\\t\\t\" + hline_text\n            for p in parameters:\n                arr = [\"\\t\\t\" + p]\n                for chain_res in fit_values:\n                    if p in chain_res:\n                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n                    else:\n                        arr.append(blank_fill)\n                center_text += \" & \".join(arr) + end_text\n        else:\n            center_text += \" & \".join([\"Model\"] + parameters) + end_text\n            if hlines:\n                center_text += \"\\t\\t\" + hline_text\n            for name, chain_res in zip([c.name for c in self.parent.chains], fit_values):\n                arr = [\"\\t\\t\" + name]\n                for p in parameters:\n                    if p in chain_res:\n                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n                    else:\n                        arr.append(blank_fill)\n                center_text += \" & \".join(arr) + end_text\n        if hlines:\n            center_text += \"\\t\\t\" + hline_text\n        final_text = get_latex_table_frame(caption, label) % (column_text, center_text)\n\n        return final_text", "title": ""}
{"_id": "d11021", "text": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "title": ""}
{"_id": "d11022", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d11023", "text": "def uniquify_list(L):\n    \"\"\"Same order unique list using only a list compression.\"\"\"\n    return [e for i, e in enumerate(L) if L.index(e) == i]", "title": ""}
{"_id": "d11024", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d11025", "text": "def get_var(self, name):\n        \"\"\" Returns the variable set with the given name.\n        \"\"\"\n        for var in self.vars:\n            if var.name == name:\n                return var\n        else:\n            raise ValueError", "title": ""}
{"_id": "d11026", "text": "def get_variables(args):\n  \"\"\"\n  Return a dictionary of variables specified at CLI\n  :param: args: Command Line Arguments namespace\n  \"\"\"\n  variables_dict = {}\n  if args.variables:\n    for var in args.variables:\n      words = var.split('=')\n      variables_dict[words[0]] = words[1]\n  return variables_dict", "title": ""}
{"_id": "d11027", "text": "def paginate(self, request, offset=0, limit=None):\n        \"\"\"Paginate queryset.\"\"\"\n        return self.collection.offset(offset).limit(limit), self.collection.count()", "title": ""}
{"_id": "d11028", "text": "def make_regex(separator):\n    \"\"\"Utility function to create regexp for matching escaped separators\n    in strings.\n\n    \"\"\"\n    return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +\n                      re.escape(separator) + r'\\\\]|\\\\.)+)')", "title": ""}
{"_id": "d11029", "text": "async def create_websocket_server(sock, filter=None):  # pylint: disable=W0622\n    \"\"\"\n    A more low-level form of open_websocket_server.\n    You are responsible for closing this websocket.\n    \"\"\"\n    ws = Websocket()\n    await ws.start_server(sock, filter=filter)\n    return ws", "title": ""}
{"_id": "d11030", "text": "def get_attribute_name_id(attr):\n    \"\"\"\n    Return the attribute name identifier\n    \"\"\"\n    return attr.value.id if isinstance(attr.value, ast.Name) else None", "title": ""}
{"_id": "d11031", "text": "def empty_tree(input_list):\n    \"\"\"Recursively iterate through values in nested lists.\"\"\"\n    for item in input_list:\n        if not isinstance(item, list) or not empty_tree(item):\n            return False\n    return True", "title": ""}
{"_id": "d11032", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d11033", "text": "def calc_list_average(l):\n    \"\"\"\n    Calculates the average value of a list of numbers\n    Returns a float\n    \"\"\"\n    total = 0.0\n    for value in l:\n        total += value\n    return total / len(l)", "title": ""}
{"_id": "d11034", "text": "def polygon_from_points(points):\n    \"\"\"\n    Constructs a numpy-compatible polygon from a page representation.\n    \"\"\"\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", "title": ""}
{"_id": "d11035", "text": "def _mean_dict(dict_list):\n    \"\"\"Compute the mean value across a list of dictionaries\n    \"\"\"\n    return {k: np.array([d[k] for d in dict_list]).mean()\n            for k in dict_list[0].keys()}", "title": ""}
{"_id": "d11036", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d11037", "text": "def RadiusGrid(gridSize):\n    \"\"\"\n    Return a square grid with values of the distance from the centre \n    of the grid to each gridpoint\n    \"\"\"\n    x,y=np.mgrid[0:gridSize,0:gridSize]\n    x = x-(gridSize-1.0)/2.0\n    y = y-(gridSize-1.0)/2.0\n    return np.abs(x+1j*y)", "title": ""}
{"_id": "d11038", "text": "def prevmonday(num):\n    \"\"\"\n    Return unix SECOND timestamp of \"num\" mondays ago\n    \"\"\"\n    today = get_today()\n    lastmonday = today - timedelta(days=today.weekday(), weeks=num)\n    return lastmonday", "title": ""}
{"_id": "d11039", "text": "def array_size(x, axis):\n  \"\"\"Calculate the size of `x` along `axis` dimensions only.\"\"\"\n  axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)\n  return max(numpy.prod(axis_shape), 1)", "title": ""}
{"_id": "d11040", "text": "def align_file_position(f, size):\n    \"\"\" Align the position in the file to the next block of specified size \"\"\"\n    align = (size - 1) - (f.tell() % size)\n    f.seek(align, 1)", "title": ""}
{"_id": "d11041", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d11042", "text": "def _normalize(obj):\n    \"\"\"\n    Normalize dicts and lists\n\n    :param obj:\n    :return: normalized object\n    \"\"\"\n    if isinstance(obj, list):\n        return [_normalize(item) for item in obj]\n    elif isinstance(obj, dict):\n        return {k: _normalize(v) for k, v in obj.items() if v is not None}\n    elif hasattr(obj, 'to_python'):\n        return obj.to_python()\n    return obj", "title": ""}
{"_id": "d11043", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d11044", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d11045", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d11046", "text": "def _get_item_position(self, idx):\n        \"\"\"Return a tuple of (start, end) indices of an item from its index.\"\"\"\n        start = 0 if idx == 0 else self._index[idx - 1] + 1\n        end = self._index[idx]\n        return start, end", "title": ""}
{"_id": "d11047", "text": "def getRowCurrentIndex(self):\n        \"\"\" Returns the index of column 0 of the current item in the underlying model.\n            See also the notes at the top of this module on current item vs selected item(s).\n        \"\"\"\n        curIndex = self.currentIndex()\n        col0Index = curIndex.sibling(curIndex.row(), 0)\n        return col0Index", "title": ""}
{"_id": "d11048", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d11049", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d11050", "text": "def get_idx_rect(index_list):\n    \"\"\"Extract the boundaries from a list of indexes\"\"\"\n    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\n    return ( min(rows), max(rows), min(cols), max(cols) )", "title": ""}
{"_id": "d11051", "text": "def strip_spaces(s):\n    \"\"\" Strip excess spaces from a string \"\"\"\n    return u\" \".join([c for c in s.split(u' ') if c])", "title": ""}
{"_id": "d11052", "text": "def extract_keywords_from_text(self, text):\n        \"\"\"Method to extract keywords from the text provided.\n\n        :param text: Text to extract keywords from, provided as a string.\n        \"\"\"\n        sentences = nltk.tokenize.sent_tokenize(text)\n        self.extract_keywords_from_sentences(sentences)", "title": ""}
{"_id": "d11053", "text": "def drop_trailing_zeros_decimal(num):\n    \"\"\" Drops the trailinz zeros from decimal value.\n        Returns a string\n    \"\"\"\n    out = str(num)\n    return out.rstrip('0').rstrip('.') if '.' in out else out", "title": ""}
{"_id": "d11054", "text": "def add_todo(request):\n    cur = request.cursor\n    todo = request.json[\"todo\"]\n    cur.execute(\"\"\"INSERT INTO todos (todo) VALUES (?)\"\"\", (todo,))\n    last_id = cur.lastrowid\n    cur.connection.commit()\n\n    return request.Response(json={\"id\": last_id, \"todo\": todo})", "title": ""}
{"_id": "d11055", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d11056", "text": "def get_last_modified_timestamp(self):\n        \"\"\"\n        Looks at the files in a git root directory and grabs the last modified timestamp\n        \"\"\"\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", "title": ""}
{"_id": "d11057", "text": "def monkey_restore():\n    \"\"\"restore real versions. Inverse of `monkey_patch`\"\"\"\n    for k, v in originals.items():\n        setattr(time_mod, k, v)\n    \n    global epoch\n    epoch = None", "title": ""}
{"_id": "d11058", "text": "def get_mouse_location(self):\n        \"\"\"\n        Get the current mouse location (coordinates and screen number).\n\n        :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields\n        \"\"\"\n        x = ctypes.c_int(0)\n        y = ctypes.c_int(0)\n        screen_num = ctypes.c_int(0)\n        _libxdo.xdo_get_mouse_location(\n            self._xdo, ctypes.byref(x), ctypes.byref(y),\n            ctypes.byref(screen_num))\n        return mouse_location(x.value, y.value, screen_num.value)", "title": ""}
{"_id": "d11059", "text": "def __contains__(self, key):\n        \"\"\"\n        Invoked when determining whether a specific key is in the dictionary\n        using `key in d`.\n\n        The key is looked up case-insensitively.\n        \"\"\"\n        k = self._real_key(key)\n        return k in self._data", "title": ""}
{"_id": "d11060", "text": "def _nth(arr, n):\n    \"\"\"\n    Return the nth value of array\n\n    If it is missing return NaN\n    \"\"\"\n    try:\n        return arr.iloc[n]\n    except (KeyError, IndexError):\n        return np.nan", "title": ""}
{"_id": "d11061", "text": "def set_constraint_bound(self, name, value):\n        \"\"\"Set the upper bound of a constraint.\"\"\"\n        index = self._get_constraint_index(name)\n        self.upper_bounds[index] = value\n        self._reset_solution()", "title": ""}
{"_id": "d11062", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d11063", "text": "def _days_in_month(date):\n    \"\"\"The number of days in the month of the given 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", "title": ""}
{"_id": "d11064", "text": "def schunk(string, size):\n    \"\"\"Splits string into n sized chunks.\"\"\"\n    return [string[i:i+size] for i in range(0, len(string), size)]", "title": ""}
{"_id": "d11065", "text": "def count(data, axis=None):\n    \"\"\"Count the number of non-NA in this array along the given axis or axes\n    \"\"\"\n    return np.sum(np.logical_not(isnull(data)), axis=axis)", "title": ""}
{"_id": "d11066", "text": "def _normalize_instancemethod(instance_method):\n    \"\"\"\n    wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up;\n    we want the original repr to show up in the logs, therefore we do this trick\n    \"\"\"\n    if not hasattr(instance_method, 'im_self'):\n        return instance_method\n\n    def _func(*args, **kwargs):\n        return instance_method(*args, **kwargs)\n\n    _func.__name__ = repr(instance_method)\n    return _func", "title": ""}
{"_id": "d11067", "text": "def cli_command_quit(self, msg):\n        \"\"\"\\\n        kills the child and exits\n        \"\"\"\n        if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:\n            self.sprocess.proc.kill()\n        else:\n            sys.exit(0)", "title": ""}
{"_id": "d11068", "text": "def get_previous(self):\n        \"\"\"Get the billing cycle prior to this one. May return None\"\"\"\n        return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()", "title": ""}
{"_id": "d11069", "text": "def get_number(s, cast=int):\n    \"\"\"\n    Try to get a number out of a string, and cast it.\n    \"\"\"\n    import string\n    d = \"\".join(x for x in str(s) if x in string.digits)\n    return cast(d)", "title": ""}
{"_id": "d11070", "text": "def get_keys_from_class(cc):\n    \"\"\"Return list of the key property names for a class \"\"\"\n    return [prop.name for prop in cc.properties.values() \\\n            if 'key' in prop.qualifiers]", "title": ""}
{"_id": "d11071", "text": "def log_to_json(log):\n    \"\"\"Convert a log record into a list of strings\"\"\"\n    return [log.timestamp.isoformat()[:22],\n            log.level, log.process, log.message]", "title": ""}
{"_id": "d11072", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d11073", "text": "def get_colors(img):\n    \"\"\"\n    Returns a list of all the image's colors.\n    \"\"\"\n    w, h = img.size\n    return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]", "title": ""}
{"_id": "d11074", "text": "def upgrade(directory, sql, tag, x_arg, revision):\n    \"\"\"Upgrade to a later version\"\"\"\n    _upgrade(directory, revision, sql, tag, x_arg)", "title": ""}
{"_id": "d11075", "text": "def get(key, default=None):\n    \"\"\" return the key from the request\n    \"\"\"\n    data = get_form() or get_query_string()\n    return data.get(key, default)", "title": ""}
{"_id": "d11076", "text": "def inverseHistogram(hist, bin_range):\n    \"\"\"sample data from given histogram and min, max values within range\n\n    Returns:\n        np.array: data that would create the same histogram as given\n    \"\"\"\n    data = hist.astype(float) / np.min(hist[np.nonzero(hist)])\n    new_data = np.empty(shape=np.sum(data, dtype=int))\n    i = 0\n    xvals = np.linspace(bin_range[0], bin_range[1], len(data))\n    for d, x in zip(data, xvals):\n        new_data[i:i + d] = x\n        i += int(d)\n    return new_data", "title": ""}
{"_id": "d11077", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d11078", "text": "def __enter__(self):\n        \"\"\" Implements the context manager protocol. Specially useful for asserting exceptions\n        \"\"\"\n        clone = self.clone()\n        self._contexts.append(clone)\n        self.reset()\n        return self", "title": ""}
{"_id": "d11079", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d11080", "text": "def is_iterable(value):\n    \"\"\"must be an iterable (list, array, tuple)\"\"\"\n    return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "title": ""}
{"_id": "d11081", "text": "def find_nearest_index(arr, value):\n    \"\"\"For a given value, the function finds the nearest value\n    in the array and returns its index.\"\"\"\n    arr = np.array(arr)\n    index = (abs(arr-value)).argmin()\n    return index", "title": ""}
{"_id": "d11082", "text": "def html(header_rows):\n    \"\"\"\n    Convert a list of tuples describing a table into a HTML string\n    \"\"\"\n    name = 'table%d' % next(tablecounter)\n    return HtmlTable([map(str, row) for row in header_rows], name).render()", "title": ""}
{"_id": "d11083", "text": "def get_index_nested(x, i):\n    \"\"\"\n    Description:\n        Returns the first index of the array (vector) x containing the value i.\n    Parameters:\n        x: one-dimensional array\n        i: search value\n    \"\"\"\n    for ind in range(len(x)):\n        if i == x[ind]:\n            return ind\n    return -1", "title": ""}
{"_id": "d11084", "text": "def process_bool_arg(arg):\n    \"\"\" Determine True/False from argument \"\"\"\n    if isinstance(arg, bool):\n        return arg\n    elif isinstance(arg, basestring):\n        if arg.lower() in [\"true\", \"1\"]:\n            return True\n        elif arg.lower() in [\"false\", \"0\"]:\n            return False", "title": ""}
{"_id": "d11085", "text": "def file_length(file_obj):\n    \"\"\"\n    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.\n    \"\"\"\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length", "title": ""}
{"_id": "d11086", "text": "def ensure_dir_exists(directory):\n    \"\"\"Se asegura de que un directorio exista.\"\"\"\n    if directory and not os.path.exists(directory):\n        os.makedirs(directory)", "title": ""}
{"_id": "d11087", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d11088", "text": "def issuperset(self, other):\n        \"\"\"Report whether this RangeSet contains another set.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issuperset(self, other)", "title": ""}
{"_id": "d11089", "text": "def get_table_list(dbconn):\n    \"\"\"\n    Get a list of tables that exist in dbconn\n    :param dbconn: database connection\n    :return: List of table names\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n    try:\n        return [item[0] for item in cur.fetchall()]\n    except IndexError:\n        return get_table_list(dbconn)", "title": ""}
{"_id": "d11090", "text": "def resize_image_with_crop_or_pad(img, target_height, target_width):\n    \"\"\"\n    Crops and/or pads an image to a target width and height.\n\n    Resizes an image to a target width and height by either cropping the image or padding it with zeros.\n\n    NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom right)\n\n    :param img: Numpy array representing the image.\n    :param target_height: Target height.\n    :param target_width: Target width.\n    :return: The cropped and padded image.\n    \"\"\"\n    h, w = target_height, target_width\n    max_h, max_w, c = img.shape\n\n    # crop\n    img = crop_center(img, min(max_h, h), min(max_w, w))\n\n    # pad\n    padded_img = np.zeros(shape=(h, w, c), dtype=img.dtype)\n    padded_img[:img.shape[0], :img.shape[1], :img.shape[2]] = img\n\n    return padded_img", "title": ""}
{"_id": "d11091", "text": "def debug_on_error(type, value, tb):\n    \"\"\"Code due to Thomas Heller - published in Python Cookbook (O'Reilley)\"\"\"\n    traceback.print_exc(type, value, tb)\n    print()\n    pdb.pm()", "title": ""}
{"_id": "d11092", "text": "def timestamp_from_datetime(dt):\n    \"\"\"\n    Compute timestamp from a datetime object that could be timezone aware\n    or unaware.\n    \"\"\"\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())", "title": ""}
{"_id": "d11093", "text": "def resize_image(self, data, size):\n        \"\"\" Resizes the given image to fit inside a box of the given size. \"\"\"\n        from machina.core.compat import PILImage as Image\n        image = Image.open(BytesIO(data))\n\n        # Resize!\n        image.thumbnail(size, Image.ANTIALIAS)\n\n        string = BytesIO()\n        image.save(string, format='PNG')\n        return string.getvalue()", "title": ""}
{"_id": "d11094", "text": "def find_all(self, string, callback):\n\t\t\"\"\"\n\t\tWrapper on iter method, callback gets an iterator result\n\t\t\"\"\"\n\t\tfor index, output in self.iter(string):\n\t\t\tcallback(index, output)", "title": ""}
{"_id": "d11095", "text": "def scale_image(image, new_width):\n    \"\"\"Resizes an image preserving the aspect ratio.\n    \"\"\"\n    (original_width, original_height) = image.size\n    aspect_ratio = original_height/float(original_width)\n    new_height = int(aspect_ratio * new_width)\n\n    # This scales it wider than tall, since characters are biased\n    new_image = image.resize((new_width*2, new_height))\n    return new_image", "title": ""}
{"_id": "d11096", "text": "def getChildElementsByTagName(self, tagName):\n    \"\"\" Return child elements of type tagName if found, else [] \"\"\"\n    result = []\n    for child in self.childNodes:\n        if isinstance(child, Element):\n            if child.tagName == tagName:\n                result.append(child)\n    return result", "title": ""}
{"_id": "d11097", "text": "def _hue(color, **kwargs):\n    \"\"\" Get hue value of HSL color.\n    \"\"\"\n    h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0]\n    return NumberValue(h * 360.0)", "title": ""}
{"_id": "d11098", "text": "def search_script_directory(self, path):\n        \"\"\"\n        Recursively loop through a directory to find all python\n        script files. When one is found, it is analyzed for import statements\n        :param path: string\n        :return: generator\n        \"\"\"\n        for subdir, dirs, files in os.walk(path):\n            for file_name in files:\n                if file_name.endswith(\".py\"):\n                    self.search_script_file(subdir, file_name)", "title": ""}
{"_id": "d11099", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d11100", "text": "def dfs_recursive(graph, node, seen):\n    \"\"\"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|)`\n    \"\"\"\n    seen[node] = True\n    for neighbor in graph[node]:\n        if not seen[neighbor]:\n            dfs_recursive(graph, neighbor, seen)", "title": ""}
{"_id": "d11101", "text": "def inverse(self):\n        \"\"\"\n        Returns inverse of transformation.\n        \"\"\"\n        invr = np.linalg.inv(self.affine_matrix)\n        return SymmOp(invr)", "title": ""}
{"_id": "d11102", "text": "def to_networkx(graph):\n    \"\"\" Convert a Mapper 1-complex to a networkx graph.\n\n    Parameters\n    -----------\n\n    graph: dictionary, graph object returned from `kmapper.map`\n\n    Returns\n    --------\n\n    g: graph as networkx.Graph() object\n\n    \"\"\"\n\n    # import here so networkx is not always required.\n    import networkx as nx\n\n    nodes = graph[\"nodes\"].keys()\n    edges = [[start, end] for start, ends in graph[\"links\"].items() for end in ends]\n\n    g = nx.Graph()\n    g.add_nodes_from(nodes)\n    nx.set_node_attributes(g, dict(graph[\"nodes\"]), \"membership\")\n\n    g.add_edges_from(edges)\n\n    return g", "title": ""}
{"_id": "d11103", "text": "def indent(self):\n        \"\"\"\n        Begins an indented block. Must be used in a 'with' code block.\n        All calls to the logger inside of the block will be indented.\n        \"\"\"\n        blk = IndentBlock(self, self._indent)\n        self._indent += 1\n        return blk", "title": ""}
{"_id": "d11104", "text": "def _text_to_graphiz(self, text):\n        \"\"\"create a graphviz graph from text\"\"\"\n        dot = Source(text, format='svg')\n        return dot.pipe().decode('utf-8')", "title": ""}
{"_id": "d11105", "text": "def rgb2gray(img):\n    \"\"\"Converts an RGB image to grayscale using matlab's algorithm.\"\"\"\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", "title": ""}
{"_id": "d11106", "text": "def MultiArgMax(x):\n  \"\"\"\n  Get tuple (actually a generator) of indices where the max value of\n  array x occurs. Requires that x have a max() method, as x.max()\n  (in the case of NumPy) is much faster than max(x).\n  For a simpler, faster argmax when there is only a single maximum entry,\n  or when knowing only the first index where the maximum occurs,\n  call argmax() on a NumPy array.\n\n  :param x: Any sequence that has a max() method.\n  :returns: Generator with the indices where the max value occurs.\n  \"\"\"\n  m = x.max()\n  return (i for i, v in enumerate(x) if v == m)", "title": ""}
{"_id": "d11107", "text": "def hamming(s, t):\n    \"\"\"\n    Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.\n\n    :param s: string 1\n    :type s: str\n    :param t: string 2\n    :type s: str\n    :return: Hamming distance\n    :rtype: float\n    \"\"\"\n    if len(s) != len(t):\n        raise ValueError('Hamming distance needs strings of equal length.')\n    return sum(s_ != t_ for s_, t_ in zip(s, t))", "title": ""}
{"_id": "d11108", "text": "def equal(list1, list2):\n    \"\"\" takes flags returns indexes of True values \"\"\"\n    return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]", "title": ""}
{"_id": "d11109", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d11110", "text": "def get_public_members(obj):\n    \"\"\"\n    Retrieves a list of member-like objects (members or properties) that are\n    publically exposed.\n\n    :param obj: The object to probe.\n    :return:    A list of strings.\n    \"\"\"\n    return {attr: getattr(obj, attr) for attr in dir(obj)\n            if not attr.startswith(\"_\")\n            and not hasattr(getattr(obj, attr), '__call__')}", "title": ""}
{"_id": "d11111", "text": "def hide(self):\n        \"\"\"Hide the window.\"\"\"\n        self.tk.withdraw()\n        self._visible = False\n        if self._modal:\n            self.tk.grab_release()", "title": ""}
{"_id": "d11112", "text": "def _module_name_from_previous_frame(num_frames_back):\n    \"\"\"\n    Returns the module name associated with a frame `num_frames_back` in the\n    call stack. This function adds 1 to account for itself, so `num_frames_back`\n    should be given relative to the caller.\n    \"\"\"\n    frm = inspect.stack()[num_frames_back + 1]\n    return inspect.getmodule(frm[0]).__name__", "title": ""}
{"_id": "d11113", "text": "def combinations(l):\n    \"\"\"Pure-Python implementation of itertools.combinations(l, 2).\"\"\"\n    result = []\n    for x in xrange(len(l) - 1):\n        ls = l[x + 1:]\n        for y in ls:\n            result.append((l[x], y))\n    return result", "title": ""}
{"_id": "d11114", "text": "def pop():\n        \"\"\"Remove instance from instance list\"\"\"\n        pid = os.getpid()\n        thread = threading.current_thread()\n        Wdb._instances.pop((pid, thread))", "title": ""}
{"_id": "d11115", "text": "def xeval(source, optimize=True):\n    \"\"\"Compiles to native Python bytecode and runs program, returning the\n    topmost value on the stack.\n\n    Args:\n        optimize: Whether to optimize the code after parsing it.\n\n    Returns:\n        None: If the stack is empty\n        obj: If the stack contains a single value\n        [obj, obj, ...]: If the stack contains many values\n    \"\"\"\n    native = xcompile(source, optimize=optimize)\n    return native()", "title": ""}
{"_id": "d11116", "text": "def type_converter(text):\n    \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n    if text.isdigit():\n        return int(text), int\n\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE", "title": ""}
{"_id": "d11117", "text": "def getpackagepath():\n    \"\"\"\n     *Get the root path for this python package - used in unit testing code*\n    \"\"\"\n    moduleDirectory = os.path.dirname(__file__)\n    packagePath = os.path.dirname(__file__) + \"/../\"\n\n    return packagePath", "title": ""}
{"_id": "d11118", "text": "def get_example_features(example):\n  \"\"\"Returns the non-sequence features from the provided example.\"\"\"\n  return (example.features.feature if isinstance(example, tf.train.Example)\n          else example.context.feature)", "title": ""}
{"_id": "d11119", "text": "def intToBin(i):\n    \"\"\" Integer to two bytes \"\"\"\n    # devide in two parts (bytes)\n    i1 = i % 256\n    i2 = int(i / 256)\n    # make string (little endian)\n    return chr(i1) + chr(i2)", "title": ""}
{"_id": "d11120", "text": "def to_unicode_repr( _letter ):\n    \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n        in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n    # Python 2-3 compatible\n    return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"", "title": ""}
{"_id": "d11121", "text": "def isdir(s):\n    \"\"\"Return true if the pathname refers to an existing directory.\"\"\"\n    try:\n        st = os.stat(s)\n    except os.error:\n        return False\n    return stat.S_ISDIR(st.st_mode)", "title": ""}
{"_id": "d11122", "text": "def fopenat(base_fd, path):\n    \"\"\"\n    Does openat read-only, then does fdopen to get a file object\n    \"\"\"\n\n    return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')", "title": ""}
{"_id": "d11123", "text": "def widget(self, f):\n        \"\"\"\n        Return an interactive function widget for the given function.\n\n        The widget is only constructed, not displayed nor attached to\n        the function.\n\n        Returns\n        -------\n        An instance of ``self.cls`` (typically :class:`interactive`).\n\n        Parameters\n        ----------\n        f : function\n            The function to which the interactive widgets are tied.\n        \"\"\"\n        return self.cls(f, self.opts, **self.kwargs)", "title": ""}
{"_id": "d11124", "text": "def main(pargs):\n    \"\"\"This should only be used for testing. The primary mode of operation is\n    as an imported library.\n    \"\"\"\n    input_file = sys.argv[1]\n    fp = ParseFileLineByLine(input_file)\n    for i in fp:\n        print(i)", "title": ""}
{"_id": "d11125", "text": "def last_day(year=_year, month=_month):\n    \"\"\"\n    get the current month's last day\n    :param year:  default to current year\n    :param month:  default to current month\n    :return: month's last day\n    \"\"\"\n    last_day = calendar.monthrange(year, month)[1]\n    return datetime.date(year=year, month=month, day=last_day)", "title": ""}
{"_id": "d11126", "text": "def restart(self, reset=False):\n        \"\"\"\n        Quit and Restart Spyder application.\n\n        If reset True it allows to reset spyder on restart.\n        \"\"\"\n        # Get start path to use in restart script\n        spyder_start_directory = get_module_path('spyder')\n        restart_script = osp.join(spyder_start_directory, 'app', 'restart.py')\n\n        # Get any initial argument passed when spyder was started\n        # Note: Variables defined in bootstrap.py and spyder/app/start.py\n        env = os.environ.copy()\n        bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None)\n        spyder_args = env.pop('SPYDER_ARGS')\n\n        # Get current process and python running spyder\n        pid = os.getpid()\n        python = sys.executable\n\n        # Check if started with bootstrap.py\n        if bootstrap_args is not None:\n            spyder_args = bootstrap_args\n            is_bootstrap = True\n        else:\n            is_bootstrap = False\n\n        # Pass variables as environment variables (str) to restarter subprocess\n        env['SPYDER_ARGS'] = spyder_args\n        env['SPYDER_PID'] = str(pid)\n        env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap)\n        env['SPYDER_RESET'] = str(reset)\n\n        if DEV:\n            if os.name == 'nt':\n                env['PYTHONPATH'] = ';'.join(sys.path)\n            else:\n                env['PYTHONPATH'] = ':'.join(sys.path)\n\n        # Build the command and popen arguments depending on the OS\n        if os.name == 'nt':\n            # Hide flashing command prompt\n            startupinfo = subprocess.STARTUPINFO()\n            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n            shell = False\n        else:\n            startupinfo = None\n            shell = True\n\n        command = '\"{0}\" \"{1}\"'\n        command = command.format(python, restart_script)\n\n        try:\n            if self.closing(True):\n                subprocess.Popen(command, shell=shell, env=env,\n                                 startupinfo=startupinfo)\n                self.console.quit()\n        except Exception as error:\n            # If there is an error with subprocess, Spyder should not quit and\n            # the error can be inspected in the internal console\n            print(error)  # spyder: test-skip\n            print(command)", "title": ""}
{"_id": "d11127", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d11128", "text": "def server(port):\n    \"\"\"Start the Django dev server.\"\"\"\n    args = ['python', 'manage.py', 'runserver']\n    if port:\n        args.append(port)\n    run.main(args)", "title": ""}
{"_id": "d11129", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d11130", "text": "def safe_int(val, default=None):\n    \"\"\"\n    Returns int() of val if val is not convertable to int use default\n    instead\n\n    :param val:\n    :param default:\n    \"\"\"\n\n    try:\n        val = int(val)\n    except (ValueError, TypeError):\n        val = default\n\n    return val", "title": ""}
{"_id": "d11131", "text": "def _iterate_flattened_values(value):\n  \"\"\"Provides an iterator over all values in a nested structure.\"\"\"\n  if isinstance(value, six.string_types):\n    yield value\n    return\n\n  if isinstance(value, collections.Mapping):\n    value = collections.ValuesView(value)\n\n  if isinstance(value, collections.Iterable):\n    for nested_value in value:\n      for nested_nested_value in _iterate_flattened_values(nested_value):\n        yield nested_nested_value\n\n  yield value", "title": ""}
{"_id": "d11132", "text": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "title": ""}
{"_id": "d11133", "text": "def listified_tokenizer(source):\n    \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n    io_obj = io.StringIO(source)\n    return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]", "title": ""}
{"_id": "d11134", "text": "def compare(dicts):\n    \"\"\"Compare by iteration\"\"\"\n\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\n    return common_members", "title": ""}
{"_id": "d11135", "text": "def check_github(self):\n        \"\"\"\n        If the requirement is frozen to a github url, check for new commits.\n\n        API Tokens\n        ----------\n        For more than 50 github api calls per hour, pipchecker requires\n        authentication with the github api by settings the environemnt\n        variable ``GITHUB_API_TOKEN`` or setting the command flag\n        --github-api-token='mytoken'``.\n\n        To create a github api token for use at the command line::\n             curl -u 'rizumu' -d '{\"scopes\":[\"repo\"], \"note\":\"pipchecker\"}' https://api.github.com/authorizations\n\n        For more info on github api tokens:\n            https://help.github.com/articles/creating-an-oauth-token-for-command-line-use\n            http://developer.github.com/v3/oauth/#oauth-authorizations-api\n\n        Requirement Format\n        ------------------\n        Pipchecker gets the sha of frozen repo and checks if it is\n        found at the head of any branches. If it is not found then\n        the requirement is considered to be out of date.\n\n        Therefore, freezing at the commit hash will provide the expected\n        results, but if freezing at a branch or tag name, pipchecker will\n        not be able to determine with certainty if the repo is out of date.\n\n        Freeze at the commit hash (sha)::\n            git+git://github.com/django/django.git@393c268e725f5b229ecb554f3fac02cfc250d2df#egg=Django\n            https://github.com/django/django/archive/393c268e725f5b229ecb554f3fac02cfc250d2df.tar.gz#egg=Django\n            https://github.com/django/django/archive/393c268e725f5b229ecb554f3fac02cfc250d2df.zip#egg=Django\n\n        Freeze with a branch name::\n            git+git://github.com/django/django.git@master#egg=Django\n            https://github.com/django/django/archive/master.tar.gz#egg=Django\n            https://github.com/django/django/archive/master.zip#egg=Django\n\n        Freeze with a tag::\n            git+git://github.com/django/django.git@1.5b2#egg=Django\n            https://github.com/django/django/archive/1.5b2.tar.gz#egg=Django\n            https://github.com/django/django/archive/1.5b2.zip#egg=Django\n\n        Do not freeze::\n            git+git://github.com/django/django.git#egg=Django\n\n        \"\"\"\n        for name, req in list(self.reqs.items()):\n            req_url = req[\"url\"]\n            if not req_url:\n                continue\n            req_url = str(req_url)\n            if req_url.startswith(\"git\") and \"github.com/\" not in req_url:\n                continue\n            if req_url.endswith((\".tar.gz\", \".tar.bz2\", \".zip\")):\n                continue\n\n            headers = {\n                \"content-type\": \"application/json\",\n            }\n            if self.github_api_token:\n                headers[\"Authorization\"] = \"token {0}\".format(self.github_api_token)\n            try:\n                path_parts = urlparse(req_url).path.split(\"#\", 1)[0].strip(\"/\").rstrip(\"/\").split(\"/\")\n\n                if len(path_parts) == 2:\n                    user, repo = path_parts\n\n                elif 'archive' in path_parts:\n                    # Supports URL of format:\n                    # https://github.com/django/django/archive/master.tar.gz#egg=Django\n                    # https://github.com/django/django/archive/master.zip#egg=Django\n                    user, repo = path_parts[:2]\n                    repo += '@' + path_parts[-1].replace('.tar.gz', '').replace('.zip', '')\n\n                else:\n                    self.style.ERROR(\"\\nFailed to parse %r\\n\" % (req_url, ))\n                    continue\n            except (ValueError, IndexError) as e:\n                self.stdout.write(self.style.ERROR(\"\\nFailed to parse %r: %s\\n\" % (req_url, e)))\n                continue\n\n            try:\n                test_auth = requests.get(\"https://api.github.com/django/\", headers=headers).json()\n            except HTTPError as e:\n                self.stdout.write(\"\\n%s\\n\" % str(e))\n                return\n\n            if \"message\" in test_auth and test_auth[\"message\"] == \"Bad credentials\":\n                self.stdout.write(self.style.ERROR(\"\\nGithub API: Bad credentials. Aborting!\\n\"))\n                return\n            elif \"message\" in test_auth and test_auth[\"message\"].startswith(\"API Rate Limit Exceeded\"):\n                self.stdout.write(self.style.ERROR(\"\\nGithub API: Rate Limit Exceeded. Aborting!\\n\"))\n                return\n\n            frozen_commit_sha = None\n            if \".git\" in repo:\n                repo_name, frozen_commit_full = repo.split(\".git\")\n                if frozen_commit_full.startswith(\"@\"):\n                    frozen_commit_sha = frozen_commit_full[1:]\n            elif \"@\" in repo:\n                repo_name, frozen_commit_sha = repo.split(\"@\")\n\n            if frozen_commit_sha is None:\n                msg = self.style.ERROR(\"repo is not frozen\")\n\n            if frozen_commit_sha:\n                branch_url = \"https://api.github.com/repos/{0}/{1}/branches\".format(user, repo_name)\n                branch_data = requests.get(branch_url, headers=headers).json()\n\n                frozen_commit_url = \"https://api.github.com/repos/{0}/{1}/commits/{2}\".format(\n                    user, repo_name, frozen_commit_sha\n                )\n                frozen_commit_data = requests.get(frozen_commit_url, headers=headers).json()\n\n                if \"message\" in frozen_commit_data and frozen_commit_data[\"message\"] == \"Not Found\":\n                    msg = self.style.ERROR(\"{0} not found in {1}. Repo may be private.\".format(frozen_commit_sha[:10], name))\n                elif frozen_commit_data[\"sha\"] in [branch[\"commit\"][\"sha\"] for branch in branch_data]:\n                    msg = self.style.BOLD(\"up to date\")\n                else:\n                    msg = self.style.INFO(\"{0} is not the head of any branch\".format(frozen_commit_data[\"sha\"][:10]))\n\n            if \"dist\" in req:\n                pkg_info = \"{dist.project_name} {dist.version}\".format(dist=req[\"dist\"])\n            elif frozen_commit_sha is None:\n                pkg_info = name\n            else:\n                pkg_info = \"{0} {1}\".format(name, frozen_commit_sha[:10])\n            self.stdout.write(\"{pkg_info:40} {msg}\".format(pkg_info=pkg_info, msg=msg))\n            del self.reqs[name]", "title": ""}
{"_id": "d11136", "text": "def __call__(self, _):\n        \"\"\"Update the progressbar.\"\"\"\n        if self.iter % self.step == 0:\n            self.pbar.update(self.step)\n\n        self.iter += 1", "title": ""}
{"_id": "d11137", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d11138", "text": "def _query_for_reverse_geocoding(lat, lng):\n    \"\"\"\n    Given a lat & lng, what's the string search query.\n\n    If the API changes, change this function. Only for internal use.\n    \"\"\"\n    # have to do some stupid f/Decimal/str stuff to (a) ensure we get as much\n    # decimal places as the user already specified and (b) to ensure we don't\n    # get e-5 stuff\n    return \"{0:f},{1:f}\".format(Decimal(str(lat)), Decimal(str(lng)))", "title": ""}
{"_id": "d11139", "text": "def iterparse(source, events=('end',), remove_comments=True, **kw):\n    \"\"\"Thin wrapper around ElementTree.iterparse\"\"\"\n    return ElementTree.iterparse(source, events, SourceLineParser(), **kw)", "title": ""}
{"_id": "d11140", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d11141", "text": "def jaccard(c_1, c_2):\n    \"\"\"\n    Calculates the Jaccard similarity between two sets of nodes. Called by mroc.\n\n    Inputs:  - c_1: Community (set of nodes) 1.\n             - c_2: Community (set of nodes) 2.\n\n    Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.\n    \"\"\"\n    nom = np.intersect1d(c_1, c_2).size\n    denom = np.union1d(c_1, c_2).size\n    return nom/denom", "title": ""}
{"_id": "d11142", "text": "def cli_command_quit(self, msg):\n        \"\"\"\\\n        kills the child and exits\n        \"\"\"\n        if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:\n            self.sprocess.proc.kill()\n        else:\n            sys.exit(0)", "title": ""}
{"_id": "d11143", "text": "def render(template, context):\n        \"\"\"Wrapper to the jinja2 render method from a template file\n\n        Parameters\n        ----------\n        template : str\n            Path to template file.\n        context : dict\n            Dictionary with kwargs context to populate the template\n        \"\"\"\n\n        path, filename = os.path.split(template)\n\n        return jinja2.Environment(\n            loader=jinja2.FileSystemLoader(path or './')\n        ).get_template(filename).render(context)", "title": ""}
{"_id": "d11144", "text": "def load_image(fname):\n    \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n    with open(fname, \"rb\") as f:\n        i = Image.open(fname)\n        #i.load()\n        return i", "title": ""}
{"_id": "d11145", "text": "def format_line(data, linestyle):\n    \"\"\"Formats a list of elements using the given line style\"\"\"\n    return linestyle.begin + linestyle.sep.join(data) + linestyle.end", "title": ""}
{"_id": "d11146", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d11147", "text": "def get_join_cols(by_entry):\n  \"\"\" helper function used for joins\n  builds left and right join list for join function\n  \"\"\"\n  left_cols = []\n  right_cols = []\n  for col in by_entry:\n    if isinstance(col, str):\n      left_cols.append(col)\n      right_cols.append(col)\n    else:\n      left_cols.append(col[0])\n      right_cols.append(col[1])\n  return left_cols, right_cols", "title": ""}
{"_id": "d11148", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d11149", "text": "def join_images(img_files, out_file):\n    \"\"\"Join the list of images into the out file\"\"\"\n    images = [PIL.Image.open(f) for f in img_files]\n    joined = PIL.Image.new(\n        'RGB',\n        (sum(i.size[0] for i in images), max(i.size[1] for i in images))\n    )\n    left = 0\n    for img in images:\n        joined.paste(im=img, box=(left, 0))\n        left = left + img.size[0]\n    joined.save(out_file)", "title": ""}
{"_id": "d11150", "text": "def equal(obj1, obj2):\n    \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n    Comparable.log(obj1, obj2, '==')\n    equality = obj1.equality(obj2)\n    Comparable.log(obj1, obj2, '==', result=equality)\n    return equality", "title": ""}
{"_id": "d11151", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d11152", "text": "def type_converter(text):\n    \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n    if text.isdigit():\n        return int(text), int\n\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE", "title": ""}
{"_id": "d11153", "text": "def urljoin(*urls):\n    \"\"\"\n    The default urlparse.urljoin behavior look strange\n    Standard urlparse.urljoin('http://a.com/foo', '/bar')\n    Expect: http://a.com/foo/bar\n    Actually: http://a.com/bar\n\n    This function fix that.\n    \"\"\"\n    return reduce(urlparse.urljoin, [u.strip('/')+'/' for u in urls if u.strip('/')], '').rstrip('/')", "title": ""}
{"_id": "d11154", "text": "def complex_check(*args, func=None):\n    \"\"\"Check if arguments are complex numbers.\"\"\"\n    func = func or inspect.stack()[2][3]\n    for var in args:\n        if not isinstance(var, numbers.Complex):\n            name = type(var).__name__\n            raise ComplexError(\n                f'Function {func} expected complex number, {name} got instead.')", "title": ""}
{"_id": "d11155", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d11156", "text": "def magic(self, alias):\n        \"\"\"Returns the appropriate IPython code magic when\n        called with an alias for a language.\n        \"\"\"\n        if alias in self.aliases:\n            return self.aliases[alias]\n        else:\n            return \"%%{}\\n\".format(alias)", "title": ""}
{"_id": "d11157", "text": "def is_serializable(obj):\n    \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool\n    \"\"\"\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')", "title": ""}
{"_id": "d11158", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d11159", "text": "def pprint(j, no_pretty):\n    \"\"\"\n    Prints as formatted JSON\n    \"\"\"\n    if not no_pretty:\n        click.echo(\n            json.dumps(j, cls=PotionJSONEncoder, sort_keys=True, indent=4, separators=(\",\", \": \"))\n        )\n    else:\n        click.echo(j)", "title": ""}
{"_id": "d11160", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d11161", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d11162", "text": "def dump_json(obj):\n    \"\"\"Dump Python object as JSON string.\"\"\"\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)", "title": ""}
{"_id": "d11163", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d11164", "text": "def parse_json(filename):\n    \"\"\" Parse a JSON file\n        First remove comments and then use the json module package\n        Comments look like :\n            // ...\n        or\n            /*\n            ...\n            */\n    \"\"\"\n    # Regular expression for comments\n    comment_re = re.compile(\n        '(^)?[^\\S\\n]*/(?:\\*(.*?)\\*/[^\\S\\n]*|/[^\\n]*)($)?',\n        re.DOTALL | re.MULTILINE\n    )\n\n    with open(filename) as f:\n        content = ''.join(f.readlines())\n\n        ## Looking for comments\n        match = comment_re.search(content)\n        while match:\n            # single line comment\n            content = content[:match.start()] + content[match.end():]\n            match = comment_re.search(content)\n\n        # Return json file\n        return json.loads(content)", "title": ""}
{"_id": "d11165", "text": "def find_first_number(ll):\n    \"\"\" Returns nr of first entry parseable to float in ll, None otherwise\"\"\"\n    for nr, entry in enumerate(ll):\n        try:\n            float(entry)\n        except (ValueError, TypeError) as e:\n            pass\n        else:\n            return nr\n    return None", "title": ""}
{"_id": "d11166", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d11167", "text": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "title": ""}
{"_id": "d11168", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d11169", "text": "def linedelimited (inlist,delimiter):\n    \"\"\"\nReturns a string composed of elements in inlist, with each element\nseparated by 'delimiter.'  Used by function writedelimited.  Use '\\t'\nfor tab-delimiting.\n\nUsage:   linedelimited (inlist,delimiter)\n\"\"\"\n    outstr = ''\n    for item in inlist:\n        if type(item) != StringType:\n            item = str(item)\n        outstr = outstr + item + delimiter\n    outstr = outstr[0:-1]\n    return outstr", "title": ""}
{"_id": "d11170", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d11171", "text": "def plot_kde(data, ax, title=None, color='r', fill_bt=True):\n    \"\"\"\n    Plot a smoothed (by kernel density estimate) histogram.\n    :type data: numpy array\n    :param data: An array containing the data to be plotted\n\n    :type ax: matplotlib.Axes\n    :param ax: The Axes object to draw to\n\n    :type title: str\n    :param title: The plot title\n\n    :type color: str\n    :param color: The color of the histogram line and fill. Note that the fill\n                  will be plotted with an alpha of 0.35.\n\n    :type fill_bt: bool\n    :param fill_bt: Specify whether to fill the area beneath the histogram line\n    \"\"\"\n    if isinstance(data, list):\n        data = np.asarray(data)\n    e = kde.KDEUnivariate(data.astype(np.float))\n    e.fit()\n    ax.plot(e.support, e.density, color=color, alpha=0.9, linewidth=2.25)\n    if fill_bt:\n        ax.fill_between(e.support, e.density, alpha=.35, zorder=1,\n                        antialiased=True, color=color)\n    if title is not None:\n        t = ax.set_title(title)\n        t.set_y(1.05)", "title": ""}
{"_id": "d11172", "text": "def indent(txt, spacing=4):\n    \"\"\"\n    Indent given text using custom spacing, default is set to 4.\n    \"\"\"\n    return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))", "title": ""}
{"_id": "d11173", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d11174", "text": "def get_long_description():\n    \"\"\" Read the long description. \"\"\"\n    here = path.abspath(path.dirname(__file__))\n    with open(path.join(here, 'README.rst')) as readme:\n        return readme.read()\n    return None", "title": ""}
{"_id": "d11175", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d11176", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d11177", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d11178", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d11179", "text": "def has_edit_permission(self, request):\n        \"\"\" Can edit this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "title": ""}
{"_id": "d11180", "text": "def last(self):\n        \"\"\"Get the last object in file.\"\"\"\n        # End of file\n        self.__file.seek(0, 2)\n\n        # Get the last struct\n        data = self.get(self.length - 1)\n\n        return data", "title": ""}
{"_id": "d11181", "text": "def print_display_png(o):\n    \"\"\"\n    A function to display sympy expression using display style LaTeX in PNG.\n    \"\"\"\n    s = latex(o, mode='plain')\n    s = s.strip('$')\n    # As matplotlib does not support display style, dvipng backend is\n    # used here.\n    png = latex_to_png('$$%s$$' % s, backend='dvipng')\n    return png", "title": ""}
{"_id": "d11182", "text": "def lazy_reverse_binmap(f, xs):\n    \"\"\"\n    Same as lazy_binmap, except the parameters are flipped for the binary function\n    \"\"\"\n    return (f(y, x) for x, y in zip(xs, xs[1:]))", "title": ""}
{"_id": "d11183", "text": "def _mid(string, start, end=None):\n    \"\"\"\n    Returns a substring delimited by start and end position.\n    \"\"\"\n    if end is None:\n        end = len(string)\n    return string[start:start + end]", "title": ""}
{"_id": "d11184", "text": "def log_normalize(data):\n    \"\"\"Perform log transform log(x + 1).\n    \n    Parameters\n    ----------\n    data : array_like\n    \n    \"\"\"\n    if sp.issparse(data):\n        data = data.copy()\n        data.data = np.log2(data.data + 1)\n        return data\n\n    return np.log2(data.astype(np.float64) + 1)", "title": ""}
{"_id": "d11185", "text": "def size(self):\n        \"\"\"\n        Recursively find size of a tree. Slow.\n        \"\"\"\n\n        if self is NULL:\n            return 0\n        return 1 + self.left.size() + self.right.size()", "title": ""}
{"_id": "d11186", "text": "def confirm(question, default=True):\n    \"\"\"Ask a yes/no question interactively.\n\n    :param question: The text of the question to ask.\n    :returns: True if the answer was \"yes\", False otherwise.\n    \"\"\"\n    valid = {\"\": default, \"yes\": True, \"y\": True, \"no\": False, \"n\": False}\n    while 1:\n        choice = input(question + (\" [Y/n] \" if default else \" [y/N] \")).lower()\n        if choice in valid:\n            return valid[choice]\n        print(\"Please respond with 'y' or 'n' \")", "title": ""}
{"_id": "d11187", "text": "def levenshtein_distance_metric(a, b):\n    \"\"\" 1 - farthest apart (same number of words, all diff). 0 - same\"\"\"\n    return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1)))", "title": ""}
{"_id": "d11188", "text": "def classnameify(s):\n  \"\"\"\n  Makes a classname\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))", "title": ""}
{"_id": "d11189", "text": "def ylim(self, low, high):\n        \"\"\"Set yaxis limits\n\n        Parameters\n        ----------\n        low : number\n        high : number\n        index : int, optional\n\n        Returns\n        -------\n        Chart\n\n        \"\"\"\n        self.chart['yAxis'][0]['min'] = low\n        self.chart['yAxis'][0]['max'] = high\n        return self", "title": ""}
{"_id": "d11190", "text": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d11191", "text": "def get_tail(self):\n        \"\"\"Gets tail\n\n        :return: Tail of linked list\n        \"\"\"\n        node = self.head\n        last_node = self.head\n\n        while node is not None:\n            last_node = node\n            node = node.next_node\n\n        return last_node", "title": ""}
{"_id": "d11192", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d11193", "text": "def list2string (inlist,delimit=' '):\n    \"\"\"\nConverts a 1D list to a single long string for file output, using\nthe string.join function.\n\nUsage:   list2string (inlist,delimit=' ')\nReturns: the string created from inlist\n\"\"\"\n    stringlist = [makestr(_) for _ in inlist]\n    return string.join(stringlist,delimit)", "title": ""}
{"_id": "d11194", "text": "def empirical(X):\n    \"\"\"Compute empirical covariance as baseline estimator.\n    \"\"\"\n    print(\"Empirical\")\n    cov = np.dot(X.T, X) / n_samples\n    return cov, np.linalg.inv(cov)", "title": ""}
{"_id": "d11195", "text": "def dedup(seq):\n    \"\"\"Remove duplicates from a list while keeping order.\"\"\"\n    seen = set()\n    for item in seq:\n        if item not in seen:\n            seen.add(item)\n            yield item", "title": ""}
{"_id": "d11196", "text": "def stddev(values, meanval=None):  #from AI: A Modern Appproach\n    \"\"\"The standard deviation of a set of values.\n    Pass in the mean if you already know it.\"\"\"\n    if meanval == None: meanval = mean(values)\n    return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) )", "title": ""}
{"_id": "d11197", "text": "def _fill_array_from_list(the_list, the_array):\n        \"\"\"Fill an `array` from a `list`\"\"\"\n        for i, val in enumerate(the_list):\n            the_array[i] = val\n        return the_array", "title": ""}
{"_id": "d11198", "text": "def get_previous_month(self):\n        \"\"\"Returns date range for the previous full month.\"\"\"\n        end = utils.get_month_start() - relativedelta(days=1)\n        end = utils.to_datetime(end)\n        start = utils.get_month_start(end)\n        return start, end", "title": ""}
{"_id": "d11199", "text": "def equal(list1, list2):\n    \"\"\" takes flags returns indexes of True values \"\"\"\n    return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]", "title": ""}
{"_id": "d11200", "text": "def LinSpace(start, stop, num):\n    \"\"\"\n    Linspace op.\n    \"\"\"\n    return np.linspace(start, stop, num=num, dtype=np.float32),", "title": ""}
{"_id": "d11201", "text": "def median(data):\n    \"\"\"Calculate the median of a list.\"\"\"\n    data.sort()\n    num_values = len(data)\n    half = num_values // 2\n    if num_values % 2:\n        return data[half]\n    return 0.5 * (data[half-1] + data[half])", "title": ""}
{"_id": "d11202", "text": "def printheader(h=None):\n    \"\"\"Print the header for the CSV table.\"\"\"\n    writer = csv.writer(sys.stdout)\n    writer.writerow(header_fields(h))", "title": ""}
{"_id": "d11203", "text": "def _unique_rows_numpy(a):\n    \"\"\"return unique rows\"\"\"\n    a = np.ascontiguousarray(a)\n    unique_a = np.unique(a.view([('', a.dtype)] * a.shape[1]))\n    return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))", "title": ""}
{"_id": "d11204", "text": "def comma_converter(float_string):\n    \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n    trans_table = maketrans(b',', b'.')\n    return float(float_string.translate(trans_table))", "title": ""}
{"_id": "d11205", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d11206", "text": "def b2u(string):\n    \"\"\" bytes to unicode \"\"\"\n    if (isinstance(string, bytes) or\n        (PY2 and isinstance(string, str))):\n        return string.decode('utf-8')\n    return string", "title": ""}
{"_id": "d11207", "text": "def _openResources(self):\n        \"\"\" Uses numpy.load to open the underlying file\n        \"\"\"\n        arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n        check_is_an_array(arr)\n        self._array = arr", "title": ""}
{"_id": "d11208", "text": "def comma_delimited_to_list(list_param):\n    \"\"\"Convert comma-delimited list / string into a list of strings\n\n    :param list_param: Comma-delimited string\n    :type list_param: str | unicode\n    :return: A list of strings\n    :rtype: list\n    \"\"\"\n    if isinstance(list_param, list):\n        return list_param\n    if isinstance(list_param, str):\n        return list_param.split(',')\n    else:\n        return []", "title": ""}
{"_id": "d11209", "text": "def flat(l):\n    \"\"\"\nReturns the flattened version of a '2D' list.  List-correlate to the a.flat()\nmethod of NumPy arrays.\n\nUsage:    flat(l)\n\"\"\"\n    newl = []\n    for i in range(len(l)):\n        for j in range(len(l[i])):\n            newl.append(l[i][j])\n    return newl", "title": ""}
{"_id": "d11210", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d11211", "text": "def _varargs_to_iterable_method(func):\n    \"\"\"decorator to convert a *args method to one taking a iterable\"\"\"\n    def wrapped(self, iterable, **kwargs):\n        return func(self, *iterable, **kwargs)\n    return wrapped", "title": ""}
{"_id": "d11212", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d11213", "text": "def _check_and_convert_bools(self):\n        \"\"\"Replace boolean variables by the characters 'F'/'T'\n        \"\"\"\n        replacements = {\n            True: 'T',\n            False: 'F',\n        }\n\n        for key in self.bools:\n            if isinstance(self[key], bool):\n                self[key] = replacements[self[key]]", "title": ""}
{"_id": "d11214", "text": "def findMax(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMax(arr, out)\n    return out", "title": ""}
{"_id": "d11215", "text": "def forward(self, step):\n        \"\"\"Move the turtle forward.\n\n        :param step: Integer. Distance to move forward.\n        \"\"\"\n        x = self.pos_x + math.cos(math.radians(self.rotation)) * step\n        y = self.pos_y + math.sin(math.radians(self.rotation)) * step\n        prev_brush_state = self.brush_on\n        self.brush_on = True\n        self.move(x, y)\n        self.brush_on = prev_brush_state", "title": ""}
{"_id": "d11216", "text": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "title": ""}
{"_id": "d11217", "text": "def to_str(obj):\n    \"\"\"Attempts to convert given object to a string object\n    \"\"\"\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)", "title": ""}
{"_id": "d11218", "text": "def __enter__(self):\n        \"\"\"Acquire a lock on the output file, prevents collisions between multiple runs.\"\"\"\n        self.fd = open(self.filename, 'a')\n        fcntl.lockf(self.fd, fcntl.LOCK_EX)\n        return self.fd", "title": ""}
{"_id": "d11219", "text": "def to_snake_case(s):\n    \"\"\"Converts camel-case identifiers to snake-case.\"\"\"\n    return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)", "title": ""}
{"_id": "d11220", "text": "def interpolate_logscale_single(start, end, coefficient):\n    \"\"\" Cosine interpolation \"\"\"\n    return np.exp(np.log(start) + (np.log(end) - np.log(start)) * coefficient)", "title": ""}
{"_id": "d11221", "text": "def forward(self, step):\n        \"\"\"Move the turtle forward.\n\n        :param step: Integer. Distance to move forward.\n        \"\"\"\n        x = self.pos_x + math.cos(math.radians(self.rotation)) * step\n        y = self.pos_y + math.sin(math.radians(self.rotation)) * step\n        prev_brush_state = self.brush_on\n        self.brush_on = True\n        self.move(x, y)\n        self.brush_on = prev_brush_state", "title": ""}
{"_id": "d11222", "text": "def log_loss(preds, labels):\n    \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n    log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n    return -log_likelihood", "title": ""}
{"_id": "d11223", "text": "def update_scale(self, value):\n        \"\"\" updates the scale of all actors in the plotter \"\"\"\n        self.plotter.set_scale(self.x_slider_group.value,\n                               self.y_slider_group.value,\n                               self.z_slider_group.value)", "title": ""}
{"_id": "d11224", "text": "def log_stop(logger):\n    \"\"\"log stop\"\"\"\n\n    handlers = logger.handlers[:]\n    for handler in handlers:\n        handler.close()\n        logger.removeHandler(handler)", "title": ""}
{"_id": "d11225", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d11226", "text": "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d11227", "text": "def _is_proper_sequence(seq):\n    \"\"\"Returns is seq is sequence and not string.\"\"\"\n    return (isinstance(seq, collections.abc.Sequence) and\n            not isinstance(seq, str))", "title": ""}
{"_id": "d11228", "text": "def parse(self):\n        \"\"\"\n        Parses format string looking for substitutions\n\n        This method is responsible for returning a list of fields (as strings)\n        to include in all log messages.\n        \"\"\"\n        standard_formatters = re.compile(r'\\((.+?)\\)', re.IGNORECASE)\n        return standard_formatters.findall(self._fmt)", "title": ""}
{"_id": "d11229", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d11230", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d11231", "text": "def add_queue_handler(queue):\n    \"\"\"Add a queue log handler to the global logger.\"\"\"\n    handler = QueueLogHandler(queue)\n    handler.setFormatter(QueueFormatter())\n    handler.setLevel(DEBUG)\n    GLOBAL_LOGGER.addHandler(handler)", "title": ""}
{"_id": "d11232", "text": "def contains_case_insensitive(adict, akey):\n    \"\"\"Check if key is in adict. The search is case insensitive.\"\"\"\n    for key in adict:\n        if key.lower() == akey.lower():\n            return True\n    return False", "title": ""}
{"_id": "d11233", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d11234", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d11235", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d11236", "text": "def _is_retryable_exception(e):\n    \"\"\"Returns True if the exception is always safe to retry.\n\n    This is True if the client was never able to establish a connection\n    to the server (for example, name resolution failed or the connection\n    could otherwise not be initialized).\n\n    Conservatively, if we can't tell whether a network connection could\n    have been established, we return False.\n\n    \"\"\"\n    if isinstance(e, urllib3.exceptions.ProtocolError):\n        e = e.args[1]\n    if isinstance(e, (socket.gaierror, socket.herror)):\n        return True\n    if isinstance(e, socket.error) and e.errno in _RETRYABLE_SOCKET_ERRORS:\n        return True\n    if isinstance(e, urllib3.exceptions.NewConnectionError):\n        return True\n    return False", "title": ""}
{"_id": "d11237", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d11238", "text": "def get_dt_list(fn_list):\n    \"\"\"Get list of datetime objects, extracted from a filename\n    \"\"\"\n    dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])\n    return dt_list", "title": ""}
{"_id": "d11239", "text": "def url_syntax_check(url):  # pragma: no cover\n    \"\"\"\n    Check the syntax of the given URL.\n\n    :param url: The URL to check the syntax for.\n    :type url: str\n\n    :return: The syntax validity.\n    :rtype: bool\n\n    .. warning::\n        If an empty or a non-string :code:`url` is given, we return :code:`None`.\n    \"\"\"\n\n    if url and isinstance(url, str):\n        # The given URL is not empty nor None.\n        # and\n        # * The given URL is a string.\n\n        # We silently load the configuration.\n        load_config(True)\n\n        return Check(url).is_url_valid()\n\n    # We return None, there is nothing to check.\n    return None", "title": ""}
{"_id": "d11240", "text": "def unique(transactions):\n    \"\"\" Remove any duplicate entries. \"\"\"\n    seen = set()\n    # TODO: Handle comments\n    return [x for x in transactions if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d11241", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d11242", "text": "def stdoutwriteline(*args):\n    \"\"\"\n    @type args: tuple\n    @return: None\n    \"\"\"\n    s = \"\"\n\n    for i in args:\n        s += str(i) + \" \"\n\n    s = s.strip()\n    sys.stdout.write(str(s) + \"\\n\")\n    sys.stdout.flush()\n\n    return s", "title": ""}
{"_id": "d11243", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d11244", "text": "def enableEditing(self, enabled):\n        \"\"\"Enable the editing buttons to add/remove rows/columns and to edit the data.\n\n        This method is also a slot.\n        In addition, the data of model will be made editable,\n        if the `enabled` parameter is true.\n\n        Args:\n            enabled (bool): This flag indicates, if the buttons\n                shall be activated.\n\n        \"\"\"\n        for button in self.buttons[1:]:\n            button.setEnabled(enabled)\n            if button.isChecked():\n                button.setChecked(False)\n\n        model = self.tableView.model()\n\n        if model is not None:\n            model.enableEditing(enabled)", "title": ""}
{"_id": "d11245", "text": "def _not(condition=None, **kwargs):\n    \"\"\"\n    Return the opposite of input condition.\n\n    :param condition: condition to process.\n\n    :result: not condition.\n    :rtype: bool\n    \"\"\"\n\n    result = True\n\n    if condition is not None:\n        result = not run(condition, **kwargs)\n\n    return result", "title": ""}
{"_id": "d11246", "text": "def _config_win32_domain(self, domain):\n        \"\"\"Configure a Domain registry entry.\"\"\"\n        # we call str() on domain to convert it from unicode to ascii\n        self.domain = dns.name.from_text(str(domain))", "title": ""}
{"_id": "d11247", "text": "def is_power_of_2(num):\n    \"\"\"Return whether `num` is a power of two\"\"\"\n    log = math.log2(num)\n    return int(log) == float(log)", "title": ""}
{"_id": "d11248", "text": "def OnDoubleClick(self, event):\n        \"\"\"Double click on a given square in the map\"\"\"\n        node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())\n        if node:\n            wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) )", "title": ""}
{"_id": "d11249", "text": "def contains_empty(features):\n    \"\"\"Check features data are not empty\n\n    :param features: The features data to check.\n    :type features: list of numpy arrays.\n\n    :return: True if one of the array is empty, False else.\n\n    \"\"\"\n    if not features:\n        return True\n    for feature in features:\n        if feature.shape[0] == 0:\n            return True\n    return False", "title": ""}
{"_id": "d11250", "text": "def apply_color_map(name: str, mat: np.ndarray = None):\n    \"\"\"returns an RGB matrix scaled by a matplotlib color map\"\"\"\n    def apply_map(mat):\n        return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)\n        \n    return apply_map if mat is None else apply_map(mat)", "title": ""}
{"_id": "d11251", "text": "def asMaskedArray(self):\n        \"\"\" Creates converts to a masked array\n        \"\"\"\n        return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)", "title": ""}
{"_id": "d11252", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d11253", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d11254", "text": "def read_image(filepath):\n  \"\"\"Returns an image tensor.\"\"\"\n  im_bytes = tf.io.read_file(filepath)\n  im = tf.image.decode_image(im_bytes, channels=CHANNELS)\n  im = tf.image.convert_image_dtype(im, tf.float32)\n  return im", "title": ""}
{"_id": "d11255", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d11256", "text": "def is_valid(number):\n    \"\"\"determines whether the card number is valid.\"\"\"\n    n = str(number)\n    if not n.isdigit():\n        return False\n    return int(n[-1]) == get_check_digit(n[:-1])", "title": ""}
{"_id": "d11257", "text": "def palettebar(height, length, colormap):\n    \"\"\"Return the channels of a palettebar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.palettize(cbar)", "title": ""}
{"_id": "d11258", "text": "def is_file(path):\n    \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n    try:\n        return path.expanduser().absolute().is_file()\n    except AttributeError:\n        return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))", "title": ""}
{"_id": "d11259", "text": "def raise_figure_window(f=0):\n    \"\"\"\n    Raises the supplied figure number or figure window.\n    \"\"\"\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()", "title": ""}
{"_id": "d11260", "text": "def raise_figure_window(f=0):\n    \"\"\"\n    Raises the supplied figure number or figure window.\n    \"\"\"\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()", "title": ""}
{"_id": "d11261", "text": "def series_index(self, series):\n        \"\"\"\n        Return the integer index of *series* in this sequence.\n        \"\"\"\n        for idx, s in enumerate(self):\n            if series is s:\n                return idx\n        raise ValueError('series not in chart data object')", "title": ""}
{"_id": "d11262", "text": "def are_in_interval(s, l, r, border = 'included'):\n        \"\"\"\n        Checks whether all number in the sequence s lie inside the interval formed by\n        l and r.\n        \"\"\"\n        return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s])", "title": ""}
{"_id": "d11263", "text": "def magnitude(X):\n    \"\"\"Magnitude of a complex matrix.\"\"\"\n    r = np.real(X)\n    i = np.imag(X)\n    return np.sqrt(r * r + i * i);", "title": ""}
{"_id": "d11264", "text": "def _stream_docker_logs(self):\n        \"\"\"Stream stdout and stderr from the task container to this\n        process's stdout and stderr, respectively.\n        \"\"\"\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()", "title": ""}
{"_id": "d11265", "text": "def calculate_size(name, max_size):\n    \"\"\" Calculates the request payload size\"\"\"\n    data_size = 0\n    data_size += calculate_size_str(name)\n    data_size += INT_SIZE_IN_BYTES\n    return data_size", "title": ""}
{"_id": "d11266", "text": "def _file_exists(path, filename):\n  \"\"\"Checks if the filename exists under the path.\"\"\"\n  return os.path.isfile(os.path.join(path, filename))", "title": ""}
{"_id": "d11267", "text": "def _multiline_width(multiline_s, line_width_fn=len):\n    \"\"\"Visible width of a potentially multiline content.\"\"\"\n    return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "title": ""}
{"_id": "d11268", "text": "def shape(self):\n        \"\"\"Compute the shape of the dataset as (rows, cols).\"\"\"\n        if not self.data:\n            return (0, 0)\n        return (len(self.data), len(self.dimensions))", "title": ""}
{"_id": "d11269", "text": "def clear_all(self):\n        \"\"\" clear all files that were to be injected \"\"\"\n        self.injections.clear_all()\n        for config_file in CONFIG_FILES:\n            self.injections.clear(os.path.join(\"~\", config_file))", "title": ""}
{"_id": "d11270", "text": "def merge_pdfs(pdf_filepaths, out_filepath):\n    \"\"\" Merge all the PDF files in `pdf_filepaths` in a new PDF file `out_filepath`.\n\n    Parameters\n    ----------\n    pdf_filepaths: list of str\n        Paths to PDF files.\n\n    out_filepath: str\n        Path to the result PDF file.\n\n    Returns\n    -------\n    path: str\n        The output file path.\n    \"\"\"\n    merger = PdfFileMerger()\n    for pdf in pdf_filepaths:\n        merger.append(PdfFileReader(open(pdf, 'rb')))\n\n    merger.write(out_filepath)\n\n    return out_filepath", "title": ""}
{"_id": "d11271", "text": "def clear_worker_output(self):\n        \"\"\"Drops all of the worker output collections\n            Args:\n                None\n            Returns:\n                Nothing\n        \"\"\"\n        self.data_store.clear_worker_output()\n\n        # Have the plugin manager reload all the plugins\n        self.plugin_manager.load_all_plugins()\n\n        # Store information about commands and workbench\n        self._store_information()", "title": ""}
{"_id": "d11272", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d11273", "text": "def clear(self):\n        \"\"\" clear plot \"\"\"\n        self.axes.cla()\n        self.conf.ntrace = 0\n        self.conf.xlabel = ''\n        self.conf.ylabel = ''\n        self.conf.title  = ''", "title": ""}
{"_id": "d11274", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d11275", "text": "def wait_until_exit(self):\n        \"\"\" Wait until all the threads are finished.\n\n        \"\"\"\n        [t.join() for t in self.threads]\n\n        self.threads = list()", "title": ""}
{"_id": "d11276", "text": "def cleanup_nodes(doc):\n    \"\"\"\n    Remove text nodes containing only whitespace\n    \"\"\"\n    for node in doc.documentElement.childNodes:\n        if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():\n            doc.documentElement.removeChild(node)\n    return doc", "title": ""}
{"_id": "d11277", "text": "def close_all_but_this(self):\n        \"\"\"Close all files but the current one\"\"\"\n        self.close_all_right()\n        for i in range(0, self.get_stack_count()-1  ):\n            self.close_file(0)", "title": ""}
{"_id": "d11278", "text": "def fn_min(self, a, axis=None):\n        \"\"\"\n        Return the minimum of an array, ignoring any NaNs.\n\n        :param a: The array.\n        :return: The minimum value of the array.\n        \"\"\"\n\n        return numpy.nanmin(self._to_ndarray(a), axis=axis)", "title": ""}
{"_id": "d11279", "text": "def count_words(file):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  c = Counter()\n  with open(file, 'r') as f:\n    for l in f:\n      words = l.strip().split()\n      c.update(words)\n  return c", "title": ""}
{"_id": "d11280", "text": "def lognorm(x, mu, sigma=1.0):\n    \"\"\" Log-normal function from scipy \"\"\"\n    return stats.lognorm(sigma, scale=mu).pdf(x)", "title": ""}
{"_id": "d11281", "text": "def adjacency(tree):\n    \"\"\"\n    Construct the adjacency matrix of the tree\n    :param tree:\n    :return:\n    \"\"\"\n    dd = ids(tree)\n    N = len(dd)\n    A = np.zeros((N, N))\n\n    def _adj(node):\n        if np.isscalar(node):\n            return\n        elif isinstance(node, tuple) and len(node) == 2:\n            A[dd[node], dd[node[0]]] = 1\n            A[dd[node[0]], dd[node]] = 1\n            _adj(node[0])\n\n            A[dd[node], dd[node[1]]] = 1\n            A[dd[node[1]], dd[node]] = 1\n            _adj(node[1])\n\n    _adj(tree)\n    return A", "title": ""}
{"_id": "d11282", "text": "def tinsel(to_patch, module_name, decorator=mock_decorator):\n    \"\"\"\n    Decorator for simple in-place decorator mocking for tests\n\n    Args:\n        to_patch: the string path of the function to patch\n        module_name: complete string path of the module to reload\n        decorator (optional): replacement decorator. By default a pass-through\n            will be used.\n\n    Returns:\n        A wrapped test function, during the context of execution the specified\n        path is patched.\n\n    \"\"\"\n    def fn_decorator(function):\n        def wrapper(*args, **kwargs):\n            with patch(to_patch, decorator):\n                m = importlib.import_module(module_name)\n                reload(m)\n                function(*args, **kwargs)\n\n            reload(m)\n        return wrapper\n    return fn_decorator", "title": ""}
{"_id": "d11283", "text": "def stringc(text, color):\n    \"\"\"\n    Return a string with terminal colors.\n    \"\"\"\n    if has_colors:\n        text = str(text)\n\n        return \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"\n    else:\n        return text", "title": ""}
{"_id": "d11284", "text": "def __setitem__(self, _ignored, return_value):\n        \"\"\"Item assignment sets the return value and removes any side effect\"\"\"\n        self.mock.return_value = return_value\n        self.mock.side_effect = None", "title": ""}
{"_id": "d11285", "text": "def step_table_made(self):\n        \"\"\"check if the step table exists\"\"\"\n        try:\n            empty = self.step_table.empty\n        except AttributeError:\n            empty = True\n        return not empty", "title": ""}
{"_id": "d11286", "text": "def on_modified(self, event):\n        \"\"\"Function called everytime a new file is modified.\n\n        Args:\n            event: Event to process.\n        \"\"\"\n        self._logger.debug('Detected modify event on watched path: %s', event.src_path)\n\n        self._process_event(event)", "title": ""}
{"_id": "d11287", "text": "def software_fibonacci(n):\n    \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n    a, b = 0, 1\n    for i in range(n):\n        a, b = b, a + b\n    return a", "title": ""}
{"_id": "d11288", "text": "def _modify(item, func):\n    \"\"\"\n    Modifies each item.keys() string based on the func passed in.\n    Often used with inflection's camelize or underscore methods.\n\n    :param item: dictionary representing item to be modified\n    :param func: function to run on each key string\n    :return: dictionary where each key has been modified by func.\n    \"\"\"\n    result = dict()\n    for key in item:\n        result[func(key)] = item[key]\n    return result", "title": ""}
{"_id": "d11289", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d11290", "text": "def find_one_by_id(self, _id):\n        \"\"\"\n        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\n\n        \"\"\"\n        document = (yield self.collection.find_one({\"_id\": ObjectId(_id)}))\n        raise Return(self._obj_cursor_to_dictionary(document))", "title": ""}
{"_id": "d11291", "text": "def _records_commit(record_ids):\n    \"\"\"Commit all records.\"\"\"\n    for record_id in record_ids:\n        record = Record.get_record(record_id)\n        record.commit()", "title": ""}
{"_id": "d11292", "text": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "title": ""}
{"_id": "d11293", "text": "def is_int(string):\n    \"\"\"\n    Checks if a string is an integer. If the string value is an integer\n    return True, otherwise return False. \n    \n    Args:\n        string: a string to test.\n\n    Returns: \n        boolean\n    \"\"\"\n    try:\n        a = float(string)\n        b = int(a)\n    except ValueError:\n        return False\n    else:\n        return a == b", "title": ""}
{"_id": "d11294", "text": "def ensure_index(self, key, unique=False):\n        \"\"\"Wrapper for pymongo.Collection.ensure_index\n        \"\"\"\n        return self.collection.ensure_index(key, unique=unique)", "title": ""}
{"_id": "d11295", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d11296", "text": "def _obj_cursor_to_dictionary(self, cursor):\n        \"\"\"Handle conversion of pymongo cursor into a JSON object formatted for UI consumption\n\n        :param dict cursor: a mongo document that should be converted to primitive types for the client code\n        :returns: a primitive dictionary\n        :rtype: dict\n        \"\"\"\n        if not cursor:\n            return cursor\n\n        cursor = json.loads(json.dumps(cursor, cls=BSONEncoder))\n\n        if cursor.get(\"_id\"):\n            cursor[\"id\"] = cursor.get(\"_id\")\n            del cursor[\"_id\"]\n\n        return cursor", "title": ""}
{"_id": "d11297", "text": "def median(data):\n    \"\"\"Calculate the median of a list.\"\"\"\n    data.sort()\n    num_values = len(data)\n    half = num_values // 2\n    if num_values % 2:\n        return data[half]\n    return 0.5 * (data[half-1] + data[half])", "title": ""}
{"_id": "d11298", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d11299", "text": "def __connect():\n    \"\"\"\n    Connect to a redis instance.\n    \"\"\"\n    global redis_instance\n    if use_tcp_socket:\n        redis_instance = redis.StrictRedis(host=hostname, port=port)\n    else:\n        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "title": ""}
{"_id": "d11300", "text": "def select_up(self):\n        \"\"\"move cursor up\"\"\"\n        r, c = self._index\n        self._select_index(r-1, c)", "title": ""}
{"_id": "d11301", "text": "def init_mq(self):\n        \"\"\"Init connection and consumer with openstack mq.\"\"\"\n        mq = self.init_connection()\n        self.init_consumer(mq)\n        return mq.connection", "title": ""}
{"_id": "d11302", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d11303", "text": "def replace_sys_args(new_args):\n    \"\"\"Temporarily replace sys.argv with current arguments\n\n    Restores sys.argv upon exit of the context manager.\n    \"\"\"\n    # Replace sys.argv arguments\n    # for module import\n    old_args = sys.argv\n    sys.argv = new_args\n    try:\n        yield\n    finally:\n        sys.argv = old_args", "title": ""}
{"_id": "d11304", "text": "def _cast_to_type(self, value):\n        \"\"\" Convert the value to its string representation\"\"\"\n        if isinstance(value, str) or value is None:\n            return value\n        return str(value)", "title": ""}
{"_id": "d11305", "text": "def format_line(data, linestyle):\n    \"\"\"Formats a list of elements using the given line style\"\"\"\n    return linestyle.begin + linestyle.sep.join(data) + linestyle.end", "title": ""}
{"_id": "d11306", "text": "def display_len(text):\n    \"\"\"\n    Get the display length of a string. This can differ from the character\n    length if the string contains wide characters.\n    \"\"\"\n    text = unicodedata.normalize('NFD', text)\n    return sum(char_width(char) for char in text)", "title": ""}
{"_id": "d11307", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d11308", "text": "def multiply(self, number):\n        \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n        return self.from_list([x * number for x in self.to_list()])", "title": ""}
{"_id": "d11309", "text": "def get_wordnet_syns(word):\n    \"\"\"\n    Utilize wordnet (installed with nltk) to get synonyms for words\n    word is the input word\n    returns a list of unique synonyms\n    \"\"\"\n    synonyms = []\n    regex = r\"_\"\n    pat = re.compile(regex)\n    synset = nltk.wordnet.wordnet.synsets(word)\n    for ss in synset:\n        for swords in ss.lemma_names:\n            synonyms.append(pat.sub(\" \", swords.lower()))\n    synonyms = f7(synonyms)\n    return synonyms", "title": ""}
{"_id": "d11310", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d11311", "text": "def stop(self, timeout=None):\n        \"\"\" Initiates a graceful stop of the processes \"\"\"\n\n        self.stopping = True\n\n        for process in list(self.processes):\n            self.stop_process(process, timeout=timeout)", "title": ""}
{"_id": "d11312", "text": "def _intermediary_to_dot(tables, relationships):\n    \"\"\" Returns the dot source representing the database in a string. \"\"\"\n    t = '\\n'.join(t.to_dot() for t in tables)\n    r = '\\n'.join(r.to_dot() for r in relationships)\n    return '{}\\n{}\\n{}\\n}}'.format(GRAPH_BEGINNING, t, r)", "title": ""}
{"_id": "d11313", "text": "def build_output(self, fout):\n        \"\"\"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.\n        \"\"\"\n        fout.write('\\n'.join([s for s in self.out]))", "title": ""}
{"_id": "d11314", "text": "def getCursor(self):\n\t\t\"\"\"\n\t\tGet a Dictionary Cursor for executing queries\n\t\t\"\"\"\n\t\tif self.connection is None:\n\t\t\tself.Connect()\n\t\t\t\n\t\treturn self.connection.cursor(MySQLdb.cursors.DictCursor)", "title": ""}
{"_id": "d11315", "text": "def _clip(sid, prefix):\n    \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n    return sid[len(prefix):] if sid.startswith(prefix) else sid", "title": ""}
{"_id": "d11316", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d11317", "text": "def unpickle_file(picklefile, **kwargs):\n    \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)", "title": ""}
{"_id": "d11318", "text": "def has_edge(self, p_from, p_to):\n        \"\"\" Returns True when the graph has the given edge. \"\"\"\n        return p_from in self._edges and p_to in self._edges[p_from]", "title": ""}
{"_id": "d11319", "text": "def gaussian_distribution(mean, stdev, num_pts=50):\n    \"\"\" get an x and y numpy.ndarray that spans the +/- 4\n    standard deviation range of a gaussian distribution with\n    a given mean and standard deviation. useful for plotting\n\n    Parameters\n    ----------\n    mean : float\n        the mean of the distribution\n    stdev : float\n        the standard deviation of the distribution\n    num_pts : int\n        the number of points in the returned ndarrays.\n        Default is 50\n\n    Returns\n    -------\n    x : numpy.ndarray\n        the x-values of the distribution\n    y : numpy.ndarray\n        the y-values of the distribution\n\n    \"\"\"\n    xstart = mean - (4.0 * stdev)\n    xend = mean + (4.0 * stdev)\n    x = np.linspace(xstart,xend,num_pts)\n    y = (1.0/np.sqrt(2.0*np.pi*stdev*stdev)) * np.exp(-1.0 * ((x - mean)**2)/(2.0*stdev*stdev))\n    return x,y", "title": ""}
{"_id": "d11320", "text": "def remove_node(self, node):\n        \"\"\" Remove a node from this network. \"\"\"\n        if _debug: Network._debug(\"remove_node %r\", node)\n\n        self.nodes.remove(node)\n        node.lan = None", "title": ""}
{"_id": "d11321", "text": "def test3():\n    \"\"\"Test the multiprocess\n    \"\"\"\n    import time\n    \n    p = MVisionProcess()\n    p.start()\n    time.sleep(5)\n    p.stop()", "title": ""}
{"_id": "d11322", "text": "def new(self, size, fill):\n        \"\"\"Return a new Image instance filled with a color.\"\"\"\n        return Image(PIL.Image.new(\"RGB\", size, fill))", "title": ""}
{"_id": "d11323", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d11324", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d11325", "text": "def _remove_duplicate_files(xs):\n    \"\"\"Remove files specified multiple times in a list.\n    \"\"\"\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", "title": ""}
{"_id": "d11326", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d11327", "text": "def remove_last_entry(self):\n        \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n        self.current_beat -= 1.0 / self.bar[-1][1]\n        self.bar = self.bar[:-1]\n        return self.current_beat", "title": ""}
{"_id": "d11328", "text": "def run(self):\n        \"\"\"\n        Runs the unit test framework. Can be overridden to run anything.\n        Returns True on passing and False on failure.\n        \"\"\"\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", "title": ""}
{"_id": "d11329", "text": "def _sanitize(text):\n    \"\"\"Return sanitized Eidos text field for human readability.\"\"\"\n    d = {'-LRB-': '(', '-RRB-': ')'}\n    return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text)", "title": ""}
{"_id": "d11330", "text": "def test(nose_argsuments):\n    \"\"\" Run application tests \"\"\"\n    from nose import run\n\n    params = ['__main__', '-c', 'nose.ini']\n    params.extend(nose_argsuments)\n    run(argv=params)", "title": ""}
{"_id": "d11331", "text": "def _not(condition=None, **kwargs):\n    \"\"\"\n    Return the opposite of input condition.\n\n    :param condition: condition to process.\n\n    :result: not condition.\n    :rtype: bool\n    \"\"\"\n\n    result = True\n\n    if condition is not None:\n        result = not run(condition, **kwargs)\n\n    return result", "title": ""}
{"_id": "d11332", "text": "def clear(self):\n        \"\"\"Clear the displayed image.\"\"\"\n        self._imgobj = None\n        try:\n            # See if there is an image on the canvas\n            self.canvas.delete_object_by_tag(self._canvas_img_tag)\n            self.redraw()\n        except KeyError:\n            pass", "title": ""}
{"_id": "d11333", "text": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "title": ""}
{"_id": "d11334", "text": "def restore_scrollbar_position(self):\n        \"\"\"Restoring scrollbar position after main window is visible\"\"\"\n        scrollbar_pos = self.get_option('scrollbar_position', None)\n        if scrollbar_pos is not None:\n            self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)", "title": ""}
{"_id": "d11335", "text": "def _getTypename(self, defn):\n        \"\"\" Returns the SQL typename required to store the given FieldDefinition \"\"\"\n        return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'", "title": ""}
{"_id": "d11336", "text": "def wheel(delta=1):\n    \"\"\" Sends a wheel event for the provided number of clicks. May be negative to reverse\n    direction. \"\"\"\n    location = get_position()\n    e = Quartz.CGEventCreateMouseEvent(\n        None,\n        Quartz.kCGEventScrollWheel,\n        location,\n        Quartz.kCGMouseButtonLeft)\n    e2 = Quartz.CGEventCreateScrollWheelEvent(\n        None,\n        Quartz.kCGScrollEventUnitLine,\n        1,\n        delta)\n    Quartz.CGEventPost(Quartz.kCGHIDEventTap, e)\n    Quartz.CGEventPost(Quartz.kCGHIDEventTap, e2)", "title": ""}
{"_id": "d11337", "text": "def header_length(bytearray):\n    \"\"\"Return the length of s when it is encoded with base64.\"\"\"\n    groups_of_3, leftover = divmod(len(bytearray), 3)\n    # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.\n    n = groups_of_3 * 4\n    if leftover:\n        n += 4\n    return n", "title": ""}
{"_id": "d11338", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d11339", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d11340", "text": "def get_line_flux(line_wave, wave, flux, **kwargs):\n    \"\"\"Interpolated flux at a given wavelength (calls np.interp).\"\"\"\n    return np.interp(line_wave, wave, flux, **kwargs)", "title": ""}
{"_id": "d11341", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d11342", "text": "def count_rows_with_nans(X):\n    \"\"\"Count the number of rows in 2D arrays that contain any nan values.\"\"\"\n    if X.ndim == 2:\n        return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()", "title": ""}
{"_id": "d11343", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d11344", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d11345", "text": "def length(self):\n        \"\"\"Array of vector lengths\"\"\"\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "title": ""}
{"_id": "d11346", "text": "def contains_all(self, array):\n        \"\"\"Test if `array` is an array of real numbers.\"\"\"\n        dtype = getattr(array, 'dtype', None)\n        if dtype is None:\n            dtype = np.result_type(*array)\n        return is_real_dtype(dtype)", "title": ""}
{"_id": "d11347", "text": "def main(argv, version=DEFAULT_VERSION):\n    \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n    tarball = download_setuptools()\n    _install(tarball, _build_install_args(argv))", "title": ""}
{"_id": "d11348", "text": "def setdict(self, D):\n        \"\"\"Set dictionary array.\"\"\"\n\n        self.D = np.asarray(D, dtype=self.dtype)", "title": ""}
{"_id": "d11349", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d11350", "text": "def zoomed_scaled_array_around_mask(self, mask, buffer=1):\n        \"\"\"Extract the 2D region of an array corresponding to the rectangle encompassing all unmasked values.\n\n        This is used to extract and visualize only the region of an image that is used in an analysis.\n\n        Parameters\n        ----------\n        mask : mask.Mask\n            The mask around which the scaled array is extracted.\n        buffer : int\n            The buffer of pixels around the extraction.\n        \"\"\"\n        return self.new_with_array(array=array_util.extracted_array_2d_from_array_2d_and_coordinates(\n            array_2d=self,  y0=mask.zoom_region[0]-buffer, y1=mask.zoom_region[1]+buffer,\n            x0=mask.zoom_region[2]-buffer, x1=mask.zoom_region[3]+buffer))", "title": ""}
{"_id": "d11351", "text": "def _download(url):\n    \"\"\"Downloads an URL and returns a file-like object open for reading,\n    compatible with zipping.ZipFile (it has a seek() method).\n    \"\"\"\n    fh = StringIO()\n\n    for line in get(url):\n        fh.write(line)\n\n    fh.seek(0)\n    return fh", "title": ""}
{"_id": "d11352", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d11353", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d11354", "text": "def _numpy_char_to_bytes(arr):\n    \"\"\"Like netCDF4.chartostring, but faster and more flexible.\n    \"\"\"\n    # based on: http://stackoverflow.com/a/10984878/809705\n    arr = np.array(arr, copy=False, order='C')\n    dtype = 'S' + str(arr.shape[-1])\n    return arr.view(dtype).reshape(arr.shape[:-1])", "title": ""}
{"_id": "d11355", "text": "def safe_dump(data, stream=None, **kwds):\n    \"\"\"implementation of safe dumper using Ordered Dict Yaml Dumper\"\"\"\n    return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)", "title": ""}
{"_id": "d11356", "text": "def findMax(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMax(arr, out)\n    return out", "title": ""}
{"_id": "d11357", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d11358", "text": "def new_random_state(seed=None, fully_random=False):\n    \"\"\"\n    Returns a new random state.\n\n    Parameters\n    ----------\n    seed : None or int, optional\n        Optional seed value to use.\n        The same datatypes are allowed as for ``numpy.random.RandomState(seed)``.\n\n    fully_random : bool, optional\n        Whether to use numpy's random initialization for the\n        RandomState (used if set to True). If False, a seed is sampled from\n        the global random state, which is a bit faster and hence the default.\n\n    Returns\n    -------\n    numpy.random.RandomState\n        The new random state.\n\n    \"\"\"\n    if seed is None:\n        if not fully_random:\n            # sample manually a seed instead of just RandomState(),\n            # because the latter one\n            # is way slower.\n            seed = CURRENT_RANDOM_STATE.randint(SEED_MIN_VALUE, SEED_MAX_VALUE, 1)[0]\n    return np.random.RandomState(seed)", "title": ""}
{"_id": "d11359", "text": "def to_unicode_repr( _letter ):\n    \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n        in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n    # Python 2-3 compatible\n    return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"", "title": ""}
{"_id": "d11360", "text": "def maskIndex(self):\n        \"\"\" 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.\n        \"\"\"\n        if isinstance(self.mask, bool):\n            return np.full(self.data.shape, self.mask, dtype=np.bool)\n        else:\n            return self.mask", "title": ""}
{"_id": "d11361", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d11362", "text": "def cat_acc(y_true, y_pred):\n    \"\"\"Categorical accuracy\n    \"\"\"\n    return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))", "title": ""}
{"_id": "d11363", "text": "def asMaskedArray(self):\n        \"\"\" Creates converts to a masked array\n        \"\"\"\n        return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)", "title": ""}
{"_id": "d11364", "text": "def _strip_empty_keys(self, params):\n        \"\"\"Added because the Dropbox OAuth2 flow doesn't\n        work when scope is passed in, which is empty.\n        \"\"\"\n        keys = [k for k, v in params.items() if v == '']\n        for key in keys:\n            del params[key]", "title": ""}
{"_id": "d11365", "text": "def click_by_selector(self, selector):\n    \"\"\"Click the element matching the CSS selector.\"\"\"\n    # No need for separate button press step with selector style.\n    elem = find_element_by_jquery(world.browser, selector)\n    elem.click()", "title": ""}
{"_id": "d11366", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d11367", "text": "def managepy(cmd, extra=None):\n    \"\"\"Run manage.py using this component's specific Django settings\"\"\"\n\n    extra = extra.split() if extra else []\n    run_django_cli(['invoke', cmd] + extra)", "title": ""}
{"_id": "d11368", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d11369", "text": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "title": ""}
{"_id": "d11370", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d11371", "text": "def get_table_columns(dbconn, tablename):\n    \"\"\"\n    Return a list of tuples specifying the column name and type\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n    info = cur.fetchall()\n    cols = [(i[1], i[2]) for i in info]\n    return cols", "title": ""}
{"_id": "d11372", "text": "def Sum(a, axis, keep_dims):\n    \"\"\"\n    Sum reduction op.\n    \"\"\"\n    return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                  keepdims=keep_dims),", "title": ""}
{"_id": "d11373", "text": "def get_previous_month(self):\n        \"\"\"Returns date range for the previous full month.\"\"\"\n        end = utils.get_month_start() - relativedelta(days=1)\n        end = utils.to_datetime(end)\n        start = utils.get_month_start(end)\n        return start, end", "title": ""}
{"_id": "d11374", "text": "def set_attrs(self):\n        \"\"\" set our object attributes \"\"\"\n        self.attrs.encoding = self.encoding\n        self.attrs.errors = self.errors", "title": ""}
{"_id": "d11375", "text": "def values(self):\n        \"\"\"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\n        \"\"\"\n        lower = float(self.lowerSpnbx.value())\n        upper = float(self.upperSpnbx.value())\n        return (lower, upper)", "title": ""}
{"_id": "d11376", "text": "def is_serializable(obj):\n    \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool\n    \"\"\"\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')", "title": ""}
{"_id": "d11377", "text": "def is_writable_by_others(filename):\n    \"\"\"Check if file or directory is world writable.\"\"\"\n    mode = os.stat(filename)[stat.ST_MODE]\n    return mode & stat.S_IWOTH", "title": ""}
{"_id": "d11378", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d11379", "text": "def update(self, **kwargs):\n        \"\"\"Customize the lazy field\"\"\"\n        assert not self.called\n        self.kw.update(kwargs)\n        return self", "title": ""}
{"_id": "d11380", "text": "def stylize(text, styles, reset=True):\n    \"\"\"conveniently styles your text as and resets ANSI codes at its end.\"\"\"\n    terminator = attr(\"reset\") if reset else \"\"\n    return \"{}{}{}\".format(\"\".join(styles), text, terminator)", "title": ""}
{"_id": "d11381", "text": "def save_excel(self, fd):\n        \"\"\" Saves the case as an Excel spreadsheet.\n        \"\"\"\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)", "title": ""}
{"_id": "d11382", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d11383", "text": "def read_string(buff, byteorder='big'):\n    \"\"\"Read a string from a file-like object.\"\"\"\n    length = read_numeric(USHORT, buff, byteorder)\n    return buff.read(length).decode('utf-8')", "title": ""}
{"_id": "d11384", "text": "def GeneratePassphrase(length=20):\n  \"\"\"Create a 20 char passphrase with easily typeable chars.\"\"\"\n  valid_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  valid_chars += \"0123456789 ,-_&$#\"\n  return \"\".join(random.choice(valid_chars) for i in range(length))", "title": ""}
{"_id": "d11385", "text": "def file_read(filename):\n    \"\"\"Read a file and close it.  Returns the file source.\"\"\"\n    fobj = open(filename,'r');\n    source = fobj.read();\n    fobj.close()\n    return source", "title": ""}
{"_id": "d11386", "text": "def _get_random_id():\n    \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n    symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(symbols) for _ in range(15))", "title": ""}
{"_id": "d11387", "text": "def _readuntil(f, end=_TYPE_END):\n\t\"\"\"Helper function to read bytes until a certain end byte is hit\"\"\"\n\tbuf = bytearray()\n\tbyte = f.read(1)\n\twhile byte != end:\n\t\tif byte == b'':\n\t\t\traise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))\n\t\tbuf += byte\n\t\tbyte = f.read(1)\n\treturn buf", "title": ""}
{"_id": "d11388", "text": "def _covariance_matrix(self, type='noise'):\n        \"\"\"\n        Constructs the covariance matrix from PCA\n        residuals\n        \"\"\"\n        if type == 'sampling':\n            return self.sigma**2/(self.n-1)\n        elif type == 'noise':\n            return 4*self.sigma*N.var(self.rotated(), axis=0)", "title": ""}
{"_id": "d11389", "text": "def open_with_encoding(filename, encoding, mode='r'):\n    \"\"\"Return opened file with a specific encoding.\"\"\"\n    return io.open(filename, mode=mode, encoding=encoding,\n                   newline='')", "title": ""}
{"_id": "d11390", "text": "def wordfreq(text, is_filename=False):\n    \"\"\"Return a dictionary of words and word counts in a string.\"\"\"\n    if is_filename:\n        with open(text) as f:\n            text = f.read()\n    freqs = {}\n    for word in text.split():\n        lword = word.lower()\n        freqs[lword] = freqs.get(lword, 0) + 1\n    return freqs", "title": ""}
{"_id": "d11391", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d11392", "text": "def get_all_names(self):\n        \"\"\"Return the list of all cached global names\"\"\"\n        result = set()\n        for module in self.names:\n            result.update(set(self.names[module]))\n        return result", "title": ""}
{"_id": "d11393", "text": "def gray2bgr(img):\n    \"\"\"Convert a grayscale image to BGR image.\n\n    Args:\n        img (ndarray or str): The input image.\n\n    Returns:\n        ndarray: The converted BGR image.\n    \"\"\"\n    img = img[..., None] if img.ndim == 2 else img\n    out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n    return out_img", "title": ""}
{"_id": "d11394", "text": "def _get_all_constants():\n    \"\"\"\n    Get list of all uppercase, non-private globals (doesn't start with ``_``).\n\n    Returns:\n        list: Uppercase names defined in `globals()` (variables from this \\\n              module).\n    \"\"\"\n    return [\n        key for key in globals().keys()\n        if all([\n            not key.startswith(\"_\"),          # publicly accesible\n            key.upper() == key,               # uppercase\n            type(globals()[key]) in _ALLOWED  # and with type from _ALLOWED\n        ])\n    ]", "title": ""}
{"_id": "d11395", "text": "def _get_background_color(self):\n        \"\"\"Returns background color rgb tuple of right line\"\"\"\n\n        color = self.cell_attributes[self.key][\"bgcolor\"]\n        return tuple(c / 255.0 for c in color_pack2rgb(color))", "title": ""}
{"_id": "d11396", "text": "def camelcase2list(s, lower=False):\n    \"\"\"Converts a camelcase string to a list.\"\"\"\n    s = re.findall(r'([A-Z][a-z0-9]+)', s)\n    return [w.lower() for w in s] if lower else s", "title": ""}
{"_id": "d11397", "text": "def _genTex2D(self):\n        \"\"\"Generate an empty texture in OpenGL\"\"\"\n        for face in range(6):\n            gl.glTexImage2D(self.target0 + face, 0, self.internal_fmt, self.width, self.height, 0,\n                            self.pixel_fmt, gl.GL_UNSIGNED_BYTE, 0)", "title": ""}
{"_id": "d11398", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d11399", "text": "def dictfetchall(cursor):\n    \"\"\"Returns all rows from a cursor as a dict (rather than a headerless table)\n\n    From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/\n    \"\"\"\n    desc = cursor.description\n    return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]", "title": ""}
{"_id": "d11400", "text": "def min_or_none(val1, val2):\n    \"\"\"Returns min(val1, val2) returning None only if both values are None\"\"\"\n    return min(val1, val2, key=lambda x: sys.maxint if x is None else x)", "title": ""}
{"_id": "d11401", "text": "def _index_ordering(redshift_list):\n        \"\"\"\n\n        :param redshift_list: list of redshifts\n        :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n        \"\"\"\n        redshift_list = np.array(redshift_list)\n        sort_index = np.argsort(redshift_list)\n        return sort_index", "title": ""}
{"_id": "d11402", "text": "def get_previous(self):\n        \"\"\"Get the billing cycle prior to this one. May return None\"\"\"\n        return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()", "title": ""}
{"_id": "d11403", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d11404", "text": "def get_active_window(self):\n        \"\"\"\n        The current active :class:`.Window`.\n        \"\"\"\n        app = get_app()\n\n        try:\n            return self._active_window_for_cli[app]\n        except KeyError:\n            self._active_window_for_cli[app] = self._last_active_window or self.windows[0]\n            return self.windows[0]", "title": ""}
{"_id": "d11405", "text": "def write_config(self, outfile):\n        \"\"\"Write the configuration dictionary to an output file.\"\"\"\n        utils.write_yaml(self.config, outfile, default_flow_style=False)", "title": ""}
{"_id": "d11406", "text": "def list_files(directory):\n    \"\"\"Returns all files in a given directory\n    \"\"\"\n    return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]", "title": ""}
{"_id": "d11407", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d11408", "text": "def trivial_partition(set_):\n    \"\"\"Returns a parition of given set into 1-element subsets.\n\n    :return: Trivial partition of given set, i.e. iterable containing disjoint\n             1-element sets, each consisting of a single element\n             from given set\n    \"\"\"\n    ensure_countable(set_)\n\n    result = ((x,) for x in set_)\n    return _harmonize_subset_types(set_, result)", "title": ""}
{"_id": "d11409", "text": "def report_stdout(host, stdout):\n    \"\"\"Take a stdout 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 stdout: the std out of that process\n    :type stdout: paramiko.channel.Channel\n    \"\"\"\n    lines = stdout.readlines()\n    if lines:\n        print(\"STDOUT from {host}:\".format(host=host))\n        for line in lines:\n            print(line.rstrip(), file=sys.stdout)", "title": ""}
{"_id": "d11410", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d11411", "text": "def report_stdout(host, stdout):\n    \"\"\"Take a stdout 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 stdout: the std out of that process\n    :type stdout: paramiko.channel.Channel\n    \"\"\"\n    lines = stdout.readlines()\n    if lines:\n        print(\"STDOUT from {host}:\".format(host=host))\n        for line in lines:\n            print(line.rstrip(), file=sys.stdout)", "title": ""}
{"_id": "d11412", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d11413", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d11414", "text": "def horz_dpi(self):\n        \"\"\"\n        Integer dots per inch for the width of this image. Defaults to 72\n        when not present in the file, as is often the case.\n        \"\"\"\n        pHYs = self._chunks.pHYs\n        if pHYs is None:\n            return 72\n        return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)", "title": ""}
{"_id": "d11415", "text": "def _parse(self, date_str, format='%Y-%m-%d'):\n        \"\"\"\n        helper function for parsing FRED date string into datetime\n        \"\"\"\n        rv = pd.to_datetime(date_str, format=format)\n        if hasattr(rv, 'to_pydatetime'):\n            rv = rv.to_pydatetime()\n        return rv", "title": ""}
{"_id": "d11416", "text": "def inventory(self, source_id, fetch=False, fmt='table'):\n        \"\"\"\n        Prints a summary of all objects in the database. Input string or list of strings in **ID** or **unum**\n        for specific objects.\n\n        Parameters\n        ----------\n        source_id: int\n            The id from the SOURCES table whose data across all tables is to be printed.\n        fetch: bool\n            Return the results.\n        fmt: str\n            Returns the data as a dictionary, array, or astropy.table given 'dict', 'array', or 'table'\n\n        Returns\n        -------\n        data_tables: dict\n            Returns a dictionary of astropy tables with the table name as the keys.\n\n        \"\"\"\n        data_tables = {}\n\n        t = self.query(\"SELECT * FROM sqlite_master WHERE type='table'\", fmt='table')\n        all_tables = t['name'].tolist()\n        for table in ['sources'] + [t for t in all_tables if\n                                    t not in ['sources', 'sqlite_sequence']]:\n\n            try:\n\n                # Get the columns, pull out redundant ones, and query the table for this source's data\n                t = self.query(\"PRAGMA table_info({})\".format(table), fmt='table')\n                columns = np.array(t['name'])\n                types = np.array(t['type'])\n\n                if table == 'sources' or 'source_id' in columns:\n\n                    # If printing, only get simple data types and exclude redundant 'source_id' for nicer printing\n                    if not fetch:\n                        columns = columns[\n                            ((types == 'REAL') | (types == 'INTEGER') | (types == 'TEXT')) & (columns != 'source_id')]\n\n                    # Query the table\n                    try:\n                        id = 'id' if table.lower() == 'sources' else 'source_id'\n                        data = self.query(\n                            \"SELECT {} FROM {} WHERE {}={}\".format(','.join(columns), table, id, source_id),\n                            fmt='table')\n\n                        if not data and table.lower() == 'sources':\n                            print(\n                            'No source with id {}. Try db.search() to search the database for a source_id.'.format(\n                                source_id))\n\n                    except:\n                        data = None\n\n                    # If there's data for this table, save it\n                    if data:\n                        if fetch:\n                            data_tables[table] = self.query(\n                                \"SELECT {} FROM {} WHERE {}={}\".format(','.join(columns), table, id, source_id), \\\n                                fetch=True, fmt=fmt)\n                        else:\n                            data = data[[c.lower() for c in columns]]\n                            pprint(data, title=table.upper())\n\n                else:\n                    pass\n\n            except:\n                print('Could not retrieve data from {} table.'.format(table.upper()))\n\n        if fetch: return data_tables", "title": ""}
{"_id": "d11417", "text": "def convert_time_string(date_str):\n    \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n    dt, _, _ = date_str.partition(\".\")\n    dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n    return dt", "title": ""}
{"_id": "d11418", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d11419", "text": "def parse(self, data, lexer=None, *args, **kwargs):\n        \"\"\"Parse the input JSON data string into a python data structure.\n        Args:\n          data: An input data string\n          lexer:  An optional ply.lex instance that overrides the default lexer.\n        Returns:\n          A python dict or list representing the input JSON data.\n        \"\"\"\n        if lexer is None:\n            lexer = self.lexer\n        return self.parser.parse(data, lexer=lexer, *args, **kwargs)", "title": ""}
{"_id": "d11420", "text": "def searchlast(self,n=10):\n        \"\"\"Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.\"\"\"            \n        solutions = deque([], n)\n        for solution in self:\n            solutions.append(solution)\n        return solutions", "title": ""}
{"_id": "d11421", "text": "def coords_from_query(query):\n    \"\"\"Transform a query line into a (lng, lat) pair of coordinates.\"\"\"\n    try:\n        coords = json.loads(query)\n    except ValueError:\n        vals = re.split(r'[,\\s]+', query.strip())\n        coords = [float(v) for v in vals]\n    return tuple(coords[:2])", "title": ""}
{"_id": "d11422", "text": "def parse_s3_url(url):\n    \"\"\"\n    Parses S3 URL.\n\n    Returns bucket (domain) and file (full path).\n    \"\"\"\n    bucket = ''\n    path = ''\n    if url:\n        result = urlparse(url)\n        bucket = result.netloc\n        path = result.path.strip('/')\n    return bucket, path", "title": ""}
{"_id": "d11423", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d11424", "text": "def deserialize_date(string):\n    \"\"\"\n    Deserializes string to date.\n\n    :param string: str.\n    :type string: str\n    :return: date.\n    :rtype: date\n    \"\"\"\n    try:\n        from dateutil.parser import parse\n        return parse(string).date()\n    except ImportError:\n        return string", "title": ""}
{"_id": "d11425", "text": "def get_month_start_date(self):\n        \"\"\"Returns the first day of the current month\"\"\"\n        now = timezone.now()\n        return timezone.datetime(day=1, month=now.month, year=now.year, tzinfo=now.tzinfo)", "title": ""}
{"_id": "d11426", "text": "def _parse_boolean(value, default=False):\n    \"\"\"\n    Attempt to cast *value* into a bool, returning *default* if it fails.\n    \"\"\"\n    if value is None:\n        return default\n    try:\n        return bool(value)\n    except ValueError:\n        return default", "title": ""}
{"_id": "d11427", "text": "def gday_of_year(self):\n        \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n        return (self.date - dt.date(self.date.year, 1, 1)).days", "title": ""}
{"_id": "d11428", "text": "def parse_form(self, req, name, field):\n        \"\"\"Pull a form value from the request.\"\"\"\n        return get_value(req.body_arguments, name, field)", "title": ""}
{"_id": "d11429", "text": "def gday_of_year(self):\n        \"\"\"Return the number of days since January 1 of the given year.\"\"\"\n        return (self.date - dt.date(self.date.year, 1, 1)).days", "title": ""}
{"_id": "d11430", "text": "def _sourced_dict(self, source=None, **kwargs):\n        \"\"\"Like ``dict(**kwargs)``, but where the ``source`` key is special.\n        \"\"\"\n        if source:\n            kwargs['source'] = source\n        elif self.source:\n            kwargs['source'] = self.source\n        return kwargs", "title": ""}
{"_id": "d11431", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d11432", "text": "def do(self):\n        \"\"\"\n        Set a restore point (copy the object), then call the method.\n        :return: obj.do_method(*args)\n        \"\"\"\n        self.restore_point = self.obj.copy()\n        return self.do_method(self.obj, *self.args)", "title": ""}
{"_id": "d11433", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d11434", "text": "def generate_write_yaml_to_file(file_name):\n    \"\"\" generate a method to write the configuration in yaml to the method desired \"\"\"\n    def write_yaml(config):\n        with open(file_name, 'w+') as fh:\n            fh.write(yaml.dump(config))\n    return write_yaml", "title": ""}
{"_id": "d11435", "text": "def method(func):\n    \"\"\"Wrap a function as a method.\"\"\"\n    attr = abc.abstractmethod(func)\n    attr.__imethod__ = True\n    return attr", "title": ""}
{"_id": "d11436", "text": "def add_parent(self, parent):\n        \"\"\"\n        Adds self as child of parent, then adds parent.\n        \"\"\"\n        parent.add_child(self)\n        self.parent = parent\n        return parent", "title": ""}
{"_id": "d11437", "text": "def ColumnToIndex (col):\n        \"\"\"convert column to index. Eg: ConvertInIndex(\"AB\") = 28\"\"\"\n        ndx = 0\n        for c in col:\n                ndx = ndx * 26 + ord(c.upper()) - 64\n        return ndx", "title": ""}
{"_id": "d11438", "text": "def rel_path(filename):\n    \"\"\"\n    Function that gets relative path to the filename\n    \"\"\"\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)", "title": ""}
{"_id": "d11439", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d11440", "text": "def rel_path(filename):\n    \"\"\"\n    Function that gets relative path to the filename\n    \"\"\"\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)", "title": ""}
{"_id": "d11441", "text": "def debug_on_error(type, value, tb):\n    \"\"\"Code due to Thomas Heller - published in Python Cookbook (O'Reilley)\"\"\"\n    traceback.print_exc(type, value, tb)\n    print()\n    pdb.pm()", "title": ""}
{"_id": "d11442", "text": "def get_cursor(self):\n        \"\"\"Returns current grid cursor cell (row, col, tab)\"\"\"\n\n        return self.grid.GetGridCursorRow(), self.grid.GetGridCursorCol(), \\\n            self.grid.current_table", "title": ""}
{"_id": "d11443", "text": "def user_return(self, frame, return_value):\n        \"\"\"This function is called when a return trap is set here.\"\"\"\n        pdb.Pdb.user_return(self, frame, return_value)", "title": ""}
{"_id": "d11444", "text": "def translate_index_to_position(self, index):\n        \"\"\"\n        Given an index for the text, return the corresponding (row, col) tuple.\n        (0-based. Returns (0, 0) for index=0.)\n        \"\"\"\n        # Find start of this line.\n        row, row_index = self._find_line_start_index(index)\n        col = index - row_index\n\n        return row, col", "title": ""}
{"_id": "d11445", "text": "def dimensions(path):\n    \"\"\"Get width and height of a PDF\"\"\"\n    pdf = PdfFileReader(path)\n    size = pdf.getPage(0).mediaBox\n    return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d11446", "text": "def get_data():\n    \"\"\"\n    Currently pretends to talk to an instrument and get back the magnitud\n    and phase of the measurement.\n    \"\"\"\n\n    # pretend we're measuring a noisy resonance at zero\n    y = 1.0 / (1.0 + 1j*(n_x.get_value()-0.002)*1000) + _n.random.rand()*0.1\n\n    # and that it takes time to do so\n    _t.sleep(0.1)\n\n    # return mag phase\n    return abs(y), _n.angle(y, True)", "title": ""}
{"_id": "d11447", "text": "def _pdf_at_peak(self):\n    \"\"\"Pdf evaluated at the peak.\"\"\"\n    return (self.peak - self.low) / (self.high - self.low)", "title": ""}
{"_id": "d11448", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d11449", "text": "def _restore_seq_field_pickle(checked_class, item_type, data):\n    \"\"\"Unpickling function for auto-generated PVec/PSet field types.\"\"\"\n    type_ = _seq_field_types[checked_class, item_type]\n    return _restore_pickle(type_, data)", "title": ""}
{"_id": "d11450", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x.\"\"\"\n    i = bs.bisect_left(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d11451", "text": "def save(self, f):\n        \"\"\"Save pickled model to file.\"\"\"\n        return pickle.dump((self.perceptron.weights, self.tagdict, self.classes, self.clusters), f, protocol=pickle.HIGHEST_PROTOCOL)", "title": ""}
{"_id": "d11452", "text": "def get_idx_rect(index_list):\n    \"\"\"Extract the boundaries from a list of indexes\"\"\"\n    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))\n    return ( min(rows), max(rows), min(cols), max(cols) )", "title": ""}
{"_id": "d11453", "text": "def locate(command, on):\n    \"\"\"Locate the command's man page.\"\"\"\n    location = find_page_location(command, on)\n    click.echo(location)", "title": ""}
{"_id": "d11454", "text": "def puts_err(s='', newline=True, stream=STDERR):\n    \"\"\"Prints given string to stderr.\"\"\"\n    puts(s, newline, stream)", "title": ""}
{"_id": "d11455", "text": "def set_scrollregion(self, event=None):\n        \"\"\" Set the scroll region on the canvas\"\"\"\n        self.canvas.configure(scrollregion=self.canvas.bbox('all'))", "title": ""}
{"_id": "d11456", "text": "def get_nt_system_uid():\n    \"\"\"Get the MachineGuid from\n    HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Cryptography\\MachineGuid\n    \"\"\"\n    try:\n        import _winreg as winreg\n    except ImportError:\n        import winreg\n    lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)\n    try:\n        key = winreg.OpenKey(lm, r\"Software\\Microsoft\\Cryptography\")\n        try:\n            return winreg.QueryValueEx(key, \"MachineGuid\")[0]\n        finally:\n            key.Close()\n    finally:\n        lm.Close()", "title": ""}
{"_id": "d11457", "text": "def oplot(self, x, y, **kw):\n        \"\"\"generic plotting method, overplotting any existing plot \"\"\"\n        self.panel.oplot(x, y, **kw)", "title": ""}
{"_id": "d11458", "text": "def get_base_dir():\n    \"\"\"\n    Return the base directory\n    \"\"\"\n    return os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]", "title": ""}
{"_id": "d11459", "text": "def image_to_texture(image):\n    \"\"\"Converts ``vtkImageData`` to a ``vtkTexture``\"\"\"\n    vtex = vtk.vtkTexture()\n    vtex.SetInputDataObject(image)\n    vtex.Update()\n    return vtex", "title": ""}
{"_id": "d11460", "text": "def write_to_file(file_path, contents, encoding=\"utf-8\"):\n    \"\"\"\n    Write helper method\n\n    :type file_path: str|unicode\n    :type contents: str|unicode\n    :type encoding: str|unicode\n    \"\"\"\n    with codecs.open(file_path, \"w\", encoding) as f:\n        f.write(contents)", "title": ""}
{"_id": "d11461", "text": "def as_dict(self):\n        \"\"\"\n        Json-serializable dict representation of PhononDos.\n        \"\"\"\n        return {\"@module\": self.__class__.__module__,\n                \"@class\": self.__class__.__name__,\n                \"frequencies\": list(self.frequencies),\n                \"densities\": list(self.densities)}", "title": ""}
{"_id": "d11462", "text": "def levenshtein_distance_metric(a, b):\n    \"\"\" 1 - farthest apart (same number of words, all diff). 0 - same\"\"\"\n    return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1)))", "title": ""}
{"_id": "d11463", "text": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "title": ""}
{"_id": "d11464", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d11465", "text": "def pop(h):\n    \"\"\"Pop the heap value from the heap.\"\"\"\n    n = h.size() - 1\n    h.swap(0, n)\n    down(h, 0, n)\n    return h.pop()", "title": ""}
{"_id": "d11466", "text": "def dumps(obj):\n    \"\"\"Outputs json with formatting edits + object handling.\"\"\"\n    return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)", "title": ""}
{"_id": "d11467", "text": "def is_floating(self):\n        \"\"\"Returns whether this is a (non-quantized, real) floating point type.\"\"\"\n        return (\n            self.is_numpy_compatible and np.issubdtype(self.as_numpy_dtype, np.floating)\n        ) or self.base_dtype == bfloat16", "title": ""}
{"_id": "d11468", "text": "def _prtfmt(self, item_id, dashes):\n        \"\"\"Print object information using a namedtuple and a format pattern.\"\"\"\n        ntprt = self.id2nt[item_id]\n        dct = ntprt._asdict()\n        self.prt.write('{DASHES:{N}}'.format(\n            DASHES=self.fmt_dashes.format(DASHES=dashes, ID=self.nm2prtfmt['ID'].format(**dct)),\n            N=self.dash_len))\n        self.prt.write(\"{INFO}\\n\".format(INFO=self.nm2prtfmt['ITEM'].format(**dct)))", "title": ""}
{"_id": "d11469", "text": "def _guess_type(val):\n        \"\"\"Guess the input type of the parameter based off the default value, if unknown use text\"\"\"\n        if isinstance(val, bool):\n            return \"choice\"\n        elif isinstance(val, int):\n            return \"number\"\n        elif isinstance(val, float):\n            return \"number\"\n        elif isinstance(val, str):\n            return \"text\"\n        elif hasattr(val, 'read'):\n            return \"file\"\n        else:\n            return \"text\"", "title": ""}
{"_id": "d11470", "text": "def _tuple_repr(data):\n    \"\"\"Return a repr() for a list/tuple\"\"\"\n    if len(data) == 1:\n        return \"(%s,)\" % rpr(data[0])\n    else:\n        return \"(%s)\" % \", \".join([rpr(x) for x in data])", "title": ""}
{"_id": "d11471", "text": "def impute_data(self,x):\n        \"\"\"Imputes data set containing Nan values\"\"\"\n        imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n        return imp.fit_transform(x)", "title": ""}
{"_id": "d11472", "text": "def pretty(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Pretty print the object's representation.\n    \"\"\"\n    stream = StringIO()\n    printer = RepresentationPrinter(stream, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    return stream.getvalue()", "title": ""}
{"_id": "d11473", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d11474", "text": "def query_sum(queryset, field):\n    \"\"\"\n    Let the DBMS perform a sum on a queryset\n    \"\"\"\n    return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']", "title": ""}
{"_id": "d11475", "text": "def top(n, width=WIDTH, style=STYLE):\n    \"\"\"Prints the top row of a table\"\"\"\n    return hrule(n, width, linestyle=STYLES[style].top)", "title": ""}
{"_id": "d11476", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d11477", "text": "def hidden_cursor():\n    \"\"\"Temporarily hide the terminal cursor.\"\"\"\n    if sys.stdout.isatty():\n        _LOGGER.debug('Hiding cursor.')\n        print('\\x1B[?25l', end='')\n        sys.stdout.flush()\n    try:\n        yield\n    finally:\n        if sys.stdout.isatty():\n            _LOGGER.debug('Showing cursor.')\n            print('\\n\\x1B[?25h', end='')\n            sys.stdout.flush()", "title": ""}
{"_id": "d11478", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d11479", "text": "def show():\n    \"\"\"Show (print out) current environment variables.\"\"\"\n    env = get_environment()\n\n    for key, val in sorted(env.env.items(), key=lambda item: item[0]):\n        click.secho('%s = %s' % (key, val))", "title": ""}
{"_id": "d11480", "text": "def peekiter(iterable):\n    \"\"\"Return first row and also iterable with same items as original\"\"\"\n    it = iter(iterable)\n    one = next(it)\n\n    def gen():\n        \"\"\"Generator that returns first and proxy other items from source\"\"\"\n        yield one\n        while True:\n            yield next(it)\n    return (one, gen())", "title": ""}
{"_id": "d11481", "text": "def info(txt):\n    \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d11482", "text": "def get_all_files(folder):\n    \"\"\"\n    Generator that loops through all absolute paths of the files within folder\n\n    Parameters\n    ----------\n    folder: str\n    Root folder start point for recursive search.\n\n    Yields\n    ------\n    fpath: str\n    Absolute path of one file in the folders\n    \"\"\"\n    for path, dirlist, filelist in os.walk(folder):\n        for fn in filelist:\n            yield op.join(path, fn)", "title": ""}
{"_id": "d11483", "text": "def _attrprint(d, delimiter=', '):\n    \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n    return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))", "title": ""}
{"_id": "d11484", "text": "def debug(ftn, txt):\n    \"\"\"Used for debugging.\"\"\"\n    if debug_p:\n        sys.stdout.write(\"{0}.{1}:{2}\\n\".format(modname, ftn, txt))\n        sys.stdout.flush()", "title": ""}
{"_id": "d11485", "text": "def _join_masks_from_masked_array(data):\n    \"\"\"Union of masks.\"\"\"\n    if not isinstance(data.mask, np.ndarray):\n        # workaround to handle mask compressed to single value\n        mask = np.empty(data.data.shape, dtype=np.bool)\n        mask.fill(data.mask)\n        return mask\n    mask = data.mask[0].copy()\n    for i in range(1, len(data.mask)):\n        mask = np.logical_or(mask, data.mask[i])\n    return mask[np.newaxis, :, :]", "title": ""}
{"_id": "d11486", "text": "def _help():\n    \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n    statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n    print statement.strip()", "title": ""}
{"_id": "d11487", "text": "def go_to_line(self, line):\n        \"\"\"\n        Moves the text cursor to given line.\n\n        :param line: Line to go to.\n        :type line: int\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        cursor = self.textCursor()\n        cursor.setPosition(self.document().findBlockByNumber(line - 1).position())\n        self.setTextCursor(cursor)\n        return True", "title": ""}
{"_id": "d11488", "text": "def append(self, item):\n        \"\"\" append item and print it to stdout \"\"\"\n        print(item)\n        super(MyList, self).append(item)", "title": ""}
{"_id": "d11489", "text": "def get_unique_indices(df, axis=1):\n    \"\"\"\n\n    :param df:\n    :param axis:\n    :return:\n    \"\"\"\n    return dict(zip(df.columns.names, dif.columns.levels))", "title": ""}
{"_id": "d11490", "text": "def pretty(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Pretty print the object's representation.\n    \"\"\"\n    stream = StringIO()\n    printer = RepresentationPrinter(stream, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    return stream.getvalue()", "title": ""}
{"_id": "d11491", "text": "def contains_empty(features):\n    \"\"\"Check features data are not empty\n\n    :param features: The features data to check.\n    :type features: list of numpy arrays.\n\n    :return: True if one of the array is empty, False else.\n\n    \"\"\"\n    if not features:\n        return True\n    for feature in features:\n        if feature.shape[0] == 0:\n            return True\n    return False", "title": ""}
{"_id": "d11492", "text": "def pretty(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Pretty print the object's representation.\n    \"\"\"\n    stream = StringIO()\n    printer = RepresentationPrinter(stream, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    return stream.getvalue()", "title": ""}
{"_id": "d11493", "text": "def printOut(value, end='\\n'):\n    \"\"\"\n    This function prints the given String immediately and flushes the output.\n    \"\"\"\n    sys.stdout.write(value)\n    sys.stdout.write(end)\n    sys.stdout.flush()", "title": ""}
{"_id": "d11494", "text": "def help(self, level=0):\n        \"\"\"return the usage string for available options \"\"\"\n        self.cmdline_parser.formatter.output_level = level\n        with _patch_optparse():\n            return self.cmdline_parser.format_help()", "title": ""}
{"_id": "d11495", "text": "def _shape(self):\n        \"\"\"Return the tensor shape of the matrix operator\"\"\"\n        return tuple(reversed(self.output_dims())) + tuple(\n            reversed(self.input_dims()))", "title": ""}
{"_id": "d11496", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d11497", "text": "def _get_printable_columns(columns, row):\n    \"\"\"Return only the part of the row which should be printed.\n    \"\"\"\n    if not columns:\n        return row\n\n    # Extract the column values, in the order specified.\n    return tuple(row[c] for c in columns)", "title": ""}
{"_id": "d11498", "text": "def nlevels(self):\n        \"\"\"\n        Get the number of factor levels for each categorical column.\n\n        :returns: A list of the number of levels per column.\n        \"\"\"\n        levels = self.levels()\n        return [len(l) for l in levels] if levels else 0", "title": ""}
{"_id": "d11499", "text": "def _attrprint(d, delimiter=', '):\n    \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n    return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))", "title": ""}
{"_id": "d11500", "text": "def machine_info():\n    \"\"\"Retrieve core and memory information for the current machine.\n    \"\"\"\n    import psutil\n    BYTES_IN_GIG = 1073741824.0\n    free_bytes = psutil.virtual_memory().total\n    return [{\"memory\": float(\"%.1f\" % (free_bytes / BYTES_IN_GIG)), \"cores\": multiprocessing.cpu_count(),\n             \"name\": socket.gethostname()}]", "title": ""}
{"_id": "d11501", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d11502", "text": "def fetch_token(self, **kwargs):\n        \"\"\"Exchange a code (and 'state' token) for a bearer token\"\"\"\n        return super(AsanaOAuth2Session, self).fetch_token(self.token_url, client_secret=self.client_secret, **kwargs)", "title": ""}
{"_id": "d11503", "text": "def index(m, val):\n    \"\"\"\n    Return the indices of all the ``val`` in ``m``\n    \"\"\"\n    mm = np.array(m)\n    idx_tuple = np.where(mm == val)\n    idx = idx_tuple[0].tolist()\n\n    return idx", "title": ""}
{"_id": "d11504", "text": "def on_property_change(self, name, old_value, new_value):\n        \"\"\"\n        Called by the instance manager when a component property is modified\n\n        :param name: The changed property name\n        :param old_value: The previous property value\n        :param new_value: The new property value\n        \"\"\"\n        if self._registration is not None:\n            # use the registration to trigger the service event\n            self._registration.set_properties({name: new_value})", "title": ""}
{"_id": "d11505", "text": "def get_python():\n    \"\"\"Determine the path to the virtualenv 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", "title": ""}
{"_id": "d11506", "text": "def get_property(self):\n        \"\"\"Establishes access of GettableProperty values\"\"\"\n\n        scope = self\n\n        def fget(self):\n            \"\"\"Call the HasProperties _get method\"\"\"\n            return self._get(scope.name)\n\n        return property(fget=fget, doc=scope.sphinx())", "title": ""}
{"_id": "d11507", "text": "def to_camel_case(text):\n    \"\"\"Convert to camel case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    split = text.split('_')\n    return split[0] + \"\".join(x.title() for x in split[1:])", "title": ""}
{"_id": "d11508", "text": "def load(self):\n        \"\"\"Load proxy list from configured proxy source\"\"\"\n        self._list = self._source.load()\n        self._list_iter = itertools.cycle(self._list)", "title": ""}
{"_id": "d11509", "text": "def ci(a, which=95, axis=None):\n    \"\"\"Return a percentile range from an array of values.\"\"\"\n    p = 50 - which / 2, 50 + which / 2\n    return percentiles(a, p, axis)", "title": ""}
{"_id": "d11510", "text": "def url_to_image(url):\n    \"\"\"\n    Fetch an image from url and convert it into a Pillow Image object\n    \"\"\"\n    r = requests.get(url)\n    image = StringIO(r.content)\n    return image", "title": ""}
{"_id": "d11511", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d11512", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d11513", "text": "def end_of_history(event):\n    \"\"\"\n    Move to the end of the input history, i.e., the line currently being entered.\n    \"\"\"\n    event.current_buffer.history_forward(count=10**100)\n    buff = event.current_buffer\n    buff.go_to_history(len(buff._working_lines) - 1)", "title": ""}
{"_id": "d11514", "text": "def read_dict_from_file(file_path):\n    \"\"\"\n    Read a dictionary of strings from a file\n    \"\"\"\n    with open(file_path) as file:\n        lines = file.read().splitlines()\n\n    obj = {}\n    for line in lines:\n        key, value = line.split(':', maxsplit=1)\n        obj[key] = eval(value)\n\n    return obj", "title": ""}
{"_id": "d11515", "text": "def a2s(a):\n    \"\"\"\n     convert 3,3 a matrix to 6 element \"s\" list  (see Tauxe 1998)\n    \"\"\"\n    s = np.zeros((6,), 'f')  # make the a matrix\n    for i in range(3):\n        s[i] = a[i][i]\n    s[3] = a[0][1]\n    s[4] = a[1][2]\n    s[5] = a[0][2]\n    return s", "title": ""}
{"_id": "d11516", "text": "def fopen(name, mode='r', buffering=-1):\n    \"\"\"Similar to Python's built-in `open()` function.\"\"\"\n    f = _fopen(name, mode, buffering)\n    return _FileObjectThreadWithContext(f, mode, buffering)", "title": ""}
{"_id": "d11517", "text": "def on_key_press(self, symbol, modifiers):\n        \"\"\"\n        Pyglet specific key press callback.\n        Forwards and translates the events to :py:func:`keyboard_event`\n        \"\"\"\n        self.keyboard_event(symbol, self.keys.ACTION_PRESS, modifiers)", "title": ""}
{"_id": "d11518", "text": "def map(cls, iterable, func, *a, **kw):\n    \"\"\"\n    Iterable-first replacement of Python's built-in `map()` function.\n    \"\"\"\n\n    return cls(func(x, *a, **kw) for x in iterable)", "title": ""}
{"_id": "d11519", "text": "def update_one(self, query, doc):\n        \"\"\"\n        Updates one element of the collection\n\n        :param query: dictionary representing the mongo query\n        :param doc: dictionary representing the item to be updated\n        :return: UpdateResult\n        \"\"\"\n        if self.table is None:\n            self.build_table()\n\n        if u\"$set\" in doc:\n            doc = doc[u\"$set\"]\n\n        allcond = self.parse_query(query)\n\n        try:\n            result = self.table.update(doc, allcond)\n        except:\n            # TODO: check table.update result\n            # check what pymongo does in that case\n            result = None\n\n        return UpdateResult(raw_result=result)", "title": ""}
{"_id": "d11520", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d11521", "text": "def _get_column_by_db_name(cls, name):\n        \"\"\"\n        Returns the column, mapped by db_field name\n        \"\"\"\n        return cls._columns.get(cls._db_map.get(name, name))", "title": ""}
{"_id": "d11522", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d11523", "text": "def readme():\n    \"\"\"Try converting the README to an RST document. Return it as is on failure.\"\"\"\n    try:\n        import pypandoc\n        readme_content = pypandoc.convert('README.md', 'rst')\n    except(IOError, ImportError):\n        print(\"Warning: no pypandoc module found.\")\n        try:\n            readme_content = open('README.md').read()\n        except IOError:\n            readme_content = ''\n    return readme_content", "title": ""}
{"_id": "d11524", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d11525", "text": "def _updateItemComboBoxIndex(self, item, column, num):\n        \"\"\"Callback for comboboxes: notifies us that a combobox for the given item and column has changed\"\"\"\n        item._combobox_current_index[column] = num\n        item._combobox_current_value[column] = item._combobox_option_list[column][num][0]", "title": ""}
{"_id": "d11526", "text": "def get_auth():\n    \"\"\"Get authentication.\"\"\"\n    import getpass\n    user = input(\"User Name: \")  # noqa\n    pswd = getpass.getpass('Password: ')\n    return Github(user, pswd)", "title": ""}
{"_id": "d11527", "text": "def parse_querystring(self, req, name, field):\n        \"\"\"Pull a querystring value from the request.\"\"\"\n        return core.get_value(req.args, name, field)", "title": ""}
{"_id": "d11528", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d11529", "text": "def represented_args(args, separator=\" \"):\n    \"\"\"\n    Args:\n        args (list | tuple | None): Arguments to represent\n        separator (str | unicode): Separator to use\n\n    Returns:\n        (str): Quoted as needed textual representation\n    \"\"\"\n    result = []\n    if args:\n        for text in args:\n            result.append(quoted(short(text)))\n    return separator.join(result)", "title": ""}
{"_id": "d11530", "text": "def err(msg):\n    \"\"\"Pretty-print an error.\"\"\"\n    click.echo(click.style(msg, fg=\"red\", bold=True))", "title": ""}
{"_id": "d11531", "text": "def reconnect(self):\n        \"\"\"Reconnect to rabbitmq server\"\"\"\n        import pika\n        import pika.exceptions\n\n        self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))\n        self.channel = self.connection.channel()\n        try:\n            self.channel.queue_declare(self.name)\n        except pika.exceptions.ChannelClosed:\n            self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))\n            self.channel = self.connection.channel()", "title": ""}
{"_id": "d11532", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d11533", "text": "def reraise(error):\n    \"\"\"Re-raises the error that was processed by prepare_for_reraise earlier.\"\"\"\n    if hasattr(error, \"_type_\"):\n        six.reraise(type(error), error, error._traceback)\n    raise error", "title": ""}
{"_id": "d11534", "text": "def is_sparse_vector(x):\n    \"\"\" x is a 2D sparse matrix with it's first shape equal to 1.\n    \"\"\"\n    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1", "title": ""}
{"_id": "d11535", "text": "def _re_raise_as(NewExc, *args, **kw):\n    \"\"\"Raise a new exception using the preserved traceback of the last one.\"\"\"\n    etype, val, tb = sys.exc_info()\n    raise NewExc(*args, **kw), None, tb", "title": ""}
{"_id": "d11536", "text": "def _iterable_to_varargs_method(func):\n    \"\"\"decorator to convert a method taking a iterable to a *args one\"\"\"\n    def wrapped(self, *args, **kwargs):\n        return func(self, args, **kwargs)\n    return wrapped", "title": ""}
{"_id": "d11537", "text": "async def power(source, exponent):\n    \"\"\"Raise the elements of an asynchronous sequence to the given power.\"\"\"\n    async with streamcontext(source) as streamer:\n        async for item in streamer:\n            yield item ** exponent", "title": ""}
{"_id": "d11538", "text": "def  make_html_code( self, lines ):\n        \"\"\" convert a code sequence to HTML \"\"\"\n        line = code_header + '\\n'\n        for l in lines:\n            line = line + html_quote( l ) + '\\n'\n\n        return line + code_footer", "title": ""}
{"_id": "d11539", "text": "def rlognormal(mu, tau, size=None):\n    \"\"\"\n    Return random lognormal variates.\n    \"\"\"\n\n    return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "title": ""}
{"_id": "d11540", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d11541", "text": "def move_back(self, dt):\n        \"\"\" If called after an update, the sprite can move back\n        \"\"\"\n        self._position = self._old_position\n        self.rect.topleft = self._position\n        self.feet.midbottom = self.rect.midbottom", "title": ""}
{"_id": "d11542", "text": "def random_color(_min=MIN_COLOR, _max=MAX_COLOR):\n    \"\"\"Returns a random color between min and max.\"\"\"\n    return color(random.randint(_min, _max))", "title": ""}
{"_id": "d11543", "text": "def startEdit( self ):\n        \"\"\"\n        Rebuilds the pathing based on the parts.\n        \"\"\"\n        self._originalText = self.text()\n        self.scrollWidget().hide()\n        self.setFocus()\n        self.selectAll()", "title": ""}
{"_id": "d11544", "text": "def _loadfilepath(self, filepath, **kwargs):\n        \"\"\"This loads a geojson file into a geojson python\n        dictionary using the json module.\n        \n        Note: to load with a different text encoding use the encoding argument.\n        \"\"\"\n        with open(filepath, \"r\") as f:\n            data = json.load(f, **kwargs)\n        return data", "title": ""}
{"_id": "d11545", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d11546", "text": "def ReadManyFromPath(filepath):\n  \"\"\"Reads a Python object stored in a specified YAML file.\n\n  Args:\n    filepath: A filepath to the YAML file.\n\n  Returns:\n    A Python data structure corresponding to the YAML in the given file.\n  \"\"\"\n  with io.open(filepath, mode=\"r\", encoding=\"utf-8\") as filedesc:\n    return ReadManyFromFile(filedesc)", "title": ""}
{"_id": "d11547", "text": "def _clean_workers(self):\n        \"\"\"Delete periodically workers in workers bag.\"\"\"\n        while self._bag_collector:\n            self._bag_collector.popleft()\n        self._timer_worker_delete.stop()", "title": ""}
{"_id": "d11548", "text": "def read_data(file, endian, num=1):\n    \"\"\"\n    Read a given number of 32-bits unsigned integers from the given file\n    with the given endianness.\n    \"\"\"\n    res = struct.unpack(endian + 'L' * num, file.read(num * 4))\n    if len(res) == 1:\n        return res[0]\n    return res", "title": ""}
{"_id": "d11549", "text": "def disable(self):\n        \"\"\"\n        Disable the button, if in non-expert mode;\n        unset its activity flag come-what-may.\n        \"\"\"\n        if not self._expert:\n            self.config(state='disable')\n        self._active = False", "title": ""}
{"_id": "d11550", "text": "def _parse_config(config_file_path):\n    \"\"\" Parse Config File from yaml file. \"\"\"\n    config_file = open(config_file_path, 'r')\n    config = yaml.load(config_file)\n    config_file.close()\n    return config", "title": ""}
{"_id": "d11551", "text": "def filter_contour(imageFile, opFile):\n    \"\"\" convert an image by applying a contour \"\"\"\n    im = Image.open(imageFile)\n    im1 = im.filter(ImageFilter.CONTOUR)\n    im1.save(opFile)", "title": ""}
{"_id": "d11552", "text": "def timedcall(executable_function, *args):\n    \"\"\"!\n    @brief Executes specified method or function with measuring of execution time.\n    \n    @param[in] executable_function (pointer): Pointer to function or method.\n    @param[in] args (*): Arguments of called function or method.\n    \n    @return (tuple) Execution time and result of execution of function or method (execution_time, result_execution).\n    \n    \"\"\"\n    \n    time_start = time.clock();\n    result = executable_function(*args);\n    time_end = time.clock();\n    \n    return (time_end - time_start, result);", "title": ""}
{"_id": "d11553", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d11554", "text": "def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx):\n        \"\"\"Merge all columns and place text string in widened cell.\"\"\"\n        hdridxval = len(self.hdrs) - 1\n        worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt)\n        return row_idx + 1", "title": ""}
{"_id": "d11555", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d11556", "text": "def _int64_feature(value):\n  \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))", "title": ""}
{"_id": "d11557", "text": "def attach_to_container(self, container_id):\n        \"\"\" A socket attached to the stdin/stdout of a container. The object returned contains a get_socket() function to get a socket.socket\n        object and  close_socket() to close the connection \"\"\"\n        sock = self._docker.containers.get(container_id).attach_socket(params={\n            'stdin': 1,\n            'stdout': 1,\n            'stderr': 0,\n            'stream': 1,\n        })\n        # fix a problem with docker-py; we must keep a reference of sock at every time\n        return FixDockerSocket(sock)", "title": ""}
{"_id": "d11558", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d11559", "text": "def _read_json_file(self, json_file):\n        \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n        self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n        with open(json_file, 'r') as f:\n            return json.load(f, object_pairs_hook=OrderedDict)", "title": ""}
{"_id": "d11560", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d11561", "text": "def get(url):\n    \"\"\"Recieving the JSON file from uulm\"\"\"\n    response = urllib.request.urlopen(url)\n    data = response.read()\n    data = data.decode(\"utf-8\")\n    data = json.loads(data)\n    return data", "title": ""}
{"_id": "d11562", "text": "def normalize(self, string):\n        \"\"\"Normalize the string according to normalization list\"\"\"\n        return ''.join([self._normalize.get(x, x) for x in nfd(string)])", "title": ""}
{"_id": "d11563", "text": "def flattened_nested_key_indices(nested_dict):\n    \"\"\"\n    Combine the outer and inner keys of nested dictionaries into a single\n    ordering.\n    \"\"\"\n    outer_keys, inner_keys = collect_nested_keys(nested_dict)\n    combined_keys = list(sorted(set(outer_keys + inner_keys)))\n    return {k: i for (i, k) in enumerate(combined_keys)}", "title": ""}
{"_id": "d11564", "text": "def read_stdin():\n    \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n    if sys.stdin.isatty() and sys.stdout.isatty():\n        print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n    return sys.stdin.read()", "title": ""}
{"_id": "d11565", "text": "def zero_pad(m, n=1):\n    \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n    return np.pad(m, (n, n), mode='constant', constant_values=[0])", "title": ""}
{"_id": "d11566", "text": "def _openResources(self):\n        \"\"\" Uses numpy.load to open the underlying file\n        \"\"\"\n        arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n        check_is_an_array(arr)\n        self._array = arr", "title": ""}
{"_id": "d11567", "text": "def save_list(key, *values):\n    \"\"\"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.\n\n    \"\"\"\n    return json.dumps({key: [_get_json(value) for value in values]})", "title": ""}
{"_id": "d11568", "text": "def read_corpus(file_name):\n    \"\"\"\n    Read and return the data from a corpus json file.\n    \"\"\"\n    with io.open(file_name, encoding='utf-8') as data_file:\n        return yaml.load(data_file)", "title": ""}
{"_id": "d11569", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d11570", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d11571", "text": "def send(socket, data, num_bytes=20):\n    \"\"\"Send data to specified socket.\n\n\n    :param socket: open socket instance\n    :param data: data to send\n    :param num_bytes: number of bytes to read\n\n    :return: received data\n    \"\"\"\n    pickled_data = pickle.dumps(data, -1)\n    length = str(len(pickled_data)).zfill(num_bytes)\n    socket.sendall(length.encode())\n    socket.sendall(pickled_data)", "title": ""}
{"_id": "d11572", "text": "def _readuntil(f, end=_TYPE_END):\n\t\"\"\"Helper function to read bytes until a certain end byte is hit\"\"\"\n\tbuf = bytearray()\n\tbyte = f.read(1)\n\twhile byte != end:\n\t\tif byte == b'':\n\t\t\traise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))\n\t\tbuf += byte\n\t\tbyte = f.read(1)\n\treturn buf", "title": ""}
{"_id": "d11573", "text": "def push(h, x):\n    \"\"\"Push a new value into heap.\"\"\"\n    h.push(x)\n    up(h, h.size()-1)", "title": ""}
{"_id": "d11574", "text": "def osx_clipboard_get():\n    \"\"\" Get the clipboard's text on OS X.\n    \"\"\"\n    p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n        stdout=subprocess.PIPE)\n    text, stderr = p.communicate()\n    # Text comes in with old Mac \\r line endings. Change them to \\n.\n    text = text.replace('\\r', '\\n')\n    return text", "title": ""}
{"_id": "d11575", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d11576", "text": "def camelcase2list(s, lower=False):\n    \"\"\"Converts a camelcase string to a list.\"\"\"\n    s = re.findall(r'([A-Z][a-z0-9]+)', s)\n    return [w.lower() for w in s] if lower else s", "title": ""}
{"_id": "d11577", "text": "def print(*a):\n    \"\"\" print just one that returns what you give it instead of None \"\"\"\n    try:\n        _print(*a)\n        return a[0] if len(a) == 1 else a\n    except:\n        _print(*a)", "title": ""}
{"_id": "d11578", "text": "def get_naive(dt):\n  \"\"\"Gets a naive datetime from a datetime.\n\n  datetime_tz objects can't just have tzinfo replaced with None, you need to\n  call asdatetime.\n\n  Args:\n    dt: datetime object.\n\n  Returns:\n    datetime object without any timezone information.\n  \"\"\"\n  if not dt.tzinfo:\n    return dt\n  if hasattr(dt, \"asdatetime\"):\n    return dt.asdatetime()\n  return dt.replace(tzinfo=None)", "title": ""}
{"_id": "d11579", "text": "def _help():\n    \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n    statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n    print statement.strip()", "title": ""}
{"_id": "d11580", "text": "def validate(schema, data, owner=None):\n    \"\"\"Validate input data with input schema.\n\n    :param Schema schema: schema able to validate input data.\n    :param data: data to validate.\n    :param Schema owner: input schema parent schema.\n    :raises: Exception if the data is not validated.\n    \"\"\"\n    schema._validate(data=data, owner=owner)", "title": ""}
{"_id": "d11581", "text": "def out(self, output, newline=True):\n        \"\"\"Outputs a string to the console (stdout).\"\"\"\n        click.echo(output, nl=newline)", "title": ""}
{"_id": "d11582", "text": "def flat_list(lst):\n    \"\"\"This function flatten given nested list.\n    Argument:\n        nested list\n    Returns:\n        flat list\n    \"\"\"\n    if isinstance(lst, list):\n        for item in lst:\n            for i in flat_list(item):\n                yield i\n    else:\n        yield lst", "title": ""}
{"_id": "d11583", "text": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d11584", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d11585", "text": "def printc(cls, txt, color=colors.red):\n        \"\"\"Print in color.\"\"\"\n        print(cls.color_txt(txt, color))", "title": ""}
{"_id": "d11586", "text": "def make_key(self, key, version=None):\n        \"\"\"RedisCache will set prefix+version as prefix for each key.\"\"\"\n        return '{}:{}:{}'.format(\n            self.prefix,\n            version or self.version,\n            key,\n        )", "title": ""}
{"_id": "d11587", "text": "def head_and_tail_print(self, n=5):\n        \"\"\"Display the first and last n elements of a DataFrame.\"\"\"\n        from IPython import display\n        display.display(display.HTML(self._head_and_tail_table(n)))", "title": ""}
{"_id": "d11588", "text": "def rpop(self, key):\n        \"\"\"Emulate lpop.\"\"\"\n        redis_list = self._get_list(key, 'RPOP')\n\n        if self._encode(key) not in self.redis:\n            return None\n\n        try:\n            value = redis_list.pop()\n            if len(redis_list) == 0:\n                self.delete(key)\n            return value\n        except (IndexError):\n            # Redis returns nil if popping from an empty list\n            return None", "title": ""}
{"_id": "d11589", "text": "def confusion_matrix(links_true, links_pred, total=None):\n    \"\"\"Compute the confusion matrix.\n\n    The confusion matrix is of the following form:\n\n    +----------------------+-----------------------+----------------------+\n    |                      |  Predicted Positives  | Predicted Negatives  |\n    +======================+=======================+======================+\n    | **True Positives**   | True Positives (TP)   | False Negatives (FN) |\n    +----------------------+-----------------------+----------------------+\n    | **True Negatives**   | False Positives (FP)  | True Negatives (TN)  |\n    +----------------------+-----------------------+----------------------+\n\n    The confusion matrix is an informative way to analyse a prediction. The\n    matrix can used to compute measures like precision and recall. The count\n    of true prositives is [0,0], false negatives is [0,1], true negatives\n    is [1,1] and false positives is [1,0].\n\n    Parameters\n    ----------\n    links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n        The true (or actual) links.\n    links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n        The predicted links.\n    total: int, pandas.MultiIndex\n        The count of all record pairs (both links and non-links). When the\n        argument is a pandas.MultiIndex, the length of the index is used. If\n        the total is None, the number of True Negatives is not computed.\n        Default None.\n\n    Returns\n    -------\n    numpy.array\n        The confusion matrix with TP, TN, FN, FP values.\n\n    Note\n    ----\n    The number of True Negatives is computed based on the total argument.\n    This argument is the number of record pairs of the entire matrix.\n\n    \"\"\"\n\n    links_true = _get_multiindex(links_true)\n    links_pred = _get_multiindex(links_pred)\n\n    tp = true_positives(links_true, links_pred)\n    fp = false_positives(links_true, links_pred)\n    fn = false_negatives(links_true, links_pred)\n\n    if total is None:\n        tn = numpy.nan\n    else:\n        tn = true_negatives(links_true, links_pred, total)\n\n    return numpy.array([[tp, fn], [fp, tn]])", "title": ""}
{"_id": "d11590", "text": "def lpush(self, key, *args):\n        \"\"\"Emulate lpush.\"\"\"\n        redis_list = self._get_list(key, 'LPUSH', create=True)\n\n        # Creates the list at this key if it doesn't exist, and appends args to its beginning\n        args_reversed = [self._encode(arg) for arg in args]\n        args_reversed.reverse()\n        updated_list = args_reversed + redis_list\n        self.redis[self._encode(key)] = updated_list\n\n        # Return the length of the list after the push operation\n        return len(updated_list)", "title": ""}
{"_id": "d11591", "text": "def m(name='', **kwargs):\n    \"\"\"\n    Print out memory usage at this point in time\n\n    http://docs.python.org/2/library/resource.html\n    http://stackoverflow.com/a/15448600/5006\n    http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended\n    \"\"\"\n    with Reflect.context(**kwargs) as r:\n        kwargs[\"name\"] = name\n        instance = M_CLASS(r, stream, **kwargs)\n        instance()", "title": ""}
{"_id": "d11592", "text": "def connect(self):\n        \"\"\"\n        Connects to publisher\n        \"\"\"\n        self.client = redis.Redis(\n            host=self.host, port=self.port, password=self.password)", "title": ""}
{"_id": "d11593", "text": "def append(self, item):\n        \"\"\" append item and print it to stdout \"\"\"\n        print(item)\n        super(MyList, self).append(item)", "title": ""}
{"_id": "d11594", "text": "def camel_to_(s):\n    \"\"\"\n    Convert CamelCase to camel_case\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', s)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d11595", "text": "def exit(self):\n        \"\"\"Handle interactive exit.\n\n        This method calls the ask_exit callback.\"\"\"\n        if self.confirm_exit:\n            if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):\n                self.ask_exit()\n        else:\n            self.ask_exit()", "title": ""}
{"_id": "d11596", "text": "def parse_domain(url):\n    \"\"\" parse the domain from the url \"\"\"\n    domain_match = lib.DOMAIN_REGEX.match(url)\n    if domain_match:\n        return domain_match.group()", "title": ""}
{"_id": "d11597", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d11598", "text": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "title": ""}
{"_id": "d11599", "text": "def to_snake_case(text):\n    \"\"\"Convert to snake case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d11600", "text": "def download_json(local_filename, url, clobber=False):\n    \"\"\"Download the given JSON file, and pretty-print before we output it.\"\"\"\n    with open(local_filename, 'w') as json_file:\n        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))", "title": ""}
{"_id": "d11601", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d11602", "text": "def __init__(self, node_def, op, message):\n        \"\"\"Creates an `InvalidArgumentError`.\"\"\"\n        super(InvalidArgumentError, self).__init__(\n            node_def, op, message, INVALID_ARGUMENT\n        )", "title": ""}
{"_id": "d11603", "text": "def parse_scale(x):\n    \"\"\"Splits a \"%s:%d\" string and returns the string and number.\n\n    :return: A ``(string, int)`` pair extracted from ``x``.\n\n    :raise ValueError: the string ``x`` does not respect the input format.\n    \"\"\"\n    match = re.match(r'^(.+?):(\\d+)$', x)\n    if not match:\n        raise ValueError('Invalid scale \"%s\".' % x)\n    return match.group(1), int(match.group(2))", "title": ""}
{"_id": "d11604", "text": "def import_path(self):\n    \"\"\"The full remote import path as used in import statements in `.go` source files.\"\"\"\n    return os.path.join(self.remote_root, self.pkg) if self.pkg else self.remote_root", "title": ""}
{"_id": "d11605", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d11606", "text": "def cmd_reindex():\n    \"\"\"Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.\n\n    The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until\n    the rename succeeds.\n    \"\"\"\n    db = connect(args.database)\n    for idx in args.indexes:\n        pg_reindex(db, idx)", "title": ""}
{"_id": "d11607", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d11608", "text": "def read_raw(data_path):\n    \"\"\"\n    Parameters\n    ----------\n    data_path : str\n    \"\"\"\n    with open(data_path, 'rb') as f:\n        data = pickle.load(f)\n    return data", "title": ""}
{"_id": "d11609", "text": "def unaccentuate(s):\n    \"\"\" Replace accentuated chars in string by their non accentuated equivalent. \"\"\"\n    return \"\".join(c for c in unicodedata.normalize(\"NFKD\", s) if not unicodedata.combining(c))", "title": ""}
{"_id": "d11610", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d11611", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d11612", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d11613", "text": "def removeFromRegistery(obj) :\n\t\"\"\"Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory\n\ttaken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects,\n\tcascades to free the registeries of related rabalists also\"\"\"\n\t\n\tif isRabaObject(obj) :\n\t\t_unregisterRabaObjectInstance(obj)\n\telif isRabaList(obj) :\n\t\t_unregisterRabaListInstance(obj)", "title": ""}
{"_id": "d11614", "text": "def xmltreefromfile(filename):\n    \"\"\"Internal function to read an XML file\"\"\"\n    try:\n        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n    except TypeError:\n        return ElementTree.parse(filename, ElementTree.XMLParser())", "title": ""}
{"_id": "d11615", "text": "def clean_axis(axis):\n    \"\"\"Remove ticks, tick labels, and frame from axis\"\"\"\n    axis.get_xaxis().set_ticks([])\n    axis.get_yaxis().set_ticks([])\n    for spine in list(axis.spines.values()):\n        spine.set_visible(False)", "title": ""}
{"_id": "d11616", "text": "def method(func):\n    \"\"\"Wrap a function as a method.\"\"\"\n    attr = abc.abstractmethod(func)\n    attr.__imethod__ = True\n    return attr", "title": ""}
{"_id": "d11617", "text": "def _series_col_letter(self, series):\n        \"\"\"\n        The letter of the Excel worksheet column in which the data for a\n        series appears.\n        \"\"\"\n        column_number = 1 + series.categories.depth + series.index\n        return self._column_reference(column_number)", "title": ""}
{"_id": "d11618", "text": "def _remove_duplicate_files(xs):\n    \"\"\"Remove files specified multiple times in a list.\n    \"\"\"\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", "title": ""}
{"_id": "d11619", "text": "def _remove_from_index(index, obj):\n    \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n    try:\n        index.value_map[indexed_value(index, obj)].remove(obj.id)\n    except KeyError:\n        pass", "title": ""}
{"_id": "d11620", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d11621", "text": "def remove_punctuation(text, exceptions=[]):\n    \"\"\"\n    Return a string with punctuation removed.\n\n    Parameters:\n        text (str): The text to remove punctuation from.\n        exceptions (list): List of symbols to keep in the given text.\n\n    Return:\n        str: The input text without the punctuation.\n    \"\"\"\n\n    all_but = [\n        r'\\w',\n        r'\\s'\n    ]\n\n    all_but.extend(exceptions)\n\n    pattern = '[^{}]'.format(''.join(all_but))\n\n    return re.sub(pattern, '', text)", "title": ""}
{"_id": "d11622", "text": "def __del__(self):\n    \"\"\"Cleans up the file entry.\"\"\"\n    # __del__ can be invoked before __init__ has completed.\n    if hasattr(self, '_encoded_stream'):\n      self._encoded_stream.close()\n      self._encoded_stream = None\n\n    super(EncodedStreamFileEntry, self).__del__()", "title": ""}
{"_id": "d11623", "text": "def pop (self, key):\n        \"\"\"Remove key from dict and return value.\"\"\"\n        if key in self._keys:\n            self._keys.remove(key)\n        super(ListDict, self).pop(key)", "title": ""}
{"_id": "d11624", "text": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "title": ""}
{"_id": "d11625", "text": "def pop(h):\n    \"\"\"Pop the heap value from the heap.\"\"\"\n    n = h.size() - 1\n    h.swap(0, n)\n    down(h, 0, n)\n    return h.pop()", "title": ""}
{"_id": "d11626", "text": "def DeleteIndex(self, index):\n        \"\"\"\n        Remove a spent coin based on its index.\n\n        Args:\n            index (int):\n        \"\"\"\n        to_remove = None\n        for i in self.Items:\n            if i.index == index:\n                to_remove = i\n\n        if to_remove:\n            self.Items.remove(to_remove)", "title": ""}
{"_id": "d11627", "text": "def urlize_twitter(text):\n    \"\"\"\n    Replace #hashtag and @username references in a tweet with HTML text.\n    \"\"\"\n    html = TwitterText(text).autolink.auto_link()\n    return mark_safe(html.replace(\n        'twitter.com/search?q=', 'twitter.com/search/realtime/'))", "title": ""}
{"_id": "d11628", "text": "def lowstrip(term):\n    \"\"\"Convert to lowercase and strip spaces\"\"\"\n    term = re.sub('\\s+', ' ', term)\n    term = term.lower()\n    return term", "title": ""}
{"_id": "d11629", "text": "def format_screen(strng):\n    \"\"\"Format a string for screen printing.\n\n    This removes some latex-type format codes.\"\"\"\n    # Paragraph continue\n    par_re = re.compile(r'\\\\$',re.MULTILINE)\n    strng = par_re.sub('',strng)\n    return strng", "title": ""}
{"_id": "d11630", "text": "def remove_instance(self, item):\n        \"\"\"Remove `instance` from model\"\"\"\n        self.instances.remove(item)\n        self.remove_item(item)", "title": ""}
{"_id": "d11631", "text": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n    \"\"\"Clean a pandas dataframe by:\n        1. Filling empty values with Nan\n        2. Dropping columns with all empty values\n\n    Args:\n        df: Pandas DataFrame\n        fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n        drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n    Returns:\n        DataFrame: cleaned DataFrame\n\n    \"\"\"\n    if fill_nan:\n        df = df.fillna(value=np.nan)\n    if drop_empty_columns:\n        df = df.dropna(axis=1, how='all')\n    return df.sort_index()", "title": ""}
{"_id": "d11632", "text": "def dict_keys_without_hyphens(a_dict):\n    \"\"\"Return the a new dict with underscores instead of hyphens in keys.\"\"\"\n    return dict(\n        (key.replace('-', '_'), val) for key, val in a_dict.items())", "title": ""}
{"_id": "d11633", "text": "def _remove_blank(l):\n        \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n        ret = []\n        for i, _ in enumerate(l):\n            if l[i] == 0:\n                break\n            ret.append(l[i])\n        return ret", "title": ""}
{"_id": "d11634", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d11635", "text": "def insort_no_dup(lst, item):\n    \"\"\"\n    If item is not in lst, add item to list at its sorted position\n    \"\"\"\n    import bisect\n    ix = bisect.bisect_left(lst, item)\n    if lst[ix] != item: \n        lst[ix:ix] = [item]", "title": ""}
{"_id": "d11636", "text": "def delistify(x):\n    \"\"\" A basic slug version of a given parameter list. \"\"\"\n    if isinstance(x, list):\n        x = [e.replace(\"'\", \"\") for e in x]\n        return '-'.join(sorted(x))\n    return x", "title": ""}
{"_id": "d11637", "text": "def _index_ordering(redshift_list):\n        \"\"\"\n\n        :param redshift_list: list of redshifts\n        :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n        \"\"\"\n        redshift_list = np.array(redshift_list)\n        sort_index = np.argsort(redshift_list)\n        return sort_index", "title": ""}
{"_id": "d11638", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d11639", "text": "def template_substitute(text, **kwargs):\n    \"\"\"\n    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.\n    \"\"\"\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", "title": ""}
{"_id": "d11640", "text": "def to_snake_case(text):\n    \"\"\"Convert to snake case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d11641", "text": "def normalise_string(string):\n    \"\"\" Strips trailing whitespace from string, lowercases it and replaces\n        spaces with underscores\n    \"\"\"\n    string = (string.strip()).lower()\n    return re.sub(r'\\W+', '_', string)", "title": ""}
{"_id": "d11642", "text": "def quote(s, unsafe='/'):\n    \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n    encoded value as the value.\"\"\"\n    res = s.replace('%', '%25')\n    for c in unsafe:\n        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n    return res", "title": ""}
{"_id": "d11643", "text": "def rewindbody(self):\n        \"\"\"Rewind the file to the start of the body (if seekable).\"\"\"\n        if not self.seekable:\n            raise IOError, \"unseekable file\"\n        self.fp.seek(self.startofbody)", "title": ""}
{"_id": "d11644", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d11645", "text": "def find_whole_word(w):\n    \"\"\"\n    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.\n    \"\"\"\n    return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search", "title": ""}
{"_id": "d11646", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d11647", "text": "def now_time(str=False):\n    \"\"\"Get the current time.\"\"\"\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()", "title": ""}
{"_id": "d11648", "text": "def replace(s, replace):\n    \"\"\"Replace multiple values in a string\"\"\"\n    for r in replace:\n        s = s.replace(*r)\n    return s", "title": ""}
{"_id": "d11649", "text": "def calculate_month(birth_date):\n    \"\"\"\n    Calculates and returns a month number basing on PESEL standard.\n    \"\"\"\n    year = int(birth_date.strftime('%Y'))\n    month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20\n\n    return month", "title": ""}
{"_id": "d11650", "text": "def fillna(series_or_arr, missing_value=0.0):\n    \"\"\"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.\n    \"\"\"\n\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\n    return series_or_arr", "title": ""}
{"_id": "d11651", "text": "def get_rounded(self, digits):\n        \"\"\" Return a vector with the elements rounded to the given number of digits. \"\"\"\n        result = self.copy()\n        result.round(digits)\n        return result", "title": ""}
{"_id": "d11652", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d11653", "text": "def bash(filename):\n    \"\"\"Runs a bash script in the local directory\"\"\"\n    sys.stdout.flush()\n    subprocess.call(\"bash {}\".format(filename), shell=True)", "title": ""}
{"_id": "d11654", "text": "def copy_user_agent_from_driver(self):\n        \"\"\" 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.\n        \"\"\"\n        selenium_user_agent = self.driver.execute_script(\"return navigator.userAgent;\")\n        self.headers.update({\"user-agent\": selenium_user_agent})", "title": ""}
{"_id": "d11655", "text": "def jupytext_cli(args=None):\n    \"\"\"Entry point for the jupytext script\"\"\"\n    try:\n        jupytext(args)\n    except (ValueError, TypeError, IOError) as err:\n        sys.stderr.write('[jupytext] Error: ' + str(err) + '\\n')\n        exit(1)", "title": ""}
{"_id": "d11656", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d11657", "text": "def __gzip(filename):\n\t\t\"\"\" Compress a file returning the new filename (.gz)\n\t\t\"\"\"\n\t\tzipname = filename + '.gz'\n\t\tfile_pointer = open(filename,'rb')\n\t\tzip_pointer = gzip.open(zipname,'wb')\n\t\tzip_pointer.writelines(file_pointer)\n\t\tfile_pointer.close()\n\t\tzip_pointer.close()\n\t\treturn zipname", "title": ""}
{"_id": "d11658", "text": "def reset_namespace(self):\n        \"\"\"Resets the namespace by removing all names defined by the user\"\"\"\n        self.shellwidget.reset_namespace(warning=self.reset_warning,\n                                         message=True)", "title": ""}
{"_id": "d11659", "text": "def write_str2file(pathname, astr):\n    \"\"\"writes a string to file\"\"\"\n    fname = pathname\n    fhandle = open(fname, 'wb')\n    fhandle.write(astr)\n    fhandle.close()", "title": ""}
{"_id": "d11660", "text": "def batchify(data, batch_size):\n    \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n    nbatch = data.shape[0] // batch_size\n    data = data[:nbatch * batch_size]\n    data = data.reshape((batch_size, nbatch)).T\n    return data", "title": ""}
{"_id": "d11661", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d11662", "text": "def scale_image(image, new_width):\n    \"\"\"Resizes an image preserving the aspect ratio.\n    \"\"\"\n    (original_width, original_height) = image.size\n    aspect_ratio = original_height/float(original_width)\n    new_height = int(aspect_ratio * new_width)\n\n    # This scales it wider than tall, since characters are biased\n    new_image = image.resize((new_width*2, new_height))\n    return new_image", "title": ""}
{"_id": "d11663", "text": "def input_yn(conf_mess):\n    \"\"\"Print Confirmation Message and Get Y/N response from user.\"\"\"\n    ui_erase_ln()\n    ui_print(conf_mess)\n    with term.cbreak():\n        input_flush()\n        val = input_by_key()\n    return bool(val.lower() == 'y')", "title": ""}
{"_id": "d11664", "text": "def scale_image(image, new_width):\n    \"\"\"Resizes an image preserving the aspect ratio.\n    \"\"\"\n    (original_width, original_height) = image.size\n    aspect_ratio = original_height/float(original_width)\n    new_height = int(aspect_ratio * new_width)\n\n    # This scales it wider than tall, since characters are biased\n    new_image = image.resize((new_width*2, new_height))\n    return new_image", "title": ""}
{"_id": "d11665", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d11666", "text": "def signal_handler(signal_name, frame):\n    \"\"\"Quit signal handler.\"\"\"\n    sys.stdout.flush()\n    print(\"\\nSIGINT in frame signal received. Quitting...\")\n    sys.stdout.flush()\n    sys.exit(0)", "title": ""}
{"_id": "d11667", "text": "def _read_group_h5(filename, groupname):\n    \"\"\"Return group content.\n\n    Args:\n        filename (:class:`pathlib.Path`): path of hdf5 file.\n        groupname (str): name of group to read.\n    Returns:\n        :class:`numpy.array`: content of group.\n    \"\"\"\n    with h5py.File(filename, 'r') as h5f:\n        data = h5f[groupname][()]\n    return data", "title": ""}
{"_id": "d11668", "text": "def _normal_prompt(self):\n        \"\"\"\n        Flushes the prompt before requesting the input\n\n        :return: The command line\n        \"\"\"\n        sys.stdout.write(self.__get_ps1())\n        sys.stdout.flush()\n        return safe_input()", "title": ""}
{"_id": "d11669", "text": "def normalized(vector):\n    \"\"\"\n    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.\n    \"\"\"\n    length = numpy.sum(vector * vector, axis=-1)\n    length = numpy.sqrt(length.reshape(length.shape + (1, )))\n    return vector / length", "title": ""}
{"_id": "d11670", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d11671", "text": "def ci(a, which=95, axis=None):\n    \"\"\"Return a percentile range from an array of values.\"\"\"\n    p = 50 - which / 2, 50 + which / 2\n    return percentiles(a, p, axis)", "title": ""}
{"_id": "d11672", "text": "def stats(self):\n        \"\"\"\n        Return a new raw REST interface to stats resources\n\n        :rtype: :py:class:`ns1.rest.stats.Stats`\n        \"\"\"\n        import ns1.rest.stats\n        return ns1.rest.stats.Stats(self.config)", "title": ""}
{"_id": "d11673", "text": "def _send_cmd(self, cmd):\n        \"\"\"Write command to remote process\n        \"\"\"\n        self._process.stdin.write(\"{}\\n\".format(cmd).encode(\"utf-8\"))\n        self._process.stdin.flush()", "title": ""}
{"_id": "d11674", "text": "def str_from_file(path):\n    \"\"\"\n    Return file contents as string.\n\n    \"\"\"\n    with open(path) as f:\n        s = f.read().strip()\n    return s", "title": ""}
{"_id": "d11675", "text": "def indent(txt, spacing=4):\n    \"\"\"\n    Indent given text using custom spacing, default is set to 4.\n    \"\"\"\n    return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))", "title": ""}
{"_id": "d11676", "text": "def growthfromrange(rangegrowth, startdate, enddate):\n    \"\"\"\n    Annual growth given growth from start date to end date.\n    \"\"\"\n    _yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\\\n            dt.timedelta(365.25).total_seconds()\n    return yrlygrowth(rangegrowth, _yrs)", "title": ""}
{"_id": "d11677", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d11678", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d11679", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d11680", "text": "def where_is(strings, pattern, n=1, lookup_func=re.match):\n    \"\"\"Return index of the nth match found of pattern in strings\n\n    Parameters\n    ----------\n    strings: list of str\n        List of strings\n\n    pattern: str\n        Pattern to be matched\n\n    nth: int\n        Number of times the match must happen to return the item index.\n\n    lookup_func: callable\n        Function to match each item in strings to the pattern, e.g., re.match or re.search.\n\n    Returns\n    -------\n    index: int\n        Index of the nth item that matches the pattern.\n        If there are no n matches will return -1\n    \"\"\"\n    count = 0\n    for idx, item in enumerate(strings):\n        if lookup_func(pattern, item):\n            count += 1\n            if count == n:\n                return idx\n    return -1", "title": ""}
{"_id": "d11681", "text": "def end_index(self):\n        \"\"\"\n        Returns the 1-based index of the last object on this page,\n        relative to total objects found (hits).\n        \"\"\"\n        return ((self.number - 1) * self.paginator.per_page +\n            len(self.object_list))", "title": ""}
{"_id": "d11682", "text": "def show(self, title=''):\n        \"\"\"\n        Display Bloch sphere and corresponding data sets.\n        \"\"\"\n        self.render(title=title)\n        if self.fig:\n            plt.show(self.fig)", "title": ""}
{"_id": "d11683", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d11684", "text": "def show(self, title=''):\n        \"\"\"\n        Display Bloch sphere and corresponding data sets.\n        \"\"\"\n        self.render(title=title)\n        if self.fig:\n            plt.show(self.fig)", "title": ""}
{"_id": "d11685", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d11686", "text": "def estimate_complexity(self, x,y,z,n):\n        \"\"\" \n        calculates a rough guess of runtime based on product of parameters \n        \"\"\"\n        num_calculations = x * y * z * n\n        run_time = num_calculations / 100000  # a 2014 PC does about 100k calcs in a second (guess based on prior logs)\n        return self.show_time_as_short_string(run_time)", "title": ""}
{"_id": "d11687", "text": "def _interval_to_bound_points(array):\n    \"\"\"\n    Helper function which returns an array\n    with the Intervals' boundaries.\n    \"\"\"\n\n    array_boundaries = np.array([x.left for x in array])\n    array_boundaries = np.concatenate(\n        (array_boundaries, np.array([array[-1].right])))\n\n    return array_boundaries", "title": ""}
{"_id": "d11688", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d11689", "text": "def __reversed__(self):\n        \"\"\"\n        Return a reversed iterable over the items in the dictionary. Items are\n        iterated over in their reverse sort order.\n\n        Iterating views while adding or deleting entries in the dictionary may\n        raise a RuntimeError or fail to iterate over all entries.\n        \"\"\"\n        _dict = self._dict\n        return iter((key, _dict[key]) for key in reversed(self._list))", "title": ""}
{"_id": "d11690", "text": "def norm_vec(vector):\n    \"\"\"Normalize the length of a vector to one\"\"\"\n    assert len(vector) == 3\n    v = np.array(vector)\n    return v/np.sqrt(np.sum(v**2))", "title": ""}
{"_id": "d11691", "text": "def rewindbody(self):\n        \"\"\"Rewind the file to the start of the body (if seekable).\"\"\"\n        if not self.seekable:\n            raise IOError, \"unseekable file\"\n        self.fp.seek(self.startofbody)", "title": ""}
{"_id": "d11692", "text": "def R_rot_3d(th):\n    \"\"\"Return a 3-dimensional rotation matrix.\n\n    Parameters\n    ----------\n    th: array, shape (n, 3)\n        Angles about which to rotate along each axis.\n\n    Returns\n    -------\n    R: array, shape (n, 3, 3)\n    \"\"\"\n    sx, sy, sz = np.sin(th).T\n    cx, cy, cz = np.cos(th).T\n    R = np.empty((len(th), 3, 3), dtype=np.float)\n\n    R[:, 0, 0] = cy * cz\n    R[:, 0, 1] = -cy * sz\n    R[:, 0, 2] = sy\n\n    R[:, 1, 0] = sx * sy * cz + cx * sz\n    R[:, 1, 1] = -sx * sy * sz + cx * cz\n    R[:, 1, 2] = -sx * cy\n\n    R[:, 2, 0] = -cx * sy * cz + sx * sz\n    R[:, 2, 1] = cx * sy * sz + sx * cz\n    R[:, 2, 2] = cx * cy\n    return R", "title": ""}
{"_id": "d11693", "text": "def Slice(a, begin, size):\n    \"\"\"\n    Slicing op.\n    \"\"\"\n    return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],", "title": ""}
{"_id": "d11694", "text": "def from_rotation_vector(rot):\n    \"\"\"Convert input 3-vector in axis-angle representation to unit quaternion\n\n    Parameters\n    ----------\n    rot: (Nx3) float array\n        Each vector represents the axis of the rotation, with norm\n        proportional to the angle of the rotation in radians.\n\n    Returns\n    -------\n    q: array of quaternions\n        Unit quaternions resulting in rotations corresponding to input\n        rotations.  Output shape is rot.shape[:-1].\n\n    \"\"\"\n    rot = np.array(rot, copy=False)\n    quats = np.zeros(rot.shape[:-1]+(4,))\n    quats[..., 1:] = rot[...]/2\n    quats = as_quat_array(quats)\n    return np.exp(quats)", "title": ""}
{"_id": "d11695", "text": "def unsort_vector(data, indices_of_increasing):\n    \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n    return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])", "title": ""}
{"_id": "d11696", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d11697", "text": "def sort_data(data, cols):\n    \"\"\"Sort `data` rows and order columns\"\"\"\n    return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "title": ""}
{"_id": "d11698", "text": "def rq_job(self):\n        \"\"\"The last RQ Job this ran on\"\"\"\n        if not self.rq_id or not self.rq_origin:\n            return\n        try:\n            return RQJob.fetch(self.rq_id, connection=get_connection(self.rq_origin))\n        except NoSuchJobError:\n            return", "title": ""}
{"_id": "d11699", "text": "def transcript_sort_key(transcript):\n    \"\"\"\n    Key function used to sort transcripts. Taking the negative of\n    protein sequence length and nucleotide sequence length so that\n    the transcripts with longest sequences come first in the list. This couldn't\n    be accomplished with `reverse=True` since we're also sorting by\n    transcript name (which places TP53-001 before TP53-002).\n    \"\"\"\n    return (\n        -len(transcript.protein_sequence),\n        -len(transcript.sequence),\n        transcript.name\n    )", "title": ""}
{"_id": "d11700", "text": "def execute_in_background(self):\n        \"\"\"Executes a (shell) command in the background\n\n        :return: the process' pid\n        \"\"\"\n        # http://stackoverflow.com/questions/1605520\n        args = shlex.split(self.cmd)\n        p = Popen(args)\n        return p.pid", "title": ""}
{"_id": "d11701", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d11702", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d11703", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d11704", "text": "def normalize_path(filename):\n    \"\"\"Normalize a file/dir name for comparison purposes\"\"\"\n    return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))", "title": ""}
{"_id": "d11705", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d11706", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d11707", "text": "def _config_win32_domain(self, domain):\n        \"\"\"Configure a Domain registry entry.\"\"\"\n        # we call str() on domain to convert it from unicode to ascii\n        self.domain = dns.name.from_text(str(domain))", "title": ""}
{"_id": "d11708", "text": "def _array2cstr(arr):\n    \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())", "title": ""}
{"_id": "d11709", "text": "def first(series, order_by=None):\n    \"\"\"\n    Returns the first value of a series.\n\n    Args:\n        series (pandas.Series): column to summarize.\n\n    Kwargs:\n        order_by: a pandas.Series or list of series (can be symbolic) to order\n            the input series by before summarization.\n    \"\"\"\n\n    if order_by is not None:\n        series = order_series_by(series, order_by)\n    first_s = series.iloc[0]\n    return first_s", "title": ""}
{"_id": "d11710", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d11711", "text": "def set_sig_figs(n=4):\n    \"\"\"Set the number of significant figures used to print Pint, Pandas, and\n    NumPy quantities.\n\n    Args:\n        n (int): Number of significant figures to display.\n    \"\"\"\n    u.default_format = '.' + str(n) + 'g'\n    pd.options.display.float_format = ('{:,.' + str(n) + '}').format", "title": ""}
{"_id": "d11712", "text": "def save_keras_definition(keras_model, path):\n    \"\"\"\n    Save a Keras model definition to JSON with given path\n    \"\"\"\n    model_json = keras_model.to_json()\n    with open(path, \"w\") as json_file:\n        json_file.write(model_json)", "title": ""}
{"_id": "d11713", "text": "def get_kind(self, value):\n        \"\"\"Return the kind (type) of the attribute\"\"\"\n        if isinstance(value, float):\n            return 'f'\n        elif isinstance(value, int):\n            return 'i'\n        else:\n            raise ValueError(\"Only integer or floating point values can be stored.\")", "title": ""}
{"_id": "d11714", "text": "def get_local_image(self, src):\n        \"\"\"\\\n        returns the bytes of the image file on disk\n        \"\"\"\n        return ImageUtils.store_image(self.fetcher, self.article.link_hash, src, self.config)", "title": ""}
{"_id": "d11715", "text": "def incidence(boundary):\n    \"\"\"\n    given an Nxm matrix containing boundary info between simplices,\n    compute indidence info matrix\n    not very reusable; should probably not be in this lib\n    \"\"\"\n    return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1])", "title": ""}
{"_id": "d11716", "text": "def set_scale(self, scale, no_reset=False):\n        \"\"\"Scale the image in a channel.\n        Also see :meth:`zoom_to`.\n\n        Parameters\n        ----------\n        scale : tuple of float\n            Scaling factors for the image in the X and Y axes.\n\n        no_reset : bool\n            Do not reset ``autozoom`` setting.\n\n        \"\"\"\n        return self.scale_to(*scale[:2], no_reset=no_reset)", "title": ""}
{"_id": "d11717", "text": "def _chunks(l, n):\n    \"\"\" Yield successive n-sized chunks from l.\n\n    http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python\n    \"\"\"\n    for i in xrange(0, len(l), n):\n        yield l[i:i+n]", "title": ""}
{"_id": "d11718", "text": "def linregress(x, y, return_stats=False):\n    \"\"\"linear regression calculation\n\n    Parameters\n    ----\n    x :         independent variable (series)\n    y :         dependent variable (series)\n    return_stats : returns statistical values as well if required (bool)\n    \n\n    Returns\n    ----\n    list of parameters (and statistics)\n    \"\"\"\n    a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y)\n\n    retval = a1, a0\n    if return_stats:\n        retval += r_value, p_value, stderr\n\n    return retval", "title": ""}
{"_id": "d11719", "text": "def run_hive_script(script):\n    \"\"\"\n    Runs the contents of the given script in hive and returns stdout.\n    \"\"\"\n    if not os.path.isfile(script):\n        raise RuntimeError(\"Hive script: {0} does not exist.\".format(script))\n    return run_hive(['-f', script])", "title": ""}
{"_id": "d11720", "text": "def stop_button_click_handler(self):\n        \"\"\"Method to handle what to do when the stop button is pressed\"\"\"\n        self.stop_button.setDisabled(True)\n        # Interrupt computations or stop debugging\n        if not self.shellwidget._reading:\n            self.interrupt_kernel()\n        else:\n            self.shellwidget.write_to_stdin('exit')", "title": ""}
{"_id": "d11721", "text": "def load_db(file, db, verbose=True):\n    \"\"\"\n    Load :class:`mongomock.database.Database` from a local file.\n\n    :param file: file path.\n    :param db: instance of :class:`mongomock.database.Database`.\n    :param verbose: bool, toggle on log.\n    :return: loaded db.\n    \"\"\"\n    db_data = json.load(file, verbose=verbose)\n    return _load(db_data, db)", "title": ""}
{"_id": "d11722", "text": "def stop(self, reason=None):\n        \"\"\"Shutdown the service with a reason.\"\"\"\n        self.logger.info('stopping')\n        self.loop.stop(pyev.EVBREAK_ALL)", "title": ""}
{"_id": "d11723", "text": "def _write_pidfile(pidfile):\n    \"\"\" Write file with current process ID.\n    \"\"\"\n    pid = str(os.getpid())\n    handle = open(pidfile, 'w')\n    try:\n        handle.write(\"%s\\n\" % pid)\n    finally:\n        handle.close()", "title": ""}
{"_id": "d11724", "text": "def on_error(e):  # pragma: no cover\n    \"\"\"Error handler\n\n    RuntimeError or ValueError exceptions raised by commands will be handled\n    by this function.\n    \"\"\"\n    exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'}\n    sys.stderr.write('{}: {}\\n'.format(exname[e.__class__.__name__], str(e)))\n    sys.stderr.write('See file slam_error.log for additional details.\\n')\n    sys.exit(1)", "title": ""}
{"_id": "d11725", "text": "def _write_pidfile(pidfile):\n    \"\"\" Write file with current process ID.\n    \"\"\"\n    pid = str(os.getpid())\n    handle = open(pidfile, 'w')\n    try:\n        handle.write(\"%s\\n\" % pid)\n    finally:\n        handle.close()", "title": ""}
{"_id": "d11726", "text": "def dump_to_log(self, logger):\n        \"\"\"Send the cmd info and collected stdout to logger.\"\"\"\n        logger.error(\"Execution ended in %s for cmd %s\", self._retcode, self._cmd)\n        for line in self._collected_stdout:\n            logger.error(STDOUT_LOG_PREFIX + line)", "title": ""}
{"_id": "d11727", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d11728", "text": "def readCommaList(fileList):\n    \"\"\" Return a list of the files with the commas removed. \"\"\"\n    names=fileList.split(',')\n    fileList=[]\n    for item in names:\n        fileList.append(item)\n    return fileList", "title": ""}
{"_id": "d11729", "text": "def find_largest_contig(contig_lengths_dict):\n    \"\"\"\n    Determine the largest contig for each strain\n    :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n    :return: longest_contig_dict: dictionary of strain name: longest contig\n    \"\"\"\n    # Initialise the dictionary\n    longest_contig_dict = dict()\n    for file_name, contig_lengths in contig_lengths_dict.items():\n        # As the list is sorted in descending order, the largest contig is the first entry in the list\n        longest_contig_dict[file_name] = contig_lengths[0]\n    return longest_contig_dict", "title": ""}
{"_id": "d11730", "text": "def get_stripped_file_lines(filename):\n    \"\"\"\n    Return lines of a file with whitespace removed\n    \"\"\"\n    try:\n        lines = open(filename).readlines()\n    except FileNotFoundError:\n        fatal(\"Could not open file: {!r}\".format(filename))\n\n    return [line.strip() for line in lines]", "title": ""}
{"_id": "d11731", "text": "def random_choice(sequence):\n    \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n    return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)", "title": ""}
{"_id": "d11732", "text": "def lowstrip(term):\n    \"\"\"Convert to lowercase and strip spaces\"\"\"\n    term = re.sub('\\s+', ' ', term)\n    term = term.lower()\n    return term", "title": ""}
{"_id": "d11733", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d11734", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d11735", "text": "def get_last(self, table=None):\n        \"\"\"Just the last entry.\"\"\"\n        if table is None: table = self.main_table\n        query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n        return self.own_cursor.execute(query).fetchone()", "title": ""}
{"_id": "d11736", "text": "def to_snake_case(name):\n    \"\"\" Given a name in camelCase return in snake_case \"\"\"\n    s1 = FIRST_CAP_REGEX.sub(r'\\1_\\2', name)\n    return ALL_CAP_REGEX.sub(r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d11737", "text": "def camelcase_underscore(name):\n    \"\"\" Convert camelcase names to underscore \"\"\"\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()", "title": ""}
{"_id": "d11738", "text": "def translate_fourier(image, dx):\n    \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n    N = image.shape[0]\n\n    f = 2*np.pi*np.fft.fftfreq(N)\n    kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n    kv = np.array([kx,ky,kz]).T\n\n    q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n    return np.real(np.fft.ifftn(q))", "title": ""}
{"_id": "d11739", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d11740", "text": "def import_path(self):\n    \"\"\"The full remote import path as used in import statements in `.go` source files.\"\"\"\n    return os.path.join(self.remote_root, self.pkg) if self.pkg else self.remote_root", "title": ""}
{"_id": "d11741", "text": "def is_serializable(obj):\n    \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool\n    \"\"\"\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')", "title": ""}
{"_id": "d11742", "text": "def stringToDate(fmt=\"%Y-%m-%d\"):\n    \"\"\"returns a function to convert a string to a datetime.date instance\n    using the formatting string fmt as in time.strftime\"\"\"\n    import time\n    import datetime\n    def conv_func(s):\n        return datetime.date(*time.strptime(s,fmt)[:3])\n    return conv_func", "title": ""}
{"_id": "d11743", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d11744", "text": "def get_own_ip():\n    \"\"\"Get the host's ip number.\n    \"\"\"\n    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    try:\n        sock.connect((\"8.8.8.8\", 80))\n    except socket.gaierror:\n        ip_ = \"127.0.0.1\"\n    else:\n        ip_ = sock.getsockname()[0]\n    finally:\n        sock.close()\n    return ip_", "title": ""}
{"_id": "d11745", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d11746", "text": "def set_file_mtime(path, mtime, atime=None):\n  \"\"\"Set access and modification times on a file.\"\"\"\n  if not atime:\n    atime = mtime\n  f = open(path, 'a')\n  try:\n    os.utime(path, (atime, mtime))\n  finally:\n    f.close()", "title": ""}
{"_id": "d11747", "text": "def print_verbose(*args, **kwargs):\n    \"\"\"Utility to print something only if verbose=True is given\n    \"\"\"\n    if kwargs.pop('verbose', False) is True:\n        gprint(*args, **kwargs)", "title": ""}
{"_id": "d11748", "text": "def clean_colnames(df):\n    \"\"\" Cleans the column names on a DataFrame\n    Parameters:\n    df - DataFrame\n        The DataFrame to clean\n    \"\"\"\n    col_list = []\n    for index in range(_dutils.cols(df)):\n        col_list.append(df.columns[index].strip().lower().replace(' ','_'))\n    df.columns = col_list", "title": ""}
{"_id": "d11749", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d11750", "text": "def get(key, default=None):\n    \"\"\" return the key from the request\n    \"\"\"\n    data = get_form() or get_query_string()\n    return data.get(key, default)", "title": ""}
{"_id": "d11751", "text": "def trapz2(f, x=None, y=None, dx=1.0, dy=1.0):\n    \"\"\"Double integrate.\"\"\"\n    return numpy.trapz(numpy.trapz(f, x=y, dx=dy), x=x, dx=dx)", "title": ""}
{"_id": "d11752", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d11753", "text": "def transpose(table):\n    \"\"\"\n    transpose matrix\n    \"\"\"\n    t = []\n    for i in range(0, len(table[0])):\n        t.append([row[i] for row in table])\n    return t", "title": ""}
{"_id": "d11754", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d11755", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d11756", "text": "def set_attr(self, name, value):\n    \"\"\" Sets the value of an attribute. \"\"\"\n    self.exec_script(\"node.setAttribute(%s, %s)\" % (repr(name), repr(value)))", "title": ""}
{"_id": "d11757", "text": "def match_aspect_to_viewport(self):\n        \"\"\"Updates Camera.aspect to match the viewport's aspect ratio.\"\"\"\n        viewport = self.viewport\n        self.aspect = float(viewport.width) / viewport.height", "title": ""}
{"_id": "d11758", "text": "def _set_tab_width(self, tab_width):\n        \"\"\" Sets the width (in terms of space characters) for tab characters.\n        \"\"\"\n        font_metrics = QtGui.QFontMetrics(self.font)\n        self._control.setTabStopWidth(tab_width * font_metrics.width(' '))\n\n        self._tab_width = tab_width", "title": ""}
{"_id": "d11759", "text": "def split_elements(value):\n    \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n    l = [v.strip() for v in value.split(',')]\n    if len(l) == 1:\n        l = value.split()\n    return l", "title": ""}
{"_id": "d11760", "text": "def main(argv, version=DEFAULT_VERSION):\n    \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n    tarball = download_setuptools()\n    _install(tarball, _build_install_args(argv))", "title": ""}
{"_id": "d11761", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d11762", "text": "def get_shape_mask(self, shape_obj):\n        \"\"\"\n        Return full mask where True marks pixels within the given shape.\n        \"\"\"\n        wd, ht = self.get_size()\n        yi = np.mgrid[:ht].reshape(-1, 1)\n        xi = np.mgrid[:wd].reshape(1, -1)\n        pts = np.asarray((xi, yi)).T\n        contains = shape_obj.contains_pts(pts)\n        return contains", "title": ""}
{"_id": "d11763", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d11764", "text": "def move(self, x, y):\n        \"\"\"Move the virtual cursor.\n\n        Args:\n            x (int): x-coordinate to place the cursor.\n            y (int): y-coordinate to place the cursor.\n\n        .. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`\n        \"\"\"\n        self._cursor = self._normalizePoint(x, y)", "title": ""}
{"_id": "d11765", "text": "def parse_datetime(dt_str):\n    \"\"\"Parse datetime.\"\"\"\n    date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n    dt_str = dt_str.replace(\"Z\", \" +0000\")\n    return datetime.datetime.strptime(dt_str, date_format)", "title": ""}
{"_id": "d11766", "text": "def now_time(str=False):\n    \"\"\"Get the current time.\"\"\"\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()", "title": ""}
{"_id": "d11767", "text": "def _listify(collection):\n        \"\"\"This is a workaround where Collections are no longer iterable\n        when using JPype.\"\"\"\n        new_list = []\n        for index in range(len(collection)):\n            new_list.append(collection[index])\n        return new_list", "title": ""}
{"_id": "d11768", "text": "def Softsign(a):\n    \"\"\"\n    Softsign op.\n    \"\"\"\n    return np.divide(a, np.add(np.abs(a), 1)),", "title": ""}
{"_id": "d11769", "text": "def coerce(self, value):\n        \"\"\"Convert from whatever is given to a list of scalars for the lookup_field.\"\"\"\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]", "title": ""}
{"_id": "d11770", "text": "def bin_to_int(string):\n    \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n    if isinstance(string, str):\n        return struct.unpack(\"b\", string)[0]\n    else:\n        return struct.unpack(\"b\", bytes([string]))[0]", "title": ""}
{"_id": "d11771", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d11772", "text": "def _expand(self, str, local_vars={}):\n        \"\"\"Expand $vars in a string.\"\"\"\n        return ninja_syntax.expand(str, self.vars, local_vars)", "title": ""}
{"_id": "d11773", "text": "def _unzip_handle(handle):\n    \"\"\"Transparently unzip the file handle\"\"\"\n    if isinstance(handle, basestring):\n        handle = _gzip_open_filename(handle)\n    else:\n        handle = _gzip_open_handle(handle)\n    return handle", "title": ""}
{"_id": "d11774", "text": "def _synced(method, self, args, kwargs):\n    \"\"\"Underlying synchronized wrapper.\"\"\"\n    with self._lock:\n        return method(*args, **kwargs)", "title": ""}
{"_id": "d11775", "text": "def string_input(prompt=''):\n    \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n    v = sys.version[0]\n    if v == '3':\n        return input(prompt)\n    else:\n        return raw_input(prompt)", "title": ""}
{"_id": "d11776", "text": "def singleton_per_scope(_cls, _scope=None, _renew=False, *args, **kwargs):\n    \"\"\"Instanciate a singleton per scope.\"\"\"\n\n    result = None\n\n    singletons = SINGLETONS_PER_SCOPES.setdefault(_scope, {})\n\n    if _renew or _cls not in singletons:\n        singletons[_cls] = _cls(*args, **kwargs)\n\n    result = singletons[_cls]\n\n    return result", "title": ""}
{"_id": "d11777", "text": "def connected_socket(address, timeout=3):\n    \"\"\" yields a connected socket \"\"\"\n    sock = socket.create_connection(address, timeout)\n    yield sock\n    sock.close()", "title": ""}
{"_id": "d11778", "text": "def ignore_comments(iterator):\n    \"\"\"\n    Strips and filters empty or commented lines.\n    \"\"\"\n    for line in iterator:\n        line = COMMENT_RE.sub('', line)\n        line = line.strip()\n        if line:\n            yield line", "title": ""}
{"_id": "d11779", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d11780", "text": "def filter_useless_pass(source):\n    \"\"\"Yield code with useless \"pass\" lines removed.\"\"\"\n    try:\n        marked_lines = frozenset(useless_pass_line_numbers(source))\n    except (SyntaxError, tokenize.TokenError):\n        marked_lines = frozenset()\n\n    sio = io.StringIO(source)\n    for line_number, line in enumerate(sio.readlines(), start=1):\n        if line_number not in marked_lines:\n            yield line", "title": ""}
{"_id": "d11781", "text": "def wordfreq(text, is_filename=False):\n    \"\"\"Return a dictionary of words and word counts in a string.\"\"\"\n    if is_filename:\n        with open(text) as f:\n            text = f.read()\n    freqs = {}\n    for word in text.split():\n        lword = word.lower()\n        freqs[lword] = freqs.get(lword, 0) + 1\n    return freqs", "title": ""}
{"_id": "d11782", "text": "def cric__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n    model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)\n\n    # we want to explain the raw probability outputs of the trees\n    model.predict = lambda X: model.predict_proba(X)[:,1]\n    \n    return model", "title": ""}
{"_id": "d11783", "text": "def copy_and_update(dictionary, update):\n    \"\"\"Returns an updated copy of the dictionary without modifying the original\"\"\"\n    newdict = dictionary.copy()\n    newdict.update(update)\n    return newdict", "title": ""}
{"_id": "d11784", "text": "def generic_div(a, b):\n    \"\"\"Simple function to divide two numbers\"\"\"\n    logger.debug('Called generic_div({}, {})'.format(a, b))\n    return a / b", "title": ""}
{"_id": "d11785", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d11786", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d11787", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d11788", "text": "def SegmentMax(a, ids):\n    \"\"\"\n    Segmented max op.\n    \"\"\"\n    func = lambda idxs: np.amax(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d11789", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d11790", "text": "def ratio_and_percentage(current, total, time_remaining):\n    \"\"\"Returns the progress ratio and percentage.\"\"\"\n    return \"{} / {} ({}% completed)\".format(current, total, int(current / total * 100))", "title": ""}
{"_id": "d11791", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d11792", "text": "def include_raw_constructor(self, loader, node):\n        \"\"\"\n        Called when PyYaml encounters '!include-raw'\n        \"\"\"\n\n        path = convert_path(node.value)\n\n        with open(path, 'r') as f:\n            config = f.read()\n\n            config = self.inject_include_info(path, config, include_type='include-raw')\n\n            self.add_file(path, config)\n\n            return config", "title": ""}
{"_id": "d11793", "text": "def sort_data(data, cols):\n    \"\"\"Sort `data` rows and order columns\"\"\"\n    return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "title": ""}
{"_id": "d11794", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d11795", "text": "def _sort_lambda(sortedby='cpu_percent',\n                 sortedby_secondary='memory_percent'):\n    \"\"\"Return a sort lambda function for the sortedbykey\"\"\"\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", "title": ""}
{"_id": "d11796", "text": "def gaussian_variogram_model(m, d):\n    \"\"\"Gaussian model, m is [psill, range, nugget]\"\"\"\n    psill = float(m[0])\n    range_ = float(m[1])\n    nugget = float(m[2])\n    return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget", "title": ""}
{"_id": "d11797", "text": "def safe_unicode(string):\n    \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n    if not PY3:\n        uni = string.replace(u'\\u2019', \"'\")\n        return uni.encode('utf-8')\n        \n    return string", "title": ""}
{"_id": "d11798", "text": "def get_attr(self, method_name):\n        \"\"\"Get attribute from the target object\"\"\"\n        return self.attrs.get(method_name) or self.get_callable_attr(method_name)", "title": ""}
{"_id": "d11799", "text": "def _set_module_names_for_sphinx(modules: List, new_name: str):\n    \"\"\" Trick sphinx into displaying the desired module in these objects' documentation. \"\"\"\n    for obj in modules:\n        obj.__module__ = new_name", "title": ""}
{"_id": "d11800", "text": "def makedirs(path, mode=0o777, exist_ok=False):\n    \"\"\"A wrapper of os.makedirs().\"\"\"\n    os.makedirs(path, mode, exist_ok)", "title": ""}
{"_id": "d11801", "text": "def read_sphinx_environment(pth):\n    \"\"\"Read the sphinx environment.pickle file at path `pth`.\"\"\"\n\n    with open(pth, 'rb') as fo:\n        env = pickle.load(fo)\n    return env", "title": ""}
{"_id": "d11802", "text": "def __call__(self, xy):\n        \"\"\"Project x and y\"\"\"\n        x, y = xy\n        return (self.x(x), self.y(y))", "title": ""}
{"_id": "d11803", "text": "def _set_module_names_for_sphinx(modules: List, new_name: str):\n    \"\"\" Trick sphinx into displaying the desired module in these objects' documentation. \"\"\"\n    for obj in modules:\n        obj.__module__ = new_name", "title": ""}
{"_id": "d11804", "text": "def send(self, *args, **kwargs):\n        \"\"\"Writes the passed chunk and flushes it to the client.\"\"\"\n        self.write(*args, **kwargs)\n        self.flush()", "title": ""}
{"_id": "d11805", "text": "def set_value(self, value):\n        \"\"\"Set value of the checkbox.\n\n        Parameters\n        ----------\n        value : bool\n            value for the checkbox\n\n        \"\"\"\n        if value:\n            self.setCheckState(Qt.Checked)\n        else:\n            self.setCheckState(Qt.Unchecked)", "title": ""}
{"_id": "d11806", "text": "def parsePoint(line):\n    \"\"\"\n    Parse a line of text into an MLlib LabeledPoint object.\n    \"\"\"\n    values = [float(s) for s in line.split(' ')]\n    if values[0] == -1:   # Convert -1 labels to 0 for MLlib\n        values[0] = 0\n    return LabeledPoint(values[0], values[1:])", "title": ""}
{"_id": "d11807", "text": "def chunked(l, n):\n    \"\"\"Chunk one big list into few small lists.\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d11808", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d11809", "text": "def chunks(arr, size):\n    \"\"\"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`\n    \"\"\"\n    for i in _range(0, len(arr), size):\n        yield arr[i:i+size]", "title": ""}
{"_id": "d11810", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d11811", "text": "def group(data, num):\n    \"\"\" Split data into chunks of num chars each \"\"\"\n    return [data[i:i+num] for i in range(0, len(data), num)]", "title": ""}
{"_id": "d11812", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d11813", "text": "def schunk(string, size):\n    \"\"\"Splits string into n sized chunks.\"\"\"\n    return [string[i:i+size] for i in range(0, len(string), size)]", "title": ""}
{"_id": "d11814", "text": "def type_converter(text):\n    \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n    if text.isdigit():\n        return int(text), int\n\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE", "title": ""}
{"_id": "d11815", "text": "def split_len(s, length):\n    \"\"\"split string *s* into list of strings no longer than *length*\"\"\"\n    return [s[i:i+length] for i in range(0, len(s), length)]", "title": ""}
{"_id": "d11816", "text": "def set_json_item(key, value):\n    \"\"\" manipulate json data on the fly\n    \"\"\"\n    data = get_json()\n    data[key] = value\n\n    request = get_request()\n    request[\"BODY\"] = json.dumps(data)", "title": ""}
{"_id": "d11817", "text": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "title": ""}
{"_id": "d11818", "text": "def _write_json(file, contents):\n    \"\"\"Write a dict to a JSON file.\"\"\"\n    with open(file, 'w') as f:\n        return json.dump(contents, f, indent=2, sort_keys=True)", "title": ""}
{"_id": "d11819", "text": "def _file_chunks(self, data, chunk_size):\n        \"\"\" Yield compressed chunks from a data array\"\"\"\n        for i in xrange(0, len(data), chunk_size):\n            yield self.compressor(data[i:i+chunk_size])", "title": ""}
{"_id": "d11820", "text": "def save_excel(self, fd):\n        \"\"\" Saves the case as an Excel spreadsheet.\n        \"\"\"\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)", "title": ""}
{"_id": "d11821", "text": "def filter_query(s):\n    \"\"\"\n    Filters given query with the below regex\n    and returns lists of quoted and unquoted strings\n    \"\"\"\n    matches = re.findall(r'(?:\"([^\"]*)\")|([^\"]*)', s)\n    result_quoted = [t[0].strip() for t in matches if t[0]]\n    result_unquoted = [t[1].strip() for t in matches if t[1]]\n    return result_quoted, result_unquoted", "title": ""}
{"_id": "d11822", "text": "def stdoutwriteline(*args):\n    \"\"\"\n    @type args: tuple\n    @return: None\n    \"\"\"\n    s = \"\"\n\n    for i in args:\n        s += str(i) + \" \"\n\n    s = s.strip()\n    sys.stdout.write(str(s) + \"\\n\")\n    sys.stdout.flush()\n\n    return s", "title": ""}
{"_id": "d11823", "text": "def update(table, values, where=(), **kwargs):\n    \"\"\"Convenience wrapper for database UPDATE.\"\"\"\n    where = dict(where, **kwargs).items()\n    sql, args = makeSQL(\"UPDATE\", table, values=values, where=where)\n    return execute(sql, args).rowcount", "title": ""}
{"_id": "d11824", "text": "def unzip_file_to_dir(path_to_zip, output_directory):\n    \"\"\"\n    Extract a ZIP archive to a directory\n    \"\"\"\n    z = ZipFile(path_to_zip, 'r')\n    z.extractall(output_directory)\n    z.close()", "title": ""}
{"_id": "d11825", "text": "def bulk_query(self, query, *multiparams):\n        \"\"\"Bulk insert or update.\"\"\"\n\n        with self.get_connection() as conn:\n            conn.bulk_query(query, *multiparams)", "title": ""}
{"_id": "d11826", "text": "def counter(items):\n    \"\"\"\n    Simplest required implementation of collections.Counter. Required as 2.6\n    does not have Counter in collections.\n    \"\"\"\n    results = {}\n    for item in items:\n        results[item] = results.get(item, 0) + 1\n    return results", "title": ""}
{"_id": "d11827", "text": "def dict_keys_without_hyphens(a_dict):\n    \"\"\"Return the a new dict with underscores instead of hyphens in keys.\"\"\"\n    return dict(\n        (key.replace('-', '_'), val) for key, val in a_dict.items())", "title": ""}
{"_id": "d11828", "text": "def to_dict(self):\n        \"\"\"Serialize representation of the table for local caching.\"\"\"\n        return {'schema': self.schema, 'name': self.name, 'columns': [col.to_dict() for col in self._columns],\n                'foreign_keys': self.foreign_keys.to_dict(), 'ref_keys': self.ref_keys.to_dict()}", "title": ""}
{"_id": "d11829", "text": "def get_least_distinct_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):\n    \"\"\"\n    Order the words from `vocab` by \"distinctiveness score\" (Chuang et al. 2012) from least to most distinctive.\n    Optionally only return the `n` least distinctive words.\n\n    J. Chuang, C. Manning, J. Heer 2012: \"Termite: Visualization Techniques for Assessing Textual Topic Models\"\n    \"\"\"\n    return _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n,\n                                           least_to_most=True)", "title": ""}
{"_id": "d11830", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d11831", "text": "def delete(self, key_name):\n        \"\"\"Delete the key and return true if the key was deleted, else false\n        \"\"\"\n        self.db.remove(Query().name == key_name)\n        return self.get(key_name) == {}", "title": ""}
{"_id": "d11832", "text": "def teardown(self):\n        \"\"\"Cleanup cache tables.\"\"\"\n        for table_spec in reversed(self._table_specs):\n            with self._conn:\n                table_spec.teardown(self._conn)", "title": ""}
{"_id": "d11833", "text": "def is_string(obj):\n    \"\"\"Is this a string.\n\n    :param object obj:\n    :rtype: bool\n    \"\"\"\n    if PYTHON3:\n        str_type = (bytes, str)\n    else:\n        str_type = (bytes, str, unicode)\n    return isinstance(obj, str_type)", "title": ""}
{"_id": "d11834", "text": "def sqliteRowsToDicts(sqliteRows):\n    \"\"\"\n    Unpacks sqlite rows as returned by fetchall\n    into an array of simple dicts.\n\n    :param sqliteRows: array of rows returned from fetchall DB call\n    :return:  array of dicts, keyed by the column names.\n    \"\"\"\n    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "title": ""}
{"_id": "d11835", "text": "def show_intro(self):\n        \"\"\"Show intro to IPython help\"\"\"\n        from IPython.core.usage import interactive_usage\n        self.main.help.show_rich_text(interactive_usage)", "title": ""}
{"_id": "d11836", "text": "def sqliteRowsToDicts(sqliteRows):\n    \"\"\"\n    Unpacks sqlite rows as returned by fetchall\n    into an array of simple dicts.\n\n    :param sqliteRows: array of rows returned from fetchall DB call\n    :return:  array of dicts, keyed by the column names.\n    \"\"\"\n    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "title": ""}
{"_id": "d11837", "text": "def denorm(self,arr):\n        \"\"\"Reverse the normalization done to a batch of images.\n\n        Arguments:\n            arr: of shape/size (N,3,sz,sz)\n        \"\"\"\n        if type(arr) is not np.ndarray: arr = to_np(arr)\n        if len(arr.shape)==3: arr = arr[None]\n        return self.transform.denorm(np.rollaxis(arr,1,4))", "title": ""}
{"_id": "d11838", "text": "def flatten(lis):\n    \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n    new_lis = []\n    for item in lis:\n        if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n            new_lis.extend(flatten(item))\n        else:\n            new_lis.append(item)\n    return new_lis", "title": ""}
{"_id": "d11839", "text": "def downsample_with_striding(array, factor):\n    \"\"\"Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x.\n    \"\"\"\n    return array[tuple(np.s_[::f] for f in factor)]", "title": ""}
{"_id": "d11840", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d11841", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d11842", "text": "def is_array(self, key):\n        \"\"\"Return True if variable is a numpy array\"\"\"\n        data = self.model.get_data()\n        return isinstance(data[key], (ndarray, MaskedArray))", "title": ""}
{"_id": "d11843", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d11844", "text": "def find_all(self, string, callback):\n\t\t\"\"\"\n\t\tWrapper on iter method, callback gets an iterator result\n\t\t\"\"\"\n\t\tfor index, output in self.iter(string):\n\t\t\tcallback(index, output)", "title": ""}
{"_id": "d11845", "text": "def stop(self):\n        \"\"\"Stop the resolver threads.\n        \"\"\"\n        with self.lock:\n            for dummy in self.threads:\n                self.queue.put(None)", "title": ""}
{"_id": "d11846", "text": "def _digits(minval, maxval):\n    \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n    if minval == maxval:\n        return 3\n    else:\n        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "title": ""}
{"_id": "d11847", "text": "def adapt_array(arr):\n    \"\"\"\n    Adapts a Numpy array into an ARRAY string to put into the database.\n\n    Parameters\n    ----------\n    arr: array\n        The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n    Returns\n    -------\n    ARRAY\n            The adapted array object\n\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr), out.seek(0)\n    return buffer(out.read())", "title": ""}
{"_id": "d11848", "text": "def comment (self, s, **args):\n        \"\"\"Write DOT comment.\"\"\"\n        self.write(u\"// \")\n        self.writeln(s=s, **args)", "title": ""}
{"_id": "d11849", "text": "def adapt_array(arr):\n    \"\"\"\n    Adapts a Numpy array into an ARRAY string to put into the database.\n\n    Parameters\n    ----------\n    arr: array\n        The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n    Returns\n    -------\n    ARRAY\n            The adapted array object\n\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr), out.seek(0)\n    return buffer(out.read())", "title": ""}
{"_id": "d11850", "text": "def _digits(minval, maxval):\n    \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n    if minval == maxval:\n        return 3\n    else:\n        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "title": ""}
{"_id": "d11851", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d11852", "text": "def ylabelsize(self, size, index=1):\n        \"\"\"Set the size of the label.\n\n        Parameters\n        ----------\n        size : int\n\n        Returns\n        -------\n        Chart\n\n        \"\"\"\n        self.layout['yaxis' + str(index)]['titlefont']['size'] = size\n        return self", "title": ""}
{"_id": "d11853", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d11854", "text": "def set_font_size(self, size):\n        \"\"\"Convenience method for just changing font size.\"\"\"\n        if self.font.font_size == size:\n            pass\n        else:\n            self.font._set_size(size)", "title": ""}
{"_id": "d11855", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d11856", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d11857", "text": "def parse_float_literal(ast, _variables=None):\n    \"\"\"Parse a float value node in the AST.\"\"\"\n    if isinstance(ast, (FloatValueNode, IntValueNode)):\n        return float(ast.value)\n    return INVALID", "title": ""}
{"_id": "d11858", "text": "def sorted_index(values, x):\n    \"\"\"\n    For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n    :param values: list\n    :param x: item\n    :return: integer index\n    \"\"\"\n    i = bisect_left(values, x)\n    j = bisect_right(values, x)\n    return values[i:j].index(x) + i", "title": ""}
{"_id": "d11859", "text": "def lowstrip(term):\n    \"\"\"Convert to lowercase and strip spaces\"\"\"\n    term = re.sub('\\s+', ' ', term)\n    term = term.lower()\n    return term", "title": ""}
{"_id": "d11860", "text": "def fmt_subst(regex, subst):\n    \"\"\"Replace regex with string.\"\"\"\n    return lambda text: re.sub(regex, subst, text) if text else text", "title": ""}
{"_id": "d11861", "text": "def _date_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.date):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d11862", "text": "def _insert_row(self, i, index):\n        \"\"\"\n        Insert a new row in the Series.\n\n        :param i: index location to insert\n        :param index: index value to insert into the index list\n        :return: nothing\n        \"\"\"\n        if i == len(self._index):\n            self._add_row(index)\n        else:\n            self._index.insert(i, index)\n            self._data.insert(i, None)", "title": ""}
{"_id": "d11863", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d11864", "text": "def attr_cache_clear(self):\n        node = extract_node(\"\"\"def cache_clear(self): pass\"\"\")\n        return BoundMethod(proxy=node, bound=self._instance.parent.scope())", "title": ""}
{"_id": "d11865", "text": "def drop_trailing_zeros_decimal(num):\n    \"\"\" Drops the trailinz zeros from decimal value.\n        Returns a string\n    \"\"\"\n    out = str(num)\n    return out.rstrip('0').rstrip('.') if '.' in out else out", "title": ""}
{"_id": "d11866", "text": "def xyz2lonlat(x, y, z):\n    \"\"\"Convert cartesian to lon lat.\"\"\"\n    lon = xu.rad2deg(xu.arctan2(y, x))\n    lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2)))\n    return lon, lat", "title": ""}
{"_id": "d11867", "text": "def detokenize(s):\n    \"\"\" Detokenize a string by removing spaces before punctuation.\"\"\"\n    print(s)\n    s = re.sub(\"\\s+([;:,\\.\\?!])\", \"\\\\1\", s)\n    s = re.sub(\"\\s+(n't)\", \"\\\\1\", s)\n    return s", "title": ""}
{"_id": "d11868", "text": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "title": ""}
{"_id": "d11869", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d11870", "text": "def unpack_from(self, data, offset=0):\n        \"\"\"See :func:`~bitstruct.unpack_from()`.\n\n        \"\"\"\n\n        return tuple([v[1] for v in self.unpack_from_any(data, offset)])", "title": ""}
{"_id": "d11871", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d11872", "text": "def _column_resized(self, col, old_width, new_width):\n        \"\"\"Update the column width.\"\"\"\n        self.dataTable.setColumnWidth(col, new_width)\n        self._update_layout()", "title": ""}
{"_id": "d11873", "text": "def us2mc(string):\n    \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)", "title": ""}
{"_id": "d11874", "text": "def super_lm_tpu_memtest():\n  \"\"\"Crazy set of hyperparameters to test memory optimizations.\n\n  Quality will be very poor due to lack of attention layers.\n  853M parameters\n  This seems to run on TPU for languagemodel_lm1b8k_packed as of 2018-01-19.\n\n  Returns:\n    An hparams object.\n  \"\"\"\n  hparams = super_lm_base()\n  hparams.num_model_shards = 1\n  hparams.layers = \"ffn,\" * 8\n  hparams.hidden_size = 4096\n  hparams.filter_size = 12000\n  hparams.batch_size = 512\n  return hparams", "title": ""}
{"_id": "d11875", "text": "def to_snake_case(s):\n    \"\"\"Converts camel-case identifiers to snake-case.\"\"\"\n    return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)", "title": ""}
{"_id": "d11876", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d11877", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d11878", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d11879", "text": "def mod(value, arg):\n    \"\"\"Return the modulo value.\"\"\"\n    try:\n        return valid_numeric(value) % valid_numeric(arg)\n    except (ValueError, TypeError):\n        try:\n            return value % arg\n        except Exception:\n            return ''", "title": ""}
{"_id": "d11880", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d11881", "text": "def comment (self, s, **args):\n        \"\"\"Write DOT comment.\"\"\"\n        self.write(u\"// \")\n        self.writeln(s=s, **args)", "title": ""}
{"_id": "d11882", "text": "def excepthook(self, etype, value, tb):\n      \"\"\"One more defense for GUI apps that call sys.excepthook.\n\n      GUI frameworks like wxPython trap exceptions and call\n      sys.excepthook themselves.  I guess this is a feature that\n      enables them to keep running after exceptions that would\n      otherwise kill their mainloop. This is a bother for IPython\n      which excepts to catch all of the program exceptions with a try:\n      except: statement.\n\n      Normally, IPython sets sys.excepthook to a CrashHandler instance, so if\n      any app directly invokes sys.excepthook, it will look to the user like\n      IPython crashed.  In order to work around this, we can disable the\n      CrashHandler and replace it with this excepthook instead, which prints a\n      regular traceback using our InteractiveTB.  In this fashion, apps which\n      call sys.excepthook will generate a regular-looking exception from\n      IPython, and the CrashHandler will only be triggered by real IPython\n      crashes.\n\n      This hook should be used sparingly, only in places which are not likely\n      to be true IPython errors.\n      \"\"\"\n      self.showtraceback((etype,value,tb),tb_offset=0)", "title": ""}
{"_id": "d11883", "text": "def isdir(path, **kwargs):\n    \"\"\"Check if *path* is a directory\"\"\"\n    import os.path\n    return os.path.isdir(path, **kwargs)", "title": ""}
{"_id": "d11884", "text": "def row_to_dict(row):\n    \"\"\"Convert a table row to a dictionary.\"\"\"\n    o = {}\n    for colname in row.colnames:\n\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\n    return o", "title": ""}
{"_id": "d11885", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d11886", "text": "def table_width(self):\n        \"\"\"Return the width of the table including padding and borders.\"\"\"\n        outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]\n        outer_border = 2 if self.outer_border else 0\n        inner_border = 1 if self.inner_column_border else 0\n        return table_width(outer_widths, outer_border, inner_border)", "title": ""}
{"_id": "d11887", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d11888", "text": "def if_(*args):\n    \"\"\"Implements the 'if' operator with support for multiple elseif-s.\"\"\"\n    for i in range(0, len(args) - 1, 2):\n        if args[i]:\n            return args[i + 1]\n    if len(args) % 2:\n        return args[-1]\n    else:\n        return None", "title": ""}
{"_id": "d11889", "text": "def compute_jaccard_index(x_set, y_set):\n    \"\"\"Return the Jaccard similarity coefficient of 2 given sets.\n\n    Args:\n        x_set (set): first set.\n        y_set (set): second set.\n\n    Returns:\n        float: Jaccard similarity coefficient.\n\n    \"\"\"\n    if not x_set or not y_set:\n        return 0.0\n\n    intersection_cardinal = len(x_set & y_set)\n    union_cardinal = len(x_set | y_set)\n\n    return intersection_cardinal / float(union_cardinal)", "title": ""}
{"_id": "d11890", "text": "def _is_iterable(item):\n    \"\"\" Checks if an item is iterable (list, tuple, generator), but not string \"\"\"\n    return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)", "title": ""}
{"_id": "d11891", "text": "def inverse_jacobian(self, maps):\n        \"\"\"Returns the Jacobian for transforming mass1 and mass2 to\n        mchirp and eta.\n        \"\"\"\n        m1 = maps[parameters.mass1]\n        m2 = maps[parameters.mass2]\n        mchirp = conversions.mchirp_from_mass1_mass2(m1, m2)\n        eta = conversions.eta_from_mass1_mass2(m1, m2)\n        return -1. * mchirp / eta**(6./5)", "title": ""}
{"_id": "d11892", "text": "def is_a_sequence(var, allow_none=False):\n    \"\"\" Returns True if var is a list or a tuple (but not a string!)\n    \"\"\"\n    return isinstance(var, (list, tuple)) or (var is None and allow_none)", "title": ""}
{"_id": "d11893", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d11894", "text": "def dimension_size(x, axis):\n  \"\"\"Returns the size of a specific dimension.\"\"\"\n  # Since tf.gather isn't \"constant-in, constant-out\", we must first check the\n  # static shape or fallback to dynamic shape.\n  s = tf.compat.dimension_value(\n      tensorshape_util.with_rank_at_least(x.shape, np.abs(axis))[axis])\n  if s is not None:\n    return s\n  return tf.shape(input=x)[axis]", "title": ""}
{"_id": "d11895", "text": "def commajoin_as_strings(iterable):\n    \"\"\" Join the given iterable with ',' \"\"\"\n    return _(u',').join((six.text_type(i) for i in iterable))", "title": ""}
{"_id": "d11896", "text": "def encode_to_shape(inputs, shape, scope):\n  \"\"\"Encode the given tensor to given image shape.\"\"\"\n  with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n    w, h = shape[1], shape[2]\n    x = inputs\n    x = tfl.flatten(x)\n    x = tfl.dense(x, w * h, activation=None, name=\"enc_dense\")\n    x = tf.reshape(x, (-1, w, h, 1))\n    return x", "title": ""}
{"_id": "d11897", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d11898", "text": "def cover(session):\n    \"\"\"Run the final coverage report.\n    This outputs the coverage report aggregating coverage from the unit\n    test runs (not system test runs), and then erases coverage data.\n    \"\"\"\n    session.interpreter = 'python3.6'\n    session.install('coverage', 'pytest-cov')\n    session.run('coverage', 'report', '--show-missing', '--fail-under=100')\n    session.run('coverage', 'erase')", "title": ""}
{"_id": "d11899", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d11900", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d11901", "text": "def load_parameters(self, source):\n        \"\"\"For JSON, the source it the file path\"\"\"\n        with open(source) as parameters_source:\n            return json.loads(parameters_source.read())", "title": ""}
{"_id": "d11902", "text": "def _is_proper_sequence(seq):\n    \"\"\"Returns is seq is sequence and not string.\"\"\"\n    return (isinstance(seq, collections.abc.Sequence) and\n            not isinstance(seq, str))", "title": ""}
{"_id": "d11903", "text": "def dump_json(obj):\n    \"\"\"Dump Python object as JSON string.\"\"\"\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)", "title": ""}
{"_id": "d11904", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d11905", "text": "def _date_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.date):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d11906", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d11907", "text": "def list(self,table, **kparams):\n        \"\"\"\n        get a collection of records by table name.\n        returns a dict (the json map) for python 3.4\n        \"\"\"\n        result = self.table_api_get(table, **kparams)\n        return self.to_records(result, table)", "title": ""}
{"_id": "d11908", "text": "def json_template(data, template_name, template_context):\n    \"\"\"Old style, use JSONTemplateResponse instead of this.\n    \"\"\"\n    html = render_to_string(template_name, template_context)\n    data = data or {}\n    data['html'] = html\n    return HttpResponse(json_encode(data), content_type='application/json')", "title": ""}
{"_id": "d11909", "text": "def first_sunday(self, year, month):\n        \"\"\"Get the first sunday of a month.\"\"\"\n        date = datetime(year, month, 1, 0)\n        days_until_sunday = 6 - date.weekday()\n\n        return date + timedelta(days=days_until_sunday)", "title": ""}
{"_id": "d11910", "text": "def log_magnitude_spectrum(frames):\n    \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))", "title": ""}
{"_id": "d11911", "text": "def join(self):\n        \"\"\"Joins the coordinator thread and all worker threads.\"\"\"\n        for thread in self.worker_threads:\n            thread.join()\n        WorkerThread.join(self)", "title": ""}
{"_id": "d11912", "text": "async def terminate(self):\n        \"\"\"Terminate a running script.\"\"\"\n        self.proc.terminate()\n\n        await asyncio.wait_for(self.proc.wait(), self.kill_delay)\n        if self.proc.returncode is None:\n            self.proc.kill()\n        await self.proc.wait()\n\n        await super().terminate()", "title": ""}
{"_id": "d11913", "text": "def socket_close(self):\n        \"\"\"Close our socket.\"\"\"\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET", "title": ""}
{"_id": "d11914", "text": "def format_time(time):\n    \"\"\" Formats the given time into HH:MM:SS \"\"\"\n    h, r = divmod(time / 1000, 3600)\n    m, s = divmod(r, 60)\n\n    return \"%02d:%02d:%02d\" % (h, m, s)", "title": ""}
{"_id": "d11915", "text": "def terminate(self):\n        \"\"\"Terminate all workers and threads.\"\"\"\n        for t in self._threads:\n            t.quit()\n        self._thread = []\n        self._workers = []", "title": ""}
{"_id": "d11916", "text": "def now_time(str=False):\n    \"\"\"Get the current time.\"\"\"\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()", "title": ""}
{"_id": "d11917", "text": "def connect(self):\n        \"\"\"\n        Connects to publisher\n        \"\"\"\n        self.client = redis.Redis(\n            host=self.host, port=self.port, password=self.password)", "title": ""}
{"_id": "d11918", "text": "def timed (log=sys.stderr, limit=2.0):\n    \"\"\"Decorator to run a function with timing info.\"\"\"\n    return lambda func: timeit(func, log, limit)", "title": ""}
{"_id": "d11919", "text": "def lambda_from_file(python_file):\n    \"\"\"\n    Reads a python file and returns a awslambda.Code object\n    :param python_file:\n    :return:\n    \"\"\"\n    lambda_function = []\n    with open(python_file, 'r') as f:\n        lambda_function.extend(f.read().splitlines())\n\n    return awslambda.Code(ZipFile=(Join('\\n', lambda_function)))", "title": ""}
{"_id": "d11920", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d11921", "text": "def check_clang_apply_replacements_binary(args):\n  \"\"\"Checks if invoking supplied clang-apply-replacements binary works.\"\"\"\n  try:\n    subprocess.check_call([args.clang_apply_replacements_binary, '--version'])\n  except:\n    print('Unable to run clang-apply-replacements. Is clang-apply-replacements '\n          'binary correctly specified?', file=sys.stderr)\n    traceback.print_exc()\n    sys.exit(1)", "title": ""}
{"_id": "d11922", "text": "def linearRegressionAnalysis(series):\n    \"\"\"\n    Returns factor and offset of linear regression function by least\n    squares method.\n\n    \"\"\"\n    n = safeLen(series)\n    sumI = sum([i for i, v in enumerate(series) if v is not None])\n    sumV = sum([v for i, v in enumerate(series) if v is not None])\n    sumII = sum([i * i for i, v in enumerate(series) if v is not None])\n    sumIV = sum([i * v for i, v in enumerate(series) if v is not None])\n    denominator = float(n * sumII - sumI * sumI)\n    if denominator == 0:\n        return None\n    else:\n        factor = (n * sumIV - sumI * sumV) / denominator / series.step\n        offset = sumII * sumV - sumIV * sumI\n        offset = offset / denominator - factor * series.start\n        return factor, offset", "title": ""}
{"_id": "d11923", "text": "def normalize_time(timestamp):\n    \"\"\"Normalize time in arbitrary timezone to UTC naive object.\"\"\"\n    offset = timestamp.utcoffset()\n    if offset is None:\n        return timestamp\n    return timestamp.replace(tzinfo=None) - offset", "title": ""}
{"_id": "d11924", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d11925", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d11926", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d11927", "text": "def _format_title_string(self, title_string):\n        \"\"\" format mpv's title \"\"\"\n        return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix))", "title": ""}
{"_id": "d11928", "text": "def _uniquify(_list):\n    \"\"\"Remove duplicates in a list.\"\"\"\n    seen = set()\n    result = []\n    for x in _list:\n        if x not in seen:\n            result.append(x)\n            seen.add(x)\n    return result", "title": ""}
{"_id": "d11929", "text": "def clean(self):\n        \"\"\"Return a copy of this Text instance with invalid characters removed.\"\"\"\n        return Text(self.__text_cleaner.clean(self[TEXT]), **self.__kwargs)", "title": ""}
{"_id": "d11930", "text": "def load_object_at_path(path):\n    \"\"\"Load an object from disk at explicit path\"\"\"\n    with open(path, 'r') as f:\n        data = _deserialize(f.read())\n        return aadict(data)", "title": ""}
{"_id": "d11931", "text": "def update_menu(self):\n        \"\"\"Update context menu\"\"\"\n        self.menu.clear()\n        add_actions(self.menu, self.create_context_menu_actions())", "title": ""}
{"_id": "d11932", "text": "def show_tip(self, tip=\"\"):\n        \"\"\"Show tip\"\"\"\n        QToolTip.showText(self.mapToGlobal(self.pos()), tip, self)", "title": ""}
{"_id": "d11933", "text": "def loadmat(filename):\n    \"\"\"This function should be called instead of direct spio.loadmat\n    as it cures the problem of not properly recovering python dictionaries\n    from mat files. It calls the function check keys to cure all entries\n    which are still mat-objects\n    \"\"\"\n    data = sploadmat(filename, struct_as_record=False, squeeze_me=True)\n    return _check_keys(data)", "title": ""}
{"_id": "d11934", "text": "def get_screen_resolution(self):\n        \"\"\"Return the screen resolution of the primary screen.\"\"\"\n        widget = QDesktopWidget()\n        geometry = widget.availableGeometry(widget.primaryScreen())\n        return geometry.width(), geometry.height()", "title": ""}
{"_id": "d11935", "text": "def loadmat(filename):\n    \"\"\"This function should be called instead of direct spio.loadmat\n    as it cures the problem of not properly recovering python dictionaries\n    from mat files. It calls the function check keys to cure all entries\n    which are still mat-objects\n    \"\"\"\n    data = sploadmat(filename, struct_as_record=False, squeeze_me=True)\n    return _check_keys(data)", "title": ""}
{"_id": "d11936", "text": "def __call__(self, _):\n        \"\"\"Update the progressbar.\"\"\"\n        if self.iter % self.step == 0:\n            self.pbar.update(self.step)\n\n        self.iter += 1", "title": ""}
{"_id": "d11937", "text": "def accel_next(self, *args):\n        \"\"\"Callback to go to the next tab. Called by the accel key.\n        \"\"\"\n        if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n            self.get_notebook().set_current_page(0)\n        else:\n            self.get_notebook().next_page()\n        return True", "title": ""}
{"_id": "d11938", "text": "def logout():\n    \"\"\" Log out the active user\n    \"\"\"\n    flogin.logout_user()\n    next = flask.request.args.get('next')\n    return flask.redirect(next or flask.url_for(\"user\"))", "title": ""}
{"_id": "d11939", "text": "def askopenfilename(**kwargs):\n    \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n    try:\n        from Tkinter import Tk\n        import tkFileDialog as filedialog\n    except ImportError:\n        from tkinter import Tk, filedialog\n    root = Tk()\n    root.withdraw()\n    root.update()\n    filenames = filedialog.askopenfilename(**kwargs)\n    root.destroy()\n    return filenames", "title": ""}
{"_id": "d11940", "text": "def weighted_std(values, weights):\n    \"\"\" Calculate standard deviation weighted by errors \"\"\"\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)", "title": ""}
{"_id": "d11941", "text": "def checkbox_uncheck(self, force_check=False):\n        \"\"\"\n        Wrapper to uncheck a checkbox\n        \"\"\"\n        if self.get_attribute('checked'):\n            self.click(force_click=force_check)", "title": ""}
{"_id": "d11942", "text": "def get_join_cols(by_entry):\n  \"\"\" helper function used for joins\n  builds left and right join list for join function\n  \"\"\"\n  left_cols = []\n  right_cols = []\n  for col in by_entry:\n    if isinstance(col, str):\n      left_cols.append(col)\n      right_cols.append(col)\n    else:\n      left_cols.append(col[0])\n      right_cols.append(col[1])\n  return left_cols, right_cols", "title": ""}
{"_id": "d11943", "text": "def _end_del(self):\n        \"\"\" Deletes the line content after the cursor  \"\"\"\n        text = self.edit_text[:self.edit_pos]\n        self.set_edit_text(text)", "title": ""}
{"_id": "d11944", "text": "def focusInEvent(self, event):\n        \"\"\"Reimplement Qt method to send focus change notification\"\"\"\n        self.focus_changed.emit()\n        return super(ShellWidget, self).focusInEvent(event)", "title": ""}
{"_id": "d11945", "text": "def yview(self, *args):\n        \"\"\"Update inplace widgets position when doing vertical scroll\"\"\"\n        self.after_idle(self.__updateWnds)\n        ttk.Treeview.yview(self, *args)", "title": ""}
{"_id": "d11946", "text": "def get_data_table(filename):\n  \"\"\"Returns a DataTable instance built from either the filename, or STDIN if filename is None.\"\"\"\n  with get_file_object(filename, \"r\") as rf:\n    return DataTable(list(csv.reader(rf)))", "title": ""}
{"_id": "d11947", "text": "def get_focused_window_sane(self):\n        \"\"\"\n        Like xdo_get_focused_window, but return the first ancestor-or-self\n        window * having a property of WM_CLASS. This allows you to get\n        the \"real\" or top-level-ish window having focus rather than something\n        you may not expect to be the window having focused.\n\n        :param window_ret:\n            Pointer to a window where the currently-focused window\n            will be stored.\n        \"\"\"\n        window_ret = window_t(0)\n        _libxdo.xdo_get_focused_window_sane(\n            self._xdo, ctypes.byref(window_ret))\n        return window_ret.value", "title": ""}
{"_id": "d11948", "text": "def _npiter(arr):\n    \"\"\"Wrapper for iterating numpy array\"\"\"\n    for a in np.nditer(arr, flags=[\"refs_ok\"]):\n        c = a.item()\n        if c is not None:\n            yield c", "title": ""}
{"_id": "d11949", "text": "def zero_state(self, batch_size):\n        \"\"\" Initial state of the network \"\"\"\n        return torch.zeros(batch_size, self.state_dim, dtype=torch.float32)", "title": ""}
{"_id": "d11950", "text": "def flush_on_close(self, stream):\n        \"\"\"Flush tornado iostream write buffer and prevent further writes.\n\n        Returns a future that resolves when the stream is flushed.\n\n        \"\"\"\n        assert get_thread_ident() == self.ioloop_thread_id\n        # Prevent futher writes\n        stream.KATCPServer_closing = True\n        # Write empty message to get future that resolves when buffer is flushed\n        return stream.write('\\n')", "title": ""}
{"_id": "d11951", "text": "def set_executable(filename):\n    \"\"\"Set the exectuable bit on the given filename\"\"\"\n    st = os.stat(filename)\n    os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d11952", "text": "def start(args):\n    \"\"\"Run server with provided command line arguments.\n    \"\"\"\n    application = tornado.web.Application([(r\"/run\", run.get_handler(args)),\n                                           (r\"/status\", run.StatusHandler)])\n    application.runmonitor = RunMonitor()\n    application.listen(args.port)\n    tornado.ioloop.IOLoop.instance().start()", "title": ""}
{"_id": "d11953", "text": "def set_executable(filename):\n    \"\"\"Set the exectuable bit on the given filename\"\"\"\n    st = os.stat(filename)\n    os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d11954", "text": "def write_json_response(self, response):\n    \"\"\" write back json response \"\"\"\n    self.write(tornado.escape.json_encode(response))\n    self.set_header(\"Content-Type\", \"application/json\")", "title": ""}
{"_id": "d11955", "text": "def _synced(method, self, args, kwargs):\n    \"\"\"Underlying synchronized wrapper.\"\"\"\n    with self._lock:\n        return method(*args, **kwargs)", "title": ""}
{"_id": "d11956", "text": "def str_traceback(error, tb):\n    \"\"\"Returns a string representation of the traceback.\n    \"\"\"\n    if not isinstance(tb, types.TracebackType):\n        return tb\n\n    return ''.join(traceback.format_exception(error.__class__, error, tb))", "title": ""}
{"_id": "d11957", "text": "def map(cls, iterable, func, *a, **kw):\n    \"\"\"\n    Iterable-first replacement of Python's built-in `map()` function.\n    \"\"\"\n\n    return cls(func(x, *a, **kw) for x in iterable)", "title": ""}
{"_id": "d11958", "text": "def multidict_to_dict(d):\n    \"\"\"\n    Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with\n    list values\n    :param d: a MultiDict or MultiValueDict instance\n    :return: a dict instance\n    \"\"\"\n    return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))", "title": ""}
{"_id": "d11959", "text": "def is_managed():\n    \"\"\"\n    Check if a Django project is being managed with ``manage.py`` or\n    ``django-admin`` scripts\n\n    :return: Check result\n    :rtype: bool\n    \"\"\"\n    for item in sys.argv:\n        if re.search(r'manage.py|django-admin|django', item) is not None:\n            return True\n    return False", "title": ""}
{"_id": "d11960", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d11961", "text": "def to_dict(self):\n        \"\"\"Converts the table to a dict.\"\"\"\n        return {\"name\": self.table_name, \"kind\": self.table_kind, \"data\": [r.to_dict() for r in self]}", "title": ""}
{"_id": "d11962", "text": "def register_view(self, view):\n        \"\"\"Register callbacks for button press events and selection changed\"\"\"\n        super(ListViewController, self).register_view(view)\n        self.tree_view.connect('button_press_event', self.mouse_click)", "title": ""}
{"_id": "d11963", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d11964", "text": "def _trim(self, somestr):\n        \"\"\" Trim left-right given string \"\"\"\n        tmp = RE_LSPACES.sub(\"\", somestr)\n        tmp = RE_TSPACES.sub(\"\", tmp)\n        return str(tmp)", "title": ""}
{"_id": "d11965", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d11966", "text": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "title": ""}
{"_id": "d11967", "text": "def truncate(self, table):\n        \"\"\"Empty a table by deleting all of its rows.\"\"\"\n        if isinstance(table, (list, set, tuple)):\n            for t in table:\n                self._truncate(t)\n        else:\n            self._truncate(table)", "title": ""}
{"_id": "d11968", "text": "def _ndarray_representer(dumper, data):\n    \"\"\"\n\n    :param dumper:\n    :param data:\n    :type data: :class:`numpy.ndarray`\n    :return:\n    \"\"\"\n    mapping = [('object', data.tolist()), ('dtype', data.dtype.name)]\n    return dumper.represent_mapping(_NUMPY_ARRAY_TAG, mapping)", "title": ""}
{"_id": "d11969", "text": "def tuple(self, var, cast=None, default=NOTSET):\n        \"\"\"\n        :rtype: tuple\n        \"\"\"\n        return self.get_value(var, cast=tuple if not cast else (cast,), default=default)", "title": ""}
{"_id": "d11970", "text": "def datetime_match(data, dts):\n    \"\"\"\n    matching of datetimes in time columns for data filtering\n    \"\"\"\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)", "title": ""}
{"_id": "d11971", "text": "def is_filelike(ob):\n    \"\"\"Check for filelikeness of an object.\n\n    Needed to distinguish it from file names.\n    Returns true if it has a read or a write method.\n    \"\"\"\n    if hasattr(ob, 'read') and callable(ob.read):\n        return True\n\n    if hasattr(ob, 'write') and callable(ob.write):\n        return True\n\n    return False", "title": ""}
{"_id": "d11972", "text": "def _from_list_dict(cls, list_dic):\n        \"\"\"Takes a list of dict like objects and uses `champ_id` field as Id\"\"\"\n        return cls({_convert_id(dic[cls.CHAMP_ID]): dict(dic) for dic in list_dic})", "title": ""}
{"_id": "d11973", "text": "def csv_matrix_print(classes, table):\n    \"\"\"\n    Return matrix as csv data.\n\n    :param classes: classes list\n    :type classes:list\n    :param table: table\n    :type table:dict\n    :return:\n    \"\"\"\n    result = \"\"\n    classes.sort()\n    for i in classes:\n        for j in classes:\n            result += str(table[i][j]) + \",\"\n        result = result[:-1] + \"\\n\"\n    return result[:-1]", "title": ""}
{"_id": "d11974", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d11975", "text": "def _swap_rows(self, i, j):\n        \"\"\"Swap i and j rows\n\n        As the side effect, determinant flips.\n\n        \"\"\"\n\n        L = np.eye(3, dtype='intc')\n        L[i, i] = 0\n        L[j, j] = 0\n        L[i, j] = 1\n        L[j, i] = 1\n        self._L.append(L.copy())\n        self._A = np.dot(L, self._A)", "title": ""}
{"_id": "d11976", "text": "def gray2bgr(img):\n    \"\"\"Convert a grayscale image to BGR image.\n\n    Args:\n        img (ndarray or str): The input image.\n\n    Returns:\n        ndarray: The converted BGR image.\n    \"\"\"\n    img = img[..., None] if img.ndim == 2 else img\n    out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n    return out_img", "title": ""}
{"_id": "d11977", "text": "def unpack(self, s):\n        \"\"\"Parse bytes and return a namedtuple.\"\"\"\n        return self._create(super(NamedStruct, self).unpack(s))", "title": ""}
{"_id": "d11978", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d11979", "text": "def str2bool(value):\n    \"\"\"Parse Yes/No/Default string\n    https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse\"\"\"\n    if value.lower() in ('yes', 'true', 't', 'y', '1'):\n        return True\n    if value.lower() in ('no', 'false', 'f', 'n', '0'):\n        return False\n    if value.lower() in ('d', 'default', ''):\n        return None\n    raise argparse.ArgumentTypeError('Expected: (Y)es/(T)rue/(N)o/(F)alse/(D)efault')", "title": ""}
{"_id": "d11980", "text": "def get_attribute_name_id(attr):\n    \"\"\"\n    Return the attribute name identifier\n    \"\"\"\n    return attr.value.id if isinstance(attr.value, ast.Name) else None", "title": ""}
{"_id": "d11981", "text": "def _upper(val_list):\n    \"\"\"\n    :param val_list: a list of strings\n    :return: a list of upper-cased strings\n    \"\"\"\n    res = []\n    for ele in val_list:\n        res.append(ele.upper())\n    return res", "title": ""}
{"_id": "d11982", "text": "def direct2dDistance(self, point):\n        \"\"\"consider the distance between two mapPoints, ignoring all terrain, pathing issues\"\"\"\n        if not isinstance(point, MapPoint): return 0.0\n        return  ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula", "title": ""}
{"_id": "d11983", "text": "def memory_usage(method):\n  \"\"\"Log memory usage before and after a method.\"\"\"\n  def wrapper(*args, **kwargs):\n    logging.info('Memory before method %s is %s.',\n                 method.__name__, runtime.memory_usage().current())\n    result = method(*args, **kwargs)\n    logging.info('Memory after method %s is %s',\n                 method.__name__, runtime.memory_usage().current())\n    return result\n  return wrapper", "title": ""}
{"_id": "d11984", "text": "def url_encode(url):\n    \"\"\"\n    Convert special characters using %xx escape.\n\n    :param url: str\n    :return: str - encoded url\n    \"\"\"\n    if isinstance(url, text_type):\n        url = url.encode('utf8')\n    return quote(url, ':/%?&=')", "title": ""}
{"_id": "d11985", "text": "def memory_usage(method):\n  \"\"\"Log memory usage before and after a method.\"\"\"\n  def wrapper(*args, **kwargs):\n    logging.info('Memory before method %s is %s.',\n                 method.__name__, runtime.memory_usage().current())\n    result = method(*args, **kwargs)\n    logging.info('Memory after method %s is %s',\n                 method.__name__, runtime.memory_usage().current())\n    return result\n  return wrapper", "title": ""}
{"_id": "d11986", "text": "def get_dict_to_encoded_url(data):\n    \"\"\"\n    Converts a dict to an encoded URL.\n    Example: given  data = {'a': 1, 'b': 2}, it returns 'a=1&b=2'\n    \"\"\"\n    unicode_data = dict([(k, smart_str(v)) for k, v in data.items()])\n    encoded = urllib.urlencode(unicode_data)\n    return encoded", "title": ""}
{"_id": "d11987", "text": "def median_high(data):\n    \"\"\"Return the high median of data.\n\n    When the number of data points is odd, the middle value is returned.\n    When it is even, the larger of the two middle values is returned.\n\n    \"\"\"\n    data = sorted(data)\n    n = len(data)\n    if n == 0:\n        raise StatisticsError(\"no median for empty data\")\n    return data[n // 2]", "title": ""}
{"_id": "d11988", "text": "def validate_args(**args):\n\t\"\"\"\n\tfunction to check if input query is not None \n\tand set missing arguments to default value\n\t\"\"\"\n\tif not args['query']:\n\t\tprint(\"\\nMissing required query argument.\")\n\t\tsys.exit()\n\n\tfor key in DEFAULTS:\n\t\tif key not in args:\n\t\t\targs[key] = DEFAULTS[key]\n\n\treturn args", "title": ""}
{"_id": "d11989", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d11990", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d11991", "text": "def getMedian(numericValues):\n    \"\"\"\n    Gets the median of a list of values\n    Returns a float/int\n    \"\"\"\n    theValues = sorted(numericValues)\n\n    if len(theValues) % 2 == 1:\n        return theValues[(len(theValues) + 1) / 2 - 1]\n    else:\n        lower = theValues[len(theValues) / 2 - 1]\n        upper = theValues[len(theValues) / 2]\n\n        return (float(lower + upper)) / 2", "title": ""}
{"_id": "d11992", "text": "def getTuple(self):\n        \"\"\" Returns the shape of the region as (x, y, w, h) \"\"\"\n        return (self.x, self.y, self.w, self.h)", "title": ""}
{"_id": "d11993", "text": "def median(data):\n    \"\"\"Calculate the median of a list.\"\"\"\n    data.sort()\n    num_values = len(data)\n    half = num_values // 2\n    if num_values % 2:\n        return data[half]\n    return 0.5 * (data[half-1] + data[half])", "title": ""}
{"_id": "d11994", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d11995", "text": "def median_high(data):\n    \"\"\"Return the high median of data.\n\n    When the number of data points is odd, the middle value is returned.\n    When it is even, the larger of the two middle values is returned.\n\n    \"\"\"\n    data = sorted(data)\n    n = len(data)\n    if n == 0:\n        raise StatisticsError(\"no median for empty data\")\n    return data[n // 2]", "title": ""}
{"_id": "d11996", "text": "def __next__(self, reward, ask_id, lbl):\n        \"\"\"For Python3 compatibility of generator.\"\"\"\n        return self.next(reward, ask_id, lbl)", "title": ""}
{"_id": "d11997", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d11998", "text": "def generate_uuid():\n    \"\"\"Generate a UUID.\"\"\"\n    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)\n    return r_uuid.decode().replace('=', '')", "title": ""}
{"_id": "d11999", "text": "async def write_register(self, address, value, skip_encode=False):\n        \"\"\"Write a modbus register.\"\"\"\n        await self._request('write_registers', address, value, skip_encode=skip_encode)", "title": ""}
{"_id": "d12000", "text": "def with_args(self, *args, **kwargs):\n        \"\"\"Declares that the double can only be called with the provided arguments.\n\n        :param args: Any positional arguments required for invocation.\n        :param kwargs: Any keyword arguments required for invocation.\n        \"\"\"\n\n        self.args = args\n        self.kwargs = kwargs\n        self.verify_arguments()\n        return self", "title": ""}
{"_id": "d12001", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d12002", "text": "def getprop(self, prop_name):\n        \"\"\"Get a property of the device.\n\n        This is a convenience wrapper for \"adb shell getprop xxx\".\n\n        Args:\n            prop_name: A string that is the name of the property to get.\n\n        Returns:\n            A string that is the value of the property, or None if the property\n            doesn't exist.\n        \"\"\"\n        return self.shell(\n            ['getprop', prop_name],\n            timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode('utf-8').strip()", "title": ""}
{"_id": "d12003", "text": "def python_mime(fn):\n    \"\"\"\n    Decorator, which adds correct MIME type for python source to the decorated\n    bottle API function.\n    \"\"\"\n    @wraps(fn)\n    def python_mime_decorator(*args, **kwargs):\n        response.content_type = \"text/x-python\"\n\n        return fn(*args, **kwargs)\n\n    return python_mime_decorator", "title": ""}
{"_id": "d12004", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d12005", "text": "def minify_js(input_files, output_file):\n    \"\"\"\n    Minifies the input javascript files to the output file.\n\n    Output file may be same as input to minify in place.\n\n    In debug mode this function just concatenates the files\n    without minifying.\n    \"\"\"\n    from .modules import minify, utils\n\n    if not isinstance(input_files, (list, tuple)):\n        raise RuntimeError('JS minifier takes a list of input files.')\n\n    return {\n        'dependencies_fn': utils.no_dependencies,\n        'compiler_fn': minify.minify_js,\n        'input': input_files,\n        'output': output_file,\n        'kwargs': {},\n    }", "title": ""}
{"_id": "d12006", "text": "def valid_uuid(value):\n    \"\"\" Check if value is a valid UUID. \"\"\"\n\n    try:\n        uuid.UUID(value, version=4)\n        return True\n    except (TypeError, ValueError, AttributeError):\n        return False", "title": ""}
{"_id": "d12007", "text": "def get_img_data(f, maxsize = (1200, 850), first = False):\n    \"\"\"Generate image data using PIL\n    \"\"\"\n    img = Image.open(f)\n    img.thumbnail(maxsize)\n    if first:                     # tkinter is inactive the first time\n        bio = io.BytesIO()\n        img.save(bio, format = \"PNG\")\n        del img\n        return bio.getvalue()\n    return ImageTk.PhotoImage(img)", "title": ""}
{"_id": "d12008", "text": "def vsh(cmd, *args, **kw):\n    \"\"\" Execute a command installed into the active virtualenv.\n    \"\"\"\n    args = '\" \"'.join(i.replace('\"', r'\\\"') for i in args)\n    easy.sh('\"%s\" \"%s\"' % (venv_bin(cmd), args))", "title": ""}
{"_id": "d12009", "text": "def distance_to_line(a, b, p):\n    \"\"\"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\n    \"\"\"\n    return distance(closest_point(a, b, p), p)", "title": ""}
{"_id": "d12010", "text": "def venv():\n    \"\"\"Install venv + deps.\"\"\"\n    try:\n        import virtualenv  # NOQA\n    except ImportError:\n        sh(\"%s -m pip install virtualenv\" % PYTHON)\n    if not os.path.isdir(\"venv\"):\n        sh(\"%s -m virtualenv venv\" % PYTHON)\n    sh(\"venv\\\\Scripts\\\\pip install -r %s\" % (REQUIREMENTS_TXT))", "title": ""}
{"_id": "d12011", "text": "def logout():\n    \"\"\" Log out the active user\n    \"\"\"\n    flogin.logout_user()\n    next = flask.request.args.get('next')\n    return flask.redirect(next or flask.url_for(\"user\"))", "title": ""}
{"_id": "d12012", "text": "def page_title(step, title):\n    \"\"\"\n    Check that the page title matches the given one.\n    \"\"\"\n\n    with AssertContextManager(step):\n        assert_equals(world.browser.title, title)", "title": ""}
{"_id": "d12013", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d12014", "text": "def page_title(step, title):\n    \"\"\"\n    Check that the page title matches the given one.\n    \"\"\"\n\n    with AssertContextManager(step):\n        assert_equals(world.browser.title, title)", "title": ""}
{"_id": "d12015", "text": "def _go_to_line(editor, line):\n    \"\"\"\n    Move cursor to this line in the current buffer.\n    \"\"\"\n    b = editor.application.current_buffer\n    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "title": ""}
{"_id": "d12016", "text": "def serve(application, host='127.0.0.1', port=8080, threads=4, **kw):\n\t\"\"\"The recommended development HTTP server.\n\t\n\tNote that this server performs additional buffering and will not honour chunked encoding breaks.\n\t\"\"\"\n\t\n\t# Bind and start the server; this is a blocking process.\n\tserve_(application, host=host, port=int(port), threads=int(threads), **kw)", "title": ""}
{"_id": "d12017", "text": "def _close_websocket(self):\n        \"\"\"Closes the websocket connection.\"\"\"\n        close_method = getattr(self._websocket, \"close\", None)\n        if callable(close_method):\n            asyncio.ensure_future(close_method(), loop=self._event_loop)\n        self._websocket = None\n        self._dispatch_event(event=\"close\")", "title": ""}
{"_id": "d12018", "text": "def page_guiref(arg_s=None):\n    \"\"\"Show a basic reference about the GUI Console.\"\"\"\n    from IPython.core import page\n    page.page(gui_reference, auto_html=True)", "title": ""}
{"_id": "d12019", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d12020", "text": "def run_migration(connection, queries, engine):\n    \"\"\" Apply a migration to the SQL server \"\"\"\n\n    # Execute query\n    with connection.cursor() as cursorMig:\n        # Parse statements\n        queries = parse_statements(queries, engine)\n\n        for query in queries:\n            cursorMig.execute(query)\n        connection.commit()\n\n    return True", "title": ""}
{"_id": "d12021", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d12022", "text": "def runiform(lower, upper, size=None):\n    \"\"\"\n    Random uniform variates.\n    \"\"\"\n    return np.random.uniform(lower, upper, size)", "title": ""}
{"_id": "d12023", "text": "def file_matches(filename, patterns):\n    \"\"\"Does this filename match any of the patterns?\"\"\"\n    return any(fnmatch.fnmatch(filename, pat) for pat in patterns)", "title": ""}
{"_id": "d12024", "text": "def LogBinomialCoef(n, k):\n    \"\"\"Computes the log of the binomial coefficient.\n\n    http://math.stackexchange.com/questions/64716/\n    approximating-the-logarithm-of-the-binomial-coefficient\n\n    n: number of trials\n    k: number of successes\n\n    Returns: float\n    \"\"\"\n    return n * log(n) - k * log(k) - (n - k) * log(n - k)", "title": ""}
{"_id": "d12025", "text": "def _position():\n    \"\"\"Returns the current xy coordinates of the mouse cursor as a two-integer\n    tuple by calling the GetCursorPos() win32 function.\n\n    Returns:\n      (x, y) tuple of the current xy coordinates of the mouse cursor.\n    \"\"\"\n\n    cursor = POINT()\n    ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))\n    return (cursor.x, cursor.y)", "title": ""}
{"_id": "d12026", "text": "def finish():\n    \"\"\"Print warning about interrupt and empty the job queue.\"\"\"\n    out.warn(\"Interrupted!\")\n    for t in threads:\n        t.stop()\n    jobs.clear()\n    out.warn(\"Waiting for download threads to finish.\")", "title": ""}
{"_id": "d12027", "text": "def title(self):\n        \"\"\" The title of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.title", "title": ""}
{"_id": "d12028", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d12029", "text": "def get_user_name():\n    \"\"\"Get user name provide by operating system\n    \"\"\"\n\n    if sys.platform == 'win32':\n        #user = os.getenv('USERPROFILE')\n        user = os.getenv('USERNAME')\n    else:\n        user = os.getenv('LOGNAME')\n\n    return user", "title": ""}
{"_id": "d12030", "text": "def unlock(self):\n    \"\"\"Closes the session to the database.\"\"\"\n    if not hasattr(self, 'session'):\n      raise RuntimeError('Error detected! The session that you want to close does not exist any more!')\n    logger.debug(\"Closed database session of '%s'\" % self._database)\n    self.session.close()\n    del self.session", "title": ""}
{"_id": "d12031", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d12032", "text": "def get_table_columns(dbconn, tablename):\n    \"\"\"\n    Return a list of tuples specifying the column name and type\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n    info = cur.fetchall()\n    cols = [(i[1], i[2]) for i in info]\n    return cols", "title": ""}
{"_id": "d12033", "text": "def clean_text_by_sentences(text, language=\"english\", additional_stopwords=None):\n    \"\"\" Tokenizes a given text into sentences, applying filters and lemmatizing them.\n    Returns a SyntacticUnit list. \"\"\"\n    init_textcleanner(language, additional_stopwords)\n    original_sentences = split_sentences(text)\n    filtered_sentences = filter_words(original_sentences)\n\n    return merge_syntactic_units(original_sentences, filtered_sentences)", "title": ""}
{"_id": "d12034", "text": "def get_naive(dt):\n  \"\"\"Gets a naive datetime from a datetime.\n\n  datetime_tz objects can't just have tzinfo replaced with None, you need to\n  call asdatetime.\n\n  Args:\n    dt: datetime object.\n\n  Returns:\n    datetime object without any timezone information.\n  \"\"\"\n  if not dt.tzinfo:\n    return dt\n  if hasattr(dt, \"asdatetime\"):\n    return dt.asdatetime()\n  return dt.replace(tzinfo=None)", "title": ""}
{"_id": "d12035", "text": "def return_future(fn):\n    \"\"\"Decorator that turns a synchronous function into one returning a future.\n\n    This should only be applied to non-blocking functions. Will do set_result()\n    with the return value, or set_exc_info() if an exception is raised.\n\n    \"\"\"\n    @wraps(fn)\n    def decorated(*args, **kwargs):\n        return gen.maybe_future(fn(*args, **kwargs))\n\n    return decorated", "title": ""}
{"_id": "d12036", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d12037", "text": "def map_wrap(f):\n    \"\"\"Wrap standard function to easily pass into 'map' processing.\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d12038", "text": "def best(self):\n        \"\"\"\n        Returns the element with the highest probability.\n        \"\"\"\n        b = (-1e999999, None)\n        for k, c in iteritems(self.counts):\n            b = max(b, (c, k))\n        return b[1]", "title": ""}
{"_id": "d12039", "text": "def encode(strs):\n    \"\"\"Encodes a list of strings to a single string.\n    :type strs: List[str]\n    :rtype: str\n    \"\"\"\n    res = ''\n    for string in strs.split():\n        res += str(len(string)) + \":\" + string\n    return res", "title": ""}
{"_id": "d12040", "text": "def neo(graph: BELGraph, connection: str, password: str):\n    \"\"\"Upload to neo4j.\"\"\"\n    import py2neo\n    neo_graph = py2neo.Graph(connection, password=password)\n    to_neo4j(graph, neo_graph)", "title": ""}
{"_id": "d12041", "text": "def write_tsv_line_from_list(linelist, outfp):\n    \"\"\"Utility method to convert list to tsv line with carriage return\"\"\"\n    line = '\\t'.join(linelist)\n    outfp.write(line)\n    outfp.write('\\n')", "title": ""}
{"_id": "d12042", "text": "def has_next_async(self):\n    \"\"\"Return a Future whose result will say whether a next item is available.\n\n    See the module docstring for the usage pattern.\n    \"\"\"\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)", "title": ""}
{"_id": "d12043", "text": "def WritePythonFile(file_descriptor, package, version, printer):\n    \"\"\"Write the given extended file descriptor to out.\"\"\"\n    _WriteFile(file_descriptor, package, version,\n               _ProtoRpcPrinter(printer))", "title": ""}
{"_id": "d12044", "text": "def _preprocess(df):\n    \"\"\"\n    given a DataFrame where records are stored row-wise, rearrange it\n    such that records are stored column-wise.\n    \"\"\"\n\n    df = df.stack()\n\n    df.index.rename([\"id\", \"time\"], inplace=True)  # .reset_index()\n    df.name = \"value\"\n    df = df.reset_index()\n\n    return df", "title": ""}
{"_id": "d12045", "text": "def sometimesish(fn):\n    \"\"\"\n    Has a 50/50 chance of calling a function\n    \"\"\"\n    def wrapped(*args, **kwargs):\n        if random.randint(1, 2) == 1:\n            return fn(*args, **kwargs)\n\n    return wrapped", "title": ""}
{"_id": "d12046", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d12047", "text": "def get_gzipped_contents(input_file):\n    \"\"\"\n    Returns a gzipped version of a previously opened file's buffer.\n    \"\"\"\n    zbuf = StringIO()\n    zfile = GzipFile(mode=\"wb\", compresslevel=6, fileobj=zbuf)\n    zfile.write(input_file.read())\n    zfile.close()\n    return ContentFile(zbuf.getvalue())", "title": ""}
{"_id": "d12048", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d12049", "text": "def save_json(object, handle, indent=2):\n    \"\"\"Save object as json on CNS.\"\"\"\n    obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder)\n    handle.write(obj_json)", "title": ""}
{"_id": "d12050", "text": "def normalize(name):\n    \"\"\"Normalize name for the Statsd convention\"\"\"\n\n    # Name should not contain some specials chars (issue #1068)\n    ret = name.replace(':', '')\n    ret = ret.replace('%', '')\n    ret = ret.replace(' ', '_')\n\n    return ret", "title": ""}
{"_id": "d12051", "text": "def write_dict_to_yaml(dictionary, path, **kwargs):\n    \"\"\"\n    Writes a dictionary to a yaml file\n    :param dictionary:  the dictionary to be written\n    :param path: the absolute path of the target yaml file\n    :param kwargs: optional additional parameters for dumper\n    \"\"\"\n    with open(path, 'w') as f:\n        yaml.dump(dictionary, f, indent=4, **kwargs)", "title": ""}
{"_id": "d12052", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d12053", "text": "def underline(self, msg):\n        \"\"\"Underline the input\"\"\"\n        return click.style(msg, underline=True) if self.colorize else msg", "title": ""}
{"_id": "d12054", "text": "def normalize(im, invert=False, scale=None, dtype=np.float64):\n    \"\"\"\n    Normalize a field to a (min, max) exposure range, default is (0, 255).\n    (min, max) exposure values. Invert the image if requested.\n    \"\"\"\n    if dtype not in {np.float16, np.float32, np.float64}:\n        raise ValueError('dtype must be numpy.float16, float32, or float64.')\n    out = im.astype('float').copy()\n\n    scale = scale or (0.0, 255.0)\n    l, u = (float(i) for i in scale)\n    out = (out - l) / (u - l)\n    if invert:\n        out = -out + (out.max() + out.min())\n    return out.astype(dtype)", "title": ""}
{"_id": "d12055", "text": "def print_yaml(o):\n    \"\"\"Pretty print an object as YAML.\"\"\"\n    print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))", "title": ""}
{"_id": "d12056", "text": "def series_table_row_offset(self, series):\n        \"\"\"\n        Return the number of rows preceding the data table for *series* in\n        the Excel worksheet.\n        \"\"\"\n        title_and_spacer_rows = series.index * 2\n        data_point_rows = series.data_point_offset\n        return title_and_spacer_rows + data_point_rows", "title": ""}
{"_id": "d12057", "text": "def print_yaml(o):\n    \"\"\"Pretty print an object as YAML.\"\"\"\n    print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))", "title": ""}
{"_id": "d12058", "text": "def load(raw_bytes):\n        \"\"\"\n        given a bytes object, should return a base python data\n        structure that represents the object.\n        \"\"\"\n        try:\n            if not isinstance(raw_bytes, string_type):\n                raw_bytes = raw_bytes.decode()\n            return json.loads(raw_bytes)\n        except ValueError as e:\n            raise SerializationException(str(e))", "title": ""}
{"_id": "d12059", "text": "def dumps(obj, indent=None, default=None, sort_keys=False, **kw):\n    \"\"\"Dump string.\"\"\"\n    return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj)", "title": ""}
{"_id": "d12060", "text": "def close_session(self):\n        \"\"\" Close tensorflow session. Exposes for memory management. \"\"\"\n        with self._graph.as_default():\n            self._sess.close()\n            self._sess = None", "title": ""}
{"_id": "d12061", "text": "def safe_dump_all(documents, stream=None, **kwds):\n    \"\"\"\n    Serialize a sequence of Python objects into a YAML stream.\n    Produce only basic YAML tags.\n    If stream is None, return the produced string instead.\n    \"\"\"\n    return dump_all(documents, stream, Dumper=SafeDumper, **kwds)", "title": ""}
{"_id": "d12062", "text": "def min_max_normalize(img):\n    \"\"\"Centre and normalize a given array.\n\n    Parameters:\n    ----------\n    img: np.ndarray\n\n    \"\"\"\n\n    min_img = img.min()\n    max_img = img.max()\n\n    return (img - min_img) / (max_img - min_img)", "title": ""}
{"_id": "d12063", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d12064", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d12065", "text": "def to_dict(self):\n        \"\"\"Converts the table to a dict.\"\"\"\n        return {\"name\": self.table_name, \"kind\": self.table_kind, \"data\": [r.to_dict() for r in self]}", "title": ""}
{"_id": "d12066", "text": "def compressBuffer(buffer):\n    \"\"\"\n    Note that this code compresses into a buffer held in memory, rather\n    than a disk file. This is done through the use of cStringIO.StringIO().\n    \"\"\"\n    # http://jython.xhaus.com/http-compression-in-python-and-jython/\n    zbuf = cStringIO.StringIO()\n    zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)\n    zfile.write(buffer)\n    zfile.close()\n    return zbuf.getvalue()", "title": ""}
{"_id": "d12067", "text": "def json_pretty_dump(obj, filename):\n    \"\"\"\n    Serialize obj as a JSON formatted stream to the given filename (\n    pretty printing version)\n    \"\"\"\n    with open(filename, \"wt\") as fh:\n        json.dump(obj, fh, indent=4, sort_keys=4)", "title": ""}
{"_id": "d12068", "text": "def dump(self, *args, **kwargs):\n        \"\"\"Dumps a representation of the Model on standard output.\"\"\"\n        lxml.etree.dump(self._obj, *args, **kwargs)", "title": ""}
{"_id": "d12069", "text": "def parse_datetime(dt_str):\n    \"\"\"Parse datetime.\"\"\"\n    date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n    dt_str = dt_str.replace(\"Z\", \" +0000\")\n    return datetime.datetime.strptime(dt_str, date_format)", "title": ""}
{"_id": "d12070", "text": "def printdict(adict):\n    \"\"\"printdict\"\"\"\n    dlist = list(adict.keys())\n    dlist.sort()\n    for i in range(0, len(dlist)):\n        print(dlist[i], adict[dlist[i]])", "title": ""}
{"_id": "d12071", "text": "def parse(text, showToc=True):\n\t\"\"\"Returns HTML from MediaWiki markup\"\"\"\n\tp = Parser(show_toc=showToc)\n\treturn p.parse(text)", "title": ""}
{"_id": "d12072", "text": "def load(self, name):\n        \"\"\"Loads and returns foreign library.\"\"\"\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)", "title": ""}
{"_id": "d12073", "text": "def run(args):\n    \"\"\"Process command line arguments and walk inputs.\"\"\"\n    raw_arguments = get_arguments(args[1:])\n    process_arguments(raw_arguments)\n    walk.run()\n    return True", "title": ""}
{"_id": "d12074", "text": "def get_best_encoding(stream):\n    \"\"\"Returns the default stream encoding if not found.\"\"\"\n    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n    if is_ascii_encoding(rv):\n        return 'utf-8'\n    return rv", "title": ""}
{"_id": "d12075", "text": "def extract_keywords_from_text(self, text):\n        \"\"\"Method to extract keywords from the text provided.\n\n        :param text: Text to extract keywords from, provided as a string.\n        \"\"\"\n        sentences = nltk.tokenize.sent_tokenize(text)\n        self.extract_keywords_from_sentences(sentences)", "title": ""}
{"_id": "d12076", "text": "def index_all(self, index_name):\n        \"\"\"Index all available documents, using streaming_bulk for speed\n        Args:\n\n        index_name (string): The index\n        \"\"\"\n        oks = 0\n        notoks = 0\n        for ok, item in streaming_bulk(\n            self.es_client,\n            self._iter_documents(index_name)\n        ):\n            if ok:\n                oks += 1\n            else:\n                notoks += 1\n        logging.info(\n            \"Import results: %d ok, %d not ok\",\n            oks,\n            notoks\n        )", "title": ""}
{"_id": "d12077", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d12078", "text": "def find_console_handler(logger):\n    \"\"\"Return a stream handler, if it exists.\"\"\"\n    for handler in logger.handlers:\n        if (isinstance(handler, logging.StreamHandler) and\n                handler.stream == sys.stderr):\n            return handler", "title": ""}
{"_id": "d12079", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d12080", "text": "def html_to_text(content):\n    \"\"\" Converts html content to plain text \"\"\"\n    text = None\n    h2t = html2text.HTML2Text()\n    h2t.ignore_links = False\n    text = h2t.handle(content)\n    return text", "title": ""}
{"_id": "d12081", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d12082", "text": "def list2string (inlist,delimit=' '):\n    \"\"\"\nConverts a 1D list to a single long string for file output, using\nthe string.join function.\n\nUsage:   list2string (inlist,delimit=' ')\nReturns: the string created from inlist\n\"\"\"\n    stringlist = [makestr(_) for _ in inlist]\n    return string.join(stringlist,delimit)", "title": ""}
{"_id": "d12083", "text": "def cor(y_true, y_pred):\n    \"\"\"Compute Pearson correlation coefficient.\n    \"\"\"\n    y_true, y_pred = _mask_nan(y_true, y_pred)\n    return np.corrcoef(y_true, y_pred)[0, 1]", "title": ""}
{"_id": "d12084", "text": "def is_string(obj):\n    \"\"\"Is this a string.\n\n    :param object obj:\n    :rtype: bool\n    \"\"\"\n    if PYTHON3:\n        str_type = (bytes, str)\n    else:\n        str_type = (bytes, str, unicode)\n    return isinstance(obj, str_type)", "title": ""}
{"_id": "d12085", "text": "def extract_module_locals(depth=0):\n    \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n    f = sys._getframe(depth + 1)\n    global_ns = f.f_globals\n    module = sys.modules[global_ns['__name__']]\n    return (module, f.f_locals)", "title": ""}
{"_id": "d12086", "text": "def polite_string(a_string):\n    \"\"\"Returns a \"proper\" string that should work in both Py3/Py2\"\"\"\n    if is_py3() and hasattr(a_string, 'decode'):\n        try:\n            return a_string.decode('utf-8')\n        except UnicodeDecodeError:\n            return a_string\n\n    return a_string", "title": ""}
{"_id": "d12087", "text": "def clearImg(self):\n        \"\"\"Clears the current image\"\"\"\n        self.img.setImage(np.array([[0]]))\n        self.img.image = None", "title": ""}
{"_id": "d12088", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d12089", "text": "def turn(self):\n        \"\"\"Turn the ring for a single position.\n        For example, [a, b, c, d] becomes [b, c, d, a].\"\"\"\n        first = self._data.pop(0)\n        self._data.append(first)", "title": ""}
{"_id": "d12090", "text": "def _valid_other_type(x, types):\n    \"\"\"\n    Do all elements of x have a type from types?\n    \"\"\"\n    return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))", "title": ""}
{"_id": "d12091", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d12092", "text": "def sql(self, sql: str, *qmark_params, **named_params):\n        \"\"\"\n        :deprecated: use self.statement to execute properly-formatted sql statements\n        \"\"\"\n        statement = SingleSqlStatement(sql)\n        return self.statement(statement).execute(*qmark_params, **named_params)", "title": ""}
{"_id": "d12093", "text": "def _increment_numeric_suffix(s):\n        \"\"\"Increment (or add) numeric suffix to identifier.\"\"\"\n        if re.match(r\".*\\d+$\", s):\n            return re.sub(r\"\\d+$\", lambda n: str(int(n.group(0)) + 1), s)\n        return s + \"_2\"", "title": ""}
{"_id": "d12094", "text": "def listunion(ListOfLists):\n    \"\"\"\n    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`.\n\n    \"\"\"\n    u = []\n    for s in ListOfLists:\n        if s != None:\n            u.extend(s)\n    return u", "title": ""}
{"_id": "d12095", "text": "def trigger_installed(connection: connection, table: str, schema: str='public'):\n    \"\"\"Test whether or not a psycopg2-pgevents trigger is installed for a table.\n\n    Parameters\n    ----------\n    connection: psycopg2.extensions.connection\n        Active connection to a PostGreSQL database.\n    table: str\n        Table whose trigger-existence will be checked.\n    schema: str\n        Schema to which the table belongs.\n\n    Returns\n    -------\n    bool\n        True if the trigger is installed, otherwise False.\n\n    \"\"\"\n    installed = False\n\n    log('Checking if {}.{} trigger installed...'.format(schema, table), logger_name=_LOGGER_NAME)\n\n    statement = SELECT_TRIGGER_STATEMENT.format(\n        table=table,\n        schema=schema\n    )\n\n    result = execute(connection, statement)\n    if result:\n        installed = True\n\n    log('...{}installed'.format('' if installed else 'NOT '), logger_name=_LOGGER_NAME)\n\n    return installed", "title": ""}
{"_id": "d12096", "text": "def reseed_random(seed):\n    \"\"\"Reseed factory.fuzzy's random generator.\"\"\"\n    r = random.Random(seed)\n    random_internal_state = r.getstate()\n    set_random_state(random_internal_state)", "title": ""}
{"_id": "d12097", "text": "def format_screen(strng):\n    \"\"\"Format a string for screen printing.\n\n    This removes some latex-type format codes.\"\"\"\n    # Paragraph continue\n    par_re = re.compile(r'\\\\$',re.MULTILINE)\n    strng = par_re.sub('',strng)\n    return strng", "title": ""}
{"_id": "d12098", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d12099", "text": "def __copy__(self):\n        \"\"\"A magic method to implement shallow copy behavior.\"\"\"\n        return self.__class__.load(self.dump(), context=self.context)", "title": ""}
{"_id": "d12100", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d12101", "text": "def print_param_values(self_):\n        \"\"\"Print the values of all this object's Parameters.\"\"\"\n        self = self_.self\n        for name,val in self.param.get_param_values():\n            print('%s.%s = %s' % (self.name,name,val))", "title": ""}
{"_id": "d12102", "text": "def _fast_read(self, infile):\n        \"\"\"Function for fast reading from sensor files.\"\"\"\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))", "title": ""}
{"_id": "d12103", "text": "def stack_as_string():\n    \"\"\"\n    stack_as_string\n    \"\"\"\n    if sys.version_info.major == 3:\n        stack = io.StringIO()\n    else:\n        stack = io.BytesIO()\n\n    traceback.print_stack(file=stack)\n    stack.seek(0)\n    stack = stack.read()\n    return stack", "title": ""}
{"_id": "d12104", "text": "def string_to_float_list(string_var):\n        \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n        try:\n            return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n        except:\n            return [float(s) for s in string_var.strip('[').strip(']').split(',')]", "title": ""}
{"_id": "d12105", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d12106", "text": "def url_to_image(url):\n    \"\"\"\n    Fetch an image from url and convert it into a Pillow Image object\n    \"\"\"\n    r = requests.get(url)\n    image = StringIO(r.content)\n    return image", "title": ""}
{"_id": "d12107", "text": "def build_docs(directory):\n    \"\"\"Builds sphinx docs from a given directory.\"\"\"\n    os.chdir(directory)\n    process = subprocess.Popen([\"make\", \"html\"], cwd=directory)\n    process.communicate()", "title": ""}
{"_id": "d12108", "text": "def __init__(self, usb):\n    \"\"\"Constructs a FastbootCommands instance.\n\n    Arguments:\n      usb: UsbHandle instance.\n    \"\"\"\n    self._usb = usb\n    self._protocol = self.protocol_handler(usb)", "title": ""}
{"_id": "d12109", "text": "def __print_table(table):\n        \"\"\"Print a list in tabular format\n        Based on https://stackoverflow.com/a/8356620\"\"\"\n\n        col_width = [max(len(x) for x in col) for col in zip(*table)]\n        print(\"| \" + \" | \".join(\"{:{}}\".format(x, col_width[i])\n                                for i, x in enumerate(table[0])) + \" |\")\n        print(\"| \" + \" | \".join(\"{:{}}\".format('-' * col_width[i], col_width[i])\n                                for i, x in enumerate(table[0])) + \" |\")\n        for line in table[1:]:\n            print(\"| \" + \" | \".join(\"{:{}}\".format(x, col_width[i])\n                                    for i, x in enumerate(line)) + \" |\")", "title": ""}
{"_id": "d12110", "text": "def argmax(l,f=None):\n    \"\"\"http://stackoverflow.com/questions/5098580/implementing-argmax-in-python\"\"\"\n    if f:\n        l = [f(i) for i in l]\n    return max(enumerate(l), key=lambda x:x[1])[0]", "title": ""}
{"_id": "d12111", "text": "def Output(self):\n    \"\"\"Output all sections of the page.\"\"\"\n    self.Open()\n    self.Header()\n    self.Body()\n    self.Footer()", "title": ""}
{"_id": "d12112", "text": "def maxDepth(self, currentDepth=0):\n        \"\"\"Compute the depth of the longest branch of the tree\"\"\"\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", "title": ""}
{"_id": "d12113", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d12114", "text": "def flat_list(lst):\n    \"\"\"This function flatten given nested list.\n    Argument:\n        nested list\n    Returns:\n        flat list\n    \"\"\"\n    if isinstance(lst, list):\n        for item in lst:\n            for i in flat_list(item):\n                yield i\n    else:\n        yield lst", "title": ""}
{"_id": "d12115", "text": "def _stdout_raw(self, s):\n        \"\"\"Writes the string to stdout\"\"\"\n        print(s, end='', file=sys.stdout)\n        sys.stdout.flush()", "title": ""}
{"_id": "d12116", "text": "def _tuple_repr(data):\n    \"\"\"Return a repr() for a list/tuple\"\"\"\n    if len(data) == 1:\n        return \"(%s,)\" % rpr(data[0])\n    else:\n        return \"(%s)\" % \", \".join([rpr(x) for x in data])", "title": ""}
{"_id": "d12117", "text": "def is_managed():\n    \"\"\"\n    Check if a Django project is being managed with ``manage.py`` or\n    ``django-admin`` scripts\n\n    :return: Check result\n    :rtype: bool\n    \"\"\"\n    for item in sys.argv:\n        if re.search(r'manage.py|django-admin|django', item) is not None:\n            return True\n    return False", "title": ""}
{"_id": "d12118", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d12119", "text": "def redirect_stdout(new_stdout):\n    \"\"\"Redirect the stdout\n\n    Args:\n        new_stdout (io.StringIO): New stdout to use instead\n    \"\"\"\n    old_stdout, sys.stdout = sys.stdout, new_stdout\n    try:\n        yield None\n    finally:\n        sys.stdout = old_stdout", "title": ""}
{"_id": "d12120", "text": "def is_palindrome(string, strict=True):\n    \"\"\"\n    Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n    :param string: String to check.\n    :type string: str\n    :param strict: True if white spaces matter (default), false otherwise.\n    :type strict: bool\n    :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\n    False otherwise\n    \"\"\"\n    if is_full_string(string):\n        if strict:\n            return reverse(string) == string\n        return is_palindrome(SPACES_RE.sub('', string))\n    return False", "title": ""}
{"_id": "d12121", "text": "def hstrlen(self, name, key):\n        \"\"\"\n        Return the number of bytes stored in the value of ``key``\n        within hash ``name``\n        \"\"\"\n        with self.pipe as pipe:\n            return pipe.hstrlen(self.redis_key(name), key)", "title": ""}
{"_id": "d12122", "text": "def __call__(self, func, *args, **kwargs):\n        \"\"\"Shorcut for self.run.\"\"\"\n        return self.run(func, *args, **kwargs)", "title": ""}
{"_id": "d12123", "text": "def delete_entry(self, key):\n        \"\"\"Delete an object from the redis table\"\"\"\n        pipe = self.client.pipeline()\n        pipe.srem(self.keys_container, key)\n        pipe.delete(key)\n        pipe.execute()", "title": ""}
{"_id": "d12124", "text": "def toJson(protoObject, indent=None):\n    \"\"\"\n    Serialises a protobuf object as json\n    \"\"\"\n    # Using the internal method because this way we can reformat the JSON\n    js = json_format.MessageToDict(protoObject, False)\n    return json.dumps(js, indent=indent)", "title": ""}
{"_id": "d12125", "text": "def is_standalone(self):\n        \"\"\"Return True if Glances is running in standalone mode.\"\"\"\n        return (not self.args.client and\n                not self.args.browser and\n                not self.args.server and\n                not self.args.webserver)", "title": ""}
{"_id": "d12126", "text": "def AsPrimitiveProto(self):\n    \"\"\"Return an old style protocol buffer object.\"\"\"\n    if self.protobuf:\n      result = self.protobuf()\n      result.ParseFromString(self.SerializeToString())\n      return result", "title": ""}
{"_id": "d12127", "text": "def addfield(self, pkt, buf, val):\n        \"\"\"add the field with endianness to the buffer\"\"\"\n        self.set_endianess(pkt)\n        return self.fld.addfield(pkt, buf, val)", "title": ""}
{"_id": "d12128", "text": "def slugify(s, delimiter='-'):\n    \"\"\"\n    Normalize `s` into ASCII and replace non-word characters with `delimiter`.\n    \"\"\"\n    s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')\n    return RE_SLUG.sub(delimiter, s).strip(delimiter).lower()", "title": ""}
{"_id": "d12129", "text": "def _remove_blank(l):\n        \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n        ret = []\n        for i, _ in enumerate(l):\n            if l[i] == 0:\n                break\n            ret.append(l[i])\n        return ret", "title": ""}
{"_id": "d12130", "text": "def have_pyrex():\n    \"\"\"\n    Return True if Cython or Pyrex can be imported.\n    \"\"\"\n    pyrex_impls = 'Cython.Distutils.build_ext', 'Pyrex.Distutils.build_ext'\n    for pyrex_impl in pyrex_impls:\n        try:\n            # from (pyrex_impl) import build_ext\n            __import__(pyrex_impl, fromlist=['build_ext']).build_ext\n            return True\n        except Exception:\n            pass\n    return False", "title": ""}
{"_id": "d12131", "text": "def reverse_transform(self, col):\n        \"\"\"Converts data back into original format.\n\n        Args:\n            col(pandas.DataFrame): Data to transform.\n\n        Returns:\n            pandas.DataFrame\n        \"\"\"\n\n        output = pd.DataFrame()\n        output[self.col_name] = self.get_category(col[self.col_name])\n\n        return output", "title": ""}
{"_id": "d12132", "text": "def nb_to_python(nb_path):\n    \"\"\"convert notebook to python script\"\"\"\n    exporter = python.PythonExporter()\n    output, resources = exporter.from_filename(nb_path)\n    return output", "title": ""}
{"_id": "d12133", "text": "def unique(transactions):\n    \"\"\" Remove any duplicate entries. \"\"\"\n    seen = set()\n    # TODO: Handle comments\n    return [x for x in transactions if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d12134", "text": "async def iso(self, source):\n        \"\"\"Convert to timestamp.\"\"\"\n        from datetime import datetime\n        unix_timestamp = int(source)\n        return datetime.fromtimestamp(unix_timestamp).isoformat()", "title": ""}
{"_id": "d12135", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d12136", "text": "def timestamp_to_datetime(timestamp):\n    \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n    from datetime import datetime, timedelta\n    obj = datetime.fromtimestamp(timestamp[0])\n    return obj + timedelta(microseconds=int(timestamp[1]))", "title": ""}
{"_id": "d12137", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d12138", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d12139", "text": "def unapostrophe(text):\n    \"\"\"Strip apostrophe and 's' from the end of a string.\"\"\"\n    text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)\n    return text", "title": ""}
{"_id": "d12140", "text": "def is_sparse_vector(x):\n    \"\"\" x is a 2D sparse matrix with it's first shape equal to 1.\n    \"\"\"\n    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1", "title": ""}
{"_id": "d12141", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d12142", "text": "def slugify(string):\n    \"\"\"\n    Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n    \"\"\"\n    string = re.sub('[^\\w .-]', '', string)\n    string = string.replace(\" \", \"-\")\n    return string", "title": ""}
{"_id": "d12143", "text": "def command_py2to3(args):\n    \"\"\"\n    Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n    \"\"\"\n    from lib2to3.main import main\n    sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "title": ""}
{"_id": "d12144", "text": "def _removeStopwords(text_list):\n    \"\"\"\n    Removes stopwords contained in a list of words.\n\n    :param text_string: A list of strings.\n    :type text_string: list.\n\n    :returns: The input ``text_list`` with stopwords removed.\n    :rtype: list\n    \"\"\"\n\n    output_list = []\n\n    for word in text_list:\n        if word.lower() not in _stopwords:\n            output_list.append(word)\n\n    return output_list", "title": ""}
{"_id": "d12145", "text": "def apply_argument_parser(argumentsParser, options=None):\n    \"\"\" Apply the argument parser. \"\"\"\n    if options is not None:\n        args = argumentsParser.parse_args(options)\n    else:\n        args = argumentsParser.parse_args()\n    return args", "title": ""}
{"_id": "d12146", "text": "def synthesize(self, duration):\n        \"\"\"\n        Synthesize white noise\n\n        Args:\n            duration (numpy.timedelta64): The duration of the synthesized sound\n        \"\"\"\n        sr = self.samplerate.samples_per_second\n        seconds = duration / Seconds(1)\n        samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n        return AudioSamples(samples, self.samplerate)", "title": ""}
{"_id": "d12147", "text": "def _is_readable(self, obj):\n        \"\"\"Check if the argument is a readable file-like object.\"\"\"\n        try:\n            read = getattr(obj, 'read')\n        except AttributeError:\n            return False\n        else:\n            return is_method(read, max_arity=1)", "title": ""}
{"_id": "d12148", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d12149", "text": "def get_attr(self, method_name):\n        \"\"\"Get attribute from the target object\"\"\"\n        return self.attrs.get(method_name) or self.get_callable_attr(method_name)", "title": ""}
{"_id": "d12150", "text": "def convert_tstamp(response):\n\t\"\"\"\n\tConvert a Stripe API timestamp response (unix epoch) to a native datetime.\n\n\t:rtype: datetime\n\t\"\"\"\n\tif response is None:\n\t\t# Allow passing None to convert_tstamp()\n\t\treturn response\n\n\t# Overrides the set timezone to UTC - I think...\n\ttz = timezone.utc if settings.USE_TZ else None\n\n\treturn datetime.datetime.fromtimestamp(response, tz)", "title": ""}
{"_id": "d12151", "text": "def isstring(value):\n    \"\"\"Report whether the given value is a byte or unicode string.\"\"\"\n    classes = (str, bytes) if pyutils.PY3 else basestring  # noqa: F821\n    return isinstance(value, classes)", "title": ""}
{"_id": "d12152", "text": "def timed_rotating_file_handler(name, logname, filename, when='h',\n                                interval=1, backupCount=0,\n                                encoding=None, delay=False, utc=False):\n    \"\"\"\n    A Bark logging handler logging output to a named file.  At\n    intervals specified by the 'when', the file will be rotated, under\n    control of 'backupCount'.\n\n    Similar to logging.handlers.TimedRotatingFileHandler.\n    \"\"\"\n\n    return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n        filename, when=when, interval=interval, backupCount=backupCount,\n        encoding=encoding, delay=delay, utc=utc))", "title": ""}
{"_id": "d12153", "text": "def columnclean(column):\n        \"\"\"\n        Modifies column header format to be importable into a database\n        :param column: raw column header\n        :return: cleanedcolumn: reformatted column header\n        \"\"\"\n        cleanedcolumn = str(column) \\\n            .replace('%', 'percent') \\\n            .replace('(', '_') \\\n            .replace(')', '') \\\n            .replace('As', 'Adenosines') \\\n            .replace('Cs', 'Cytosines') \\\n            .replace('Gs', 'Guanines') \\\n            .replace('Ts', 'Thymines') \\\n            .replace('Ns', 'Unknowns') \\\n            .replace('index', 'adapterIndex')\n        return cleanedcolumn", "title": ""}
{"_id": "d12154", "text": "def csv_to_dicts(file, header=None):\n    \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n    with open(file) as csvfile:\n        return [row for row in csv.DictReader(csvfile, fieldnames=header)]", "title": ""}
{"_id": "d12155", "text": "def _parallel_compare_helper(class_obj, pairs, x, x_link=None):\n    \"\"\"Internal function to overcome pickling problem in python2.\"\"\"\n    return class_obj._compute(pairs, x, x_link)", "title": ""}
{"_id": "d12156", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d12157", "text": "def is_iterable(obj):\n    \"\"\"\n    Are we being asked to look up a list of things, instead of a single thing?\n    We check for the `__iter__` attribute so that this can cover types that\n    don't have to be known by this module, such as NumPy arrays.\n\n    Strings, however, should be considered as atomic values to look up, not\n    iterables. The same goes for tuples, since they are immutable and therefore\n    valid entries.\n\n    We don't need to check for the Python 2 `unicode` type, because it doesn't\n    have an `__iter__` attribute anyway.\n    \"\"\"\n    return (\n        hasattr(obj, \"__iter__\")\n        and not isinstance(obj, str)\n        and not isinstance(obj, tuple)\n    )", "title": ""}
{"_id": "d12158", "text": "def _to_lower_alpha_only(s):\n    \"\"\"Return a lowercased string with non alphabetic chars removed.\n\n    White spaces are not to be removed.\"\"\"\n    s = re.sub(r'\\n', ' ',  s.lower())\n    return re.sub(r'[^a-z\\s]', '', s)", "title": ""}
{"_id": "d12159", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d12160", "text": "def strip_tweet(text, remove_url=True):\n    \"\"\"Strip tweet message.\n\n    This method removes mentions strings and urls(optional).\n\n    :param text: tweet message\n    :type text: :class:`str`\n\n    :param remove_url: Remove urls. default :const:`True`.\n    :type remove_url: :class:`boolean`\n\n    :returns: Striped tweet message\n    :rtype: :class:`str`\n\n    \"\"\"\n    if remove_url:\n        text = url_pattern.sub('', text)\n    else:\n        text = expand_url(text)\n    text = mention_pattern.sub('', text)\n    text = html_parser.unescape(text)\n    text = text.strip()\n    return text", "title": ""}
{"_id": "d12161", "text": "def dedupe(items):\n    \"\"\"Remove duplicates from a sequence (of hashable items) while maintaining\n    order. NOTE: This only works if items in the list are hashable types.\n\n    Taken from the Python Cookbook, 3rd ed. Such a great book!\n\n    \"\"\"\n    seen = set()\n    for item in items:\n        if item not in seen:\n            yield item\n            seen.add(item)", "title": ""}
{"_id": "d12162", "text": "def strip_xml_namespace(root):\n    \"\"\"Strip out namespace data from an ElementTree.\n\n    This function is recursive and will traverse all\n    subnodes to the root element\n\n    @param root: the root element\n\n    @return: the same root element, minus namespace\n    \"\"\"\n    try:\n        root.tag = root.tag.split('}')[1]\n    except IndexError:\n        pass\n\n    for element in root.getchildren():\n        strip_xml_namespace(element)", "title": ""}
{"_id": "d12163", "text": "def _get_printable_columns(columns, row):\n    \"\"\"Return only the part of the row which should be printed.\n    \"\"\"\n    if not columns:\n        return row\n\n    # Extract the column values, in the order specified.\n    return tuple(row[c] for c in columns)", "title": ""}
{"_id": "d12164", "text": "def split_comma_argument(comma_sep_str):\n    \"\"\"Split a comma separated option into a list.\"\"\"\n    terms = []\n    for term in comma_sep_str.split(','):\n        if term:\n            terms.append(term)\n    return terms", "title": ""}
{"_id": "d12165", "text": "def makeBiDirectional(d):\n    \"\"\"\n    Helper for generating tagNameConverter\n    Makes dict that maps from key to value and back\n    \"\"\"\n    dTmp = d.copy()\n    for k in d:\n        dTmp[d[k]] = k\n    return dTmp", "title": ""}
{"_id": "d12166", "text": "def getfirstline(file, default):\n    \"\"\"\n    Returns the first line of a file.\n    \"\"\"\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\n    return default", "title": ""}
{"_id": "d12167", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d12168", "text": "def dict_keys_without_hyphens(a_dict):\n    \"\"\"Return the a new dict with underscores instead of hyphens in keys.\"\"\"\n    return dict(\n        (key.replace('-', '_'), val) for key, val in a_dict.items())", "title": ""}
{"_id": "d12169", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d12170", "text": "def fmt_subst(regex, subst):\n    \"\"\"Replace regex with string.\"\"\"\n    return lambda text: re.sub(regex, subst, text) if text else text", "title": ""}
{"_id": "d12171", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d12172", "text": "def test_kwargs_are_optional(self):\n        \"\"\"kwarg values always have defaults\"\"\"\n        with patch(\"sys.exit\") as mock_exit:\n            cli = MicroCLITestCase.T(\"script_name f3\".split()).run()\n            # kwargs are optional\n            mock_exit.assert_called_with(4)", "title": ""}
{"_id": "d12173", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d12174", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d12175", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d12176", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d12177", "text": "def unique(iterable):\n    \"\"\" Returns a list copy in which each item occurs only once (in-order).\n    \"\"\"\n    seen = set()\n    return [x for x in iterable if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d12178", "text": "def fillScreen(self, color=None):\n        \"\"\"Fill the matrix with the given RGB color\"\"\"\n        md.fill_rect(self.set, 0, 0, self.width, self.height, color)", "title": ""}
{"_id": "d12179", "text": "def loads(s, model=None, parser=None):\n    \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n    with StringIO(s) as f:\n        return load(f, model=model, parser=parser)", "title": ""}
{"_id": "d12180", "text": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "title": ""}
{"_id": "d12181", "text": "def __unroll(self, rolled):\n        \"\"\"Converts parameter matrices into an array.\"\"\"\n        return np.array(np.concatenate([matrix.flatten() for matrix in rolled], axis=1)).reshape(-1)", "title": ""}
{"_id": "d12182", "text": "def next(self):\n        \"\"\"Get the next value in the page.\"\"\"\n        item = six.next(self._item_iter)\n        result = self._item_to_value(self._parent, item)\n        # Since we've successfully got the next value from the\n        # iterator, we update the number of remaining.\n        self._remaining -= 1\n        return result", "title": ""}
{"_id": "d12183", "text": "def batchify(data, batch_size):\n    \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n    nbatch = data.shape[0] // batch_size\n    data = data[:nbatch * batch_size]\n    data = data.reshape((batch_size, nbatch)).T\n    return data", "title": ""}
{"_id": "d12184", "text": "def move_datetime_year(dt, direction, num_shifts):\n    \"\"\"\n    Move datetime 1 year in the chosen direction.\n    unit is a no-op, to keep the API the same as the day case\n    \"\"\"\n    delta = relativedelta(years=+num_shifts)\n    return _move_datetime(dt, direction, delta)", "title": ""}
{"_id": "d12185", "text": "def downgrade():\n    \"\"\"Downgrade database.\"\"\"\n    op.drop_table('transaction')\n    if op._proxy.migration_context.dialect.supports_sequences:\n        op.execute(DropSequence(Sequence('transaction_id_seq')))", "title": ""}
{"_id": "d12186", "text": "def uncomment_line(line, prefix):\n    \"\"\"Remove prefix (and space) from line\"\"\"\n    if not prefix:\n        return line\n    if line.startswith(prefix + ' '):\n        return line[len(prefix) + 1:]\n    if line.startswith(prefix):\n        return line[len(prefix):]\n    return line", "title": ""}
{"_id": "d12187", "text": "def get(self, key):  \n        \"\"\" get a set of keys from redis \"\"\"\n        res = self.connection.get(key)\n        print(res)\n        return res", "title": ""}
{"_id": "d12188", "text": "def iparallel_progbar(mapper, iterable, nprocs=None, starmap=False, flatmap=False, shuffle=False,\n                      verbose=True, verbose_flatmap=None, max_cache=-1, **kwargs):\n    \"\"\"Performs a parallel mapping of the given iterable, reporting a progress bar as values get returned. Yields\n    objects as soon as they're computed, but does not guarantee that they'll be in the correct order.\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 max_cache: Maximum number of mapped objects to permit in the queue at once\n    :param kwargs: Any other keyword arguments to pass to the progress bar (see ``progbar``)\n    :return: A list of the returned objects, in whatever order they're done being computed\n    \"\"\"\n\n    results = _parallel_progbar_launch(mapper, iterable, nprocs, starmap, flatmap, shuffle, verbose,\n                                       verbose_flatmap, max_cache, **kwargs)\n    return (x for i, x in results)", "title": ""}
{"_id": "d12189", "text": "def resource_property(klass, name, **kwargs):\n    \"\"\"Builds a resource object property.\"\"\"\n    klass.PROPERTIES[name] = kwargs\n\n    def getter(self):\n        return getattr(self, '_%s' % name, kwargs.get('default', None))\n\n    if kwargs.get('readonly', False):\n        setattr(klass, name, property(getter))\n    else:\n        def setter(self, value):\n            setattr(self, '_%s' % name, value)\n        setattr(klass, name, property(getter, setter))", "title": ""}
{"_id": "d12190", "text": "def get_single_file_info(self, rel_path):\n        \"\"\" Gets last change time for a single file \"\"\"\n\n        f_path = self.get_full_file_path(rel_path)\n        return get_single_file_info(f_path, rel_path)", "title": ""}
{"_id": "d12191", "text": "def block(seed):\n    \"\"\" 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\n    \"\"\"\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)", "title": ""}
{"_id": "d12192", "text": "def get_Callable_args_res(clb):\n    \"\"\"Python version independent function to obtain the parameters\n    of a typing.Callable object. Returns as tuple: args, result.\n    Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.\n    \"\"\"\n    try:\n        return clb.__args__, clb.__result__\n    except AttributeError:\n        # Python 3.6\n        return clb.__args__[:-1], clb.__args__[-1]", "title": ""}
{"_id": "d12193", "text": "def classnameify(s):\n  \"\"\"\n  Makes a classname\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))", "title": ""}
{"_id": "d12194", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d12195", "text": "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d12196", "text": "def __repr__(self):\n    \"\"\"Returns a stringified representation of this object.\"\"\"\n    return str({'name': self._name, 'watts': self._watts,\n                'type': self._output_type, 'id': self._integration_id})", "title": ""}
{"_id": "d12197", "text": "def _config_win32_domain(self, domain):\n        \"\"\"Configure a Domain registry entry.\"\"\"\n        # we call str() on domain to convert it from unicode to ascii\n        self.domain = dns.name.from_text(str(domain))", "title": ""}
{"_id": "d12198", "text": "def getBuffer(x):\n    \"\"\"\n    Copy @x into a (modifiable) ctypes byte array\n    \"\"\"\n    b = bytes(x)\n    return (c_ubyte * len(b)).from_buffer_copy(bytes(x))", "title": ""}
{"_id": "d12199", "text": "def align_to_mmap(num, round_up):\n    \"\"\"\n    Align the given integer number to the closest page offset, which usually is 4096 bytes.\n\n    :param round_up: if True, the next higher multiple of page size is used, otherwise\n        the lower page_size will be used (i.e. if True, 1 becomes 4096, otherwise it becomes 0)\n    :return: num rounded to closest page\"\"\"\n    res = (num // ALLOCATIONGRANULARITY) * ALLOCATIONGRANULARITY\n    if round_up and (res != num):\n        res += ALLOCATIONGRANULARITY\n    # END handle size\n    return res", "title": ""}
{"_id": "d12200", "text": "def series_index(self, series):\n        \"\"\"\n        Return the integer index of *series* in this sequence.\n        \"\"\"\n        for idx, s in enumerate(self):\n            if series is s:\n                return idx\n        raise ValueError('series not in chart data object')", "title": ""}
{"_id": "d12201", "text": "def unpickle_stats(stats):\n    \"\"\"Unpickle a pstats.Stats object\"\"\"\n    stats = cPickle.loads(stats)\n    stats.stream = True\n    return stats", "title": ""}
{"_id": "d12202", "text": "def _elapsed(self):\n        \"\"\" Returns elapsed time at update. \"\"\"\n        self.last_time = time.time()\n        return self.last_time - self.start", "title": ""}
{"_id": "d12203", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d12204", "text": "def angle(x, y):\n    \"\"\"Return the angle between vectors a and b in degrees.\"\"\"\n    return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi", "title": ""}
{"_id": "d12205", "text": "def get_attribute_name_id(attr):\n    \"\"\"\n    Return the attribute name identifier\n    \"\"\"\n    return attr.value.id if isinstance(attr.value, ast.Name) else None", "title": ""}
{"_id": "d12206", "text": "def angle(x, y):\n    \"\"\"Return the angle between vectors a and b in degrees.\"\"\"\n    return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi", "title": ""}
{"_id": "d12207", "text": "def transform_to_3d(points,normal,z=0):\n    \"\"\"Project points into 3d from 2d points.\"\"\"\n    d = np.cross(normal, (0, 0, 1))\n    M = rotation_matrix(d)\n    transformed_points = M.dot(points.T).T + z\n    return transformed_points", "title": ""}
{"_id": "d12208", "text": "def _visual_width(line):\n    \"\"\"Get the the number of columns required to display a string\"\"\"\n\n    return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, \"\", line))", "title": ""}
{"_id": "d12209", "text": "def SegmentMin(a, ids):\n    \"\"\"\n    Segmented min op.\n    \"\"\"\n    func = lambda idxs: np.amin(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d12210", "text": "def similarity_transformation(rot, mat):\n    \"\"\" R x M x R^-1 \"\"\"\n    return np.dot(rot, np.dot(mat, np.linalg.inv(rot)))", "title": ""}
{"_id": "d12211", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d12212", "text": "def add_option(self, *args, **kwargs):\n        \"\"\"Add optparse or argparse option depending on CmdHelper initialization.\"\"\"\n        if self.parseTool == 'argparse':\n            if args and args[0] == '':   # no short option\n                args = args[1:]\n            return self.parser.add_argument(*args, **kwargs)\n        else:\n            return self.parser.add_option(*args, **kwargs)", "title": ""}
{"_id": "d12213", "text": "def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):\n    \"\"\" Rotates an image by deg degrees\n\n    Arguments:\n        deg (float): degree to rotate.\n    \"\"\"\n    r,c,*_ = im.shape\n    M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)\n    return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation)", "title": ""}
{"_id": "d12214", "text": "def help(self, level=0):\n        \"\"\"return the usage string for available options \"\"\"\n        self.cmdline_parser.formatter.output_level = level\n        with _patch_optparse():\n            return self.cmdline_parser.format_help()", "title": ""}
{"_id": "d12215", "text": "def __round_time(self, dt):\n    \"\"\"Round a datetime object to a multiple of a timedelta\n    dt : datetime.datetime object, default now.\n    \"\"\"\n    round_to = self._resolution.total_seconds()\n    seconds  = (dt - dt.min).seconds\n    rounding = (seconds + round_to / 2) // round_to * round_to\n    return dt + timedelta(0, rounding - seconds, -dt.microsecond)", "title": ""}
{"_id": "d12216", "text": "def add_to_parser(self, parser):\n        \"\"\"\n        Adds the argument to an argparse.ArgumentParser instance\n\n        @param parser An argparse.ArgumentParser instance\n        \"\"\"\n        kwargs = self._get_kwargs()\n        args = self._get_args()\n        parser.add_argument(*args, **kwargs)", "title": ""}
{"_id": "d12217", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d12218", "text": "def _add_default_arguments(parser):\n    \"\"\"Add the default arguments to the parser.\n\n    :param argparse.ArgumentParser parser: The argument parser\n\n    \"\"\"\n    parser.add_argument('-c', '--config', action='store', dest='config',\n                        help='Path to the configuration file')\n    parser.add_argument('-f', '--foreground', action='store_true', dest='foreground',\n                        help='Run the application interactively')", "title": ""}
{"_id": "d12219", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d12220", "text": "def email_type(arg):\n\t\"\"\"An argparse type representing an email address.\"\"\"\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", "title": ""}
{"_id": "d12221", "text": "def jupytext_cli(args=None):\n    \"\"\"Entry point for the jupytext script\"\"\"\n    try:\n        jupytext(args)\n    except (ValueError, TypeError, IOError) as err:\n        sys.stderr.write('[jupytext] Error: ' + str(err) + '\\n')\n        exit(1)", "title": ""}
{"_id": "d12222", "text": "def build_parser():\n    \"\"\"Build argument parsers.\"\"\"\n\n    parser = argparse.ArgumentParser(\"Release packages to pypi\")\n    parser.add_argument('--check', '-c', action=\"store_true\", help=\"Do a dry run without uploading\")\n    parser.add_argument('component', help=\"The component to release as component-version\")\n    return parser", "title": ""}
{"_id": "d12223", "text": "def jupytext_cli(args=None):\n    \"\"\"Entry point for the jupytext script\"\"\"\n    try:\n        jupytext(args)\n    except (ValueError, TypeError, IOError) as err:\n        sys.stderr.write('[jupytext] Error: ' + str(err) + '\\n')\n        exit(1)", "title": ""}
{"_id": "d12224", "text": "def _is_one_arg_pos_call(call):\n    \"\"\"Is this a call with exactly 1 argument,\n    where that argument is positional?\n    \"\"\"\n    return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords", "title": ""}
{"_id": "d12225", "text": "async def unignore_all(self, ctx):\n        \"\"\"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.\n        \"\"\"\n        channels = [c for c in ctx.message.server.channels if c.type is discord.ChannelType.text]\n        await ctx.invoke(self.unignore, *channels)", "title": ""}
{"_id": "d12226", "text": "def getbyteslice(self, start, end):\n        \"\"\"Direct access to byte data.\"\"\"\n        c = self._rawarray[start:end]\n        return c", "title": ""}
{"_id": "d12227", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d12228", "text": "def getbyteslice(self, start, end):\n        \"\"\"Direct access to byte data.\"\"\"\n        c = self._rawarray[start:end]\n        return c", "title": ""}
{"_id": "d12229", "text": "def save_pdf(path):\n  \"\"\"\n  Saves a pdf of the current matplotlib figure.\n\n  :param path: str, filepath to save to\n  \"\"\"\n\n  pp = PdfPages(path)\n  pp.savefig(pyplot.gcf())\n  pp.close()", "title": ""}
{"_id": "d12230", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d12231", "text": "def save_pdf(path):\n  \"\"\"\n  Saves a pdf of the current matplotlib figure.\n\n  :param path: str, filepath to save to\n  \"\"\"\n\n  pp = PdfPages(path)\n  pp.savefig(pyplot.gcf())\n  pp.close()", "title": ""}
{"_id": "d12232", "text": "def resize(self):\n        \"\"\"\n        Get target size for a cropped image and do the resizing if we got\n        anything usable.\n        \"\"\"\n        resized_size = self.get_resized_size()\n        if not resized_size:\n            return\n\n        self.image = self.image.resize(resized_size, Image.ANTIALIAS)", "title": ""}
{"_id": "d12233", "text": "def read_full(stream):\n    \"\"\"Read the full contents of the given stream into memory.\n\n    :return:\n        A future containing the complete stream contents.\n    \"\"\"\n    assert stream, \"stream is required\"\n\n    chunks = []\n    chunk = yield stream.read()\n\n    while chunk:\n        chunks.append(chunk)\n        chunk = yield stream.read()\n\n    raise tornado.gen.Return(b''.join(chunks))", "title": ""}
{"_id": "d12234", "text": "def list_to_csv(my_list, csv_file):\n    \"\"\"\n    Save a matrix (list of lists) to a file as a CSV\n\n    .. code:: python\n\n        my_list = [[\"Name\", \"Location\"],\n                   [\"Chris\", \"South Pole\"],\n                   [\"Harry\", \"Depth of Winter\"],\n                   [\"Bob\", \"Skull\"]]\n\n        reusables.list_to_csv(my_list, \"example.csv\")\n\n    example.csv\n\n    .. code:: csv\n\n        \"Name\",\"Location\"\n        \"Chris\",\"South Pole\"\n        \"Harry\",\"Depth of Winter\"\n        \"Bob\",\"Skull\"\n\n    :param my_list: list of lists to save to CSV\n    :param csv_file: File to save data to\n    \"\"\"\n    if PY3:\n        csv_handler = open(csv_file, 'w', newline='')\n    else:\n        csv_handler = open(csv_file, 'wb')\n\n    try:\n        writer = csv.writer(csv_handler, delimiter=',', quoting=csv.QUOTE_ALL)\n        writer.writerows(my_list)\n    finally:\n        csv_handler.close()", "title": ""}
{"_id": "d12235", "text": "def StringIO(*args, **kwargs):\n    \"\"\"StringIO constructor shim for the async wrapper.\"\"\"\n    raw = sync_io.StringIO(*args, **kwargs)\n    return AsyncStringIOWrapper(raw)", "title": ""}
{"_id": "d12236", "text": "def _nth(arr, n):\n    \"\"\"\n    Return the nth value of array\n\n    If it is missing return NaN\n    \"\"\"\n    try:\n        return arr.iloc[n]\n    except (KeyError, IndexError):\n        return np.nan", "title": ""}
{"_id": "d12237", "text": "def test_kwargs_are_optional(self):\n        \"\"\"kwarg values always have defaults\"\"\"\n        with patch(\"sys.exit\") as mock_exit:\n            cli = MicroCLITestCase.T(\"script_name f3\".split()).run()\n            # kwargs are optional\n            mock_exit.assert_called_with(4)", "title": ""}
{"_id": "d12238", "text": "def sent2features(sentence, template):\n    \"\"\" extract features in a sentence\n\n    :type sentence: list of token, each token is a list of tag\n    \"\"\"\n    return [word2features(sentence, i, template) for i in range(len(sentence))]", "title": ""}
{"_id": "d12239", "text": "def dispatch(self):\n    \"\"\"Wraps the dispatch method to add session support.\"\"\"\n    try:\n      webapp2.RequestHandler.dispatch(self)\n    finally:\n      self.session_store.save_sessions(self.response)", "title": ""}
{"_id": "d12240", "text": "def close(*args, **kwargs):\n    r\"\"\"Close last created figure, alias to ``plt.close()``.\"\"\"\n    _, plt, _ = _import_plt()\n    plt.close(*args, **kwargs)", "title": ""}
{"_id": "d12241", "text": "def setDictDefaults (d, defaults):\n  \"\"\"Sets all defaults for the given dictionary to those contained in a\n  second defaults dictionary.  This convenience method calls:\n\n    d.setdefault(key, value)\n\n  for each key and value in the given defaults dictionary.\n  \"\"\"\n  for key, val in defaults.items():\n    d.setdefault(key, val)\n\n  return d", "title": ""}
{"_id": "d12242", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d12243", "text": "def table_width(self):\n        \"\"\"Return the width of the table including padding and borders.\"\"\"\n        outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]\n        outer_border = 2 if self.outer_border else 0\n        inner_border = 1 if self.inner_column_border else 0\n        return table_width(outer_widths, outer_border, inner_border)", "title": ""}
{"_id": "d12244", "text": "def decode_arr(data):\n    \"\"\"Extract a numpy array from a base64 buffer\"\"\"\n    data = data.encode('utf-8')\n    return frombuffer(base64.b64decode(data), float64)", "title": ""}
{"_id": "d12245", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d12246", "text": "def generate(env):\n    \"\"\"Add Builders and construction variables for SGI MIPS C++ to an Environment.\"\"\"\n\n    cplusplus.generate(env)\n\n    env['CXX']         = 'CC'\n    env['CXXFLAGS']    = SCons.Util.CLVar('-LANG:std')\n    env['SHCXX']       = '$CXX'\n    env['SHOBJSUFFIX'] = '.o'\n    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1", "title": ""}
{"_id": "d12247", "text": "def set_xticks_for_all(self, row_column_list=None, ticks=None):\n        \"\"\"Manually specify the x-axis tick values.\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\n        :param ticks: list of tick values.\n\n        \"\"\"\n        if row_column_list is None:\n            self.ticks['x'] = ticks\n        else:\n            for row, column in row_column_list:\n                self.set_xticks(row, column, ticks)", "title": ""}
{"_id": "d12248", "text": "def log_request(self, code='-', size='-'):\n        \"\"\"Selectively log an accepted request.\"\"\"\n\n        if self.server.logRequests:\n            BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)", "title": ""}
{"_id": "d12249", "text": "def get_var(name, factory=None):\n    \"\"\"Gets a global variable given its name.\n\n    If factory is not None and the variable is not set, factory\n    is a callable that will set the variable.\n\n    If not set, returns None.\n    \"\"\"\n    if name not in _VARS and factory is not None:\n        _VARS[name] = factory()\n    return _VARS.get(name)", "title": ""}
{"_id": "d12250", "text": "def serve_dtool_directory(directory, port):\n    \"\"\"Serve the datasets in a directory over HTTP.\"\"\"\n    os.chdir(directory)\n    server_address = (\"localhost\", port)\n    httpd = DtoolHTTPServer(server_address, DtoolHTTPRequestHandler)\n    httpd.serve_forever()", "title": ""}
{"_id": "d12251", "text": "def visit_Str(self, node):\n        \"\"\" Set the pythonic string type. \"\"\"\n        self.result[node] = self.builder.NamedType(pytype_to_ctype(str))", "title": ""}
{"_id": "d12252", "text": "def get_anchor_href(markup):\n    \"\"\"\n    Given HTML markup, return a list of hrefs for each anchor tag.\n    \"\"\"\n    soup = BeautifulSoup(markup, 'lxml')\n    return ['%s' % link.get('href') for link in soup.find_all('a')]", "title": ""}
{"_id": "d12253", "text": "def optional(self, value = None):\n\t\t\"\"\"Optional\n\n\t\tGetter/Setter method for optional flag\n\n\t\tArgs:\n\t\t\tvalue (bool): If set, the method is a setter\n\n\t\tReturns:\n\t\t\tbool | None\n\t\t\"\"\"\n\n\t\t# If there's no value, this is a getter\n\t\tif value is None:\n\t\t\treturn this._optional\n\n\t\t# Else, set the flag\n\t\telse:\n\t\t\tthis._optional = value and True or False", "title": ""}
{"_id": "d12254", "text": "def into2dBlocks(arr, n0, n1):\n    \"\"\"\n    similar to blockshaped\n    but splits an array into n0*n1 blocks\n    \"\"\"\n    s0, s1 = arr.shape\n    b = blockshaped(arr, s0// n0, s1// n1)\n    return b.reshape(n0, n1, *b.shape[1:])", "title": ""}
{"_id": "d12255", "text": "def _EnforceProcessMemoryLimit(self, memory_limit):\n    \"\"\"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.\n    \"\"\"\n    # Resource is not supported on Windows.\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\n      resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))", "title": ""}
{"_id": "d12256", "text": "def get_code_language(self):\n        \"\"\"\n        This is largely copied from bokeh.sphinxext.bokeh_plot.run\n        \"\"\"\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\"]", "title": ""}
{"_id": "d12257", "text": "def libpath(self):\n        \"\"\"Returns the full path to the shared *wrapper* library created for the\n        module.\n        \"\"\"\n        from os import path\n        return path.join(self.dirpath, self.libname)", "title": ""}
{"_id": "d12258", "text": "def arg_bool(name, default=False):\n    \"\"\" Fetch a query argument, as a boolean. \"\"\"\n    v = request.args.get(name, '')\n    if not len(v):\n        return default\n    return v in BOOL_TRUISH", "title": ""}
{"_id": "d12259", "text": "def inject_into_urllib3():\n    \"\"\"\n    Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n    \"\"\"\n    util.ssl_.SSLContext = SecureTransportContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_SECURETRANSPORT = True\n    util.ssl_.IS_SECURETRANSPORT = True", "title": ""}
{"_id": "d12260", "text": "def _type_bool(label,default=False):\n    \"\"\"Shortcut fot boolean like fields\"\"\"\n    return label, abstractSearch.nothing, abstractRender.boolen, default", "title": ""}
{"_id": "d12261", "text": "def move_datetime_year(dt, direction, num_shifts):\n    \"\"\"\n    Move datetime 1 year in the chosen direction.\n    unit is a no-op, to keep the API the same as the day case\n    \"\"\"\n    delta = relativedelta(years=+num_shifts)\n    return _move_datetime(dt, direction, delta)", "title": ""}
{"_id": "d12262", "text": "def get_as_bytes(self, s3_path):\n        \"\"\"\n        Get the contents of an object stored in S3 as bytes\n\n        :param s3_path: URL for target S3 location\n        :return: File contents as pure bytes\n        \"\"\"\n        (bucket, key) = self._path_to_bucket_and_key(s3_path)\n        obj = self.s3.Object(bucket, key)\n        contents = obj.get()['Body'].read()\n        return contents", "title": ""}
{"_id": "d12263", "text": "def to_unicode_repr( _letter ):\n    \"\"\" helpful in situations where browser/app may recognize Unicode encoding\n        in the \\u0b8e type syntax but not actual unicode glyph/code-point\"\"\"\n    # Python 2-3 compatible\n    return u\"u'\"+ u\"\".join( [ u\"\\\\u%04x\"%ord(l) for l in _letter ] ) + u\"'\"", "title": ""}
{"_id": "d12264", "text": "def list_rds(region, filter_by_kwargs):\n    \"\"\"List all RDS thingys.\"\"\"\n    conn = boto.rds.connect_to_region(region)\n    instances = conn.get_all_dbinstances()\n    return lookup(instances, filter_by=filter_by_kwargs)", "title": ""}
{"_id": "d12265", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d12266", "text": "def _shuffle(data, idx):\n    \"\"\"Shuffle the data.\"\"\"\n    shuffle_data = []\n\n    for idx_k, idx_v in data:\n        shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context)))\n\n    return shuffle_data", "title": ""}
{"_id": "d12267", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d12268", "text": "def RandomShuffle(a, seed):\n    \"\"\"\n    Random uniform op.\n    \"\"\"\n    if seed:\n        np.random.seed(seed)\n    r = a.copy()\n    np.random.shuffle(r)\n    return r,", "title": ""}
{"_id": "d12269", "text": "def md_to_text(content):\n    \"\"\" Converts markdown content to text \"\"\"\n    text = None\n    html = markdown.markdown(content)\n    if html:\n        text = html_to_text(content)\n    return text", "title": ""}
{"_id": "d12270", "text": "def day_to_month(timeperiod):\n    \"\"\":param timeperiod: as string in YYYYMMDD00 format\n    :return string in YYYYMM0000 format\"\"\"\n    t = datetime.strptime(timeperiod, SYNERGY_DAILY_PATTERN)\n    return t.strftime(SYNERGY_MONTHLY_PATTERN)", "title": ""}
{"_id": "d12271", "text": "def barray(iterlines):\n    \"\"\"\n    Array of bytes\n    \"\"\"\n    lst = [line.encode('utf-8') for line in iterlines]\n    arr = numpy.array(lst)\n    return arr", "title": ""}
{"_id": "d12272", "text": "def partition(a, sz): \n    \"\"\"splits iterables a in equal parts of size sz\"\"\"\n    return [a[i:i+sz] for i in range(0, len(a), sz)]", "title": ""}
{"_id": "d12273", "text": "def string_to_int( s ):\n  \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n  result = 0\n  for c in s:\n    if not isinstance(c, int): c = ord( c )\n    result = 256 * result + c\n  return result", "title": ""}
{"_id": "d12274", "text": "def consecutive(data, stepsize=1):\n    \"\"\"Converts array into chunks with consecutive elements of given step size.\n    http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy\n    \"\"\"\n    return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)", "title": ""}
{"_id": "d12275", "text": "def read_bytes(fo, writer_schema=None, reader_schema=None):\n    \"\"\"Bytes are encoded as a long followed by that many bytes of data.\"\"\"\n    size = read_long(fo)\n    return fo.read(size)", "title": ""}
{"_id": "d12276", "text": "def sort_fn_list(fn_list):\n    \"\"\"Sort input filename list by datetime\n    \"\"\"\n    dt_list = get_dt_list(fn_list)\n    fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]\n    return fn_list_sort", "title": ""}
{"_id": "d12277", "text": "def get_cached_data(datatable, **kwargs):\n    \"\"\" Returns the cached object list under the appropriate key, or None if not set. \"\"\"\n    cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs))\n    data = cache.get(cache_key)\n    log.debug(\"Reading data from cache at %r: %r\", cache_key, data)\n    return data", "title": ""}
{"_id": "d12278", "text": "def us2mc(string):\n    \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)", "title": ""}
{"_id": "d12279", "text": "def get_file_md5sum(path):\n    \"\"\"Calculate the MD5 hash for a file.\"\"\"\n    with open(path, 'rb') as fh:\n        h = str(hashlib.md5(fh.read()).hexdigest())\n    return h", "title": ""}
{"_id": "d12280", "text": "def is_sparse_vector(x):\n    \"\"\" x is a 2D sparse matrix with it's first shape equal to 1.\n    \"\"\"\n    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1", "title": ""}
{"_id": "d12281", "text": "def get_previous_month(self):\n        \"\"\"Returns date range for the previous full month.\"\"\"\n        end = utils.get_month_start() - relativedelta(days=1)\n        end = utils.to_datetime(end)\n        start = utils.get_month_start(end)\n        return start, end", "title": ""}
{"_id": "d12282", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d12283", "text": "def Distance(lat1, lon1, lat2, lon2):\n    \"\"\"Get distance between pairs of lat-lon points\"\"\"\n\n    az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)\n    return az21, dist", "title": ""}
{"_id": "d12284", "text": "def read_key(self, key, bucket_name=None):\n        \"\"\"\n        Reads a key from S3\n\n        :param key: S3 key that will point to the file\n        :type key: str\n        :param bucket_name: Name of the bucket in which the file is stored\n        :type bucket_name: str\n        \"\"\"\n\n        obj = self.get_key(key, bucket_name)\n        return obj.get()['Body'].read().decode('utf-8')", "title": ""}
{"_id": "d12285", "text": "def _days_in_month(date):\n    \"\"\"The number of days in the month of the given 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", "title": ""}
{"_id": "d12286", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d12287", "text": "def callJavaFunc(func, *args):\n    \"\"\" Call Java Function \"\"\"\n    gateway = _get_gateway()\n    args = [_py2java(gateway, a) for a in args]\n    result = func(*args)\n    return _java2py(gateway, result)", "title": ""}
{"_id": "d12288", "text": "def consecutive(data, stepsize=1):\n    \"\"\"Converts array into chunks with consecutive elements of given step size.\n    http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy\n    \"\"\"\n    return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)", "title": ""}
{"_id": "d12289", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d12290", "text": "def iterate_chunks(file, chunk_size):\n    \"\"\"\n    Iterate chunks of size chunk_size from a file-like object\n    \"\"\"\n    chunk = file.read(chunk_size)\n    while chunk:\n        yield chunk\n        chunk = file.read(chunk_size)", "title": ""}
{"_id": "d12291", "text": "def autoscan():\n    \"\"\"autoscan will check all of the serial ports to see if they have\n       a matching VID:PID for a MicroPython board.\n    \"\"\"\n    for port in serial.tools.list_ports.comports():\n        if is_micropython_usb_device(port):\n            connect_serial(port[0])", "title": ""}
{"_id": "d12292", "text": "def set_primary_key(self, table, column):\n        \"\"\"Create a Primary Key constraint on a specific column when the table is already created.\"\"\"\n        self.execute('ALTER TABLE {0} ADD PRIMARY KEY ({1})'.format(wrap(table), column))\n        self._printer('\\tAdded primary key to {0} on column {1}'.format(wrap(table), column))", "title": ""}
{"_id": "d12293", "text": "def ffmpeg_works():\n  \"\"\"Tries to encode images with ffmpeg to check if it 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", "title": ""}
{"_id": "d12294", "text": "def is_primary(self):\n        \"\"\"``True`` if this is a primary key; ``False`` if this is a subkey\"\"\"\n        return isinstance(self._key, Primary) and not isinstance(self._key, Sub)", "title": ""}
{"_id": "d12295", "text": "def convert_value(bind, value):\n    \"\"\" Type casting. \"\"\"\n    type_name = get_type(bind)\n    try:\n        return typecast.cast(type_name, value)\n    except typecast.ConverterError:\n        return value", "title": ""}
{"_id": "d12296", "text": "def locked_delete(self):\n        \"\"\"Delete credentials from the SQLAlchemy datastore.\"\"\"\n        filters = {self.key_name: self.key_value}\n        self.session.query(self.model_class).filter_by(**filters).delete()", "title": ""}
{"_id": "d12297", "text": "def datetime_created(self):\n        \"\"\"Returns file group's create aware *datetime* in UTC format.\"\"\"\n        if self.info().get('datetime_created'):\n            return dateutil.parser.parse(self.info()['datetime_created'])", "title": ""}
{"_id": "d12298", "text": "def maxId(self):\n        \"\"\"int: current max id of objects\"\"\"\n        if len(self.model.db) == 0:\n            return 0\n\n        return max(map(lambda obj: obj[\"id\"], self.model.db))", "title": ""}
{"_id": "d12299", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d12300", "text": "def string_to_float_list(string_var):\n        \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n        try:\n            return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n        except:\n            return [float(s) for s in string_var.strip('[').strip(']').split(',')]", "title": ""}
{"_id": "d12301", "text": "def init_db():\n    \"\"\"\n    Drops and re-creates the SQL schema\n    \"\"\"\n    db.drop_all()\n    db.configure_mappers()\n    db.create_all()\n    db.session.commit()", "title": ""}
{"_id": "d12302", "text": "def bytes_to_str(s, encoding='utf-8'):\n    \"\"\"Returns a str if a bytes object is given.\"\"\"\n    if six.PY3 and isinstance(s, bytes):\n        return s.decode(encoding)\n    return s", "title": ""}
{"_id": "d12303", "text": "def push(h, x):\n    \"\"\"Push a new value into heap.\"\"\"\n    h.push(x)\n    up(h, h.size()-1)", "title": ""}
{"_id": "d12304", "text": "def _possibly_convert_objects(values):\n    \"\"\"Convert arrays of datetime.datetime and datetime.timedelta objects into\n    datetime64 and timedelta64, according to the pandas convention.\n    \"\"\"\n    return np.asarray(pd.Series(values.ravel())).reshape(values.shape)", "title": ""}
{"_id": "d12305", "text": "def stackplot(marray, seconds=None, start_time=None, ylabels=None):\n    \"\"\"\n    will plot a stack of traces one above the other assuming\n    marray.shape = numRows, numSamples\n    \"\"\"\n    tarray = np.transpose(marray)\n    stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)\n    plt.show()", "title": ""}
{"_id": "d12306", "text": "def imdecode(image_path):\n    \"\"\"Return BGR image read by opencv\"\"\"\n    import os\n    assert os.path.exists(image_path), image_path + ' not found'\n    im = cv2.imread(image_path)\n    return im", "title": ""}
{"_id": "d12307", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d12308", "text": "def get_incomplete_path(filename):\n  \"\"\"Returns a temporary filename based on filename.\"\"\"\n  random_suffix = \"\".join(\n      random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n  return filename + \".incomplete\" + random_suffix", "title": ""}
{"_id": "d12309", "text": "def _unzip_handle(handle):\n    \"\"\"Transparently unzip the file handle\"\"\"\n    if isinstance(handle, basestring):\n        handle = _gzip_open_filename(handle)\n    else:\n        handle = _gzip_open_handle(handle)\n    return handle", "title": ""}
{"_id": "d12310", "text": "def getCenter(self):\n        \"\"\" Return the ``Location`` of the center of this region \"\"\"\n        return Location(self.x+(self.w/2), self.y+(self.h/2))", "title": ""}
{"_id": "d12311", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d12312", "text": "def _StopStatusUpdateThread(self):\n    \"\"\"Stops the status update thread.\"\"\"\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", "title": ""}
{"_id": "d12313", "text": "def clean_with_zeros(self,x):\n        \"\"\" set nan and inf rows from x to zero\"\"\"\n        x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0\n        return x", "title": ""}
{"_id": "d12314", "text": "def _to_corrected_pandas_type(dt):\n    \"\"\"\n    When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n    This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n    \"\"\"\n    import numpy as np\n    if type(dt) == ByteType:\n        return np.int8\n    elif type(dt) == ShortType:\n        return np.int16\n    elif type(dt) == IntegerType:\n        return np.int32\n    elif type(dt) == FloatType:\n        return np.float32\n    else:\n        return None", "title": ""}
{"_id": "d12315", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d12316", "text": "def convert_str_to_datetime(df, *, column: str, format: str):\n    \"\"\"\n    Convert string column into datetime column\n\n    ---\n\n    ### Parameters\n\n    *mandatory :*\n    - `column` (*str*): name of the column to format\n    - `format` (*str*): current format of the values (see [available formats](\n    https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))\n    \"\"\"\n    df[column] = pd.to_datetime(df[column], format=format)\n    return df", "title": ""}
{"_id": "d12317", "text": "def _strvar(a, prec='{:G}'):\n    r\"\"\"Return variable as a string to print, with given precision.\"\"\"\n    return ' '.join([prec.format(i) for i in np.atleast_1d(a)])", "title": ""}
{"_id": "d12318", "text": "def inc_date(date_obj, num, date_fmt):\n    \"\"\"Increment the date by a certain number and return date object.\n    as the specific string format.\n    \"\"\"\n    return (date_obj + timedelta(days=num)).strftime(date_fmt)", "title": ""}
{"_id": "d12319", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d12320", "text": "def styles(self, dictobj):\n\t\t\"\"\"\n\t\tAdd or update styles\n\t\t\"\"\"\n\t\tfor k in dictobj:\n\t\t\tself.chart_style[k] = dictobj[k]", "title": ""}
{"_id": "d12321", "text": "def string_to_int( s ):\n  \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n  result = 0\n  for c in s:\n    if not isinstance(c, int): c = ord( c )\n    result = 256 * result + c\n  return result", "title": ""}
{"_id": "d12322", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d12323", "text": "def string_to_int( s ):\n  \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n  result = 0\n  for c in s:\n    if not isinstance(c, int): c = ord( c )\n    result = 256 * result + c\n  return result", "title": ""}
{"_id": "d12324", "text": "def flipwritable(fn, mode=None):\n    \"\"\"\n    Flip the writability of a file and return the old mode. Returns None\n    if the file is already writable.\n    \"\"\"\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", "title": ""}
{"_id": "d12325", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d12326", "text": "def to_camel(s):\n    \"\"\"\n    :param string s: under_scored string to be CamelCased\n    :return: CamelCase version of input\n    :rtype: str\n    \"\"\"\n    # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n    return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "title": ""}
{"_id": "d12327", "text": "def _fullname(o):\n    \"\"\"Return the fully-qualified name of a function.\"\"\"\n    return o.__module__ + \".\" + o.__name__ if o.__module__ else o.__name__", "title": ""}
{"_id": "d12328", "text": "def covstr(s):\n  \"\"\" convert string to int or float. \"\"\"\n  try:\n    ret = int(s)\n  except ValueError:\n    ret = float(s)\n  return ret", "title": ""}
{"_id": "d12329", "text": "def synth_hangul(string):\n    \"\"\"Convert jamo characters in a string into hcj as much as possible.\"\"\"\n    raise NotImplementedError\n    return ''.join([''.join(''.join(jamo_to_hcj(_)) for _ in string)])", "title": ""}
{"_id": "d12330", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d12331", "text": "def deserialize_date(string):\n    \"\"\"\n    Deserializes string to date.\n\n    :param string: str.\n    :type string: str\n    :return: date.\n    :rtype: date\n    \"\"\"\n    try:\n        from dateutil.parser import parse\n        return parse(string).date()\n    except ImportError:\n        return string", "title": ""}
{"_id": "d12332", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d12333", "text": "def __init__(self, encoding='utf-8'):\n    \"\"\"Initializes an stdin input reader.\n\n    Args:\n      encoding (Optional[str]): input encoding.\n    \"\"\"\n    super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)", "title": ""}
{"_id": "d12334", "text": "def strip_querystring(url):\n    \"\"\"Remove the querystring from the end of a URL.\"\"\"\n    p = six.moves.urllib.parse.urlparse(url)\n    return p.scheme + \"://\" + p.netloc + p.path", "title": ""}
{"_id": "d12335", "text": "def equal(x, y):\n    \"\"\"\n    Return True if x == y and False otherwise.\n\n    This function returns False whenever x and/or y is a NaN.\n\n    \"\"\"\n    x = BigFloat._implicit_convert(x)\n    y = BigFloat._implicit_convert(y)\n    return mpfr.mpfr_equal_p(x, y)", "title": ""}
{"_id": "d12336", "text": "def load_from_file(module_path):\n    \"\"\"\n    Load a python module from its absolute filesystem path\n\n    Borrowed from django-cms\n    \"\"\"\n    from imp import load_module, PY_SOURCE\n\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", "title": ""}
{"_id": "d12337", "text": "def _is_iterable(item):\n    \"\"\" Checks if an item is iterable (list, tuple, generator), but not string \"\"\"\n    return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)", "title": ""}
{"_id": "d12338", "text": "def submitbutton(self, request, tag):\n        \"\"\"\n        Render an INPUT element of type SUBMIT which will post this form to the\n        server.\n        \"\"\"\n        return tags.input(type='submit',\n                          name='__submit__',\n                          value=self._getDescription())", "title": ""}
{"_id": "d12339", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d12340", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d12341", "text": "def is_readable(fp, size=1):\n    \"\"\"\n    Check if the file-like object is readable.\n\n    :param fp: file-like object\n    :param size: byte size\n    :return: bool\n    \"\"\"\n    read_size = len(fp.read(size))\n    fp.seek(-read_size, 1)\n    return read_size == size", "title": ""}
{"_id": "d12342", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d12343", "text": "def is_archlinux():\n    \"\"\"return True if the current distribution is running on debian like OS.\"\"\"\n    if platform.system().lower() == 'linux':\n        if platform.linux_distribution() == ('', '', ''):\n            # undefined distribution. Fixed in python 3.\n            if os.path.exists('/etc/arch-release'):\n                return True\n    return False", "title": ""}
{"_id": "d12344", "text": "def maybeparens(lparen, item, rparen):\n    \"\"\"Wrap an item in optional parentheses, only applying them if necessary.\"\"\"\n    return item | lparen.suppress() + item + rparen.suppress()", "title": ""}
{"_id": "d12345", "text": "def contains_empty(features):\n    \"\"\"Check features data are not empty\n\n    :param features: The features data to check.\n    :type features: list of numpy arrays.\n\n    :return: True if one of the array is empty, False else.\n\n    \"\"\"\n    if not features:\n        return True\n    for feature in features:\n        if feature.shape[0] == 0:\n            return True\n    return False", "title": ""}
{"_id": "d12346", "text": "def get_python_dict(scala_map):\n    \"\"\"Return a dict from entries in a scala.collection.immutable.Map\"\"\"\n    python_dict = {}\n    keys = get_python_list(scala_map.keys().toList())\n    for key in keys:\n        python_dict[key] = scala_map.apply(key)\n    return python_dict", "title": ""}
{"_id": "d12347", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d12348", "text": "def remove_na_arraylike(arr):\n    \"\"\"\n    Return array-like containing only true/non-NaN values, possibly empty.\n    \"\"\"\n    if is_extension_array_dtype(arr):\n        return arr[notna(arr)]\n    else:\n        return arr[notna(lib.values_from_object(arr))]", "title": ""}
{"_id": "d12349", "text": "def watched_extension(extension):\n    \"\"\"Return True if the given extension is one of the watched extensions\"\"\"\n    for ext in hamlpy.VALID_EXTENSIONS:\n        if extension.endswith('.' + ext):\n            return True\n    return False", "title": ""}
{"_id": "d12350", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d12351", "text": "def clean_float(v):\n    \"\"\"Remove commas from a float\"\"\"\n\n    if v is None or not str(v).strip():\n        return None\n\n    return float(str(v).replace(',', ''))", "title": ""}
{"_id": "d12352", "text": "def test():\n    \"\"\"Test program for telnetlib.\n\n    Usage: python telnetlib.py [-d] ... [host [port]]\n\n    Default host is localhost; default port is 23.\n\n    \"\"\"\n    debuglevel = 0\n    while sys.argv[1:] and sys.argv[1] == '-d':\n        debuglevel = debuglevel + 1\n        del sys.argv[1]\n    host = 'localhost'\n    if sys.argv[1:]:\n        host = sys.argv[1]\n    port = 0\n    if sys.argv[2:]:\n        portstr = sys.argv[2]\n        try:\n            port = int(portstr)\n        except ValueError:\n            port = socket.getservbyname(portstr, 'tcp')\n    tn = Telnet()\n    tn.set_debuglevel(debuglevel)\n    tn.open(host, port)\n    tn.interact()\n    tn.close()", "title": ""}
{"_id": "d12353", "text": "def is_clicked(self, MouseStateType):\n        \"\"\"\n        Did the user depress and release the button to signify a click?\n        MouseStateType is the button to query. Values found under StateTypes.py\n        \"\"\"\n        return self.previous_mouse_state.query_state(MouseStateType) and (\n        not self.current_mouse_state.query_state(MouseStateType))", "title": ""}
{"_id": "d12354", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d12355", "text": "def is_managed():\n    \"\"\"\n    Check if a Django project is being managed with ``manage.py`` or\n    ``django-admin`` scripts\n\n    :return: Check result\n    :rtype: bool\n    \"\"\"\n    for item in sys.argv:\n        if re.search(r'manage.py|django-admin|django', item) is not None:\n            return True\n    return False", "title": ""}
{"_id": "d12356", "text": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "title": ""}
{"_id": "d12357", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d12358", "text": "def run(self, value):\n        \"\"\" Determines if value value is empty.\n        Keyword arguments:\n        value str -- the value of the associated field to compare\n        \"\"\"\n        if self.pass_ and not value.strip():\n            return True\n\n        if not value:\n            return False\n        return True", "title": ""}
{"_id": "d12359", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d12360", "text": "def check_type_and_size_of_param_list(param_list, expected_length):\n    \"\"\"\n    Ensure that param_list is a list with the expected length. Raises a helpful\n    ValueError if this is not the case.\n    \"\"\"\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\n    return None", "title": ""}
{"_id": "d12361", "text": "def _size_36():\n    \"\"\" returns the rows, columns of terminal \"\"\"\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", "title": ""}
{"_id": "d12362", "text": "def is_enum_type(type_):\n    \"\"\" Checks if the given type is an enum type.\n\n    :param type_: The type to check\n    :return: True if the type is a enum type, otherwise False\n    :rtype: bool\n    \"\"\"\n\n    return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))", "title": ""}
{"_id": "d12363", "text": "def main(argv=None):\n  \"\"\"Run a Tensorflow model on the Iris dataset.\"\"\"\n  args = parse_arguments(sys.argv if argv is None else argv)\n\n  tf.logging.set_verbosity(tf.logging.INFO)\n  learn_runner.run(\n      experiment_fn=get_experiment_fn(args),\n      output_dir=args.job_dir)", "title": ""}
{"_id": "d12364", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d12365", "text": "def print_err(*args, end='\\n'):\n    \"\"\"Similar to print, but prints to stderr.\n    \"\"\"\n    print(*args, end=end, file=sys.stderr)\n    sys.stderr.flush()", "title": ""}
{"_id": "d12366", "text": "def run(self, value):\n        \"\"\" Determines if value value is empty.\n        Keyword arguments:\n        value str -- the value of the associated field to compare\n        \"\"\"\n        if self.pass_ and not value.strip():\n            return True\n\n        if not value:\n            return False\n        return True", "title": ""}
{"_id": "d12367", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d12368", "text": "def qth_pw(self, q):\n        \"\"\"\n        returns the qth most probable element in the dawg.\n        \"\"\"\n        return heapq.nlargest(q + 2, self._T.iteritems(),\n                              key=operator.itemgetter(1))[-1]", "title": ""}
{"_id": "d12369", "text": "def remote_file_exists(self, url):\n        \"\"\" 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.\n        \"\"\"\n        status = requests.head(url).status_code\n\n        if status != 200:\n            raise RemoteFileDoesntExist", "title": ""}
{"_id": "d12370", "text": "def do_last(environment, seq):\n    \"\"\"Return the last item of a sequence.\"\"\"\n    try:\n        return next(iter(reversed(seq)))\n    except StopIteration:\n        return environment.undefined('No last item, sequence was empty.')", "title": ""}
{"_id": "d12371", "text": "def watched_extension(extension):\n    \"\"\"Return True if the given extension is one of the watched extensions\"\"\"\n    for ext in hamlpy.VALID_EXTENSIONS:\n        if extension.endswith('.' + ext):\n            return True\n    return False", "title": ""}
{"_id": "d12372", "text": "def pop(self):\n        \"\"\"\n        return the last stack element and delete it from the list\n        \"\"\"\n        if not self.empty():\n            val = self.stack[-1]\n            del self.stack[-1]\n            return val", "title": ""}
{"_id": "d12373", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d12374", "text": "def is_readable(filename):\n    \"\"\"Check if file is a regular file and is readable.\"\"\"\n    return os.path.isfile(filename) and os.access(filename, os.R_OK)", "title": ""}
{"_id": "d12375", "text": "def hasattrs(object, *names):\n    \"\"\"\n    Takes in an object and a variable length amount of named attributes,\n    and checks to see if the object has each property. If any of the\n    attributes are missing, this returns false.\n\n    :param object: an object that may or may not contain the listed attributes\n    :param names: a variable amount of attribute names to check for\n    :return: True if the object contains each named attribute, false otherwise\n    \"\"\"\n    for name in names:\n        if not hasattr(object, name):\n            return False\n    return True", "title": ""}
{"_id": "d12376", "text": "def is_writable_by_others(filename):\n    \"\"\"Check if file or directory is world writable.\"\"\"\n    mode = os.stat(filename)[stat.ST_MODE]\n    return mode & stat.S_IWOTH", "title": ""}
{"_id": "d12377", "text": "async def iso(self, source):\n        \"\"\"Convert to timestamp.\"\"\"\n        from datetime import datetime\n        unix_timestamp = int(source)\n        return datetime.fromtimestamp(unix_timestamp).isoformat()", "title": ""}
{"_id": "d12378", "text": "def is_valid_folder(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.isdir(arg):\n        parser.error(\"The folder %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d12379", "text": "def lower_ext(abspath):\n    \"\"\"Convert file extension to lowercase.\n    \"\"\"\n    fname, ext = os.path.splitext(abspath)\n    return fname + ext.lower()", "title": ""}
{"_id": "d12380", "text": "def is_non_empty_string(input_string):\n    \"\"\"\n    Validate if non empty string\n\n    :param input_string: Input is a *str*.\n    :return: True if input is string and non empty.\n       Raise :exc:`Exception` otherwise.\n    \"\"\"\n    try:\n        if not input_string.strip():\n            raise ValueError()\n    except AttributeError as error:\n        raise TypeError(error)\n\n    return True", "title": ""}
{"_id": "d12381", "text": "def default_number_converter(number_str):\n    \"\"\"\n    Converts the string representation of a json number into its python object equivalent, an\n    int, long, float or whatever type suits.\n    \"\"\"\n    is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()\n    # FIXME: this handles a wider range of numbers than allowed by the json standard,\n    # etc.: float('nan') and float('inf'). But is this a problem?\n    return int(number_str) if is_int else float(number_str)", "title": ""}
{"_id": "d12382", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d12383", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d12384", "text": "def timed_call(func, *args, log_level='DEBUG', **kwargs):\n    \"\"\"Logs a function's run time\n\n    :param func: The function to run\n    :param args: The args to pass to the function\n    :param kwargs: The keyword args to pass to the function\n    :param log_level: The log level at which to print the run time\n    :return: The function's return value\n    \"\"\"\n    start = time()\n    r = func(*args, **kwargs)\n    t = time() - start\n    log(log_level, \"Call to '{}' took {:0.6f}s\".format(func.__name__, t))\n    return r", "title": ""}
{"_id": "d12385", "text": "def _get_line_no_from_comments(py_line):\n    \"\"\"Return the line number parsed from the comment or 0.\"\"\"\n    matched = LINECOL_COMMENT_RE.match(py_line)\n    if matched:\n        return int(matched.group(1))\n    else:\n        return 0", "title": ""}
{"_id": "d12386", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d12387", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d12388", "text": "def _to_array(value):\n    \"\"\"As a convenience, turn Python lists and tuples into NumPy arrays.\"\"\"\n    if isinstance(value, (tuple, list)):\n        return array(value)\n    elif isinstance(value, (float, int)):\n        return np.float64(value)\n    else:\n        return value", "title": ""}
{"_id": "d12389", "text": "def empty_tree(input_list):\n    \"\"\"Recursively iterate through values in nested lists.\"\"\"\n    for item in input_list:\n        if not isinstance(item, list) or not empty_tree(item):\n            return False\n    return True", "title": ""}
{"_id": "d12390", "text": "def post_process(self):\n        \"\"\" Apply last 2D transforms\"\"\"\n        self.image.putdata(self.pixels)\n        self.image = self.image.transpose(Image.ROTATE_90)", "title": ""}
{"_id": "d12391", "text": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "title": ""}
{"_id": "d12392", "text": "def retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n\t\"\"\"\n\tGiven a callable func, trap the indicated exceptions\n\tfor up to 'retries' times, invoking cleanup on the\n\texception. On the final attempt, allow any exceptions\n\tto propagate.\n\t\"\"\"\n\tattempts = count() if retries == float('inf') else range(retries)\n\tfor attempt in attempts:\n\t\ttry:\n\t\t\treturn func()\n\t\texcept trap:\n\t\t\tcleanup()\n\n\treturn func()", "title": ""}
{"_id": "d12393", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d12394", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d12395", "text": "def is_number(obj):\n    \"\"\"Check if obj is number.\"\"\"\n    return isinstance(obj, (int, float, np.int_, np.float_))", "title": ""}
{"_id": "d12396", "text": "def int_to_date(date):\n    \"\"\"\n    Convert an int of form yyyymmdd to a python date object.\n    \"\"\"\n\n    year = date // 10**4\n    month = date % 10**4 // 10**2\n    day = date % 10**2\n\n    return datetime.date(year, month, day)", "title": ""}
{"_id": "d12397", "text": "def is_symlink(self):\n        \"\"\"\n        Whether this path is a symbolic link.\n        \"\"\"\n        try:\n            return S_ISLNK(self.lstat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            # Path doesn't exist\n            return False", "title": ""}
{"_id": "d12398", "text": "def toarray(self):\n        \"\"\"Returns the data as numpy.array from each partition.\"\"\"\n        rdd = self._rdd.map(lambda x: x.toarray())\n        return np.concatenate(rdd.collect())", "title": ""}
{"_id": "d12399", "text": "def stringify_dict_contents(dct):\n    \"\"\"Turn dict keys and values into native strings.\"\"\"\n    return {\n        str_if_nested_or_str(k): str_if_nested_or_str(v)\n        for k, v in dct.items()\n    }", "title": ""}
{"_id": "d12400", "text": "def ishex(obj):\n    \"\"\"\n    Test if the argument is a string representing a valid hexadecimal digit.\n\n    :param obj: Object\n    :type  obj: any\n\n    :rtype: boolean\n    \"\"\"\n    return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits)", "title": ""}
{"_id": "d12401", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d12402", "text": "def is_connected(self):\n        \"\"\"\n        Return true if the socket managed by this connection is connected\n\n        :rtype: bool\n        \"\"\"\n        try:\n            return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)\n        except socket.error:\n            return False", "title": ""}
{"_id": "d12403", "text": "def getBuffer(x):\n    \"\"\"\n    Copy @x into a (modifiable) ctypes byte array\n    \"\"\"\n    b = bytes(x)\n    return (c_ubyte * len(b)).from_buffer_copy(bytes(x))", "title": ""}
{"_id": "d12404", "text": "def boxes_intersect(box1, box2):\n    \"\"\"Determines if two rectangles, each input as a tuple\n        (xmin, xmax, ymin, ymax), intersect.\"\"\"\n    xmin1, xmax1, ymin1, ymax1 = box1\n    xmin2, xmax2, ymin2, ymax2 = box2\n    if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \\\n            interval_intersection_width(ymin1, ymax1, ymin2, ymax2):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d12405", "text": "def sbatch_template(self):\n        \"\"\":return Jinja sbatch template for the current tag\"\"\"\n        template = self.sbatch_template_str\n        if template.startswith('#!'):\n            # script is embedded in YAML\n            return jinja_environment.from_string(template)\n        return jinja_environment.get_template(template)", "title": ""}
{"_id": "d12406", "text": "def is_local_url(target):\n    \"\"\"Determine if URL is safe to redirect to.\"\"\"\n    ref_url = urlparse(request.host_url)\n    test_url = urlparse(urljoin(request.host_url, target))\n    return test_url.scheme in ('http', 'https') and \\\n        ref_url.netloc == test_url.netloc", "title": ""}
{"_id": "d12407", "text": "def post_tweet(user_id, message, additional_params={}):\n    \"\"\"\n    Helper function to post a tweet \n    \"\"\"\n    url = \"https://api.twitter.com/1.1/statuses/update.json\"    \n    params = { \"status\" : message }\n    params.update(additional_params)\n    r = make_twitter_request(url, user_id, params, request_type='POST')\n    print (r.text)\n    return \"Successfully posted a tweet {}\".format(message)", "title": ""}
{"_id": "d12408", "text": "def require_root(fn):\n    \"\"\"\n    Decorator to make sure, that user is root.\n    \"\"\"\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\n    return xex", "title": ""}
{"_id": "d12409", "text": "def sort_func(self, key):\n        \"\"\"Sorting logic for `Quantity` objects.\"\"\"\n        if key == self._KEYS.VALUE:\n            return 'aaa'\n        if key == self._KEYS.SOURCE:\n            return 'zzz'\n        return key", "title": ""}
{"_id": "d12410", "text": "def is_enum_type(type_):\n    \"\"\" Checks if the given type is an enum type.\n\n    :param type_: The type to check\n    :return: True if the type is a enum type, otherwise False\n    :rtype: bool\n    \"\"\"\n\n    return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))", "title": ""}
{"_id": "d12411", "text": "def remove_from_lib(self, name):\n        \"\"\" Remove an object from the bin folder. \"\"\"\n        self.__remove_path(os.path.join(self.root_dir, \"lib\", name))", "title": ""}
{"_id": "d12412", "text": "def is_float_array(l):\n    r\"\"\"Checks if l is a numpy array of floats (any dimension\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.dtype.kind == 'f':\n            return True\n    return False", "title": ""}
{"_id": "d12413", "text": "def log_normalize(data):\n    \"\"\"Perform log transform log(x + 1).\n    \n    Parameters\n    ----------\n    data : array_like\n    \n    \"\"\"\n    if sp.issparse(data):\n        data = data.copy()\n        data.data = np.log2(data.data + 1)\n        return data\n\n    return np.log2(data.astype(np.float64) + 1)", "title": ""}
{"_id": "d12414", "text": "def is_valid_image_extension(file_path):\n    \"\"\"is_valid_image_extension.\"\"\"\n    valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']\n    _, extension = os.path.splitext(file_path)\n    return extension.lower() in valid_extensions", "title": ""}
{"_id": "d12415", "text": "def _config_section(config, section):\n    \"\"\"Read the configuration file and return a section.\"\"\"\n    path = os.path.join(config.get('config_path'), config.get('config_file'))\n    conf = _config_ini(path)\n    return conf.get(section)", "title": ""}
{"_id": "d12416", "text": "def is_sequence(obj):\n    \"\"\"Check if `obj` is a sequence, but not a string or bytes.\"\"\"\n    return isinstance(obj, Sequence) and not (\n        isinstance(obj, str) or BinaryClass.is_valid_type(obj))", "title": ""}
{"_id": "d12417", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d12418", "text": "def camelcase_underscore(name):\n    \"\"\" Convert camelcase names to underscore \"\"\"\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()", "title": ""}
{"_id": "d12419", "text": "def issubset(self, other):\n        \"\"\"Report whether another set contains this RangeSet.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issubset(self, other)", "title": ""}
{"_id": "d12420", "text": "def unique_items(seq):\n    \"\"\"Return the unique items from iterable *seq* (in order).\"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d12421", "text": "def stdin_readable():\n    \"\"\"Determine whether stdin has any data to read.\"\"\"\n    if not WINDOWS:\n        try:\n            return bool(select([sys.stdin], [], [], 0)[0])\n        except Exception:\n            logger.log_exc()\n    try:\n        return not sys.stdin.isatty()\n    except Exception:\n        logger.log_exc()\n    return False", "title": ""}
{"_id": "d12422", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d12423", "text": "def any_contains_any(strings, candidates):\n    \"\"\"Whether any of the strings contains any of the candidates.\"\"\"\n    for string in strings:\n        for c in candidates:\n            if c in string:\n                return True", "title": ""}
{"_id": "d12424", "text": "def date_to_timestamp(date):\n    \"\"\"\n        date to unix timestamp in milliseconds\n    \"\"\"\n    date_tuple = date.timetuple()\n    timestamp = calendar.timegm(date_tuple) * 1000\n    return timestamp", "title": ""}
{"_id": "d12425", "text": "def starts_with_prefix_in_list(text, prefixes):\n    \"\"\"\n    Return True if the given string starts with one of the prefixes in the given list, otherwise\n    return False.\n\n    Arguments:\n        text (str): Text to check for prefixes.\n        prefixes (list): List of prefixes to check for.\n\n    Returns:\n        bool: True if the given text starts with any of the given prefixes, otherwise False.\n    \"\"\"\n    for prefix in prefixes:\n        if text.startswith(prefix):\n            return True\n    return False", "title": ""}
{"_id": "d12426", "text": "def cmp_contents(filename1, filename2):\n    \"\"\" Returns True if contents of the files are the same\n\n    Parameters\n    ----------\n    filename1 : str\n        filename of first file to compare\n    filename2 : str\n        filename of second file to compare\n\n    Returns\n    -------\n    tf : bool\n        True if binary contents of `filename1` is same as binary contents of\n        `filename2`, False otherwise.\n    \"\"\"\n    with open_readable(filename1, 'rb') as fobj:\n        contents1 = fobj.read()\n    with open_readable(filename2, 'rb') as fobj:\n        contents2 = fobj.read()\n    return contents1 == contents2", "title": ""}
{"_id": "d12427", "text": "def update_dict(obj, dict, attributes):\n    \"\"\"Update dict with fields from obj.attributes.\n\n    :param obj: the object updated into dict\n    :param dict: the result dictionary\n    :param attributes: a list of attributes belonging to obj\n    \"\"\"\n    for attribute in attributes:\n        if hasattr(obj, attribute) and getattr(obj, attribute) is not None:\n            dict[attribute] = getattr(obj, attribute)", "title": ""}
{"_id": "d12428", "text": "def get_url_args(url):\n    \"\"\" Returns a dictionary from a URL params \"\"\"\n    url_data = urllib.parse.urlparse(url)\n    arg_dict = urllib.parse.parse_qs(url_data.query)\n    return arg_dict", "title": ""}
{"_id": "d12429", "text": "def input_int_default(question=\"\", default=0):\n    \"\"\"A function that works for both, Python 2.x and Python 3.x.\n       It asks the user for input and returns it as a string.\n    \"\"\"\n    answer = input_string(question)\n    if answer == \"\" or answer == \"yes\":\n        return default\n    else:\n        return int(answer)", "title": ""}
{"_id": "d12430", "text": "def is_file(path):\n    \"\"\"Determine if a Path or string is a file on the file system.\"\"\"\n    try:\n        return path.expanduser().absolute().is_file()\n    except AttributeError:\n        return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))", "title": ""}
{"_id": "d12431", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d12432", "text": "def is_iterable(value):\n    \"\"\"must be an iterable (list, array, tuple)\"\"\"\n    return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "title": ""}
{"_id": "d12433", "text": "def setConfigKey(key, value):\n\t\t\"\"\"\n\t\tSets the config data value for the specified dictionary key\n\t\t\"\"\"\n\t\tconfigFile = ConfigurationManager._configFile()\n\t\treturn JsonDataManager(configFile).setKey(key, value)", "title": ""}
{"_id": "d12434", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d12435", "text": "def is_valid_file(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.exists(arg):\n        parser.error(\"The file %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d12436", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d12437", "text": "def find_largest_contig(contig_lengths_dict):\n    \"\"\"\n    Determine the largest contig for each strain\n    :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n    :return: longest_contig_dict: dictionary of strain name: longest contig\n    \"\"\"\n    # Initialise the dictionary\n    longest_contig_dict = dict()\n    for file_name, contig_lengths in contig_lengths_dict.items():\n        # As the list is sorted in descending order, the largest contig is the first entry in the list\n        longest_contig_dict[file_name] = contig_lengths[0]\n    return longest_contig_dict", "title": ""}
{"_id": "d12438", "text": "def retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n\t\"\"\"\n\tGiven a callable func, trap the indicated exceptions\n\tfor up to 'retries' times, invoking cleanup on the\n\texception. On the final attempt, allow any exceptions\n\tto propagate.\n\t\"\"\"\n\tattempts = count() if retries == float('inf') else range(retries)\n\tfor attempt in attempts:\n\t\ttry:\n\t\t\treturn func()\n\t\texcept trap:\n\t\t\tcleanup()\n\n\treturn func()", "title": ""}
{"_id": "d12439", "text": "def kill_mprocess(process):\n    \"\"\"kill process\n    Args:\n        process - Popen object for process\n    \"\"\"\n    if process and proc_alive(process):\n        process.terminate()\n        process.communicate()\n    return not proc_alive(process)", "title": ""}
{"_id": "d12440", "text": "def generate_uuid():\n    \"\"\"Generate a UUID.\"\"\"\n    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)\n    return r_uuid.decode().replace('=', '')", "title": ""}
{"_id": "d12441", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d12442", "text": "def get_neg_infinity(dtype):\n    \"\"\"Return an appropriate positive infinity for this dtype.\n\n    Parameters\n    ----------\n    dtype : np.dtype\n\n    Returns\n    -------\n    fill_value : positive infinity value corresponding to this dtype.\n    \"\"\"\n    if issubclass(dtype.type, (np.floating, np.integer)):\n        return -np.inf\n\n    if issubclass(dtype.type, np.complexfloating):\n        return -np.inf - 1j * np.inf\n\n    return NINF", "title": ""}
{"_id": "d12443", "text": "def _removeLru(self):\n        \"\"\"\n        Remove the least recently used file handle from the cache.\n        The pop method removes an element from the right of the deque.\n        Returns the name of the file that has been removed.\n        \"\"\"\n        (dataFile, handle) = self._cache.pop()\n        handle.close()\n        return dataFile", "title": ""}
{"_id": "d12444", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d12445", "text": "def _clear(self):\n        \"\"\"Resets all assigned data for the current message.\"\"\"\n        self._finished = False\n        self._measurement = None\n        self._message = None\n        self._message_body = None", "title": ""}
{"_id": "d12446", "text": "def dot_v2(vec1, vec2):\n    \"\"\"Return the dot product of two vectors\"\"\"\n\n    return vec1.x * vec2.x + vec1.y * vec2.y", "title": ""}
{"_id": "d12447", "text": "def underline(self, msg):\n        \"\"\"Underline the input\"\"\"\n        return click.style(msg, underline=True) if self.colorize else msg", "title": ""}
{"_id": "d12448", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d12449", "text": "def close_database_session(session):\n    \"\"\"Close connection with the database\"\"\"\n\n    try:\n        session.close()\n    except OperationalError as e:\n        raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])", "title": ""}
{"_id": "d12450", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d12451", "text": "def eval(e, amplitude, e_0, alpha, beta):\n        \"\"\"One dimenional log parabola model function\"\"\"\n\n        ee = e / e_0\n        eeponent = -alpha - beta * np.log(ee)\n        return amplitude * ee ** eeponent", "title": ""}
{"_id": "d12452", "text": "def home():\n    \"\"\"Temporary helper function to link to the API routes\"\"\"\n    return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \\\n        HTTPStatus.OK", "title": ""}
{"_id": "d12453", "text": "def update_screen(self):\n        \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n        self.clock.tick(self.FPS)\n        pygame.display.update()", "title": ""}
{"_id": "d12454", "text": "def visit_ellipsis(self, node, parent):\n        \"\"\"visit an Ellipsis node by returning a fresh instance of it\"\"\"\n        return nodes.Ellipsis(\n            getattr(node, \"lineno\", None), getattr(node, \"col_offset\", None), parent\n        )", "title": ""}
{"_id": "d12455", "text": "def track_update(self):\n        \"\"\"Update the lastest updated date in the database.\"\"\"\n        metadata = self.info()\n        metadata.updated_at = dt.datetime.now()\n        self.commit()", "title": ""}
{"_id": "d12456", "text": "def struct2dict(struct):\n    \"\"\"convert a ctypes structure to a dictionary\"\"\"\n    return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}", "title": ""}
{"_id": "d12457", "text": "def strip_comment_marker(text):\n    \"\"\" Strip # markers at the front of a block of comment text.\n    \"\"\"\n    lines = []\n    for line in text.splitlines():\n        lines.append(line.lstrip('#'))\n    text = textwrap.dedent('\\n'.join(lines))\n    return text", "title": ""}
{"_id": "d12458", "text": "def is_cyclic(graph):\n    \"\"\"\n    Return True if the directed graph g has a cycle. The directed graph\n    should be represented as a dictionary mapping of edges for each node.\n    \"\"\"\n    path = set()\n\n    def visit(vertex):\n        path.add(vertex)\n        for neighbour in graph.get(vertex, ()):\n            if neighbour in path or visit(neighbour):\n                return True\n        path.remove(vertex)\n        return False\n\n    return any(visit(v) for v in graph)", "title": ""}
{"_id": "d12459", "text": "def coverage(ctx, opts=\"\"):\n    \"\"\"\n    Execute all tests (normal and slow) with coverage enabled.\n    \"\"\"\n    return test(ctx, coverage=True, include_slow=True, opts=opts)", "title": ""}
{"_id": "d12460", "text": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "title": ""}
{"_id": "d12461", "text": "def scale_v2(vec, amount):\n    \"\"\"Return a new Vec2 with x and y from vec and multiplied by amount.\"\"\"\n\n    return Vec2(vec.x * amount, vec.y * amount)", "title": ""}
{"_id": "d12462", "text": "def allsame(list_, strict=True):\n    \"\"\"\n    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\n    \"\"\"\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)", "title": ""}
{"_id": "d12463", "text": "def software_fibonacci(n):\n    \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n    a, b = 0, 1\n    for i in range(n):\n        a, b = b, a + b\n    return a", "title": ""}
{"_id": "d12464", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d12465", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d12466", "text": "def is_adb_detectable(self):\n        \"\"\"Checks if USB is on and device is ready by verifying adb devices.\"\"\"\n        serials = list_adb_devices()\n        if self.serial in serials:\n            self.log.debug('Is now adb detectable.')\n            return True\n        return False", "title": ""}
{"_id": "d12467", "text": "def subsystem(s):\n    \"\"\"Validate a |Subsystem|.\n\n    Checks its state and cut.\n    \"\"\"\n    node_states(s.state)\n    cut(s.cut, s.cut_indices)\n    if config.VALIDATE_SUBSYSTEM_STATES:\n        state_reachable(s)\n    return True", "title": ""}
{"_id": "d12468", "text": "def get_oauth_token():\n    \"\"\"Retrieve a simple OAuth Token for use with the local http client.\"\"\"\n    url = \"{0}/token\".format(DEFAULT_ORIGIN[\"Origin\"])\n    r = s.get(url=url)\n    return r.json()[\"t\"]", "title": ""}
{"_id": "d12469", "text": "def write_line(self, line, count=1):\n        \"\"\"writes the line and count newlines after the line\"\"\"\n        self.write(line)\n        self.write_newlines(count)", "title": ""}
{"_id": "d12470", "text": "def remove_from_lib(self, name):\n        \"\"\" Remove an object from the bin folder. \"\"\"\n        self.__remove_path(os.path.join(self.root_dir, \"lib\", name))", "title": ""}
{"_id": "d12471", "text": "def equal(obj1, obj2):\n    \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n    Comparable.log(obj1, obj2, '==')\n    equality = obj1.equality(obj2)\n    Comparable.log(obj1, obj2, '==', result=equality)\n    return equality", "title": ""}
{"_id": "d12472", "text": "def _trim(image):\n    \"\"\"Trim a PIL image and remove white space.\"\"\"\n    background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n    diff = PIL.ImageChops.difference(image, background)\n    diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n    bbox = diff.getbbox()\n    if bbox:\n        image = image.crop(bbox)\n    return image", "title": ""}
{"_id": "d12473", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d12474", "text": "def template_substitute(text, **kwargs):\n    \"\"\"\n    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.\n    \"\"\"\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", "title": ""}
{"_id": "d12475", "text": "def post_process(self):\n        \"\"\" Apply last 2D transforms\"\"\"\n        self.image.putdata(self.pixels)\n        self.image = self.image.transpose(Image.ROTATE_90)", "title": ""}
{"_id": "d12476", "text": "def all_collections(db):\n\t\"\"\"\n\tYield all non-sytem collections in db.\n\t\"\"\"\n\tinclude_pattern = r'(?!system\\.)'\n\treturn (\n\t\tdb[name]\n\t\tfor name in db.list_collection_names()\n\t\tif re.match(include_pattern, name)\n\t)", "title": ""}
{"_id": "d12477", "text": "def _serialize_json(obj, fp):\n    \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n    json.dump(obj, fp, indent=4, default=serialize)", "title": ""}
{"_id": "d12478", "text": "def calculate_month(birth_date):\n    \"\"\"\n    Calculates and returns a month number basing on PESEL standard.\n    \"\"\"\n    year = int(birth_date.strftime('%Y'))\n    month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20\n\n    return month", "title": ""}
{"_id": "d12479", "text": "def _dump_spec(spec):\n    \"\"\"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.\n    \"\"\"\n    with open(\"spec.yaml\", \"w\") as f:\n        yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False)", "title": ""}
{"_id": "d12480", "text": "def _truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):\n    \"\"\"\n    Truncates a colormap to use.\n    Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib\n    \"\"\"\n    new_cmap = LinearSegmentedColormap.from_list(\n        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),\n        cmap(numpy.linspace(minval, maxval, n))\n    )\n    return new_cmap", "title": ""}
{"_id": "d12481", "text": "def __eq__(self, other):\n        \"\"\"Determine if two objects are equal.\"\"\"\n        return isinstance(other, self.__class__) \\\n            and self._freeze() == other._freeze()", "title": ""}
{"_id": "d12482", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d12483", "text": "def _tool_to_dict(tool):\n    \"\"\"Parse a tool definition into a cwl2wdl style dictionary.\n    \"\"\"\n    out = {\"name\": _id_to_name(tool.tool[\"id\"]),\n           \"baseCommand\": \" \".join(tool.tool[\"baseCommand\"]),\n           \"arguments\": [],\n           \"inputs\": [_input_to_dict(i) for i in tool.tool[\"inputs\"]],\n           \"outputs\": [_output_to_dict(o) for o in tool.tool[\"outputs\"]],\n           \"requirements\": _requirements_to_dict(tool.requirements + tool.hints),\n           \"stdin\": None, \"stdout\": None}\n    return out", "title": ""}
{"_id": "d12484", "text": "def compare(string1, string2):\n    \"\"\"Compare two strings while protecting against timing attacks\n\n    :param str string1: the first string\n    :param str string2: the second string\n\n    :returns: True if the strings are equal, False if not\n    :rtype: :obj:`bool`\n    \"\"\"\n    if len(string1) != len(string2):\n        return False\n    result = True\n    for c1, c2 in izip(string1, string2):\n        result &= c1 == c2\n    return result", "title": ""}
{"_id": "d12485", "text": "def on_close(self, evt):\n    \"\"\"\n    Pop-up menu and wx.EVT_CLOSE closing event\n    \"\"\"\n    self.stop() # DoseWatcher\n    if evt.EventObject is not self: # Avoid deadlocks\n      self.Close() # wx.Frame\n    evt.Skip()", "title": ""}
{"_id": "d12486", "text": "def is_instance_or_subclass(val, class_):\n    \"\"\"Return True if ``val`` is either a subclass or instance of ``class_``.\"\"\"\n    try:\n        return issubclass(val, class_)\n    except TypeError:\n        return isinstance(val, class_)", "title": ""}
{"_id": "d12487", "text": "def on_close(self, evt):\n    \"\"\"\n    Pop-up menu and wx.EVT_CLOSE closing event\n    \"\"\"\n    self.stop() # DoseWatcher\n    if evt.EventObject is not self: # Avoid deadlocks\n      self.Close() # wx.Frame\n    evt.Skip()", "title": ""}
{"_id": "d12488", "text": "def _check_for_int(x):\n    \"\"\"\n    This is a compatibility function that takes a C{float} and converts it to an\n    C{int} if the values are equal.\n    \"\"\"\n    try:\n        y = int(x)\n    except (OverflowError, ValueError):\n        pass\n    else:\n        # There is no way in AMF0 to distinguish between integers and floats\n        if x == x and y == x:\n            return y\n\n    return x", "title": ""}
{"_id": "d12489", "text": "def disable_wx(self):\n        \"\"\"Disable event loop integration with wxPython.\n\n        This merely sets PyOS_InputHook to NULL.\n        \"\"\"\n        if self._apps.has_key(GUI_WX):\n            self._apps[GUI_WX]._in_event_loop = False\n        self.clear_inputhook()", "title": ""}
{"_id": "d12490", "text": "def _compile(pattern, flags):\n    \"\"\"Compile the pattern to regex.\"\"\"\n\n    return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())", "title": ""}
{"_id": "d12491", "text": "def on_close(self, evt):\n    \"\"\"\n    Pop-up menu and wx.EVT_CLOSE closing event\n    \"\"\"\n    self.stop() # DoseWatcher\n    if evt.EventObject is not self: # Avoid deadlocks\n      self.Close() # wx.Frame\n    evt.Skip()", "title": ""}
{"_id": "d12492", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d12493", "text": "def average(iterator):\n    \"\"\"Iterative mean.\"\"\"\n    count = 0\n    total = 0\n    for num in iterator:\n        count += 1\n        total += num\n    return float(total)/count", "title": ""}
{"_id": "d12494", "text": "def lower_ext(abspath):\n    \"\"\"Convert file extension to lowercase.\n    \"\"\"\n    fname, ext = os.path.splitext(abspath)\n    return fname + ext.lower()", "title": ""}
{"_id": "d12495", "text": "def str_is_well_formed(xml_str):\n    \"\"\"\n  Args:\n    xml_str : str\n      DataONE API XML doc.\n\n  Returns:\n    bool: **True** if XML doc is well formed.\n  \"\"\"\n    try:\n        str_to_etree(xml_str)\n    except xml.etree.ElementTree.ParseError:\n        return False\n    else:\n        return True", "title": ""}
{"_id": "d12496", "text": "def install_postgres(user=None, dbname=None, password=None):\n    \"\"\"Install Postgres on remote\"\"\"\n    execute(pydiploy.django.install_postgres_server,\n            user=user, dbname=dbname, password=password)", "title": ""}
{"_id": "d12497", "text": "def load_yaml(filepath):\n    \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n    with open(filepath) as f:\n        txt = f.read()\n    return yaml.load(txt)", "title": ""}
{"_id": "d12498", "text": "def atlasdb_format_query( query, values ):\n    \"\"\"\n    Turn a query into a string for printing.\n    Useful for debugging.\n    \"\"\"\n    return \"\".join( [\"%s %s\" % (frag, \"'%s'\" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split(\"?\"), values + (\"\",))] )", "title": ""}
{"_id": "d12499", "text": "def _compress_obj(obj, level):\n    \"\"\"Compress object to bytes.\n    \"\"\"\n    return zlib.compress(pickle.dumps(obj, protocol=2), level)", "title": ""}
{"_id": "d12500", "text": "def loads(string):\n  \"\"\"\n  Deserializes Java objects and primitive data serialized by ObjectOutputStream\n  from a string.\n  \"\"\"\n  f = StringIO.StringIO(string)\n  marshaller = JavaObjectUnmarshaller(f)\n  marshaller.add_transformer(DefaultObjectTransformer())\n  return marshaller.readObject()", "title": ""}
{"_id": "d12501", "text": "def replace_sys_args(new_args):\n    \"\"\"Temporarily replace sys.argv with current arguments\n\n    Restores sys.argv upon exit of the context manager.\n    \"\"\"\n    # Replace sys.argv arguments\n    # for module import\n    old_args = sys.argv\n    sys.argv = new_args\n    try:\n        yield\n    finally:\n        sys.argv = old_args", "title": ""}
{"_id": "d12502", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d12503", "text": "def mtf_unitransformer_all_layers_tiny():\n  \"\"\"Test out all the layers on local CPU.\"\"\"\n  hparams = mtf_unitransformer_tiny()\n  hparams.moe_num_experts = 4\n  hparams.moe_expert_x = 4\n  hparams.moe_expert_y = 4\n  hparams.moe_hidden_size = 512\n  hparams.layers = [\"self_att\", \"local_self_att\", \"moe_1d\", \"moe_2d\", \"drd\"]\n  return hparams", "title": ""}
{"_id": "d12504", "text": "def cumsum(inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1, len(newlist)):\n        newlist[i] = newlist[i] + newlist[i - 1]\n    return newlist", "title": ""}
{"_id": "d12505", "text": "def isbinary(*args):\n    \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n    return all(map(lambda c: isnumber(c) or isbool(c), args))", "title": ""}
{"_id": "d12506", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d12507", "text": "def out(self, output, newline=True):\n        \"\"\"Outputs a string to the console (stdout).\"\"\"\n        click.echo(output, nl=newline)", "title": ""}
{"_id": "d12508", "text": "def split_len(s, length):\n    \"\"\"split string *s* into list of strings no longer than *length*\"\"\"\n    return [s[i:i+length] for i in range(0, len(s), length)]", "title": ""}
{"_id": "d12509", "text": "def std_datestr(self, datestr):\n        \"\"\"Reformat a date string to standard format.\n        \"\"\"\n        return date.strftime(\n                self.str2date(datestr), self.std_dateformat)", "title": ""}
{"_id": "d12510", "text": "def each_img(img_dir):\n    \"\"\"\n    Reads and iterates through each image file in the given directory\n    \"\"\"\n    for fname in utils.each_img(img_dir):\n        fname = os.path.join(img_dir, fname)\n        yield cv.imread(fname), fname", "title": ""}
{"_id": "d12511", "text": "def clean(ctx, dry_run=False):\n    \"\"\"Cleanup generated document artifacts.\"\"\"\n    basedir = ctx.sphinx.destdir or \"build/docs\"\n    cleanup_dirs([basedir], dry_run=dry_run)", "title": ""}
{"_id": "d12512", "text": "def _join(verb):\n    \"\"\"\n    Join helper\n    \"\"\"\n    data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n    # Preserve x groups\n    if isinstance(verb.x, GroupedDataFrame):\n        data.plydata_groups = list(verb.x.plydata_groups)\n    return data", "title": ""}
{"_id": "d12513", "text": "def exit(self):\n        \"\"\"Handle interactive exit.\n\n        This method calls the ask_exit callback.\"\"\"\n        if self.confirm_exit:\n            if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):\n                self.ask_exit()\n        else:\n            self.ask_exit()", "title": ""}
{"_id": "d12514", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d12515", "text": "def format_float(value): # not used\n    \"\"\"Modified form of the 'g' format specifier.\n    \"\"\"\n    string = \"{:g}\".format(value).replace(\"e+\", \"e\")\n    string = re.sub(\"e(-?)0*(\\d+)\", r\"e\\1\\2\", string)\n    return string", "title": ""}
{"_id": "d12516", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d12517", "text": "def read_bytes(fo, writer_schema=None, reader_schema=None):\n    \"\"\"Bytes are encoded as a long followed by that many bytes of data.\"\"\"\n    size = read_long(fo)\n    return fo.read(size)", "title": ""}
{"_id": "d12518", "text": "async def iso(self, source):\n        \"\"\"Convert to timestamp.\"\"\"\n        from datetime import datetime\n        unix_timestamp = int(source)\n        return datetime.fromtimestamp(unix_timestamp).isoformat()", "title": ""}
{"_id": "d12519", "text": "def min_values(args):\n    \"\"\" Return possible range for min function. \"\"\"\n    return Interval(min(x.low for x in args), min(x.high for x in args))", "title": ""}
{"_id": "d12520", "text": "def convert_date(date):\n    \"\"\"Convert string to datetime object.\"\"\"\n    date = convert_month(date, shorten=False)\n    clean_string = convert_string(date)\n    return datetime.strptime(clean_string, DATE_FMT.replace('-',''))", "title": ""}
{"_id": "d12521", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d12522", "text": "def date_to_timestamp(date):\n    \"\"\"\n        date to unix timestamp in milliseconds\n    \"\"\"\n    date_tuple = date.timetuple()\n    timestamp = calendar.timegm(date_tuple) * 1000\n    return timestamp", "title": ""}
{"_id": "d12523", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d12524", "text": "def make_aware(dt):\n    \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n    return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "title": ""}
{"_id": "d12525", "text": "def is_palindrome(string, strict=True):\n    \"\"\"\n    Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome).\n\n    :param string: String to check.\n    :type string: str\n    :param strict: True if white spaces matter (default), false otherwise.\n    :type strict: bool\n    :return: True if the string is a palindrome (like \"otto\", or \"i topi non avevano nipoti\" if strict=False),\n    False otherwise\n    \"\"\"\n    if is_full_string(string):\n        if strict:\n            return reverse(string) == string\n        return is_palindrome(SPACES_RE.sub('', string))\n    return False", "title": ""}
{"_id": "d12526", "text": "def median_date(dt_list):\n    \"\"\"Calcuate median datetime from datetime list\n    \"\"\"\n    #dt_list_sort = sorted(dt_list)\n    idx = len(dt_list)/2\n    if len(dt_list) % 2 == 0:\n        md = mean_date([dt_list[idx-1], dt_list[idx]])\n    else:\n        md = dt_list[idx]\n    return md", "title": ""}
{"_id": "d12527", "text": "def getSystemVariable(self, remote, name):\n        \"\"\"Get single system variable from CCU / Homegear\"\"\"\n        if self._server is not None:\n            return self._server.getSystemVariable(remote, name)", "title": ""}
{"_id": "d12528", "text": "def parse_datetime(dt_str, format):\n    \"\"\"Create a timezone-aware datetime object from a datetime string.\"\"\"\n    t = time.strptime(dt_str, format)\n    return datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], pytz.UTC)", "title": ""}
{"_id": "d12529", "text": "def move_datetime_year(dt, direction, num_shifts):\n    \"\"\"\n    Move datetime 1 year in the chosen direction.\n    unit is a no-op, to keep the API the same as the day case\n    \"\"\"\n    delta = relativedelta(years=+num_shifts)\n    return _move_datetime(dt, direction, delta)", "title": ""}
{"_id": "d12530", "text": "def _int64_feature(value):\n  \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))", "title": ""}
{"_id": "d12531", "text": "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()", "title": ""}
{"_id": "d12532", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d12533", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d12534", "text": "def get_hline():\n    \"\"\" gets a horiztonal line \"\"\"\n    return Window(\n        width=LayoutDimension.exact(1),\n        height=LayoutDimension.exact(1),\n        content=FillControl('-', token=Token.Line))", "title": ""}
{"_id": "d12535", "text": "def _round_half_hour(record):\n    \"\"\"\n    Round a time DOWN to half nearest half-hour.\n    \"\"\"\n    k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))\n    return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)", "title": ""}
{"_id": "d12536", "text": "def softplus(attrs, inputs, proto_obj):\n    \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs", "title": ""}
{"_id": "d12537", "text": "def _DateToEpoch(date):\n  \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n  tz_zero = datetime.datetime.utcfromtimestamp(0)\n  diff_sec = int((date - tz_zero).total_seconds())\n  return diff_sec * 1000000", "title": ""}
{"_id": "d12538", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d12539", "text": "def serialize(self, value):\n        \"\"\"Takes a datetime object and returns a string\"\"\"\n        if isinstance(value, str):\n            return value\n        return value.strftime(DATETIME_FORMAT)", "title": ""}
{"_id": "d12540", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d12541", "text": "def __init__(self, xmin=0, ymin=0, xmax=1, ymax=1):\n        \"\"\"\n        Create the chart bounds with min max horizontal\n        and vertical values\n        \"\"\"\n        self._xmin = xmin\n        self._ymin = ymin\n        self._xmax = xmax\n        self._ymax = ymax", "title": ""}
{"_id": "d12542", "text": "def tfds_dir():\n  \"\"\"Path to tensorflow_datasets directory.\"\"\"\n  return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))", "title": ""}
{"_id": "d12543", "text": "def set_attached_console_visible(state):\n    \"\"\"Show/hide system console window attached to current process.\n       Return it's previous state.\n\n       Availability: Windows\"\"\"\n    flag = {True: SW_SHOW, False: SW_HIDE}\n    return bool(ShowWindow(console_window_handle, flag[state]))", "title": ""}
{"_id": "d12544", "text": "def __add__(self, other):\n        \"\"\"Left addition.\"\"\"\n        return chaospy.poly.collection.arithmetics.add(self, other)", "title": ""}
{"_id": "d12545", "text": "def setDictDefaults (d, defaults):\n  \"\"\"Sets all defaults for the given dictionary to those contained in a\n  second defaults dictionary.  This convenience method calls:\n\n    d.setdefault(key, value)\n\n  for each key and value in the given defaults dictionary.\n  \"\"\"\n  for key, val in defaults.items():\n    d.setdefault(key, val)\n\n  return d", "title": ""}
{"_id": "d12546", "text": "def colorize(string, color, *args, **kwargs):\n    \"\"\"\n    Implements string formatting along with color specified in colorama.Fore\n    \"\"\"\n    string = string.format(*args, **kwargs)\n    return color + string + colorama.Fore.RESET", "title": ""}
{"_id": "d12547", "text": "def getdefaultencoding():\n    \"\"\"Return IPython's guess for the default encoding for bytes as text.\n\n    Asks for stdin.encoding first, to match the calling Terminal, but that\n    is often None for subprocesses.  Fall back on locale.getpreferredencoding()\n    which should be a sensible platform default (that respects LANG environment),\n    and finally to sys.getdefaultencoding() which is the most conservative option,\n    and usually ASCII.\n    \"\"\"\n    enc = get_stream_enc(sys.stdin)\n    if not enc or enc=='ascii':\n        try:\n            # There are reports of getpreferredencoding raising errors\n            # in some cases, which may well be fixed, but let's be conservative here.\n            enc = locale.getpreferredencoding()\n        except Exception:\n            pass\n    return enc or sys.getdefaultencoding()", "title": ""}
{"_id": "d12548", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d12549", "text": "def update(packages, env=None, user=None):\n    \"\"\"\n    Update conda packages in a conda env\n\n    Attributes\n    ----------\n        packages: list of packages comma delimited\n    \"\"\"\n    packages = ' '.join(packages.split(','))\n    cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user)\n    return _execcmd(cmd, user=user)", "title": ""}
{"_id": "d12550", "text": "def delete_environment(self, environment_name):\n        \"\"\"\n        Deletes an environment\n        \"\"\"\n        self.ebs.terminate_environment(environment_name=environment_name, terminate_resources=True)", "title": ""}
{"_id": "d12551", "text": "def __add__(self, other):\n        \"\"\"Left addition.\"\"\"\n        return chaospy.poly.collection.arithmetics.add(self, other)", "title": ""}
{"_id": "d12552", "text": "def remove_instance(self, item):\n        \"\"\"Remove `instance` from model\"\"\"\n        self.instances.remove(item)\n        self.remove_item(item)", "title": ""}
{"_id": "d12553", "text": "def n_choose_k(n, k):\n    \"\"\" get the number of quartets as n-choose-k. This is used\n    in equal splits to decide whether a split should be exhaustively sampled\n    or randomly sampled. Edges near tips can be exhaustive while highly nested\n    edges probably have too many quartets\n    \"\"\"\n    return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1))", "title": ""}
{"_id": "d12554", "text": "def __delitem__ (self, key):\n        \"\"\"Remove key from dict.\"\"\"\n        self._keys.remove(key)\n        super(ListDict, self).__delitem__(key)", "title": ""}
{"_id": "d12555", "text": "def assert_exactly_one_true(bool_list):\n    \"\"\"This method asserts that only one value of the provided list is True.\n\n    :param bool_list: List of booleans to check\n    :return: True if only one value is True, False otherwise\n    \"\"\"\n    assert isinstance(bool_list, list)\n    counter = 0\n    for item in bool_list:\n        if item:\n            counter += 1\n    return counter == 1", "title": ""}
{"_id": "d12556", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d12557", "text": "def _get_node_path(self, node):\n        \"\"\"Return the path from the root to ``node`` as a list of node names.\"\"\"\n        path = []\n        while node.up:\n            path.append(node.name)\n            node = node.up\n        return list(reversed(path))", "title": ""}
{"_id": "d12558", "text": "def clean_out_dir(directory):\n    \"\"\"\n    Delete all the files and subdirectories in a directory.\n    \"\"\"\n    if not isinstance(directory, path):\n        directory = path(directory)\n    for file_path in directory.files():\n        file_path.remove()\n    for dir_path in directory.dirs():\n        dir_path.rmtree()", "title": ""}
{"_id": "d12559", "text": "def vec_angle(a, b):\n    \"\"\"\n    Calculate angle between two vectors\n    \"\"\"\n    cosang = np.dot(a, b)\n    sinang = fast_norm(np.cross(a, b))\n    return np.arctan2(sinang, cosang)", "title": ""}
{"_id": "d12560", "text": "def _delete_keys(dct, keys):\n    \"\"\"Returns a copy of dct without `keys` keys\n    \"\"\"\n    c = deepcopy(dct)\n    assert isinstance(keys, list)\n    for k in keys:\n        c.pop(k)\n    return c", "title": ""}
{"_id": "d12561", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d12562", "text": "def pop(h):\n    \"\"\"Pop the heap value from the heap.\"\"\"\n    n = h.size() - 1\n    h.swap(0, n)\n    down(h, 0, n)\n    return h.pop()", "title": ""}
{"_id": "d12563", "text": "def map_tree(visitor, tree):\n    \"\"\"Apply function to nodes\"\"\"\n    newn = [map_tree(visitor, node) for node in tree.nodes]\n    return visitor(tree, newn)", "title": ""}
{"_id": "d12564", "text": "def clear_global(self):\n        \"\"\"Clear only any cached global data.\n\n        \"\"\"\n        vname = self.varname\n        logger.debug(f'global clearning {vname}')\n        if vname in globals():\n            logger.debug('removing global instance var: {}'.format(vname))\n            del globals()[vname]", "title": ""}
{"_id": "d12565", "text": "def clean_dataframe(df):\n    \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n    df = df.fillna(method='ffill')\n    df = df.fillna(0.0)\n    return df", "title": ""}
{"_id": "d12566", "text": "def save_dot(self, fd):\n        \"\"\" Saves a representation of the case in the Graphviz DOT language.\n        \"\"\"\n        from pylon.io import DotWriter\n        DotWriter(self).write(fd)", "title": ""}
{"_id": "d12567", "text": "def scroll_up(self, locator):\n        \"\"\"Scrolls up to element\"\"\"\n        driver = self._current_application()\n        element = self._element_find(locator, True, True)\n        driver.execute_script(\"mobile: scroll\", {\"direction\": 'up', 'element': element.id})", "title": ""}
{"_id": "d12568", "text": "def guess_title(basename):\n    \"\"\" Attempt to guess the title from the filename \"\"\"\n\n    base, _ = os.path.splitext(basename)\n    return re.sub(r'[ _-]+', r' ', base).title()", "title": ""}
{"_id": "d12569", "text": "def transform(self, df):\n        \"\"\"\n        Transforms a DataFrame in place. Computes all outputs of the DataFrame.\n\n        Args:\n            df (pandas.DataFrame): DataFrame to transform.\n        \"\"\"\n        for name, function in self.outputs:\n            df[name] = function(df)", "title": ""}
{"_id": "d12570", "text": "def _name_exists(self, name):\n        \"\"\"\n        Checks if we already have an opened tab with the same name.\n        \"\"\"\n        for i in range(self.count()):\n            if self.tabText(i) == name:\n                return True\n        return False", "title": ""}
{"_id": "d12571", "text": "def mask_and_flatten(self):\n        \"\"\"Return a vector of the masked data.\n\n        Returns\n        -------\n        np.ndarray, tuple of indices (np.ndarray), tuple of the mask shape\n        \"\"\"\n        self._check_for_mask()\n\n        return self.get_data(smoothed=True, masked=True, safe_copy=False)[self.get_mask_indices()],\\\n               self.get_mask_indices(), self.mask.shape", "title": ""}
{"_id": "d12572", "text": "def size():\n    \"\"\"Determines the height and width of the console window\n\n        Returns:\n            tuple of int: The height in lines, then width in characters\n    \"\"\"\n    try:\n        assert os != 'nt' and sys.stdout.isatty()\n        rows, columns = os.popen('stty size', 'r').read().split()\n    except (AssertionError, AttributeError, ValueError):\n        # in case of failure, use dimensions of a full screen 13\" laptop\n        rows, columns = DEFAULT_HEIGHT, DEFAULT_WIDTH\n\n    return int(rows), int(columns)", "title": ""}
{"_id": "d12573", "text": "def lighting(im, b, c):\n    \"\"\" Adjust image balance and contrast \"\"\"\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)", "title": ""}
{"_id": "d12574", "text": "def stdin_readable():\n    \"\"\"Determine whether stdin has any data to read.\"\"\"\n    if not WINDOWS:\n        try:\n            return bool(select([sys.stdin], [], [], 0)[0])\n        except Exception:\n            logger.log_exc()\n    try:\n        return not sys.stdin.isatty()\n    except Exception:\n        logger.log_exc()\n    return False", "title": ""}
{"_id": "d12575", "text": "def _convert_dict_to_json(array):\n    \"\"\" Converts array to a json string \"\"\"\n    return json.dumps(\n        array,\n        skipkeys=False,\n        allow_nan=False,\n        indent=None,\n        separators=(\",\", \":\"),\n        sort_keys=True,\n        default=lambda o: o.__dict__,\n    )", "title": ""}
{"_id": "d12576", "text": "def isnamedtuple(obj):\n    \"\"\"Heuristic check if an object is a namedtuple.\"\"\"\n    return isinstance(obj, tuple) \\\n           and hasattr(obj, \"_fields\") \\\n           and hasattr(obj, \"_asdict\") \\\n           and callable(obj._asdict)", "title": ""}
{"_id": "d12577", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d12578", "text": "def is_real_floating_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a real floating point type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.floating)", "title": ""}
{"_id": "d12579", "text": "def ansi(color, text):\n    \"\"\"Wrap text in an ansi escape sequence\"\"\"\n    code = COLOR_CODES[color]\n    return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)", "title": ""}
{"_id": "d12580", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d12581", "text": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "title": ""}
{"_id": "d12582", "text": "def is_executable(path):\n  \"\"\"Returns whether a path names an existing executable file.\"\"\"\n  return os.path.isfile(path) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d12583", "text": "async def acquire_async(self):\n        \"\"\"Acquire the :attr:`lock` asynchronously\n\n        \"\"\"\n        r = self.acquire(blocking=False)\n        while not r:\n            await asyncio.sleep(.01)\n            r = self.acquire(blocking=False)", "title": ""}
{"_id": "d12584", "text": "def is_running(self):\n        \"\"\"Returns a bool determining if the process is in a running state or\n        not\n\n        :rtype: bool\n\n        \"\"\"\n        return self.state in [self.STATE_IDLE, self.STATE_ACTIVE,\n                              self.STATE_SLEEPING]", "title": ""}
{"_id": "d12585", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d12586", "text": "def get_unique_indices(df, axis=1):\n    \"\"\"\n\n    :param df:\n    :param axis:\n    :return:\n    \"\"\"\n    return dict(zip(df.columns.names, dif.columns.levels))", "title": ""}
{"_id": "d12587", "text": "def dumped(text, level, indent=2):\n    \"\"\"Put curly brackets round an indented text\"\"\"\n    return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "title": ""}
{"_id": "d12588", "text": "def ask_dir(self):\n\t\t\"\"\"\n\t\tdialogue box for choosing directory\n\t\t\"\"\"\n\t\targs ['directory'] = askdirectory(**self.dir_opt) \n\t\tself.dir_text.set(args ['directory'])", "title": ""}
{"_id": "d12589", "text": "def _mean_dict(dict_list):\n    \"\"\"Compute the mean value across a list of dictionaries\n    \"\"\"\n    return {k: np.array([d[k] for d in dict_list]).mean()\n            for k in dict_list[0].keys()}", "title": ""}
{"_id": "d12590", "text": "def dict_pop_or(d, key, default=None):\n    \"\"\" Try popping a key from a dict.\n        Instead of raising KeyError, just return the default value.\n    \"\"\"\n    val = default\n    with suppress(KeyError):\n        val = d.pop(key)\n    return val", "title": ""}
{"_id": "d12591", "text": "def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key):\n    \"\"\"Creates an AWS Chalice project for deployment to AWS Lambda.\"\"\"\n    from canari.commands.create_aws_lambda import create_aws_lambda\n    create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key)", "title": ""}
{"_id": "d12592", "text": "def update(dct, dct_merge):\n    \"\"\"Recursively merge dicts.\"\"\"\n    for key, value in dct_merge.items():\n        if key in dct and isinstance(dct[key], dict):\n            dct[key] = update(dct[key], value)\n        else:\n            dct[key] = value\n    return dct", "title": ""}
{"_id": "d12593", "text": "def _attrprint(d, delimiter=', '):\n    \"\"\"Print a dictionary of attributes in the DOT format\"\"\"\n    return delimiter.join(('\"%s\"=\"%s\"' % item) for item in sorted(d.items()))", "title": ""}
{"_id": "d12594", "text": "def file_writelines_flush_sync(path, lines):\n    \"\"\"\n    Fill file at @path with @lines then flush all buffers\n    (Python and system buffers)\n    \"\"\"\n    fp = open(path, 'w')\n    try:\n        fp.writelines(lines)\n        flush_sync_file_object(fp)\n    finally:\n        fp.close()", "title": ""}
{"_id": "d12595", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d12596", "text": "def get_object_as_string(obj):\n    \"\"\"\n    Converts any object to JSON-like readable format, ready to be printed for debugging purposes\n    :param obj: Any object\n    :return: string\n    \"\"\"\n    if isinstance(obj, str):\n        return obj\n    if isinstance(obj, list):\n        return '\\r\\n\\;'.join([get_object_as_string(item) for item in obj])\n    attrs = vars(obj)\n    as_string = ', '.join(\"%s: %s\" % item for item in attrs.items())\n    return as_string", "title": ""}
{"_id": "d12597", "text": "def dict_to_html_attrs(dict_):\n    \"\"\"\n    Banana banana\n    \"\"\"\n    res = ' '.join('%s=\"%s\"' % (k, v) for k, v in dict_.items())\n    return res", "title": ""}
{"_id": "d12598", "text": "def val_to_bin(edges, x):\n    \"\"\"Convert axis coordinate to bin index.\"\"\"\n    ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n    return ibin", "title": ""}
{"_id": "d12599", "text": "def get_from_human_key(self, key):\n        \"\"\"Return the key (aka database value) of a human key (aka Python identifier).\"\"\"\n        if key in self._identifier_map:\n            return self._identifier_map[key]\n        raise KeyError(key)", "title": ""}
{"_id": "d12600", "text": "def get_single_item(d):\n    \"\"\"Get an item from a dict which contains just one item.\"\"\"\n    assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)\n    return next(six.iteritems(d))", "title": ""}
{"_id": "d12601", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d12602", "text": "def _select_features(example, feature_list=None):\n  \"\"\"Select a subset of features from the example dict.\"\"\"\n  feature_list = feature_list or [\"inputs\", \"targets\"]\n  return {f: example[f] for f in feature_list}", "title": ""}
{"_id": "d12603", "text": "def b2u(string):\n    \"\"\" bytes to unicode \"\"\"\n    if (isinstance(string, bytes) or\n        (PY2 and isinstance(string, str))):\n        return string.decode('utf-8')\n    return string", "title": ""}
{"_id": "d12604", "text": "def pop (self, key):\n        \"\"\"Remove key from dict and return value.\"\"\"\n        if key in self._keys:\n            self._keys.remove(key)\n        super(ListDict, self).pop(key)", "title": ""}
{"_id": "d12605", "text": "def cpp_prog_builder(build_context, target):\n    \"\"\"Build a C++ binary executable\"\"\"\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)", "title": ""}
{"_id": "d12606", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d12607", "text": "def total_seconds(td):\n  \"\"\"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.\n  \"\"\"\n  secs = td.seconds + td.days * 24 * 3600\n  if td.microseconds:\n    secs += 1\n  return secs", "title": ""}
{"_id": "d12608", "text": "def calculate_delay(original, delay):\n    \"\"\"\n        Calculate the delay\n    \"\"\"\n    original = datetime.strptime(original, '%H:%M')\n    delayed = datetime.strptime(delay, '%H:%M')\n    diff = delayed - original\n    return diff.total_seconds() // 60", "title": ""}
{"_id": "d12609", "text": "def obj_to_string(obj, top=True):\n    \"\"\"\n    Turn an arbitrary object into a unicode string. If complex (dict/list/tuple), will be json-encoded.\n    \"\"\"\n    obj = prepare_for_json_encoding(obj)\n    if type(obj) == six.text_type:\n        return obj\n    return json.dumps(obj)", "title": ""}
{"_id": "d12610", "text": "def build_docs(directory):\n    \"\"\"Builds sphinx docs from a given directory.\"\"\"\n    os.chdir(directory)\n    process = subprocess.Popen([\"make\", \"html\"], cwd=directory)\n    process.communicate()", "title": ""}
{"_id": "d12611", "text": "def glog(x,l = 2):\n    \"\"\"\n    Generalised logarithm\n\n    :param x: number\n    :param p: number added befor logarithm \n\n    \"\"\"\n    return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)", "title": ""}
{"_id": "d12612", "text": "def angle(vec1, vec2):\n    \"\"\"Returns the angle between two vectors\"\"\"\n    dot_vec = dot(vec1, vec2)\n    mag1 = vec1.length()\n    mag2 = vec2.length()\n    result = dot_vec / (mag1 * mag2)\n    return math.acos(result)", "title": ""}
{"_id": "d12613", "text": "def makedirs(path, mode=0o777, exist_ok=False):\n    \"\"\"A wrapper of os.makedirs().\"\"\"\n    os.makedirs(path, mode, exist_ok)", "title": ""}
{"_id": "d12614", "text": "def _distance(coord1, coord2):\n    \"\"\"\n    Return the distance between two points, `coord1` and `coord2`. These\n    parameters are assumed to be (x, y) tuples.\n    \"\"\"\n    xdist = coord1[0] - coord2[0]\n    ydist = coord1[1] - coord2[1]\n    return sqrt(xdist*xdist + ydist*ydist)", "title": ""}
{"_id": "d12615", "text": "def num_leaves(tree):\n    \"\"\"Determine the number of leaves in a tree\"\"\"\n    if tree.is_leaf:\n        return 1\n    else:\n        return num_leaves(tree.left_child) + num_leaves(tree.right_child)", "title": ""}
{"_id": "d12616", "text": "async def join(self, ctx, *, channel: discord.VoiceChannel):\n        \"\"\"Joins a voice channel\"\"\"\n\n        if ctx.voice_client is not None:\n            return await ctx.voice_client.move_to(channel)\n\n        await channel.connect()", "title": ""}
{"_id": "d12617", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d12618", "text": "def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):\n  \"\"\"A block of standard 2d convolutions.\"\"\"\n  return conv_block_internal(conv, inputs, filters,\n                             dilation_rates_and_kernel_sizes, **kwargs)", "title": ""}
{"_id": "d12619", "text": "def _render_table(data, fields=None):\n  \"\"\" Helper to render a list of dictionaries as an HTML display object. \"\"\"\n  return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))", "title": ""}
{"_id": "d12620", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d12621", "text": "def vector_distance(a, b):\n    \"\"\"The Euclidean distance between two vectors.\"\"\"\n    a = np.array(a)\n    b = np.array(b)\n    return np.linalg.norm(a - b)", "title": ""}
{"_id": "d12622", "text": "def haversine(x):\n    \"\"\"Return the haversine of an angle\n\n    haversine(x) = sin(x/2)**2, where x is an angle in radians\n    \"\"\"\n    y = .5*x\n    y = np.sin(y)\n    return y*y", "title": ""}
{"_id": "d12623", "text": "def hamming(s, t):\n    \"\"\"\n    Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.\n\n    :param s: string 1\n    :type s: str\n    :param t: string 2\n    :type s: str\n    :return: Hamming distance\n    :rtype: float\n    \"\"\"\n    if len(s) != len(t):\n        raise ValueError('Hamming distance needs strings of equal length.')\n    return sum(s_ != t_ for s_, t_ in zip(s, t))", "title": ""}
{"_id": "d12624", "text": "def get_future_days(self):\n        \"\"\"Return only future Day objects.\"\"\"\n        today = timezone.now().date()\n\n        return Day.objects.filter(date__gte=today)", "title": ""}
{"_id": "d12625", "text": "def _nth(arr, n):\n    \"\"\"\n    Return the nth value of array\n\n    If it is missing return NaN\n    \"\"\"\n    try:\n        return arr.iloc[n]\n    except (KeyError, IndexError):\n        return np.nan", "title": ""}
{"_id": "d12626", "text": "def get_enum_documentation(class_name, module_name, enum_class_object):\n    documentation = \"\"\".. _{module_name}.{class_name}:\n\n``enum {class_name}``\n+++++++{plus}++\n\n**module:** ``{module_name}``\"\"\".format(\n        module_name=module_name,\n        class_name=class_name,\n        plus='+' * len(class_name),\n    )\n\n    if enum_class_object.__doc__ and enum_class_object.__doc__.strip():\n        documentation += '\\n\\n{}'.format(_clean_literals(inspect.cleandoc(enum_class_object.__doc__)))\n\n    documentation += '\\n\\nConstant Values:\\n'\n    for e in enum_class_object:\n        documentation += '\\n- ``{}`` (``{}``)'.format(e.name, repr(e.value).lstrip('u'))\n\n    return documentation", "title": ""}
{"_id": "d12627", "text": "def main(argv=sys.argv, stream=sys.stderr):\n    \"\"\"Entry point for ``tappy`` command.\"\"\"\n    args = parse_args(argv)\n    suite = build_suite(args)\n    runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)\n    result = runner.run(suite)\n\n    return get_status(result)", "title": ""}
{"_id": "d12628", "text": "def fill_document(doc):\n    \"\"\"Add a section, a subsection and some text to the document.\n\n    :param doc: the document\n    :type doc: :class:`pylatex.document.Document` instance\n    \"\"\"\n    with doc.create(Section('A section')):\n        doc.append('Some regular text and some ')\n        doc.append(italic('italic text. '))\n\n        with doc.create(Subsection('A subsection')):\n            doc.append('Also some crazy characters: $&#{}')", "title": ""}
{"_id": "d12629", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d12630", "text": "def fill_document(doc):\n    \"\"\"Add a section, a subsection and some text to the document.\n\n    :param doc: the document\n    :type doc: :class:`pylatex.document.Document` instance\n    \"\"\"\n    with doc.create(Section('A section')):\n        doc.append('Some regular text and some ')\n        doc.append(italic('italic text. '))\n\n        with doc.create(Subsection('A subsection')):\n            doc.append('Also some crazy characters: $&#{}')", "title": ""}
{"_id": "d12631", "text": "def uncamel(name):\n    \"\"\"Transform CamelCase naming convention into C-ish convention.\"\"\"\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()", "title": ""}
{"_id": "d12632", "text": "def update_redirect(self):\n        \"\"\"\n            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.\n        \"\"\"\n        page_history = Stack(session.get(\"page_history\", []))\n        page_history.push(request.url)\n        session[\"page_history\"] = page_history.to_json()", "title": ""}
{"_id": "d12633", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d12634", "text": "def dot_product(self, other):\n        \"\"\" Return the dot product of the given vectors. \"\"\"\n        return self.x * other.x + self.y * other.y", "title": ""}
{"_id": "d12635", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d12636", "text": "def resize_by_area(img, size):\n  \"\"\"image resize function used by quite a few image problems.\"\"\"\n  return tf.to_int64(\n      tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))", "title": ""}
{"_id": "d12637", "text": "def flat_list(input_list):\n    r\"\"\"\n    Given a list of nested lists of arbitrary depth, returns a single level or\n    'flat' list.\n\n    \"\"\"\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]", "title": ""}
{"_id": "d12638", "text": "def polyline(self, arr):\n        \"\"\"Draw a set of lines\"\"\"\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])", "title": ""}
{"_id": "d12639", "text": "def save_excel(self, fd):\n        \"\"\" Saves the case as an Excel spreadsheet.\n        \"\"\"\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)", "title": ""}
{"_id": "d12640", "text": "def xmltreefromfile(filename):\n    \"\"\"Internal function to read an XML file\"\"\"\n    try:\n        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n    except TypeError:\n        return ElementTree.parse(filename, ElementTree.XMLParser())", "title": ""}
{"_id": "d12641", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d12642", "text": "def _delete_keys(dct, keys):\n    \"\"\"Returns a copy of dct without `keys` keys\n    \"\"\"\n    c = deepcopy(dct)\n    assert isinstance(keys, list)\n    for k in keys:\n        c.pop(k)\n    return c", "title": ""}
{"_id": "d12643", "text": "def compress(obj):\n    \"\"\"Outputs json without whitespace.\"\"\"\n    return json.dumps(obj, sort_keys=True, separators=(',', ':'),\n                      cls=CustomEncoder)", "title": ""}
{"_id": "d12644", "text": "def cell(self, rowName, columnName):\n        \"\"\"\n        Returns the value of the cell on the given row and column.\n        \"\"\"\n        return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]]", "title": ""}
{"_id": "d12645", "text": "def deserialize_ndarray_npy(d):\n    \"\"\"\n    Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's\n    :obj:`save` function.\n\n    Args:\n        d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created\n            using :obj:`numpy.save`.\n\n    Returns:\n        An :obj:`ndarray` object.\n    \"\"\"\n    with io.BytesIO() as f:\n        f.write(json.loads(d['npy']).encode('latin-1'))\n        f.seek(0)\n        return np.load(f)", "title": ""}
{"_id": "d12646", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d12647", "text": "def convert(self, value, _type):\n        \"\"\"\n        Convert instances of textx types and match rules to python types.\n        \"\"\"\n        return self.type_convertors.get(_type, lambda x: x)(value)", "title": ""}
{"_id": "d12648", "text": "def _crop_list_to_size(l, size):\n    \"\"\"Make a list a certain size\"\"\"\n    for x in range(size - len(l)):\n        l.append(False)\n    for x in range(len(l) - size):\n        l.pop()\n    return l", "title": ""}
{"_id": "d12649", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d12650", "text": "def datetime_from_timestamp(timestamp, content):\n    \"\"\"\n    Helper function to add timezone information to datetime,\n    so that datetime is comparable to other datetime objects in recent versions\n    that now also have timezone information.\n    \"\"\"\n    return set_date_tzinfo(\n        datetime.fromtimestamp(timestamp),\n        tz_name=content.settings.get('TIMEZONE', None))", "title": ""}
{"_id": "d12651", "text": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "title": ""}
{"_id": "d12652", "text": "def arr_to_vector(arr):\n    \"\"\"Reshape a multidimensional array to a vector.\n    \"\"\"\n    dim = array_dim(arr)\n    tmp_arr = []\n    for n in range(len(dim) - 1):\n        for inner in arr:\n            for i in inner:\n                tmp_arr.append(i)\n        arr = tmp_arr\n        tmp_arr = []\n    return arr", "title": ""}
{"_id": "d12653", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d12654", "text": "def has_edit_permission(self, request):\n        \"\"\" Can edit this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "title": ""}
{"_id": "d12655", "text": "def _snake_to_camel_case(value):\n    \"\"\"Convert snake case string to camel case.\"\"\"\n    words = value.split(\"_\")\n    return words[0] + \"\".join(map(str.capitalize, words[1:]))", "title": ""}
{"_id": "d12656", "text": "def has_edit_permission(self, request):\n        \"\"\" Can edit this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "title": ""}
{"_id": "d12657", "text": "def get_index(self, bucket, index, startkey, endkey=None,\n                  return_terms=None, max_results=None, continuation=None,\n                  timeout=None, term_regex=None):\n        \"\"\"\n        Performs a secondary index query.\n        \"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d12658", "text": "def cartesian_product(arrays, flat=True, copy=False):\n    \"\"\"\n    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.\n    \"\"\"\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)", "title": ""}
{"_id": "d12659", "text": "def update_index(index):\n    \"\"\"Re-index every document in a named index.\"\"\"\n    logger.info(\"Updating search index: '%s'\", index)\n    client = get_client()\n    responses = []\n    for model in get_index_models(index):\n        logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n        objects = model.objects.get_search_queryset(index).iterator()\n        actions = bulk_actions(objects, index=index, action=\"index\")\n        response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n        responses.append(response)\n    return responses", "title": ""}
{"_id": "d12660", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d12661", "text": "def update_index(index):\n    \"\"\"Re-index every document in a named index.\"\"\"\n    logger.info(\"Updating search index: '%s'\", index)\n    client = get_client()\n    responses = []\n    for model in get_index_models(index):\n        logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n        objects = model.objects.get_search_queryset(index).iterator()\n        actions = bulk_actions(objects, index=index, action=\"index\")\n        response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n        responses.append(response)\n    return responses", "title": ""}
{"_id": "d12662", "text": "def scan(client, query=None, scroll='5m', raise_on_error=True,\n         preserve_order=False, size=1000, **kwargs):\n    \"\"\"\n    Simple abstraction on top of the\n    :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that\n    yields all hits as returned by underlining scroll requests.\n    By default scan does not return results in any pre-determined order. To\n    have a standard order in the returned documents (either by score or\n    explicit sort definition) when scrolling, use ``preserve_order=True``. This\n    may be an expensive operation and will negate the performance benefits of\n    using ``scan``.\n    :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n    :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api\n    :arg scroll: Specify how long a consistent view of the index should be\n        maintained for scrolled search\n    :arg raise_on_error: raises an exception (``ScanError``) if an error is\n        encountered (some shards fail to execute). By default we raise.\n    :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will\n        cause the scroll to paginate with preserving the order. Note that this\n        can be an extremely expensive operation and can easily lead to\n        unpredictable results, use with caution.\n    :arg size: size (per shard) of the batch send at each iteration.\n    Any additional keyword arguments will be passed to the initial\n    :meth:`~elasticsearch.Elasticsearch.search` call::\n        scan(es,\n            query={\"query\": {\"match\": {\"title\": \"python\"}}},\n            index=\"orders-*\",\n            doc_type=\"books\"\n        )\n    \"\"\"\n    if not preserve_order:\n        kwargs['search_type'] = 'scan'\n    # initial search\n    resp = client.search(body=query, scroll=scroll, size=size, **kwargs)\n\n    scroll_id = resp.get('_scroll_id')\n    if scroll_id is None:\n        return\n\n    first_run = True\n    while True:\n        # if we didn't set search_type to scan initial search contains data\n        if preserve_order and first_run:\n            first_run = False\n        else:\n            resp = client.scroll(scroll_id, scroll=scroll)\n\n        for hit in resp['hits']['hits']:\n            yield hit\n\n        # check if we have any errrors\n        if resp[\"_shards\"][\"failed\"]:\n            logger.warning(\n                'Scroll request has failed on %d shards out of %d.',\n                resp['_shards']['failed'], resp['_shards']['total']\n            )\n            if raise_on_error:\n                raise ScanError(\n                    'Scroll request has failed on %d shards out of %d.' %\n                    (resp['_shards']['failed'], resp['_shards']['total'])\n                )\n\n        scroll_id = resp.get('_scroll_id')\n        # end of scroll\n        if scroll_id is None or not resp['hits']['hits']:\n            break", "title": ""}
{"_id": "d12663", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d12664", "text": "def SegmentMin(a, ids):\n    \"\"\"\n    Segmented min op.\n    \"\"\"\n    func = lambda idxs: np.amin(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d12665", "text": "def str2bytes(x):\n  \"\"\"Convert input argument to bytes\"\"\"\n  if type(x) is bytes:\n    return x\n  elif type(x) is str:\n    return bytes([ ord(i) for i in x ])\n  else:\n    return str2bytes(str(x))", "title": ""}
{"_id": "d12666", "text": "def deduplicate(list_object):\n    \"\"\"Rebuild `list_object` removing duplicated and keeping order\"\"\"\n    new = []\n    for item in list_object:\n        if item not in new:\n            new.append(item)\n    return new", "title": ""}
{"_id": "d12667", "text": "def to_binary(s, encoding='utf8'):\n    \"\"\"Portable cast function.\n\n    In python 2 the ``str`` function which is used to coerce objects to bytes does not\n    accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n    :param s: object to be converted to binary_type\n    :return: binary_type instance, representing s.\n    \"\"\"\n    if PY3:  # pragma: no cover\n        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n    return binary_type(s)", "title": ""}
{"_id": "d12668", "text": "def indent(self):\n        \"\"\"\n        Begins an indented block. Must be used in a 'with' code block.\n        All calls to the logger inside of the block will be indented.\n        \"\"\"\n        blk = IndentBlock(self, self._indent)\n        self._indent += 1\n        return blk", "title": ""}
{"_id": "d12669", "text": "def safe_unicode(string):\n    \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n    if not PY3:\n        uni = string.replace(u'\\u2019', \"'\")\n        return uni.encode('utf-8')\n        \n    return string", "title": ""}
{"_id": "d12670", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d12671", "text": "def is_enum_type(type_):\n    \"\"\" Checks if the given type is an enum type.\n\n    :param type_: The type to check\n    :return: True if the type is a enum type, otherwise False\n    :rtype: bool\n    \"\"\"\n\n    return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))", "title": ""}
{"_id": "d12672", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d12673", "text": "def metres2latlon(mx, my, origin_shift= 2 * pi * 6378137 / 2.0):\n    \"\"\"Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in\n    WGS84 Datum\"\"\"\n    lon = (mx / origin_shift) * 180.0\n    lat = (my / origin_shift) * 180.0\n\n    lat = 180 / pi * (2 * atan( exp( lat * pi / 180.0)) - pi / 2.0)\n    return lat, lon", "title": ""}
{"_id": "d12674", "text": "def robust_int(v):\n    \"\"\"Parse an int robustly, ignoring commas and other cruft. \"\"\"\n\n    if isinstance(v, int):\n        return v\n\n    if isinstance(v, float):\n        return int(v)\n\n    v = str(v).replace(',', '')\n\n    if not v:\n        return None\n\n    return int(v)", "title": ""}
{"_id": "d12675", "text": "async def iso(self, source):\n        \"\"\"Convert to timestamp.\"\"\"\n        from datetime import datetime\n        unix_timestamp = int(source)\n        return datetime.fromtimestamp(unix_timestamp).isoformat()", "title": ""}
{"_id": "d12676", "text": "def set_font_size(self, size):\n        \"\"\"Convenience method for just changing font size.\"\"\"\n        if self.font.font_size == size:\n            pass\n        else:\n            self.font._set_size(size)", "title": ""}
{"_id": "d12677", "text": "def notin(arg, values):\n    \"\"\"\n    Like isin, but checks whether this expression's value(s) are not\n    contained in the passed values. See isin docs for full usage.\n    \"\"\"\n    op = ops.NotContains(arg, values)\n    return op.to_expr()", "title": ""}
{"_id": "d12678", "text": "def gray2bgr(img):\n    \"\"\"Convert a grayscale image to BGR image.\n\n    Args:\n        img (ndarray or str): The input image.\n\n    Returns:\n        ndarray: The converted BGR image.\n    \"\"\"\n    img = img[..., None] if img.ndim == 2 else img\n    out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n    return out_img", "title": ""}
{"_id": "d12679", "text": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "title": ""}
{"_id": "d12680", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d12681", "text": "def _escape(s):\n    \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n    e = s\n    e = e.replace('\\\\', '\\\\\\\\')\n    e = e.replace('\\n', '\\\\n')\n    e = e.replace('\\r', '\\\\r')\n    e = e.replace(\"'\", \"\\\\'\")\n    e = e.replace('\"', '\\\\\"')\n    return e", "title": ""}
{"_id": "d12682", "text": "def update_scale(self, value):\n        \"\"\" updates the scale of all actors in the plotter \"\"\"\n        self.plotter.set_scale(self.x_slider_group.value,\n                               self.y_slider_group.value,\n                               self.z_slider_group.value)", "title": ""}
{"_id": "d12683", "text": "def _from_dict(cls, _dict):\n        \"\"\"Initialize a KeyValuePair object from a json dictionary.\"\"\"\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)", "title": ""}
{"_id": "d12684", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d12685", "text": "def assert_exactly_one_true(bool_list):\n    \"\"\"This method asserts that only one value of the provided list is True.\n\n    :param bool_list: List of booleans to check\n    :return: True if only one value is True, False otherwise\n    \"\"\"\n    assert isinstance(bool_list, list)\n    counter = 0\n    for item in bool_list:\n        if item:\n            counter += 1\n    return counter == 1", "title": ""}
{"_id": "d12686", "text": "def str2int(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n    return NumConv(radix, alphabet).str2int(num)", "title": ""}
{"_id": "d12687", "text": "def fast_exit(code):\n    \"\"\"Exit without garbage collection, this speeds up exit by about 10ms for\n    things like bash completion.\n    \"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(code)", "title": ""}
{"_id": "d12688", "text": "def __exit__(self, type, value, traceback):\n        \"\"\"When the `with` statement ends.\"\"\"\n\n        if not self.asarfile:\n            return\n\n        self.asarfile.close()\n        self.asarfile = None", "title": ""}
{"_id": "d12689", "text": "def update_scale(self, value):\n        \"\"\" updates the scale of all actors in the plotter \"\"\"\n        self.plotter.set_scale(self.x_slider_group.value,\n                               self.y_slider_group.value,\n                               self.z_slider_group.value)", "title": ""}
{"_id": "d12690", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d12691", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d12692", "text": "def class_check(vector):\n    \"\"\"\n    Check different items in matrix classes.\n\n    :param vector: input vector\n    :type vector : list\n    :return: bool\n    \"\"\"\n    for i in vector:\n        if not isinstance(i, type(vector[0])):\n            return False\n    return True", "title": ""}
{"_id": "d12693", "text": "def indent(self):\n        \"\"\"\n        Begins an indented block. Must be used in a 'with' code block.\n        All calls to the logger inside of the block will be indented.\n        \"\"\"\n        blk = IndentBlock(self, self._indent)\n        self._indent += 1\n        return blk", "title": ""}
{"_id": "d12694", "text": "def _is_iterable(item):\n    \"\"\" Checks if an item is iterable (list, tuple, generator), but not string \"\"\"\n    return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)", "title": ""}
{"_id": "d12695", "text": "def cpp_checker(code, working_directory):\n    \"\"\"Return checker.\"\"\"\n    return gcc_checker(code, '.cpp',\n                       [os.getenv('CXX', 'g++'), '-std=c++0x'] + INCLUDE_FLAGS,\n                       working_directory=working_directory)", "title": ""}
{"_id": "d12696", "text": "def get_numbers(s):\n    \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n    result = map(int, re.findall(r'[0-9]+', unicode(s)))\n    return result + [1] * (2 - len(result))", "title": ""}
{"_id": "d12697", "text": "def is_number(obj):\n    \"\"\"Check if obj is number.\"\"\"\n    return isinstance(obj, (int, float, np.int_, np.float_))", "title": ""}
{"_id": "d12698", "text": "def get_by(self, name):\n    \"\"\"get element by name\"\"\"\n    return next((item for item in self if item.name == name), None)", "title": ""}
{"_id": "d12699", "text": "def starts_with_prefix_in_list(text, prefixes):\n    \"\"\"\n    Return True if the given string starts with one of the prefixes in the given list, otherwise\n    return False.\n\n    Arguments:\n        text (str): Text to check for prefixes.\n        prefixes (list): List of prefixes to check for.\n\n    Returns:\n        bool: True if the given text starts with any of the given prefixes, otherwise False.\n    \"\"\"\n    for prefix in prefixes:\n        if text.startswith(prefix):\n            return True\n    return False", "title": ""}
{"_id": "d12700", "text": "def contains_extractor(document):\n    \"\"\"A basic document feature extractor that returns a dict of words that the\n    document contains.\"\"\"\n    tokens = _get_document_tokens(document)\n    features = dict((u'contains({0})'.format(w), True) for w in tokens)\n    return features", "title": ""}
{"_id": "d12701", "text": "def get_url_args(url):\n    \"\"\" Returns a dictionary from a URL params \"\"\"\n    url_data = urllib.parse.urlparse(url)\n    arg_dict = urllib.parse.parse_qs(url_data.query)\n    return arg_dict", "title": ""}
{"_id": "d12702", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d12703", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d12704", "text": "def is_number(obj):\n    \"\"\"Check if obj is number.\"\"\"\n    return isinstance(obj, (int, float, np.int_, np.float_))", "title": ""}
{"_id": "d12705", "text": "def get_image_dimension(self, url):\n        \"\"\"\n        Return a tuple that contains (width, height)\n        Pass in a url to an image and find out its size without loading the whole file\n        If the image wxh could not be found, the tuple will contain `None` values\n        \"\"\"\n        w_h = (None, None)\n        try:\n            if url.startswith('//'):\n                url = 'http:' + url\n            data = requests.get(url).content\n            im = Image.open(BytesIO(data))\n\n            w_h = im.size\n        except Exception:\n            logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n        return w_h", "title": ""}
{"_id": "d12706", "text": "def is_number(obj):\n    \"\"\"Check if obj is number.\"\"\"\n    return isinstance(obj, (int, float, np.int_, np.float_))", "title": ""}
{"_id": "d12707", "text": "def open(name=None, fileobj=None, closefd=True):\n    \"\"\"\n    Use all decompressor possible to make the stream\n    \"\"\"\n    return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)", "title": ""}
{"_id": "d12708", "text": "def is_delimiter(line):\n    \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n    return bool(line) and line[0] in punctuation and line[0]*len(line) == line", "title": ""}
{"_id": "d12709", "text": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n    \"\"\"\n    http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n    \"\"\"\n    fft = np.fft.fft(data)\n    # n = len(data)\n    # timestep = 1.0 / fs\n    # freq = np.fft.fftfreq(n, d=timestep)\n    bp = fft.copy()\n\n    # Zero out fft coefficients\n    # bp[10:-10] = 0\n\n    # Normalise\n    # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n    bp *= fft.dot(fft) / bp.dot(bp)\n\n    # must multipy by 2 to get the correct amplitude\n    ibp = 12 * np.fft.ifft(bp)\n    return ibp", "title": ""}
{"_id": "d12710", "text": "def is_a_sequence(var, allow_none=False):\n    \"\"\" Returns True if var is a list or a tuple (but not a string!)\n    \"\"\"\n    return isinstance(var, (list, tuple)) or (var is None and allow_none)", "title": ""}
{"_id": "d12711", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d12712", "text": "def calculate_top_margin(self):\n\t\t\"\"\"\n\t\tCalculate the margin in pixels above the plot area, setting\n\t\tborder_top.\n\t\t\"\"\"\n\t\tself.border_top = 5\n\t\tif self.show_graph_title:\n\t\t\tself.border_top += self.title_font_size\n\t\tself.border_top += 5\n\t\tif self.show_graph_subtitle:\n\t\t\tself.border_top += self.subtitle_font_size", "title": ""}
{"_id": "d12713", "text": "def is_same_shape(self, other_im, check_channels=False):\n        \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n        Parameters\n        ----------\n        other_im : :obj:`Image`\n            image to compare\n        check_channels : bool\n            whether or not to check equality of the channels\n\n        Returns\n        -------\n        bool\n            True if the images are the same shape, False otherwise\n        \"\"\"\n        if self.height == other_im.height and self.width == other_im.width:\n            if check_channels and self.channels != other_im.channels:\n                return False\n            return True\n        return False", "title": ""}
{"_id": "d12714", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d12715", "text": "def isstring(value):\n    \"\"\"Report whether the given value is a byte or unicode string.\"\"\"\n    classes = (str, bytes) if pyutils.PY3 else basestring  # noqa: F821\n    return isinstance(value, classes)", "title": ""}
{"_id": "d12716", "text": "def update_hash(cls, filelike, digest):\n    \"\"\"Update the digest of a single file in a memory-efficient manner.\"\"\"\n    block_size = digest.block_size * 1024\n    for chunk in iter(lambda: filelike.read(block_size), b''):\n      digest.update(chunk)", "title": ""}
{"_id": "d12717", "text": "def _rectangular(n):\n    \"\"\"Checks to see if a 2D list is a valid 2D matrix\"\"\"\n    for i in n:\n        if len(i) != len(n[0]):\n            return False\n    return True", "title": ""}
{"_id": "d12718", "text": "def nb_to_python(nb_path):\n    \"\"\"convert notebook to python script\"\"\"\n    exporter = python.PythonExporter()\n    output, resources = exporter.from_filename(nb_path)\n    return output", "title": ""}
{"_id": "d12719", "text": "def memory_used(self):\n        \"\"\"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.\n        \"\"\"\n        if self._end_memory:\n            memory_used = self._end_memory - self._start_memory\n            return memory_used\n        else:\n            return None", "title": ""}
{"_id": "d12720", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d12721", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d12722", "text": "def selectin(table, field, value, complement=False):\n    \"\"\"Select rows where the given field is a member of the given value.\"\"\"\n\n    return select(table, field, lambda v: v in value,\n                  complement=complement)", "title": ""}
{"_id": "d12723", "text": "def _check_surrounded_by_space(self, tokens, i):\n        \"\"\"Check that a binary operator is surrounded by exactly one space.\"\"\"\n        self._check_space(tokens, i, (_MUST, _MUST))", "title": ""}
{"_id": "d12724", "text": "def __init__(self, function):\n\t\t\"\"\"function: to be called with each stream element as its\n\t\tonly argument\n\t\t\"\"\"\n\t\tsuper(filter, self).__init__()\n\t\tself.function = function", "title": ""}
{"_id": "d12725", "text": "def contains_geometric_info(var):\n    \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)", "title": ""}
{"_id": "d12726", "text": "def get_own_ip():\n    \"\"\"Get the host's ip number.\n    \"\"\"\n    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    try:\n        sock.connect((\"8.8.8.8\", 80))\n    except socket.gaierror:\n        ip_ = \"127.0.0.1\"\n    else:\n        ip_ = sock.getsockname()[0]\n    finally:\n        sock.close()\n    return ip_", "title": ""}
{"_id": "d12727", "text": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "title": ""}
{"_id": "d12728", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d12729", "text": "def load_library(version):\n    \"\"\"\n    Load the correct module according to the version\n\n    :type version: ``str``\n    :param version: the version of the library to be loaded (e.g. '2.6')\n    :rtype: module object\n    \"\"\"\n    check_version(version)\n    module_name = SUPPORTED_LIBRARIES[version]\n    lib = sys.modules.get(module_name)\n    if lib is None:\n        lib = importlib.import_module(module_name)\n    return lib", "title": ""}
{"_id": "d12730", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d12731", "text": "def _is_path(s):\n    \"\"\"Return whether an object is a path.\"\"\"\n    if isinstance(s, string_types):\n        try:\n            return op.exists(s)\n        except (OSError, ValueError):\n            return False\n    else:\n        return False", "title": ""}
{"_id": "d12732", "text": "def fit_linear(X, y):\n    \"\"\"\n    Uses OLS to fit the regression.\n    \"\"\"\n    model = linear_model.LinearRegression()\n    model.fit(X, y)\n    return model", "title": ""}
{"_id": "d12733", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d12734", "text": "def fit_gaussian(samples, ddof=0):\n    \"\"\"Calculates the mean and the standard deviation of the given samples.\n\n    Args:\n        samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all\n            values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension.\n        ddof (int): the difference degrees of freedom in the std calculation. See numpy.\n    \"\"\"\n    if len(samples.shape) == 1:\n        return np.mean(samples), np.std(samples, ddof=ddof)\n    return np.mean(samples, axis=1), np.std(samples, axis=1, ddof=ddof)", "title": ""}
{"_id": "d12735", "text": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "title": ""}
{"_id": "d12736", "text": "def fit_gaussian(x, y, yerr, p0):\n    \"\"\" Fit a Gaussian to the data \"\"\"\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", "title": ""}
{"_id": "d12737", "text": "def remove_unsafe_chars(text):\n    \"\"\"Remove unsafe unicode characters from a piece of text.\"\"\"\n    if isinstance(text, six.string_types):\n        text = UNSAFE_RE.sub('', text)\n    return text", "title": ""}
{"_id": "d12738", "text": "def resize(self, width, height):\n        \"\"\"\n        @summary: override resize function\n        @param width: {int} width of widget\n        @param height: {int} height of widget\n        \"\"\"\n        self._buffer = QtGui.QImage(width, height, QtGui.QImage.Format_RGB32)\n        QtGui.QWidget.resize(self, width, height)", "title": ""}
{"_id": "d12739", "text": "def check_by_selector(self, selector):\n    \"\"\"Check the checkbox matching the CSS selector.\"\"\"\n    elem = find_element_by_jquery(world.browser, selector)\n    if not elem.is_selected():\n        elem.click()", "title": ""}
{"_id": "d12740", "text": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "title": ""}
{"_id": "d12741", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d12742", "text": "def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):\n    \"\"\"webargs error handler that uses Flask-RESTful's abort function to return\n    a JSON error response to the client.\n    \"\"\"\n    abort(error_status_code, errors=err.messages)", "title": ""}
{"_id": "d12743", "text": "def logout():\n    \"\"\" Log out the active user\n    \"\"\"\n    flogin.logout_user()\n    next = flask.request.args.get('next')\n    return flask.redirect(next or flask.url_for(\"user\"))", "title": ""}
{"_id": "d12744", "text": "def logout():\n    \"\"\" Log out the active user\n    \"\"\"\n    flogin.logout_user()\n    next = flask.request.args.get('next')\n    return flask.redirect(next or flask.url_for(\"user\"))", "title": ""}
{"_id": "d12745", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d12746", "text": "def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,\ncontent=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for not-authorized access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=401)", "title": ""}
{"_id": "d12747", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d12748", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d12749", "text": "def colorbar(height, length, colormap):\n    \"\"\"Return the channels of a colorbar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.colorize(cbar)", "title": ""}
{"_id": "d12750", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d12751", "text": "def sample_colormap(cmap_name, n_samples):\n    \"\"\"\n    Sample a colormap from matplotlib\n    \"\"\"\n    colors = []\n    colormap = cm.cmap_d[cmap_name]\n    for i in np.linspace(0, 1, n_samples):\n        colors.append(colormap(i))\n\n    return colors", "title": ""}
{"_id": "d12752", "text": "def save_image(pdf_path, img_path, page_num):\n    \"\"\"\n\n    Creates images for a page of the input pdf document and saves it\n    at img_path.\n\n    :param pdf_path: path to pdf to create images for.\n    :param img_path: path where to save the images.\n    :param page_num: page number to create image from in the pdf file.\n    :return:\n    \"\"\"\n    pdf_img = Image(filename=\"{}[{}]\".format(pdf_path, page_num))\n    with pdf_img.convert(\"png\") as converted:\n        # Set white background.\n        converted.background_color = Color(\"white\")\n        converted.alpha_channel = \"remove\"\n        converted.save(filename=img_path)", "title": ""}
{"_id": "d12753", "text": "def flatten(nested):\n    \"\"\" Return a flatten version of the nested argument \"\"\"\n    flat_return = list()\n\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\n    __inner_flat(nested,flat_return)\n\n    return flat_return", "title": ""}
{"_id": "d12754", "text": "def hide(self):\n        \"\"\"Hides the main window of the terminal and sets the visible\n        flag to False.\n        \"\"\"\n        if not HidePrevention(self.window).may_hide():\n            return\n        self.hidden = True\n        self.get_widget('window-root').unstick()\n        self.window.hide()", "title": ""}
{"_id": "d12755", "text": "def flatten(nested):\n    \"\"\" Return a flatten version of the nested argument \"\"\"\n    flat_return = list()\n\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\n    __inner_flat(nested,flat_return)\n\n    return flat_return", "title": ""}
{"_id": "d12756", "text": "def autoscan():\n    \"\"\"autoscan will check all of the serial ports to see if they have\n       a matching VID:PID for a MicroPython board.\n    \"\"\"\n    for port in serial.tools.list_ports.comports():\n        if is_micropython_usb_device(port):\n            connect_serial(port[0])", "title": ""}
{"_id": "d12757", "text": "def flat_list(lst):\n    \"\"\"This function flatten given nested list.\n    Argument:\n        nested list\n    Returns:\n        flat list\n    \"\"\"\n    if isinstance(lst, list):\n        for item in lst:\n            for i in flat_list(item):\n                yield i\n    else:\n        yield lst", "title": ""}
{"_id": "d12758", "text": "def retrieve_by_id(self, id_):\n        \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n        items_with_id = [item for item in self if item.id == int(id_)]\n        if len(items_with_id) == 1:\n            return items_with_id[0].retrieve()", "title": ""}
{"_id": "d12759", "text": "def flatten(lis):\n    \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n    new_lis = []\n    for item in lis:\n        if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n            new_lis.extend(flatten(item))\n        else:\n            new_lis.append(item)\n    return new_lis", "title": ""}
{"_id": "d12760", "text": "def _compile(pattern, flags):\n    \"\"\"Compile the pattern to regex.\"\"\"\n\n    return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())", "title": ""}
{"_id": "d12761", "text": "def round_sig(x, sig):\n    \"\"\"Round the number to the specified number of significant figures\"\"\"\n    return round(x, sig - int(floor(log10(abs(x)))) - 1)", "title": ""}
{"_id": "d12762", "text": "def clean_whitespace(string, compact=False):\n    \"\"\"Return string with compressed whitespace.\"\"\"\n    for a, b in (('\\r\\n', '\\n'), ('\\r', '\\n'), ('\\n\\n', '\\n'),\n                 ('\\t', ' '), ('  ', ' ')):\n        string = string.replace(a, b)\n    if compact:\n        for a, b in (('\\n', ' '), ('[ ', '['),\n                     ('  ', ' '), ('  ', ' '), ('  ', ' ')):\n            string = string.replace(a, b)\n    return string.strip()", "title": ""}
{"_id": "d12763", "text": "def _convert(self, image, output=None):\n        \"\"\"Private method for converting a single PNG image to a PDF.\"\"\"\n        with Image.open(image) as im:\n            width, height = im.size\n\n            co = CanvasObjects()\n            co.add(CanvasImg(image, 1.0, w=width, h=height))\n\n            return WatermarkDraw(co, tempdir=self.tempdir, pagesize=(width, height)).write(output)", "title": ""}
{"_id": "d12764", "text": "def cor(y_true, y_pred):\n    \"\"\"Compute Pearson correlation coefficient.\n    \"\"\"\n    y_true, y_pred = _mask_nan(y_true, y_pred)\n    return np.corrcoef(y_true, y_pred)[0, 1]", "title": ""}
{"_id": "d12765", "text": "def _read_indexlist(self, name):\n        \"\"\"Read a list of indexes.\"\"\"\n        setattr(self, '_' + name, [self._timeline[int(i)] for i in\n                                   self.db.lrange('site:{0}'.format(name), 0,\n                                                  -1)])", "title": ""}
{"_id": "d12766", "text": "def flush(self):\n        \"\"\" Force commit changes to the file and stdout \"\"\"\n        if not self.nostdout:\n            self.stdout.flush()\n        if self.file is not None:\n            self.file.flush()", "title": ""}
{"_id": "d12767", "text": "def __add__(self, other):\n        \"\"\"Concatenate two InferenceData objects.\"\"\"\n        return concat(self, other, copy=True, inplace=False)", "title": ""}
{"_id": "d12768", "text": "def visit_Str(self, node):\n        \"\"\" Set the pythonic string type. \"\"\"\n        self.result[node] = self.builder.NamedType(pytype_to_ctype(str))", "title": ""}
{"_id": "d12769", "text": "def error_rate(predictions, labels):\n  \"\"\"Return the error rate based on dense predictions and 1-hot labels.\"\"\"\n  return 100.0 - (\n      100.0 *\n      np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) /\n      predictions.shape[0])", "title": ""}
{"_id": "d12770", "text": "def safe_format(s, **kwargs):\n  \"\"\"\n  :type s str\n  \"\"\"\n  return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))", "title": ""}
{"_id": "d12771", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d12772", "text": "def fixed(ctx, number, decimals=2, no_commas=False):\n    \"\"\"\n    Formats the given number in decimal format using a period and commas\n    \"\"\"\n    value = _round(ctx, number, decimals)\n    format_str = '{:f}' if no_commas else '{:,f}'\n    return format_str.format(value)", "title": ""}
{"_id": "d12773", "text": "def instance_contains(container, item):\n    \"\"\"Search into instance attributes, properties and return values of no-args methods.\"\"\"\n    return item in (member for _, member in inspect.getmembers(container))", "title": ""}
{"_id": "d12774", "text": "def median(ls):\n    \"\"\"\n    Takes a list and returns the median.\n    \"\"\"\n    ls = sorted(ls)\n    return ls[int(floor(len(ls)/2.0))]", "title": ""}
{"_id": "d12775", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d12776", "text": "def RMS_energy(frames):\n    \"\"\"Computes the RMS energy of frames\"\"\"\n    f = frames.flatten()\n    return N.sqrt(N.mean(f * f))", "title": ""}
{"_id": "d12777", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d12778", "text": "def INIT_LIST_EXPR(self, cursor):\n        \"\"\"Returns a list of literal values.\"\"\"\n        values = [self.parse_cursor(child)\n                  for child in list(cursor.get_children())]\n        return values", "title": ""}
{"_id": "d12779", "text": "def _convert_to_array(array_like, dtype):\n        \"\"\"\n        Convert Matrix attributes which are array-like or buffer to array.\n        \"\"\"\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)", "title": ""}
{"_id": "d12780", "text": "def remote_file_exists(self, url):\n        \"\"\" 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.\n        \"\"\"\n        status = requests.head(url).status_code\n\n        if status != 200:\n            raise RemoteFileDoesntExist", "title": ""}
{"_id": "d12781", "text": "async def _thread_coro(self, *args):\n        \"\"\" Coroutine called by MapAsync. It's wrapping the call of\n        run_in_executor to run the synchronous function as thread \"\"\"\n        return await self._loop.run_in_executor(\n            self._executor, self._function, *args)", "title": ""}
{"_id": "d12782", "text": "def sample_correlations(self):\n        \"\"\"Returns an `ExpMatrix` containing all pairwise sample correlations.\n\n        Returns\n        -------\n        `ExpMatrix`\n            The sample correlation matrix.\n\n        \"\"\"\n        C = np.corrcoef(self.X.T)\n        corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)\n        return corr_matrix", "title": ""}
{"_id": "d12783", "text": "def parameter_vector(self):\n        \"\"\"An array of all parameters (including frozen parameters)\"\"\"\n        return np.array([getattr(self, k) for k in self.parameter_names])", "title": ""}
{"_id": "d12784", "text": "def count_rows_with_nans(X):\n    \"\"\"Count the number of rows in 2D arrays that contain any nan values.\"\"\"\n    if X.ndim == 2:\n        return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()", "title": ""}
{"_id": "d12785", "text": "def log_loss(preds, labels):\n    \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n    log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n    return -log_likelihood", "title": ""}
{"_id": "d12786", "text": "def _calc_overlap_count(\n    markers1: dict,\n    markers2: dict,\n):\n    \"\"\"Calculate overlap count between the values of two dictionaries\n\n    Note: dict values must be sets\n    \"\"\"\n    overlaps=np.zeros((len(markers1), len(markers2)))\n\n    j=0\n    for marker_group in markers1:\n        tmp = [len(markers2[i].intersection(markers1[marker_group])) for i in markers2.keys()]\n        overlaps[j,:] = tmp\n        j += 1\n\n    return overlaps", "title": ""}
{"_id": "d12787", "text": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "title": ""}
{"_id": "d12788", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d12789", "text": "def to_snake_case(s):\n    \"\"\"Converts camel-case identifiers to snake-case.\"\"\"\n    return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)", "title": ""}
{"_id": "d12790", "text": "def coverage(ctx, opts=\"\"):\n    \"\"\"\n    Execute all tests (normal and slow) with coverage enabled.\n    \"\"\"\n    return test(ctx, coverage=True, include_slow=True, opts=opts)", "title": ""}
{"_id": "d12791", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d12792", "text": "def _array2cstr(arr):\n    \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())", "title": ""}
{"_id": "d12793", "text": "def unique(input_list):\n    \"\"\"\n    Return a list of unique items (similar to set functionality).\n\n    Parameters\n    ----------\n    input_list : list\n        A list containg some items that can occur more than once.\n\n    Returns\n    -------\n    list\n        A list with only unique occurances of an item.\n\n    \"\"\"\n    output = []\n    for item in input_list:\n        if item not in output:\n            output.append(item)\n    return output", "title": ""}
{"_id": "d12794", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d12795", "text": "def identifierify(name):\n    \"\"\" Clean up name so it works for a Python identifier. \"\"\"\n    name = name.lower()\n    name = re.sub('[^a-z0-9]', '_', name)\n    return name", "title": ""}
{"_id": "d12796", "text": "def reduce_freqs(freqlist):\n    \"\"\"\n    Add up a list of freq counts to get the total counts.\n    \"\"\"\n    allfreqs = np.zeros_like(freqlist[0])\n    for f in freqlist:\n        allfreqs += f\n    return allfreqs", "title": ""}
{"_id": "d12797", "text": "def _is_leap_year(year):\n    \"\"\"Determine if a year is leap year.\n\n    Parameters\n    ----------\n    year : numeric\n\n    Returns\n    -------\n    isleap : array of bools\n    \"\"\"\n    isleap = ((np.mod(year, 4) == 0) &\n              ((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0)))\n    return isleap", "title": ""}
{"_id": "d12798", "text": "def sent2features(sentence, template):\n    \"\"\" extract features in a sentence\n\n    :type sentence: list of token, each token is a list of tag\n    \"\"\"\n    return [word2features(sentence, i, template) for i in range(len(sentence))]", "title": ""}
{"_id": "d12799", "text": "def get_rounded(self, digits):\n        \"\"\" Return a vector with the elements rounded to the given number of digits. \"\"\"\n        result = self.copy()\n        result.round(digits)\n        return result", "title": ""}
{"_id": "d12800", "text": "def create(self, ami, count, config=None):\n        \"\"\"Create an instance using the launcher.\"\"\"\n        return self.Launcher(config=config).launch(ami, count)", "title": ""}
{"_id": "d12801", "text": "def def_linear(fun):\n    \"\"\"Flags that a function is linear wrt all args\"\"\"\n    defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:\n                  fun(*subval(args, argnum, g), **kwargs))", "title": ""}
{"_id": "d12802", "text": "def load(cls, tree_path):\n        \"\"\"Create a new instance from a file.\"\"\"\n        with open(tree_path) as f:\n            tree_dict = json.load(f)\n\n        return cls.from_dict(tree_dict)", "title": ""}
{"_id": "d12803", "text": "def parsed_args():\n    parser = argparse.ArgumentParser(description=\"\"\"python runtime functions\"\"\", epilog=\"\")\n    parser.add_argument('command',nargs='*',\n        help=\"Name of the function to run with arguments\")\n    args = parser.parse_args()\n    return (args, parser)", "title": ""}
{"_id": "d12804", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d12805", "text": "def interpolate_slice(slice_rows, slice_cols, interpolator):\n    \"\"\"Interpolate the given slice of the larger array.\"\"\"\n    fine_rows = np.arange(slice_rows.start, slice_rows.stop, slice_rows.step)\n    fine_cols = np.arange(slice_cols.start, slice_cols.stop, slice_cols.step)\n    return interpolator(fine_cols, fine_rows)", "title": ""}
{"_id": "d12806", "text": "def vectorize(values):\n    \"\"\"\n    Takes a value or list of values and returns a single result, joined by \",\"\n    if necessary.\n    \"\"\"\n    if isinstance(values, list):\n        return ','.join(str(v) for v in values)\n    return values", "title": ""}
{"_id": "d12807", "text": "def write_str2file(pathname, astr):\n    \"\"\"writes a string to file\"\"\"\n    fname = pathname\n    fhandle = open(fname, 'wb')\n    fhandle.write(astr)\n    fhandle.close()", "title": ""}
{"_id": "d12808", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d12809", "text": "def zeros(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.zeros`.\"\"\"\n        return self._write_op(self._zeros_nosync, name, **kwargs)", "title": ""}
{"_id": "d12810", "text": "def _rndPointDisposition(dx, dy):\n        \"\"\"Return random disposition point.\"\"\"\n        x = int(random.uniform(-dx, dx))\n        y = int(random.uniform(-dy, dy))\n        return (x, y)", "title": ""}
{"_id": "d12811", "text": "def dmap(fn, record):\n    \"\"\"map for a directory\"\"\"\n    values = (fn(v) for k, v in record.items())\n    return dict(itertools.izip(record, values))", "title": ""}
{"_id": "d12812", "text": "def rlognormal(mu, tau, size=None):\n    \"\"\"\n    Return random lognormal variates.\n    \"\"\"\n\n    return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "title": ""}
{"_id": "d12813", "text": "def create_dir_rec(path: Path):\n    \"\"\"\n    Create a folder recursive.\n\n    :param path: path\n    :type path: ~pathlib.Path\n    \"\"\"\n    if not path.exists():\n        Path.mkdir(path, parents=True, exist_ok=True)", "title": ""}
{"_id": "d12814", "text": "def _get_random_id():\n    \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n    symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(symbols) for _ in range(15))", "title": ""}
{"_id": "d12815", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d12816", "text": "def list_files(directory):\n    \"\"\"Returns all files in a given directory\n    \"\"\"\n    return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]", "title": ""}
{"_id": "d12817", "text": "def ensure_index(self, key, unique=False):\n        \"\"\"Wrapper for pymongo.Collection.ensure_index\n        \"\"\"\n        return self.collection.ensure_index(key, unique=unique)", "title": ""}
{"_id": "d12818", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d12819", "text": "def deskew(S):\n    \"\"\"Converts a skew-symmetric cross-product matrix to its corresponding\n    vector. Only works for 3x3 matrices.\n\n    Parameters\n    ----------\n    S : :obj:`numpy.ndarray` of float\n        A 3x3 skew-symmetric matrix.\n\n    Returns\n    -------\n    :obj:`numpy.ndarray` of float\n        A 3-entry vector that corresponds to the given cross product matrix.\n    \"\"\"\n    x = np.zeros(3)\n    x[0] = S[2,1]\n    x[1] = S[0,2]\n    x[2] = S[1,0]\n    return x", "title": ""}
{"_id": "d12820", "text": "def get_the_node_dict(G, name):\n    \"\"\"\n    Helper function that returns the node data\n    of the node with the name supplied\n    \"\"\"\n    for node in G.nodes(data=True):\n        if node[0] == name:\n            return node[1]", "title": ""}
{"_id": "d12821", "text": "def js_classnameify(s):\n  \"\"\"\n  Makes a classname.\n  \"\"\"\n  if not '_' in s:\n    return s\n  return ''.join(w[0].upper() + w[1:].lower() for w in s.split('_'))", "title": ""}
{"_id": "d12822", "text": "def rel_path(filename):\n    \"\"\"\n    Function that gets relative path to the filename\n    \"\"\"\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)", "title": ""}
{"_id": "d12823", "text": "def install_postgres(user=None, dbname=None, password=None):\n    \"\"\"Install Postgres on remote\"\"\"\n    execute(pydiploy.django.install_postgres_server,\n            user=user, dbname=dbname, password=password)", "title": ""}
{"_id": "d12824", "text": "def url(self):\n        \"\"\" The url of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.url", "title": ""}
{"_id": "d12825", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d12826", "text": "def uniq(seq):\n    \"\"\" Return a copy of seq without duplicates. \"\"\"\n    seen = set()\n    return [x for x in seq if str(x) not in seen and not seen.add(str(x))]", "title": ""}
{"_id": "d12827", "text": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "title": ""}
{"_id": "d12828", "text": "def items(self):\n    \"\"\"Return a list of the (name, value) pairs of the enum.\n\n    These are returned in the order they were defined in the .proto file.\n    \"\"\"\n    return [(value_descriptor.name, value_descriptor.number)\n            for value_descriptor in self._enum_type.values]", "title": ""}
{"_id": "d12829", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d12830", "text": "def double_sha256(data):\n    \"\"\"A standard compound hash.\"\"\"\n    return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())", "title": ""}
{"_id": "d12831", "text": "def get_url_file_name(url):\n    \"\"\"Get the file name from an url\n    \n    Parameters\n    ----------\n    url : str\n\n    Returns\n    -------\n    str\n        The file name \n    \"\"\"\n\n    assert isinstance(url, (str, _oldstr))\n    return urlparse.urlparse(url).path.split('/')[-1]", "title": ""}
{"_id": "d12832", "text": "def from_json(value, **kwargs):\n        \"\"\"Coerces JSON string to boolean\"\"\"\n        if isinstance(value, string_types):\n            value = value.upper()\n            if value in ('TRUE', 'Y', 'YES', 'ON'):\n                return True\n            if value in ('FALSE', 'N', 'NO', 'OFF'):\n                return False\n        if isinstance(value, int):\n            return value\n        raise ValueError('Could not load boolean from JSON: {}'.format(value))", "title": ""}
{"_id": "d12833", "text": "def validate(self, value, model_instance, **kwargs):\n        \"\"\"This follows the validate rules for choices_form_class field used.\n        \"\"\"\n        self.get_choices_form_class().validate(value, model_instance, **kwargs)", "title": ""}
{"_id": "d12834", "text": "def to_camel_case(text):\n    \"\"\"Convert to camel case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    split = text.split('_')\n    return split[0] + \"\".join(x.title() for x in split[1:])", "title": ""}
{"_id": "d12835", "text": "def snap_to_beginning_of_week(day, weekday_start=\"Sunday\"):\n    \"\"\" Get the first day of the current week.\n\n    :param day: The input date to snap.\n    :param weekday_start: Either \"Monday\" or \"Sunday\", indicating the first day of the week.\n    :returns: A date representing the first day of the current week.\n    \"\"\"\n    delta_days = ((day.weekday() + 1) % 7) if weekday_start is \"Sunday\" else day.weekday()\n    return day - timedelta(days=delta_days)", "title": ""}
{"_id": "d12836", "text": "def osx_clipboard_get():\n    \"\"\" Get the clipboard's text on OS X.\n    \"\"\"\n    p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n        stdout=subprocess.PIPE)\n    text, stderr = p.communicate()\n    # Text comes in with old Mac \\r line endings. Change them to \\n.\n    text = text.replace('\\r', '\\n')\n    return text", "title": ""}
{"_id": "d12837", "text": "def cric__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n    model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)\n\n    # we want to explain the raw probability outputs of the trees\n    model.predict = lambda X: model.predict_proba(X)[:,1]\n    \n    return model", "title": ""}
{"_id": "d12838", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d12839", "text": "def data_directory():\n    \"\"\"Return the absolute path to the directory containing the package data.\"\"\"\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")", "title": ""}
{"_id": "d12840", "text": "def get_free_memory_win():\n    \"\"\"Return current free memory on the machine for windows.\n\n    Warning : this script is really not robust\n    Return in MB unit\n    \"\"\"\n    stat = MEMORYSTATUSEX()\n    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n    return int(stat.ullAvailPhys / 1024 / 1024)", "title": ""}
{"_id": "d12841", "text": "def _DateToEpoch(date):\n  \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n  tz_zero = datetime.datetime.utcfromtimestamp(0)\n  diff_sec = int((date - tz_zero).total_seconds())\n  return diff_sec * 1000000", "title": ""}
{"_id": "d12842", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d12843", "text": "def get_current_branch():\n    \"\"\"\n    Return the current branch\n    \"\"\"\n    cmd = [\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\"]\n    output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n    return output.strip().decode(\"utf-8\")", "title": ""}
{"_id": "d12844", "text": "def ToDatetime(self):\n    \"\"\"Converts Timestamp to datetime.\"\"\"\n    return datetime.utcfromtimestamp(\n        self.seconds + self.nanos / float(_NANOS_PER_SECOND))", "title": ""}
{"_id": "d12845", "text": "def datetime_to_year_quarter(dt):\n    \"\"\"\n    Args:\n        dt: a datetime\n    Returns:\n        tuple of the datetime's year and quarter\n    \"\"\"\n    year = dt.year\n    quarter = int(math.ceil(float(dt.month)/3))\n    return (year, quarter)", "title": ""}
{"_id": "d12846", "text": "def date_to_timestamp(date):\n    \"\"\"\n        date to unix timestamp in milliseconds\n    \"\"\"\n    date_tuple = date.timetuple()\n    timestamp = calendar.timegm(date_tuple) * 1000\n    return timestamp", "title": ""}
{"_id": "d12847", "text": "def get_best_encoding(stream):\n    \"\"\"Returns the default stream encoding if not found.\"\"\"\n    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n    if is_ascii_encoding(rv):\n        return 'utf-8'\n    return rv", "title": ""}
{"_id": "d12848", "text": "def _defaultdict(dct, fallback=_illegal_character):\n    \"\"\"Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is\n    accessed.\n    \"\"\"\n    out = defaultdict(lambda: fallback)\n    for k, v in six.iteritems(dct):\n        out[k] = v\n    return out", "title": ""}
{"_id": "d12849", "text": "def parse_domain(url):\n    \"\"\" parse the domain from the url \"\"\"\n    domain_match = lib.DOMAIN_REGEX.match(url)\n    if domain_match:\n        return domain_match.group()", "title": ""}
{"_id": "d12850", "text": "def fromDict(cls, _dict):\n        \"\"\" Builds instance from dictionary of properties. \"\"\"\n        obj = cls()\n        obj.__dict__.update(_dict)\n        return obj", "title": ""}
{"_id": "d12851", "text": "def get_filetype_icon(fname):\n    \"\"\"Return file type icon\"\"\"\n    ext = osp.splitext(fname)[1]\n    if ext.startswith('.'):\n        ext = ext[1:]\n    return get_icon( \"%s.png\" % ext, ima.icon('FileIcon') )", "title": ""}
{"_id": "d12852", "text": "def remove_examples_all():\n    \"\"\"remove arduino/examples/all directory.\n\n    :rtype: None\n\n    \"\"\"\n    d = examples_all_dir()\n    if d.exists():\n        log.debug('remove %s', d)\n        d.rmtree()\n    else:\n        log.debug('nothing to remove: %s', d)", "title": ""}
{"_id": "d12853", "text": "def remove_columns(self, data, columns):\n        \"\"\" This method removes columns in data\n\n        :param data: original Pandas dataframe\n        :param columns: list of columns to remove\n        :type data: pandas.DataFrame\n        :type columns: list of strings\n\n        :returns: Pandas dataframe with removed columns\n        :rtype: pandas.DataFrame\n        \"\"\"\n\n        for column in columns:\n            if column in data.columns:\n                data = data.drop(column, axis=1)\n\n        return data", "title": ""}
{"_id": "d12854", "text": "def guess_media_type(filepath):\n    \"\"\"Returns the media-type of the file at the given ``filepath``\"\"\"\n    o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath])\n    o = o.strip()\n    return o", "title": ""}
{"_id": "d12855", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d12856", "text": "def clear_global(self):\n        \"\"\"Clear only any cached global data.\n\n        \"\"\"\n        vname = self.varname\n        logger.debug(f'global clearning {vname}')\n        if vname in globals():\n            logger.debug('removing global instance var: {}'.format(vname))\n            del globals()[vname]", "title": ""}
{"_id": "d12857", "text": "def rm_keys_from_dict(d, keys):\n    \"\"\"\n    Given a dictionary and a key list, remove any data in the dictionary with the given keys.\n\n    :param dict d: Metadata\n    :param list keys: Keys to be removed\n    :return dict d: Metadata\n    \"\"\"\n    # Loop for each key given\n    for key in keys:\n        # Is the key in the dictionary?\n        if key in d:\n            try:\n                d.pop(key, None)\n            except KeyError:\n                # Not concerned with an error. Keep going.\n                pass\n    return d", "title": ""}
{"_id": "d12858", "text": "def get_system_uid():\n    \"\"\"Get a (probably) unique ID to identify a system.\n    Used to differentiate votes.\n    \"\"\"\n    try:\n        if os.name == 'nt':\n            return get_nt_system_uid()\n        if sys.platform == 'darwin':\n            return get_osx_system_uid()\n    except Exception:\n        return get_mac_uid()\n    else:\n        return get_mac_uid()", "title": ""}
{"_id": "d12859", "text": "def ver_to_tuple(value):\n    \"\"\"\n    Convert version like string to a tuple of integers.\n    \"\"\"\n    return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "title": ""}
{"_id": "d12860", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d12861", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d12862", "text": "def on_press_key(key, callback, suppress=False):\n    \"\"\"\n    Invokes `callback` for KEY_DOWN event related to the given key. For details see `hook`.\n    \"\"\"\n    return hook_key(key, lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)", "title": ""}
{"_id": "d12863", "text": "def __getitem__(self, index):\n    \"\"\"Get the item at the given index.\n\n    Index is a tuple of (row, col)\n    \"\"\"\n    row, col = index\n    return self.rows[row][col]", "title": ""}
{"_id": "d12864", "text": "def pdf(x, mu, std):\n    \"\"\"Probability density function (normal distribution)\"\"\"\n    return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))", "title": ""}
{"_id": "d12865", "text": "def get_mtime(fname):\n        \"\"\"\n        Find the time this file was last modified.\n\n        :param fname: File name\n        :return: The last time the file was modified.\n        \"\"\"\n        try:\n            mtime = os.stat(fname).st_mtime_ns\n        except OSError:\n            # The file might be right in the middle of being written\n            # so sleep\n            time.sleep(1)\n            mtime = os.stat(fname).st_mtime_ns\n\n        return mtime", "title": ""}
{"_id": "d12866", "text": "def linregress(x, y, return_stats=False):\n    \"\"\"linear regression calculation\n\n    Parameters\n    ----\n    x :         independent variable (series)\n    y :         dependent variable (series)\n    return_stats : returns statistical values as well if required (bool)\n    \n\n    Returns\n    ----\n    list of parameters (and statistics)\n    \"\"\"\n    a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y)\n\n    retval = a1, a0\n    if return_stats:\n        retval += r_value, p_value, stderr\n\n    return retval", "title": ""}
{"_id": "d12867", "text": "def _get_current_label(self):\n        \"\"\"Get the label from the last line read\"\"\"\n        if len(self._last) == 0:\n            raise StopIteration\n        return self._last[:self._last.find(\":\")]", "title": ""}
{"_id": "d12868", "text": "def is_function(self):\n        \"\"\"return True if callback is a vanilla plain jane function\"\"\"\n        if self.is_instance() or self.is_class(): return False\n        return isinstance(self.callback, (Callable, classmethod))", "title": ""}
{"_id": "d12869", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d12870", "text": "def estimate_complexity(self, x,y,z,n):\n        \"\"\" \n        calculates a rough guess of runtime based on product of parameters \n        \"\"\"\n        num_calculations = x * y * z * n\n        run_time = num_calculations / 100000  # a 2014 PC does about 100k calcs in a second (guess based on prior logs)\n        return self.show_time_as_short_string(run_time)", "title": ""}
{"_id": "d12871", "text": "def dir_modtime(dpath):\n    \"\"\"\n    Returns the latest modification time of all files/subdirectories in a\n    directory\n    \"\"\"\n    return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))", "title": ""}
{"_id": "d12872", "text": "def splitBy(data, num):\n    \"\"\" Turn a list to list of list \"\"\"\n    return [data[i:i + num] for i in range(0, len(data), num)]", "title": ""}
{"_id": "d12873", "text": "def last_day(year=_year, month=_month):\n    \"\"\"\n    get the current month's last day\n    :param year:  default to current year\n    :param month:  default to current month\n    :return: month's last day\n    \"\"\"\n    last_day = calendar.monthrange(year, month)[1]\n    return datetime.date(year=year, month=month, day=last_day)", "title": ""}
{"_id": "d12874", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d12875", "text": "def last_day(year=_year, month=_month):\n    \"\"\"\n    get the current month's last day\n    :param year:  default to current year\n    :param month:  default to current month\n    :return: month's last day\n    \"\"\"\n    last_day = calendar.monthrange(year, month)[1]\n    return datetime.date(year=year, month=month, day=last_day)", "title": ""}
{"_id": "d12876", "text": "def get_entity_kind(self, model_obj):\n        \"\"\"\n        Returns a tuple for a kind name and kind display name of an entity.\n        By default, uses the app_label and model of the model object's content\n        type as the kind.\n        \"\"\"\n        model_obj_ctype = ContentType.objects.get_for_model(self.queryset.model)\n        return (u'{0}.{1}'.format(model_obj_ctype.app_label, model_obj_ctype.model), u'{0}'.format(model_obj_ctype))", "title": ""}
{"_id": "d12877", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d12878", "text": "def get_known_read_position(fp, buffered=True):\n    \"\"\" \n    Return a position in a file which is known to be read & handled.\n    It assumes a buffered file and streaming processing. \n    \"\"\"\n    buffer_size = io.DEFAULT_BUFFER_SIZE if buffered else 0\n    return max(fp.tell() - buffer_size, 0)", "title": ""}
{"_id": "d12879", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d12880", "text": "def unfolding(tens, i):\n    \"\"\"Compute the i-th unfolding of a tensor.\"\"\"\n    return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1))", "title": ""}
{"_id": "d12881", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d12882", "text": "def should_skip_logging(func):\n    \"\"\"\n    Should we skip logging for this handler?\n\n    \"\"\"\n    disabled = strtobool(request.headers.get(\"x-request-nolog\", \"false\"))\n    return disabled or getattr(func, SKIP_LOGGING, False)", "title": ""}
{"_id": "d12883", "text": "def _longest_val_in_column(self, col):\n        \"\"\"\n        get size of longest value in specific column\n\n        :param col: str, column name\n        :return int\n        \"\"\"\n        try:\n            # +2 is for implicit separator\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", "title": ""}
{"_id": "d12884", "text": "def disable_cert_validation():\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d12885", "text": "def get_memory_usage():\n    \"\"\"Gets RAM memory usage\n\n    :return: MB of memory used by this process\n    \"\"\"\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info().rss\n    return mem / (1024 * 1024)", "title": ""}
{"_id": "d12886", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d12887", "text": "def get_method_name(method):\n    \"\"\"\n    Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode\n    \"\"\"\n\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", "title": ""}
{"_id": "d12888", "text": "def _take_ownership(self):\n        \"\"\"Make the Python instance take ownership of the GIBaseInfo. i.e.\n        unref if the python instance gets gc'ed.\n        \"\"\"\n\n        if self:\n            ptr = cast(self.value, GIBaseInfo)\n            _UnrefFinalizer.track(self, ptr)\n            self.__owns = True", "title": ""}
{"_id": "d12889", "text": "async def delete(self):\n        \"\"\"\n        Delete this message\n\n        :return: bool\n        \"\"\"\n        return await self.bot.delete_message(self.chat.id, self.message_id)", "title": ""}
{"_id": "d12890", "text": "def get_month_namedays(self, month=None):\n        \"\"\"Return names as a tuple based on given month.\n        If no month given, use current one\"\"\"\n        if month is None:\n            month = datetime.now().month\n        return self.NAMEDAYS[month-1]", "title": ""}
{"_id": "d12891", "text": "def get_system_root_directory():\n    \"\"\"\n    Get system root directory (application installed root directory)\n\n    Returns\n    -------\n    string\n        A full path\n\n    \"\"\"\n    root = os.path.dirname(__file__)\n    root = os.path.dirname(root)\n    root = os.path.abspath(root)\n    return root", "title": ""}
{"_id": "d12892", "text": "def yank(event):\n    \"\"\"\n    Paste before cursor.\n    \"\"\"\n    event.current_buffer.paste_clipboard_data(\n        event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)", "title": ""}
{"_id": "d12893", "text": "def consecutive(data, stepsize=1):\n    \"\"\"Converts array into chunks with consecutive elements of given step size.\n    http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy\n    \"\"\"\n    return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)", "title": ""}
{"_id": "d12894", "text": "def _nth(arr, n):\n    \"\"\"\n    Return the nth value of array\n\n    If it is missing return NaN\n    \"\"\"\n    try:\n        return arr.iloc[n]\n    except (KeyError, IndexError):\n        return np.nan", "title": ""}
{"_id": "d12895", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d12896", "text": "def _jit_pairwise_distances(pos1, pos2):\n        \"\"\"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.\n        \"\"\"\n        n1 = pos1.shape[0]\n        n2 = pos2.shape[0]\n        D = np.empty((n1, n2))\n\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", "title": ""}
{"_id": "d12897", "text": "def _update_globals():\n    \"\"\"\n    Patch the globals to remove the objects not available on some platforms.\n\n    XXX it'd be better to test assertions about bytecode instead.\n    \"\"\"\n\n    if not sys.platform.startswith('java') and sys.platform != 'cli':\n        return\n    incompatible = 'extract_constant', 'get_module_constant'\n    for name in incompatible:\n        del globals()[name]\n        __all__.remove(name)", "title": ""}
{"_id": "d12898", "text": "def url_to_image(url):\n    \"\"\"\n    Fetch an image from url and convert it into a Pillow Image object\n    \"\"\"\n    r = requests.get(url)\n    image = StringIO(r.content)\n    return image", "title": ""}
{"_id": "d12899", "text": "def do_exit(self, arg):\n        \"\"\"Exit the shell session.\"\"\"\n\n        if self.current:\n            self.current.close()\n        self.resource_manager.close()\n        del self.resource_manager\n        return True", "title": ""}
{"_id": "d12900", "text": "def get_content_type (headers):\n    \"\"\"\n    Get the MIME type from the Content-Type header value, or\n    'application/octet-stream' if not found.\n\n    @return: MIME type\n    @rtype: string\n    \"\"\"\n    ptype = headers.get('Content-Type', 'application/octet-stream')\n    if \";\" in ptype:\n        # split off not needed extension info\n        ptype = ptype.split(';')[0]\n    return ptype.strip().lower()", "title": ""}
{"_id": "d12901", "text": "def security(self):\n        \"\"\"Print security object information for a pdf document\"\"\"\n        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}", "title": ""}
{"_id": "d12902", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d12903", "text": "def get_property_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d12904", "text": "def call_with_context(func, context, *args):\n    \"\"\"\n    Check if given function has more arguments than given. Call it with context\n    as last argument or without it.\n    \"\"\"\n    return make_context_aware(func, len(args))(*args + (context,))", "title": ""}
{"_id": "d12905", "text": "def min_depth(self, root):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: int\n    \"\"\"\n    if root is None:\n        return 0\n    if root.left is not None or root.right is not None:\n        return max(self.minDepth(root.left), self.minDepth(root.right))+1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1", "title": ""}
{"_id": "d12906", "text": "def unit_ball_L2(shape):\n  \"\"\"A tensorflow variable tranfomed to be constrained in a L2 unit ball.\n\n  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n  they are strong attacks. We are not yet confident in this code.\n  \"\"\"\n  x = tf.Variable(tf.zeros(shape))\n  return constrain_L2(x)", "title": ""}
{"_id": "d12907", "text": "def get_screen_resolution(self):\n        \"\"\"Return the screen resolution of the primary screen.\"\"\"\n        widget = QDesktopWidget()\n        geometry = widget.availableGeometry(widget.primaryScreen())\n        return geometry.width(), geometry.height()", "title": ""}
{"_id": "d12908", "text": "def dot(self, w):\n        \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n        return sum([x * y for x, y in zip(self, w)])", "title": ""}
{"_id": "d12909", "text": "def get_list_dimensions(_list):\n    \"\"\"\n    Takes a nested list and returns the size of each dimension followed\n    by the element type in the list\n    \"\"\"\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []", "title": ""}
{"_id": "d12910", "text": "def downsample_with_striding(array, factor):\n    \"\"\"Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x.\n    \"\"\"\n    return array[tuple(np.s_[::f] for f in factor)]", "title": ""}
{"_id": "d12911", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d12912", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d12913", "text": "def _extract_traceback(start):\n    \"\"\"\n    SNAGGED FROM traceback.py\n\n    RETURN list OF dicts DESCRIBING THE STACK TRACE\n    \"\"\"\n    tb = sys.exc_info()[2]\n    for i in range(start):\n        tb = tb.tb_next\n    return _parse_traceback(tb)", "title": ""}
{"_id": "d12914", "text": "def print_display_png(o):\n    \"\"\"\n    A function to display sympy expression using display style LaTeX in PNG.\n    \"\"\"\n    s = latex(o, mode='plain')\n    s = s.strip('$')\n    # As matplotlib does not support display style, dvipng backend is\n    # used here.\n    png = latex_to_png('$$%s$$' % s, backend='dvipng')\n    return png", "title": ""}
{"_id": "d12915", "text": "async def json_or_text(response):\n    \"\"\"Turns response into a properly formatted json or text object\"\"\"\n    text = await response.text()\n    if response.headers['Content-Type'] == 'application/json; charset=utf-8':\n        return json.loads(text)\n    return text", "title": ""}
{"_id": "d12916", "text": "def del_Unnamed(df):\n    \"\"\"\n    Deletes all the unnamed columns\n\n    :param df: pandas dataframe\n    \"\"\"\n    cols_del=[c for c in df.columns if 'Unnamed' in c]\n    return df.drop(cols_del,axis=1)", "title": ""}
{"_id": "d12917", "text": "def get_month_start(day=None):\n    \"\"\"Returns the first day of the given month.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(day=1)", "title": ""}
{"_id": "d12918", "text": "def __call__(self, *args, **kwargs):\n        \"\"\" Instanciates a new *Document* from this collection \"\"\"\n        kwargs[\"mongokat_collection\"] = self\n        return self.document_class(*args, **kwargs)", "title": ""}
{"_id": "d12919", "text": "def encode_batch(self, inputBatch):\n        \"\"\"Encodes a whole batch of input arrays, without learning.\"\"\"\n        X      = inputBatch\n        encode = self.encode\n        Y      = np.array([ encode(x) for x in X])\n        return Y", "title": ""}
{"_id": "d12920", "text": "def tail(self, n=10):\n        \"\"\"\n        Get an SArray that contains the last n elements in the SArray.\n\n        Parameters\n        ----------\n        n : int\n            The number of elements to fetch\n\n        Returns\n        -------\n        out : SArray\n            A new SArray which contains the last n rows of the current SArray.\n        \"\"\"\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.tail(n))", "title": ""}
{"_id": "d12921", "text": "def lmx_h1k_f64k():\n  \"\"\"HParams for training languagemodel_lm1b32k_packed.  880M Params.\"\"\"\n  hparams = lmx_base()\n  hparams.hidden_size = 1024\n  hparams.filter_size = 65536\n  hparams.batch_size = 2048\n  return hparams", "title": ""}
{"_id": "d12922", "text": "def check_output(args, env=None, sp=subprocess):\n    \"\"\"Call an external binary and return its stdout.\"\"\"\n    log.debug('calling %s with env %s', args, env)\n    output = sp.check_output(args=args, env=env)\n    log.debug('output: %r', output)\n    return output", "title": ""}
{"_id": "d12923", "text": "def a2s(a):\n    \"\"\"\n     convert 3,3 a matrix to 6 element \"s\" list  (see Tauxe 1998)\n    \"\"\"\n    s = np.zeros((6,), 'f')  # make the a matrix\n    for i in range(3):\n        s[i] = a[i][i]\n    s[3] = a[0][1]\n    s[4] = a[1][2]\n    s[5] = a[0][2]\n    return s", "title": ""}
{"_id": "d12924", "text": "def convert_2_utc(self, datetime_, timezone):\n        \"\"\"convert to datetime to UTC offset.\"\"\"\n\n        datetime_ = self.tz_mapper[timezone].localize(datetime_)\n        return datetime_.astimezone(pytz.UTC)", "title": ""}
{"_id": "d12925", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d12926", "text": "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()", "title": ""}
{"_id": "d12927", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d12928", "text": "def accuracy(conf_matrix):\n  \"\"\"\n  Given a confusion matrix, returns the accuracy.\n  Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml\n  \"\"\"\n  total, correct = 0.0, 0.0\n  for true_response, guess_dict in conf_matrix.items():\n    for guess, count in guess_dict.items():\n      if true_response == guess:\n        correct += count\n      total += count\n  return correct/total", "title": ""}
{"_id": "d12929", "text": "def to_binary(s, encoding='utf8'):\n    \"\"\"Portable cast function.\n\n    In python 2 the ``str`` function which is used to coerce objects to bytes does not\n    accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n    :param s: object to be converted to binary_type\n    :return: binary_type instance, representing s.\n    \"\"\"\n    if PY3:  # pragma: no cover\n        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n    return binary_type(s)", "title": ""}
{"_id": "d12930", "text": "def get_value(key, obj, default=missing):\n    \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n    if isinstance(key, int):\n        return _get_value_for_key(key, obj, default)\n    return _get_value_for_keys(key.split('.'), obj, default)", "title": ""}
{"_id": "d12931", "text": "def _Enum(docstring, *names):\n  \"\"\"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.\n  \"\"\"\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)", "title": ""}
{"_id": "d12932", "text": "def restore_image_options(cli, image, options):\n    \"\"\" 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.\n    \"\"\"\n    dockerfile = io.StringIO()\n\n    dockerfile.write(u'FROM {image}\\nCMD {cmd}'.format(\n        image=image, cmd=json.dumps(options['cmd'])))\n\n    if options['entrypoint']:\n        dockerfile.write(\n            '\\nENTRYPOINT {}'.format(json.dumps(options['entrypoint'])))\n\n    cli.build(tag=image, fileobj=dockerfile)", "title": ""}
{"_id": "d12933", "text": "def getSystemVariable(self, remote, name):\n        \"\"\"Get single system variable from CCU / Homegear\"\"\"\n        if self._server is not None:\n            return self._server.getSystemVariable(remote, name)", "title": ""}
{"_id": "d12934", "text": "def session_to_epoch(timestamp):\n    \"\"\" converts Synergy Timestamp for session to UTC zone seconds since epoch \"\"\"\n    utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()\n    return calendar.timegm(utc_timetuple)", "title": ""}
{"_id": "d12935", "text": "def branches(self):\n        \"\"\"All branches in a list\"\"\"\n        result = self.git(self.default + ['branch', '-a', '--no-color'])\n        return [l.strip(' *\\n') for l in result.split('\\n') if l.strip(' *\\n')]", "title": ""}
{"_id": "d12936", "text": "def get_sparse_matrix_keys(session, key_table):\n    \"\"\"Return a list of keys for the sparse matrix.\"\"\"\n    return session.query(key_table).order_by(key_table.name).all()", "title": ""}
{"_id": "d12937", "text": "def case_us2mc(x):\n    \"\"\" underscore to mixed case notation \"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)", "title": ""}
{"_id": "d12938", "text": "def rdist(x, y):\n    \"\"\"Reduced Euclidean distance.\n\n    Parameters\n    ----------\n    x: array of shape (embedding_dim,)\n    y: array of shape (embedding_dim,)\n\n    Returns\n    -------\n    The squared euclidean distance between x and y\n    \"\"\"\n    result = 0.0\n    for i in range(x.shape[0]):\n        result += (x[i] - y[i]) ** 2\n\n    return result", "title": ""}
{"_id": "d12939", "text": "def _to_hours_mins_secs(time_taken):\n    \"\"\"Convert seconds to hours, mins, and seconds.\"\"\"\n    mins, secs = divmod(time_taken, 60)\n    hours, mins = divmod(mins, 60)\n    return hours, mins, secs", "title": ""}
{"_id": "d12940", "text": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "title": ""}
{"_id": "d12941", "text": "def restore_default_settings():\n    \"\"\" Restore settings to default values. \n    \"\"\"\n    global __DEFAULTS\n    __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR\n    __DEFAULTS.SET_SEED = defaults.SET_SEED\n    __DEFAULTS.SEED = defaults.SEED\n    logging.info('Settings reverted to their default values.')", "title": ""}
{"_id": "d12942", "text": "def get_all_attributes(klass_or_instance):\n    \"\"\"Get all attribute members (attribute, property style method).\n    \"\"\"\n    pairs = list()\n    for attr, value in inspect.getmembers(\n            klass_or_instance, lambda x: not inspect.isroutine(x)):\n        if not (attr.startswith(\"__\") or attr.endswith(\"__\")):\n            pairs.append((attr, value))\n    return pairs", "title": ""}
{"_id": "d12943", "text": "def query_proc_row(procname, args=(), factory=None):\n    \"\"\"\n    Execute a stored procedure. Returns the first row of the result set,\n    or `None`.\n    \"\"\"\n    for row in query_proc(procname, args, factory):\n        return row\n    return None", "title": ""}
{"_id": "d12944", "text": "def _check_graphviz_available(output_format):\n    \"\"\"check if we need graphviz for different output format\"\"\"\n    try:\n        subprocess.call([\"dot\", \"-V\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    except OSError:\n        print(\n            \"The output format '%s' is currently not available.\\n\"\n            \"Please install 'Graphviz' to have other output formats \"\n            \"than 'dot' or 'vcg'.\" % output_format\n        )\n        sys.exit(32)", "title": ""}
{"_id": "d12945", "text": "def load_files(files):\n    \"\"\"Load and execute a python file.\"\"\"\n\n    for py_file in files:\n        LOG.debug(\"exec %s\", py_file)\n        execfile(py_file, globals(), locals())", "title": ""}
{"_id": "d12946", "text": "def table_width(self):\n        \"\"\"Return the width of the table including padding and borders.\"\"\"\n        outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]\n        outer_border = 2 if self.outer_border else 0\n        inner_border = 1 if self.inner_column_border else 0\n        return table_width(outer_widths, outer_border, inner_border)", "title": ""}
{"_id": "d12947", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d12948", "text": "def get_window(self): \n        \"\"\"\n        Returns the object's parent window. Returns None if no window found.\n        \"\"\"\n        x = self\n        while not x._parent == None and \\\n              not isinstance(x._parent, Window): \n                  x = x._parent\n        return x._parent", "title": ""}
{"_id": "d12949", "text": "def _parse(self, date_str, format='%Y-%m-%d'):\n        \"\"\"\n        helper function for parsing FRED date string into datetime\n        \"\"\"\n        rv = pd.to_datetime(date_str, format=format)\n        if hasattr(rv, 'to_pydatetime'):\n            rv = rv.to_pydatetime()\n        return rv", "title": ""}
{"_id": "d12950", "text": "def OnMove(self, event):\n        \"\"\"Main window move event\"\"\"\n\n        # Store window position in config\n        position = self.main_window.GetScreenPositionTuple()\n\n        config[\"window_position\"] = repr(position)", "title": ""}
{"_id": "d12951", "text": "def correlation_2D(image):\n    \"\"\"\n\n    :param image: 2d image\n    :return: psd1D, psd2D\n    \"\"\"\n    # Take the fourier transform of the image.\n    F1 = fftpack.fft2(image)\n\n    # Now shift the quadrants around so that low spatial frequencies are in\n    # the center of the 2D fourier transformed image.\n    F2 = fftpack.fftshift(F1)\n\n    # Calculate a 2D power spectrum\n    psd2D = np.abs(F2)\n\n    # Calculate the azimuthally averaged 1D power spectrum\n    psd1D = analysis_util.azimuthalAverage(psd2D)\n    return psd1D, psd2D", "title": ""}
{"_id": "d12952", "text": "def is_gzipped_fastq(file_name):\n    \"\"\"\n    Determine whether indicated file appears to be a gzipped FASTQ.\n\n    :param str file_name: Name/path of file to check as gzipped FASTQ.\n    :return bool: Whether indicated file appears to be in gzipped FASTQ format.\n    \"\"\"\n    _, ext = os.path.splitext(file_name)\n    return file_name.endswith(\".fastq.gz\") or file_name.endswith(\".fq.gz\")", "title": ""}
{"_id": "d12953", "text": "def get_least_distinct_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):\n    \"\"\"\n    Order the words from `vocab` by \"distinctiveness score\" (Chuang et al. 2012) from least to most distinctive.\n    Optionally only return the `n` least distinctive words.\n\n    J. Chuang, C. Manning, J. Heer 2012: \"Termite: Visualization Techniques for Assessing Textual Topic Models\"\n    \"\"\"\n    return _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n,\n                                           least_to_most=True)", "title": ""}
{"_id": "d12954", "text": "def open_hdf5(filename, mode='r'):\n    \"\"\"Wrapper to open a :class:`h5py.File` from disk, gracefully\n    handling a few corner cases\n    \"\"\"\n    if isinstance(filename, (h5py.Group, h5py.Dataset)):\n        return filename\n    if isinstance(filename, FILE_LIKE):\n        return h5py.File(filename.name, mode)\n    return h5py.File(filename, mode)", "title": ""}
{"_id": "d12955", "text": "def load_fasta_file(filename):\n    \"\"\"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\n\n    \"\"\"\n\n    with open(filename, \"r\") as handle:\n        records = list(SeqIO.parse(handle, \"fasta\"))\n    return records", "title": ""}
{"_id": "d12956", "text": "def open_hdf5(filename, mode='r'):\n    \"\"\"Wrapper to open a :class:`h5py.File` from disk, gracefully\n    handling a few corner cases\n    \"\"\"\n    if isinstance(filename, (h5py.Group, h5py.Dataset)):\n        return filename\n    if isinstance(filename, FILE_LIKE):\n        return h5py.File(filename.name, mode)\n    return h5py.File(filename, mode)", "title": ""}
{"_id": "d12957", "text": "def draw_image(self, ax, image):\n        \"\"\"Process a matplotlib image object and call renderer.draw_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)", "title": ""}
{"_id": "d12958", "text": "def hamming(s, t):\n    \"\"\"\n    Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.\n\n    :param s: string 1\n    :type s: str\n    :param t: string 2\n    :type s: str\n    :return: Hamming distance\n    :rtype: float\n    \"\"\"\n    if len(s) != len(t):\n        raise ValueError('Hamming distance needs strings of equal length.')\n    return sum(s_ != t_ for s_, t_ in zip(s, t))", "title": ""}
{"_id": "d12959", "text": "def ffmpeg_version():\n    \"\"\"Returns the available ffmpeg version\n\n    Returns\n    ----------\n    version : str\n        version number as string\n    \"\"\"\n\n    cmd = [\n        'ffmpeg',\n        '-version'\n    ]\n\n    output = sp.check_output(cmd)\n    aac_codecs = [\n        x for x in\n        output.splitlines() if \"ffmpeg version \" in str(x)\n    ][0]\n    hay = aac_codecs.decode('ascii')\n    match = re.findall(r'ffmpeg version (\\d+\\.)?(\\d+\\.)?(\\*|\\d+)', hay)\n    if match:\n        return \"\".join(match[0])\n    else:\n        return None", "title": ""}
{"_id": "d12960", "text": "def hamming(s, t):\n    \"\"\"\n    Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.\n\n    :param s: string 1\n    :type s: str\n    :param t: string 2\n    :type s: str\n    :return: Hamming distance\n    :rtype: float\n    \"\"\"\n    if len(s) != len(t):\n        raise ValueError('Hamming distance needs strings of equal length.')\n    return sum(s_ != t_ for s_, t_ in zip(s, t))", "title": ""}
{"_id": "d12961", "text": "def scaled_fft(fft, scale=1.0):\n    \"\"\"\n    Produces a nicer graph, I'm not sure if this is correct\n    \"\"\"\n    data = np.zeros(len(fft))\n    for i, v in enumerate(fft):\n        data[i] = scale * (i * v) / NUM_SAMPLES\n\n    return data", "title": ""}
{"_id": "d12962", "text": "def normalize_field(self, value):\n        \"\"\"\n        Method that must transform the value from string\n        Ex: if the expected type is int, it should return int(self._attr)\n\n        \"\"\"\n        if self.default is not None:\n            if value is None or value == '':\n                value = self.default\n        return value", "title": ""}
{"_id": "d12963", "text": "def exists(self, path):\n        \"\"\"\n        Returns true if the path exists and false otherwise.\n        \"\"\"\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", "title": ""}
{"_id": "d12964", "text": "def is_integer(obj):\n    \"\"\"Is this an integer.\n\n    :param object obj:\n    :return:\n    \"\"\"\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))", "title": ""}
{"_id": "d12965", "text": "def get_bin_indices(self, values):\n        \"\"\"Returns index tuple in histogram of bin which contains value\"\"\"\n        return tuple([self.get_axis_bin_index(values[ax_i], ax_i)\n                      for ax_i in range(self.dimensions)])", "title": ""}
{"_id": "d12966", "text": "def normalize_path(path):\n    \"\"\"\n    Convert a path to its canonical, case-normalized, absolute version.\n\n    \"\"\"\n    return os.path.normcase(os.path.realpath(os.path.expanduser(path)))", "title": ""}
{"_id": "d12967", "text": "def getSize(self):\n        \"\"\"\n        Returns the size of the layer, with the border size already subtracted.\n        \"\"\"\n        return self.widget.size[0]-self.border[0]*2,self.widget.size[1]-self.border[1]*2", "title": ""}
{"_id": "d12968", "text": "def make_writeable(filename):\n    \"\"\"\n    Make sure that the file is writeable.\n    Useful if our source is read-only.\n    \"\"\"\n    if not os.access(filename, os.W_OK):\n        st = os.stat(filename)\n        new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR\n        os.chmod(filename, new_permissions)", "title": ""}
{"_id": "d12969", "text": "def get_image_dimension(self, url):\n        \"\"\"\n        Return a tuple that contains (width, height)\n        Pass in a url to an image and find out its size without loading the whole file\n        If the image wxh could not be found, the tuple will contain `None` values\n        \"\"\"\n        w_h = (None, None)\n        try:\n            if url.startswith('//'):\n                url = 'http:' + url\n            data = requests.get(url).content\n            im = Image.open(BytesIO(data))\n\n            w_h = im.size\n        except Exception:\n            logger.warning(\"Error getting image size {}\".format(url), exc_info=True)\n\n        return w_h", "title": ""}
{"_id": "d12970", "text": "def filter_bolts(table, header):\n  \"\"\" filter to keep bolts \"\"\"\n  bolts_info = []\n  for row in table:\n    if row[0] == 'bolt':\n      bolts_info.append(row)\n  return bolts_info, header", "title": ""}
{"_id": "d12971", "text": "def is_array(self, key):\n        \"\"\"Return True if variable is a numpy array\"\"\"\n        data = self.model.get_data()\n        return isinstance(data[key], (ndarray, MaskedArray))", "title": ""}
{"_id": "d12972", "text": "def chunks(dictionary, chunk_size):\n    \"\"\"\n    Yield successive n-sized chunks from dictionary.\n    \"\"\"\n    iterable = iter(dictionary)\n    for __ in range(0, len(dictionary), chunk_size):\n        yield {key: dictionary[key] for key in islice(iterable, chunk_size)}", "title": ""}
{"_id": "d12973", "text": "def inpaint(self):\n        \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n        import inpaint\n        filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n        self.raster_data = np.ma.masked_invalid(filled)", "title": ""}
{"_id": "d12974", "text": "def quit(self):\n        \"\"\" Quits the application (called when the last window is closed)\n        \"\"\"\n        logger.debug(\"ArgosApplication.quit called\")\n        assert len(self.mainWindows) == 0, \\\n            \"Bug: still {} windows present at application quit!\".format(len(self.mainWindows))\n        self.qApplication.quit()", "title": ""}
{"_id": "d12975", "text": "def extend_with(func):\n    \"\"\"Extends with class or function\"\"\"\n    if not func.__name__ in ArgParseInator._plugins:\n        ArgParseInator._plugins[func.__name__] = func", "title": ""}
{"_id": "d12976", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d12977", "text": "def _transform_col(self, x, i):\n        \"\"\"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.\n        \"\"\"\n        return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)", "title": ""}
{"_id": "d12978", "text": "def twitter_timeline(screen_name, since_id=None):\n    \"\"\" Return relevant twitter timeline \"\"\"\n    consumer_key = twitter_credential('consumer_key')\n    consumer_secret = twitter_credential('consumer_secret')\n    access_token = twitter_credential('access_token')\n    access_token_secret = twitter_credential('access_secret')\n    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n    auth.set_access_token(access_token, access_token_secret)\n    api = tweepy.API(auth)\n    return get_all_tweets(screen_name, api, since_id)", "title": ""}
{"_id": "d12979", "text": "def round_data(filter_data):\n    \"\"\" round the data\"\"\"\n    for index, _ in enumerate(filter_data):\n        filter_data[index][0] = round(filter_data[index][0] / 100.0) * 100.0\n    return filter_data", "title": ""}
{"_id": "d12980", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d12981", "text": "def _bind_parameter(self, parameter, value):\n        \"\"\"Assigns a parameter value to matching instructions in-place.\"\"\"\n        for (instr, param_index) in self._parameter_table[parameter]:\n            instr.params[param_index] = value", "title": ""}
{"_id": "d12982", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d12983", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d12984", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d12985", "text": "def check_if_numbers_are_consecutive(list_):\n    \"\"\"\n    Returns True if numbers in the list are consecutive\n\n    :param list_: list of integers\n    :return: Boolean\n    \"\"\"\n    return all((True if second - first == 1 else False\n                for first, second in zip(list_[:-1], list_[1:])))", "title": ""}
{"_id": "d12986", "text": "def class_check(vector):\n    \"\"\"\n    Check different items in matrix classes.\n\n    :param vector: input vector\n    :type vector : list\n    :return: bool\n    \"\"\"\n    for i in vector:\n        if not isinstance(i, type(vector[0])):\n            return False\n    return True", "title": ""}
{"_id": "d12987", "text": "def get_previous(self):\n        \"\"\"Get the billing cycle prior to this one. May return None\"\"\"\n        return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()", "title": ""}
{"_id": "d12988", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d12989", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d12990", "text": "def findMax(arr):\n    \"\"\"\n    in comparison to argrelmax() more simple and  reliable peak finder\n    \"\"\"\n    out = np.zeros(shape=arr.shape, dtype=bool)\n    _calcMax(arr, out)\n    return out", "title": ""}
{"_id": "d12991", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d12992", "text": "def fit_gaussian(x, y, yerr, p0):\n    \"\"\" Fit a Gaussian to the data \"\"\"\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", "title": ""}
{"_id": "d12993", "text": "def chi_square_calc(classes, table, TOP, P, POP):\n    \"\"\"\n    Calculate chi-squared.\n\n    :param classes: confusion matrix classes\n    :type classes : list\n    :param table: confusion matrix table\n    :type table : dict\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: chi-squared as float\n    \"\"\"\n    try:\n        result = 0\n        for i in classes:\n            for index, j in enumerate(classes):\n                expected = (TOP[j] * P[i]) / (POP[i])\n                result += ((table[i][j] - expected)**2) / expected\n        return result\n    except Exception:\n        return \"None\"", "title": ""}
{"_id": "d12994", "text": "def sbatch_template(self):\n        \"\"\":return Jinja sbatch template for the current tag\"\"\"\n        template = self.sbatch_template_str\n        if template.startswith('#!'):\n            # script is embedded in YAML\n            return jinja_environment.from_string(template)\n        return jinja_environment.get_template(template)", "title": ""}
{"_id": "d12995", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d12996", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d12997", "text": "def auto_update(cls, function):\n        \"\"\"\n        This class method could be used as decorator on subclasses, it ensures\n        update method is called after function execution.\n        \"\"\"\n\n        def wrapper(self, *args, **kwargs):\n            f = function(self, *args, **kwargs)\n            self.update()\n            return f\n        return wrapper", "title": ""}
{"_id": "d12998", "text": "def hflip(img):\n    \"\"\"Horizontally flip the given PIL Image.\n\n    Args:\n        img (PIL Image): Image to be flipped.\n\n    Returns:\n        PIL Image:  Horizontall flipped image.\n    \"\"\"\n    if not _is_pil_image(img):\n        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n    return img.transpose(Image.FLIP_LEFT_RIGHT)", "title": ""}
{"_id": "d12999", "text": "def _delete_local(self, filename):\n        \"\"\"Deletes the specified file from the local filesystem.\"\"\"\n\n        if os.path.exists(filename):\n            os.remove(filename)", "title": ""}
{"_id": "d13000", "text": "def safe_exit(output):\n    \"\"\"exit without breaking pipes.\"\"\"\n    try:\n        sys.stdout.write(output)\n        sys.stdout.flush()\n    except IOError:\n        pass", "title": ""}
{"_id": "d13001", "text": "def _platform_is_windows(platform=sys.platform):\n        \"\"\"Is the current OS a Windows?\"\"\"\n        matched = platform in ('cygwin', 'win32', 'win64')\n        if matched:\n            error_msg = \"Windows isn't supported yet\"\n            raise OSError(error_msg)\n        return matched", "title": ""}
{"_id": "d13002", "text": "def get_page_and_url(session, url):\n    \"\"\"\n    Download an HTML page using the requests session and return\n    the final URL after following redirects.\n    \"\"\"\n    reply = get_reply(session, url)\n    return reply.text, reply.url", "title": ""}
{"_id": "d13003", "text": "def compute_boxplot(self, series):\n        \"\"\"\n        Compute boxplot for given pandas Series.\n        \"\"\"\n        from matplotlib.cbook import boxplot_stats\n        series = series[series.notnull()]\n        if len(series.values) == 0:\n            return {}\n        elif not is_numeric_dtype(series):\n            return self.non_numeric_stats(series)\n        stats = boxplot_stats(list(series.values))[0]\n        stats['count'] = len(series.values)\n        stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n        return stats", "title": ""}
{"_id": "d13004", "text": "def serialize(self, value, **kwargs):\n        \"\"\"Serialize every item of the list.\"\"\"\n        return [self.item_type.serialize(val, **kwargs) for val in value]", "title": ""}
{"_id": "d13005", "text": "def unit_tangent(self, t):\n        \"\"\"returns the unit tangent vector of the segment at t (centered at\n        the origin and expressed as a complex number).\"\"\"\n        dseg = self.derivative(t)\n        return dseg/abs(dseg)", "title": ""}
{"_id": "d13006", "text": "def find_frequencies(data, freq=44100, bits=16):\n    \"\"\"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.\n    \"\"\"\n    # Fast fourier transform\n    n = len(data)\n    p = _fft(data)\n    uniquePts = numpy.ceil((n + 1) / 2.0)\n\n    # Scale by the length (n) and square the value to get the amplitude\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\n    # Generate the frequencies and zip with the amplitudes\n    s = freq / float(n)\n    freqArray = numpy.arange(0, uniquePts * s, s)\n    return zip(freqArray, p)", "title": ""}
{"_id": "d13007", "text": "def autoscan():\n    \"\"\"autoscan will check all of the serial ports to see if they have\n       a matching VID:PID for a MicroPython board.\n    \"\"\"\n    for port in serial.tools.list_ports.comports():\n        if is_micropython_usb_device(port):\n            connect_serial(port[0])", "title": ""}
{"_id": "d13008", "text": "def parse_float(float_str):\n    \"\"\"Parse a string of the form 305.48b into a Python float.\n       The terminal letter, if present, indicates e.g. billions.\"\"\"\n    factor = __get_factor(float_str)\n    if factor != 1:\n        float_str = float_str[:-1]\n\n    try:\n        return float(float_str.replace(',', '')) * factor\n    except ValueError:\n        return None", "title": ""}
{"_id": "d13009", "text": "def cli(ctx, project_dir):\n    \"\"\"Clean the previous generated files.\"\"\"\n    exit_code = SCons(project_dir).clean()\n    ctx.exit(exit_code)", "title": ""}
{"_id": "d13010", "text": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "title": ""}
{"_id": "d13011", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d13012", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d13013", "text": "def _digits(minval, maxval):\n    \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n    if minval == maxval:\n        return 3\n    else:\n        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "title": ""}
{"_id": "d13014", "text": "def _bytes_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, bytes):\n        value = base64.standard_b64encode(value).decode(\"ascii\")\n    return value", "title": ""}
{"_id": "d13015", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d13016", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d13017", "text": "def find_root(self):\n        \"\"\" Traverse parent refs to top. \"\"\"\n        cmd = self\n        while cmd.parent:\n            cmd = cmd.parent\n        return cmd", "title": ""}
{"_id": "d13018", "text": "def _fullname(o):\n    \"\"\"Return the fully-qualified name of a function.\"\"\"\n    return o.__module__ + \".\" + o.__name__ if o.__module__ else o.__name__", "title": ""}
{"_id": "d13019", "text": "def get_obj_cols(df):\n    \"\"\"\n    Returns names of 'object' columns in the DataFrame.\n    \"\"\"\n    obj_cols = []\n    for idx, dt in enumerate(df.dtypes):\n        if dt == 'object' or is_category(dt):\n            obj_cols.append(df.columns.values[idx])\n\n    return obj_cols", "title": ""}
{"_id": "d13020", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d13021", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d13022", "text": "def _check_task_id(self, context):\n        \"\"\"\n        Gets the returned Celery result from the Airflow task\n        ID provided to the sensor, and returns True if the\n        celery result has been finished execution.\n\n        :param context: Airflow's execution context\n        :type context: dict\n        :return: True if task has been executed, otherwise False\n        :rtype: bool\n        \"\"\"\n        ti = context['ti']\n        celery_result = ti.xcom_pull(task_ids=self.target_task_id)\n        return celery_result.ready()", "title": ""}
{"_id": "d13023", "text": "def _file_exists(path, filename):\n  \"\"\"Checks if the filename exists under the path.\"\"\"\n  return os.path.isfile(os.path.join(path, filename))", "title": ""}
{"_id": "d13024", "text": "def to_tree(self):\n        \"\"\" returns a TreeLib tree \"\"\"\n        tree = TreeLibTree()\n        for node in self:\n            tree.create_node(node, node.node_id, parent=node.parent)\n        return tree", "title": ""}
{"_id": "d13025", "text": "def test3():\n    \"\"\"Test the multiprocess\n    \"\"\"\n    import time\n    \n    p = MVisionProcess()\n    p.start()\n    time.sleep(5)\n    p.stop()", "title": ""}
{"_id": "d13026", "text": "def hash_iterable(it):\n\t\"\"\"Perform a O(1) memory hash of an iterable of arbitrary length.\n\n\thash(tuple(it)) creates a temporary tuple containing all values from it\n\twhich could be a problem if it is large.\n\n\tSee discussion at:\n\thttps://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ\n\t\"\"\"\n\thash_value = hash(type(it))\n\tfor value in it:\n\t\thash_value = hash((hash_value, value))\n\treturn hash_value", "title": ""}
{"_id": "d13027", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d13028", "text": "def handle_m2m(self, sender, instance, **kwargs):\n    \"\"\" Handle many to many relationships \"\"\"\n    self.handle_save(instance.__class__, instance)", "title": ""}
{"_id": "d13029", "text": "def gaussian_kernel(sigma, truncate=4.0):\n    \"\"\"Return Gaussian that truncates at the given number of std deviations.\n\n    Adapted from https://github.com/nicjhan/gaussian-filter\n    \"\"\"\n\n    sigma = float(sigma)\n    radius = int(truncate * sigma + 0.5)\n\n    x, y = np.mgrid[-radius:radius + 1, -radius:radius + 1]\n    sigma = sigma ** 2\n\n    k = 2 * np.exp(-0.5 * (x ** 2 + y ** 2) / sigma)\n    k = k / np.sum(k)\n\n    return k", "title": ""}
{"_id": "d13030", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d13031", "text": "def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"Generate random id numbers.\"\"\"\n    return \"\".join(random.choice(chars) for x in range(size))", "title": ""}
{"_id": "d13032", "text": "def _unique_rows_numpy(a):\n    \"\"\"return unique rows\"\"\"\n    a = np.ascontiguousarray(a)\n    unique_a = np.unique(a.view([('', a.dtype)] * a.shape[1]))\n    return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))", "title": ""}
{"_id": "d13033", "text": "def mongoqs_to_json(qs, fields=None):\n    \"\"\"\n    transform mongoengine.QuerySet to json\n    \"\"\"\n\n    l = list(qs.as_pymongo())\n\n    for element in l:\n        element.pop('_cls')\n\n    # use DjangoJSONEncoder for transform date data type to datetime\n    json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)\n    return json_qs", "title": ""}
{"_id": "d13034", "text": "def _ratelimited_get(self, *args, **kwargs):\n        \"\"\"Perform get request, handling rate limiting.\"\"\"\n        with self._ratelimiter:\n            resp = self.session.get(*args, **kwargs)\n\n        # It's possible that Space-Track will return HTTP status 500 with a\n        # query rate limit violation. This can happen if a script is cancelled\n        # before it has finished sleeping to satisfy the rate limit and it is\n        # started again.\n        #\n        # Let's catch this specific instance and retry once if it happens.\n        if resp.status_code == 500:\n            # Let's only retry if the error page tells us it's a rate limit\n            # violation.\n            if 'violated your query rate limit' in resp.text:\n                # Mimic the RateLimiter callback behaviour.\n                until = time.time() + self._ratelimiter.period\n                t = threading.Thread(target=self._ratelimit_callback, args=(until,))\n                t.daemon = True\n                t.start()\n                time.sleep(self._ratelimiter.period)\n\n                # Now retry\n                with self._ratelimiter:\n                    resp = self.session.get(*args, **kwargs)\n\n        return resp", "title": ""}
{"_id": "d13035", "text": "def _uniform_phi(M):\n        \"\"\"\n        Generate M random numbers in [-pi, pi).\n\n        \"\"\"\n        return np.random.uniform(-np.pi, np.pi, M)", "title": ""}
{"_id": "d13036", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d13037", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d13038", "text": "def daterange(start_date, end_date):\n    \"\"\"\n    Yield one date per day from starting date to ending date.\n\n    Args:\n        start_date (date): starting date.\n        end_date (date): ending date.\n\n    Yields:\n        date: a date for each day within the range.\n    \"\"\"\n    for n in range(int((end_date - start_date).days)):\n        yield start_date + timedelta(n)", "title": ""}
{"_id": "d13039", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d13040", "text": "def title(self):\n        \"\"\" The title of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.title", "title": ""}
{"_id": "d13041", "text": "def do_restart(self, line):\n        \"\"\"Request that the Outstation perform a cold restart. Command syntax is: restart\"\"\"\n        self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)", "title": ""}
{"_id": "d13042", "text": "def _get_str_columns(sf):\n    \"\"\"\n    Returns a list of names of columns that are string type.\n    \"\"\"\n    return [name for name in sf.column_names() if sf[name].dtype == str]", "title": ""}
{"_id": "d13043", "text": "def ma(self):\n        \"\"\"Represent data as a masked array.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n        inf and nan are filtered via :func:`numpy.isfinite`.\n        \"\"\"\n        a = self.array\n        return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))", "title": ""}
{"_id": "d13044", "text": "def __get_xml_text(root):\n    \"\"\" Return the text for the given root node (xml.dom.minidom). \"\"\"\n    txt = \"\"\n    for e in root.childNodes:\n        if (e.nodeType == e.TEXT_NODE):\n            txt += e.data\n    return txt", "title": ""}
{"_id": "d13045", "text": "def set_context(self, data):\n        \"\"\"Load Context with data\"\"\"\n        for key in data:\n            setattr(self.local_context, key, data[key])", "title": ""}
{"_id": "d13046", "text": "def get_attribute_name_id(attr):\n    \"\"\"\n    Return the attribute name identifier\n    \"\"\"\n    return attr.value.id if isinstance(attr.value, ast.Name) else None", "title": ""}
{"_id": "d13047", "text": "def normalize_array(lst):\n    \"\"\"Normalizes list\n\n    :param lst: Array of floats\n    :return: Normalized (in [0, 1]) input array\n    \"\"\"\n    np_arr = np.array(lst)\n    x_normalized = np_arr / np_arr.max(axis=0)\n    return list(x_normalized)", "title": ""}
{"_id": "d13048", "text": "def shape(self):\n        \"\"\"\n        Return a tuple of axis dimensions\n        \"\"\"\n        return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)", "title": ""}
{"_id": "d13049", "text": "def normalize(self, string):\n        \"\"\"Normalize the string according to normalization list\"\"\"\n        return ''.join([self._normalize.get(x, x) for x in nfd(string)])", "title": ""}
{"_id": "d13050", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d13051", "text": "def fopenat(base_fd, path):\n    \"\"\"\n    Does openat read-only, then does fdopen to get a file object\n    \"\"\"\n\n    return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')", "title": ""}
{"_id": "d13052", "text": "def array_bytes(array):\n    \"\"\" Estimates the memory of the supplied array in bytes \"\"\"\n    return np.product(array.shape)*np.dtype(array.dtype).itemsize", "title": ""}
{"_id": "d13053", "text": "def reopen(self):\n        \"\"\"Reopen the tough connection.\n\n        It will not complain if the connection cannot be reopened.\n\n        \"\"\"\n        try:\n            self._con.reopen()\n        except Exception:\n            if self._transcation:\n                self._transaction = False\n                try:\n                    self._con.query('rollback')\n                except Exception:\n                    pass\n        else:\n            self._transaction = False\n            self._closed = False\n            self._setsession()\n            self._usage = 0", "title": ""}
{"_id": "d13054", "text": "def paste(cmd=paste_cmd, stdout=PIPE):\n    \"\"\"Returns system clipboard contents.\n    \"\"\"\n    return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')", "title": ""}
{"_id": "d13055", "text": "def native_conn(self):\n        \"\"\"Native connection object.\"\"\"\n        if self.__native is None:\n            self.__native = self._get_connection()\n\n        return self.__native", "title": ""}
{"_id": "d13056", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d13057", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d13058", "text": "def datetime64_to_datetime(dt):\n    \"\"\" convert numpy's datetime64 to datetime \"\"\"\n    dt64 = np.datetime64(dt)\n    ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')\n    return datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d13059", "text": "def _dump_enum(self, e, top=''):\n        \"\"\"Dump single enum type.\n        \n        Keyword arguments:\n        top -- top namespace\n        \"\"\"\n        self._print()\n        self._print('enum {} {{'.format(e.name))\n        self.defines.append('{}.{}'.format(top,e.name))\n        \n        self.tabs+=1\n        for v in e.value:\n            self._print('{} = {};'.format(v.name, v.number))\n        self.tabs-=1\n        self._print('}')", "title": ""}
{"_id": "d13060", "text": "def min_depth(self, root):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: int\n    \"\"\"\n    if root is None:\n        return 0\n    if root.left is not None or root.right is not None:\n        return max(self.minDepth(root.left), self.minDepth(root.right))+1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1", "title": ""}
{"_id": "d13061", "text": "def stats(self):\n        \"\"\" shotcut to pull out useful info for interactive use \"\"\"\n        printDebug(\"Classes.....: %d\" % len(self.all_classes))\n        printDebug(\"Properties..: %d\" % len(self.all_properties))", "title": ""}
{"_id": "d13062", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d13063", "text": "def rand_elem(seq, n=None):\n    \"\"\"returns a random element from seq n times. If n is None, it continues indefinitly\"\"\"\n    return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))", "title": ""}
{"_id": "d13064", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d13065", "text": "def _remove_from_index(index, obj):\n    \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n    try:\n        index.value_map[indexed_value(index, obj)].remove(obj.id)\n    except KeyError:\n        pass", "title": ""}
{"_id": "d13066", "text": "def PopTask(self):\n    \"\"\"Retrieves and removes the first task from the heap.\n\n    Returns:\n      Task: the task or None if the heap is empty.\n    \"\"\"\n    try:\n      _, task = heapq.heappop(self._heap)\n\n    except IndexError:\n      return None\n    self._task_identifiers.remove(task.identifier)\n    return task", "title": ""}
{"_id": "d13067", "text": "def remove_punctuation(text, exceptions=[]):\n    \"\"\"\n    Return a string with punctuation removed.\n\n    Parameters:\n        text (str): The text to remove punctuation from.\n        exceptions (list): List of symbols to keep in the given text.\n\n    Return:\n        str: The input text without the punctuation.\n    \"\"\"\n\n    all_but = [\n        r'\\w',\n        r'\\s'\n    ]\n\n    all_but.extend(exceptions)\n\n    pattern = '[^{}]'.format(''.join(all_but))\n\n    return re.sub(pattern, '', text)", "title": ""}
{"_id": "d13068", "text": "def path_for_import(name):\n    \"\"\"\n    Returns the directory path for the given package or module.\n    \"\"\"\n    return os.path.dirname(os.path.abspath(import_module(name).__file__))", "title": ""}
{"_id": "d13069", "text": "def dict_keys_without_hyphens(a_dict):\n    \"\"\"Return the a new dict with underscores instead of hyphens in keys.\"\"\"\n    return dict(\n        (key.replace('-', '_'), val) for key, val in a_dict.items())", "title": ""}
{"_id": "d13070", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d13071", "text": "def _init_unique_sets(self):\n        \"\"\"Initialise sets used for uniqueness checking.\"\"\"\n\n        ks = dict()\n        for t in self._unique_checks:\n            key = t[0]\n            ks[key] = set() # empty set\n        return ks", "title": ""}
{"_id": "d13072", "text": "def eval_Rf(self, Vf):\n        \"\"\"Evaluate smooth term in Vf.\"\"\"\n\n        return sl.inner(self.Df, Vf, axis=self.cri.axisM) - self.Sf", "title": ""}
{"_id": "d13073", "text": "def _update_index_on_df(df, index_names):\n    \"\"\"Helper function to restore index information after collection. Doesn't\n    use self so we can serialize this.\"\"\"\n    if index_names:\n        df = df.set_index(index_names)\n        # Remove names from unnamed indexes\n        index_names = _denormalize_index_names(index_names)\n        df.index.names = index_names\n    return df", "title": ""}
{"_id": "d13074", "text": "def _hue(color, **kwargs):\n    \"\"\" Get hue value of HSL color.\n    \"\"\"\n    h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0]\n    return NumberValue(h * 360.0)", "title": ""}
{"_id": "d13075", "text": "def is_integer(dtype):\n  \"\"\"Returns whether this is a (non-quantized) integer type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_integer'):\n    return dtype.is_integer\n  return np.issubdtype(np.dtype(dtype), np.integer)", "title": ""}
{"_id": "d13076", "text": "def uniquify_list(L):\n    \"\"\"Same order unique list using only a list compression.\"\"\"\n    return [e for i, e in enumerate(L) if L.index(e) == i]", "title": ""}
{"_id": "d13077", "text": "def matches_glob_list(path, glob_list):\n    \"\"\"\n    Given a list of glob patterns, returns a boolean\n    indicating if a path matches any glob in the list\n    \"\"\"\n    for glob in glob_list:\n        try:\n            if PurePath(path).match(glob):\n                return True\n        except TypeError:\n            pass\n    return False", "title": ""}
{"_id": "d13078", "text": "def _find_value(key, *args):\n    \"\"\"Find a value for 'key' in any of the objects given as 'args'\"\"\"\n    for arg in args:\n        v = _get_value(arg, key)\n        if v is not None:\n            return v", "title": ""}
{"_id": "d13079", "text": "def set_cursor(self, x, y):\n        \"\"\"\n        Sets the cursor to the desired position.\n\n        :param x: X position\n        :param y: Y position\n        \"\"\"\n        curses.curs_set(1)\n        self.screen.move(y, x)", "title": ""}
{"_id": "d13080", "text": "def _normalize_abmn(abmn):\n    \"\"\"return a normalized version of abmn\n    \"\"\"\n    abmn_2d = np.atleast_2d(abmn)\n    abmn_normalized = np.hstack((\n        np.sort(abmn_2d[:, 0:2], axis=1),\n        np.sort(abmn_2d[:, 2:4], axis=1),\n    ))\n    return abmn_normalized", "title": ""}
{"_id": "d13081", "text": "def list_files(directory):\n    \"\"\"Returns all files in a given directory\n    \"\"\"\n    return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]", "title": ""}
{"_id": "d13082", "text": "def is_collection(obj):\n    \"\"\"Tests if an object is a collection.\"\"\"\n\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n\n    if isinstance(obj, basestring):\n        val = False\n\n    return val", "title": ""}
{"_id": "d13083", "text": "def _random_x(self):\n        \"\"\"If the database is empty, generate a random vector.\"\"\"\n        return (tuple(random.random() for _ in range(self.fmodel.dim_x)),)", "title": ""}
{"_id": "d13084", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d13085", "text": "def model_field_attr(model, model_field, attr):\n    \"\"\"\n    Returns the specified attribute for the specified field on the model class.\n    \"\"\"\n    fields = dict([(field.name, field) for field in model._meta.fields])\n    return getattr(fields[model_field], attr)", "title": ""}
{"_id": "d13086", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d13087", "text": "def get_next_weekday(self, including_today=False):\n        \"\"\"Gets next week day\n\n        :param including_today: If today is sunday and requesting next sunday\n        :return: Date of next monday, tuesday ..\n        \"\"\"\n        weekday = self.date_time.weekday()\n        return Weekday.get_next(weekday, including_today=including_today)", "title": ""}
{"_id": "d13088", "text": "def Unlock(fd, path):\n  \"\"\"Release the lock on the file.\n\n  Args:\n    fd: int, the file descriptor of the file to unlock.\n    path: string, the name of the file to lock.\n\n  Raises:\n    IOError, raised from flock while attempting to release a file lock.\n  \"\"\"\n  try:\n    fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB)\n  except IOError as e:\n    if e.errno == errno.EWOULDBLOCK:\n      raise IOError('Exception unlocking %s. Locked by another process.' % path)\n    else:\n      raise IOError('Exception unlocking %s. %s.' % (path, str(e)))", "title": ""}
{"_id": "d13089", "text": "def line_count(fn):\n    \"\"\" Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)\n    \"\"\"\n\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "title": ""}
{"_id": "d13090", "text": "def get_page_and_url(session, url):\n    \"\"\"\n    Download an HTML page using the requests session and return\n    the final URL after following redirects.\n    \"\"\"\n    reply = get_reply(session, url)\n    return reply.text, reply.url", "title": ""}
{"_id": "d13091", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d13092", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d13093", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d13094", "text": "def display_iframe_url(target, **kwargs):\n    \"\"\"Display the contents of a URL in an IPython notebook.\n    \n    :param target: the target url.\n    :type target: string\n\n    .. seealso:: `iframe_url()` for additional arguments.\"\"\"\n\n    txt = iframe_url(target, **kwargs)\n    display(HTML(txt))", "title": ""}
{"_id": "d13095", "text": "def grandparent_path(self):\n        \"\"\" return grandparent's path string \"\"\"\n        return os.path.basename(os.path.join(self.path, '../..'))", "title": ""}
{"_id": "d13096", "text": "def _gzip(self, response):\n        \"\"\"Apply gzip compression to a response.\"\"\"\n        bytesio = six.BytesIO()\n        with gzip.GzipFile(fileobj=bytesio, mode='w') as gz:\n            gz.write(response)\n        return bytesio.getvalue()", "title": ""}
{"_id": "d13097", "text": "def unmatched(match):\n    \"\"\"Return unmatched part of re.Match object.\"\"\"\n    start, end = match.span(0)\n    return match.string[:start]+match.string[end:]", "title": ""}
{"_id": "d13098", "text": "def safe_quotes(text, escape_single_quotes=False):\n    \"\"\"htmlify string\"\"\"\n    if isinstance(text, str):\n        safe_text = text.replace('\"', \"&quot;\")\n        if escape_single_quotes:\n            safe_text = safe_text.replace(\"'\", \"&#92;'\")\n        return safe_text.replace('True', 'true')\n    return text", "title": ""}
{"_id": "d13099", "text": "def get_points(self):\n        \"\"\"Returns a ketama compatible list of (position, nodename) tuples.\n        \"\"\"\n        return [(k, self.runtime._ring[k]) for k in self.runtime._keys]", "title": ""}
{"_id": "d13100", "text": "def getheader(self, name, default=None):\n        \"\"\"Returns a given response header.\"\"\"\n        return self.aiohttp_response.headers.get(name, default)", "title": ""}
{"_id": "d13101", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d13102", "text": "def remote_file_exists(self, url):\n        \"\"\" 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.\n        \"\"\"\n        status = requests.head(url).status_code\n\n        if status != 200:\n            raise RemoteFileDoesntExist", "title": ""}
{"_id": "d13103", "text": "def parse_querystring(self, req, name, field):\n        \"\"\"Pull a querystring value from the request.\"\"\"\n        return core.get_value(req.args, name, field)", "title": ""}
{"_id": "d13104", "text": "def is_gzipped_fastq(file_name):\n    \"\"\"\n    Determine whether indicated file appears to be a gzipped FASTQ.\n\n    :param str file_name: Name/path of file to check as gzipped FASTQ.\n    :return bool: Whether indicated file appears to be in gzipped FASTQ format.\n    \"\"\"\n    _, ext = os.path.splitext(file_name)\n    return file_name.endswith(\".fastq.gz\") or file_name.endswith(\".fq.gz\")", "title": ""}
{"_id": "d13105", "text": "def remove_duplicates(lst):\n    \"\"\"\n    Emulate what a Python ``set()`` does, but keeping the element's order.\n    \"\"\"\n    dset = set()\n    return [l for l in lst if l not in dset and not dset.add(l)]", "title": ""}
{"_id": "d13106", "text": "def MultiArgMax(x):\n  \"\"\"\n  Get tuple (actually a generator) of indices where the max value of\n  array x occurs. Requires that x have a max() method, as x.max()\n  (in the case of NumPy) is much faster than max(x).\n  For a simpler, faster argmax when there is only a single maximum entry,\n  or when knowing only the first index where the maximum occurs,\n  call argmax() on a NumPy array.\n\n  :param x: Any sequence that has a max() method.\n  :returns: Generator with the indices where the max value occurs.\n  \"\"\"\n  m = x.max()\n  return (i for i, v in enumerate(x) if v == m)", "title": ""}
{"_id": "d13107", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d13108", "text": "def _findNearest(arr, value):\n    \"\"\" Finds the value in arr that value is closest to\n    \"\"\"\n    arr = np.array(arr)\n    # find nearest value in array\n    idx = (abs(arr-value)).argmin()\n    return arr[idx]", "title": ""}
{"_id": "d13109", "text": "def get_page_text(self, page):\n        \"\"\"\n        Downloads and returns the full text of a particular page\n        in the document.\n        \"\"\"\n        url = self.get_page_text_url(page)\n        return self._get_url(url)", "title": ""}
{"_id": "d13110", "text": "def is_iterable(value):\n    \"\"\"must be an iterable (list, array, tuple)\"\"\"\n    return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "title": ""}
{"_id": "d13111", "text": "def legend_title_header_element(feature, parent):\n    \"\"\"Retrieve legend title header string from definitions.\"\"\"\n    _ = feature, parent  # NOQA\n    header = legend_title_header['string_format']\n    return header.capitalize()", "title": ""}
{"_id": "d13112", "text": "def datatype(dbtype, description, cursor):\n    \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n    dt = cursor.db.introspection.get_field_type(dbtype, description)\n    if type(dt) is tuple:\n        return dt[0]\n    else:\n        return dt", "title": ""}
{"_id": "d13113", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d13114", "text": "def IsBinary(self, filename):\n\t\t\"\"\"Returns true if the guessed mimetyped isnt't in text group.\"\"\"\n\t\tmimetype = mimetypes.guess_type(filename)[0]\n\t\tif not mimetype:\n\t\t\treturn False  # e.g. README, \"real\" binaries usually have an extension\n\t\t# special case for text files which don't start with text/\n\t\tif mimetype in TEXT_MIMETYPES:\n\t\t\treturn False\n\t\treturn not mimetype.startswith(\"text/\")", "title": ""}
{"_id": "d13115", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d13116", "text": "def normalized_distance(self, image):\n        \"\"\"Calculates the distance of a given image to the\n        original image.\n\n        Parameters\n        ----------\n        image : `numpy.ndarray`\n            The image that should be compared to the original image.\n\n        Returns\n        -------\n        :class:`Distance`\n            The distance between the given image and the original image.\n\n        \"\"\"\n        return self.__distance(\n            self.__original_image_for_distance,\n            image,\n            bounds=self.bounds())", "title": ""}
{"_id": "d13117", "text": "def calculate_size(name, count):\n    \"\"\" Calculates the request payload size\"\"\"\n    data_size = 0\n    data_size += calculate_size_str(name)\n    data_size += INT_SIZE_IN_BYTES\n    return data_size", "title": ""}
{"_id": "d13118", "text": "def uint32_to_uint8(cls, img):\n        \"\"\"\n        Cast uint32 RGB image to 4 uint8 channels.\n        \"\"\"\n        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))", "title": ""}
{"_id": "d13119", "text": "def _get_minidom_tag_value(station, tag_name):\n    \"\"\"get a value from a tag (if it exists)\"\"\"\n    tag = station.getElementsByTagName(tag_name)[0].firstChild\n    if tag:\n        return tag.nodeValue\n\n    return None", "title": ""}
{"_id": "d13120", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d13121", "text": "def poke_array(self, store, name, elemtype, elements, container, visited, _stack):\n        \"\"\"abstract method\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d13122", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d13123", "text": "def impute_data(self,x):\n        \"\"\"Imputes data set containing Nan values\"\"\"\n        imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n        return imp.fit_transform(x)", "title": ""}
{"_id": "d13124", "text": "def dir_modtime(dpath):\n    \"\"\"\n    Returns the latest modification time of all files/subdirectories in a\n    directory\n    \"\"\"\n    return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))", "title": ""}
{"_id": "d13125", "text": "def impute_data(self,x):\n        \"\"\"Imputes data set containing Nan values\"\"\"\n        imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n        return imp.fit_transform(x)", "title": ""}
{"_id": "d13126", "text": "def _uniquify(_list):\n    \"\"\"Remove duplicates in a list.\"\"\"\n    seen = set()\n    result = []\n    for x in _list:\n        if x not in seen:\n            result.append(x)\n            seen.add(x)\n    return result", "title": ""}
{"_id": "d13127", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d13128", "text": "def convert_2_utc(self, datetime_, timezone):\n        \"\"\"convert to datetime to UTC offset.\"\"\"\n\n        datetime_ = self.tz_mapper[timezone].localize(datetime_)\n        return datetime_.astimezone(pytz.UTC)", "title": ""}
{"_id": "d13129", "text": "def layout(self, indent='    '):\n\t\t\"\"\"This will indent each new tag in the body by given number of spaces.\"\"\"\n\n\n\t\tself.__indent(self.head, indent)\n\t\tself.__indent(self.meta, indent)\n\t\tself.__indent(self.stylesheet, indent)\n\t\tself.__indent(self.header, indent)\n\t\tself.__indent(self.body, indent, initial=3)\n\t\tself.__indent(self.footer, indent)\n\t\tself.__indent(self.body_pre_docinfo, indent, initial=3)\n\t\tself.__indent(self.docinfo, indent)", "title": ""}
{"_id": "d13130", "text": "def get_week_start_end_day():\n    \"\"\"\n    Get the week start date and end date\n    \"\"\"\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))", "title": ""}
{"_id": "d13131", "text": "def _frombuffer(ptr, frames, channels, dtype):\n    \"\"\"Create NumPy array from a pointer to some memory.\"\"\"\n    framesize = channels * dtype.itemsize\n    data = np.frombuffer(ffi.buffer(ptr, frames * framesize), dtype=dtype)\n    data.shape = -1, channels\n    return data", "title": ""}
{"_id": "d13132", "text": "def get_stripped_file_lines(filename):\n    \"\"\"\n    Return lines of a file with whitespace removed\n    \"\"\"\n    try:\n        lines = open(filename).readlines()\n    except FileNotFoundError:\n        fatal(\"Could not open file: {!r}\".format(filename))\n\n    return [line.strip() for line in lines]", "title": ""}
{"_id": "d13133", "text": "def pagerank_limit_push(s, r, w_i, a_i, push_node, rho):\n    \"\"\"\n    Performs a random step without a self-loop.\n    \"\"\"\n    # Calculate the A and B quantities to infinity\n    A_inf = rho*r[push_node]\n    B_inf = (1-rho)*r[push_node]\n\n    # Update approximate Pagerank and residual vectors\n    s[push_node] += A_inf\n    r[push_node] = 0.0\n\n    # Update residual vector at push node's adjacent nodes\n    r[a_i] += B_inf * w_i", "title": ""}
{"_id": "d13134", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d13135", "text": "def from_dict(cls, d):\n        \"\"\"Create an instance from a dictionary.\"\"\"\n        return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})", "title": ""}
{"_id": "d13136", "text": "def set_clear_color(self, color='black', alpha=None):\n        \"\"\"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.\n        \"\"\"\n        self.glir.command('FUNC', 'glClearColor', *Color(color, alpha).rgba)", "title": ""}
{"_id": "d13137", "text": "def _get_binary_from_ipv4(self, ip_addr):\n        \"\"\"Converts IPv4 address to binary form.\"\"\"\n\n        return struct.unpack(\"!L\", socket.inet_pton(socket.AF_INET,\n                                                    ip_addr))[0]", "title": ""}
{"_id": "d13138", "text": "def to_gtp(coord):\n    \"\"\"Converts from a Minigo coordinate to a GTP coordinate.\"\"\"\n    if coord is None:\n        return 'pass'\n    y, x = coord\n    return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)", "title": ""}
{"_id": "d13139", "text": "def _get_ipv4_from_binary(self, bin_addr):\n        \"\"\"Converts binary address to Ipv4 format.\"\"\"\n\n        return socket.inet_ntop(socket.AF_INET, struct.pack(\"!L\", bin_addr))", "title": ""}
{"_id": "d13140", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x.\"\"\"\n    i = bs.bisect_left(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d13141", "text": "def partition_all(n, iterable):\n    \"\"\"Partition a list into equally sized pieces, including last smaller parts\n    http://stackoverflow.com/questions/5129102/python-equivalent-to-clojures-partition-all\n    \"\"\"\n    it = iter(iterable)\n    while True:\n        chunk = list(itertools.islice(it, n))\n        if not chunk:\n            break\n        yield chunk", "title": ""}
{"_id": "d13142", "text": "def _hess_two_param(self, funct, p0, p1, dl=2e-5, rts=False, **kwargs):\n        \"\"\"\n        Hessian of `func` wrt two parameters `p0` and `p1`. (see _graddoc)\n        \"\"\"\n        vals0 = self.get_values(p0)\n        vals1 = self.get_values(p1)\n\n        f00 = funct(**kwargs)\n\n        self.update(p0, vals0+dl)\n        f10 = funct(**kwargs)\n\n        self.update(p1, vals1+dl)\n        f11 = funct(**kwargs)\n\n        self.update(p0, vals0)\n        f01 = funct(**kwargs)\n\n        if rts:\n            self.update(p0, vals0)\n            self.update(p1, vals1)\n        return (f11 - f10 - f01 + f00) / (dl**2)", "title": ""}
{"_id": "d13143", "text": "def interp(x, xp, *args, **kwargs):\n    \"\"\"Wrap interpolate_1d for deprecated interp.\"\"\"\n    return interpolate_1d(x, xp, *args, **kwargs)", "title": ""}
{"_id": "d13144", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d13145", "text": "def is_timestamp(obj):\n    \"\"\"\n    Yaml either have automatically converted it to a datetime object\n    or it is a string that will be validated later.\n    \"\"\"\n    return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)", "title": ""}
{"_id": "d13146", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d13147", "text": "def _run_cmd_get_output(cmd):\n    \"\"\"Runs a shell command, returns console output.\n\n    Mimics python3's subprocess.getoutput\n    \"\"\"\n    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n    out, err = process.communicate()\n    return out or err", "title": ""}
{"_id": "d13148", "text": "def hash_iterable(it):\n\t\"\"\"Perform a O(1) memory hash of an iterable of arbitrary length.\n\n\thash(tuple(it)) creates a temporary tuple containing all values from it\n\twhich could be a problem if it is large.\n\n\tSee discussion at:\n\thttps://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ\n\t\"\"\"\n\thash_value = hash(type(it))\n\tfor value in it:\n\t\thash_value = hash((hash_value, value))\n\treturn hash_value", "title": ""}
{"_id": "d13149", "text": "def unique_iter(seq):\n    \"\"\"\n    See http://www.peterbe.com/plog/uniqifiers-benchmark\n    Originally f8 written by Dave Kirby\n    \"\"\"\n    seen = set()\n    return [x for x in seq if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d13150", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d13151", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d13152", "text": "def find_geom(geom, geoms):\n    \"\"\"\n    Returns the index of a geometry in a list of geometries avoiding\n    expensive equality checks of `in` operator.\n    \"\"\"\n    for i, g in enumerate(geoms):\n        if g is geom:\n            return i", "title": ""}
{"_id": "d13153", "text": "def is_symlink(self):\n        \"\"\"\n        Whether this path is a symbolic link.\n        \"\"\"\n        try:\n            return S_ISLNK(self.lstat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            # Path doesn't exist\n            return False", "title": ""}
{"_id": "d13154", "text": "def _validate_input_data(self, data, request):\n        \"\"\" Validate input data.\n\n        :param request: the HTTP request\n        :param data: the parsed data\n        :return: if validation is performed and succeeds the data is converted\n                 into whatever format the validation uses (by default Django's\n                 Forms) If not, the data is returned unchanged.\n        :raises: HttpStatusCodeError if data is not valid\n        \"\"\"\n\n        validator = self._get_input_validator(request)\n        if isinstance(data, (list, tuple)):\n            return map(validator.validate, data)\n        else:\n            return validator.validate(data)", "title": ""}
{"_id": "d13155", "text": "def isdir(path, **kwargs):\n    \"\"\"Check if *path* is a directory\"\"\"\n    import os.path\n    return os.path.isdir(path, **kwargs)", "title": ""}
{"_id": "d13156", "text": "def set(self, f):\n        \"\"\"Call a function after a delay, unless another function is set\n        in the meantime.\"\"\"\n        self.stop()\n        self._create_timer(f)\n        self.start()", "title": ""}
{"_id": "d13157", "text": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "title": ""}
{"_id": "d13158", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d13159", "text": "def finditer(self, string, pos=0, endpos=sys.maxint):\n        \"\"\"Return a list of all non-overlapping matches of pattern in string.\"\"\"\n        scanner = self.scanner(string, pos, endpos)\n        return iter(scanner.search, None)", "title": ""}
{"_id": "d13160", "text": "def set(cls, color):\n        \"\"\"\n        Sets the terminal to the passed color.\n        :param color: one of the availabe colors.\n        \"\"\"\n        sys.stdout.write(cls.colors.get(color, cls.colors['RESET']))", "title": ""}
{"_id": "d13161", "text": "def _dict_values_sorted_by_key(dictionary):\n    # This should be a yield from instead.\n    \"\"\"Internal helper to return the values of a dictionary, sorted by key.\n    \"\"\"\n    for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):\n        yield value", "title": ""}
{"_id": "d13162", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d13163", "text": "def find_all(self, string, callback):\n\t\t\"\"\"\n\t\tWrapper on iter method, callback gets an iterator result\n\t\t\"\"\"\n\t\tfor index, output in self.iter(string):\n\t\t\tcallback(index, output)", "title": ""}
{"_id": "d13164", "text": "def refresh_core(self):\n        \"\"\"Query device for all attributes that exist regardless of power state.\n\n        This will force a refresh for all device queries that are valid to\n        request at any time.  It's the only safe suite of queries that we can\n        make if we do not know the current state (on or off+standby).\n\n        This does not return any data, it just issues the queries.\n        \"\"\"\n        self.log.info('Sending out mass query for all attributes')\n        for key in ATTR_CORE:\n            self.query(key)", "title": ""}
{"_id": "d13165", "text": "def each_img(dir_path):\n    \"\"\"\n    Iterates through each image in the given directory. (not recursive)\n    :param dir_path: Directory path where images files are present\n    :return: Iterator to iterate through image files\n    \"\"\"\n    for fname in os.listdir(dir_path):\n        if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'):\n            yield fname", "title": ""}
{"_id": "d13166", "text": "def determine_interactive(self):\n\t\t\"\"\"Determine whether we're in an interactive shell.\n\t\tSets interactivity off if appropriate.\n\t\tcf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):\n\t\t\t\tself.interactive = 0\n\t\t\t\treturn False\n\t\texcept Exception:\n\t\t\tself.interactive = 0\n\t\t\treturn False\n\t\tif self.interactive == 0:\n\t\t\treturn False\n\t\treturn True", "title": ""}
{"_id": "d13167", "text": "def next(self):\n        \"\"\"Provides hook for Python2 iterator functionality.\"\"\"\n        _LOGGER.debug(\"reading next\")\n        if self.closed:\n            _LOGGER.debug(\"stream is closed\")\n            raise StopIteration()\n\n        line = self.readline()\n        if not line:\n            _LOGGER.debug(\"nothing more to read\")\n            raise StopIteration()\n\n        return line", "title": ""}
{"_id": "d13168", "text": "def remove_bad(string):\n    \"\"\"\n    remove problem characters from string\n    \"\"\"\n    remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n    for c in remove:\n        string = string.replace(c, '_')\n    return string", "title": ""}
{"_id": "d13169", "text": "def txt_line_iterator(path):\n  \"\"\"Iterate through lines of file.\"\"\"\n  with tf.gfile.Open(path) as f:\n    for line in f:\n      yield line.strip()", "title": ""}
{"_id": "d13170", "text": "def printc(cls, txt, color=colors.red):\n        \"\"\"Print in color.\"\"\"\n        print(cls.color_txt(txt, color))", "title": ""}
{"_id": "d13171", "text": "def __iter__(self):\n        \"\"\"Overloads iter(condition), and also, for bit in condition. The\n        values yielded by the iterator are True (1), False (0), or\n        None (#).\"\"\"\n        for bit, mask in zip(self._bits, self._mask):\n            yield bit if mask else None", "title": ""}
{"_id": "d13172", "text": "def stop_at(iterable, idx):\n    \"\"\"Stops iterating before yielding the specified idx.\"\"\"\n    for i, item in enumerate(iterable):\n        if i == idx: return\n        yield item", "title": ""}
{"_id": "d13173", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d13174", "text": "def list2string (inlist,delimit=' '):\n    \"\"\"\nConverts a 1D list to a single long string for file output, using\nthe string.join function.\n\nUsage:   list2string (inlist,delimit=' ')\nReturns: the string created from inlist\n\"\"\"\n    stringlist = [makestr(_) for _ in inlist]\n    return string.join(stringlist,delimit)", "title": ""}
{"_id": "d13175", "text": "def _letter_map(word):\n    \"\"\"Creates a map of letter use in a word.\n\n    Args:\n        word: a string to create a letter map from\n\n    Returns:\n        a dictionary of {letter: integer count of letter in word}\n    \"\"\"\n\n    lmap = {}\n    for letter in word:\n        try:\n            lmap[letter] += 1\n        except KeyError:\n            lmap[letter] = 1\n    return lmap", "title": ""}
{"_id": "d13176", "text": "def eval(self, expression, use_compilation_plan=False):\n        \"\"\"evaluates expression in current context and returns its value\"\"\"\n        code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression)\n        self.execute(code, use_compilation_plan=use_compilation_plan)\n        return self['PyJsEvalResult']", "title": ""}
{"_id": "d13177", "text": "def enable_proxy(self, host, port):\n        \"\"\"Enable a default web proxy\"\"\"\n\n        self.proxy = [host, _number(port)]\n        self.proxy_enabled = True", "title": ""}
{"_id": "d13178", "text": "def from_json(value, **kwargs):\n        \"\"\"Coerces JSON string to boolean\"\"\"\n        if isinstance(value, string_types):\n            value = value.upper()\n            if value in ('TRUE', 'Y', 'YES', 'ON'):\n                return True\n            if value in ('FALSE', 'N', 'NO', 'OFF'):\n                return False\n        if isinstance(value, int):\n            return value\n        raise ValueError('Could not load boolean from JSON: {}'.format(value))", "title": ""}
{"_id": "d13179", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d13180", "text": "def task_property_present_predicate(service, task, prop):\n    \"\"\" True if the json_element passed is present for the task specified.\n    \"\"\"\n    try:\n        response = get_service_task(service, task)\n    except Exception as e:\n        pass\n\n    return (response is not None) and (prop in response)", "title": ""}
{"_id": "d13181", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d13182", "text": "def _bytes_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, bytes):\n        value = base64.standard_b64encode(value).decode(\"ascii\")\n    return value", "title": ""}
{"_id": "d13183", "text": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "title": ""}
{"_id": "d13184", "text": "def classnameify(s):\n  \"\"\"\n  Makes a classname\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))", "title": ""}
{"_id": "d13185", "text": "def test_security(self):\n        \"\"\" Run security.py -- demonstrate the SECURITY extension \"\"\"\n        self.assertEqual(run_example(examples_folder + \"security.py --generate\"), 0)\n        self.assertEqual(run_example(examples_folder + \"security.py --revoke\"), 0)", "title": ""}
{"_id": "d13186", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d13187", "text": "def distance_to_line(a, b, p):\n    \"\"\"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\n    \"\"\"\n    return distance(closest_point(a, b, p), p)", "title": ""}
{"_id": "d13188", "text": "def json(body, charset='utf-8', **kwargs):\n    \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n    return json_converter.loads(text(body, charset=charset))", "title": ""}
{"_id": "d13189", "text": "def do_exit(self, arg):\n        \"\"\"Exit the shell session.\"\"\"\n\n        if self.current:\n            self.current.close()\n        self.resource_manager.close()\n        del self.resource_manager\n        return True", "title": ""}
{"_id": "d13190", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d13191", "text": "def home():\n    \"\"\"Temporary helper function to link to the API routes\"\"\"\n    return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \\\n        HTTPStatus.OK", "title": ""}
{"_id": "d13192", "text": "def default_number_converter(number_str):\n    \"\"\"\n    Converts the string representation of a json number into its python object equivalent, an\n    int, long, float or whatever type suits.\n    \"\"\"\n    is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()\n    # FIXME: this handles a wider range of numbers than allowed by the json standard,\n    # etc.: float('nan') and float('inf'). But is this a problem?\n    return int(number_str) if is_int else float(number_str)", "title": ""}
{"_id": "d13193", "text": "def method(func):\n    \"\"\"Wrap a function as a method.\"\"\"\n    attr = abc.abstractmethod(func)\n    attr.__imethod__ = True\n    return attr", "title": ""}
{"_id": "d13194", "text": "def from_json(value, **kwargs):\n        \"\"\"Coerces JSON string to boolean\"\"\"\n        if isinstance(value, string_types):\n            value = value.upper()\n            if value in ('TRUE', 'Y', 'YES', 'ON'):\n                return True\n            if value in ('FALSE', 'N', 'NO', 'OFF'):\n                return False\n        if isinstance(value, int):\n            return value\n        raise ValueError('Could not load boolean from JSON: {}'.format(value))", "title": ""}
{"_id": "d13195", "text": "def wait_on_rate_limit(self, value):\n        \"\"\"Enable or disable automatic rate-limit handling.\"\"\"\n        check_type(value, bool, may_be_none=False)\n        self._wait_on_rate_limit = value", "title": ""}
{"_id": "d13196", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d13197", "text": "def equal(obj1, obj2):\n    \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n    Comparable.log(obj1, obj2, '==')\n    equality = obj1.equality(obj2)\n    Comparable.log(obj1, obj2, '==', result=equality)\n    return equality", "title": ""}
{"_id": "d13198", "text": "def _linearInterpolationTransformMatrix(matrix1, matrix2, value):\n    \"\"\" Linear, 'oldstyle' interpolation of the transform matrix.\"\"\"\n    return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))", "title": ""}
{"_id": "d13199", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d13200", "text": "def url_encode(url):\n    \"\"\"\n    Convert special characters using %xx escape.\n\n    :param url: str\n    :return: str - encoded url\n    \"\"\"\n    if isinstance(url, text_type):\n        url = url.encode('utf8')\n    return quote(url, ':/%?&=')", "title": ""}
{"_id": "d13201", "text": "def _check_and_convert_bools(self):\n        \"\"\"Replace boolean variables by the characters 'F'/'T'\n        \"\"\"\n        replacements = {\n            True: 'T',\n            False: 'F',\n        }\n\n        for key in self.bools:\n            if isinstance(self[key], bool):\n                self[key] = replacements[self[key]]", "title": ""}
{"_id": "d13202", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d13203", "text": "def unique_list(lst):\n    \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n    uniq = []\n    for item in lst:\n        if item not in uniq:\n            uniq.append(item)\n    return uniq", "title": ""}
{"_id": "d13204", "text": "def assign_to(self, obj):\n    \"\"\"Assign `x` and `y` to an object that has properties `x` and `y`.\"\"\"\n    obj.x = self.x\n    obj.y = self.y", "title": ""}
{"_id": "d13205", "text": "def toggle_pause(self):\n        \"\"\"Toggle pause mode\"\"\"\n        self.controller.playing = not self.controller.playing\n        self.music.toggle_pause()", "title": ""}
{"_id": "d13206", "text": "def dispatch(self):\n    \"\"\"Wraps the dispatch method to add session support.\"\"\"\n    try:\n      webapp2.RequestHandler.dispatch(self)\n    finally:\n      self.session_store.save_sessions(self.response)", "title": ""}
{"_id": "d13207", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d13208", "text": "def kill(self):\n        \"\"\"Kill the browser.\n\n        This is useful when the browser is stuck.\n        \"\"\"\n        if self.process:\n            self.process.kill()\n            self.process.wait()", "title": ""}
{"_id": "d13209", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d13210", "text": "def _cal_dist2center(X, center):\n    \"\"\" Calculate the SSE to the cluster center\n    \"\"\"\n    dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')\n    return(np.sum(dmemb2cen))", "title": ""}
{"_id": "d13211", "text": "def _int64_feature(value):\n  \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))", "title": ""}
{"_id": "d13212", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d13213", "text": "def tfds_dir():\n  \"\"\"Path to tensorflow_datasets directory.\"\"\"\n  return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))", "title": ""}
{"_id": "d13214", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d13215", "text": "def vadd(v1, v2):\n    \"\"\" Add two 3 dimensional vectors.\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vadd_c.html\n\n    :param v1: First vector to be added. \n    :type v1: 3-Element Array of floats\n    :param v2: Second vector to be added. \n    :type v2: 3-Element Array of floats\n    :return: v1+v2\n    :rtype: 3-Element Array of floats\n    \"\"\"\n    v1 = stypes.toDoubleVector(v1)\n    v2 = stypes.toDoubleVector(v2)\n    vout = stypes.emptyDoubleVector(3)\n    libspice.vadd_c(v1, v2, vout)\n    return stypes.cVectorToPython(vout)", "title": ""}
{"_id": "d13216", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d13217", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d13218", "text": "def query(self, base, filterstr, attrlist=None):\n\t\t\"\"\" wrapper to search_s \"\"\"\n\t\treturn self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)", "title": ""}
{"_id": "d13219", "text": "def cols_strip(df,col_list, dest = False):\n    \"\"\" Performs str.strip() a column of a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_list - list of strings\n        names of columns to strip\n    dest - bool, default False\n        Whether to apply the result to the DataFrame or return it.\n        True is apply, False is return.\n    \"\"\"\n    if not dest:\n        return _pd.DataFrame({col_name:col_strip(df,col_name) for col_name in col_list})\n    for col_name in col_list:\n        col_strip(df,col_name,dest)", "title": ""}
{"_id": "d13220", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d13221", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d13222", "text": "def raw_print(*args, **kw):\n    \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()", "title": ""}
{"_id": "d13223", "text": "def size(self):\n        \"\"\"\n        Recursively find size of a tree. Slow.\n        \"\"\"\n\n        if self is NULL:\n            return 0\n        return 1 + self.left.size() + self.right.size()", "title": ""}
{"_id": "d13224", "text": "def merge_dict(data, *args):\n    \"\"\"Merge any number of dictionaries\n    \"\"\"\n    results = {}\n    for current in (data,) + args:\n        results.update(current)\n    return results", "title": ""}
{"_id": "d13225", "text": "def _get_xy_scaling_parameters(self):\n        \"\"\"Get the X/Y coordinate limits for the full resulting image\"\"\"\n        return self.mx, self.bx, self.my, self.by", "title": ""}
{"_id": "d13226", "text": "def _set_request_cache_if_django_cache_hit(key, django_cached_response):\n        \"\"\"\n        Sets the value in the request cache if the django cached response was a hit.\n\n        Args:\n            key (string)\n            django_cached_response (CachedResponse)\n\n        \"\"\"\n        if django_cached_response.is_found:\n            DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value)", "title": ""}
{"_id": "d13227", "text": "def linear_variogram_model(m, d):\n    \"\"\"Linear model, m is [slope, nugget]\"\"\"\n    slope = float(m[0])\n    nugget = float(m[1])\n    return slope * d + nugget", "title": ""}
{"_id": "d13228", "text": "def fgrad_y(self, y, return_precalc=False):\n        \"\"\"\n        gradient of f w.r.t to y ([N x 1])\n\n        :returns: Nx1 vector of derivatives, unless return_precalc is true, \n        then it also returns the precomputed stuff\n        \"\"\"\n        d = self.d\n        mpsi = self.psi\n\n        # vectorized version\n        S = (mpsi[:,1] * (y[:,:,None] + mpsi[:,2])).T\n        R = np.tanh(S)\n        D = 1 - (R ** 2)\n\n        GRAD = (d + (mpsi[:,0:1][:,:,None] * mpsi[:,1:2][:,:,None] * D).sum(axis=0)).T\n\n        if return_precalc:\n            return GRAD, S, R, D\n\n        return GRAD", "title": ""}
{"_id": "d13229", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d13230", "text": "def get_pid_list():\n    \"\"\"Returns a list of PIDs currently running on the system.\"\"\"\n    pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]\n    return pids", "title": ""}
{"_id": "d13231", "text": "def indentsize(line):\n    \"\"\"Return the indent size, in spaces, at the start of a line of text.\"\"\"\n    expline = string.expandtabs(line)\n    return len(expline) - len(string.lstrip(expline))", "title": ""}
{"_id": "d13232", "text": "def _crop_list_to_size(l, size):\n    \"\"\"Make a list a certain size\"\"\"\n    for x in range(size - len(l)):\n        l.append(False)\n    for x in range(len(l) - size):\n        l.pop()\n    return l", "title": ""}
{"_id": "d13233", "text": "def _cal_dist2center(X, center):\n    \"\"\" Calculate the SSE to the cluster center\n    \"\"\"\n    dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')\n    return(np.sum(dmemb2cen))", "title": ""}
{"_id": "d13234", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d13235", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d13236", "text": "def list_files(directory):\n    \"\"\"Returns all files in a given directory\n    \"\"\"\n    return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]", "title": ""}
{"_id": "d13237", "text": "def zs(inlist):\n    \"\"\"\nReturns a list of z-scores, one for each score in the passed list.\n\nUsage:   lzs(inlist)\n\"\"\"\n    zscores = []\n    for item in inlist:\n        zscores.append(z(inlist, item))\n    return zscores", "title": ""}
{"_id": "d13238", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d13239", "text": "def bash(filename):\n    \"\"\"Runs a bash script in the local directory\"\"\"\n    sys.stdout.flush()\n    subprocess.call(\"bash {}\".format(filename), shell=True)", "title": ""}
{"_id": "d13240", "text": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "title": ""}
{"_id": "d13241", "text": "def test3():\n    \"\"\"Test the multiprocess\n    \"\"\"\n    import time\n    \n    p = MVisionProcess()\n    p.start()\n    time.sleep(5)\n    p.stop()", "title": ""}
{"_id": "d13242", "text": "def remove_list_duplicates(lista, unique=False):\n    \"\"\"\n    Remove duplicated elements in a list.\n    Args:\n        lista: List with elements to clean duplicates.\n    \"\"\"\n    result = []\n    allready = []\n\n    for elem in lista:\n        if elem not in result:\n            result.append(elem)\n        else:\n            allready.append(elem)\n\n    if unique:\n        for elem in allready:\n            result = list(filter((elem).__ne__, result))\n\n    return result", "title": ""}
{"_id": "d13243", "text": "def other_ind(self):\n        \"\"\"last row or column of square A\"\"\"\n        return np.full(self.n_min, self.size - 1, dtype=np.int)", "title": ""}
{"_id": "d13244", "text": "def ss(*args, **kwargs):\n    \"\"\"\n    exactly like s, but doesn't return variable names or file positions (useful for logging)\n\n    since -- 10-15-2015\n    return -- str\n    \"\"\"\n    if not args:\n        raise ValueError(\"you didn't pass any arguments to print out\")\n\n    with Reflect.context(args, **kwargs) as r:\n        instance = V_CLASS(r, stream, **kwargs)\n        return instance.value().strip()", "title": ""}
{"_id": "d13245", "text": "def delistify(x):\n    \"\"\" A basic slug version of a given parameter list. \"\"\"\n    if isinstance(x, list):\n        x = [e.replace(\"'\", \"\") for e in x]\n        return '-'.join(sorted(x))\n    return x", "title": ""}
{"_id": "d13246", "text": "def __next__(self, reward, ask_id, lbl):\n        \"\"\"For Python3 compatibility of generator.\"\"\"\n        return self.next(reward, ask_id, lbl)", "title": ""}
{"_id": "d13247", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d13248", "text": "def mixedcase(path):\n    \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n    words = path.split('_')\n    return words[0] + ''.join(word.title() for word in words[1:])", "title": ""}
{"_id": "d13249", "text": "def update(self, **kwargs):\n        \"\"\" Explicitly reload context with DB usage to get access\n        to complete DB object.\n        \"\"\"\n        self.reload_context(es_based=False, **kwargs)\n        return super(ESCollectionView, self).update(**kwargs)", "title": ""}
{"_id": "d13250", "text": "def mixedcase(path):\n    \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n    words = path.split('_')\n    return words[0] + ''.join(word.title() for word in words[1:])", "title": ""}
{"_id": "d13251", "text": "def from_file(filename):\n    \"\"\"\n    load an nparray object from a json filename\n\n    @parameter str filename: path to the file\n    \"\"\"\n    f = open(filename, 'r')\n    j = json.load(f)\n    f.close()\n\n    return from_dict(j)", "title": ""}
{"_id": "d13252", "text": "def handle_test(self, command, **options):\n        \"\"\"Send a test error to APM Server\"\"\"\n        # can't be async for testing\n        config = {\"async_mode\": False}\n        for key in (\"service_name\", \"secret_token\"):\n            if options.get(key):\n                config[key] = options[key]\n        client = DjangoClient(**config)\n        client.error_logger = ColoredLogger(self.stderr)\n        client.logger = ColoredLogger(self.stderr)\n        self.write(\n            \"Trying to send a test error to APM Server using these settings:\\n\\n\"\n            \"SERVICE_NAME:\\t%s\\n\"\n            \"SECRET_TOKEN:\\t%s\\n\"\n            \"SERVER:\\t\\t%s\\n\\n\" % (client.config.service_name, client.config.secret_token, client.config.server_url)\n        )\n\n        try:\n            raise TestException(\"Hi there!\")\n        except TestException:\n            client.capture_exception()\n            if not client.error_logger.errors:\n                self.write(\n                    \"Success! We tracked the error successfully! You should be\"\n                    \" able to see it in a few seconds at the above URL\"\n                )\n        finally:\n            client.close()", "title": ""}
{"_id": "d13253", "text": "def load(cls, fp, **kwargs):\n    \"\"\"wrapper for :py:func:`json.load`\"\"\"\n    json_obj = json.load(fp, **kwargs)\n    return parse(cls, json_obj)", "title": ""}
{"_id": "d13254", "text": "def int2str(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from integers to strings\"\"\"\n    return NumConv(radix, alphabet).int2str(num)", "title": ""}
{"_id": "d13255", "text": "def load_graph_from_rdf(fname):\n    \"\"\" reads an RDF file into a graph \"\"\"\n    print(\"reading RDF from \" + fname + \"....\")\n    store = Graph()\n    store.parse(fname, format=\"n3\")\n    print(\"Loaded \" + str(len(store)) + \" tuples\")\n    return store", "title": ""}
{"_id": "d13256", "text": "def info(txt):\n    \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d13257", "text": "def tuple_search(t, i, v):\n    \"\"\"\n    Search tuple array by index and value\n    :param t: tuple array\n    :param i: index of the value in each tuple\n    :param v: value\n    :return: the first tuple in the array with the specific index / value\n    \"\"\"\n    for e in t:\n        if e[i] == v:\n            return e\n    return None", "title": ""}
{"_id": "d13258", "text": "def col_rename(df,col_name,new_col_name):\n    \"\"\" Changes a column name in a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_name - string\n        Name of column to change\n    new_col_name - string\n        New name of column\n    \"\"\"\n    col_list = list(df.columns)\n    for index,value in enumerate(col_list):\n        if value == col_name:\n            col_list[index] = new_col_name\n            break\n    df.columns = col_list", "title": ""}
{"_id": "d13259", "text": "def _find(string, sub_string, start_index):\n    \"\"\"Return index of sub_string in string.\n\n    Raise TokenError if sub_string is not found.\n    \"\"\"\n    result = string.find(sub_string, start_index)\n    if result == -1:\n        raise TokenError(\"expected '{0}'\".format(sub_string))\n    return result", "title": ""}
{"_id": "d13260", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d13261", "text": "def assert_lock(fname):\n    \"\"\"\n    If file is locked then terminate program else lock file.\n    \"\"\"\n\n    if not set_lock(fname):\n        logger.error('File {} is already locked. Terminating.'.format(fname))\n        sys.exit()", "title": ""}
{"_id": "d13262", "text": "def colorize(string, color, *args, **kwargs):\n    \"\"\"\n    Implements string formatting along with color specified in colorama.Fore\n    \"\"\"\n    string = string.format(*args, **kwargs)\n    return color + string + colorama.Fore.RESET", "title": ""}
{"_id": "d13263", "text": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "title": ""}
{"_id": "d13264", "text": "def normalise_string(string):\n    \"\"\" Strips trailing whitespace from string, lowercases it and replaces\n        spaces with underscores\n    \"\"\"\n    string = (string.strip()).lower()\n    return re.sub(r'\\W+', '_', string)", "title": ""}
{"_id": "d13265", "text": "def write(self, text):\n        \"\"\"Write text. An additional attribute terminator with a value of\n           None is added to the logging record to indicate that StreamHandler\n           should not add a newline.\"\"\"\n        self.logger.log(self.loglevel, text, extra={'terminator': None})", "title": ""}
{"_id": "d13266", "text": "def str2int(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n    return NumConv(radix, alphabet).str2int(num)", "title": ""}
{"_id": "d13267", "text": "def printc(cls, txt, color=colors.red):\n        \"\"\"Print in color.\"\"\"\n        print(cls.color_txt(txt, color))", "title": ""}
{"_id": "d13268", "text": "def guess_media_type(filepath):\n    \"\"\"Returns the media-type of the file at the given ``filepath``\"\"\"\n    o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath])\n    o = o.strip()\n    return o", "title": ""}
{"_id": "d13269", "text": "def clog(color):\n    \"\"\"Same to ``log``, but this one centralizes the message first.\"\"\"\n    logger = log(color)\n    return lambda msg: logger(centralize(msg).rstrip())", "title": ""}
{"_id": "d13270", "text": "def execute_cast_simple_literal_to_timestamp(op, data, type, **kwargs):\n    \"\"\"Cast integer and strings to timestamps\"\"\"\n    return pd.Timestamp(data, tz=type.timezone)", "title": ""}
{"_id": "d13271", "text": "def find_console_handler(logger):\n    \"\"\"Return a stream handler, if it exists.\"\"\"\n    for handler in logger.handlers:\n        if (isinstance(handler, logging.StreamHandler) and\n                handler.stream == sys.stderr):\n            return handler", "title": ""}
{"_id": "d13272", "text": "def title(msg):\n    \"\"\"Sets the title of the console window.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "title": ""}
{"_id": "d13273", "text": "def _debug_log(self, msg):\n        \"\"\"Debug log messages if debug=True\"\"\"\n        if not self.debug:\n            return\n        sys.stderr.write('{}\\n'.format(msg))", "title": ""}
{"_id": "d13274", "text": "def set_ylim(self, xlims, dx, xscale, reverse=False):\n        \"\"\"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.\n\n        \"\"\"\n        self._set_axis_limits('y', xlims, dx, xscale, reverse)\n        return", "title": ""}
{"_id": "d13275", "text": "def close_log(log, verbose=True):\n    \"\"\"Close log\n\n    This method closes and active logging.Logger instance.\n\n    Parameters\n    ----------\n    log : logging.Logger\n        Logging instance\n\n    \"\"\"\n\n    if verbose:\n        print('Closing log file:', log.name)\n\n    # Send closing message.\n    log.info('The log file has been closed.')\n\n    # Remove all handlers from log.\n    [log.removeHandler(handler) for handler in log.handlers]", "title": ""}
{"_id": "d13276", "text": "def check_dependencies_remote(args):\n    \"\"\"\n    Invoke this command on a remote Python.\n    \"\"\"\n    cmd = [args.python, '-m', 'depends', args.requirement]\n    env = dict(PYTHONPATH=os.path.dirname(__file__))\n    return subprocess.check_call(cmd, env=env)", "title": ""}
{"_id": "d13277", "text": "def timed_rotating_file_handler(name, logname, filename, when='h',\n                                interval=1, backupCount=0,\n                                encoding=None, delay=False, utc=False):\n    \"\"\"\n    A Bark logging handler logging output to a named file.  At\n    intervals specified by the 'when', the file will be rotated, under\n    control of 'backupCount'.\n\n    Similar to logging.handlers.TimedRotatingFileHandler.\n    \"\"\"\n\n    return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n        filename, when=when, interval=interval, backupCount=backupCount,\n        encoding=encoding, delay=delay, utc=utc))", "title": ""}
{"_id": "d13278", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d13279", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d13280", "text": "def get_from_human_key(self, key):\n        \"\"\"Return the key (aka database value) of a human key (aka Python identifier).\"\"\"\n        if key in self._identifier_map:\n            return self._identifier_map[key]\n        raise KeyError(key)", "title": ""}
{"_id": "d13281", "text": "def count_nulls(self, field):\n        \"\"\"\n        Count the number of null values in a column\n        \"\"\"\n        try:\n            n = self.df[field].isnull().sum()\n        except KeyError:\n            self.warning(\"Can not find column\", field)\n            return\n        except Exception as e:\n            self.err(e, \"Can not count nulls\")\n            return\n        self.ok(\"Found\", n, \"nulls in column\", field)", "title": ""}
{"_id": "d13282", "text": "async def restart(request):\n    \"\"\"\n    Returns OK, then waits approximately 1 second and restarts container\n    \"\"\"\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\"})", "title": ""}
{"_id": "d13283", "text": "def make_kind_check(python_types, numpy_kind):\n    \"\"\"\n    Make a function that checks whether a scalar or array is of a given kind\n    (e.g. float, int, datetime, timedelta).\n    \"\"\"\n    def check(value):\n        if hasattr(value, 'dtype'):\n            return value.dtype.kind == numpy_kind\n        return isinstance(value, python_types)\n    return check", "title": ""}
{"_id": "d13284", "text": "def dict_keys_without_hyphens(a_dict):\n    \"\"\"Return the a new dict with underscores instead of hyphens in keys.\"\"\"\n    return dict(\n        (key.replace('-', '_'), val) for key, val in a_dict.items())", "title": ""}
{"_id": "d13285", "text": "def validate_email(email):\n    \"\"\"\n    Validates an email address\n    Source: Himanshu Shankar (https://github.com/iamhssingh)\n    Parameters\n    ----------\n    email: str\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    from django.core.validators import validate_email\n    from django.core.exceptions import ValidationError\n    try:\n        validate_email(email)\n        return True\n    except ValidationError:\n        return False", "title": ""}
{"_id": "d13286", "text": "def _guess_extract_method(fname):\n  \"\"\"Guess extraction method, given file name (or path).\"\"\"\n  for method, extensions in _EXTRACTION_METHOD_TO_EXTS:\n    for ext in extensions:\n      if fname.endswith(ext):\n        return method\n  return ExtractMethod.NO_EXTRACT", "title": ""}
{"_id": "d13287", "text": "def is_empty(self):\n        \"\"\"Returns True if the root node contains no child elements, no text,\n        and no attributes other than **type**. Returns False if any are present.\"\"\"\n        non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type']\n        return len(self.node) == 0 and len(non_type_attributes) == 0 \\\n            and not self.node.text and not self.node.tail", "title": ""}
{"_id": "d13288", "text": "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n    \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n    return maybe_list and any(is_multiline(item) for item in maybe_list)", "title": ""}
{"_id": "d13289", "text": "def path_to_list(pathstr):\n    \"\"\"Conver a path string to a list of path elements.\"\"\"\n    return [elem for elem in pathstr.split(os.path.pathsep) if elem]", "title": ""}
{"_id": "d13290", "text": "def issorted(list_, op=operator.le):\n    \"\"\"\n    Determines if a list is sorted\n\n    Args:\n        list_ (list):\n        op (func): sorted operation (default=operator.le)\n\n    Returns:\n        bool : True if the list is sorted\n    \"\"\"\n    return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))", "title": ""}
{"_id": "d13291", "text": "def package_in_pypi(package):\n    \"\"\"Check whether the package is registered on pypi\"\"\"\n    url = 'http://pypi.python.org/simple/%s' % package\n    try:\n        urllib.request.urlopen(url)\n        return True\n    except urllib.error.HTTPError as e:\n        logger.debug(\"Package not found on pypi: %s\", e)\n        return False", "title": ""}
{"_id": "d13292", "text": "def is_alive(self):\n        \"\"\"\n        Will test whether the ACS service is up and alive.\n        \"\"\"\n        response = self.get_monitoring_heartbeat()\n        if response.status_code == 200 and response.content == 'alive':\n            return True\n\n        return False", "title": ""}
{"_id": "d13293", "text": "def sine_wave(frequency):\n  \"\"\"Emit a sine wave at the given frequency.\"\"\"\n  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n  ts = xs / FLAGS.sample_rate\n  return tf.sin(2 * math.pi * frequency * ts)", "title": ""}
{"_id": "d13294", "text": "def starts_with_prefix_in_list(text, prefixes):\n    \"\"\"\n    Return True if the given string starts with one of the prefixes in the given list, otherwise\n    return False.\n\n    Arguments:\n        text (str): Text to check for prefixes.\n        prefixes (list): List of prefixes to check for.\n\n    Returns:\n        bool: True if the given text starts with any of the given prefixes, otherwise False.\n    \"\"\"\n    for prefix in prefixes:\n        if text.startswith(prefix):\n            return True\n    return False", "title": ""}
{"_id": "d13295", "text": "def cleanup_storage(*args):\n    \"\"\"Clean up processes after SIGTERM or SIGINT is received.\"\"\"\n    ShardedClusters().cleanup()\n    ReplicaSets().cleanup()\n    Servers().cleanup()\n    sys.exit(0)", "title": ""}
{"_id": "d13296", "text": "def is_string(val):\n    \"\"\"Determines whether the passed value is a string, safe for 2/3.\"\"\"\n    try:\n        basestring\n    except NameError:\n        return isinstance(val, str)\n    return isinstance(val, basestring)", "title": ""}
{"_id": "d13297", "text": "def colorbar(height, length, colormap):\n    \"\"\"Return the channels of a colorbar.\n    \"\"\"\n    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n    cbar = (cbar * (colormap.values.max() - colormap.values.min())\n            + colormap.values.min())\n\n    return colormap.colorize(cbar)", "title": ""}
{"_id": "d13298", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d13299", "text": "def imapchain(*a, **kwa):\n    \"\"\" Like map but also chains the results. \"\"\"\n\n    imap_results = map( *a, **kwa )\n    return itertools.chain( *imap_results )", "title": ""}
{"_id": "d13300", "text": "def instance_name(string):\n    \"\"\"Check for valid instance name\n    \"\"\"\n    invalid = ':/@'\n    if set(string).intersection(invalid):\n        msg = 'Invalid instance name {}'.format(string)\n        raise argparse.ArgumentTypeError(msg)\n    return string", "title": ""}
{"_id": "d13301", "text": "def OnDoubleClick(self, event):\n        \"\"\"Double click on a given square in the map\"\"\"\n        node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())\n        if node:\n            wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) )", "title": ""}
{"_id": "d13302", "text": "def check_update():\n    \"\"\"\n    Check for app updates and print/log them.\n    \"\"\"\n    logging.info('Check for app updates.')\n    try:\n        update = updater.check_for_app_updates()\n    except Exception:\n        logging.exception('Check for updates failed.')\n        return\n    if update:\n        print(\"!!! UPDATE AVAILABLE !!!\\n\"\n              \"\" + static_data.PROJECT_URL + \"\\n\\n\")\n        logging.info(\"Update available: \" + static_data.PROJECT_URL)\n    else:\n        logging.info(\"No update available.\")", "title": ""}
{"_id": "d13303", "text": "def is_number(obj):\n    \"\"\"Check if obj is number.\"\"\"\n    return isinstance(obj, (int, float, np.int_, np.float_))", "title": ""}
{"_id": "d13304", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d13305", "text": "def service_available(service_name):\n    \"\"\"Determine whether a system service is available\"\"\"\n    try:\n        subprocess.check_output(\n            ['service', service_name, 'status'],\n            stderr=subprocess.STDOUT).decode('UTF-8')\n    except subprocess.CalledProcessError as e:\n        return b'unrecognized service' not in e.output\n    else:\n        return True", "title": ""}
{"_id": "d13306", "text": "def get_matrix(self):\n        \"\"\"  Use numpy to create a real matrix object from the data\n\n        :return: the matrix representation of the fvm\n        \"\"\"\n        return np.array([ self.get_row_list(i) for i in range(self.row_count()) ])", "title": ""}
{"_id": "d13307", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d13308", "text": "def fix(h, i):\n    \"\"\"Rearrange the heap after the item at position i got updated.\"\"\"\n    down(h, i, h.size())\n    up(h, i)", "title": ""}
{"_id": "d13309", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d13310", "text": "def heappop_max(heap):\n    \"\"\"Maxheap version of a heappop.\"\"\"\n    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty\n    if heap:\n        returnitem = heap[0]\n        heap[0] = lastelt\n        _siftup_max(heap, 0)\n        return returnitem\n    return lastelt", "title": ""}
{"_id": "d13311", "text": "def db_exists():\n    \"\"\"Test if DATABASES['default'] exists\"\"\"\n    logger.info(\"Checking to see if %s already exists\", repr(DB[\"NAME\"]))\n    try:\n        # Hide stderr since it is confusing here\n        psql(\"\", stderr=subprocess.STDOUT)\n    except subprocess.CalledProcessError:\n        return False\n    return True", "title": ""}
{"_id": "d13312", "text": "def hmean_int(a, a_min=5778, a_max=1149851):\n    \"\"\" Harmonic mean of an array, returns the closest int\n    \"\"\"\n    from scipy.stats import hmean\n    return int(round(hmean(np.clip(a, a_min, a_max))))", "title": ""}
{"_id": "d13313", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d13314", "text": "def min_or_none(val1, val2):\n    \"\"\"Returns min(val1, val2) returning None only if both values are None\"\"\"\n    return min(val1, val2, key=lambda x: sys.maxint if x is None else x)", "title": ""}
{"_id": "d13315", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d13316", "text": "def main_func(args=None):\n    \"\"\"Main funcion when executing this module as script\n\n    :param args: commandline arguments\n    :type args: list\n    :returns: None\n    :rtype: None\n    :raises: None\n    \"\"\"\n    # we have to initialize a gui even if we dont need one right now.\n    # as soon as you call maya.standalone.initialize(), a QApplication\n    # with type Tty is created. This is the type for conosle apps.\n    # Because i have not found a way to replace that, we just init the gui.\n    guimain.init_gui()\n\n    main.init()\n    launcher = Launcher()\n    parsed, unknown = launcher.parse_args(args)\n    parsed.func(parsed, unknown)", "title": ""}
{"_id": "d13317", "text": "def launched():\n    \"\"\"Test whether the current python environment is the correct lore env.\n\n    :return:  :any:`True` if the environment is launched\n    :rtype: bool\n    \"\"\"\n    if not PREFIX:\n        return False\n\n    return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)", "title": ""}
{"_id": "d13318", "text": "def md5_hash_file(fh):\n    \"\"\"Return the md5 hash of the given file-object\"\"\"\n    md5 = hashlib.md5()\n    while True:\n        data = fh.read(8192)\n        if not data:\n            break\n        md5.update(data)\n    return md5.hexdigest()", "title": ""}
{"_id": "d13319", "text": "def timeit(method):\n    \"\"\"\n    A Python decorator for printing out the execution time for a function.\n\n    Adapted from:\n    www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods\n    \"\"\"\n    def timed(*args, **kw):\n        time_start = time.time()\n        result = method(*args, **kw)\n        time_end = time.time()\n        print('timeit: %r %2.2f sec (%r, %r) ' % (method.__name__, time_end-time_start, str(args)[:20], kw))\n        return result\n\n    return timed", "title": ""}
{"_id": "d13320", "text": "def service_available(service_name):\n    \"\"\"Determine whether a system service is available\"\"\"\n    try:\n        subprocess.check_output(\n            ['service', service_name, 'status'],\n            stderr=subprocess.STDOUT).decode('UTF-8')\n    except subprocess.CalledProcessError as e:\n        return b'unrecognized service' not in e.output\n    else:\n        return True", "title": ""}
{"_id": "d13321", "text": "def value(self):\n        \"\"\"Value of property.\"\"\"\n        if self._prop.fget is None:\n            raise AttributeError('Unable to read attribute')\n        return self._prop.fget(self._obj)", "title": ""}
{"_id": "d13322", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d13323", "text": "def contextMenuEvent(self, event):\n        \"\"\"Override Qt method\"\"\"\n        self.update_menu()\n        self.menu.popup(event.globalPos())", "title": ""}
{"_id": "d13324", "text": "def dict_merge(set1, set2):\n    \"\"\"Joins two dictionaries.\"\"\"\n    return dict(list(set1.items()) + list(set2.items()))", "title": ""}
{"_id": "d13325", "text": "def load_library(version):\n    \"\"\"\n    Load the correct module according to the version\n\n    :type version: ``str``\n    :param version: the version of the library to be loaded (e.g. '2.6')\n    :rtype: module object\n    \"\"\"\n    check_version(version)\n    module_name = SUPPORTED_LIBRARIES[version]\n    lib = sys.modules.get(module_name)\n    if lib is None:\n        lib = importlib.import_module(module_name)\n    return lib", "title": ""}
{"_id": "d13326", "text": "def dict_merge(set1, set2):\n    \"\"\"Joins two dictionaries.\"\"\"\n    return dict(list(set1.items()) + list(set2.items()))", "title": ""}
{"_id": "d13327", "text": "def string_to_list(string, sep=\",\", filter_empty=False):\n    \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n    return [value.strip() for value in string.split(sep)\n            if (not filter_empty or value)]", "title": ""}
{"_id": "d13328", "text": "def is_enum_type(type_):\n    \"\"\" Checks if the given type is an enum type.\n\n    :param type_: The type to check\n    :return: True if the type is a enum type, otherwise False\n    :rtype: bool\n    \"\"\"\n\n    return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))", "title": ""}
{"_id": "d13329", "text": "def __ror__(self, other):\n\t\t\"\"\"The main machinery of the Pipe, calling the chosen callable with the recorded arguments.\"\"\"\n\t\t\n\t\treturn self.callable(*(self.args + (other, )), **self.kwargs)", "title": ""}
{"_id": "d13330", "text": "def remove(self, key):\n        \"\"\"remove the value found at key from the queue\"\"\"\n        item = self.item_finder.pop(key)\n        item[-1] = None\n        self.removed_count += 1", "title": ""}
{"_id": "d13331", "text": "def pop (self, key):\n        \"\"\"Remove key from dict and return value.\"\"\"\n        if key in self._keys:\n            self._keys.remove(key)\n        super(ListDict, self).pop(key)", "title": ""}
{"_id": "d13332", "text": "def accel_next(self, *args):\n        \"\"\"Callback to go to the next tab. Called by the accel key.\n        \"\"\"\n        if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n            self.get_notebook().set_current_page(0)\n        else:\n            self.get_notebook().next_page()\n        return True", "title": ""}
{"_id": "d13333", "text": "def datetime_delta_to_ms(delta):\n    \"\"\"\n    Given a datetime.timedelta object, return the delta in milliseconds\n    \"\"\"\n    delta_ms = delta.days * 24 * 60 * 60 * 1000\n    delta_ms += delta.seconds * 1000\n    delta_ms += delta.microseconds / 1000\n    delta_ms = int(delta_ms)\n    return delta_ms", "title": ""}
{"_id": "d13334", "text": "def pair_strings_sum_formatter(a, b):\n  \"\"\"\n  Formats the sum of a and b.\n\n  Note\n  ----\n  Both inputs are numbers already converted to strings.\n\n  \"\"\"\n  if b[:1] == \"-\":\n    return \"{0} - {1}\".format(a, b[1:])\n  return \"{0} + {1}\".format(a, b)", "title": ""}
{"_id": "d13335", "text": "def distance_to_line(a, b, p):\n    \"\"\"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\n    \"\"\"\n    return distance(closest_point(a, b, p), p)", "title": ""}
{"_id": "d13336", "text": "def compare(self, first, second):\n        \"\"\"\n        Case in-sensitive comparison of two strings.\n        Required arguments:\n        * first - The first string to compare.\n        * second - The second string to compare.\n        \"\"\"\n        if first.lower() == second.lower():\n            return True\n        else:\n            return False", "title": ""}
{"_id": "d13337", "text": "def comments(self):\n    \"\"\"The AST comments.\"\"\"\n    if self._comments is None:\n      self._comments = [c for c in self.grammar.children if c.is_type(TokenType.comment)]\n    return self._comments", "title": ""}
{"_id": "d13338", "text": "def mock_decorator(*args, **kwargs):\n    \"\"\"Mocked decorator, needed in the case we need to mock a decorator\"\"\"\n    def _called_decorator(dec_func):\n        @wraps(dec_func)\n        def _decorator(*args, **kwargs):\n            return dec_func()\n        return _decorator\n    return _called_decorator", "title": ""}
{"_id": "d13339", "text": "def cols_str(columns):\n    \"\"\"Concatenate list of columns into a string.\"\"\"\n    cols = \"\"\n    for c in columns:\n        cols = cols + wrap(c) + ', '\n    return cols[:-2]", "title": ""}
{"_id": "d13340", "text": "def api_test(method='GET', **response_kwargs):\n    \"\"\" Decorator to ensure API calls are made and return expected data. \"\"\"\n\n    method = method.lower()\n\n    def api_test_factory(fn):\n        @functools.wraps(fn)\n        @mock.patch('requests.{}'.format(method))\n        def execute_test(method_func, *args, **kwargs):\n            method_func.return_value = MockResponse(**response_kwargs)\n\n            expected_url, response = fn(*args, **kwargs)\n\n            method_func.assert_called_once()\n            assert_valid_api_call(method_func, expected_url)\n            assert isinstance(response, JSONAPIParser)\n            assert response.json_data is method_func.return_value.data\n\n        return execute_test\n\n    return api_test_factory", "title": ""}
{"_id": "d13341", "text": "def _config_session():\n        \"\"\"\n        Configure session for particular device\n\n        Returns:\n            tensorflow.Session\n        \"\"\"\n        config = tf.ConfigProto()\n        config.gpu_options.allow_growth = True\n        config.gpu_options.visible_device_list = '0'\n        return tf.Session(config=config)", "title": ""}
{"_id": "d13342", "text": "def gaussian_variogram_model(m, d):\n    \"\"\"Gaussian model, m is [psill, range, nugget]\"\"\"\n    psill = float(m[0])\n    range_ = float(m[1])\n    nugget = float(m[2])\n    return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget", "title": ""}
{"_id": "d13343", "text": "def advance_one_line(self):\n    \"\"\"Advances to next line.\"\"\"\n\n    current_line = self._current_token.line_number\n    while current_line == self._current_token.line_number:\n      self._current_token = ConfigParser.Token(*next(self._token_generator))", "title": ""}
{"_id": "d13344", "text": "def get_object_or_none(model, *args, **kwargs):\n    \"\"\"\n    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.\n    \"\"\"\n    try:\n        return model._default_manager.get(*args, **kwargs)\n    except model.DoesNotExist:\n        return None", "title": ""}
{"_id": "d13345", "text": "def copy(a):\n    \"\"\" Copy an array to the shared memory. \n\n        Notes\n        -----\n        copy is not always necessary because the private memory is always copy-on-write.\n\n        Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory\n    \"\"\"\n    shared = anonymousmemmap(a.shape, dtype=a.dtype)\n    shared[:] = a[:]\n    return shared", "title": ""}
{"_id": "d13346", "text": "def _is_root():\n    \"\"\"Checks if the user is rooted.\"\"\"\n    import os\n    import ctypes\n    try:\n        return os.geteuid() == 0\n    except AttributeError:\n        return ctypes.windll.shell32.IsUserAnAdmin() != 0\n    return False", "title": ""}
{"_id": "d13347", "text": "def generic_add(a, b):\n    \"\"\"Simple function to add two numbers\"\"\"\n    logger.debug('Called generic_add({}, {})'.format(a, b))\n    return a + b", "title": ""}
{"_id": "d13348", "text": "def MatrixInverse(a, adj):\n    \"\"\"\n    Matrix inversion op.\n    \"\"\"\n    return np.linalg.inv(a if not adj else _adjoint(a)),", "title": ""}
{"_id": "d13349", "text": "def entropy(string):\n    \"\"\"Compute entropy on the string\"\"\"\n    p, lns = Counter(string), float(len(string))\n    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())", "title": ""}
{"_id": "d13350", "text": "def write(self, value):\n        \"\"\"\n        Write value to the target\n        \"\"\"\n        self.get_collection().update_one(\n            {'_id': self._document_id},\n            {'$set': {self._path: value}},\n            upsert=True\n        )", "title": ""}
{"_id": "d13351", "text": "def line_count(fn):\n    \"\"\" Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)\n    \"\"\"\n\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "title": ""}
{"_id": "d13352", "text": "def _calc_dir_size(path):\n    \"\"\"\n    Calculate size of all files in `path`.\n\n    Args:\n        path (str): Path to the directory.\n\n    Returns:\n        int: Size of the directory in bytes.\n    \"\"\"\n    dir_size = 0\n    for (root, dirs, files) in os.walk(path):\n        for fn in files:\n            full_fn = os.path.join(root, fn)\n            dir_size += os.path.getsize(full_fn)\n\n    return dir_size", "title": ""}
{"_id": "d13353", "text": "def _crop_list_to_size(l, size):\n    \"\"\"Make a list a certain size\"\"\"\n    for x in range(size - len(l)):\n        l.append(False)\n    for x in range(len(l) - size):\n        l.pop()\n    return l", "title": ""}
{"_id": "d13354", "text": "def go_to_line(self, line):\n        \"\"\"\n        Moves the text cursor to given line.\n\n        :param line: Line to go to.\n        :type line: int\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        cursor = self.textCursor()\n        cursor.setPosition(self.document().findBlockByNumber(line - 1).position())\n        self.setTextCursor(cursor)\n        return True", "title": ""}
{"_id": "d13355", "text": "def new_from_list(cls, items, **kwargs):\n        \"\"\"Populates the ListView with a string list.\n\n        Args:\n            items (list): list of strings to fill the widget with.\n        \"\"\"\n        obj = cls(**kwargs)\n        for item in items:\n            obj.append(ListItem(item))\n        return obj", "title": ""}
{"_id": "d13356", "text": "def mouse_move_event(self, event):\n        \"\"\"\n        Forward mouse cursor position events to the example\n        \"\"\"\n        self.example.mouse_position_event(event.x(), event.y())", "title": ""}
{"_id": "d13357", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d13358", "text": "def store_many(self, sql, values):\n        \"\"\"Abstraction over executemany method\"\"\"\n        cursor = self.get_cursor()\n        cursor.executemany(sql, values)\n        self.conn.commit()", "title": ""}
{"_id": "d13359", "text": "def read_dict_from_file(file_path):\n    \"\"\"\n    Read a dictionary of strings from a file\n    \"\"\"\n    with open(file_path) as file:\n        lines = file.read().splitlines()\n\n    obj = {}\n    for line in lines:\n        key, value = line.split(':', maxsplit=1)\n        obj[key] = eval(value)\n\n    return obj", "title": ""}
{"_id": "d13360", "text": "def __enter__(self):\n        \"\"\"Acquire a lock on the output file, prevents collisions between multiple runs.\"\"\"\n        self.fd = open(self.filename, 'a')\n        fcntl.lockf(self.fd, fcntl.LOCK_EX)\n        return self.fd", "title": ""}
{"_id": "d13361", "text": "def read_dict_from_file(file_path):\n    \"\"\"\n    Read a dictionary of strings from a file\n    \"\"\"\n    with open(file_path) as file:\n        lines = file.read().splitlines()\n\n    obj = {}\n    for line in lines:\n        key, value = line.split(':', maxsplit=1)\n        obj[key] = eval(value)\n\n    return obj", "title": ""}
{"_id": "d13362", "text": "def machine_info():\n    \"\"\"Retrieve core and memory information for the current machine.\n    \"\"\"\n    import psutil\n    BYTES_IN_GIG = 1073741824.0\n    free_bytes = psutil.virtual_memory().total\n    return [{\"memory\": float(\"%.1f\" % (free_bytes / BYTES_IN_GIG)), \"cores\": multiprocessing.cpu_count(),\n             \"name\": socket.gethostname()}]", "title": ""}
{"_id": "d13363", "text": "def write_file(filename, content):\n    \"\"\"Create the file with the given content\"\"\"\n    print 'Generating {0}'.format(filename)\n    with open(filename, 'wb') as out_f:\n        out_f.write(content)", "title": ""}
{"_id": "d13364", "text": "def compute(args):\n    x, y, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot(x, y, params)", "title": ""}
{"_id": "d13365", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d13366", "text": "def parallel(processes, threads):\n    \"\"\"\n    execute jobs in processes using N threads\n    \"\"\"\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()", "title": ""}
{"_id": "d13367", "text": "def percent_d(data, period):\n    \"\"\"\n    %D.\n\n    Formula:\n    %D = SMA(%K, 3)\n    \"\"\"\n    p_k = percent_k(data, period)\n    percent_d = sma(p_k, 3)\n    return percent_d", "title": ""}
{"_id": "d13368", "text": "def handle_m2m(self, sender, instance, **kwargs):\n    \"\"\" Handle many to many relationships \"\"\"\n    self.handle_save(instance.__class__, instance)", "title": ""}
{"_id": "d13369", "text": "def title(self):\n        \"\"\" The title of this window \"\"\"\n        with switch_window(self._browser, self.name):\n            return self._browser.title", "title": ""}
{"_id": "d13370", "text": "def input_yn(conf_mess):\n    \"\"\"Print Confirmation Message and Get Y/N response from user.\"\"\"\n    ui_erase_ln()\n    ui_print(conf_mess)\n    with term.cbreak():\n        input_flush()\n        val = input_by_key()\n    return bool(val.lower() == 'y')", "title": ""}
{"_id": "d13371", "text": "def get_last_id(self, cur, table='reaction'):\n        \"\"\"\n        Get the id of the last written row in table\n\n        Parameters\n        ----------\n        cur: database connection().cursor() object\n        table: str\n            'reaction', 'publication', 'publication_system', 'reaction_system'\n\n        Returns: id\n        \"\"\"\n        cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n                    .format(table))\n        result = cur.fetchone()\n        if result is not None:\n            id = result[0]\n        else:\n            id = 0\n        return id", "title": ""}
{"_id": "d13372", "text": "def from_dict(cls, d):\n        \"\"\"Create an instance from a dictionary.\"\"\"\n        return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})", "title": ""}
{"_id": "d13373", "text": "def _dictfetchall(self, cursor):\n        \"\"\" Return all rows from a cursor as a dict. \"\"\"\n        columns = [col[0] for col in cursor.description]\n        return [\n            dict(zip(columns, row))\n            for row in cursor.fetchall()\n        ]", "title": ""}
{"_id": "d13374", "text": "def create_node(self, network, participant):\n        \"\"\"Create a node for a participant.\"\"\"\n        return self.models.MCMCPAgent(network=network, participant=participant)", "title": ""}
{"_id": "d13375", "text": "def index_nearest(array, value):\n    \"\"\"\n    Finds index of nearest value in array.\n\n    Args:\n        array: numpy array\n        value:\n\n    Returns:\n        int\n\n    http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array\n    \"\"\"\n    idx = (np.abs(array-value)).argmin()\n    return idx", "title": ""}
{"_id": "d13376", "text": "def a2s(a):\n    \"\"\"\n     convert 3,3 a matrix to 6 element \"s\" list  (see Tauxe 1998)\n    \"\"\"\n    s = np.zeros((6,), 'f')  # make the a matrix\n    for i in range(3):\n        s[i] = a[i][i]\n    s[3] = a[0][1]\n    s[4] = a[1][2]\n    s[5] = a[0][2]\n    return s", "title": ""}
{"_id": "d13377", "text": "def flatten(lis):\n    \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n    new_lis = []\n    for item in lis:\n        if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n            new_lis.extend(flatten(item))\n        else:\n            new_lis.append(item)\n    return new_lis", "title": ""}
{"_id": "d13378", "text": "def doc_parser():\n    \"\"\"Utility function to allow getting the arguments for a single command, for Sphinx documentation\"\"\"\n\n    parser = argparse.ArgumentParser(\n        prog='ambry',\n        description='Ambry {}. Management interface for ambry, libraries '\n                    'and repositories. '.format(ambry._meta.__version__))\n\n    return parser", "title": ""}
{"_id": "d13379", "text": "def has_edge(self, edge):\n        \"\"\"\n        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.\n        \"\"\"\n        u, v = edge\n        return (u, v) in self.edge_properties", "title": ""}
{"_id": "d13380", "text": "def next(self):\n        \"\"\"Get the next value in the page.\"\"\"\n        item = six.next(self._item_iter)\n        result = self._item_to_value(self._parent, item)\n        # Since we've successfully got the next value from the\n        # iterator, we update the number of remaining.\n        self._remaining -= 1\n        return result", "title": ""}
{"_id": "d13381", "text": "def _Enum(docstring, *names):\n  \"\"\"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.\n  \"\"\"\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)", "title": ""}
{"_id": "d13382", "text": "def purge_duplicates(list_in):\n    \"\"\"Remove duplicates from list while preserving order.\n\n    Parameters\n    ----------\n    list_in: Iterable\n\n    Returns\n    -------\n    list\n        List of first occurences in order\n    \"\"\"\n    _list = []\n    for item in list_in:\n        if item not in _list:\n            _list.append(item)\n    return _list", "title": ""}
{"_id": "d13383", "text": "def __eq__(self, other):\n        \"\"\"Determine if two objects are equal.\"\"\"\n        return isinstance(other, self.__class__) \\\n            and self._freeze() == other._freeze()", "title": ""}
{"_id": "d13384", "text": "def is_a_sequence(var, allow_none=False):\n    \"\"\" Returns True if var is a list or a tuple (but not a string!)\n    \"\"\"\n    return isinstance(var, (list, tuple)) or (var is None and allow_none)", "title": ""}
{"_id": "d13385", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d13386", "text": "def delete_all_eggs(self):\n        \"\"\" delete all the eggs in the directory specified \"\"\"\n        path_to_delete = os.path.join(self.egg_directory, \"lib\", \"python\")\n        if os.path.exists(path_to_delete):\n            shutil.rmtree(path_to_delete)", "title": ""}
{"_id": "d13387", "text": "def Gaussian(x, mu, sig):\n    \"\"\"\n    Gaussian pdf.\n    :param x: free variable.\n    :param mu: mean of the distribution.\n    :param sig: standard deviation of the distribution.\n    :return: sympy.Expr for a Gaussian pdf.\n    \"\"\"\n    return sympy.exp(-(x - mu)**2/(2*sig**2))/sympy.sqrt(2*sympy.pi*sig**2)", "title": ""}
{"_id": "d13388", "text": "def remove_examples_all():\n    \"\"\"remove arduino/examples/all directory.\n\n    :rtype: None\n\n    \"\"\"\n    d = examples_all_dir()\n    if d.exists():\n        log.debug('remove %s', d)\n        d.rmtree()\n    else:\n        log.debug('nothing to remove: %s', d)", "title": ""}
{"_id": "d13389", "text": "def denorm(self,arr):\n        \"\"\"Reverse the normalization done to a batch of images.\n\n        Arguments:\n            arr: of shape/size (N,3,sz,sz)\n        \"\"\"\n        if type(arr) is not np.ndarray: arr = to_np(arr)\n        if len(arr.shape)==3: arr = arr[None]\n        return self.transform.denorm(np.rollaxis(arr,1,4))", "title": ""}
{"_id": "d13390", "text": "def delete_index(index):\n    \"\"\"Delete index entirely (removes all documents and mapping).\"\"\"\n    logger.info(\"Deleting search index: '%s'\", index)\n    client = get_client()\n    return client.indices.delete(index=index)", "title": ""}
{"_id": "d13391", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d13392", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d13393", "text": "def normalize(X):\n    \"\"\" equivalent to scipy.preprocessing.normalize on sparse matrices\n    , but lets avoid another depedency just for a small utility function \"\"\"\n    X = coo_matrix(X)\n    X.data = X.data / sqrt(bincount(X.row, X.data ** 2))[X.row]\n    return X", "title": ""}
{"_id": "d13394", "text": "def rm(venv_name):\n    \"\"\" Removes the venv by name \"\"\"\n    inenv = InenvManager()\n    venv = inenv.get_venv(venv_name)\n    click.confirm(\"Delete dir {}\".format(venv.path))\n    shutil.rmtree(venv.path)", "title": ""}
{"_id": "d13395", "text": "def test(nose_argsuments):\n    \"\"\" Run application tests \"\"\"\n    from nose import run\n\n    params = ['__main__', '-c', 'nose.ini']\n    params.extend(nose_argsuments)\n    run(argv=params)", "title": ""}
{"_id": "d13396", "text": "def __del__(self):\n    \"\"\"Deletes the database file.\"\"\"\n    if self._delete_file:\n      try:\n        os.remove(self.name)\n      except (OSError, IOError):\n        pass", "title": ""}
{"_id": "d13397", "text": "def request(self, method, url, body=None, headers={}):\n        \"\"\"Send a complete request to the server.\"\"\"\n        self._send_request(method, url, body, headers)", "title": ""}
{"_id": "d13398", "text": "def sometimesish(fn):\n    \"\"\"\n    Has a 50/50 chance of calling a function\n    \"\"\"\n    def wrapped(*args, **kwargs):\n        if random.randint(1, 2) == 1:\n            return fn(*args, **kwargs)\n\n    return wrapped", "title": ""}
{"_id": "d13399", "text": "def _not(condition=None, **kwargs):\n    \"\"\"\n    Return the opposite of input condition.\n\n    :param condition: condition to process.\n\n    :result: not condition.\n    :rtype: bool\n    \"\"\"\n\n    result = True\n\n    if condition is not None:\n        result = not run(condition, **kwargs)\n\n    return result", "title": ""}
{"_id": "d13400", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d13401", "text": "def fn_min(self, a, axis=None):\n        \"\"\"\n        Return the minimum of an array, ignoring any NaNs.\n\n        :param a: The array.\n        :return: The minimum value of the array.\n        \"\"\"\n\n        return numpy.nanmin(self._to_ndarray(a), axis=axis)", "title": ""}
{"_id": "d13402", "text": "def load_library(version):\n    \"\"\"\n    Load the correct module according to the version\n\n    :type version: ``str``\n    :param version: the version of the library to be loaded (e.g. '2.6')\n    :rtype: module object\n    \"\"\"\n    check_version(version)\n    module_name = SUPPORTED_LIBRARIES[version]\n    lib = sys.modules.get(module_name)\n    if lib is None:\n        lib = importlib.import_module(module_name)\n    return lib", "title": ""}
{"_id": "d13403", "text": "def _scale_shape(dshape, scale = (1,1,1)):\n    \"\"\"returns the shape after scaling (should be the same as ndimage.zoom\"\"\"\n    nshape = np.round(np.array(dshape) * np.array(scale))\n    return tuple(nshape.astype(np.int))", "title": ""}
{"_id": "d13404", "text": "def torecarray(*args, **kwargs):\n    \"\"\"\n    Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.\n\n    \"\"\"\n\n    import numpy as np\n    return toarray(*args, **kwargs).view(np.recarray)", "title": ""}
{"_id": "d13405", "text": "def isTestCaseDisabled(test_case_class, method_name):\n    \"\"\"\n    I check to see if a method on a TestCase has been disabled via nose's\n    convention for disabling a TestCase.  This makes it so that users can\n    mix nose's parameterized tests with green as a runner.\n    \"\"\"\n    test_method = getattr(test_case_class, method_name)\n    return getattr(test_method, \"__test__\", 'not nose') is False", "title": ""}
{"_id": "d13406", "text": "def gtype(n):\n    \"\"\"\n    Return the a string with the data type of a value, for Graph data\n    \"\"\"\n    t = type(n).__name__\n    return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)", "title": ""}
{"_id": "d13407", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d13408", "text": "def filter_symlog(y, base=10.0):\n    \"\"\"Symmetrical logarithmic scale.\n\n    Optional arguments:\n\n    *base*:\n        The base of the logarithm.\n    \"\"\"\n    log_base = np.log(base)\n    sign = np.sign(y)\n    logs = np.log(np.abs(y) / log_base)\n    return sign * logs", "title": ""}
{"_id": "d13409", "text": "def length(self):\n        \"\"\"Array of vector lengths\"\"\"\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "title": ""}
{"_id": "d13410", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d13411", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d13412", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d13413", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d13414", "text": "def downcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n    return [ tt.lower() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d13415", "text": "def fn_min(self, a, axis=None):\n        \"\"\"\n        Return the minimum of an array, ignoring any NaNs.\n\n        :param a: The array.\n        :return: The minimum value of the array.\n        \"\"\"\n\n        return numpy.nanmin(self._to_ndarray(a), axis=axis)", "title": ""}
{"_id": "d13416", "text": "def downcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to lower case.\"\"\"\n    return [ tt.lower() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d13417", "text": "def get_tweepy_auth(twitter_api_key,\n                    twitter_api_secret,\n                    twitter_access_token,\n                    twitter_access_token_secret):\n    \"\"\"Make a tweepy auth object\"\"\"\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", "title": ""}
{"_id": "d13418", "text": "def replace_tab_indent(s, replace=\"    \"):\n    \"\"\"\n    :param str s: string with tabs\n    :param str replace: e.g. 4 spaces\n    :rtype: str\n    \"\"\"\n    prefix = get_indent_prefix(s)\n    return prefix.replace(\"\\t\", replace) + s[len(prefix):]", "title": ""}
{"_id": "d13419", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d13420", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d13421", "text": "def dict_merge(set1, set2):\n    \"\"\"Joins two dictionaries.\"\"\"\n    return dict(list(set1.items()) + list(set2.items()))", "title": ""}
{"_id": "d13422", "text": "def _draw_lines_internal(self, coords, colour, bg):\n        \"\"\"Helper to draw lines connecting a set of nodes that are scaled for the Screen.\"\"\"\n        for i, (x, y) in enumerate(coords):\n            if i == 0:\n                self._screen.move(x, y)\n            else:\n                self._screen.draw(x, y, colour=colour, bg=bg, thin=True)", "title": ""}
{"_id": "d13423", "text": "def _replace_file(path, content):\n  \"\"\"Writes a file if it doesn't already exist with the same content.\n\n  This is useful because cargo uses timestamps to decide whether to compile things.\"\"\"\n  if os.path.exists(path):\n    with open(path, 'r') as f:\n      if content == f.read():\n        print(\"Not overwriting {} because it is unchanged\".format(path), file=sys.stderr)\n        return\n\n  with open(path, 'w') as f:\n    f.write(content)", "title": ""}
{"_id": "d13424", "text": "def vline(self, x, y, height, color):\n        \"\"\"Draw a vertical line up to a given length.\"\"\"\n        self.rect(x, y, 1, height, color, fill=True)", "title": ""}
{"_id": "d13425", "text": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "title": ""}
{"_id": "d13426", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d13427", "text": "def delete(filething):\n    \"\"\"Remove tags from a file.\n\n    Args:\n        filething (filething)\n    Raises:\n        mutagen.MutagenError\n    \"\"\"\n\n    f = FLAC(filething)\n    filething.fileobj.seek(0)\n    f.delete(filething)", "title": ""}
{"_id": "d13428", "text": "def _float_feature(value):\n  \"\"\"Wrapper for inserting float features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(float_list=tf.train.FloatList(value=value))", "title": ""}
{"_id": "d13429", "text": "def paste(xsel=False):\n    \"\"\"Returns system clipboard contents.\"\"\"\n    selection = \"primary\" if xsel else \"clipboard\"\n    try:\n        return subprocess.Popen([\"xclip\", \"-selection\", selection, \"-o\"], stdout=subprocess.PIPE).communicate()[0].decode(\"utf-8\")\n    except OSError as why:\n        raise XclipNotFound", "title": ""}
{"_id": "d13430", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d13431", "text": "def _rgbtomask(self, obj):\n        \"\"\"Convert RGB arrays from mask canvas object back to boolean mask.\"\"\"\n        dat = obj.get_image().get_data()  # RGB arrays\n        return dat.sum(axis=2).astype(np.bool)", "title": ""}
{"_id": "d13432", "text": "def get_bound(pts):\n    \"\"\"Compute a minimal rectangle that covers all the points.\"\"\"\n    (x0, y0, x1, y1) = (INF, INF, -INF, -INF)\n    for (x, y) in pts:\n        x0 = min(x0, x)\n        y0 = min(y0, y)\n        x1 = max(x1, x)\n        y1 = max(y1, y)\n    return (x0, y0, x1, y1)", "title": ""}
{"_id": "d13433", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d13434", "text": "def clean_dataframe(df):\n    \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n    df = df.fillna(method='ffill')\n    df = df.fillna(0.0)\n    return df", "title": ""}
{"_id": "d13435", "text": "def match_aspect_to_viewport(self):\n        \"\"\"Updates Camera.aspect to match the viewport's aspect ratio.\"\"\"\n        viewport = self.viewport\n        self.aspect = float(viewport.width) / viewport.height", "title": ""}
{"_id": "d13436", "text": "def filter_list_by_indices(lst, indices):\n    \"\"\"Return a modified list containing only the indices indicated.\n\n    Args:\n        lst: Original list of values\n        indices: List of indices to keep from the original list\n\n    Returns:\n        list: Filtered list of values\n\n    \"\"\"\n    return [x for i, x in enumerate(lst) if i in indices]", "title": ""}
{"_id": "d13437", "text": "def read_img(path):\n    \"\"\" Reads image specified by path into numpy.ndarray\"\"\"\n    img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255\n    img = np.expand_dims(img.transpose(1, 0), 0)\n    return img", "title": ""}
{"_id": "d13438", "text": "def _remove_keywords(d):\n    \"\"\"\n    copy the dict, filter_keywords\n\n    Parameters\n    ----------\n    d : dict\n    \"\"\"\n    return { k:v for k, v in iteritems(d) if k not in RESERVED }", "title": ""}
{"_id": "d13439", "text": "def read_img(path):\n    \"\"\" Reads image specified by path into numpy.ndarray\"\"\"\n    img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255\n    img = np.expand_dims(img.transpose(1, 0), 0)\n    return img", "title": ""}
{"_id": "d13440", "text": "def filter_bolts(table, header):\n  \"\"\" filter to keep bolts \"\"\"\n  bolts_info = []\n  for row in table:\n    if row[0] == 'bolt':\n      bolts_info.append(row)\n  return bolts_info, header", "title": ""}
{"_id": "d13441", "text": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "title": ""}
{"_id": "d13442", "text": "def fit_gaussian(x, y, yerr, p0):\n    \"\"\" Fit a Gaussian to the data \"\"\"\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", "title": ""}
{"_id": "d13443", "text": "def truncate(self, table):\n        \"\"\"Empty a table by deleting all of its rows.\"\"\"\n        if isinstance(table, (list, set, tuple)):\n            for t in table:\n                self._truncate(t)\n        else:\n            self._truncate(table)", "title": ""}
{"_id": "d13444", "text": "def __str__(self):\n        \"\"\"Return human readable string.\"\"\"\n        return \", \".join(\"{:02x}{:02x}={:02x}{:02x}\".format(c[0][0], c[0][1], c[1][0], c[1][1]) for c in self.alias_array_)", "title": ""}
{"_id": "d13445", "text": "def sort_dict(d, key=None, reverse=False):\n    \"\"\"\n    Sorts a dict by value.\n\n    Args:\n        d: Input dictionary\n        key: Function which takes an tuple (key, object) and returns a value to\n            compare and sort by. By default, the function compares the values\n            of the dict i.e. key = lambda t : t[1]\n        reverse: Allows to reverse sort order.\n\n    Returns:\n        OrderedDict object whose keys are ordered according to their value.\n    \"\"\"\n    kv_items = [kv for kv in d.items()]\n\n    # Sort kv_items according to key.\n    if key is None:\n        kv_items.sort(key=lambda t: t[1], reverse=reverse)\n    else:\n        kv_items.sort(key=key, reverse=reverse)\n\n    # Build ordered dict.\n    return collections.OrderedDict(kv_items)", "title": ""}
{"_id": "d13446", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d13447", "text": "def _IsDirectory(parent, item):\n  \"\"\"Helper that returns if parent/item is a directory.\"\"\"\n  return tf.io.gfile.isdir(os.path.join(parent, item))", "title": ""}
{"_id": "d13448", "text": "def rgamma(alpha, beta, size=None):\n    \"\"\"\n    Random gamma variates.\n    \"\"\"\n\n    return np.random.gamma(shape=alpha, scale=1. / beta, size=size)", "title": ""}
{"_id": "d13449", "text": "def normalize_text(text, line_len=80, indent=\"\"):\n    \"\"\"Wrap the text on the given line length.\"\"\"\n    return \"\\n\".join(\n        textwrap.wrap(\n            text, width=line_len, initial_indent=indent, subsequent_indent=indent\n        )\n    )", "title": ""}
{"_id": "d13450", "text": "def random_numbers(n):\n    \"\"\"\n    Generate a random string from 0-9\n    :param n: length of the string\n    :return: the random string\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(string.digits) for _ in range(n))", "title": ""}
{"_id": "d13451", "text": "def write_config(self, outfile):\n        \"\"\"Write the configuration dictionary to an output file.\"\"\"\n        utils.write_yaml(self.config, outfile, default_flow_style=False)", "title": ""}
{"_id": "d13452", "text": "def downsample_with_striding(array, factor):\n    \"\"\"Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x.\n    \"\"\"\n    return array[tuple(np.s_[::f] for f in factor)]", "title": ""}
{"_id": "d13453", "text": "def get_mouse_location(self):\n        \"\"\"\n        Get the current mouse location (coordinates and screen number).\n\n        :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields\n        \"\"\"\n        x = ctypes.c_int(0)\n        y = ctypes.c_int(0)\n        screen_num = ctypes.c_int(0)\n        _libxdo.xdo_get_mouse_location(\n            self._xdo, ctypes.byref(x), ctypes.byref(y),\n            ctypes.byref(screen_num))\n        return mouse_location(x.value, y.value, screen_num.value)", "title": ""}
{"_id": "d13454", "text": "def zero_pad(m, n=1):\n    \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n    return np.pad(m, (n, n), mode='constant', constant_values=[0])", "title": ""}
{"_id": "d13455", "text": "def dates_in_range(start_date, end_date):\n    \"\"\"Returns all dates between two dates.\n\n    Inclusive of the start date but not the end date.\n\n    Args:\n        start_date (datetime.date)\n        end_date (datetime.date)\n\n    Returns:\n        (list) of datetime.date objects\n    \"\"\"\n    return [\n        start_date + timedelta(n)\n        for n in range(int((end_date - start_date).days))\n    ]", "title": ""}
{"_id": "d13456", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d13457", "text": "def calculate_top_margin(self):\n\t\t\"\"\"\n\t\tCalculate the margin in pixels above the plot area, setting\n\t\tborder_top.\n\t\t\"\"\"\n\t\tself.border_top = 5\n\t\tif self.show_graph_title:\n\t\t\tself.border_top += self.title_font_size\n\t\tself.border_top += 5\n\t\tif self.show_graph_subtitle:\n\t\t\tself.border_top += self.subtitle_font_size", "title": ""}
{"_id": "d13458", "text": "def dict_from_object(obj: object):\n    \"\"\"Convert a object into dictionary with all of its readable attributes.\"\"\"\n\n    # If object is a dict instance, no need to convert.\n    return (obj if isinstance(obj, dict)\n            else {attr: getattr(obj, attr)\n                  for attr in dir(obj) if not attr.startswith('_')})", "title": ""}
{"_id": "d13459", "text": "def top_class(self):\n        \"\"\"reference to a parent class, which contains this class and defined\n        within a namespace\n\n        if this class is defined under a namespace, self will be returned\"\"\"\n        curr = self\n        parent = self.parent\n        while isinstance(parent, class_t):\n            curr = parent\n            parent = parent.parent\n        return curr", "title": ""}
{"_id": "d13460", "text": "def go_to_parent_directory(self):\n        \"\"\"Go to parent directory\"\"\"\n        self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))", "title": ""}
{"_id": "d13461", "text": "def find_root(self):\n        \"\"\" Traverse parent refs to top. \"\"\"\n        cmd = self\n        while cmd.parent:\n            cmd = cmd.parent\n        return cmd", "title": ""}
{"_id": "d13462", "text": "def bytes_to_c_array(data):\n    \"\"\"\n    Make a C array using the given string.\n    \"\"\"\n    chars = [\n        \"'{}'\".format(encode_escape(i))\n        for i in decode_escape(data)\n    ]\n    return ', '.join(chars) + ', 0'", "title": ""}
{"_id": "d13463", "text": "def filter_query(s):\n    \"\"\"\n    Filters given query with the below regex\n    and returns lists of quoted and unquoted strings\n    \"\"\"\n    matches = re.findall(r'(?:\"([^\"]*)\")|([^\"]*)', s)\n    result_quoted = [t[0].strip() for t in matches if t[0]]\n    result_unquoted = [t[1].strip() for t in matches if t[1]]\n    return result_quoted, result_unquoted", "title": ""}
{"_id": "d13464", "text": "def _get_str_columns(sf):\n    \"\"\"\n    Returns a list of names of columns that are string type.\n    \"\"\"\n    return [name for name in sf.column_names() if sf[name].dtype == str]", "title": ""}
{"_id": "d13465", "text": "def load_results(result_files, options, run_set_id=None, columns=None,\n                 columns_relevant_for_diff=set()):\n    \"\"\"Version of load_result for multiple input files that will be loaded concurrently.\"\"\"\n    return parallel.map(\n        load_result,\n        result_files,\n        itertools.repeat(options),\n        itertools.repeat(run_set_id),\n        itertools.repeat(columns),\n        itertools.repeat(columns_relevant_for_diff))", "title": ""}
{"_id": "d13466", "text": "def screen_to_client(self, x, y):\n        \"\"\"\n        Translates window screen coordinates to client coordinates.\n\n        @note: This is a simplified interface to some of the functionality of\n            the L{win32.Point} class.\n\n        @see: {win32.Point.screen_to_client}\n\n        @type  x: int\n        @param x: Horizontal coordinate.\n        @type  y: int\n        @param y: Vertical coordinate.\n\n        @rtype:  tuple( int, int )\n        @return: Translated coordinates in a tuple (x, y).\n\n        @raise WindowsError: An error occured while processing this request.\n        \"\"\"\n        return tuple( win32.ScreenToClient( self.get_handle(), (x, y) ) )", "title": ""}
{"_id": "d13467", "text": "def __next__(self, reward, ask_id, lbl):\n        \"\"\"For Python3 compatibility of generator.\"\"\"\n        return self.next(reward, ask_id, lbl)", "title": ""}
{"_id": "d13468", "text": "def get_month_start_end_day():\n    \"\"\"\n    Get the month start date a nd end date\n    \"\"\"\n    t = date.today()\n    n = mdays[t.month]\n    return (date(t.year, t.month, 1), date(t.year, t.month, n))", "title": ""}
{"_id": "d13469", "text": "def cfloat64_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\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')", "title": ""}
{"_id": "d13470", "text": "def min_depth(self, root):\n    \"\"\"\n    :type root: TreeNode\n    :rtype: int\n    \"\"\"\n    if root is None:\n        return 0\n    if root.left is not None or root.right is not None:\n        return max(self.minDepth(root.left), self.minDepth(root.right))+1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1", "title": ""}
{"_id": "d13471", "text": "def expand_path(path):\n  \"\"\"Returns ``path`` as an absolute path with ~user and env var expansion applied.\n\n  :API: public\n  \"\"\"\n  return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))", "title": ""}
{"_id": "d13472", "text": "def _get_gid(name):\n    \"\"\"Returns a gid, given a group name.\"\"\"\n    if getgrnam is None or name is None:\n        return None\n    try:\n        result = getgrnam(name)\n    except KeyError:\n        result = None\n    if result is not None:\n        return result[2]\n    return None", "title": ""}
{"_id": "d13473", "text": "def get_files(dir_name):\n    \"\"\"Simple directory walker\"\"\"\n    return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]", "title": ""}
{"_id": "d13474", "text": "def help_for_command(command):\n    \"\"\"Get the help text (signature + docstring) for a command (function).\"\"\"\n    help_text = pydoc.text.document(command)\n    # remove backspaces\n    return re.subn('.\\\\x08', '', help_text)[0]", "title": ""}
{"_id": "d13475", "text": "def parent(self, index):\n        \"\"\"Return the index of the parent for a given index of the\n        child. Unfortunately, the name of the method has to be parent,\n        even though a more verbose name like parentIndex, would avoid\n        confusion about what parent actually is - an index or an item.\n        \"\"\"\n        childItem = self.item(index)\n        parentItem = childItem.parent\n\n        if parentItem == self.rootItem:\n            parentIndex = QModelIndex()\n        else:\n            parentIndex = self.createIndex(parentItem.row(), 0, parentItem)\n\n        return parentIndex", "title": ""}
{"_id": "d13476", "text": "def filter_regex(names, regex):\n    \"\"\"\n    Return a tuple of strings that match the regular expression pattern.\n    \"\"\"\n    return tuple(name for name in names\n                 if regex.search(name) is not None)", "title": ""}
{"_id": "d13477", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d13478", "text": "def standardize(table, with_std=True):\n    \"\"\"\n    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.\n    \"\"\"\n    if isinstance(table, pandas.DataFrame):\n        cat_columns = table.select_dtypes(include=['category']).columns\n    else:\n        cat_columns = []\n\n    new_frame = _apply_along_column(table, standardize_column, with_std=with_std)\n\n    # work around for apply converting category dtype to object\n    # https://github.com/pydata/pandas/issues/9573\n    for col in cat_columns:\n        new_frame[col] = table[col].copy()\n\n    return new_frame", "title": ""}
{"_id": "d13479", "text": "def index(m, val):\n    \"\"\"\n    Return the indices of all the ``val`` in ``m``\n    \"\"\"\n    mm = np.array(m)\n    idx_tuple = np.where(mm == val)\n    idx = idx_tuple[0].tolist()\n\n    return idx", "title": ""}
{"_id": "d13480", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d13481", "text": "def validate_multiindex(self, obj):\n        \"\"\"validate that we can store the multi-index; reset and return the\n        new object\n        \"\"\"\n        levels = [l if l is not None else \"level_{0}\".format(i)\n                  for i, l in enumerate(obj.index.names)]\n        try:\n            return obj.reset_index(), levels\n        except ValueError:\n            raise ValueError(\"duplicate names/columns in the multi-index when \"\n                             \"storing as a table\")", "title": ""}
{"_id": "d13482", "text": "def PythonPercentFormat(format_str):\n  \"\"\"Use Python % format strings as template format specifiers.\"\"\"\n\n  if format_str.startswith('printf '):\n    fmt = format_str[len('printf '):]\n    return lambda value: fmt % value\n  else:\n    return None", "title": ""}
{"_id": "d13483", "text": "def _last_index(x, default_dim):\n  \"\"\"Returns the last dimension's index or default_dim if x has no shape.\"\"\"\n  if x.get_shape().ndims is not None:\n    return len(x.get_shape()) - 1\n  else:\n    return default_dim", "title": ""}
{"_id": "d13484", "text": "def unpickle_file(picklefile, **kwargs):\n    \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)", "title": ""}
{"_id": "d13485", "text": "def do_history(self, line):\n        \"\"\"history Display a list of commands that have been entered.\"\"\"\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))", "title": ""}
{"_id": "d13486", "text": "def unpickle_stats(stats):\n    \"\"\"Unpickle a pstats.Stats object\"\"\"\n    stats = cPickle.loads(stats)\n    stats.stream = True\n    return stats", "title": ""}
{"_id": "d13487", "text": "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location", "title": ""}
{"_id": "d13488", "text": "def a2s(a):\n    \"\"\"\n     convert 3,3 a matrix to 6 element \"s\" list  (see Tauxe 1998)\n    \"\"\"\n    s = np.zeros((6,), 'f')  # make the a matrix\n    for i in range(3):\n        s[i] = a[i][i]\n    s[3] = a[0][1]\n    s[4] = a[1][2]\n    s[5] = a[0][2]\n    return s", "title": ""}
{"_id": "d13489", "text": "def show(data, negate=False):\n    \"\"\"Show the stretched data.\n    \"\"\"\n    from PIL import Image as pil\n    data = np.array((data - data.min()) * 255.0 /\n                    (data.max() - data.min()), np.uint8)\n    if negate:\n        data = 255 - data\n    img = pil.fromarray(data)\n    img.show()", "title": ""}
{"_id": "d13490", "text": "def best(self):\n        \"\"\"\n        Returns the element with the highest probability.\n        \"\"\"\n        b = (-1e999999, None)\n        for k, c in iteritems(self.counts):\n            b = max(b, (c, k))\n        return b[1]", "title": ""}
{"_id": "d13491", "text": "def set_ylimits(self, row, column, min=None, max=None):\n        \"\"\"Set y-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_ylimits(min, max)", "title": ""}
{"_id": "d13492", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d13493", "text": "def _encode_gif(images, fps):\n  \"\"\"Encodes numpy images into gif string.\n\n  Args:\n    images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape\n      `[time, height, width, channels]` where `channels` is 1 or 3.\n    fps: frames per second of the animation\n\n  Returns:\n    The encoded gif string.\n\n  Raises:\n    IOError: If the ffmpeg command returns an error.\n  \"\"\"\n  writer = WholeVideoWriter(fps)\n  writer.write_multi(images)\n  return writer.finish()", "title": ""}
{"_id": "d13494", "text": "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location", "title": ""}
{"_id": "d13495", "text": "def eval_script(self, expr):\n    \"\"\" Evaluates a piece of Javascript in the context of the current page and\n    returns its value. \"\"\"\n    ret = self.conn.issue_command(\"Evaluate\", expr)\n    return json.loads(\"[%s]\" % ret)[0]", "title": ""}
{"_id": "d13496", "text": "def asyncStarCmap(asyncCallable, iterable):\n    \"\"\"itertools.starmap for deferred callables using cooperative multitasking\n    \"\"\"\n    results = []\n    yield coopStar(asyncCallable, results.append, iterable)\n    returnValue(results)", "title": ""}
{"_id": "d13497", "text": "def header_length(bytearray):\n    \"\"\"Return the length of s when it is encoded with base64.\"\"\"\n    groups_of_3, leftover = divmod(len(bytearray), 3)\n    # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.\n    n = groups_of_3 * 4\n    if leftover:\n        n += 4\n    return n", "title": ""}
{"_id": "d13498", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d13499", "text": "def debug_on_error(type, value, tb):\n    \"\"\"Code due to Thomas Heller - published in Python Cookbook (O'Reilley)\"\"\"\n    traceback.print_exc(type, value, tb)\n    print()\n    pdb.pm()", "title": ""}
{"_id": "d13500", "text": "def _render_table(data, fields=None):\n  \"\"\" Helper to render a list of dictionaries as an HTML display object. \"\"\"\n  return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))", "title": ""}
{"_id": "d13501", "text": "def get_example_features(example):\n  \"\"\"Returns the non-sequence features from the provided example.\"\"\"\n  return (example.features.feature if isinstance(example, tf.train.Example)\n          else example.context.feature)", "title": ""}
{"_id": "d13502", "text": "def pp_xml(body):\n    \"\"\"Pretty print format some XML so it's readable.\"\"\"\n    pretty = xml.dom.minidom.parseString(body)\n    return pretty.toprettyxml(indent=\"  \")", "title": ""}
{"_id": "d13503", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d13504", "text": "def format_prettytable(table):\n    \"\"\"Converts SoftLayer.CLI.formatting.Table instance to a prettytable.\"\"\"\n    for i, row in enumerate(table.rows):\n        for j, item in enumerate(row):\n            table.rows[i][j] = format_output(item)\n\n    ptable = table.prettytable()\n    ptable.hrules = prettytable.FRAME\n    ptable.horizontal_char = '.'\n    ptable.vertical_char = ':'\n    ptable.junction_char = ':'\n    return ptable", "title": ""}
{"_id": "d13505", "text": "def _get_str_columns(sf):\n    \"\"\"\n    Returns a list of names of columns that are string type.\n    \"\"\"\n    return [name for name in sf.column_names() if sf[name].dtype == str]", "title": ""}
{"_id": "d13506", "text": "def print_item_with_children(ac, classes, level):\n    \"\"\" Print the given item and all children items \"\"\"\n    print_row(ac.id, ac.name, f\"{ac.allocation:,.2f}\", level)\n    print_children_recursively(classes, ac, level + 1)", "title": ""}
{"_id": "d13507", "text": "def datatype(dbtype, description, cursor):\n    \"\"\"Google AppEngine Helper to convert a data type into a string.\"\"\"\n    dt = cursor.db.introspection.get_field_type(dbtype, description)\n    if type(dt) is tuple:\n        return dt[0]\n    else:\n        return dt", "title": ""}
{"_id": "d13508", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d13509", "text": "def get_tail(self):\n        \"\"\"Gets tail\n\n        :return: Tail of linked list\n        \"\"\"\n        node = self.head\n        last_node = self.head\n\n        while node is not None:\n            last_node = node\n            node = node.next_node\n\n        return last_node", "title": ""}
{"_id": "d13510", "text": "def pformat(object, indent=1, width=80, depth=None):\n    \"\"\"Format a Python object into a pretty-printed representation.\"\"\"\n    return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)", "title": ""}
{"_id": "d13511", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d13512", "text": "def pformat(object, indent=1, width=80, depth=None):\n    \"\"\"Format a Python object into a pretty-printed representation.\"\"\"\n    return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)", "title": ""}
{"_id": "d13513", "text": "def getpackagepath():\n    \"\"\"\n     *Get the root path for this python package - used in unit testing code*\n    \"\"\"\n    moduleDirectory = os.path.dirname(__file__)\n    packagePath = os.path.dirname(__file__) + \"/../\"\n\n    return packagePath", "title": ""}
{"_id": "d13514", "text": "def print_out(self, *lst):\n      \"\"\" Print list of strings to the predefined stdout. \"\"\"\n      self.print2file(self.stdout, True, True, *lst)", "title": ""}
{"_id": "d13515", "text": "def get_system_root_directory():\n    \"\"\"\n    Get system root directory (application installed root directory)\n\n    Returns\n    -------\n    string\n        A full path\n\n    \"\"\"\n    root = os.path.dirname(__file__)\n    root = os.path.dirname(root)\n    root = os.path.abspath(root)\n    return root", "title": ""}
{"_id": "d13516", "text": "def stdoutwriteline(*args):\n    \"\"\"\n    @type args: tuple\n    @return: None\n    \"\"\"\n    s = \"\"\n\n    for i in args:\n        s += str(i) + \" \"\n\n    s = s.strip()\n    sys.stdout.write(str(s) + \"\\n\")\n    sys.stdout.flush()\n\n    return s", "title": ""}
{"_id": "d13517", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x.\"\"\"\n    i = bs.bisect_left(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d13518", "text": "def format_exc(limit=None):\n    \"\"\"Like print_exc() but return a string. Backport for Python 2.3.\"\"\"\n    try:\n        etype, value, tb = sys.exc_info()\n        return ''.join(traceback.format_exception(etype, value, tb, limit))\n    finally:\n        etype = value = tb = None", "title": ""}
{"_id": "d13519", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d13520", "text": "def ss(*args, **kwargs):\n    \"\"\"\n    exactly like s, but doesn't return variable names or file positions (useful for logging)\n\n    since -- 10-15-2015\n    return -- str\n    \"\"\"\n    if not args:\n        raise ValueError(\"you didn't pass any arguments to print out\")\n\n    with Reflect.context(args, **kwargs) as r:\n        instance = V_CLASS(r, stream, **kwargs)\n        return instance.value().strip()", "title": ""}
{"_id": "d13521", "text": "def get_width():\n    \"\"\"Get terminal width\"\"\"\n    # Get terminal size\n    ws = struct.pack(\"HHHH\", 0, 0, 0, 0)\n    ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)\n    lines, columns, x, y = struct.unpack(\"HHHH\", ws)\n    width = min(columns * 39 // 40, columns - 2)\n    return width", "title": ""}
{"_id": "d13522", "text": "def set_stop_handler(self):\n        \"\"\"\n        Initializes functions that are invoked when the user or OS wants to kill this process.\n        :return:\n        \"\"\"\n        signal.signal(signal.SIGTERM, self.graceful_stop)\n        signal.signal(signal.SIGABRT, self.graceful_stop)\n        signal.signal(signal.SIGINT, self.graceful_stop)", "title": ""}
{"_id": "d13523", "text": "def get_python():\n    \"\"\"Determine the path to the virtualenv 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", "title": ""}
{"_id": "d13524", "text": "def tick(self):\n        \"\"\"Add one tick to progress bar\"\"\"\n        self.current += 1\n        if self.current == self.factor:\n            sys.stdout.write('+')\n            sys.stdout.flush()\n            self.current = 0", "title": ""}
{"_id": "d13525", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d13526", "text": "def prompt(*args, **kwargs):\n    \"\"\"Prompt the user for input and handle any abort exceptions.\"\"\"\n    try:\n        return click.prompt(*args, **kwargs)\n    except click.Abort:\n        return False", "title": ""}
{"_id": "d13527", "text": "def value_for_key(membersuite_object_data, key):\n    \"\"\"Return the value for `key` of membersuite_object_data.\n    \"\"\"\n    key_value_dicts = {\n        d['Key']: d['Value'] for d\n        in membersuite_object_data[\"Fields\"][\"KeyValueOfstringanyType\"]}\n    return key_value_dicts[key]", "title": ""}
{"_id": "d13528", "text": "def _set_property(self, val, *args):\n        \"\"\"Private method that sets the value currently of the property\"\"\"\n        val = UserClassAdapter._set_property(self, val, *args)\n        if val:\n            Adapter._set_property(self, val, *args)\n        return val", "title": ""}
{"_id": "d13529", "text": "def _baseattrs(self):\n        \"\"\"A dict of members expressed in literals\"\"\"\n\n        result = super()._baseattrs\n        result[\"params\"] = \", \".join(self.parameters)\n        return result", "title": ""}
{"_id": "d13530", "text": "def items(self):\n    \"\"\"Return a list of the (name, value) pairs of the enum.\n\n    These are returned in the order they were defined in the .proto file.\n    \"\"\"\n    return [(value_descriptor.name, value_descriptor.number)\n            for value_descriptor in self._enum_type.values]", "title": ""}
{"_id": "d13531", "text": "def has_edit_permission(self, request):\n        \"\"\" Can edit this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "title": ""}
{"_id": "d13532", "text": "def items(self):\n    \"\"\"Return a list of the (name, value) pairs of the enum.\n\n    These are returned in the order they were defined in the .proto file.\n    \"\"\"\n    return [(value_descriptor.name, value_descriptor.number)\n            for value_descriptor in self._enum_type.values]", "title": ""}
{"_id": "d13533", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d13534", "text": "def set(self, f):\n        \"\"\"Call a function after a delay, unless another function is set\n        in the meantime.\"\"\"\n        self.stop()\n        self._create_timer(f)\n        self.start()", "title": ""}
{"_id": "d13535", "text": "def _parse_ranges(ranges):\n    \"\"\" Converts a list of string ranges to a list of [low, high] tuples. \"\"\"\n    for txt in ranges:\n        if '-' in txt:\n            low, high = txt.split('-')\n        else:\n            low, high = txt, txt\n        yield int(low), int(high)", "title": ""}
{"_id": "d13536", "text": "def run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv. Return result code.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tresult_code = __import__('pytest').main()\n\t\t\tif result_code:\n\t\t\t\traise SystemExit(result_code)", "title": ""}
{"_id": "d13537", "text": "def plot_pauli_transfer_matrix(self, ax):\n        \"\"\"\n        Plot the elements of the Pauli transfer matrix.\n\n        :param matplotlib.Axes ax: A matplotlib Axes object to plot into.\n        \"\"\"\n        title = \"Estimated process\"\n        ut.plot_pauli_transfer_matrix(self.r_est, ax, self.pauli_basis.labels, title)", "title": ""}
{"_id": "d13538", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d13539", "text": "def get_closest_index(myList, myNumber):\n    \"\"\"\n    Assumes myList is sorted. Returns closest value to myNumber.\n    If two numbers are equally close, return the smallest number.\n\n    Parameters\n    ----------\n    myList : array\n        The list in which to find the closest value to myNumber\n    myNumber : float\n        The number to find the closest to in MyList\n\n    Returns\n    -------\n    closest_values_index : int\n        The index in the array of the number closest to myNumber in myList\n    \"\"\"\n    closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n    return closest_values_index", "title": ""}
{"_id": "d13540", "text": "def PopTask(self):\n    \"\"\"Retrieves and removes the first task from the heap.\n\n    Returns:\n      Task: the task or None if the heap is empty.\n    \"\"\"\n    try:\n      _, task = heapq.heappop(self._heap)\n\n    except IndexError:\n      return None\n    self._task_identifiers.remove(task.identifier)\n    return task", "title": ""}
{"_id": "d13541", "text": "def impute_data(self,x):\n        \"\"\"Imputes data set containing Nan values\"\"\"\n        imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n        return imp.fit_transform(x)", "title": ""}
{"_id": "d13542", "text": "def display_pil_image(im):\n   \"\"\"Displayhook function for PIL Images, rendered as PNG.\"\"\"\n   from IPython.core import display\n   b = BytesIO()\n   im.save(b, format='png')\n   data = b.getvalue()\n\n   ip_img = display.Image(data=data, format='png', embed=True)\n   return ip_img._repr_png_()", "title": ""}
{"_id": "d13543", "text": "def impute_data(self,x):\n        \"\"\"Imputes data set containing Nan values\"\"\"\n        imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n        return imp.fit_transform(x)", "title": ""}
{"_id": "d13544", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d13545", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d13546", "text": "def LinSpace(start, stop, num):\n    \"\"\"\n    Linspace op.\n    \"\"\"\n    return np.linspace(start, stop, num=num, dtype=np.float32),", "title": ""}
{"_id": "d13547", "text": "def adjust_bounding_box(bbox):\n    \"\"\"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.\n    \"\"\"\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", "title": ""}
{"_id": "d13548", "text": "def LinSpace(start, stop, num):\n    \"\"\"\n    Linspace op.\n    \"\"\"\n    return np.linspace(start, stop, num=num, dtype=np.float32),", "title": ""}
{"_id": "d13549", "text": "def _digits(minval, maxval):\n    \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n    if minval == maxval:\n        return 3\n    else:\n        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "title": ""}
{"_id": "d13550", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d13551", "text": "def lambda_tuple_converter(func):\n    \"\"\"\n    Converts a Python 2 function as\n      lambda (x,y): x + y\n    In the Python 3 format:\n      lambda x,y : x + y\n    \"\"\"\n    if func is not None and func.__code__.co_argcount == 1:\n        return lambda *args: func(args[0] if len(args) == 1 else args)\n    else:\n        return func", "title": ""}
{"_id": "d13552", "text": "def replace(self, text):\n        \"\"\"Do j/v replacement\"\"\"\n        for (pattern, repl) in self.patterns:\n            text = re.subn(pattern, repl, text)[0]\n        return text", "title": ""}
{"_id": "d13553", "text": "def utcfromtimestamp(cls, timestamp):\n    \"\"\"Returns a datetime object of a given timestamp (in UTC).\"\"\"\n    obj = datetime.datetime.utcfromtimestamp(timestamp)\n    obj = pytz.utc.localize(obj)\n    return cls(obj)", "title": ""}
{"_id": "d13554", "text": "def getlines(filename, module_globals=None):\n    \"\"\"Get the lines for a file from the cache.\n    Update the cache if it doesn't contain an entry for this file already.\"\"\"\n\n    if filename in cache:\n        return cache[filename][2]\n\n    try:\n        return updatecache(filename, module_globals)\n    except MemoryError:\n        clearcache()\n        return []", "title": ""}
{"_id": "d13555", "text": "def new_from_list(cls, items, **kwargs):\n        \"\"\"Populates the ListView with a string list.\n\n        Args:\n            items (list): list of strings to fill the widget with.\n        \"\"\"\n        obj = cls(**kwargs)\n        for item in items:\n            obj.append(ListItem(item))\n        return obj", "title": ""}
{"_id": "d13556", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d13557", "text": "def __iter__(self):\n\t\t\"\"\"Iterate through all elements.\n\n\t\tMultiple copies will be returned if they exist.\n\t\t\"\"\"\n\t\tfor value, count in self.counts():\n\t\t\tfor _ in range(count):\n\t\t\t\tyield value", "title": ""}
{"_id": "d13558", "text": "def smartread(path):\n    \"\"\"Read text from file, automatically detect encoding. ``chardet`` required.\n    \"\"\"\n    with open(path, \"rb\") as f:\n        content = f.read()\n        result = chardet.detect(content)\n        return content.decode(result[\"encoding\"])", "title": ""}
{"_id": "d13559", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d13560", "text": "def _read_preference_for(self, session):\n        \"\"\"Read only access to the read preference of this instance or session.\n        \"\"\"\n        # Override this operation's read preference with the transaction's.\n        if session:\n            return session._txn_read_preference() or self.__read_preference\n        return self.__read_preference", "title": ""}
{"_id": "d13561", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d13562", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d13563", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d13564", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d13565", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d13566", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d13567", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d13568", "text": "def ReadManyFromPath(filepath):\n  \"\"\"Reads a Python object stored in a specified YAML file.\n\n  Args:\n    filepath: A filepath to the YAML file.\n\n  Returns:\n    A Python data structure corresponding to the YAML in the given file.\n  \"\"\"\n  with io.open(filepath, mode=\"r\", encoding=\"utf-8\") as filedesc:\n    return ReadManyFromFile(filedesc)", "title": ""}
{"_id": "d13569", "text": "def mouse_get_pos():\n    \"\"\"\n\n    :return:\n    \"\"\"\n    p = POINT()\n    AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))\n    return p.x, p.y", "title": ""}
{"_id": "d13570", "text": "def memory_usage(method):\n  \"\"\"Log memory usage before and after a method.\"\"\"\n  def wrapper(*args, **kwargs):\n    logging.info('Memory before method %s is %s.',\n                 method.__name__, runtime.memory_usage().current())\n    result = method(*args, **kwargs)\n    logging.info('Memory after method %s is %s',\n                 method.__name__, runtime.memory_usage().current())\n    return result\n  return wrapper", "title": ""}
{"_id": "d13571", "text": "def getpackagepath():\n    \"\"\"\n     *Get the root path for this python package - used in unit testing code*\n    \"\"\"\n    moduleDirectory = os.path.dirname(__file__)\n    packagePath = os.path.dirname(__file__) + \"/../\"\n\n    return packagePath", "title": ""}
{"_id": "d13572", "text": "def tuplize(nested):\n  \"\"\"Recursively converts iterables into tuples.\n\n  Args:\n    nested: A nested structure of items and iterables.\n\n  Returns:\n    A nested structure of items and tuples.\n  \"\"\"\n  if isinstance(nested, str):\n    return nested\n  try:\n    return tuple(map(tuplize, nested))\n  except TypeError:\n    return nested", "title": ""}
{"_id": "d13573", "text": "def _get_column_types(self, data):\n        \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n        columns = list(zip_longest(*data))\n        return [self._get_column_type(column) for column in columns]", "title": ""}
{"_id": "d13574", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d13575", "text": "def get(self, key):  \n        \"\"\" get a set of keys from redis \"\"\"\n        res = self.connection.get(key)\n        print(res)\n        return res", "title": ""}
{"_id": "d13576", "text": "def _crop_list_to_size(l, size):\n    \"\"\"Make a list a certain size\"\"\"\n    for x in range(size - len(l)):\n        l.append(False)\n    for x in range(len(l) - size):\n        l.pop()\n    return l", "title": ""}
{"_id": "d13577", "text": "def connect(self):\n        \"\"\"\n        Connects to publisher\n        \"\"\"\n        self.client = redis.Redis(\n            host=self.host, port=self.port, password=self.password)", "title": ""}
{"_id": "d13578", "text": "def read_raw(data_path):\n    \"\"\"\n    Parameters\n    ----------\n    data_path : str\n    \"\"\"\n    with open(data_path, 'rb') as f:\n        data = pickle.load(f)\n    return data", "title": ""}
{"_id": "d13579", "text": "def lpush(self, key, *args):\n        \"\"\"Emulate lpush.\"\"\"\n        redis_list = self._get_list(key, 'LPUSH', create=True)\n\n        # Creates the list at this key if it doesn't exist, and appends args to its beginning\n        args_reversed = [self._encode(arg) for arg in args]\n        args_reversed.reverse()\n        updated_list = args_reversed + redis_list\n        self.redis[self._encode(key)] = updated_list\n\n        # Return the length of the list after the push operation\n        return len(updated_list)", "title": ""}
{"_id": "d13580", "text": "def _read_group_h5(filename, groupname):\n    \"\"\"Return group content.\n\n    Args:\n        filename (:class:`pathlib.Path`): path of hdf5 file.\n        groupname (str): name of group to read.\n    Returns:\n        :class:`numpy.array`: content of group.\n    \"\"\"\n    with h5py.File(filename, 'r') as h5f:\n        data = h5f[groupname][()]\n    return data", "title": ""}
{"_id": "d13581", "text": "def match_files(files, pattern: Pattern):\n    \"\"\"Yields file name if matches a regular expression pattern.\"\"\"\n\n    for name in files:\n        if re.match(pattern, name):\n            yield name", "title": ""}
{"_id": "d13582", "text": "def _load_ngram(name):\n    \"\"\"Dynamically import the python module with the ngram defined as a dictionary.\n    Since bigger ngrams are large files its wasteful to always statically import them if they're not used.\n    \"\"\"\n    module = importlib.import_module('lantern.analysis.english_ngrams.{}'.format(name))\n    return getattr(module, name)", "title": ""}
{"_id": "d13583", "text": "def CleanseComments(line):\n  \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n  Args:\n    line: A line of C++ source.\n\n  Returns:\n    The line with single-line comments removed.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1 and not IsCppString(line[:commentpos]):\n    line = line[:commentpos].rstrip()\n  # get rid of /* ... */\n  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "title": ""}
{"_id": "d13584", "text": "def load(self, path):\n        \"\"\"Load the pickled model weights.\"\"\"\n        with io.open(path, 'rb') as fin:\n            self.weights = pickle.load(fin)", "title": ""}
{"_id": "d13585", "text": "def find_number(regex, s):\n    \"\"\"Find a number using a given regular expression.\n    If the string cannot be found, returns None.\n    The regex should contain one matching group, \n    as only the result of the first group is returned.\n    The group should only contain numeric characters ([0-9]+).\n    \n    s - The string to search.\n    regex - A string containing the regular expression.\n    \n    Returns an integer or None.\n    \"\"\"\n    result = find_string(regex, s)\n    if result is None:\n        return None\n    return int(result)", "title": ""}
{"_id": "d13586", "text": "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location", "title": ""}
{"_id": "d13587", "text": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "title": ""}
{"_id": "d13588", "text": "def split_strings_in_list_retain_spaces(orig_list):\n    \"\"\"\n    Function to split every line in a list, and retain spaces for a rejoin\n    :param orig_list: Original list\n    :return:\n        A List with split lines\n\n    \"\"\"\n    temp_list = list()\n    for line in orig_list:\n        line_split = __re.split(r'(\\s+)', line)\n        temp_list.append(line_split)\n\n    return temp_list", "title": ""}
{"_id": "d13589", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d13590", "text": "def detach_index(self, name):\n        \"\"\"\n\n        :param name:\n        :return:\n        \"\"\"\n        assert type(name) == str\n\n        if name in self._indexes:\n            del self._indexes[name]", "title": ""}
{"_id": "d13591", "text": "def price_rounding(price, decimals=2):\n    \"\"\"Takes a decimal price and rounds to a number of decimal places\"\"\"\n    try:\n        exponent = D('.' + decimals * '0')\n    except InvalidOperation:\n        # Currencies with no decimal places, ex. JPY, HUF\n        exponent = D()\n    return price.quantize(exponent, rounding=ROUND_UP)", "title": ""}
{"_id": "d13592", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d13593", "text": "def gaussian_kernel(gstd):\n    \"\"\"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\n    \"\"\"\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\n    return g", "title": ""}
{"_id": "d13594", "text": "def plot_dot_graph(graph, filename=None):\n    \"\"\"\n    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\n    \"\"\"\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\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()", "title": ""}
{"_id": "d13595", "text": "def unique(list):\n    \"\"\" Returns a copy of the list without duplicates.\n    \"\"\"\n    unique = []; [unique.append(x) for x in list if x not in unique]\n    return unique", "title": ""}
{"_id": "d13596", "text": "def is_a_sequence(var, allow_none=False):\n    \"\"\" Returns True if var is a list or a tuple (but not a string!)\n    \"\"\"\n    return isinstance(var, (list, tuple)) or (var is None and allow_none)", "title": ""}
{"_id": "d13597", "text": "def strip_html(string, keep_tag_content=False):\n    \"\"\"\n    Remove html code contained into the given string.\n\n    :param string: String to manipulate.\n    :type string: str\n    :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).\n    :type keep_tag_content: bool\n    :return: String with html removed.\n    :rtype: str\n    \"\"\"\n    r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE\n    return r.sub('', string)", "title": ""}
{"_id": "d13598", "text": "def get_plugin_icon(self):\n        \"\"\"Return widget icon\"\"\"\n        path = osp.join(self.PLUGIN_PATH, self.IMG_PATH)\n        return ima.icon('pylint', icon_path=path)", "title": ""}
{"_id": "d13599", "text": "def remove_last_entry(self):\n        \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n        self.current_beat -= 1.0 / self.bar[-1][1]\n        self.bar = self.bar[:-1]\n        return self.current_beat", "title": ""}
{"_id": "d13600", "text": "def generate_header(headerfields, oldheader, group_by_field):\n    \"\"\"Returns a header as a list, ready to write to TSV file\"\"\"\n    fieldtypes = ['peptidefdr', 'peptidepep', 'nopsms', 'proteindata',\n                  'precursorquant', 'isoquant']\n    return generate_general_header(headerfields, fieldtypes,\n                                   peptabledata.HEADER_PEPTIDE, oldheader,\n                                   group_by_field)", "title": ""}
{"_id": "d13601", "text": "def remove_last_entry(self):\n        \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n        self.current_beat -= 1.0 / self.bar[-1][1]\n        self.bar = self.bar[:-1]\n        return self.current_beat", "title": ""}
{"_id": "d13602", "text": "def str2int(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n    return NumConv(radix, alphabet).str2int(num)", "title": ""}
{"_id": "d13603", "text": "def slugify(string):\n    \"\"\"\n    Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n    \"\"\"\n    string = re.sub('[^\\w .-]', '', string)\n    string = string.replace(\" \", \"-\")\n    return string", "title": ""}
{"_id": "d13604", "text": "def is_int(value):\n    \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n    if isinstance(value, bool):\n        return False\n    try:\n        int(value)\n        return True\n    except (ValueError, TypeError):\n        return False", "title": ""}
{"_id": "d13605", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d13606", "text": "def _npiter(arr):\n    \"\"\"Wrapper for iterating numpy array\"\"\"\n    for a in np.nditer(arr, flags=[\"refs_ok\"]):\n        c = a.item()\n        if c is not None:\n            yield c", "title": ""}
{"_id": "d13607", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d13608", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d13609", "text": "def drop_bad_characters(text):\n    \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n    also any whitespace characters that aren't space.\n\n    :arg str text: the text to fix\n\n    :returns: text with all bad characters dropped\n\n    \"\"\"\n    # Strip all non-ascii and non-printable characters\n    text = ''.join([c for c in text if c in ALLOWED_CHARS])\n    return text", "title": ""}
{"_id": "d13610", "text": "def to_linspace(self):\n        \"\"\"\n        convert from arange to linspace\n        \"\"\"\n        num = int((self.stop-self.start)/(self.step))\n        return Linspace(self.start, self.stop-self.step, num)", "title": ""}
{"_id": "d13611", "text": "def flatten(lis):\n    \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n    new_lis = []\n    for item in lis:\n        if isinstance(item, collections.Sequence) and not isinstance(item, basestring):\n            new_lis.extend(flatten(item))\n        else:\n            new_lis.append(item)\n    return new_lis", "title": ""}
{"_id": "d13612", "text": "def trim_trailing_silence(self):\n        \"\"\"Trim the trailing silence of the pianoroll.\"\"\"\n        length = self.get_active_length()\n        self.pianoroll = self.pianoroll[:length]", "title": ""}
{"_id": "d13613", "text": "def negate(self):\n        \"\"\"Reverse the range\"\"\"\n        self.from_value, self.to_value = self.to_value, self.from_value\n        self.include_lower, self.include_upper = self.include_upper, self.include_lower", "title": ""}
{"_id": "d13614", "text": "def remove_bad(string):\n    \"\"\"\n    remove problem characters from string\n    \"\"\"\n    remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n    for c in remove:\n        string = string.replace(c, '_')\n    return string", "title": ""}
{"_id": "d13615", "text": "def clean(some_string, uppercase=False):\n    \"\"\"\n    helper to clean up an input string\n    \"\"\"\n    if uppercase:\n        return some_string.strip().upper()\n    else:\n        return some_string.strip().lower()", "title": ""}
{"_id": "d13616", "text": "def urlize_twitter(text):\n    \"\"\"\n    Replace #hashtag and @username references in a tweet with HTML text.\n    \"\"\"\n    html = TwitterText(text).autolink.auto_link()\n    return mark_safe(html.replace(\n        'twitter.com/search?q=', 'twitter.com/search/realtime/'))", "title": ""}
{"_id": "d13617", "text": "def inpaint(self):\n        \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n        import inpaint\n        filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n        self.raster_data = np.ma.masked_invalid(filled)", "title": ""}
{"_id": "d13618", "text": "def cleanup(self):\n        \"\"\"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.\n\n        \"\"\"\n\n        for instance in self.context:\n            del(instance)\n\n        for plugin in self.plugins:\n            del(plugin)", "title": ""}
{"_id": "d13619", "text": "def match(string, patterns):\n    \"\"\"Given a string return true if it matches the supplied list of\n    patterns.\n\n    Parameters\n    ----------\n    string : str\n        The string to be matched.\n    patterns : None or [pattern, ...]\n        The series of regular expressions to attempt to match.\n    \"\"\"\n    if patterns is None:\n        return True\n    else:\n        return any(re.match(pattern, string)\n                   for pattern in patterns)", "title": ""}
{"_id": "d13620", "text": "def _remove_empty_items(d, required):\n  \"\"\"Return a new dict with any empty items removed.\n\n  Note that this is not a deep check. If d contains a dictionary which\n  itself contains empty items, those are never checked.\n\n  This method exists to make to_serializable() functions cleaner.\n  We could revisit this some day, but for now, the serialized objects are\n  stripped of empty values to keep the output YAML more compact.\n\n  Args:\n    d: a dictionary\n    required: list of required keys (for example, TaskDescriptors always emit\n      the \"task-id\", even if None)\n\n  Returns:\n    A dictionary with empty items removed.\n  \"\"\"\n\n  new_dict = {}\n  for k, v in d.items():\n    if k in required:\n      new_dict[k] = v\n    elif isinstance(v, int) or v:\n      # \"if v\" would suppress emitting int(0)\n      new_dict[k] = v\n\n  return new_dict", "title": ""}
{"_id": "d13621", "text": "def file_matches(filename, patterns):\n    \"\"\"Does this filename match any of the patterns?\"\"\"\n    return any(fnmatch.fnmatch(filename, pat) for pat in patterns)", "title": ""}
{"_id": "d13622", "text": "def replace_all(text, dic):\n    \"\"\"Takes a string and dictionary. replaces all occurrences of i with j\"\"\"\n\n    for i, j in dic.iteritems():\n        text = text.replace(i, j)\n    return text", "title": ""}
{"_id": "d13623", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d13624", "text": "def align_file_position(f, size):\n    \"\"\" Align the position in the file to the next block of specified size \"\"\"\n    align = (size - 1) - (f.tell() % size)\n    f.seek(align, 1)", "title": ""}
{"_id": "d13625", "text": "def set_property(self, key, value):\n        \"\"\"\n        Update only one property in the dict\n        \"\"\"\n        self.properties[key] = value\n        self.sync_properties()", "title": ""}
{"_id": "d13626", "text": "def __next__(self, reward, ask_id, lbl):\n        \"\"\"For Python3 compatibility of generator.\"\"\"\n        return self.next(reward, ask_id, lbl)", "title": ""}
{"_id": "d13627", "text": "def handle_whitespace(text):\n    r\"\"\"Handles whitespace cleanup.\n\n    Tabs are \"smartly\" retabbed (see sub_retab). Lines that contain\n    only whitespace are truncated to a single newline.\n    \"\"\"\n    text = re_retab.sub(sub_retab, text)\n    text = re_whitespace.sub('', text).strip()\n    return text", "title": ""}
{"_id": "d13628", "text": "def normalize_array(lst):\n    \"\"\"Normalizes list\n\n    :param lst: Array of floats\n    :return: Normalized (in [0, 1]) input array\n    \"\"\"\n    np_arr = np.array(lst)\n    x_normalized = np_arr / np_arr.max(axis=0)\n    return list(x_normalized)", "title": ""}
{"_id": "d13629", "text": "def list_replace(subject_list, replacement, string):\n    \"\"\"\n    To replace a list of items by a single replacement\n    :param subject_list: list\n    :param replacement: string\n    :param string: string\n    :return: string\n    \"\"\"\n    for s in subject_list:\n        string = string.replace(s, replacement)\n    return string", "title": ""}
{"_id": "d13630", "text": "def normalize(data):\n    \"\"\"Normalize the data to be in the [0, 1] range.\n\n    :param data:\n    :return: normalized data\n    \"\"\"\n    out_data = data.copy()\n\n    for i, sample in enumerate(out_data):\n        out_data[i] /= sum(out_data[i])\n\n    return out_data", "title": ""}
{"_id": "d13631", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d13632", "text": "def normalize_array(lst):\n    \"\"\"Normalizes list\n\n    :param lst: Array of floats\n    :return: Normalized (in [0, 1]) input array\n    \"\"\"\n    np_arr = np.array(lst)\n    x_normalized = np_arr / np_arr.max(axis=0)\n    return list(x_normalized)", "title": ""}
{"_id": "d13633", "text": "def restart_program():\n    \"\"\"\n    DOES NOT WORK WELL WITH MOPIDY\n    Hack from\n    https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program\n    to support updating the settings, since mopidy is not able to do that yet\n    Restarts the current program\n    Note: this function does not return. Any cleanup action (like\n    saving data) must be done before calling this function\n    \"\"\"\n\n    python = sys.executable\n    os.execl(python, python, * sys.argv)", "title": ""}
{"_id": "d13634", "text": "def first_unique_char(s):\n    \"\"\"\n    :type s: str\n    :rtype: int\n    \"\"\"\n    if (len(s) == 1):\n        return 0\n    ban = []\n    for i in range(len(s)):\n        if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:\n            return i\n        else:\n            ban.append(s[i])\n    return -1", "title": ""}
{"_id": "d13635", "text": "def http_request_json(*args, **kwargs):\n    \"\"\"\n\n    See: http_request\n    \"\"\"\n    ret, status = http_request(*args, **kwargs)\n    return json.loads(ret), status", "title": ""}
{"_id": "d13636", "text": "def one_hot_encoding(input_tensor, num_labels):\n    \"\"\" One-hot encode labels from input \"\"\"\n    xview = input_tensor.view(-1, 1).to(torch.long)\n\n    onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)\n    onehot.scatter_(1, xview, 1)\n    return onehot.view(list(input_tensor.shape) + [-1])", "title": ""}
{"_id": "d13637", "text": "def save_session_to_file(self, sessionfile):\n        \"\"\"Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.\"\"\"\n        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)", "title": ""}
{"_id": "d13638", "text": "def flat(l):\n    \"\"\"\nReturns the flattened version of a '2D' list.  List-correlate to the a.flat()\nmethod of NumPy arrays.\n\nUsage:    flat(l)\n\"\"\"\n    newl = []\n    for i in range(len(l)):\n        for j in range(len(l[i])):\n            newl.append(l[i][j])\n    return newl", "title": ""}
{"_id": "d13639", "text": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "title": ""}
{"_id": "d13640", "text": "def do_restart(self, line):\n        \"\"\"\n        Attempt to restart the bot.\n        \"\"\"\n        self.bot._frame = 0\n        self.bot._namespace.clear()\n        self.bot._namespace.update(self.bot._initial_namespace)", "title": ""}
{"_id": "d13641", "text": "def ReadTif(tifFile):\n        \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n        img = Image.open(tifFile)\n        img = np.array(img)\n        return img", "title": ""}
{"_id": "d13642", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d13643", "text": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "title": ""}
{"_id": "d13644", "text": "def get_previous(self):\n        \"\"\"Get the billing cycle prior to this one. May return None\"\"\"\n        return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()", "title": ""}
{"_id": "d13645", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d13646", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d13647", "text": "def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to be padded.\n\n        Returns:\n            PIL Image: Padded image.\n        \"\"\"\n        return F.pad(img, self.padding, self.fill, self.padding_mode)", "title": ""}
{"_id": "d13648", "text": "def INIT_LIST_EXPR(self, cursor):\n        \"\"\"Returns a list of literal values.\"\"\"\n        values = [self.parse_cursor(child)\n                  for child in list(cursor.get_children())]\n        return values", "title": ""}
{"_id": "d13649", "text": "def parse(filename):\n    \"\"\"Parse ASDL from the given file and return a Module node describing it.\"\"\"\n    with open(filename) as f:\n        parser = ASDLParser()\n        return parser.parse(f.read())", "title": ""}
{"_id": "d13650", "text": "def new_figure_manager_given_figure(num, figure):\n    \"\"\"\n    Create a new figure manager instance for the given figure.\n    \"\"\"\n    fig = figure\n    frame = FigureFrameWx(num, fig)\n    figmgr = frame.get_figure_manager()\n    if matplotlib.is_interactive():\n        figmgr.frame.Show()\n\n    return figmgr", "title": ""}
{"_id": "d13651", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d13652", "text": "def software_fibonacci(n):\n    \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n    a, b = 0, 1\n    for i in range(n):\n        a, b = b, a + b\n    return a", "title": ""}
{"_id": "d13653", "text": "def rand_elem(seq, n=None):\n    \"\"\"returns a random element from seq n times. If n is None, it continues indefinitly\"\"\"\n    return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))", "title": ""}
{"_id": "d13654", "text": "def finish_plot():\n    \"\"\"Helper for plotting.\"\"\"\n    plt.legend()\n    plt.grid(color='0.7')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.show()", "title": ""}
{"_id": "d13655", "text": "def rgba_bytes_tuple(self, x):\n        \"\"\"Provides the color corresponding to value `x` in the\n        form of a tuple (R,G,B,A) with int values between 0 and 255.\n        \"\"\"\n        return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))", "title": ""}
{"_id": "d13656", "text": "def rotateImage(img, angle):\n    \"\"\"\n\n    querries scipy.ndimage.rotate routine\n    :param img: image to be rotated\n    :param angle: angle to be rotated (radian)\n    :return: rotated image\n    \"\"\"\n    imgR = scipy.ndimage.rotate(img, angle, reshape=False)\n    return imgR", "title": ""}
{"_id": "d13657", "text": "def print_out(self, *lst):\n      \"\"\" Print list of strings to the predefined stdout. \"\"\"\n      self.print2file(self.stdout, True, True, *lst)", "title": ""}
{"_id": "d13658", "text": "def round_to_n(x, n):\n    \"\"\"\n    Round to sig figs\n    \"\"\"\n    return round(x, -int(np.floor(np.log10(x))) + (n - 1))", "title": ""}
{"_id": "d13659", "text": "def handle_exception(error):\n        \"\"\"Simple method for handling exceptions raised by `PyBankID`.\n\n        :param flask_pybankid.FlaskPyBankIDError error: The exception to handle.\n        :return: The exception represented as a dictionary.\n        :rtype: dict\n\n        \"\"\"\n        response = jsonify(error.to_dict())\n        response.status_code = error.status_code\n        return response", "title": ""}
{"_id": "d13660", "text": "def fail_print(error):\n    \"\"\"Print an error in red text.\n    Parameters\n        error (HTTPError)\n            Error object to print.\n    \"\"\"\n    print(COLORS.fail, error.message, COLORS.end)\n    print(COLORS.fail, error.errors, COLORS.end)", "title": ""}
{"_id": "d13661", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d13662", "text": "def _prt_line_detail(self, prt, line, lnum=\"\"):\n        \"\"\"Print each field and its value.\"\"\"\n        data = zip(self.flds, line.split('\\t'))\n        txt = [\"{:2}) {:13} {}\".format(i, hdr, val) for i, (hdr, val) in enumerate(data)]\n        prt.write(\"{LNUM}\\n{TXT}\\n\".format(LNUM=lnum, TXT='\\n'.join(txt)))", "title": ""}
{"_id": "d13663", "text": "def round_to_float(number, precision):\n    \"\"\"Round a float to a precision\"\"\"\n    rounded = Decimal(str(floor((number + precision / 2) // precision))\n                      ) * Decimal(str(precision))\n    return float(rounded)", "title": ""}
{"_id": "d13664", "text": "def show_partitioning(rdd, show=True):\n    \"\"\"Seems to be significantly more expensive on cluster than locally\"\"\"\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))))", "title": ""}
{"_id": "d13665", "text": "def managepy(cmd, extra=None):\n    \"\"\"Run manage.py using this component's specific Django settings\"\"\"\n\n    extra = extra.split() if extra else []\n    run_django_cli(['invoke', cmd] + extra)", "title": ""}
{"_id": "d13666", "text": "def parse(self, s):\n        \"\"\"\n        Parses a date string formatted like ``YYYY-MM-DD``.\n        \"\"\"\n        return datetime.datetime.strptime(s, self.date_format).date()", "title": ""}
{"_id": "d13667", "text": "def start():\n    \"\"\"Starts the web server.\"\"\"\n    global app\n    bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n               debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n               quiet=conf.WebQuiet)", "title": ""}
{"_id": "d13668", "text": "def _cumprod(l):\n  \"\"\"Cumulative product of a list.\n\n  Args:\n    l: a list of integers\n  Returns:\n    a list with one more element (starting with 1)\n  \"\"\"\n  ret = [1]\n  for item in l:\n    ret.append(ret[-1] * item)\n  return ret", "title": ""}
{"_id": "d13669", "text": "def server(port):\n    \"\"\"Start the Django dev server.\"\"\"\n    args = ['python', 'manage.py', 'runserver']\n    if port:\n        args.append(port)\n    run.main(args)", "title": ""}
{"_id": "d13670", "text": "def camel_case(self, snake_case):\n        \"\"\" Convert snake case to camel case \"\"\"\n        components = snake_case.split('_')\n        return components[0] + \"\".join(x.title() for x in components[1:])", "title": ""}
{"_id": "d13671", "text": "def fixpath(path):\n    \"\"\"Uniformly format a path.\"\"\"\n    return os.path.normpath(os.path.realpath(os.path.expanduser(path)))", "title": ""}
{"_id": "d13672", "text": "def input(self, prompt, default=None, show_default=True):\n        \"\"\"Provide a command prompt.\"\"\"\n        return click.prompt(prompt, default=default, show_default=show_default)", "title": ""}
{"_id": "d13673", "text": "def replacing_symlink(source, link_name):\n    \"\"\"Create symlink that overwrites any existing target.\n    \"\"\"\n    with make_tmp_name(link_name) as tmp_link_name:\n        os.symlink(source, tmp_link_name)\n        replace_file_or_dir(link_name, tmp_link_name)", "title": ""}
{"_id": "d13674", "text": "def bitsToString(arr):\n  \"\"\"Returns a string representing a numpy array of 0's and 1's\"\"\"\n  s = array('c','.'*len(arr))\n  for i in xrange(len(arr)):\n    if arr[i] == 1:\n      s[i]='*'\n  return s", "title": ""}
{"_id": "d13675", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d13676", "text": "def home_lib(home):\n    \"\"\"Return the lib dir under the 'home' installation scheme\"\"\"\n    if hasattr(sys, 'pypy_version_info'):\n        lib = 'site-packages'\n    else:\n        lib = os.path.join('lib', 'python')\n    return os.path.join(home, lib)", "title": ""}
{"_id": "d13677", "text": "def draw(graph, fname):\n    \"\"\"Draw a graph and save it into a file\"\"\"\n    ag = networkx.nx_agraph.to_agraph(graph)\n    ag.draw(fname, prog='dot')", "title": ""}
{"_id": "d13678", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d13679", "text": "def _std(self,x):\n        \"\"\"\n        Compute standard deviation with ddof degrees of freedom\n        \"\"\"\n        return np.nanstd(x.values,ddof=self._ddof)", "title": ""}
{"_id": "d13680", "text": "def _re_raise_as(NewExc, *args, **kw):\n    \"\"\"Raise a new exception using the preserved traceback of the last one.\"\"\"\n    etype, val, tb = sys.exc_info()\n    raise NewExc(*args, **kw), None, tb", "title": ""}
{"_id": "d13681", "text": "def aug_sysargv(cmdstr):\n    \"\"\" DEBUG FUNC modify argv to look like you ran a command \"\"\"\n    import shlex\n    argv = shlex.split(cmdstr)\n    sys.argv.extend(argv)", "title": ""}
{"_id": "d13682", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d13683", "text": "def rand_elem(seq, n=None):\n    \"\"\"returns a random element from seq n times. If n is None, it continues indefinitly\"\"\"\n    return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))", "title": ""}
{"_id": "d13684", "text": "def cpp_prog_builder(build_context, target):\n    \"\"\"Build a C++ binary executable\"\"\"\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)", "title": ""}
{"_id": "d13685", "text": "def read_dict_from_file(file_path):\n    \"\"\"\n    Read a dictionary of strings from a file\n    \"\"\"\n    with open(file_path) as file:\n        lines = file.read().splitlines()\n\n    obj = {}\n    for line in lines:\n        key, value = line.split(':', maxsplit=1)\n        obj[key] = eval(value)\n\n    return obj", "title": ""}
{"_id": "d13686", "text": "def CleanseComments(line):\n  \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n  Args:\n    line: A line of C++ source.\n\n  Returns:\n    The line with single-line comments removed.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1 and not IsCppString(line[:commentpos]):\n    line = line[:commentpos].rstrip()\n  # get rid of /* ... */\n  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "title": ""}
{"_id": "d13687", "text": "def read_dict_from_file(file_path):\n    \"\"\"\n    Read a dictionary of strings from a file\n    \"\"\"\n    with open(file_path) as file:\n        lines = file.read().splitlines()\n\n    obj = {}\n    for line in lines:\n        key, value = line.split(':', maxsplit=1)\n        obj[key] = eval(value)\n\n    return obj", "title": ""}
{"_id": "d13688", "text": "def get_login_credentials(args):\n  \"\"\"\n    Gets the login credentials from the user, if not specified while invoking\n    the script.\n    @param args: arguments provided to the script.\n    \"\"\"\n  if not args.username:\n    args.username = raw_input(\"Enter Username: \")\n  if not args.password:\n    args.password = getpass.getpass(\"Enter Password: \")", "title": ""}
{"_id": "d13689", "text": "def read_dict_from_file(file_path):\n    \"\"\"\n    Read a dictionary of strings from a file\n    \"\"\"\n    with open(file_path) as file:\n        lines = file.read().splitlines()\n\n    obj = {}\n    for line in lines:\n        key, value = line.split(':', maxsplit=1)\n        obj[key] = eval(value)\n\n    return obj", "title": ""}
{"_id": "d13690", "text": "def timespan(start_time):\n    \"\"\"Return time in milliseconds from start_time\"\"\"\n\n    timespan = datetime.datetime.now() - start_time\n    timespan_ms = timespan.total_seconds() * 1000\n    return timespan_ms", "title": ""}
{"_id": "d13691", "text": "def get_code(module):\n    \"\"\"\n    Compile and return a Module's code object.\n    \"\"\"\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()", "title": ""}
{"_id": "d13692", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d13693", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d13694", "text": "def read_key(self, key, bucket_name=None):\n        \"\"\"\n        Reads a key from S3\n\n        :param key: S3 key that will point to the file\n        :type key: str\n        :param bucket_name: Name of the bucket in which the file is stored\n        :type bucket_name: str\n        \"\"\"\n\n        obj = self.get_key(key, bucket_name)\n        return obj.get()['Body'].read().decode('utf-8')", "title": ""}
{"_id": "d13695", "text": "def selectnotin(table, field, value, complement=False):\n    \"\"\"Select rows where the given field is not a member of the given value.\"\"\"\n\n    return select(table, field, lambda v: v not in value,\n                  complement=complement)", "title": ""}
{"_id": "d13696", "text": "def wget(url):\n    \"\"\"\n    Download the page into a string\n    \"\"\"\n    import urllib.parse\n    request = urllib.request.urlopen(url)\n    filestring = request.read()\n    return filestring", "title": ""}
{"_id": "d13697", "text": "def get_last(self, table=None):\n        \"\"\"Just the last entry.\"\"\"\n        if table is None: table = self.main_table\n        query = 'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;' % table\n        return self.own_cursor.execute(query).fetchone()", "title": ""}
{"_id": "d13698", "text": "def get_active_window(self):\n        \"\"\"\n        The current active :class:`.Window`.\n        \"\"\"\n        app = get_app()\n\n        try:\n            return self._active_window_for_cli[app]\n        except KeyError:\n            self._active_window_for_cli[app] = self._last_active_window or self.windows[0]\n            return self.windows[0]", "title": ""}
{"_id": "d13699", "text": "def date(start, end):\n    \"\"\"Get a random date between two dates\"\"\"\n\n    stime = date_to_timestamp(start)\n    etime = date_to_timestamp(end)\n\n    ptime = stime + random.random() * (etime - stime)\n\n    return datetime.date.fromtimestamp(ptime)", "title": ""}
{"_id": "d13700", "text": "def load_yaml(filepath):\n    \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n    with open(filepath) as f:\n        txt = f.read()\n    return yaml.load(txt)", "title": ""}
{"_id": "d13701", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d13702", "text": "def main():\n    \"\"\"Ideally we shouldn't lose the first second of events\"\"\"\n    time.sleep(1)\n    with Input() as input_generator:\n        for e in input_generator:\n            print(repr(e))", "title": ""}
{"_id": "d13703", "text": "def selectin(table, field, value, complement=False):\n    \"\"\"Select rows where the given field is a member of the given value.\"\"\"\n\n    return select(table, field, lambda v: v in value,\n                  complement=complement)", "title": ""}
{"_id": "d13704", "text": "def redirect_output(fileobj):\n    \"\"\"Redirect standard out to file.\"\"\"\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old", "title": ""}
{"_id": "d13705", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d13706", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d13707", "text": "def _send(self, data):\n        \"\"\"Send data to statsd.\"\"\"\n        if not self._sock:\n            self.connect()\n        self._do_send(data)", "title": ""}
{"_id": "d13708", "text": "def type(self):\n        \"\"\"Returns type of the data for the given FeatureType.\"\"\"\n        if self is FeatureType.TIMESTAMP:\n            return list\n        if self is FeatureType.BBOX:\n            return BBox\n        return dict", "title": ""}
{"_id": "d13709", "text": "def send(self, data):\n        \"\"\"\n        Send data to the child process through.\n        \"\"\"\n        self.stdin.write(data)\n        self.stdin.flush()", "title": ""}
{"_id": "d13710", "text": "def strip_html(string, keep_tag_content=False):\n    \"\"\"\n    Remove html code contained into the given string.\n\n    :param string: String to manipulate.\n    :type string: str\n    :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).\n    :type keep_tag_content: bool\n    :return: String with html removed.\n    :rtype: str\n    \"\"\"\n    r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE\n    return r.sub('', string)", "title": ""}
{"_id": "d13711", "text": "def send_post(self, url, data, remove_header=None):\n        \"\"\" Send a POST request\n        \"\"\"\n        return self.send_request(method=\"post\", url=url, data=data, remove_header=remove_header)", "title": ""}
{"_id": "d13712", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d13713", "text": "def serialize_me(self, account, bucket_details):\n        \"\"\"Serializes the JSON for the Polling Event Model.\n\n        :param account:\n        :param bucket_details:\n        :return:\n        \"\"\"\n        return self.dumps({\n            \"account\": account,\n            \"detail\": {\n                \"request_parameters\": {\n                    \"bucket_name\": bucket_details[\"Name\"],\n                    \"creation_date\": bucket_details[\"CreationDate\"].replace(\n                        tzinfo=None, microsecond=0).isoformat() + \"Z\"\n                }\n            }\n        }).data", "title": ""}
{"_id": "d13714", "text": "def _remove_blank(l):\n        \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n        ret = []\n        for i, _ in enumerate(l):\n            if l[i] == 0:\n                break\n            ret.append(l[i])\n        return ret", "title": ""}
{"_id": "d13715", "text": "def stop(self, reason=None):\n        \"\"\"Shutdown the service with a reason.\"\"\"\n        self.logger.info('stopping')\n        self.loop.stop(pyev.EVBREAK_ALL)", "title": ""}
{"_id": "d13716", "text": "def remove_instance(self, item):\n        \"\"\"Remove `instance` from model\"\"\"\n        self.instances.remove(item)\n        self.remove_item(item)", "title": ""}
{"_id": "d13717", "text": "def _session_set(self, key, value):\n        \"\"\"\n        Saves a value to session.\n        \"\"\"\n\n        self.session[self._session_key(key)] = value", "title": ""}
{"_id": "d13718", "text": "def set_json_item(key, value):\n    \"\"\" manipulate json data on the fly\n    \"\"\"\n    data = get_json()\n    data[key] = value\n\n    request = get_request()\n    request[\"BODY\"] = json.dumps(data)", "title": ""}
{"_id": "d13719", "text": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n    \"\"\"Clean a pandas dataframe by:\n        1. Filling empty values with Nan\n        2. Dropping columns with all empty values\n\n    Args:\n        df: Pandas DataFrame\n        fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n        drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n    Returns:\n        DataFrame: cleaned DataFrame\n\n    \"\"\"\n    if fill_nan:\n        df = df.fillna(value=np.nan)\n    if drop_empty_columns:\n        df = df.dropna(axis=1, how='all')\n    return df.sort_index()", "title": ""}
{"_id": "d13720", "text": "def _updateTabStopWidth(self):\n        \"\"\"Update tabstop width after font or indentation changed\n        \"\"\"\n        self.setTabStopWidth(self.fontMetrics().width(' ' * self._indenter.width))", "title": ""}
{"_id": "d13721", "text": "def dict_keys_without_hyphens(a_dict):\n    \"\"\"Return the a new dict with underscores instead of hyphens in keys.\"\"\"\n    return dict(\n        (key.replace('-', '_'), val) for key, val in a_dict.items())", "title": ""}
{"_id": "d13722", "text": "def empty(self, start=None, stop=None):\n\t\t\"\"\"Empty the range from start to stop.\n\n\t\tLike delete, but no Error is raised if the entire range isn't mapped.\n\t\t\"\"\"\n\t\tself.set(NOT_SET, start=start, stop=stop)", "title": ""}
{"_id": "d13723", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d13724", "text": "def _top(self):\n        \"\"\" g \"\"\"\n        # Goto top of the list\n        self.top.body.focus_position = 2 if self.compact is False else 0\n        self.top.keypress(self.size, \"\")", "title": ""}
{"_id": "d13725", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d13726", "text": "def move_datetime_year(dt, direction, num_shifts):\n    \"\"\"\n    Move datetime 1 year in the chosen direction.\n    unit is a no-op, to keep the API the same as the day case\n    \"\"\"\n    delta = relativedelta(years=+num_shifts)\n    return _move_datetime(dt, direction, delta)", "title": ""}
{"_id": "d13727", "text": "def mock_decorator(*args, **kwargs):\n    \"\"\"Mocked decorator, needed in the case we need to mock a decorator\"\"\"\n    def _called_decorator(dec_func):\n        @wraps(dec_func)\n        def _decorator(*args, **kwargs):\n            return dec_func()\n        return _decorator\n    return _called_decorator", "title": ""}
{"_id": "d13728", "text": "def replace(s, replace):\n    \"\"\"Replace multiple values in a string\"\"\"\n    for r in replace:\n        s = s.replace(*r)\n    return s", "title": ""}
{"_id": "d13729", "text": "def set_limits(self, min_=None, max_=None):\n        \"\"\"\n        Sets limits for this config value\n\n        If the resulting integer is outside those limits, an exception will be raised\n\n        :param min_: minima\n        :param max_: maxima\n        \"\"\"\n        self._min, self._max = min_, max_", "title": ""}
{"_id": "d13730", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d13731", "text": "def _int64_feature(value):\n  \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(int64_list=tf.train.Int64List(value=value))", "title": ""}
{"_id": "d13732", "text": "def restart_program():\n    \"\"\"\n    DOES NOT WORK WELL WITH MOPIDY\n    Hack from\n    https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program\n    to support updating the settings, since mopidy is not able to do that yet\n    Restarts the current program\n    Note: this function does not return. Any cleanup action (like\n    saving data) must be done before calling this function\n    \"\"\"\n\n    python = sys.executable\n    os.execl(python, python, * sys.argv)", "title": ""}
{"_id": "d13733", "text": "def main(argv, version=DEFAULT_VERSION):\n    \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n    tarball = download_setuptools()\n    _install(tarball, _build_install_args(argv))", "title": ""}
{"_id": "d13734", "text": "def set_scale(self, scale, no_reset=False):\n        \"\"\"Scale the image in a channel.\n        Also see :meth:`zoom_to`.\n\n        Parameters\n        ----------\n        scale : tuple of float\n            Scaling factors for the image in the X and Y axes.\n\n        no_reset : bool\n            Do not reset ``autozoom`` setting.\n\n        \"\"\"\n        return self.scale_to(*scale[:2], no_reset=no_reset)", "title": ""}
{"_id": "d13735", "text": "def format_line(data, linestyle):\n    \"\"\"Formats a list of elements using the given line style\"\"\"\n    return linestyle.begin + linestyle.sep.join(data) + linestyle.end", "title": ""}
{"_id": "d13736", "text": "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)", "title": ""}
{"_id": "d13737", "text": "def close(self):\n    \"\"\"Flush the buffer and finalize the file.\n\n    When this returns the new file is available for reading.\n    \"\"\"\n    if not self.closed:\n      self.closed = True\n      self._flush(finish=True)\n      self._buffer = None", "title": ""}
{"_id": "d13738", "text": "def __init__(self, iterable):\n        \"\"\"Initialize the cycle with some iterable.\"\"\"\n        self._values = []\n        self._iterable = iterable\n        self._initialized = False\n        self._depleted = False\n        self._offset = 0", "title": ""}
{"_id": "d13739", "text": "def uniq(seq):\n    \"\"\" Return a copy of seq without duplicates. \"\"\"\n    seen = set()\n    return [x for x in seq if str(x) not in seen and not seen.add(str(x))]", "title": ""}
{"_id": "d13740", "text": "def restore_default_settings():\n    \"\"\" Restore settings to default values. \n    \"\"\"\n    global __DEFAULTS\n    __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR\n    __DEFAULTS.SET_SEED = defaults.SET_SEED\n    __DEFAULTS.SEED = defaults.SEED\n    logging.info('Settings reverted to their default values.')", "title": ""}
{"_id": "d13741", "text": "def print_message(message=None):\n    \"\"\"Print message via ``subprocess.call`` function.\n\n    This helps to ensure consistent output and avoid situations where print\n    messages actually shown after messages from all inner threads.\n\n    :param message: Text message to print.\n    \"\"\"\n    kwargs = {'stdout': sys.stdout,\n              'stderr': sys.stderr,\n              'shell': True}\n    return subprocess.call('echo \"{0}\"'.format(message or ''), **kwargs)", "title": ""}
{"_id": "d13742", "text": "def horz_dpi(self):\n        \"\"\"\n        Integer dots per inch for the width of this image. Defaults to 72\n        when not present in the file, as is often the case.\n        \"\"\"\n        pHYs = self._chunks.pHYs\n        if pHYs is None:\n            return 72\n        return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)", "title": ""}
{"_id": "d13743", "text": "def set_terminate_listeners(stream):\n    \"\"\"Die on SIGTERM or SIGINT\"\"\"\n\n    def stop(signum, frame):\n        terminate(stream.listener)\n\n    # Installs signal handlers for handling SIGINT and SIGTERM\n    # gracefully.\n    signal.signal(signal.SIGINT, stop)\n    signal.signal(signal.SIGTERM, stop)", "title": ""}
{"_id": "d13744", "text": "def _get_var_from_string(item):\n    \"\"\" Get resource variable. \"\"\"\n    modname, varname = _split_mod_var_names(item)\n    if modname:\n        mod = __import__(modname, globals(), locals(), [varname], -1)\n        return getattr(mod, varname)\n    else:\n        return globals()[varname]", "title": ""}
{"_id": "d13745", "text": "def bin_to_int(string):\n    \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n    if isinstance(string, str):\n        return struct.unpack(\"b\", string)[0]\n    else:\n        return struct.unpack(\"b\", bytes([string]))[0]", "title": ""}
{"_id": "d13746", "text": "def segments_to_numpy(segments):\n    \"\"\"given a list of 4-element tuples, transforms it into a numpy array\"\"\"\n    segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2)  # each segment in a row\n    segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments)\n    return segments", "title": ""}
{"_id": "d13747", "text": "def view_500(request, url=None):\n    \"\"\"\n    it returns a 500 http response\n    \"\"\"\n    res = render_to_response(\"500.html\", context_instance=RequestContext(request))\n    res.status_code = 500\n    return res", "title": ""}
{"_id": "d13748", "text": "def search_index_file():\n    \"\"\"Return the default local index file, from the download cache\"\"\"\n    from metapack import Downloader\n    from os import environ\n\n    return environ.get('METAPACK_SEARCH_INDEX',\n                       Downloader.get_instance().cache.getsyspath('index.json'))", "title": ""}
{"_id": "d13749", "text": "def _connect(self, servers):\n        \"\"\" connect to the given server, e.g.: \\\\connect localhost:4200 \"\"\"\n        self._do_connect(servers.split(' '))\n        self._verify_connection(verbose=True)", "title": ""}
{"_id": "d13750", "text": "def get_value(key, obj, default=missing):\n    \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n    if isinstance(key, int):\n        return _get_value_for_key(key, obj, default)\n    return _get_value_for_keys(key.split('.'), obj, default)", "title": ""}
{"_id": "d13751", "text": "def singleton(class_):\n    \"\"\"Singleton definition.\n\n    Method 1 from\n    https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n    \"\"\"\n    instances = {}\n\n    def get_instance(*args, **kwargs):\n        if class_ not in instances:\n            instances[class_] = class_(*args, **kwargs)\n        return instances[class_]\n    return get_instance", "title": ""}
{"_id": "d13752", "text": "def getTuple(self):\n        \"\"\" Returns the shape of the region as (x, y, w, h) \"\"\"\n        return (self.x, self.y, self.w, self.h)", "title": ""}
{"_id": "d13753", "text": "def singleton(class_):\n    \"\"\"Singleton definition.\n\n    Method 1 from\n    https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n    \"\"\"\n    instances = {}\n\n    def get_instance(*args, **kwargs):\n        if class_ not in instances:\n            instances[class_] = class_(*args, **kwargs)\n        return instances[class_]\n    return get_instance", "title": ""}
{"_id": "d13754", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d13755", "text": "def skip(self, n):\n        \"\"\"Skip the specified number of elements in the list.\n\n        If the number skipped is greater than the number of elements in\n        the list, hasNext() becomes false and available() returns zero\n        as there are no more elements to retrieve.\n\n        arg:    n (cardinal): the number of elements to skip\n        *compliance: mandatory -- This method must be implemented.*\n\n        \"\"\"\n        try:\n            self._iter_object.skip(n)\n        except AttributeError:\n            for i in range(0, n):\n                self.next()", "title": ""}
{"_id": "d13756", "text": "def offsets(self):\n        \"\"\" Returns the offsets values of x, y, z as a numpy array\n        \"\"\"\n        return np.array([self.x_offset, self.y_offset, self.z_offset])", "title": ""}
{"_id": "d13757", "text": "def _skip_frame(self):\n        \"\"\"Skip a single frame from the trajectory\"\"\"\n        size = self.read_size()\n        for i in range(size+1):\n            line = self._f.readline()\n            if len(line) == 0:\n                raise StopIteration", "title": ""}
{"_id": "d13758", "text": "def to_camel_case(text):\n    \"\"\"Convert to camel case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    split = text.split('_')\n    return split[0] + \"\".join(x.title() for x in split[1:])", "title": ""}
{"_id": "d13759", "text": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "title": ""}
{"_id": "d13760", "text": "def earth_orientation(date):\n    \"\"\"Earth orientation as a rotating matrix\n    \"\"\"\n\n    x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date))\n    return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p)", "title": ""}
{"_id": "d13761", "text": "def cluster_kmeans(data, n_clusters, **kwargs):\n    \"\"\"\n    Identify clusters using K - Means algorithm.\n\n    Parameters\n    ----------\n    data : array_like\n        array of size [n_samples, n_features].\n    n_clusters : int\n        The number of clusters expected in the data.\n\n    Returns\n    -------\n    dict\n        boolean array for each identified cluster.\n    \"\"\"\n    km = cl.KMeans(n_clusters, **kwargs)\n    kmf = km.fit(data)\n\n    labels = kmf.labels_\n\n    return labels, [np.nan]", "title": ""}
{"_id": "d13762", "text": "def round_to_n(x, n):\n    \"\"\"\n    Round to sig figs\n    \"\"\"\n    return round(x, -int(np.floor(np.log10(x))) + (n - 1))", "title": ""}
{"_id": "d13763", "text": "def ReverseV2(a, axes):\n    \"\"\"\n    Reverse op.\n    \"\"\"\n    idxs = tuple(slice(None, None, 2 * int(i not in axes) - 1) for i in range(len(a.shape)))\n    return np.copy(a[idxs]),", "title": ""}
{"_id": "d13764", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d13765", "text": "def Slice(a, begin, size):\n    \"\"\"\n    Slicing op.\n    \"\"\"\n    return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],", "title": ""}
{"_id": "d13766", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d13767", "text": "def set_slug(apps, schema_editor):\n    \"\"\"\n    Create a slug for each Event already in the DB.\n    \"\"\"\n    Event = apps.get_model('spectator_events', 'Event')\n\n    for e in Event.objects.all():\n        e.slug = generate_slug(e.pk)\n        e.save(update_fields=['slug'])", "title": ""}
{"_id": "d13768", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d13769", "text": "def wait_send(self, timeout = None):\n\t\t\"\"\"Wait until all queued messages are sent.\"\"\"\n\t\tself._send_queue_cleared.clear()\n\t\tself._send_queue_cleared.wait(timeout = timeout)", "title": ""}
{"_id": "d13770", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d13771", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d13772", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d13773", "text": "def unsort_vector(data, indices_of_increasing):\n    \"\"\"Upermutate 1-D data that is sorted by indices_of_increasing.\"\"\"\n    return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])", "title": ""}
{"_id": "d13774", "text": "def save_excel(self, fd):\n        \"\"\" Saves the case as an Excel spreadsheet.\n        \"\"\"\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)", "title": ""}
{"_id": "d13775", "text": "def _rows_sort(self, rows):\n        \"\"\"\n        Returns a list of rows sorted by start and end date.\n\n        :param list[dict[str,T]] rows: The list of rows.\n\n        :rtype: list[dict[str,T]]\n        \"\"\"\n        return sorted(rows, key=lambda row: (row[self._key_start_date], row[self._key_end_date]))", "title": ""}
{"_id": "d13776", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d13777", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d13778", "text": "def to_html(self, write_to):\n        \"\"\"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.\n        \"\"\"\n        page_html = self.get_html()\n\n        with open(write_to, \"wb\") as writefile:\n            writefile.write(page_html.encode(\"utf-8\"))", "title": ""}
{"_id": "d13779", "text": "def sort_data(x, y):\n    \"\"\"Sort the data.\"\"\"\n    xy = sorted(zip(x, y))\n    x, y = zip(*xy)\n    return x, y", "title": ""}
{"_id": "d13780", "text": "def get_object_attrs(obj):\n    \"\"\"\n    Get the attributes of an object using dir.\n\n    This filters protected attributes\n    \"\"\"\n    attrs = [k for k in dir(obj) if not k.startswith('__')]\n    if not attrs:\n        attrs = dir(obj)\n    return attrs", "title": ""}
{"_id": "d13781", "text": "def sort_data(x, y):\n    \"\"\"Sort the data.\"\"\"\n    xy = sorted(zip(x, y))\n    x, y = zip(*xy)\n    return x, y", "title": ""}
{"_id": "d13782", "text": "def _uniquify(_list):\n    \"\"\"Remove duplicates in a list.\"\"\"\n    seen = set()\n    result = []\n    for x in _list:\n        if x not in seen:\n            result.append(x)\n            seen.add(x)\n    return result", "title": ""}
{"_id": "d13783", "text": "def scipy_sparse_to_spmatrix(A):\n    \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP", "title": ""}
{"_id": "d13784", "text": "def Print(self, output_writer):\n    \"\"\"Prints a human readable version of the filter.\n\n    Args:\n      output_writer (CLIOutputWriter): output writer.\n    \"\"\"\n    if self._filters:\n      output_writer.Write('Filters:\\n')\n      for file_entry_filter in self._filters:\n        file_entry_filter.Print(output_writer)", "title": ""}
{"_id": "d13785", "text": "def allsame(list_, strict=True):\n    \"\"\"\n    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\n    \"\"\"\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)", "title": ""}
{"_id": "d13786", "text": "def partition(a, sz): \n    \"\"\"splits iterables a in equal parts of size sz\"\"\"\n    return [a[i:i+sz] for i in range(0, len(a), sz)]", "title": ""}
{"_id": "d13787", "text": "def ensure_dir_exists(directory):\n    \"\"\"Se asegura de que un directorio exista.\"\"\"\n    if directory and not os.path.exists(directory):\n        os.makedirs(directory)", "title": ""}
{"_id": "d13788", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d13789", "text": "def feature_subset(self, indices):\n        \"\"\" Returns some subset of the features.\n        \n        Parameters\n        ----------\n        indices : :obj:`list` of :obj:`int`\n            indices of the features in the list\n\n        Returns\n        -------\n        :obj:`list` of :obj:`Feature`\n        \"\"\"\n        if isinstance(indices, np.ndarray):\n            indices = indices.tolist()\n        if not isinstance(indices, list):\n            raise ValueError('Can only index with lists')\n        return [self.features_[i] for i in indices]", "title": ""}
{"_id": "d13790", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d13791", "text": "def _request_modify_dns_record(self, record):\n        \"\"\"Sends Modify_DNS_Record request\"\"\"\n        return self._request_internal(\"Modify_DNS_Record\",\n                                      domain=self.domain,\n                                      record=record)", "title": ""}
{"_id": "d13792", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d13793", "text": "def rewindbody(self):\n        \"\"\"Rewind the file to the start of the body (if seekable).\"\"\"\n        if not self.seekable:\n            raise IOError, \"unseekable file\"\n        self.fp.seek(self.startofbody)", "title": ""}
{"_id": "d13794", "text": "def split_into_sentences(s):\n  \"\"\"Split text into list of sentences.\"\"\"\n  s = re.sub(r\"\\s+\", \" \", s)\n  s = re.sub(r\"[\\\\.\\\\?\\\\!]\", \"\\n\", s)\n  return s.split(\"\\n\")", "title": ""}
{"_id": "d13795", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d13796", "text": "def _set_axis_limits(self, which, lims, d, scale, reverse=False):\n        \"\"\"Private method for setting axis limits.\n\n        Sets the axis limits on each axis for an individual plot.\n\n        Args:\n            which (str): The indicator of which part of the plots\n                to adjust. This currently handles `x` and `y`.\n            lims (len-2 list of floats): The limits for the axis.\n            d (float): Amount to increment by between the limits.\n            scale (str): Scale of the axis. Either `log` or `lin`.\n            reverse (bool, optional): If True, reverse the axis tick marks. Default is False.\n\n        \"\"\"\n        setattr(self.limits, which + 'lims', lims)\n        setattr(self.limits, 'd' + which, d)\n        setattr(self.limits, which + 'scale', scale)\n\n        if reverse:\n            setattr(self.limits, 'reverse_' + which + '_axis', True)\n        return", "title": ""}
{"_id": "d13797", "text": "def string_to_list(string, sep=\",\", filter_empty=False):\n    \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n    return [value.strip() for value in string.split(sep)\n            if (not filter_empty or value)]", "title": ""}
{"_id": "d13798", "text": "def save_config_value(request, response, key, value):\n    \"\"\"Sets value of key `key` to `value` in both session and cookies.\"\"\"\n    request.session[key] = value\n    response.set_cookie(key, value, expires=one_year_from_now())\n    return response", "title": ""}
{"_id": "d13799", "text": "def forceupdate(self, *args, **kw):\n        \"\"\"Like a bulk :meth:`forceput`.\"\"\"\n        self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)", "title": ""}
{"_id": "d13800", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d13801", "text": "def graphql_queries_to_json(*queries):\n    \"\"\"\n    Queries should be a list of GraphQL objects\n    \"\"\"\n    rtn = {}\n    for i, query in enumerate(queries):\n        rtn[\"q{}\".format(i)] = query.value\n    return json.dumps(rtn)", "title": ""}
{"_id": "d13802", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d13803", "text": "def table_exists(cursor, tablename, schema='public'):\n    query = \"\"\"\n    SELECT EXISTS (\n        SELECT 1\n        FROM information_schema.tables\n        WHERE table_schema = %s\n        AND table_name = %s\n    )\"\"\"\n    cursor.execute(query, (schema, tablename))\n    res = cursor.fetchone()[0]\n    return res", "title": ""}
{"_id": "d13804", "text": "def set_xlimits(self, min=None, max=None):\n        \"\"\"Set limits for the x-axis.\n\n        :param min: minimum value to be displayed.  If None, it will be\n            calculated.\n        :param max: maximum value to be displayed.  If None, it will be\n            calculated.\n\n        \"\"\"\n        self.limits['xmin'] = min\n        self.limits['xmax'] = max", "title": ""}
{"_id": "d13805", "text": "def connect_mysql(host, port, user, password, database):\n    \"\"\"Connect to MySQL with retries.\"\"\"\n    return pymysql.connect(\n        host=host, port=port,\n        user=user, passwd=password,\n        db=database\n    )", "title": ""}
{"_id": "d13806", "text": "def list_backends(_):\n    \"\"\"List all available backends.\"\"\"\n    backends = [b.__name__ for b in available_backends()]\n    print('\\n'.join(backends))", "title": ""}
{"_id": "d13807", "text": "def insert_many(self, items):\n    \"\"\"\n    Insert many items at once into a temporary table.\n\n    \"\"\"\n    return SessionContext.session.execute(\n        self.insert(values=[\n            to_dict(item, self.c)\n            for item in items\n        ]),\n    ).rowcount", "title": ""}
{"_id": "d13808", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d13809", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d13810", "text": "def csvpretty(csvfile: csvfile=sys.stdin):\n    \"\"\" Pretty print a CSV file. \"\"\"\n    shellish.tabulate(csv.reader(csvfile))", "title": ""}
{"_id": "d13811", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d13812", "text": "def show(self, title=''):\n        \"\"\"\n        Display Bloch sphere and corresponding data sets.\n        \"\"\"\n        self.render(title=title)\n        if self.fig:\n            plt.show(self.fig)", "title": ""}
{"_id": "d13813", "text": "def add_to_toolbar(self, toolbar, widget):\n        \"\"\"Add widget actions to toolbar\"\"\"\n        actions = widget.toolbar_actions\n        if actions is not None:\n            add_actions(toolbar, actions)", "title": ""}
{"_id": "d13814", "text": "def column_names(self, table):\n      \"\"\"An iterable of column names, for a particular table or\n      view.\"\"\"\n\n      table_info = self.execute(\n        u'PRAGMA table_info(%s)' % quote(table))\n      return (column['name'] for column in table_info)", "title": ""}
{"_id": "d13815", "text": "def sort_fn_list(fn_list):\n    \"\"\"Sort input filename list by datetime\n    \"\"\"\n    dt_list = get_dt_list(fn_list)\n    fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]\n    return fn_list_sort", "title": ""}
{"_id": "d13816", "text": "def disable_cert_validation():\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d13817", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d13818", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d13819", "text": "def sort_fn_list(fn_list):\n    \"\"\"Sort input filename list by datetime\n    \"\"\"\n    dt_list = get_dt_list(fn_list)\n    fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]\n    return fn_list_sort", "title": ""}
{"_id": "d13820", "text": "def safe_call(cls, method, *args):\n        \"\"\" Call a remote api method but don't raise if an error occurred.\"\"\"\n        return cls.call(method, *args, safe=True)", "title": ""}
{"_id": "d13821", "text": "def sort_func(self, key):\n        \"\"\"Sorting logic for `Quantity` objects.\"\"\"\n        if key == self._KEYS.VALUE:\n            return 'aaa'\n        if key == self._KEYS.SOURCE:\n            return 'zzz'\n        return key", "title": ""}
{"_id": "d13822", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d13823", "text": "def array_dim(arr):\n    \"\"\"Return the size of a multidimansional array.\n    \"\"\"\n    dim = []\n    while True:\n        try:\n            dim.append(len(arr))\n            arr = arr[0]\n        except TypeError:\n            return dim", "title": ""}
{"_id": "d13824", "text": "def read_stdin():\n    \"\"\" Read text from stdin, and print a helpful message for ttys. \"\"\"\n    if sys.stdin.isatty() and sys.stdout.isatty():\n        print('\\nReading from stdin until end of file (Ctrl + D)...')\n\n    return sys.stdin.read()", "title": ""}
{"_id": "d13825", "text": "def get_geoip(ip):\n    \"\"\"Lookup country for IP address.\"\"\"\n    reader = geolite2.reader()\n    ip_data = reader.get(ip) or {}\n    return ip_data.get('country', {}).get('iso_code')", "title": ""}
{"_id": "d13826", "text": "def __init__(self, encoding='utf-8'):\n    \"\"\"Initializes an stdin input reader.\n\n    Args:\n      encoding (Optional[str]): input encoding.\n    \"\"\"\n    super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)", "title": ""}
{"_id": "d13827", "text": "def fix_line_breaks(s):\n    \"\"\"\n    Convert \\r\\n and \\r to \\n chars. Strip any leading or trailing whitespace\n    on each line. Remove blank lines.\n    \"\"\"\n    l = s.splitlines()\n    x = [i.strip() for i in l]\n    x = [i for i in x if i]  # remove blank lines\n    return \"\\n\".join(x)", "title": ""}
{"_id": "d13828", "text": "def printOut(value, end='\\n'):\n    \"\"\"\n    This function prints the given String immediately and flushes the output.\n    \"\"\"\n    sys.stdout.write(value)\n    sys.stdout.write(end)\n    sys.stdout.flush()", "title": ""}
{"_id": "d13829", "text": "def is_static(*p):\n    \"\"\" A static value (does not change at runtime)\n    which is known at compile time\n    \"\"\"\n    return all(is_CONST(x) or\n               is_number(x) or\n               is_const(x)\n               for x in p)", "title": ""}
{"_id": "d13830", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d13831", "text": "def stop(self):\n        \"\"\"Stop the progress bar.\"\"\"\n        if self._progressing:\n            self._progressing = False\n            self._thread.join()", "title": ""}
{"_id": "d13832", "text": "def getFunction(self):\n        \"\"\"Called by remote workers. Useful to populate main module globals()\n        for interactive shells. Retrieves the serialized function.\"\"\"\n        return functionFactory(\n            self.code,\n            self.name,\n            self.defaults,\n            self.globals,\n            self.imports,\n        )", "title": ""}
{"_id": "d13833", "text": "def do_quit(self, arg):\n        \"\"\"\n        quit || exit || q\n        Stop and quit the current debugging session\n        \"\"\"\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)", "title": ""}
{"_id": "d13834", "text": "def bytes_to_c_array(data):\n    \"\"\"\n    Make a C array using the given string.\n    \"\"\"\n    chars = [\n        \"'{}'\".format(encode_escape(i))\n        for i in decode_escape(data)\n    ]\n    return ', '.join(chars) + ', 0'", "title": ""}
{"_id": "d13835", "text": "def on_error(e):  # pragma: no cover\n    \"\"\"Error handler\n\n    RuntimeError or ValueError exceptions raised by commands will be handled\n    by this function.\n    \"\"\"\n    exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'}\n    sys.stderr.write('{}: {}\\n'.format(exname[e.__class__.__name__], str(e)))\n    sys.stderr.write('See file slam_error.log for additional details.\\n')\n    sys.exit(1)", "title": ""}
{"_id": "d13836", "text": "def get_gzipped_contents(input_file):\n    \"\"\"\n    Returns a gzipped version of a previously opened file's buffer.\n    \"\"\"\n    zbuf = StringIO()\n    zfile = GzipFile(mode=\"wb\", compresslevel=6, fileobj=zbuf)\n    zfile.write(input_file.read())\n    zfile.close()\n    return ContentFile(zbuf.getvalue())", "title": ""}
{"_id": "d13837", "text": "def __normalize_list(self, msg):\n        \"\"\"Split message to list by commas and trim whitespace.\"\"\"\n        if isinstance(msg, list):\n            msg = \"\".join(msg)\n        return list(map(lambda x: x.strip(), msg.split(\",\")))", "title": ""}
{"_id": "d13838", "text": "def splitBy(data, num):\n    \"\"\" Turn a list to list of list \"\"\"\n    return [data[i:i + num] for i in range(0, len(data), num)]", "title": ""}
{"_id": "d13839", "text": "def add_suffix(fullname, suffix):\n    \"\"\" Add suffix to a full file name\"\"\"\n    name, ext = os.path.splitext(fullname)\n    return name + '_' + suffix + ext", "title": ""}
{"_id": "d13840", "text": "def PythonPercentFormat(format_str):\n  \"\"\"Use Python % format strings as template format specifiers.\"\"\"\n\n  if format_str.startswith('printf '):\n    fmt = format_str[len('printf '):]\n    return lambda value: fmt % value\n  else:\n    return None", "title": ""}
{"_id": "d13841", "text": "def transpose(table):\n    \"\"\"\n    transpose matrix\n    \"\"\"\n    t = []\n    for i in range(0, len(table[0])):\n        t.append([row[i] for row in table])\n    return t", "title": ""}
{"_id": "d13842", "text": "def subat(orig, index, replace):\n    \"\"\"Substitutes the replacement string/character at the given index in the\n    given string, returns the modified string.\n\n    **Examples**:\n    ::\n        auxly.stringy.subat(\"bit\", 2, \"n\")\n    \"\"\"\n    return \"\".join([(orig[x] if x != index else replace) for x in range(len(orig))])", "title": ""}
{"_id": "d13843", "text": "def require_root(fn):\n    \"\"\"\n    Decorator to make sure, that user is root.\n    \"\"\"\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\n    return xex", "title": ""}
{"_id": "d13844", "text": "def fsliceafter(astr, sub):\n    \"\"\"Return the slice after at sub in string astr\"\"\"\n    findex = astr.find(sub)\n    return astr[findex + len(sub):]", "title": ""}
{"_id": "d13845", "text": "def cat_acc(y_true, y_pred):\n    \"\"\"Categorical accuracy\n    \"\"\"\n    return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))", "title": ""}
{"_id": "d13846", "text": "def comma_delimited_to_list(list_param):\n    \"\"\"Convert comma-delimited list / string into a list of strings\n\n    :param list_param: Comma-delimited string\n    :type list_param: str | unicode\n    :return: A list of strings\n    :rtype: list\n    \"\"\"\n    if isinstance(list_param, list):\n        return list_param\n    if isinstance(list_param, str):\n        return list_param.split(',')\n    else:\n        return []", "title": ""}
{"_id": "d13847", "text": "def hard_equals(a, b):\n    \"\"\"Implements the '===' operator.\"\"\"\n    if type(a) != type(b):\n        return False\n    return a == b", "title": ""}
{"_id": "d13848", "text": "def string_to_list(string, sep=\",\", filter_empty=False):\n    \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n    return [value.strip() for value in string.split(sep)\n            if (not filter_empty or value)]", "title": ""}
{"_id": "d13849", "text": "def is_integer(dtype):\n  \"\"\"Returns whether this is a (non-quantized) integer type.\"\"\"\n  dtype = tf.as_dtype(dtype)\n  if hasattr(dtype, 'is_integer'):\n    return dtype.is_integer\n  return np.issubdtype(np.dtype(dtype), np.integer)", "title": ""}
{"_id": "d13850", "text": "def get_line_ending(line):\n    \"\"\"Return line ending.\"\"\"\n    non_whitespace_index = len(line.rstrip()) - len(line)\n    if not non_whitespace_index:\n        return ''\n    else:\n        return line[non_whitespace_index:]", "title": ""}
{"_id": "d13851", "text": "def find_first_number(ll):\n    \"\"\" Returns nr of first entry parseable to float in ll, None otherwise\"\"\"\n    for nr, entry in enumerate(ll):\n        try:\n            float(entry)\n        except (ValueError, TypeError) as e:\n            pass\n        else:\n            return nr\n    return None", "title": ""}
{"_id": "d13852", "text": "def execute_in_background(self):\n        \"\"\"Executes a (shell) command in the background\n\n        :return: the process' pid\n        \"\"\"\n        # http://stackoverflow.com/questions/1605520\n        args = shlex.split(self.cmd)\n        p = Popen(args)\n        return p.pid", "title": ""}
{"_id": "d13853", "text": "def camel_to_underscore(string):\n    \"\"\"Convert camelcase to lowercase and underscore.\n\n    Recipe from http://stackoverflow.com/a/1176023\n\n    Args:\n        string (str): The string to convert.\n\n    Returns:\n        str: The converted string.\n    \"\"\"\n    string = FIRST_CAP_RE.sub(r'\\1_\\2', string)\n    return ALL_CAP_RE.sub(r'\\1_\\2', string).lower()", "title": ""}
{"_id": "d13854", "text": "def _trim(self, somestr):\n        \"\"\" Trim left-right given string \"\"\"\n        tmp = RE_LSPACES.sub(\"\", somestr)\n        tmp = RE_TSPACES.sub(\"\", tmp)\n        return str(tmp)", "title": ""}
{"_id": "d13855", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d13856", "text": "def bytes_to_bits(bytes_):\n    \"\"\"Convert bytes to a list of bits\n    \"\"\"\n    res = []\n    for x in bytes_:\n        if not isinstance(x, int):\n            x = ord(x)\n        res += byte_to_bits(x)\n    return res", "title": ""}
{"_id": "d13857", "text": "def query_sum(queryset, field):\n    \"\"\"\n    Let the DBMS perform a sum on a queryset\n    \"\"\"\n    return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']", "title": ""}
{"_id": "d13858", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d13859", "text": "def Sum(a, axis, keep_dims):\n    \"\"\"\n    Sum reduction op.\n    \"\"\"\n    return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                  keepdims=keep_dims),", "title": ""}
{"_id": "d13860", "text": "def from_series(cls, series):\n        \"\"\"Convert a pandas.Series into an xarray.DataArray.\n\n        If the series's index is a MultiIndex, it will be expanded into a\n        tensor product of one-dimensional coordinates (filling in missing\n        values with NaN). Thus this operation should be the inverse of the\n        `to_series` method.\n        \"\"\"\n        # TODO: add a 'name' parameter\n        name = series.name\n        df = pd.DataFrame({name: series})\n        ds = Dataset.from_dataframe(df)\n        return ds[name]", "title": ""}
{"_id": "d13861", "text": "def get_last_filled_cell(self, table=None):\n        \"\"\"Returns key for the bottommost rightmost cell with content\n\n        Parameters\n        ----------\n        table: Integer, defaults to None\n        \\tLimit search to this table\n\n        \"\"\"\n\n        maxrow = 0\n        maxcol = 0\n\n        for row, col, tab in self.dict_grid:\n            if table is None or tab == table:\n                maxrow = max(row, maxrow)\n                maxcol = max(col, maxcol)\n\n        return maxrow, maxcol, table", "title": ""}
{"_id": "d13862", "text": "def to_list(var):\n    \"\"\"Checks if given value is a list, tries to convert, if it is not.\"\"\"\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", "title": ""}
{"_id": "d13863", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d13864", "text": "def coerce(self, value):\n        \"\"\"Convert from whatever is given to a list of scalars for the lookup_field.\"\"\"\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]", "title": ""}
{"_id": "d13865", "text": "def load(self, filename='classifier.dump'):\n        \"\"\"\n        Unpickles the classifier used\n        \"\"\"\n        ifile = open(filename, 'r+')\n        self.classifier = pickle.load(ifile)\n        ifile.close()", "title": ""}
{"_id": "d13866", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d13867", "text": "def get_shape(img):\n    \"\"\"Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple\n    \"\"\"\n    if hasattr(img, 'shape'):\n        shape = img.shape\n    else:\n        shape = img.get_data().shape\n    return shape", "title": ""}
{"_id": "d13868", "text": "def run_std_server(self):\n    \"\"\"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.\n    \"\"\"\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()", "title": ""}
{"_id": "d13869", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d13870", "text": "def requests_post(url, data=None, json=None, **kwargs):\n    \"\"\"Requests-mock requests.post wrapper.\"\"\"\n    return requests_request('post', url, data=data, json=json, **kwargs)", "title": ""}
{"_id": "d13871", "text": "def unpickle_file(picklefile, **kwargs):\n    \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)", "title": ""}
{"_id": "d13872", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d13873", "text": "def filesavebox(msg=None, title=None, argInitialFile=None):\n    \"\"\"Original doc: A file to get the name of a file to save.\n        Returns the name of a file, or None if user chose to cancel.\n\n        if argInitialFile contains a valid filename, the dialog will\n        be positioned at that file when it appears.\n        \"\"\"\n    return psidialogs.ask_file(message=msg, title=title, default=argInitialFile, save=True)", "title": ""}
{"_id": "d13874", "text": "def test():\n    \"\"\" Run all Tests [nose] \"\"\"\n\n    command = 'nosetests --with-coverage --cover-package=pwnurl'\n    status = subprocess.call(shlex.split(command))\n    sys.exit(status)", "title": ""}
{"_id": "d13875", "text": "def is_executable(path):\n  \"\"\"Returns whether a path names an existing executable file.\"\"\"\n  return os.path.isfile(path) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d13876", "text": "def help_for_command(command):\n    \"\"\"Get the help text (signature + docstring) for a command (function).\"\"\"\n    help_text = pydoc.text.document(command)\n    # remove backspaces\n    return re.subn('.\\\\x08', '', help_text)[0]", "title": ""}
{"_id": "d13877", "text": "def column_exists(cr, table, column):\n    \"\"\" Check whether a certain column exists \"\"\"\n    cr.execute(\n        'SELECT count(attname) FROM pg_attribute '\n        'WHERE attrelid = '\n        '( SELECT oid FROM pg_class WHERE relname = %s ) '\n        'AND attname = %s',\n        (table, column))\n    return cr.fetchone()[0] == 1", "title": ""}
{"_id": "d13878", "text": "def list_files(directory):\n    \"\"\"Returns all files in a given directory\n    \"\"\"\n    return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]", "title": ""}
{"_id": "d13879", "text": "def is_power_of_2(num):\n    \"\"\"Return whether `num` is a power of two\"\"\"\n    log = math.log2(num)\n    return int(log) == float(log)", "title": ""}
{"_id": "d13880", "text": "def _load_texture(file_name, resolver):\n    \"\"\"\n    Load a texture from a file into a PIL image.\n    \"\"\"\n    file_data = resolver.get(file_name)\n    image = PIL.Image.open(util.wrap_as_stream(file_data))\n    return image", "title": ""}
{"_id": "d13881", "text": "def is_connected(self):\n        \"\"\"\n        Return true if the socket managed by this connection is connected\n\n        :rtype: bool\n        \"\"\"\n        try:\n            return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)\n        except socket.error:\n            return False", "title": ""}
{"_id": "d13882", "text": "def fmt_subst(regex, subst):\n    \"\"\"Replace regex with string.\"\"\"\n    return lambda text: re.sub(regex, subst, text) if text else text", "title": ""}
{"_id": "d13883", "text": "def setDictDefaults (d, defaults):\n  \"\"\"Sets all defaults for the given dictionary to those contained in a\n  second defaults dictionary.  This convenience method calls:\n\n    d.setdefault(key, value)\n\n  for each key and value in the given defaults dictionary.\n  \"\"\"\n  for key, val in defaults.items():\n    d.setdefault(key, val)\n\n  return d", "title": ""}
{"_id": "d13884", "text": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "title": ""}
{"_id": "d13885", "text": "def get_join_cols(by_entry):\n  \"\"\" helper function used for joins\n  builds left and right join list for join function\n  \"\"\"\n  left_cols = []\n  right_cols = []\n  for col in by_entry:\n    if isinstance(col, str):\n      left_cols.append(col)\n      right_cols.append(col)\n    else:\n      left_cols.append(col[0])\n      right_cols.append(col[1])\n  return left_cols, right_cols", "title": ""}
{"_id": "d13886", "text": "def colorize(txt, fg=None, bg=None):\n    \"\"\"\n    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.\n    \"\"\"\n\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", "title": ""}
{"_id": "d13887", "text": "def step_impl06(context):\n    \"\"\"Prepare test for singleton property.\n\n    :param context: test context.\n    \"\"\"\n    store = context.SingleStore\n    context.st_1 = store()\n    context.st_2 = store()\n    context.st_3 = store()", "title": ""}
{"_id": "d13888", "text": "def to_snake_case(text):\n    \"\"\"Convert to snake case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d13889", "text": "def import_public_rsa_key_from_file(filename):\n    \"\"\"\n    Read a public RSA 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.rsa.RSAPublicKey instance\n    \"\"\"\n    with open(filename, \"rb\") as key_file:\n        public_key = serialization.load_pem_public_key(\n            key_file.read(),\n            backend=default_backend())\n    return public_key", "title": ""}
{"_id": "d13890", "text": "def last(self):\n        \"\"\"Get the last object in file.\"\"\"\n        # End of file\n        self.__file.seek(0, 2)\n\n        # Get the last struct\n        data = self.get(self.length - 1)\n\n        return data", "title": ""}
{"_id": "d13891", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d13892", "text": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "title": ""}
{"_id": "d13893", "text": "def post_process(self):\n        \"\"\" Apply last 2D transforms\"\"\"\n        self.image.putdata(self.pixels)\n        self.image = self.image.transpose(Image.ROTATE_90)", "title": ""}
{"_id": "d13894", "text": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "title": ""}
{"_id": "d13895", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d13896", "text": "def Join(self):\n    \"\"\"Waits until all outstanding tasks are completed.\"\"\"\n\n    for _ in range(self.JOIN_TIMEOUT_DECISECONDS):\n      if self._queue.empty() and not self.busy_threads:\n        return\n      time.sleep(0.1)\n\n    raise ValueError(\"Timeout during Join() for threadpool %s.\" % self.name)", "title": ""}
{"_id": "d13897", "text": "def _letter_map(word):\n    \"\"\"Creates a map of letter use in a word.\n\n    Args:\n        word: a string to create a letter map from\n\n    Returns:\n        a dictionary of {letter: integer count of letter in word}\n    \"\"\"\n\n    lmap = {}\n    for letter in word:\n        try:\n            lmap[letter] += 1\n        except KeyError:\n            lmap[letter] = 1\n    return lmap", "title": ""}
{"_id": "d13898", "text": "def utcfromtimestamp(cls, timestamp):\n    \"\"\"Returns a datetime object of a given timestamp (in UTC).\"\"\"\n    obj = datetime.datetime.utcfromtimestamp(timestamp)\n    obj = pytz.utc.localize(obj)\n    return cls(obj)", "title": ""}
{"_id": "d13899", "text": "def _screen(self, s, newline=False):\n        \"\"\"Print something on screen when self.verbose == True\"\"\"\n        if self.verbose:\n            if newline:\n                print(s)\n            else:\n                print(s, end=' ')", "title": ""}
{"_id": "d13900", "text": "def seconds_to_time(x):\n    \"\"\"Convert a number of second into a time\"\"\"\n    t = int(x * 10**6)\n    ms = t % 10**6\n    t = t // 10**6\n    s = t % 60\n    t = t // 60\n    m = t % 60\n    t = t // 60\n    h = t\n    return time(h, m, s, ms)", "title": ""}
{"_id": "d13901", "text": "def ratio_and_percentage(current, total, time_remaining):\n    \"\"\"Returns the progress ratio and percentage.\"\"\"\n    return \"{} / {} ({}% completed)\".format(current, total, int(current / total * 100))", "title": ""}
{"_id": "d13902", "text": "def fmt_duration(secs):\n    \"\"\"Format a duration in seconds.\"\"\"\n    return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())", "title": ""}
{"_id": "d13903", "text": "def _rotate(n, x, y, rx, ry):\n    \"\"\"Rotate and flip a quadrant appropriately\n\n    Based on the implementation here:\n        https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503\n\n    \"\"\"\n    if ry == 0:\n        if rx == 1:\n            x = n - 1 - x\n            y = n - 1 - y\n        return y, x\n    return x, y", "title": ""}
{"_id": "d13904", "text": "def add_datetime(dataframe, timestamp_key='UNIXTIME'):\n    \"\"\"Add an additional DATETIME column with standar datetime format.\n\n    This currently manipulates the incoming DataFrame!\n    \"\"\"\n\n    def convert_data(timestamp):\n        return datetime.fromtimestamp(float(timestamp) / 1e3, UTC_TZ)\n\n    try:\n        log.debug(\"Adding DATETIME column to the data\")\n        converted = dataframe[timestamp_key].apply(convert_data)\n        dataframe['DATETIME'] = converted\n    except KeyError:\n        log.warning(\"Could not add DATETIME column\")", "title": ""}
{"_id": "d13905", "text": "def _make_sql_params(self,kw):\n        \"\"\"Make a list of strings to pass to an SQL statement\n        from the dictionary kw with Python types\"\"\"\n        return ['%s=?' %k for k in kw.keys() ]\n        for k,v in kw.iteritems():\n            vals.append('%s=?' %k)\n        return vals", "title": ""}
{"_id": "d13906", "text": "def session_to_epoch(timestamp):\n    \"\"\" converts Synergy Timestamp for session to UTC zone seconds since epoch \"\"\"\n    utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()\n    return calendar.timegm(utc_timetuple)", "title": ""}
{"_id": "d13907", "text": "def extent(self):\n        \"\"\"Helper for matplotlib imshow\"\"\"\n        return (\n            self.intervals[1].pix1 - 0.5,\n            self.intervals[1].pix2 - 0.5,\n            self.intervals[0].pix1 - 0.5,\n            self.intervals[0].pix2 - 0.5,\n        )", "title": ""}
{"_id": "d13908", "text": "def current_offset(local_tz=None):\n    \"\"\"\n    Returns current utcoffset for a timezone. Uses\n    DEFAULT_LOCAL_TZ by default. That value can be\n    changed at runtime using the func below.\n    \"\"\"\n    if local_tz is None:\n        local_tz = DEFAULT_LOCAL_TZ\n    dt = local_tz.localize(datetime.now())\n    return dt.utcoffset()", "title": ""}
{"_id": "d13909", "text": "def GetRootKey(self):\n    \"\"\"Retrieves the root key.\n\n    Returns:\n      WinRegistryKey: Windows Registry root key or None if not available.\n    \"\"\"\n    regf_key = self._regf_file.get_root_key()\n    if not regf_key:\n      return None\n\n    return REGFWinRegistryKey(regf_key, key_path=self._key_path_prefix)", "title": ""}
{"_id": "d13910", "text": "def yview(self, *args):\n        \"\"\"Update inplace widgets position when doing vertical scroll\"\"\"\n        self.after_idle(self.__updateWnds)\n        ttk.Treeview.yview(self, *args)", "title": ""}
{"_id": "d13911", "text": "def html_to_text(content):\n    \"\"\" Converts html content to plain text \"\"\"\n    text = None\n    h2t = html2text.HTML2Text()\n    h2t.ignore_links = False\n    text = h2t.handle(content)\n    return text", "title": ""}
{"_id": "d13912", "text": "def _grid_widgets(self):\n        \"\"\"Puts the two whole widgets in the correct position depending on compound.\"\"\"\n        scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n        self.listbox.grid(row=0, column=1, sticky=\"nswe\")\n        self.scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")", "title": ""}
{"_id": "d13913", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d13914", "text": "def askopenfilename(**kwargs):\n    \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n    try:\n        from Tkinter import Tk\n        import tkFileDialog as filedialog\n    except ImportError:\n        from tkinter import Tk, filedialog\n    root = Tk()\n    root.withdraw()\n    root.update()\n    filenames = filedialog.askopenfilename(**kwargs)\n    root.destroy()\n    return filenames", "title": ""}
{"_id": "d13915", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d13916", "text": "def on_source_directory_chooser_clicked(self):\n        \"\"\"Autoconnect slot activated when tbSourceDir is clicked.\"\"\"\n\n        title = self.tr('Set the source directory for script and scenario')\n        self.choose_directory(self.source_directory, title)", "title": ""}
{"_id": "d13917", "text": "def value_left(self, other):\n    \"\"\"\n    Returns the value of the other type instance to use in an\n    operator method, namely when the method's instance is on the\n    left side of the expression.\n    \"\"\"\n    return other.value if isinstance(other, self.__class__) else other", "title": ""}
{"_id": "d13918", "text": "def hide(self):\n        \"\"\"Hide the window.\"\"\"\n        self.tk.withdraw()\n        self._visible = False\n        if self._modal:\n            self.tk.grab_release()", "title": ""}
{"_id": "d13919", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d13920", "text": "def closeEvent(self, e):\n        \"\"\"Qt slot when the window is closed.\"\"\"\n        self.emit('close_widget')\n        super(DockWidget, self).closeEvent(e)", "title": ""}
{"_id": "d13921", "text": "def uint8sc(im):\n    \"\"\"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\n    \"\"\"\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)", "title": ""}
{"_id": "d13922", "text": "def detach(self, *items):\n        \"\"\"\n        Unlinks all of the specified items from the tree.\n\n        The items and all of their descendants are still present, and may be\n        reinserted at another point in the tree, but will not be displayed.\n        The root item may not be detached.\n\n        :param items: list of item identifiers\n        :type items: sequence[str]\n        \"\"\"\n        self._visual_drag.detach(*items)\n        ttk.Treeview.detach(self, *items)", "title": ""}
{"_id": "d13923", "text": "def instance_contains(container, item):\n    \"\"\"Search into instance attributes, properties and return values of no-args methods.\"\"\"\n    return item in (member for _, member in inspect.getmembers(container))", "title": ""}
{"_id": "d13924", "text": "def remote_file_exists(self, url):\n        \"\"\" 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.\n        \"\"\"\n        status = requests.head(url).status_code\n\n        if status != 200:\n            raise RemoteFileDoesntExist", "title": ""}
{"_id": "d13925", "text": "def ensure_hbounds(self):\n        \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "title": ""}
{"_id": "d13926", "text": "def s3_connect(bucket_name, s3_access_key_id, s3_secret_key):\n    \"\"\" Returns a Boto connection to the provided S3 bucket. \"\"\"\n    conn = connect_s3(s3_access_key_id, s3_secret_key)\n    try:\n        return conn.get_bucket(bucket_name)\n    except S3ResponseError as e:\n        if e.status == 403:\n            raise Exception(\"Bad Amazon S3 credentials.\")\n        raise", "title": ""}
{"_id": "d13927", "text": "def Proxy(f):\n  \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n\n  return Wrapped", "title": ""}
{"_id": "d13928", "text": "def to_str(s):\n    \"\"\"\n    Convert bytes and non-string into Python 3 str\n    \"\"\"\n    if isinstance(s, bytes):\n        s = s.decode('utf-8')\n    elif not isinstance(s, str):\n        s = str(s)\n    return s", "title": ""}
{"_id": "d13929", "text": "def table_top_abs(self):\n        \"\"\"Returns the absolute position of table top\"\"\"\n        table_height = np.array([0, 0, self.table_full_size[2]])\n        return string_to_array(self.floor.get(\"pos\")) + table_height", "title": ""}
{"_id": "d13930", "text": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"React to a docstring event and append contracts to it.\"\"\"\n    # pylint: disable=unused-argument\n    # pylint: disable=too-many-arguments\n    lines.extend(_format_contracts(what=what, obj=obj))", "title": ""}
{"_id": "d13931", "text": "def python_mime(fn):\n    \"\"\"\n    Decorator, which adds correct MIME type for python source to the decorated\n    bottle API function.\n    \"\"\"\n    @wraps(fn)\n    def python_mime_decorator(*args, **kwargs):\n        response.content_type = \"text/x-python\"\n\n        return fn(*args, **kwargs)\n\n    return python_mime_decorator", "title": ""}
{"_id": "d13932", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d13933", "text": "def __run(self):\n    \"\"\"Hacked run function, which installs the trace.\"\"\"\n    sys.settrace(self.globaltrace)\n    self.__run_backup()\n    self.run = self.__run_backup", "title": ""}
{"_id": "d13934", "text": "def _read_json_file(self, json_file):\n        \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n        self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n        with open(json_file, 'r') as f:\n            return json.load(f, object_pairs_hook=OrderedDict)", "title": ""}
{"_id": "d13935", "text": "def _column_resized(self, col, old_width, new_width):\n        \"\"\"Update the column width.\"\"\"\n        self.dataTable.setColumnWidth(col, new_width)\n        self._update_layout()", "title": ""}
{"_id": "d13936", "text": "def print_tree(self, indent=2):\n        \"\"\" print_tree: prints out structure of tree\n            Args: indent (int): What level of indentation at which to start printing\n            Returns: None\n        \"\"\"\n        config.LOGGER.info(\"{indent}{data}\".format(indent=\"   \" * indent, data=str(self)))\n        for child in self.children:\n            child.print_tree(indent + 1)", "title": ""}
{"_id": "d13937", "text": "def sorted_index(values, x):\n    \"\"\"\n    For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n    :param values: list\n    :param x: item\n    :return: integer index\n    \"\"\"\n    i = bisect_left(values, x)\n    j = bisect_right(values, x)\n    return values[i:j].index(x) + i", "title": ""}
{"_id": "d13938", "text": "def register_view(self, view):\n        \"\"\"Register callbacks for button press events and selection changed\"\"\"\n        super(ListViewController, self).register_view(view)\n        self.tree_view.connect('button_press_event', self.mouse_click)", "title": ""}
{"_id": "d13939", "text": "def make_prefixed_stack_name(prefix, template_path):\n    \"\"\"\n\n    :param prefix:\n    :param template_path:\n    \"\"\"\n    parts = os.path.basename(template_path).split('-')\n    parts = parts if len(parts) == 1 else parts[:-1]\n    return ('%s-%s' % (prefix, '-'.join(parts))).split('.')[0]", "title": ""}
{"_id": "d13940", "text": "def _trim(self, somestr):\n        \"\"\" Trim left-right given string \"\"\"\n        tmp = RE_LSPACES.sub(\"\", somestr)\n        tmp = RE_TSPACES.sub(\"\", tmp)\n        return str(tmp)", "title": ""}
{"_id": "d13941", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d13942", "text": "def drop_bad_characters(text):\n    \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n    also any whitespace characters that aren't space.\n\n    :arg str text: the text to fix\n\n    :returns: text with all bad characters dropped\n\n    \"\"\"\n    # Strip all non-ascii and non-printable characters\n    text = ''.join([c for c in text if c in ALLOWED_CHARS])\n    return text", "title": ""}
{"_id": "d13943", "text": "def cint8_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):\n        return np.fromiter(cptr, dtype=np.int8, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d13944", "text": "def round_sig(x, sig):\n    \"\"\"Round the number to the specified number of significant figures\"\"\"\n    return round(x, sig - int(floor(log10(abs(x)))) - 1)", "title": ""}
{"_id": "d13945", "text": "def append_position_to_token_list(token_list):\n    \"\"\"Converts a list of Token into a list of Token, asuming size == 1\"\"\"\n    return [PositionToken(value.content, value.gd, index, index+1) for (index, value) in enumerate(token_list)]", "title": ""}
{"_id": "d13946", "text": "def _tuple_repr(data):\n    \"\"\"Return a repr() for a list/tuple\"\"\"\n    if len(data) == 1:\n        return \"(%s,)\" % rpr(data[0])\n    else:\n        return \"(%s)\" % \", \".join([rpr(x) for x in data])", "title": ""}
{"_id": "d13947", "text": "def logout(cache):\n    \"\"\"\n    Logs out the current session by removing it from the cache. This is\n    expected to only occur when a session has\n    \"\"\"\n    cache.set(flask.session['auth0_key'], None)\n    flask.session.clear()\n    return True", "title": ""}
{"_id": "d13948", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d13949", "text": "def MatrixInverse(a, adj):\n    \"\"\"\n    Matrix inversion op.\n    \"\"\"\n    return np.linalg.inv(a if not adj else _adjoint(a)),", "title": ""}
{"_id": "d13950", "text": "def on_success(self, fn, *args, **kwargs):\n        \"\"\"\n        Call the given callback if or when the connected deferred succeeds.\n\n        \"\"\"\n\n        self._callbacks.append((fn, args, kwargs))\n\n        result = self._resulted_in\n        if result is not _NOTHING_YET:\n            self._succeed(result=result)", "title": ""}
{"_id": "d13951", "text": "def cross_product_matrix(vec):\n    \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n    return np.array([[0, -vec[2], vec[1]],\n                     [vec[2], 0, -vec[0]],\n                     [-vec[1], vec[0], 0]])", "title": ""}
{"_id": "d13952", "text": "def _to_array(value):\n    \"\"\"As a convenience, turn Python lists and tuples into NumPy arrays.\"\"\"\n    if isinstance(value, (tuple, list)):\n        return array(value)\n    elif isinstance(value, (float, int)):\n        return np.float64(value)\n    else:\n        return value", "title": ""}
{"_id": "d13953", "text": "def MatrixInverse(a, adj):\n    \"\"\"\n    Matrix inversion op.\n    \"\"\"\n    return np.linalg.inv(a if not adj else _adjoint(a)),", "title": ""}
{"_id": "d13954", "text": "def string_to_float_list(string_var):\n        \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n        try:\n            return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n        except:\n            return [float(s) for s in string_var.strip('[').strip(']').split(',')]", "title": ""}
{"_id": "d13955", "text": "def _get_local_ip():\n        \"\"\"\n        Get the local ip of this device\n\n        :return: Ip of this computer\n        :rtype: str\n        \"\"\"\n        return set([x[4][0] for x in socket.getaddrinfo(\n            socket.gethostname(),\n            80,\n            socket.AF_INET\n        )]).pop()", "title": ""}
{"_id": "d13956", "text": "def _interval_to_bound_points(array):\n    \"\"\"\n    Helper function which returns an array\n    with the Intervals' boundaries.\n    \"\"\"\n\n    array_boundaries = np.array([x.left for x in array])\n    array_boundaries = np.concatenate(\n        (array_boundaries, np.array([array[-1].right])))\n\n    return array_boundaries", "title": ""}
{"_id": "d13957", "text": "def log(self, level, msg=None, *args, **kwargs):\n        \"\"\"Writes log out at any arbitray level.\"\"\"\n\n        return self._log(level, msg, args, kwargs)", "title": ""}
{"_id": "d13958", "text": "def _unordered_iterator(self):\n        \"\"\"\n        Return the value of each QuerySet, but also add the '#' property to each\n        return item.\n        \"\"\"\n        for i, qs in zip(self._queryset_idxs, self._querysets):\n            for item in qs:\n                setattr(item, '#', i)\n                yield item", "title": ""}
{"_id": "d13959", "text": "def boolean(value):\n    \"\"\"\n    Configuration-friendly boolean type converter.\n\n    Supports both boolean-valued and string-valued inputs (e.g. from env vars).\n\n    \"\"\"\n    if isinstance(value, bool):\n        return value\n\n    if value == \"\":\n        return False\n\n    return strtobool(value)", "title": ""}
{"_id": "d13960", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d13961", "text": "def isfunc(x):\n    \"\"\"\n    Returns `True` if the given value is a function or method object.\n\n    Arguments:\n        x (mixed): value to check.\n\n    Returns:\n        bool\n    \"\"\"\n    return any([\n        inspect.isfunction(x) and not asyncio.iscoroutinefunction(x),\n        inspect.ismethod(x) and not asyncio.iscoroutinefunction(x)\n    ])", "title": ""}
{"_id": "d13962", "text": "def jaccard(c_1, c_2):\n    \"\"\"\n    Calculates the Jaccard similarity between two sets of nodes. Called by mroc.\n\n    Inputs:  - c_1: Community (set of nodes) 1.\n             - c_2: Community (set of nodes) 2.\n\n    Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.\n    \"\"\"\n    nom = np.intersect1d(c_1, c_2).size\n    denom = np.union1d(c_1, c_2).size\n    return nom/denom", "title": ""}
{"_id": "d13963", "text": "def reload_localzone():\n    \"\"\"Reload the cached localzone. You need to call this if the timezone has changed.\"\"\"\n    global _cache_tz\n    _cache_tz = pytz.timezone(get_localzone_name())\n    utils.assert_tz_offset(_cache_tz)\n    return _cache_tz", "title": ""}
{"_id": "d13964", "text": "def levenshtein_distance_metric(a, b):\n    \"\"\" 1 - farthest apart (same number of words, all diff). 0 - same\"\"\"\n    return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1)))", "title": ""}
{"_id": "d13965", "text": "def __init__(self):\n        \"\"\"Initialize the state of the object\"\"\"\n        self.state = self.STATE_INITIALIZING\n        self.state_start = time.time()", "title": ""}
{"_id": "d13966", "text": "def json_dumps(self, obj):\n        \"\"\"Serializer for consistency\"\"\"\n        return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))", "title": ""}
{"_id": "d13967", "text": "def uint32_to_uint8(cls, img):\n        \"\"\"\n        Cast uint32 RGB image to 4 uint8 channels.\n        \"\"\"\n        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))", "title": ""}
{"_id": "d13968", "text": "def json_template(data, template_name, template_context):\n    \"\"\"Old style, use JSONTemplateResponse instead of this.\n    \"\"\"\n    html = render_to_string(template_name, template_context)\n    data = data or {}\n    data['html'] = html\n    return HttpResponse(json_encode(data), content_type='application/json')", "title": ""}
{"_id": "d13969", "text": "def endline_semicolon_check(self, original, loc, tokens):\n        \"\"\"Check for semicolons at the end of lines.\"\"\"\n        return self.check_strict(\"semicolon at end of line\", original, loc, tokens)", "title": ""}
{"_id": "d13970", "text": "def timestamping_validate(data, schema):\n    \"\"\"\n    Custom validation function which inserts a timestamp for when the\n    validation occurred\n    \"\"\"\n    jsonschema.validate(data, schema)\n    data['timestamp'] = str(time.time())", "title": ""}
{"_id": "d13971", "text": "def get_uniques(l):\n    \"\"\" Returns a list with no repeated elements.\n    \"\"\"\n    result = []\n\n    for i in l:\n        if i not in result:\n            result.append(i)\n\n    return result", "title": ""}
{"_id": "d13972", "text": "def _spawn_kafka_consumer_thread(self):\n        \"\"\"Spawns a kafka continuous consumer thread\"\"\"\n        self.logger.debug(\"Spawn kafka consumer thread\"\"\")\n        self._consumer_thread = Thread(target=self._consumer_loop)\n        self._consumer_thread.setDaemon(True)\n        self._consumer_thread.start()", "title": ""}
{"_id": "d13973", "text": "def assert_error(text, check, n=1):\n    \"\"\"Assert that text has n errors of type check.\"\"\"\n    assert_error.description = \"No {} error for '{}'\".format(check, text)\n    assert(check in [error[0] for error in lint(text)])", "title": ""}
{"_id": "d13974", "text": "def send(self, topic, *args, **kwargs):\n        \"\"\"\n        Appends the prefix to the topic before sendingf\n        \"\"\"\n        prefix_topic = self.heroku_kafka.prefix_topic(topic)\n        return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs)", "title": ""}
{"_id": "d13975", "text": "def assert_error(text, check, n=1):\n    \"\"\"Assert that text has n errors of type check.\"\"\"\n    assert_error.description = \"No {} error for '{}'\".format(check, text)\n    assert(check in [error[0] for error in lint(text)])", "title": ""}
{"_id": "d13976", "text": "def remove_rows_matching(df, column, match):\n    \"\"\"\n    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\n    \"\"\"\n    df = df.copy()\n    mask = df[column].values != match\n    return df.iloc[mask, :]", "title": ""}
{"_id": "d13977", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d13978", "text": "def get_known_read_position(fp, buffered=True):\n    \"\"\" \n    Return a position in a file which is known to be read & handled.\n    It assumes a buffered file and streaming processing. \n    \"\"\"\n    buffer_size = io.DEFAULT_BUFFER_SIZE if buffered else 0\n    return max(fp.tell() - buffer_size, 0)", "title": ""}
{"_id": "d13979", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d13980", "text": "def kubectl(*args, input=None, **flags):\n    \"\"\"Simple wrapper to kubectl.\"\"\"\n    # Build command line call.\n    line = ['kubectl'] + list(args)\n    line = line + get_flag_args(**flags)\n    if input is not None:\n        line = line + ['-f', '-']\n    # Run subprocess\n    output = subprocess.run(\n        line,\n        input=input,\n        capture_output=True,\n        text=True\n    )\n    return output", "title": ""}
{"_id": "d13981", "text": "def _get_context(argspec, kwargs):\n    \"\"\"Prepare a context for the serialization.\n\n    :param argspec: The argspec of the serialization function.\n    :param kwargs: Dict with context\n    :return: Keywords arguments that function can accept.\n    \"\"\"\n    if argspec.keywords is not None:\n        return kwargs\n    return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs)", "title": ""}
{"_id": "d13982", "text": "def straight_line_show(title, length=100, linestyle=\"=\", pad=0):\n        \"\"\"Print a formatted straight line.\n        \"\"\"\n        print(StrTemplate.straight_line(\n            title=title, length=length, linestyle=linestyle, pad=pad))", "title": ""}
{"_id": "d13983", "text": "def __init__(self,operand,operator,**args):\n        \"\"\"\n        Accepts a NumberGenerator operand, an operator, and\n        optional arguments to be provided to the operator when calling\n        it on the operand.\n        \"\"\"\n        # Note that it's currently not possible to set\n        # parameters in the superclass when creating an instance,\n        # because **args is used by this class itself.\n        super(UnaryOperator,self).__init__()\n\n        self.operand=operand\n        self.operator=operator\n        self.args=args", "title": ""}
{"_id": "d13984", "text": "def extract_all(zipfile, dest_folder):\n    \"\"\"\n    reads the zip file, determines compression\n    and unzips recursively until source files \n    are extracted \n    \"\"\"\n    z = ZipFile(zipfile)\n    print(z)\n    z.extract(dest_folder)", "title": ""}
{"_id": "d13985", "text": "def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,\n                                          catch_exceptions=()):\n  \"\"\"Executes a method until the retry limit is hit or not None is returned.\"\"\"\n  return retry_until_valid_or_limit_reached(\n      method, limit, lambda x: x is not None, sleep_s, catch_exceptions)", "title": ""}
{"_id": "d13986", "text": "def recursively_update(d, d2):\n  \"\"\"dict.update but which merges child dicts (dict2 takes precedence where there's conflict).\"\"\"\n  for k, v in d2.items():\n    if k in d:\n      if isinstance(v, dict):\n        recursively_update(d[k], v)\n        continue\n    d[k] = v", "title": ""}
{"_id": "d13987", "text": "def _linear_interpolation(x, X, Y):\n    \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n    \"\"\"\n    return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "title": ""}
{"_id": "d13988", "text": "def increment(self, amount=1):\n        \"\"\"\n        Increments the main progress bar by amount.\n        \"\"\"\n        self._primaryProgressBar.setValue(self.value() + amount)\n        QApplication.instance().processEvents()", "title": ""}
{"_id": "d13989", "text": "def get_tail(self):\n        \"\"\"Gets tail\n\n        :return: Tail of linked list\n        \"\"\"\n        node = self.head\n        last_node = self.head\n\n        while node is not None:\n            last_node = node\n            node = node.next_node\n\n        return last_node", "title": ""}
{"_id": "d13990", "text": "def safe_url(url):\n    \"\"\"Remove password from printed connection URLs.\"\"\"\n    parsed = urlparse(url)\n    if parsed.password is not None:\n        pwd = ':%s@' % parsed.password\n        url = url.replace(pwd, ':*****@')\n    return url", "title": ""}
{"_id": "d13991", "text": "def put_pidfile( pidfile_path, pid ):\n    \"\"\"\n    Put a PID into a pidfile\n    \"\"\"\n    with open( pidfile_path, \"w\" ) as f:\n        f.write(\"%s\" % pid)\n        os.fsync(f.fileno())\n\n    return", "title": ""}
{"_id": "d13992", "text": "def get(url):\n    \"\"\"Recieving the JSON file from uulm\"\"\"\n    response = urllib.request.urlopen(url)\n    data = response.read()\n    data = data.decode(\"utf-8\")\n    data = json.loads(data)\n    return data", "title": ""}
{"_id": "d13993", "text": "def get_services():\n        \"\"\"\n        Retrieve a list of all system services.\n\n        @see: L{get_active_services},\n            L{start_service}, L{stop_service},\n            L{pause_service}, L{resume_service}\n\n        @rtype:  list( L{win32.ServiceStatusProcessEntry} )\n        @return: List of service status descriptors.\n        \"\"\"\n        with win32.OpenSCManager(\n            dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE\n            ) as hSCManager:\n                try:\n                    return win32.EnumServicesStatusEx(hSCManager)\n                except AttributeError:\n                    return win32.EnumServicesStatus(hSCManager)", "title": ""}
{"_id": "d13994", "text": "def addClassKey(self, klass, key, obj):\n        \"\"\"\n        Adds an object to the collection, based on klass and key.\n\n        @param klass: The class of the object.\n        @param key: The datastore key of the object.\n        @param obj: The loaded instance from the datastore.\n        \"\"\"\n        d = self._getClass(klass)\n\n        d[key] = obj", "title": ""}
{"_id": "d13995", "text": "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n    \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n    return maybe_list and any(is_multiline(item) for item in maybe_list)", "title": ""}
{"_id": "d13996", "text": "def _split(value):\n    \"\"\"Split input/output value into two values.\"\"\"\n    if isinstance(value, str):\n        # iterable, but not meant for splitting\n        return value, value\n    try:\n        invalue, outvalue = value\n    except TypeError:\n        invalue = outvalue = value\n    except ValueError:\n        raise ValueError(\"Only single values and pairs are allowed\")\n    return invalue, outvalue", "title": ""}
{"_id": "d13997", "text": "def from_file(filename):\n    \"\"\"\n    load an nparray object from a json filename\n\n    @parameter str filename: path to the file\n    \"\"\"\n    f = open(filename, 'r')\n    j = json.load(f)\n    f.close()\n\n    return from_dict(j)", "title": ""}
{"_id": "d13998", "text": "def __add__(self, other):\n        \"\"\"Handle the `+` operator.\"\"\"\n        return self._handle_type(other)(self.value + other.value)", "title": ""}
{"_id": "d13999", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d14000", "text": "def get_soup(page=''):\n    \"\"\"\n    Returns a bs4 object of the page requested\n    \"\"\"\n    content = requests.get('%s/%s' % (BASE_URL, page)).text\n    return BeautifulSoup(content)", "title": ""}
{"_id": "d14001", "text": "def log_all(self, file):\n        \"\"\"Log all data received from RFLink to file.\"\"\"\n        global rflink_log\n        if file == None:\n            rflink_log = None\n        else:\n            log.debug('logging to: %s', file)\n            rflink_log = open(file, 'a')", "title": ""}
{"_id": "d14002", "text": "def generate_uuid():\n    \"\"\"Generate a UUID.\"\"\"\n    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)\n    return r_uuid.decode().replace('=', '')", "title": ""}
{"_id": "d14003", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d14004", "text": "def generate_uuid():\n    \"\"\"Generate a UUID.\"\"\"\n    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)\n    return r_uuid.decode().replace('=', '')", "title": ""}
{"_id": "d14005", "text": "def c2u(name):\n    \"\"\"Convert camelCase (used in PHP) to Python-standard snake_case.\n\n    Src:\n    https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case\n\n    Parameters\n    ----------\n    name: A function or variable name in camelCase\n\n    Returns\n    -------\n    str: The name in snake_case\n\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n    s1 = re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n    return s1", "title": ""}
{"_id": "d14006", "text": "def is_valid_email(email):\n    \"\"\"\n    Check if email is valid\n    \"\"\"\n    pattern = re.compile(r'[\\w\\.-]+@[\\w\\.-]+[.]\\w+')\n    return bool(pattern.match(email))", "title": ""}
{"_id": "d14007", "text": "def _interval_to_bound_points(array):\n    \"\"\"\n    Helper function which returns an array\n    with the Intervals' boundaries.\n    \"\"\"\n\n    array_boundaries = np.array([x.left for x in array])\n    array_boundaries = np.concatenate(\n        (array_boundaries, np.array([array[-1].right])))\n\n    return array_boundaries", "title": ""}
{"_id": "d14008", "text": "def validate_email(email):\n    \"\"\"\n    Validates an email address\n    Source: Himanshu Shankar (https://github.com/iamhssingh)\n    Parameters\n    ----------\n    email: str\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    from django.core.validators import validate_email\n    from django.core.exceptions import ValidationError\n    try:\n        validate_email(email)\n        return True\n    except ValidationError:\n        return False", "title": ""}
{"_id": "d14009", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d14010", "text": "def parse(self, s):\n        \"\"\"\n        Parses a date string formatted like ``YYYY-MM-DD``.\n        \"\"\"\n        return datetime.datetime.strptime(s, self.date_format).date()", "title": ""}
{"_id": "d14011", "text": "def clear_caches():\n    \"\"\"Jinja2 keeps internal caches for environments and lexers.  These are\n    used so that Jinja2 doesn't have to recreate environments and lexers all\n    the time.  Normally you don't have to care about that but if you are\n    measuring memory consumption you may want to clean the caches.\n    \"\"\"\n    from jinja2.environment import _spontaneous_environments\n    from jinja2.lexer import _lexer_cache\n    _spontaneous_environments.clear()\n    _lexer_cache.clear()", "title": ""}
{"_id": "d14012", "text": "def __init__(self, response):\n        \"\"\"Initialize a ResponseException instance.\n\n        :param response: A requests.response instance.\n\n        \"\"\"\n        self.response = response\n        super(ResponseException, self).__init__(\n            \"received {} HTTP response\".format(response.status_code)\n        )", "title": ""}
{"_id": "d14013", "text": "def venv():\n    \"\"\"Install venv + deps.\"\"\"\n    try:\n        import virtualenv  # NOQA\n    except ImportError:\n        sh(\"%s -m pip install virtualenv\" % PYTHON)\n    if not os.path.isdir(\"venv\"):\n        sh(\"%s -m virtualenv venv\" % PYTHON)\n    sh(\"venv\\\\Scripts\\\\pip install -r %s\" % (REQUIREMENTS_TXT))", "title": ""}
{"_id": "d14014", "text": "def stringify_dict_contents(dct):\n    \"\"\"Turn dict keys and values into native strings.\"\"\"\n    return {\n        str_if_nested_or_str(k): str_if_nested_or_str(v)\n        for k, v in dct.items()\n    }", "title": ""}
{"_id": "d14015", "text": "def check_alert(self, text):\n    \"\"\"\n    Assert an alert is showing with the given text.\n    \"\"\"\n\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        # PhantomJS is kinda poor\n        pass", "title": ""}
{"_id": "d14016", "text": "def pdf(x, mu, std):\n    \"\"\"Probability density function (normal distribution)\"\"\"\n    return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))", "title": ""}
{"_id": "d14017", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d14018", "text": "def out(self, output, newline=True):\n        \"\"\"Outputs a string to the console (stdout).\"\"\"\n        click.echo(output, nl=newline)", "title": ""}
{"_id": "d14019", "text": "def check_by_selector(self, selector):\n    \"\"\"Check the checkbox matching the CSS selector.\"\"\"\n    elem = find_element_by_jquery(world.browser, selector)\n    if not elem.is_selected():\n        elem.click()", "title": ""}
{"_id": "d14020", "text": "def timestamp_to_datetime(timestamp):\n    \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n    from datetime import datetime, timedelta\n    obj = datetime.fromtimestamp(timestamp[0])\n    return obj + timedelta(microseconds=int(timestamp[1]))", "title": ""}
{"_id": "d14021", "text": "def check_by_selector(self, selector):\n    \"\"\"Check the checkbox matching the CSS selector.\"\"\"\n    elem = find_element_by_jquery(world.browser, selector)\n    if not elem.is_selected():\n        elem.click()", "title": ""}
{"_id": "d14022", "text": "def map(cls, iterable, func, *a, **kw):\n    \"\"\"\n    Iterable-first replacement of Python's built-in `map()` function.\n    \"\"\"\n\n    return cls(func(x, *a, **kw) for x in iterable)", "title": ""}
{"_id": "d14023", "text": "def _close_websocket(self):\n        \"\"\"Closes the websocket connection.\"\"\"\n        close_method = getattr(self._websocket, \"close\", None)\n        if callable(close_method):\n            asyncio.ensure_future(close_method(), loop=self._event_loop)\n        self._websocket = None\n        self._dispatch_event(event=\"close\")", "title": ""}
{"_id": "d14024", "text": "def _group_dict_set(iterator):\n    \"\"\"Make a dict that accumulates the values for each key in an iterator of doubles.\n\n    :param iter[tuple[A,B]] iterator: An iterator\n    :rtype: dict[A,set[B]]\n    \"\"\"\n    d = defaultdict(set)\n    for key, value in iterator:\n        d[key].add(value)\n    return dict(d)", "title": ""}
{"_id": "d14025", "text": "def _increase_file_handle_limit():\n    \"\"\"Raise the open file handles permitted by the Dusty daemon process\n    and its child processes. The number we choose here needs to be within\n    the OS X default kernel hard limit, which is 10240.\"\"\"\n    logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT))\n    resource.setrlimit(resource.RLIMIT_NOFILE,\n                       (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))", "title": ""}
{"_id": "d14026", "text": "def asMaskedArray(self):\n        \"\"\" Creates converts to a masked array\n        \"\"\"\n        return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)", "title": ""}
{"_id": "d14027", "text": "def acquire_nix(lock_file):  # pragma: no cover\n    \"\"\"Acquire a lock file on linux or osx.\"\"\"\n    fd = os.open(lock_file, OPEN_MODE)\n\n    try:\n        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n    except (IOError, OSError):\n        os.close(fd)\n    else:\n        return fd", "title": ""}
{"_id": "d14028", "text": "def array(self):\n        \"\"\"\n        return the underlying numpy array\n        \"\"\"\n        return np.arange(self.start, self.stop, self.step)", "title": ""}
{"_id": "d14029", "text": "def __Logout(si):\n   \"\"\"\n   Disconnect (logout) service instance\n   @param si: Service instance (returned from Connect)\n   \"\"\"\n   try:\n      if si:\n         content = si.RetrieveContent()\n         content.sessionManager.Logout()\n   except Exception as e:\n      pass", "title": ""}
{"_id": "d14030", "text": "def is_square_matrix(mat):\n    \"\"\"Test if an array is a square matrix.\"\"\"\n    mat = np.array(mat)\n    if mat.ndim != 2:\n        return False\n    shape = mat.shape\n    return shape[0] == shape[1]", "title": ""}
{"_id": "d14031", "text": "def save_dict_to_file(filename, dictionary):\n  \"\"\"Saves dictionary as CSV file.\"\"\"\n  with open(filename, 'w') as f:\n    writer = csv.writer(f)\n    for k, v in iteritems(dictionary):\n      writer.writerow([str(k), str(v)])", "title": ""}
{"_id": "d14032", "text": "def argmax(l,f=None):\n    \"\"\"http://stackoverflow.com/questions/5098580/implementing-argmax-in-python\"\"\"\n    if f:\n        l = [f(i) for i in l]\n    return max(enumerate(l), key=lambda x:x[1])[0]", "title": ""}
{"_id": "d14033", "text": "def _write_color_colorama (fp, text, color):\n    \"\"\"Colorize text with given color.\"\"\"\n    foreground, background, style = get_win_color(color)\n    colorama.set_console(foreground=foreground, background=background,\n      style=style)\n    fp.write(text)\n    colorama.reset_console()", "title": ""}
{"_id": "d14034", "text": "def SegmentMax(a, ids):\n    \"\"\"\n    Segmented max op.\n    \"\"\"\n    func = lambda idxs: np.amax(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d14035", "text": "def write_fits(data, header, file_name):\n    \"\"\"\n    Combine data and a fits header to write a fits file.\n\n    Parameters\n    ----------\n    data : numpy.ndarray\n        The data to be written.\n\n    header : astropy.io.fits.hduheader\n        The header for the fits file.\n\n    file_name : string\n        The file to write\n\n    Returns\n    -------\n    None\n    \"\"\"\n    hdu = fits.PrimaryHDU(data)\n    hdu.header = header\n    hdulist = fits.HDUList([hdu])\n    hdulist.writeto(file_name, overwrite=True)\n    logging.info(\"Wrote {0}\".format(file_name))\n    return", "title": ""}
{"_id": "d14036", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d14037", "text": "def write_string(value, buff, byteorder='big'):\n    \"\"\"Write a string to a file-like object.\"\"\"\n    data = value.encode('utf-8')\n    write_numeric(USHORT, len(data), buff, byteorder)\n    buff.write(data)", "title": ""}
{"_id": "d14038", "text": "def get_file_md5sum(path):\n    \"\"\"Calculate the MD5 hash for a file.\"\"\"\n    with open(path, 'rb') as fh:\n        h = str(hashlib.md5(fh.read()).hexdigest())\n    return h", "title": ""}
{"_id": "d14039", "text": "def set_icon(self, bmp):\n        \"\"\"Sets main window icon to given wx.Bitmap\"\"\"\n\n        _icon = wx.EmptyIcon()\n        _icon.CopyFromBitmap(bmp)\n        self.SetIcon(_icon)", "title": ""}
{"_id": "d14040", "text": "def start_task(self, task):\n        \"\"\"Begin logging of a task\n\n        Stores the time this task was started in order to return\n        time lapsed when `complete_task` is called.\n\n        Parameters\n        ----------\n        task : str\n            Name of the task to be started\n        \"\"\"\n        self.info(\"Calculating {}...\".format(task))\n        self.tasks[task] = self.timer()", "title": ""}
{"_id": "d14041", "text": "def __call__(self, xy):\n        \"\"\"Project x and y\"\"\"\n        x, y = xy\n        return (self.x(x), self.y(y))", "title": ""}
{"_id": "d14042", "text": "def merge(self, obj):\n        \"\"\"This function merge another object's values with this instance\n\n        :param obj: An object to be merged with into this layer\n        :type obj: object\n        \"\"\"\n        for attribute in dir(obj):\n            if '__' in attribute:\n                continue\n            setattr(self, attribute, getattr(obj, attribute))", "title": ""}
{"_id": "d14043", "text": "def elXpath(self, xpath, dom=None):\n        \"\"\"check if element is present by css\"\"\"\n        if dom is None:\n            dom = self.browser\n        return expect(dom.is_element_present_by_xpath, args=[xpath])", "title": ""}
{"_id": "d14044", "text": "def dict_merge(set1, set2):\n    \"\"\"Joins two dictionaries.\"\"\"\n    return dict(list(set1.items()) + list(set2.items()))", "title": ""}
{"_id": "d14045", "text": "def serialize_yaml_tofile(filename, resource):\n    \"\"\"\n    Serializes a K8S resource to YAML-formatted file.\n    \"\"\"\n    stream = file(filename, \"w\")\n    yaml.dump(resource, stream, default_flow_style=False)", "title": ""}
{"_id": "d14046", "text": "def fn_min(self, a, axis=None):\n        \"\"\"\n        Return the minimum of an array, ignoring any NaNs.\n\n        :param a: The array.\n        :return: The minimum value of the array.\n        \"\"\"\n\n        return numpy.nanmin(self._to_ndarray(a), axis=axis)", "title": ""}
{"_id": "d14047", "text": "def guess_title(basename):\n    \"\"\" Attempt to guess the title from the filename \"\"\"\n\n    base, _ = os.path.splitext(basename)\n    return re.sub(r'[ _-]+', r' ', base).title()", "title": ""}
{"_id": "d14048", "text": "def _obj_cursor_to_dictionary(self, cursor):\n        \"\"\"Handle conversion of pymongo cursor into a JSON object formatted for UI consumption\n\n        :param dict cursor: a mongo document that should be converted to primitive types for the client code\n        :returns: a primitive dictionary\n        :rtype: dict\n        \"\"\"\n        if not cursor:\n            return cursor\n\n        cursor = json.loads(json.dumps(cursor, cls=BSONEncoder))\n\n        if cursor.get(\"_id\"):\n            cursor[\"id\"] = cursor.get(\"_id\")\n            del cursor[\"_id\"]\n\n        return cursor", "title": ""}
{"_id": "d14049", "text": "def dict_to_html_attrs(dict_):\n    \"\"\"\n    Banana banana\n    \"\"\"\n    res = ' '.join('%s=\"%s\"' % (k, v) for k, v in dict_.items())\n    return res", "title": ""}
{"_id": "d14050", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d14051", "text": "def extract_module_locals(depth=0):\n    \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n    f = sys._getframe(depth + 1)\n    global_ns = f.f_globals\n    module = sys.modules[global_ns['__name__']]\n    return (module, f.f_locals)", "title": ""}
{"_id": "d14052", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d14053", "text": "def astype(array, y):\n  \"\"\"A functional form of the `astype` method.\n\n  Args:\n    array: The array or number to cast.\n    y: An array or number, as the input, whose type should be that of array.\n\n  Returns:\n    An array or number with the same dtype as `y`.\n  \"\"\"\n  if isinstance(y, autograd.core.Node):\n    return array.astype(numpy.array(y.value).dtype)\n  return array.astype(numpy.array(y).dtype)", "title": ""}
{"_id": "d14054", "text": "def dict_merge(set1, set2):\n    \"\"\"Joins two dictionaries.\"\"\"\n    return dict(list(set1.items()) + list(set2.items()))", "title": ""}
{"_id": "d14055", "text": "def save(self):\n        \"\"\"save the current session\n        override, if session was saved earlier\"\"\"\n        if self.path:\n            self._saveState(self.path)\n        else:\n            self.saveAs()", "title": ""}
{"_id": "d14056", "text": "def user_return(self, frame, return_value):\n        \"\"\"This function is called when a return trap is set here.\"\"\"\n        pdb.Pdb.user_return(self, frame, return_value)", "title": ""}
{"_id": "d14057", "text": "def move_up(lines=1, file=sys.stdout):\n    \"\"\" Move the cursor up a number of lines.\n\n        Esc[ValueA:\n        Moves the cursor up by the specified number of lines without changing\n        columns. If the cursor is already on the top line, ANSI.SYS ignores\n        this sequence.\n    \"\"\"\n    move.up(lines).write(file=file)", "title": ""}
{"_id": "d14058", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d14059", "text": "def move_up(lines=1, file=sys.stdout):\n    \"\"\" Move the cursor up a number of lines.\n\n        Esc[ValueA:\n        Moves the cursor up by the specified number of lines without changing\n        columns. If the cursor is already on the top line, ANSI.SYS ignores\n        this sequence.\n    \"\"\"\n    move.up(lines).write(file=file)", "title": ""}
{"_id": "d14060", "text": "def get_url_args(url):\n    \"\"\" Returns a dictionary from a URL params \"\"\"\n    url_data = urllib.parse.urlparse(url)\n    arg_dict = urllib.parse.parse_qs(url_data.query)\n    return arg_dict", "title": ""}
{"_id": "d14061", "text": "def _parse_array(self, tensor_proto):\n        \"\"\"Grab data in TensorProto and convert to numpy array.\"\"\"\n        try:\n            from onnx.numpy_helper import to_array\n        except ImportError as e:\n            raise ImportError(\"Unable to import onnx which is required {}\".format(e))\n        np_array = to_array(tensor_proto).reshape(tuple(tensor_proto.dims))\n        return mx.nd.array(np_array)", "title": ""}
{"_id": "d14062", "text": "def list2dict(list_of_options):\n    \"\"\"Transforms a list of 2 element tuples to a dictionary\"\"\"\n    d = {}\n    for key, value in list_of_options:\n        d[key] = value\n    return d", "title": ""}
{"_id": "d14063", "text": "def unit_ball_L2(shape):\n  \"\"\"A tensorflow variable tranfomed to be constrained in a L2 unit ball.\n\n  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n  they are strong attacks. We are not yet confident in this code.\n  \"\"\"\n  x = tf.Variable(tf.zeros(shape))\n  return constrain_L2(x)", "title": ""}
{"_id": "d14064", "text": "def to_dicts(recarray):\n    \"\"\"convert record array to a dictionaries\"\"\"\n    for rec in recarray:\n        yield dict(zip(recarray.dtype.names, rec.tolist()))", "title": ""}
{"_id": "d14065", "text": "def to_distribution_values(self, values):\n        \"\"\"\n        Returns numpy array of natural logarithms of ``values``.\n        \"\"\"\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            # avoid RuntimeWarning: divide by zero encountered in log\n            return numpy.log(values)", "title": ""}
{"_id": "d14066", "text": "def dt_to_ts(value):\n    \"\"\" If value is a datetime, convert to timestamp \"\"\"\n    if not isinstance(value, datetime):\n        return value\n    return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0", "title": ""}
{"_id": "d14067", "text": "def log_loss(preds, labels):\n    \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n    log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n    return -log_likelihood", "title": ""}
{"_id": "d14068", "text": "def filehash(path):\n    \"\"\"Make an MD5 hash of a file, ignoring any differences in line\n    ending characters.\"\"\"\n    with open(path, \"rU\") as f:\n        return md5(py3compat.str_to_bytes(f.read())).hexdigest()", "title": ""}
{"_id": "d14069", "text": "def full_like(array, value, dtype=None):\n    \"\"\" Create a shared memory array with the same shape and type as a given array, filled with `value`.\n    \"\"\"\n    shared = empty_like(array, dtype)\n    shared[:] = value\n    return shared", "title": ""}
{"_id": "d14070", "text": "def caller_locals():\n    \"\"\"Get the local variables in the caller's frame.\"\"\"\n    import inspect\n    frame = inspect.currentframe()\n    try:\n        return frame.f_back.f_back.f_locals\n    finally:\n        del frame", "title": ""}
{"_id": "d14071", "text": "def last_modified_date(filename):\n    \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n    mtime = os.path.getmtime(filename)\n    dt = datetime.datetime.utcfromtimestamp(mtime)\n    return dt.replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d14072", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d14073", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d14074", "text": "def normalize_path(path):\n    \"\"\"\n    Convert a path to its canonical, case-normalized, absolute version.\n\n    \"\"\"\n    return os.path.normcase(os.path.realpath(os.path.expanduser(path)))", "title": ""}
{"_id": "d14075", "text": "def enable_gtk3(self, app=None):\n        \"\"\"Enable event loop integration with Gtk3 (gir bindings).\n\n        Parameters\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        This methods sets the PyOS_InputHook for Gtk3, which allows\n        the Gtk3 to integrate with terminal based applications like\n        IPython.\n        \"\"\"\n        from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3\n        self.set_inputhook(create_inputhook_gtk3(self._stdin_file))\n        self._current_gui = GUI_GTK", "title": ""}
{"_id": "d14076", "text": "def v_normalize(v):\n    \"\"\"\n    Normalizes the given vector.\n    \n    The vector given may have any number of dimensions.\n    \"\"\"\n    vmag = v_magnitude(v)\n    return [ v[i]/vmag  for i in range(len(v)) ]", "title": ""}
{"_id": "d14077", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d14078", "text": "def _to_array(value):\n    \"\"\"As a convenience, turn Python lists and tuples into NumPy arrays.\"\"\"\n    if isinstance(value, (tuple, list)):\n        return array(value)\n    elif isinstance(value, (float, int)):\n        return np.float64(value)\n    else:\n        return value", "title": ""}
{"_id": "d14079", "text": "def getvariable(name):\n    \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n    import inspect\n    fr = inspect.currentframe()\n    try:\n        while fr:\n            fr = fr.f_back\n            vars = fr.f_locals\n            if name in vars:\n                return vars[name]\n    except:\n        pass\n    return None", "title": ""}
{"_id": "d14080", "text": "def _histplot_bins(column, bins=100):\n    \"\"\"Helper to get bins for histplot.\"\"\"\n    col_min = np.min(column)\n    col_max = np.max(column)\n    return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))", "title": ""}
{"_id": "d14081", "text": "def _is_target_a_directory(link, rel_target):\n\t\"\"\"\n\tIf creating a symlink from link to a target, determine if target\n\tis a directory (relative to dirname(link)).\n\t\"\"\"\n\ttarget = os.path.join(os.path.dirname(link), rel_target)\n\treturn os.path.isdir(target)", "title": ""}
{"_id": "d14082", "text": "def merge(self, other):\n        \"\"\"\n        Merge this range object with another (ranges need not overlap or abut).\n\n        :returns: a new Range object representing the interval containing both\n                  ranges.\n        \"\"\"\n        newstart = min(self._start, other.start)\n        newend = max(self._end, other.end)\n        return Range(newstart, newend)", "title": ""}
{"_id": "d14083", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d14084", "text": "def to_str(obj):\n    \"\"\"Attempts to convert given object to a string object\n    \"\"\"\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)", "title": ""}
{"_id": "d14085", "text": "def _array2cstr(arr):\n    \"\"\" Serializes a numpy array to a compressed base64 string \"\"\"\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())", "title": ""}
{"_id": "d14086", "text": "def one_hot(x, size, dtype=np.float32):\n  \"\"\"Make a n+1 dim one-hot array from n dim int-categorical array.\"\"\"\n  return np.array(x[..., np.newaxis] == np.arange(size), dtype)", "title": ""}
{"_id": "d14087", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d14088", "text": "def read_numpy(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]\n    return fh.read_array(dtype, count)", "title": ""}
{"_id": "d14089", "text": "def fetch(self):\n        \"\"\"\n        Fetch & return a new `Domain` object representing the domain's current\n        state\n\n        :rtype: Domain\n        :raises DOAPIError: if the API endpoint replies with an error (e.g., if\n            the domain no longer exists)\n        \"\"\"\n        api = self.doapi_manager\n        return api._domain(api.request(self.url)[\"domain\"])", "title": ""}
{"_id": "d14090", "text": "def run (self):\n        \"\"\"Handle keyboard interrupt and other errors.\"\"\"\n        try:\n            self.run_checked()\n        except KeyboardInterrupt:\n            thread.interrupt_main()\n        except Exception:\n            self.internal_error()", "title": ""}
{"_id": "d14091", "text": "def autoconvert(string):\n    \"\"\"Try to convert variables into datatypes.\"\"\"\n    for fn in (boolify, int, float):\n        try:\n            return fn(string)\n        except ValueError:\n            pass\n    return string", "title": ""}
{"_id": "d14092", "text": "def _stdin_ready_posix():\n    \"\"\"Return True if there's something to read on stdin (posix version).\"\"\"\n    infds, outfds, erfds = select.select([sys.stdin],[],[],0)\n    return bool(infds)", "title": ""}
{"_id": "d14093", "text": "def list_i2str(ilist):\n    \"\"\"\n    Convert an integer list into a string list.\n    \"\"\"\n    slist = []\n    for el in ilist:\n        slist.append(str(el))\n    return slist", "title": ""}
{"_id": "d14094", "text": "def askopenfilename(**kwargs):\n    \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n    try:\n        from Tkinter import Tk\n        import tkFileDialog as filedialog\n    except ImportError:\n        from tkinter import Tk, filedialog\n    root = Tk()\n    root.withdraw()\n    root.update()\n    filenames = filedialog.askopenfilename(**kwargs)\n    root.destroy()\n    return filenames", "title": ""}
{"_id": "d14095", "text": "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)", "title": ""}
{"_id": "d14096", "text": "def timedelta_seconds(timedelta):\n    \"\"\"Returns the total timedelta duration in seconds.\"\"\"\n    return (timedelta.total_seconds() if hasattr(timedelta, \"total_seconds\")\n            else timedelta.days * 24 * 3600 + timedelta.seconds +\n                 timedelta.microseconds / 1000000.)", "title": ""}
{"_id": "d14097", "text": "def load_image(fname):\n    \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n    with open(fname, \"rb\") as f:\n        i = Image.open(fname)\n        #i.load()\n        return i", "title": ""}
{"_id": "d14098", "text": "def re_raise(self):\n        \"\"\" Raise this exception with the original traceback \"\"\"\n        if self.exc_info is not None:\n            six.reraise(type(self), self, self.exc_info[2])\n        else:\n            raise self", "title": ""}
{"_id": "d14099", "text": "def load(filename):\n    \"\"\"\n    Load the state from the given file, moving to the file's directory during\n    load (temporarily, moving back after loaded)\n\n    Parameters\n    ----------\n    filename : string\n        name of the file to open, should be a .pkl file\n    \"\"\"\n    path, name = os.path.split(filename)\n    path = path or '.'\n\n    with util.indir(path):\n        return pickle.load(open(name, 'rb'))", "title": ""}
{"_id": "d14100", "text": "def remote_file_exists(self, url):\n        \"\"\" 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.\n        \"\"\"\n        status = requests.head(url).status_code\n\n        if status != 200:\n            raise RemoteFileDoesntExist", "title": ""}
{"_id": "d14101", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d14102", "text": "def insort_no_dup(lst, item):\n    \"\"\"\n    If item is not in lst, add item to list at its sorted position\n    \"\"\"\n    import bisect\n    ix = bisect.bisect_left(lst, item)\n    if lst[ix] != item: \n        lst[ix:ix] = [item]", "title": ""}
{"_id": "d14103", "text": "def merge(left, right, how='inner', key=None, left_key=None, right_key=None,\n          left_as='left', right_as='right'):\n    \"\"\" Performs a join using the union join function. \"\"\"\n    return join(left, right, how, key, left_key, right_key,\n                join_fn=make_union_join(left_as, right_as))", "title": ""}
{"_id": "d14104", "text": "def _fetch_all_as_dict(self, cursor):\n        \"\"\"\n        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\n        \"\"\"\n        desc = cursor.description\n        return [\n            dict(zip([col[0] for col in desc], row))\n            for row in cursor.fetchall()\n        ]", "title": ""}
{"_id": "d14105", "text": "def tab(self, output):\n        \"\"\"Output data in excel-compatible tab-delimited format\"\"\"\n        import csv\n        csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab)\n        csvwriter.writerows(output)", "title": ""}
{"_id": "d14106", "text": "def test():\n    \"\"\"Test for ReverseDNS class\"\"\"\n    dns = ReverseDNS()\n\n    print(dns.lookup('192.168.0.1'))\n    print(dns.lookup('8.8.8.8'))\n\n    # Test cache\n    print(dns.lookup('8.8.8.8'))", "title": ""}
{"_id": "d14107", "text": "def add_widgets(self, *widgets_or_spacings):\n        \"\"\"Add widgets/spacing to dialog vertical layout\"\"\"\n        layout = self.layout()\n        for widget_or_spacing in widgets_or_spacings:\n            if isinstance(widget_or_spacing, int):\n                layout.addSpacing(widget_or_spacing)\n            else:\n                layout.addWidget(widget_or_spacing)", "title": ""}
{"_id": "d14108", "text": "def _sort_r(sorted, processed, key, deps, dependency_tree):\n    \"\"\"Recursive topological sort implementation.\"\"\"\n    if key in processed:\n        return\n    processed.add(key)\n    for dep_key in deps:\n        dep_deps = dependency_tree.get(dep_key)\n        if dep_deps is None:\n            log.debug('\"%s\" not found, skipped', Repr(dep_key))\n            continue\n        _sort_r(sorted, processed, dep_key, dep_deps, dependency_tree)\n    sorted.append((key, deps))", "title": ""}
{"_id": "d14109", "text": "def save_list(key, *values):\n    \"\"\"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.\n\n    \"\"\"\n    return json.dumps({key: [_get_json(value) for value in values]})", "title": ""}
{"_id": "d14110", "text": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "title": ""}
{"_id": "d14111", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d14112", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d14113", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d14114", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d14115", "text": "def double_sha256(data):\n    \"\"\"A standard compound hash.\"\"\"\n    return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())", "title": ""}
{"_id": "d14116", "text": "def load_data(filename):\n    \"\"\"\n    :rtype : numpy matrix\n    \"\"\"\n    data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n    return data.as_matrix()", "title": ""}
{"_id": "d14117", "text": "def unpickle(pickle_file):\n    \"\"\"Unpickle a python object from the given path.\"\"\"\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", "title": ""}
{"_id": "d14118", "text": "def file_to_str(fname):\n    \"\"\"\n    Read a file into a string\n    PRE: fname is a small file (to avoid hogging memory and its discontents)\n    \"\"\"\n    data = None\n    # rU = read with Universal line terminator\n    with open(fname, 'rU') as fd:\n        data = fd.read()\n    return data", "title": ""}
{"_id": "d14119", "text": "def sinwave(n=4,inc=.25):\n\t\"\"\"\n\tReturns a DataFrame with the required format for \n\ta surface (sine wave) plot\n\n\tParameters:\n\t-----------\n\t\tn : int\n\t\t\tRanges for X and Y axis (-n,n)\n\t\tn_y : int\n\t\t\tSize of increment along the axis\n\t\"\"\"\t\n\tx=np.arange(-n,n,inc)\n\ty=np.arange(-n,n,inc)\n\tX,Y=np.meshgrid(x,y)\n\tR = np.sqrt(X**2 + Y**2)\n\tZ = np.sin(R)/(.5*R)\n\treturn pd.DataFrame(Z,index=x,columns=y)", "title": ""}
{"_id": "d14120", "text": "def get_property(self, filename):\n        \"\"\"Opens the file and reads the value\"\"\"\n\n        with open(self.filepath(filename)) as f:\n            return f.read().strip()", "title": ""}
{"_id": "d14121", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d14122", "text": "def _readuntil(f, end=_TYPE_END):\n\t\"\"\"Helper function to read bytes until a certain end byte is hit\"\"\"\n\tbuf = bytearray()\n\tbyte = f.read(1)\n\twhile byte != end:\n\t\tif byte == b'':\n\t\t\traise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))\n\t\tbuf += byte\n\t\tbyte = f.read(1)\n\treturn buf", "title": ""}
{"_id": "d14123", "text": "def log_magnitude_spectrum(frames):\n    \"\"\"Compute the log of the magnitude spectrum of frames\"\"\"\n    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))", "title": ""}
{"_id": "d14124", "text": "def get_serial_number_string(self):\n        \"\"\" Get the Serial Number String from the HID device.\n\n        :return:    The Serial Number String\n        :rtype:     unicode\n\n        \"\"\"\n        self._check_device_status()\n        str_p = ffi.new(\"wchar_t[]\", 255)\n        rv = hidapi.hid_get_serial_number_string(self._device, str_p, 255)\n        if rv == -1:\n            raise IOError(\"Failed to read serial number string from HID \"\n                          \"device: {0}\".format(self._get_last_error_string()))\n        return ffi.string(str_p)", "title": ""}
{"_id": "d14125", "text": "def confusion_matrix(self):\n        \"\"\"Confusion matrix plot\n        \"\"\"\n        return plot.confusion_matrix(self.y_true, self.y_pred,\n                                     self.target_names, ax=_gen_ax())", "title": ""}
{"_id": "d14126", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d14127", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d14128", "text": "def _get_config_or_default(self, key, default, as_type=lambda x: x):\n        \"\"\"Return a main config value, or default if it does not exist.\"\"\"\n\n        if self.main_config.has_option(self.main_section, key):\n            return as_type(self.main_config.get(self.main_section, key))\n        return default", "title": ""}
{"_id": "d14129", "text": "def caller_locals():\n    \"\"\"Get the local variables in the caller's frame.\"\"\"\n    import inspect\n    frame = inspect.currentframe()\n    try:\n        return frame.f_back.f_back.f_locals\n    finally:\n        del frame", "title": ""}
{"_id": "d14130", "text": "def get_mnist(data_type=\"train\", location=\"/tmp/mnist\"):\n    \"\"\"\n    Get mnist dataset with features and label as ndarray.\n    Data would be downloaded automatically if it doesn't present at the specific location.\n\n    :param data_type: \"train\" for training data and \"test\" for testing data.\n    :param location: Location to store mnist dataset.\n    :return: (features: ndarray, label: ndarray)\n    \"\"\"\n    X, Y = mnist.read_data_sets(location, data_type)\n    return X, Y + 1", "title": ""}
{"_id": "d14131", "text": "def append(self, item):\n        \"\"\" append item and print it to stdout \"\"\"\n        print(item)\n        super(MyList, self).append(item)", "title": ""}
{"_id": "d14132", "text": "def loads(s, model=None, parser=None):\n    \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n    with StringIO(s) as f:\n        return load(f, model=model, parser=parser)", "title": ""}
{"_id": "d14133", "text": "def printdict(adict):\n    \"\"\"printdict\"\"\"\n    dlist = list(adict.keys())\n    dlist.sort()\n    for i in range(0, len(dlist)):\n        print(dlist[i], adict[dlist[i]])", "title": ""}
{"_id": "d14134", "text": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "title": ""}
{"_id": "d14135", "text": "def print_matrix(X, decimals=1):\n    \"\"\"Pretty printing for numpy matrix X\"\"\"\n    for row in np.round(X, decimals=decimals):\n        print(row)", "title": ""}
{"_id": "d14136", "text": "def loadmat(filename):\n    \"\"\"This function should be called instead of direct spio.loadmat\n    as it cures the problem of not properly recovering python dictionaries\n    from mat files. It calls the function check keys to cure all entries\n    which are still mat-objects\n    \"\"\"\n    data = sploadmat(filename, struct_as_record=False, squeeze_me=True)\n    return _check_keys(data)", "title": ""}
{"_id": "d14137", "text": "def pprint(self, seconds):\n        \"\"\"\n        Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n        :param seconds:  The time in seconds.\n        \"\"\"\n        return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))", "title": ""}
{"_id": "d14138", "text": "def readTuple(self, line, n=3):\n        \"\"\" Reads a tuple of numbers. e.g. vertices, normals or teture coords.\n        \"\"\"\n        numbers = [num for num in line.split(' ') if num]\n        return [float(num) for num in numbers[1:n + 1]]", "title": ""}
{"_id": "d14139", "text": "def print(*a):\n    \"\"\" print just one that returns what you give it instead of None \"\"\"\n    try:\n        _print(*a)\n        return a[0] if len(a) == 1 else a\n    except:\n        _print(*a)", "title": ""}
{"_id": "d14140", "text": "def ReadManyFromPath(filepath):\n  \"\"\"Reads a Python object stored in a specified YAML file.\n\n  Args:\n    filepath: A filepath to the YAML file.\n\n  Returns:\n    A Python data structure corresponding to the YAML in the given file.\n  \"\"\"\n  with io.open(filepath, mode=\"r\", encoding=\"utf-8\") as filedesc:\n    return ReadManyFromFile(filedesc)", "title": ""}
{"_id": "d14141", "text": "def __PrintEnumDocstringLines(self, enum_type):\n        description = enum_type.description or '%s enum type.' % enum_type.name\n        for line in textwrap.wrap('r\"\"\"%s' % description,\n                                  self.__printer.CalculateWidth()):\n            self.__printer(line)\n        PrintIndentedDescriptions(self.__printer, enum_type.values, 'Values')\n        self.__printer('\"\"\"')", "title": ""}
{"_id": "d14142", "text": "def map_keys_deep(f, dct):\n    \"\"\"\n    Implementation of map that recurses. This tests the same keys at every level of dict and in lists\n    :param f: 2-ary function expecting a key and value and returns a modified key\n    :param dct: Dict for deep processing\n    :return: Modified dct with matching props mapped\n    \"\"\"\n    return _map_deep(lambda k, v: [f(k, v), v], dct)", "title": ""}
{"_id": "d14143", "text": "def index():\n    \"\"\" Display productpage with normal user and test user buttons\"\"\"\n    global productpage\n\n    table = json2html.convert(json = json.dumps(productpage),\n                              table_attributes=\"class=\\\"table table-condensed table-bordered table-hover\\\"\")\n\n    return render_template('index.html', serviceTable=table)", "title": ""}
{"_id": "d14144", "text": "def logout():\n    \"\"\" Log out the active user\n    \"\"\"\n    flogin.logout_user()\n    next = flask.request.args.get('next')\n    return flask.redirect(next or flask.url_for(\"user\"))", "title": ""}
{"_id": "d14145", "text": "def head_and_tail_print(self, n=5):\n        \"\"\"Display the first and last n elements of a DataFrame.\"\"\"\n        from IPython import display\n        display.display(display.HTML(self._head_and_tail_table(n)))", "title": ""}
{"_id": "d14146", "text": "def get_instance(key, expire=None):\n    \"\"\"Return an instance of RedisSet.\"\"\"\n    global _instances\n    try:\n        instance = _instances[key]\n    except KeyError:\n        instance = RedisSet(\n            key,\n            _redis,\n            expire=expire\n        )\n        _instances[key] = instance\n\n    return instance", "title": ""}
{"_id": "d14147", "text": "def update_dict(obj, dict, attributes):\n    \"\"\"Update dict with fields from obj.attributes.\n\n    :param obj: the object updated into dict\n    :param dict: the result dictionary\n    :param attributes: a list of attributes belonging to obj\n    \"\"\"\n    for attribute in attributes:\n        if hasattr(obj, attribute) and getattr(obj, attribute) is not None:\n            dict[attribute] = getattr(obj, attribute)", "title": ""}
{"_id": "d14148", "text": "def rpop(self, key):\n        \"\"\"Emulate lpop.\"\"\"\n        redis_list = self._get_list(key, 'RPOP')\n\n        if self._encode(key) not in self.redis:\n            return None\n\n        try:\n            value = redis_list.pop()\n            if len(redis_list) == 0:\n                self.delete(key)\n            return value\n        except (IndexError):\n            # Redis returns nil if popping from an empty list\n            return None", "title": ""}
{"_id": "d14149", "text": "def property_as_list(self, property_name):\n        \"\"\" property() but encapsulates it in a list, if it's a\n        single-element property.\n        \"\"\"\n        try:\n            res = self._a_tags[property_name]\n        except KeyError:\n            return []\n\n        if type(res) == list:\n            return res\n        else:\n            return [res]", "title": ""}
{"_id": "d14150", "text": "def toJson(protoObject, indent=None):\n    \"\"\"\n    Serialises a protobuf object as json\n    \"\"\"\n    # Using the internal method because this way we can reformat the JSON\n    js = json_format.MessageToDict(protoObject, False)\n    return json.dumps(js, indent=indent)", "title": ""}
{"_id": "d14151", "text": "def calculate_top_margin(self):\n\t\t\"\"\"\n\t\tCalculate the margin in pixels above the plot area, setting\n\t\tborder_top.\n\t\t\"\"\"\n\t\tself.border_top = 5\n\t\tif self.show_graph_title:\n\t\t\tself.border_top += self.title_font_size\n\t\tself.border_top += 5\n\t\tif self.show_graph_subtitle:\n\t\t\tself.border_top += self.subtitle_font_size", "title": ""}
{"_id": "d14152", "text": "def reindex_axis(self, labels, axis=0, **kwargs):\n        \"\"\"\n        Conform Series to new index with optional filling logic.\n\n        .. deprecated:: 0.21.0\n            Use ``Series.reindex`` instead.\n        \"\"\"\n        # for compatibility with higher dims\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\n        return self.reindex(index=labels, **kwargs)", "title": ""}
{"_id": "d14153", "text": "def listen_for_updates(self):\n        \"\"\"Attach a callback on the group pubsub\"\"\"\n        self.toredis.subscribe(self.group_pubsub, callback=self.callback)", "title": ""}
{"_id": "d14154", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d14155", "text": "def _heappush_max(heap, item):\n    \"\"\" why is this not in heapq \"\"\"\n    heap.append(item)\n    heapq._siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d14156", "text": "def clean_py_files(path):\n    \"\"\"\n    Removes all .py files.\n\n    :param path: the path\n    :return: None\n    \"\"\"\n\n    for dirname, subdirlist, filelist in os.walk(path):\n\n        for f in filelist:\n            if f.endswith('py'):\n                os.remove(os.path.join(dirname, f))", "title": ""}
{"_id": "d14157", "text": "def from_pydatetime(cls, pydatetime):\n        \"\"\"\n        Creates sql datetime2 object from Python datetime object\n        ignoring timezone\n        @param pydatetime: Python datetime object\n        @return: sql datetime2 object\n        \"\"\"\n        return cls(date=Date.from_pydate(pydatetime.date),\n                   time=Time.from_pytime(pydatetime.time))", "title": ""}
{"_id": "d14158", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d14159", "text": "def locate(command, on):\n    \"\"\"Locate the command's man page.\"\"\"\n    location = find_page_location(command, on)\n    click.echo(location)", "title": ""}
{"_id": "d14160", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d14161", "text": "def value_left(self, other):\n    \"\"\"\n    Returns the value of the other type instance to use in an\n    operator method, namely when the method's instance is on the\n    left side of the expression.\n    \"\"\"\n    return other.value if isinstance(other, self.__class__) else other", "title": ""}
{"_id": "d14162", "text": "def dedup_list(l):\n    \"\"\"Given a list (l) will removing duplicates from the list,\n       preserving the original order of the list. Assumes that\n       the list entrie are hashable.\"\"\"\n    dedup = set()\n    return [ x for x in l if not (x in dedup or dedup.add(x))]", "title": ""}
{"_id": "d14163", "text": "def imapchain(*a, **kwa):\n    \"\"\" Like map but also chains the results. \"\"\"\n\n    imap_results = map( *a, **kwa )\n    return itertools.chain( *imap_results )", "title": ""}
{"_id": "d14164", "text": "def remove_element(self, e):\n        \"\"\"Remove element `e` from model\n        \"\"\"\n        \n        if e.label is not None: self.elementdict.pop(e.label)\n        self.elementlist.remove(e)", "title": ""}
{"_id": "d14165", "text": "def block_view(arr, block=(3, 3)):\n    \"\"\"Provide a 2D block view to 2D array.\n\n    No error checking made. Therefore meaningful (as implemented) only for\n    blocks strictly compatible with the shape of A.\n\n    \"\"\"\n\n    # simple shape and strides computations may seem at first strange\n    # unless one is able to recognize the 'tuple additions' involved ;-)\n    shape = (arr.shape[0] // block[0], arr.shape[1] // block[1]) + block\n    strides = (block[0] * arr.strides[0], block[1] * arr.strides[1]) + arr.strides\n    return ast(arr, shape=shape, strides=strides)", "title": ""}
{"_id": "d14166", "text": "def rfft2d_freqs(h, w):\n    \"\"\"Computes 2D spectrum frequencies.\"\"\"\n\n    fy = np.fft.fftfreq(h)[:, None]\n    # when we have an odd input dimension we need to keep one additional\n    # frequency and later cut off 1 pixel\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)", "title": ""}
{"_id": "d14167", "text": "def strip_html(string, keep_tag_content=False):\n    \"\"\"\n    Remove html code contained into the given string.\n\n    :param string: String to manipulate.\n    :type string: str\n    :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).\n    :type keep_tag_content: bool\n    :return: String with html removed.\n    :rtype: str\n    \"\"\"\n    r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE\n    return r.sub('', string)", "title": ""}
{"_id": "d14168", "text": "def get(s, delimiter='', format=\"diacritical\"):\n    \"\"\"Return pinyin of string, the string must be unicode\n    \"\"\"\n    return delimiter.join(_pinyin_generator(u(s), format=format))", "title": ""}
{"_id": "d14169", "text": "def pop(h):\n    \"\"\"Pop the heap value from the heap.\"\"\"\n    n = h.size() - 1\n    h.swap(0, n)\n    down(h, 0, n)\n    return h.pop()", "title": ""}
{"_id": "d14170", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d14171", "text": "def drop_trailing_zeros(num):\n    \"\"\"\n    Drops the trailing zeros in a float that is printed.\n    \"\"\"\n    txt = '%f' %(num)\n    txt = txt.rstrip('0')\n    if txt.endswith('.'):\n        txt = txt[:-1]\n    return txt", "title": ""}
{"_id": "d14172", "text": "def ub_to_str(string):\n    \"\"\"\n    converts py2 unicode / py3 bytestring into str\n    Args:\n        string (unicode, byte_string): string to be converted\n        \n    Returns:\n        (str)\n    \"\"\"\n    if not isinstance(string, str):\n        if six.PY2:\n            return str(string)\n        else:\n            return string.decode()\n    return string", "title": ""}
{"_id": "d14173", "text": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n    \"\"\"Clean a pandas dataframe by:\n        1. Filling empty values with Nan\n        2. Dropping columns with all empty values\n\n    Args:\n        df: Pandas DataFrame\n        fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n        drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n    Returns:\n        DataFrame: cleaned DataFrame\n\n    \"\"\"\n    if fill_nan:\n        df = df.fillna(value=np.nan)\n    if drop_empty_columns:\n        df = df.dropna(axis=1, how='all')\n    return df.sort_index()", "title": ""}
{"_id": "d14174", "text": "def is_defined(self, objtxt, force_import=False):\n        \"\"\"Return True if object is defined\"\"\"\n        return self.interpreter.is_defined(objtxt, force_import)", "title": ""}
{"_id": "d14175", "text": "def remove_from_lib(self, name):\n        \"\"\" Remove an object from the bin folder. \"\"\"\n        self.__remove_path(os.path.join(self.root_dir, \"lib\", name))", "title": ""}
{"_id": "d14176", "text": "def last_modified_date(filename):\n    \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n    mtime = os.path.getmtime(filename)\n    dt = datetime.datetime.utcfromtimestamp(mtime)\n    return dt.replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d14177", "text": "def strip_accents(s):\n    \"\"\"\n    Strip accents to prepare for slugification.\n    \"\"\"\n    nfkd = unicodedata.normalize('NFKD', unicode(s))\n    return u''.join(ch for ch in nfkd if not unicodedata.combining(ch))", "title": ""}
{"_id": "d14178", "text": "def dict_pop_or(d, key, default=None):\n    \"\"\" Try popping a key from a dict.\n        Instead of raising KeyError, just return the default value.\n    \"\"\"\n    val = default\n    with suppress(KeyError):\n        val = d.pop(key)\n    return val", "title": ""}
{"_id": "d14179", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d14180", "text": "def filter_(stream_spec, filter_name, *args, **kwargs):\n    \"\"\"Alternate name for ``filter``, so as to not collide with the\n    built-in python ``filter`` operator.\n    \"\"\"\n    return filter(stream_spec, filter_name, *args, **kwargs)", "title": ""}
{"_id": "d14181", "text": "def strip_spaces(x):\n    \"\"\"\n    Strips spaces\n    :param x:\n    :return:\n    \"\"\"\n    x = x.replace(b' ', b'')\n    x = x.replace(b'\\t', b'')\n    return x", "title": ""}
{"_id": "d14182", "text": "def glr_path_static():\n    \"\"\"Returns path to packaged static files\"\"\"\n    return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))", "title": ""}
{"_id": "d14183", "text": "def preprocess_french(trans, fr_nlp, remove_brackets_content=True):\n    \"\"\" Takes a list of sentences in french and preprocesses them.\"\"\"\n\n    if remove_brackets_content:\n        trans = pangloss.remove_content_in_brackets(trans, \"[]\")\n    # Not sure why I have to split and rejoin, but that fixes a Spacy token\n    # error.\n    trans = fr_nlp(\" \".join(trans.split()[:]))\n    #trans = fr_nlp(trans)\n    trans = \" \".join([token.lower_ for token in trans if not token.is_punct])\n\n    return trans", "title": ""}
{"_id": "d14184", "text": "def ungzip_data(input_data):\n    \"\"\"Return a string of data after gzip decoding\n\n    :param the input gziped data\n    :return  the gzip decoded data\"\"\"\n    buf = StringIO(input_data)\n    f = gzip.GzipFile(fileobj=buf)\n    return f", "title": ""}
{"_id": "d14185", "text": "def _breakRemNewlines(tag):\n\t\"\"\"non-recursively break spaces and remove newlines in the tag\"\"\"\n\tfor i,c in enumerate(tag.contents):\n\t\tif type(c) != bs4.element.NavigableString:\n\t\t\tcontinue\n\t\tc.replace_with(re.sub(r' {2,}', ' ', c).replace('\\n',''))", "title": ""}
{"_id": "d14186", "text": "def _visual_width(line):\n    \"\"\"Get the the number of columns required to display a string\"\"\"\n\n    return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, \"\", line))", "title": ""}
{"_id": "d14187", "text": "def rm_keys_from_dict(d, keys):\n    \"\"\"\n    Given a dictionary and a key list, remove any data in the dictionary with the given keys.\n\n    :param dict d: Metadata\n    :param list keys: Keys to be removed\n    :return dict d: Metadata\n    \"\"\"\n    # Loop for each key given\n    for key in keys:\n        # Is the key in the dictionary?\n        if key in d:\n            try:\n                d.pop(key, None)\n            except KeyError:\n                # Not concerned with an error. Keep going.\n                pass\n    return d", "title": ""}
{"_id": "d14188", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d14189", "text": "def __init__(self, filename, mode, encoding=None):\n        \"\"\"Use the specified filename for streamed logging.\"\"\"\n        FileHandler.__init__(self, filename, mode, encoding)\n        self.mode = mode\n        self.encoding = encoding", "title": ""}
{"_id": "d14190", "text": "def wget(url):\n    \"\"\"\n    Download the page into a string\n    \"\"\"\n    import urllib.parse\n    request = urllib.request.urlopen(url)\n    filestring = request.read()\n    return filestring", "title": ""}
{"_id": "d14191", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d14192", "text": "def issuperset(self, other):\n        \"\"\"Report whether this RangeSet contains another set.\"\"\"\n        self._binary_sanity_check(other)\n        return set.issuperset(self, other)", "title": ""}
{"_id": "d14193", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d14194", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d14195", "text": "def slugify(s, delimiter='-'):\n    \"\"\"\n    Normalize `s` into ASCII and replace non-word characters with `delimiter`.\n    \"\"\"\n    s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')\n    return RE_SLUG.sub(delimiter, s).strip(delimiter).lower()", "title": ""}
{"_id": "d14196", "text": "def _create_statusicon(self):\n        \"\"\"Return a new Gtk.StatusIcon.\"\"\"\n        statusicon = Gtk.StatusIcon()\n        statusicon.set_from_gicon(self._icons.get_gicon('media'))\n        statusicon.set_tooltip_text(_(\"udiskie\"))\n        return statusicon", "title": ""}
{"_id": "d14197", "text": "def remove_list_duplicates(lista, unique=False):\n    \"\"\"\n    Remove duplicated elements in a list.\n    Args:\n        lista: List with elements to clean duplicates.\n    \"\"\"\n    result = []\n    allready = []\n\n    for elem in lista:\n        if elem not in result:\n            result.append(elem)\n        else:\n            allready.append(elem)\n\n    if unique:\n        for elem in allready:\n            result = list(filter((elem).__ne__, result))\n\n    return result", "title": ""}
{"_id": "d14198", "text": "def __grid_widgets(self):\n        \"\"\"Places all the child widgets in the appropriate positions.\"\"\"\n        scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n        self._canvas.grid(row=0, column=1, sticky=\"nswe\")\n        self._scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")", "title": ""}
{"_id": "d14199", "text": "def readCommaList(fileList):\n    \"\"\" Return a list of the files with the commas removed. \"\"\"\n    names=fileList.split(',')\n    fileList=[]\n    for item in names:\n        fileList.append(item)\n    return fileList", "title": ""}
{"_id": "d14200", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d14201", "text": "def _update_index_on_df(df, index_names):\n    \"\"\"Helper function to restore index information after collection. Doesn't\n    use self so we can serialize this.\"\"\"\n    if index_names:\n        df = df.set_index(index_names)\n        # Remove names from unnamed indexes\n        index_names = _denormalize_index_names(index_names)\n        df.index.names = index_names\n    return df", "title": ""}
{"_id": "d14202", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d14203", "text": "def sort_matrix(a,n=0):\n    \"\"\"\n    This will rearrange the array a[n] from lowest to highest, and\n    rearrange the rest of a[i]'s in the same way. It is dumb and slow.\n\n    Returns a numpy array.\n    \"\"\"\n    a = _n.array(a)\n    return a[:,a[n,:].argsort()]", "title": ""}
{"_id": "d14204", "text": "def write_property(fh, key, value):\n  \"\"\"\n    Write a single property to the file in Java properties format.\n\n    :param fh: a writable file-like object\n    :param key: the key to write\n    :param value: the value to write\n  \"\"\"\n  if key is COMMENT:\n    write_comment(fh, value)\n    return\n\n  _require_string(key, 'keys')\n  _require_string(value, 'values')\n\n  fh.write(_escape_key(key))\n  fh.write(b'=')\n  fh.write(_escape_value(value))\n  fh.write(b'\\n')", "title": ""}
{"_id": "d14205", "text": "def substitute(dict_, source):\n    \"\"\" Perform re.sub with the patterns in the given dict\n    Args:\n      dict_: {pattern: repl}\n      source: str\n    \"\"\"\n    d_esc = (re.escape(k) for k in dict_.keys())\n    pattern = re.compile('|'.join(d_esc))\n    return pattern.sub(lambda x: dict_[x.group()], source)", "title": ""}
{"_id": "d14206", "text": "def get_column(self, X, column):\n        \"\"\"Return a column of the given matrix.\n\n        Args:\n            X: `numpy.ndarray` or `pandas.DataFrame`.\n            column: `int` or `str`.\n\n        Returns:\n            np.ndarray: Selected column.\n        \"\"\"\n        if isinstance(X, pd.DataFrame):\n            return X[column].values\n\n        return X[:, column]", "title": ""}
{"_id": "d14207", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d14208", "text": "def populate_obj(obj, attrs):\n    \"\"\"Populates an object's attributes using the provided dict\n    \"\"\"\n    for k, v in attrs.iteritems():\n        setattr(obj, k, v)", "title": ""}
{"_id": "d14209", "text": "def _trim(image):\n    \"\"\"Trim a PIL image and remove white space.\"\"\"\n    background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n    diff = PIL.ImageChops.difference(image, background)\n    diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n    bbox = diff.getbbox()\n    if bbox:\n        image = image.crop(bbox)\n    return image", "title": ""}
{"_id": "d14210", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d14211", "text": "def add_params_to_url(url, params):\n    \"\"\"Adds params to url\n\n    :param url: Url\n    :param params: Params to add\n    :return: original url with new params\n    \"\"\"\n    url_parts = list(urlparse.urlparse(url))  # get url parts\n    query = dict(urlparse.parse_qsl(url_parts[4]))  # get url query\n    query.update(params)  # add new params\n    url_parts[4] = urlencode(query)\n    return urlparse.urlunparse(url_parts)", "title": ""}
{"_id": "d14212", "text": "def replaceNewlines(string, newlineChar):\n\t\"\"\"There's probably a way to do this with string functions but I was lazy.\n\t\tReplace all instances of \\r or \\n in a string with something else.\"\"\"\n\tif newlineChar in string:\n\t\tsegments = string.split(newlineChar)\n\t\tstring = \"\"\n\t\tfor segment in segments:\n\t\t\tstring += segment\n\treturn string", "title": ""}
{"_id": "d14213", "text": "def uniform_noise(points):\n    \"\"\"Init a uniform noise variable.\"\"\"\n    return np.random.rand(1) * np.random.uniform(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d14214", "text": "def replaceNewlines(string, newlineChar):\n\t\"\"\"There's probably a way to do this with string functions but I was lazy.\n\t\tReplace all instances of \\r or \\n in a string with something else.\"\"\"\n\tif newlineChar in string:\n\t\tsegments = string.split(newlineChar)\n\t\tstring = \"\"\n\t\tfor segment in segments:\n\t\t\tstring += segment\n\treturn string", "title": ""}
{"_id": "d14215", "text": "def alter_change_column(self, table, column, field):\n        \"\"\"Support change columns.\"\"\"\n        return self._update_column(table, column, lambda a, b: b)", "title": ""}
{"_id": "d14216", "text": "def create_symlink(source, link_name):\n    \"\"\"\n    Creates symbolic link for either operating system.\n\n    http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows\n    \"\"\"\n    os_symlink = getattr(os, \"symlink\", None)\n    if isinstance(os_symlink, collections.Callable):\n        os_symlink(source, link_name)\n    else:\n        import ctypes\n        csl = ctypes.windll.kernel32.CreateSymbolicLinkW\n        csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n        csl.restype = ctypes.c_ubyte\n        flags = 1 if os.path.isdir(source) else 0\n        if csl(link_name, source, flags) == 0:\n            raise ctypes.WinError()", "title": ""}
{"_id": "d14217", "text": "def __repr__(self):\n    \"\"\"Returns a stringified representation of this object.\"\"\"\n    return str({'name': self._name, 'watts': self._watts,\n                'type': self._output_type, 'id': self._integration_id})", "title": ""}
{"_id": "d14218", "text": "def make_aware(value, timezone):\n    \"\"\"\n    Makes a naive datetime.datetime in a given time zone aware.\n    \"\"\"\n    if hasattr(timezone, 'localize') and value not in (datetime.datetime.min, datetime.datetime.max):\n        # available for pytz time zones\n        return timezone.localize(value, is_dst=None)\n    else:\n        # may be wrong around DST changes\n        return value.replace(tzinfo=timezone)", "title": ""}
{"_id": "d14219", "text": "def _is_root():\n    \"\"\"Checks if the user is rooted.\"\"\"\n    import os\n    import ctypes\n    try:\n        return os.geteuid() == 0\n    except AttributeError:\n        return ctypes.windll.shell32.IsUserAnAdmin() != 0\n    return False", "title": ""}
{"_id": "d14220", "text": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"React to a docstring event and append contracts to it.\"\"\"\n    # pylint: disable=unused-argument\n    # pylint: disable=too-many-arguments\n    lines.extend(_format_contracts(what=what, obj=obj))", "title": ""}
{"_id": "d14221", "text": "def reset_password(app, appbuilder, username, password):\n    \"\"\"\n        Resets a user's password\n    \"\"\"\n    _appbuilder = import_application(app, appbuilder)\n    user = _appbuilder.sm.find_user(username=username)\n    if not user:\n        click.echo(\"User {0} not found.\".format(username))\n    else:\n        _appbuilder.sm.reset_password(user.id, password)\n        click.echo(click.style(\"User {0} reseted.\".format(username), fg=\"green\"))", "title": ""}
{"_id": "d14222", "text": "def check(text):\n    \"\"\"Check the text.\"\"\"\n    err = \"malapropisms.misc\"\n    msg = u\"'{}' is a malapropism.\"\n\n    illogics = [\n        \"the infinitesimal universe\",\n        \"a serial experience\",\n        \"attack my voracity\",\n    ]\n\n    return existence_check(text, illogics, err, msg, offset=1)", "title": ""}
{"_id": "d14223", "text": "def format_doc_text(text):\n    \"\"\"\n    A very thin wrapper around textwrap.fill to consistently wrap documentation text\n    for display in a command line environment. The text is wrapped to 99 characters with an\n    indentation depth of 4 spaces. Each line is wrapped independently in order to preserve\n    manually added line breaks.\n\n    :param text: The text to format, it is cleaned by inspect.cleandoc.\n    :return: The formatted doc text.\n    \"\"\"\n\n    return '\\n'.join(\n        textwrap.fill(line, width=99, initial_indent='    ', subsequent_indent='    ')\n        for line in inspect.cleandoc(text).splitlines())", "title": ""}
{"_id": "d14224", "text": "def extract_all(zipfile, dest_folder):\n    \"\"\"\n    reads the zip file, determines compression\n    and unzips recursively until source files \n    are extracted \n    \"\"\"\n    z = ZipFile(zipfile)\n    print(z)\n    z.extract(dest_folder)", "title": ""}
{"_id": "d14225", "text": "def get_decimal_quantum(precision):\n    \"\"\"Return minimal quantum of a number, as defined by precision.\"\"\"\n    assert isinstance(precision, (int, decimal.Decimal))\n    return decimal.Decimal(10) ** (-precision)", "title": ""}
{"_id": "d14226", "text": "def angle(x0, y0, x1, y1):\n    \"\"\" Returns the angle between two points.\n    \"\"\"\n    return degrees(atan2(y1-y0, x1-x0))", "title": ""}
{"_id": "d14227", "text": "def getvariable(name):\n    \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n    import inspect\n    fr = inspect.currentframe()\n    try:\n        while fr:\n            fr = fr.f_back\n            vars = fr.f_locals\n            if name in vars:\n                return vars[name]\n    except:\n        pass\n    return None", "title": ""}
{"_id": "d14228", "text": "def apply(filter):\n    \"\"\"Manufacture decorator that filters return value with given function.\n\n    ``filter``:\n      Callable that takes a single parameter.\n    \"\"\"\n    def decorator(callable):\n        return lambda *args, **kwargs: filter(callable(*args, **kwargs))\n    return decorator", "title": ""}
{"_id": "d14229", "text": "def create_response(self, request, content, content_type):\n        \"\"\"Returns a response object for the request. Can be overridden to return different responses.\"\"\"\n\n        return HttpResponse(content=content, content_type=content_type)", "title": ""}
{"_id": "d14230", "text": "def latlng(arg):\n    \"\"\"Converts a lat/lon pair to a comma-separated string.\n\n    For example:\n\n    sydney = {\n        \"lat\" : -33.8674869,\n        \"lng\" : 151.2069902\n    }\n\n    convert.latlng(sydney)\n    # '-33.8674869,151.2069902'\n\n    For convenience, also accepts lat/lon pair as a string, in\n    which case it's returned unchanged.\n\n    :param arg: The lat/lon pair.\n    :type arg: string or dict or list or tuple\n    \"\"\"\n    if is_string(arg):\n        return arg\n\n    normalized = normalize_lat_lng(arg)\n    return \"%s,%s\" % (format_float(normalized[0]), format_float(normalized[1]))", "title": ""}
{"_id": "d14231", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d14232", "text": "def extend(self, iterable):\n        \"\"\"Extend the list by appending all the items in the given list.\"\"\"\n        return super(Collection, self).extend(\n            self._ensure_iterable_is_valid(iterable))", "title": ""}
{"_id": "d14233", "text": "def path_to_list(pathstr):\n    \"\"\"Conver a path string to a list of path elements.\"\"\"\n    return [elem for elem in pathstr.split(os.path.pathsep) if elem]", "title": ""}
{"_id": "d14234", "text": "def allclose(a, b):\n    \"\"\"\n    Test that a and b are close and match in shape.\n\n    Parameters\n    ----------\n    a : ndarray\n        First array to check\n\n    b : ndarray\n        First array to check\n    \"\"\"\n    from numpy import allclose\n    return (a.shape == b.shape) and allclose(a, b)", "title": ""}
{"_id": "d14235", "text": "def counter(items):\n    \"\"\"\n    Simplest required implementation of collections.Counter. Required as 2.6\n    does not have Counter in collections.\n    \"\"\"\n    results = {}\n    for item in items:\n        results[item] = results.get(item, 0) + 1\n    return results", "title": ""}
{"_id": "d14236", "text": "def set_subparsers_args(self, *args, **kwargs):\n        \"\"\"\n        Sets args and kwargs that are passed when creating a subparsers group\n        in an argparse.ArgumentParser i.e. when calling\n        argparser.ArgumentParser.add_subparsers\n        \"\"\"\n        self.subparsers_args = args\n        self.subparsers_kwargs = kwargs", "title": ""}
{"_id": "d14237", "text": "def __reversed__(self):\n        \"\"\"\n        Return a reversed iterable over the items in the dictionary. Items are\n        iterated over in their reverse sort order.\n\n        Iterating views while adding or deleting entries in the dictionary may\n        raise a RuntimeError or fail to iterate over all entries.\n        \"\"\"\n        _dict = self._dict\n        return iter((key, _dict[key]) for key in reversed(self._list))", "title": ""}
{"_id": "d14238", "text": "def add_option(self, *args, **kwargs):\n        \"\"\"Add optparse or argparse option depending on CmdHelper initialization.\"\"\"\n        if self.parseTool == 'argparse':\n            if args and args[0] == '':   # no short option\n                args = args[1:]\n            return self.parser.add_argument(*args, **kwargs)\n        else:\n            return self.parser.add_option(*args, **kwargs)", "title": ""}
{"_id": "d14239", "text": "def delete(filething):\n    \"\"\" delete(filething)\n\n    Arguments:\n        filething (filething)\n    Raises:\n        mutagen.MutagenError\n\n    Remove tags from a file.\n    \"\"\"\n\n    t = MP4(filething)\n    filething.fileobj.seek(0)\n    t.delete(filething)", "title": ""}
{"_id": "d14240", "text": "def __init__(self, name, flag, **kwargs):\n    \"\"\"\n    Argument class constructor, should be used inside a class that inherits the BaseAction class.\n\n    :param name(str): the optional argument name to be used with two slahes (--cmd)\n    :param flag(str): a short flag for the argument (-c)\n    :param \\*\\*kwargs: all keywords arguments supported for argparse actions.\n    \"\"\"\n    self.name = name\n    self.flag = flag\n    self.options = kwargs", "title": ""}
{"_id": "d14241", "text": "def get_system_root_directory():\n    \"\"\"\n    Get system root directory (application installed root directory)\n\n    Returns\n    -------\n    string\n        A full path\n\n    \"\"\"\n    root = os.path.dirname(__file__)\n    root = os.path.dirname(root)\n    root = os.path.abspath(root)\n    return root", "title": ""}
{"_id": "d14242", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d14243", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d14244", "text": "def c_array(ctype, values):\n    \"\"\"Convert a python string to c array.\"\"\"\n    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):\n        return (ctype * len(values)).from_buffer_copy(values)\n    return (ctype * len(values))(*values)", "title": ""}
{"_id": "d14245", "text": "def round_to_float(number, precision):\n    \"\"\"Round a float to a precision\"\"\"\n    rounded = Decimal(str(floor((number + precision / 2) // precision))\n                      ) * Decimal(str(precision))\n    return float(rounded)", "title": ""}
{"_id": "d14246", "text": "def access_ok(self, access):\n        \"\"\" Check if there is enough permissions for access \"\"\"\n        for c in access:\n            if c not in self.perms:\n                return False\n        return True", "title": ""}
{"_id": "d14247", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d14248", "text": "def install_postgres(user=None, dbname=None, password=None):\n    \"\"\"Install Postgres on remote\"\"\"\n    execute(pydiploy.django.install_postgres_server,\n            user=user, dbname=dbname, password=password)", "title": ""}
{"_id": "d14249", "text": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "title": ""}
{"_id": "d14250", "text": "async def list(source):\n    \"\"\"Generate a single list from an asynchronous sequence.\"\"\"\n    result = []\n    async with streamcontext(source) as streamer:\n        async for item in streamer:\n            result.append(item)\n    yield result", "title": ""}
{"_id": "d14251", "text": "def StringIO(*args, **kwargs):\n    \"\"\"StringIO constructor shim for the async wrapper.\"\"\"\n    raw = sync_io.StringIO(*args, **kwargs)\n    return AsyncStringIOWrapper(raw)", "title": ""}
{"_id": "d14252", "text": "def save_pdf(path):\n  \"\"\"\n  Saves a pdf of the current matplotlib figure.\n\n  :param path: str, filepath to save to\n  \"\"\"\n\n  pp = PdfPages(path)\n  pp.savefig(pyplot.gcf())\n  pp.close()", "title": ""}
{"_id": "d14253", "text": "def creation_time(self):\n    \"\"\"dfdatetime.Filetime: creation time or None if not set.\"\"\"\n    timestamp = self._fsntfs_attribute.get_creation_time_as_integer()\n    return dfdatetime_filetime.Filetime(timestamp=timestamp)", "title": ""}
{"_id": "d14254", "text": "def download_file(save_path, file_url):\n    \"\"\" Download file from http url link \"\"\"\n\n    r = requests.get(file_url)  # create HTTP response object\n\n    with open(save_path, 'wb') as f:\n        f.write(r.content)\n\n    return save_path", "title": ""}
{"_id": "d14255", "text": "def nmse(a, b):\n    \"\"\"Returns the normalized mean square error of a and b\n    \"\"\"\n    return np.square(a - b).mean() / (a.mean() * b.mean())", "title": ""}
{"_id": "d14256", "text": "def save_pdf(path):\n  \"\"\"\n  Saves a pdf of the current matplotlib figure.\n\n  :param path: str, filepath to save to\n  \"\"\"\n\n  pp = PdfPages(path)\n  pp.savefig(pyplot.gcf())\n  pp.close()", "title": ""}
{"_id": "d14257", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d14258", "text": "def extract_vars_above(*names):\n    \"\"\"Extract a set of variables by name from another frame.\n\n    Similar to extractVars(), but with a specified depth of 1, so that names\n    are exctracted exactly from above the caller.\n\n    This is simply a convenience function so that the very common case (for us)\n    of skipping exactly 1 frame doesn't have to construct a special dict for\n    keyword passing.\"\"\"\n\n    callerNS = sys._getframe(2).f_locals\n    return dict((k,callerNS[k]) for k in names)", "title": ""}
{"_id": "d14259", "text": "def __init__(self, name, contained_key):\n        \"\"\"Instantiate an anonymous file-based Bucket around a single key.\n        \"\"\"\n        self.name = name\n        self.contained_key = contained_key", "title": ""}
{"_id": "d14260", "text": "def is_nullable_list(val, vtype):\n    \"\"\"Return True if list contains either values of type `vtype` or None.\"\"\"\n    return (isinstance(val, list) and\n            any(isinstance(v, vtype) for v in val) and\n            all((isinstance(v, vtype) or v is None) for v in val))", "title": ""}
{"_id": "d14261", "text": "def compute_boxplot(self, series):\n        \"\"\"\n        Compute boxplot for given pandas Series.\n        \"\"\"\n        from matplotlib.cbook import boxplot_stats\n        series = series[series.notnull()]\n        if len(series.values) == 0:\n            return {}\n        elif not is_numeric_dtype(series):\n            return self.non_numeric_stats(series)\n        stats = boxplot_stats(list(series.values))[0]\n        stats['count'] = len(series.values)\n        stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n        return stats", "title": ""}
{"_id": "d14262", "text": "def Any(a, axis, keep_dims):\n    \"\"\"\n    Any reduction op.\n    \"\"\"\n    return np.any(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                  keepdims=keep_dims),", "title": ""}
{"_id": "d14263", "text": "def compute_boxplot(self, series):\n        \"\"\"\n        Compute boxplot for given pandas Series.\n        \"\"\"\n        from matplotlib.cbook import boxplot_stats\n        series = series[series.notnull()]\n        if len(series.values) == 0:\n            return {}\n        elif not is_numeric_dtype(series):\n            return self.non_numeric_stats(series)\n        stats = boxplot_stats(list(series.values))[0]\n        stats['count'] = len(series.values)\n        stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n        return stats", "title": ""}
{"_id": "d14264", "text": "def selectin(table, field, value, complement=False):\n    \"\"\"Select rows where the given field is a member of the given value.\"\"\"\n\n    return select(table, field, lambda v: v in value,\n                  complement=complement)", "title": ""}
{"_id": "d14265", "text": "def compute_boxplot(self, series):\n        \"\"\"\n        Compute boxplot for given pandas Series.\n        \"\"\"\n        from matplotlib.cbook import boxplot_stats\n        series = series[series.notnull()]\n        if len(series.values) == 0:\n            return {}\n        elif not is_numeric_dtype(series):\n            return self.non_numeric_stats(series)\n        stats = boxplot_stats(list(series.values))[0]\n        stats['count'] = len(series.values)\n        stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n        return stats", "title": ""}
{"_id": "d14266", "text": "def uncheck(self, locator=None, allow_label_click=None, **kwargs):\n        \"\"\"\n        Find a check box and uncheck it. The check box can be found via name, id, or label text. ::\n\n            page.uncheck(\"German\")\n\n        Args:\n            locator (str, optional): Which check box to uncheck.\n            allow_label_click (bool, optional): Attempt to click the label to toggle state if\n                element is non-visible. Defaults to :data:`capybara.automatic_label_click`.\n            **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.\n        \"\"\"\n\n        self._check_with_label(\n            \"checkbox\", False, locator=locator, allow_label_click=allow_label_click, **kwargs)", "title": ""}
{"_id": "d14267", "text": "def upload_as_json(name, mylist):\n    \"\"\"\n    Upload the IPList as json payload. \n\n    :param str name: name of IPList\n    :param list: list of IPList entries\n    :return: None\n    \"\"\"\n    location = list(IPList.objects.filter(name))\n    if location:\n        iplist = location[0]\n        return iplist.upload(json=mylist, as_type='json')", "title": ""}
{"_id": "d14268", "text": "def comma_delimited_to_list(list_param):\n    \"\"\"Convert comma-delimited list / string into a list of strings\n\n    :param list_param: Comma-delimited string\n    :type list_param: str | unicode\n    :return: A list of strings\n    :rtype: list\n    \"\"\"\n    if isinstance(list_param, list):\n        return list_param\n    if isinstance(list_param, str):\n        return list_param.split(',')\n    else:\n        return []", "title": ""}
{"_id": "d14269", "text": "def __getattr__(self, *args, **kwargs):\n        \"\"\"\n        Magic method dispatcher\n        \"\"\"\n\n        return xmlrpc.client._Method(self.__request, *args, **kwargs)", "title": ""}
{"_id": "d14270", "text": "def getbyteslice(self, start, end):\n        \"\"\"Direct access to byte data.\"\"\"\n        c = self._rawarray[start:end]\n        return c", "title": ""}
{"_id": "d14271", "text": "def get_serializable_data_for_fields(model):\n    \"\"\"\n    Return a serialised version of the model's fields which exist as local database\n    columns (i.e. excluding m2m and incoming foreign key relations)\n    \"\"\"\n    pk_field = model._meta.pk\n    # If model is a child via multitable inheritance, use parent's pk\n    while pk_field.remote_field and pk_field.remote_field.parent_link:\n        pk_field = pk_field.remote_field.model._meta.pk\n\n    obj = {'pk': get_field_value(pk_field, model)}\n\n    for field in model._meta.fields:\n        if field.serialize:\n            obj[field.name] = get_field_value(field, model)\n\n    return obj", "title": ""}
{"_id": "d14272", "text": "def __init__(self, ba=None):\n        \"\"\"Constructor.\"\"\"\n        self.bytearray = ba or (bytearray(b'\\0') * self.SIZEOF)", "title": ""}
{"_id": "d14273", "text": "def calc_base64(s):\n    \"\"\"Return base64 encoded binarystring.\"\"\"\n    s = compat.to_bytes(s)\n    s = compat.base64_encodebytes(s).strip()  # return bytestring\n    return compat.to_native(s)", "title": ""}
{"_id": "d14274", "text": "def plot_target(target, ax):\n    \"\"\"Ajoute la target au plot\"\"\"\n    ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)", "title": ""}
{"_id": "d14275", "text": "def prsint(string):\n    \"\"\"\n    Parse a string as an integer, encapsulating error handling.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html\n\n    :param string: String representing an integer.\n    :type string: str\n    :return: Integer value obtained by parsing string.\n    :rtype: int\n    \"\"\"\n    string = stypes.stringToCharP(string)\n    intval = ctypes.c_int()\n    libspice.prsint_c(string, ctypes.byref(intval))\n    return intval.value", "title": ""}
{"_id": "d14276", "text": "def set_default(self, key, value):\n        \"\"\"Set the default value for this key.\n        Default only used when no value is provided by the user via\n        arg, config or env.\n        \"\"\"\n        k = self._real_key(key.lower())\n        self._defaults[k] = value", "title": ""}
{"_id": "d14277", "text": "def struct2dict(struct):\n    \"\"\"convert a ctypes structure to a dictionary\"\"\"\n    return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}", "title": ""}
{"_id": "d14278", "text": "def set_logxticks_for_all(self, row_column_list=None, logticks=None):\n        \"\"\"Manually specify the x-axis log tick values.\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\n        :param logticks: logarithm of the locations for the ticks along the\n            axis.\n\n        For example, if you specify [1, 2, 3], ticks will be placed at 10,\n        100 and 1000.\n\n        \"\"\"\n        if row_column_list is None:\n            self.ticks['x'] = ['1e%d' % u for u in logticks]\n        else:\n            for row, column in row_column_list:\n                self.set_logxticks(row, column, logticks)", "title": ""}
{"_id": "d14279", "text": "def testable_memoized_property(func=None, key_factory=per_instance, **kwargs):\n  \"\"\"A variant of `memoized_property` that allows for setting of properties (for tests, etc).\"\"\"\n  getter = memoized_method(func=func, key_factory=key_factory, **kwargs)\n\n  def setter(self, val):\n    with getter.put(self) as putter:\n      putter(val)\n\n  return property(fget=getter,\n                  fset=setter,\n                  fdel=lambda self: getter.forget(self))", "title": ""}
{"_id": "d14280", "text": "def is_cached(self, url):\n        \"\"\"Checks if specified URL is cached.\"\"\"\n        try:\n            return True if url in self.cache else False\n        except TypeError:\n            return False", "title": ""}
{"_id": "d14281", "text": "def set_xlimits_widgets(self, set_min=True, set_max=True):\n        \"\"\"Populate axis limits GUI with current plot values.\"\"\"\n        xmin, xmax = self.tab_plot.ax.get_xlim()\n        if set_min:\n            self.w.x_lo.set_text('{0}'.format(xmin))\n        if set_max:\n            self.w.x_hi.set_text('{0}'.format(xmax))", "title": ""}
{"_id": "d14282", "text": "def ttl(self):\n        \"\"\"how long you should cache results for cacheable queries\"\"\"\n        ret = 3600\n        cn = self.get_process()\n        if \"ttl\" in cn:\n            ret = cn[\"ttl\"]\n        return ret", "title": ""}
{"_id": "d14283", "text": "def set_xlimits(self, min=None, max=None):\n        \"\"\"Set limits for the x-axis.\n\n        :param min: minimum value to be displayed.  If None, it will be\n            calculated.\n        :param max: maximum value to be displayed.  If None, it will be\n            calculated.\n\n        \"\"\"\n        self.limits['xmin'] = min\n        self.limits['xmax'] = max", "title": ""}
{"_id": "d14284", "text": "def manhattan_distance_numpy(object1, object2):\n    \"\"\"!\n    @brief Calculate Manhattan distance between two objects using numpy.\n\n    @param[in] object1 (array_like): The first array_like object.\n    @param[in] object2 (array_like): The second array_like object.\n\n    @return (double) Manhattan distance between two objects.\n\n    \"\"\"\n    return numpy.sum(numpy.absolute(object1 - object2), axis=1).T", "title": ""}
{"_id": "d14285", "text": "def add_xlabel(self, text=None):\n        \"\"\"\n        Add a label to the x-axis.\n        \"\"\"\n        x = self.fit.meta['independent']\n        if not text:\n            text = '$' + x['tex_symbol'] + r'$ $(\\si{' + x['siunitx'] +  r'})$'\n        self.plt.set_xlabel(text)", "title": ""}
{"_id": "d14286", "text": "def get_model(name):\n    \"\"\"\n    Convert a model's verbose name to the model class. This allows us to\n    use the models verbose name in steps.\n    \"\"\"\n\n    model = MODELS.get(name.lower(), None)\n\n    assert model, \"Could not locate model by name '%s'\" % name\n\n    return model", "title": ""}
{"_id": "d14287", "text": "def setDictDefaults (d, defaults):\n  \"\"\"Sets all defaults for the given dictionary to those contained in a\n  second defaults dictionary.  This convenience method calls:\n\n    d.setdefault(key, value)\n\n  for each key and value in the given defaults dictionary.\n  \"\"\"\n  for key, val in defaults.items():\n    d.setdefault(key, val)\n\n  return d", "title": ""}
{"_id": "d14288", "text": "def test():  # pragma: no cover\n    \"\"\"Execute the unit tests on an installed copy of unyt.\n\n    Note that this function requires pytest to run. If pytest is not\n    installed this function will raise ImportError.\n    \"\"\"\n    import pytest\n    import os\n\n    pytest.main([os.path.dirname(os.path.abspath(__file__))])", "title": ""}
{"_id": "d14289", "text": "def stft(func=None, **kwparams):\n  \"\"\"\n  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.\n  \"\"\"\n  from numpy.fft import fft, ifft\n  return stft.base(transform=fft, inverse_transform=ifft)(func, **kwparams)", "title": ""}
{"_id": "d14290", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d14291", "text": "def prettyprint(d):\n        \"\"\"Print dicttree in Json-like format. keys are sorted\n        \"\"\"\n        print(json.dumps(d, sort_keys=True, \n                         indent=4, separators=(\",\" , \": \")))", "title": ""}
{"_id": "d14292", "text": "def sdmethod(meth):\n    \"\"\"\n    This is a hack to monkey patch sdproperty to work as expected with instance methods.\n    \"\"\"\n    sd = singledispatch(meth)\n\n    def wrapper(obj, *args, **kwargs):\n        return sd.dispatch(args[0].__class__)(obj, *args, **kwargs)\n\n    wrapper.register = sd.register\n    wrapper.dispatch = sd.dispatch\n    wrapper.registry = sd.registry\n    wrapper._clear_cache = sd._clear_cache\n    functools.update_wrapper(wrapper, meth)\n    return wrapper", "title": ""}
{"_id": "d14293", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d14294", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d14295", "text": "def query(self, base, filterstr, attrlist=None):\n\t\t\"\"\" wrapper to search_s \"\"\"\n\t\treturn self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)", "title": ""}
{"_id": "d14296", "text": "def angle_to_cartesian(lon, lat):\n    \"\"\"Convert spherical coordinates to cartesian unit vectors.\"\"\"\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", "title": ""}
{"_id": "d14297", "text": "def shutdown(self):\n        \"\"\"close socket, immediately.\"\"\"\n        if self.sock:\n            self.sock.close()\n            self.sock = None\n            self.connected = False", "title": ""}
{"_id": "d14298", "text": "def bin_to_int(string):\n    \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n    if isinstance(string, str):\n        return struct.unpack(\"b\", string)[0]\n    else:\n        return struct.unpack(\"b\", bytes([string]))[0]", "title": ""}
{"_id": "d14299", "text": "def advance_one_line(self):\n    \"\"\"Advances to next line.\"\"\"\n\n    current_line = self._current_token.line_number\n    while current_line == self._current_token.line_number:\n      self._current_token = ConfigParser.Token(*next(self._token_generator))", "title": ""}
{"_id": "d14300", "text": "def FromString(self, string):\n    \"\"\"Parse a bool from a string.\"\"\"\n    if string.lower() in (\"false\", \"no\", \"n\"):\n      return False\n\n    if string.lower() in (\"true\", \"yes\", \"y\"):\n      return True\n\n    raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "title": ""}
{"_id": "d14301", "text": "def solve(A, x):\n    \"\"\"Solves a linear equation system with a matrix of shape (n, n) and an\n    array of shape (n, ...). The output has the same shape as the second\n    argument.\n    \"\"\"\n    # https://stackoverflow.com/a/48387507/353337\n    x = numpy.asarray(x)\n    return numpy.linalg.solve(A, x.reshape(x.shape[0], -1)).reshape(x.shape)", "title": ""}
{"_id": "d14302", "text": "def sort_data(x, y):\n    \"\"\"Sort the data.\"\"\"\n    xy = sorted(zip(x, y))\n    x, y = zip(*xy)\n    return x, y", "title": ""}
{"_id": "d14303", "text": "def str_to_boolean(input_str):\n    \"\"\" a conversion function for boolean\n    \"\"\"\n    if not isinstance(input_str, six.string_types):\n        raise ValueError(input_str)\n    input_str = str_quote_stripper(input_str)\n    return input_str.lower() in (\"true\", \"t\", \"1\", \"y\", \"yes\")", "title": ""}
{"_id": "d14304", "text": "def _index_ordering(redshift_list):\n        \"\"\"\n\n        :param redshift_list: list of redshifts\n        :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n        \"\"\"\n        redshift_list = np.array(redshift_list)\n        sort_index = np.argsort(redshift_list)\n        return sort_index", "title": ""}
{"_id": "d14305", "text": "def schedule_task(self):\n        \"\"\"\n        Schedules this publish action as a Celery task.\n        \"\"\"\n        from .tasks import publish_task\n\n        publish_task.apply_async(kwargs={'pk': self.pk}, eta=self.scheduled_time)", "title": ""}
{"_id": "d14306", "text": "def get_order(self, codes):\n        \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n        return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "title": ""}
{"_id": "d14307", "text": "def schedule_task(self):\n        \"\"\"\n        Schedules this publish action as a Celery task.\n        \"\"\"\n        from .tasks import publish_task\n\n        publish_task.apply_async(kwargs={'pk': self.pk}, eta=self.scheduled_time)", "title": ""}
{"_id": "d14308", "text": "def sort_data(x, y):\n    \"\"\"Sort the data.\"\"\"\n    xy = sorted(zip(x, y))\n    x, y = zip(*xy)\n    return x, y", "title": ""}
{"_id": "d14309", "text": "def force_stop(self):\n        \"\"\"\n        Forcibly terminates all Celery processes.\n        \"\"\"\n        r = self.local_renderer\n        with self.settings(warn_only=True):\n            r.sudo('pkill -9 -f celery')\n        r.sudo('rm -f /tmp/celery*.pid')", "title": ""}
{"_id": "d14310", "text": "def has_add_permission(self, request):\n        \"\"\" Can add this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "title": ""}
{"_id": "d14311", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d14312", "text": "def do_forceescape(value):\n    \"\"\"Enforce HTML escaping.  This will probably double escape variables.\"\"\"\n    if hasattr(value, '__html__'):\n        value = value.__html__()\n    return escape(unicode(value))", "title": ""}
{"_id": "d14313", "text": "def fieldstorage(self):\n        \"\"\" `cgi.FieldStorage` from `wsgi.input`.\n        \"\"\"\n        if self._fieldstorage is None:\n            if self._body is not None:\n                raise ReadBodyTwiceError()\n\n            self._fieldstorage = cgi.FieldStorage(\n                environ=self._environ,\n                fp=self._environ['wsgi.input']\n            )\n\n        return self._fieldstorage", "title": ""}
{"_id": "d14314", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d14315", "text": "def stringc(text, color):\n    \"\"\"\n    Return a string with terminal colors.\n    \"\"\"\n    if has_colors:\n        text = str(text)\n\n        return \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"\n    else:\n        return text", "title": ""}
{"_id": "d14316", "text": "def napoleon_to_sphinx(docstring, **config_params):\n    \"\"\"\n    Convert napoleon docstring to plain sphinx string.\n\n    Args:\n        docstring (str): Docstring in napoleon format.\n        **config_params (dict): Whatever napoleon doc configuration you want.\n\n    Returns:\n        str: Sphinx string.\n    \"\"\"\n    if \"napoleon_use_param\" not in config_params:\n        config_params[\"napoleon_use_param\"] = False\n\n    if \"napoleon_use_rtype\" not in config_params:\n        config_params[\"napoleon_use_rtype\"] = False\n\n    config = Config(**config_params)\n\n    return str(GoogleDocstring(docstring, config))", "title": ""}
{"_id": "d14317", "text": "def _possibly_convert_objects(values):\n    \"\"\"Convert arrays of datetime.datetime and datetime.timedelta objects into\n    datetime64 and timedelta64, according to the pandas convention.\n    \"\"\"\n    return np.asarray(pd.Series(values.ravel())).reshape(values.shape)", "title": ""}
{"_id": "d14318", "text": "def _split(string, splitters):\n    \"\"\"Splits a string into parts at multiple characters\"\"\"\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", "title": ""}
{"_id": "d14319", "text": "def _to_corrected_pandas_type(dt):\n    \"\"\"\n    When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n    This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n    \"\"\"\n    import numpy as np\n    if type(dt) == ByteType:\n        return np.int8\n    elif type(dt) == ShortType:\n        return np.int16\n    elif type(dt) == IntegerType:\n        return np.int32\n    elif type(dt) == FloatType:\n        return np.float32\n    else:\n        return None", "title": ""}
{"_id": "d14320", "text": "def split_string(text, chars_per_string):\n    \"\"\"\n    Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string.\n    This is very useful for splitting one giant message into multiples.\n\n    :param text: The text to split\n    :param chars_per_string: The number of characters per line the text is split into.\n    :return: The splitted text as a list of strings.\n    \"\"\"\n    return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)]", "title": ""}
{"_id": "d14321", "text": "def set_time(filename, mod_time):\n\t\"\"\"\n\tSet the modified time of a file\n\t\"\"\"\n\tlog.debug('Setting modified time to %s', mod_time)\n\tmtime = calendar.timegm(mod_time.utctimetuple())\n\t# utctimetuple discards microseconds, so restore it (for consistency)\n\tmtime += mod_time.microsecond / 1000000\n\tatime = os.stat(filename).st_atime\n\tos.utime(filename, (atime, mtime))", "title": ""}
{"_id": "d14322", "text": "def split_into_words(s):\n  \"\"\"Split a sentence into list of words.\"\"\"\n  s = re.sub(r\"\\W+\", \" \", s)\n  s = re.sub(r\"[_0-9]+\", \" \", s)\n  return s.split()", "title": ""}
{"_id": "d14323", "text": "def gauss_pdf(x, mu, sigma):\n    \"\"\"Normalized Gaussian\"\"\"\n    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)", "title": ""}
{"_id": "d14324", "text": "def bulk_query(self, query, *multiparams):\n        \"\"\"Bulk insert or update.\"\"\"\n\n        with self.get_connection() as conn:\n            conn.bulk_query(query, *multiparams)", "title": ""}
{"_id": "d14325", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d14326", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d14327", "text": "def col_rename(df,col_name,new_col_name):\n    \"\"\" Changes a column name in a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_name - string\n        Name of column to change\n    new_col_name - string\n        New name of column\n    \"\"\"\n    col_list = list(df.columns)\n    for index,value in enumerate(col_list):\n        if value == col_name:\n            col_list[index] = new_col_name\n            break\n    df.columns = col_list", "title": ""}
{"_id": "d14328", "text": "def get_db_version(session):\n    \"\"\"\n    :param session: actually it is a sqlalchemy session\n    :return: version number\n    \"\"\"\n    value = session.query(ProgramInformation.value).filter(ProgramInformation.name == \"db_version\").scalar()\n    return int(value)", "title": ""}
{"_id": "d14329", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d14330", "text": "def get_checkerboard_matrix(kernel_width):\n\n    \"\"\"\n    example matrix for width = 2\n\n    -1  -1    1   1\n    -1  -1    1   1\n     1   1   -1  -1\n     1   1   -1  -1\n\n    :param kernel_width:\n    :return:\n    \"\"\"\n\n    return np.vstack((\n        np.hstack((\n            -1 * np.ones((kernel_width, kernel_width)), np.ones((kernel_width, kernel_width))\n        )),\n        np.hstack((\n            np.ones((kernel_width, kernel_width)), -1 * np.ones((kernel_width, kernel_width))\n        ))\n    ))", "title": ""}
{"_id": "d14331", "text": "def cric__lasso():\n    \"\"\" Lasso Regression\n    \"\"\"\n    model = sklearn.linear_model.LogisticRegression(penalty=\"l1\", C=0.002)\n\n    # we want to explain the raw probability outputs of the trees\n    model.predict = lambda X: model.predict_proba(X)[:,1]\n    \n    return model", "title": ""}
{"_id": "d14332", "text": "def norm_slash(name):\n    \"\"\"Normalize path slashes.\"\"\"\n\n    if isinstance(name, str):\n        return name.replace('/', \"\\\\\") if not is_case_sensitive() else name\n    else:\n        return name.replace(b'/', b\"\\\\\") if not is_case_sensitive() else name", "title": ""}
{"_id": "d14333", "text": "def hex_escape(bin_str):\n  \"\"\"\n  Hex encode a binary string\n  \"\"\"\n  printable = string.ascii_letters + string.digits + string.punctuation + ' '\n  return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)", "title": ""}
{"_id": "d14334", "text": "def from_file_url(url):\n    \"\"\" Convert from file:// url to file path\n    \"\"\"\n    if url.startswith('file://'):\n        url = url[len('file://'):].replace('/', os.path.sep)\n\n    return url", "title": ""}
{"_id": "d14335", "text": "def static_method(cls, f):\n        \"\"\"Decorator which dynamically binds static methods to the model for later use.\"\"\"\n        setattr(cls, f.__name__, staticmethod(f))\n        return f", "title": ""}
{"_id": "d14336", "text": "def _uniquify(_list):\n    \"\"\"Remove duplicates in a list.\"\"\"\n    seen = set()\n    result = []\n    for x in _list:\n        if x not in seen:\n            result.append(x)\n            seen.add(x)\n    return result", "title": ""}
{"_id": "d14337", "text": "def _StopStatusUpdateThread(self):\n    \"\"\"Stops the status update thread.\"\"\"\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", "title": ""}
{"_id": "d14338", "text": "def _check_key(self, key):\n        \"\"\"\n        Ensures well-formedness of a key.\n        \"\"\"\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])", "title": ""}
{"_id": "d14339", "text": "def _StopStatusUpdateThread(self):\n    \"\"\"Stops the status update thread.\"\"\"\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", "title": ""}
{"_id": "d14340", "text": "def kill(self):\n        \"\"\"Kill the browser.\n\n        This is useful when the browser is stuck.\n        \"\"\"\n        if self.process:\n            self.process.kill()\n            self.process.wait()", "title": ""}
{"_id": "d14341", "text": "def memory_used(self):\n        \"\"\"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.\n        \"\"\"\n        if self._end_memory:\n            memory_used = self._end_memory - self._start_memory\n            return memory_used\n        else:\n            return None", "title": ""}
{"_id": "d14342", "text": "def stop_button_click_handler(self):\n        \"\"\"Method to handle what to do when the stop button is pressed\"\"\"\n        self.stop_button.setDisabled(True)\n        # Interrupt computations or stop debugging\n        if not self.shellwidget._reading:\n            self.interrupt_kernel()\n        else:\n            self.shellwidget.write_to_stdin('exit')", "title": ""}
{"_id": "d14343", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d14344", "text": "def _write_json(file, contents):\n    \"\"\"Write a dict to a JSON file.\"\"\"\n    with open(file, 'w') as f:\n        return json.dump(contents, f, indent=2, sort_keys=True)", "title": ""}
{"_id": "d14345", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d14346", "text": "def __str__(self):\n        \"\"\"Executes self.function to convert LazyString instance to a real\n        str.\"\"\"\n        if not hasattr(self, '_str'):\n            self._str=self.function(*self.args, **self.kwargs)\n        return self._str", "title": ""}
{"_id": "d14347", "text": "def is_datetime_like(dtype):\n    \"\"\"Check if a dtype is a subclass of the numpy datetime types\n    \"\"\"\n    return (np.issubdtype(dtype, np.datetime64) or\n            np.issubdtype(dtype, np.timedelta64))", "title": ""}
{"_id": "d14348", "text": "def boolean(value):\n    \"\"\"\n    Configuration-friendly boolean type converter.\n\n    Supports both boolean-valued and string-valued inputs (e.g. from env vars).\n\n    \"\"\"\n    if isinstance(value, bool):\n        return value\n\n    if value == \"\":\n        return False\n\n    return strtobool(value)", "title": ""}
{"_id": "d14349", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d14350", "text": "def underscore(text):\n    \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n    return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()", "title": ""}
{"_id": "d14351", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d14352", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d14353", "text": "def _check_valid(key, val, valid):\n    \"\"\"Helper to check valid options\"\"\"\n    if val not in valid:\n        raise ValueError('%s must be one of %s, not \"%s\"'\n                         % (key, valid, val))", "title": ""}
{"_id": "d14354", "text": "def camel_to_(s):\n    \"\"\"\n    Convert CamelCase to camel_case\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', s)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d14355", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d14356", "text": "def blueprint_name_to_url(name):\n        \"\"\" remove the last . in the string it it ends with a .\n            for the url structure must follow the flask routing format\n            it should be /model/method instead of /model/method/\n        \"\"\"\n        if name[-1:] == \".\":\n            name = name[:-1]\n        name = str(name).replace(\".\", \"/\")\n        return name", "title": ""}
{"_id": "d14357", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d14358", "text": "def call_and_exit(self, cmd, shell=True):\n        \"\"\"Run the *cmd* and exit with the proper exit code.\"\"\"\n        sys.exit(subprocess.call(cmd, shell=shell))", "title": ""}
{"_id": "d14359", "text": "def contains_geometric_info(var):\n    \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)", "title": ""}
{"_id": "d14360", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d14361", "text": "def is_bytes(string):\n    \"\"\"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\n    \"\"\"\n    if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)):  # noqa\n        return True\n    elif six.PY2 and isinstance(string, (buffer, bytearray)):  # noqa\n        return True\n    return False", "title": ""}
{"_id": "d14362", "text": "def Sum(a, axis, keep_dims):\n    \"\"\"\n    Sum reduction op.\n    \"\"\"\n    return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                  keepdims=keep_dims),", "title": ""}
{"_id": "d14363", "text": "def closeEvent(self, e):\n        \"\"\"Qt slot when the window is closed.\"\"\"\n        if self._closed:\n            return\n        res = self.emit('close')\n        # Discard the close event if False is returned by one of the callback\n        # functions.\n        if False in res:  # pragma: no cover\n            e.ignore()\n            return\n        super(GUI, self).closeEvent(e)\n        self._closed = True", "title": ""}
{"_id": "d14364", "text": "def print_err(*args, end='\\n'):\n    \"\"\"Similar to print, but prints to stderr.\n    \"\"\"\n    print(*args, end=end, file=sys.stderr)\n    sys.stderr.flush()", "title": ""}
{"_id": "d14365", "text": "def _isstring(dtype):\n    \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n    if the dtype is string or unicode.\n    \"\"\"\n    return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "title": ""}
{"_id": "d14366", "text": "def byteswap(data, word_size=4):\n    \"\"\" Swap the byte-ordering in a packet with N=4 bytes per word\n    \"\"\"\n    return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '')", "title": ""}
{"_id": "d14367", "text": "def is_executable(path):\n  \"\"\"Returns whether a path names an existing executable file.\"\"\"\n  return os.path.isfile(path) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d14368", "text": "def instance_contains(container, item):\n    \"\"\"Search into instance attributes, properties and return values of no-args methods.\"\"\"\n    return item in (member for _, member in inspect.getmembers(container))", "title": ""}
{"_id": "d14369", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d14370", "text": "def is_valid_file(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.exists(arg):\n        parser.error(\"The file %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d14371", "text": "def ci(a, which=95, axis=None):\n    \"\"\"Return a percentile range from an array of values.\"\"\"\n    p = 50 - which / 2, 50 + which / 2\n    return percentiles(a, p, axis)", "title": ""}
{"_id": "d14372", "text": "def is_readable(fp, size=1):\n    \"\"\"\n    Check if the file-like object is readable.\n\n    :param fp: file-like object\n    :param size: byte size\n    :return: bool\n    \"\"\"\n    read_size = len(fp.read(size))\n    fp.seek(-read_size, 1)\n    return read_size == size", "title": ""}
{"_id": "d14373", "text": "def determine_interactive(self):\n\t\t\"\"\"Determine whether we're in an interactive shell.\n\t\tSets interactivity off if appropriate.\n\t\tcf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):\n\t\t\t\tself.interactive = 0\n\t\t\t\treturn False\n\t\texcept Exception:\n\t\t\tself.interactive = 0\n\t\t\treturn False\n\t\tif self.interactive == 0:\n\t\t\treturn False\n\t\treturn True", "title": ""}
{"_id": "d14374", "text": "def _first_and_last_element(arr):\n    \"\"\"Returns first and last element of numpy array or sparse matrix.\"\"\"\n    if isinstance(arr, np.ndarray) or hasattr(arr, 'data'):\n        # numpy array or sparse matrix with .data attribute\n        data = arr.data if sparse.issparse(arr) else arr\n        return data.flat[0], data.flat[-1]\n    else:\n        # Sparse matrices without .data attribute. Only dok_matrix at\n        # the time of writing, in this case indexing is fast\n        return arr[0, 0], arr[-1, -1]", "title": ""}
{"_id": "d14375", "text": "def __contains__(self, key):\n        \"\"\"\n        Invoked when determining whether a specific key is in the dictionary\n        using `key in d`.\n\n        The key is looked up case-insensitively.\n        \"\"\"\n        k = self._real_key(key)\n        return k in self._data", "title": ""}
{"_id": "d14376", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d14377", "text": "def is_valid_regex(string):\n    \"\"\"\n    Checks whether the re module can compile the given regular expression.\n\n    Parameters\n    ----------\n    string: str\n\n    Returns\n    -------\n    boolean\n    \"\"\"\n    try:\n        re.compile(string)\n        is_valid = True\n    except re.error:\n        is_valid = False\n    return is_valid", "title": ""}
{"_id": "d14378", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d14379", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d14380", "text": "def _using_stdout(self):\n        \"\"\"\n        Return whether the handler is using sys.stdout.\n        \"\"\"\n        if WINDOWS and colorama:\n            # Then self.stream is an AnsiToWin32 object.\n            return self.stream.wrapped is sys.stdout\n\n        return self.stream is sys.stdout", "title": ""}
{"_id": "d14381", "text": "def unicode_is_ascii(u_string):\n    \"\"\"Determine if unicode string only contains ASCII characters.\n\n    :param str u_string: unicode string to check. Must be unicode\n        and not Python 2 `str`.\n    :rtype: bool\n    \"\"\"\n    assert isinstance(u_string, str)\n    try:\n        u_string.encode('ascii')\n        return True\n    except UnicodeEncodeError:\n        return False", "title": ""}
{"_id": "d14382", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d14383", "text": "def is_lazy_iterable(obj):\n    \"\"\"\n    Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n    \"\"\"\n    return isinstance(obj,\n        (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))", "title": ""}
{"_id": "d14384", "text": "def user_in_all_groups(user, groups):\n    \"\"\"Returns True if the given user is in all given groups\"\"\"\n    return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)", "title": ""}
{"_id": "d14385", "text": "def unicode_is_ascii(u_string):\n    \"\"\"Determine if unicode string only contains ASCII characters.\n\n    :param str u_string: unicode string to check. Must be unicode\n        and not Python 2 `str`.\n    :rtype: bool\n    \"\"\"\n    assert isinstance(u_string, str)\n    try:\n        u_string.encode('ascii')\n        return True\n    except UnicodeEncodeError:\n        return False", "title": ""}
{"_id": "d14386", "text": "def wrap(s, width=80):\n    \"\"\"\n    Formats the text input with newlines given the user specified width for\n    each line.\n\n    Parameters\n    ----------\n\n    s : str\n    width : int\n\n    Returns\n    -------\n\n    text : str\n\n    Notes\n    -----\n\n    .. versionadded:: 1.1\n\n    \"\"\"\n    return '\\n'.join(textwrap.wrap(str(s), width=width))", "title": ""}
{"_id": "d14387", "text": "def has_virtualenv(self):\n        \"\"\"\n        Returns true if the virtualenv tool is installed.\n        \"\"\"\n        with self.settings(warn_only=True):\n            ret = self.run_or_local('which virtualenv').strip()\n            return bool(ret)", "title": ""}
{"_id": "d14388", "text": "def normalize_text(text, line_len=80, indent=\"\"):\n    \"\"\"Wrap the text on the given line length.\"\"\"\n    return \"\\n\".join(\n        textwrap.wrap(\n            text, width=line_len, initial_indent=indent, subsequent_indent=indent\n        )\n    )", "title": ""}
{"_id": "d14389", "text": "def get_substring_idxs(substr, string):\n    \"\"\"\n    Return a list of indexes of substr. If substr not found, list is\n    empty.\n\n    Arguments:\n        substr (str): Substring to match.\n        string (str): String to match in.\n\n    Returns:\n        list of int: Start indices of substr.\n    \"\"\"\n    return [match.start() for match in re.finditer(substr, string)]", "title": ""}
{"_id": "d14390", "text": "def mul(a, b):\n  \"\"\"\n  A wrapper around tf multiplication that does more automatic casting of\n  the input.\n  \"\"\"\n  def multiply(a, b):\n    \"\"\"Multiplication\"\"\"\n    return a * b\n  return op_with_scalar_cast(a, b, multiply)", "title": ""}
{"_id": "d14391", "text": "def is_edge_consistent(graph, u, v):\n    \"\"\"Check if all edges between two nodes have the same relation.\n\n    :param pybel.BELGraph graph: A BEL Graph\n    :param tuple u: The source BEL node\n    :param tuple v: The target BEL node\n    :return: If all edges from the source to target node have the same relation\n    :rtype: bool\n    \"\"\"\n    if not graph.has_edge(u, v):\n        raise ValueError('{} does not contain an edge ({}, {})'.format(graph, u, v))\n\n    return 0 == len(set(d[RELATION] for d in graph.edge[u][v].values()))", "title": ""}
{"_id": "d14392", "text": "def percent_d(data, period):\n    \"\"\"\n    %D.\n\n    Formula:\n    %D = SMA(%K, 3)\n    \"\"\"\n    p_k = percent_k(data, period)\n    percent_d = sma(p_k, 3)\n    return percent_d", "title": ""}
{"_id": "d14393", "text": "def service_available(service_name):\n    \"\"\"Determine whether a system service is available\"\"\"\n    try:\n        subprocess.check_output(\n            ['service', service_name, 'status'],\n            stderr=subprocess.STDOUT).decode('UTF-8')\n    except subprocess.CalledProcessError as e:\n        return b'unrecognized service' not in e.output\n    else:\n        return True", "title": ""}
{"_id": "d14394", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d14395", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d14396", "text": "def now(timezone=None):\n    \"\"\"\n    Return a naive datetime object for the given ``timezone``. A ``timezone``\n    is any pytz- like or datetime.tzinfo-like timezone object. If no timezone\n    is given, then UTC is assumed.\n\n    This method is best used with pytz installed::\n\n        pip install pytz\n    \"\"\"\n    d = datetime.datetime.utcnow()\n    if not timezone:\n        return d\n\n    return to_timezone(d, timezone).replace(tzinfo=None)", "title": ""}
{"_id": "d14397", "text": "def _is_path(s):\n    \"\"\"Return whether an object is a path.\"\"\"\n    if isinstance(s, string_types):\n        try:\n            return op.exists(s)\n        except (OSError, ValueError):\n            return False\n    else:\n        return False", "title": ""}
{"_id": "d14398", "text": "def popup(self, title, callfn, initialdir=None):\n        \"\"\"Let user select a directory.\"\"\"\n        super(DirectorySelection, self).popup(title, callfn, initialdir)", "title": ""}
{"_id": "d14399", "text": "def _match_literal(self, a, b=None):\n        \"\"\"Match two names.\"\"\"\n\n        return a.lower() == b if not self.case_sensitive else a == b", "title": ""}
{"_id": "d14400", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d14401", "text": "def is_connected(self):\n        \"\"\"\n        Return true if the socket managed by this connection is connected\n\n        :rtype: bool\n        \"\"\"\n        try:\n            return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self)\n        except socket.error:\n            return False", "title": ""}
{"_id": "d14402", "text": "def is_timestamp(obj):\n    \"\"\"\n    Yaml either have automatically converted it to a datetime object\n    or it is a string that will be validated later.\n    \"\"\"\n    return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)", "title": ""}
{"_id": "d14403", "text": "def count_words(file):\n  \"\"\" Counts the word frequences in a list of sentences.\n\n  Note:\n    This is a helper function for parallel execution of `Vocabulary.from_text`\n    method.\n  \"\"\"\n  c = Counter()\n  with open(file, 'r') as f:\n    for l in f:\n      words = l.strip().split()\n      c.update(words)\n  return c", "title": ""}
{"_id": "d14404", "text": "def isreal(obj):\n    \"\"\"\n    Test if the argument is a real number (float or integer).\n\n    :param obj: Object\n    :type  obj: any\n\n    :rtype: boolean\n    \"\"\"\n    return (\n        (obj is not None)\n        and (not isinstance(obj, bool))\n        and isinstance(obj, (int, float))\n    )", "title": ""}
{"_id": "d14405", "text": "def validate_email(email):\n    \"\"\"\n    Validates an email address\n    Source: Himanshu Shankar (https://github.com/iamhssingh)\n    Parameters\n    ----------\n    email: str\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    from django.core.validators import validate_email\n    from django.core.exceptions import ValidationError\n    try:\n        validate_email(email)\n        return True\n    except ValidationError:\n        return False", "title": ""}
{"_id": "d14406", "text": "def irecarray_to_py(a):\n    \"\"\"Slow conversion of a recarray into a list of records with python types.\n\n    Get the field names from :attr:`a.dtype.names`.\n\n    :Returns: iterator so that one can handle big input arrays\n    \"\"\"\n    pytypes = [pyify(typestr) for name,typestr in a.dtype.descr]\n    def convert_record(r):\n        return tuple([converter(value) for converter, value in zip(pytypes,r)])\n    return (convert_record(r) for r in a)", "title": ""}
{"_id": "d14407", "text": "def is_image(filename):\n    \"\"\"Determine if given filename is an image.\"\"\"\n    # note: isfile() also accepts symlinks\n    return os.path.isfile(filename) and filename.lower().endswith(ImageExts)", "title": ""}
{"_id": "d14408", "text": "def _encode_gif(images, fps):\n  \"\"\"Encodes numpy images into gif string.\n\n  Args:\n    images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape\n      `[time, height, width, channels]` where `channels` is 1 or 3.\n    fps: frames per second of the animation\n\n  Returns:\n    The encoded gif string.\n\n  Raises:\n    IOError: If the ffmpeg command returns an error.\n  \"\"\"\n  writer = WholeVideoWriter(fps)\n  writer.write_multi(images)\n  return writer.finish()", "title": ""}
{"_id": "d14409", "text": "def current_zipfile():\n    \"\"\"A function to vend the current zipfile, if any\"\"\"\n    if zipfile.is_zipfile(sys.argv[0]):\n        fd = open(sys.argv[0], \"rb\")\n        return zipfile.ZipFile(fd)", "title": ""}
{"_id": "d14410", "text": "def num_leaves(tree):\n    \"\"\"Determine the number of leaves in a tree\"\"\"\n    if tree.is_leaf:\n        return 1\n    else:\n        return num_leaves(tree.left_child) + num_leaves(tree.right_child)", "title": ""}
{"_id": "d14411", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d14412", "text": "def _crop_list_to_size(l, size):\n    \"\"\"Make a list a certain size\"\"\"\n    for x in range(size - len(l)):\n        l.append(False)\n    for x in range(len(l) - size):\n        l.pop()\n    return l", "title": ""}
{"_id": "d14413", "text": "def duplicated_rows(df, col_name):\n    \"\"\" Return a DataFrame with the duplicated values of the column `col_name`\n    in `df`.\"\"\"\n    _check_cols(df, [col_name])\n\n    dups = df[pd.notnull(df[col_name]) & df.duplicated(subset=[col_name])]\n    return dups", "title": ""}
{"_id": "d14414", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d14415", "text": "def is_image(filename):\n    \"\"\"Determine if given filename is an image.\"\"\"\n    # note: isfile() also accepts symlinks\n    return os.path.isfile(filename) and filename.lower().endswith(ImageExts)", "title": ""}
{"_id": "d14416", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d14417", "text": "def time_string(seconds):\n    \"\"\"Returns time in seconds as a string formatted HHHH:MM:SS.\"\"\"\n    s = int(round(seconds))  # round to nearest second\n    h, s = divmod(s, 3600)  # get hours and remainder\n    m, s = divmod(s, 60)  # split remainder into minutes and seconds\n    return \"%2i:%02i:%02i\" % (h, m, s)", "title": ""}
{"_id": "d14418", "text": "def close_database_session(session):\n    \"\"\"Close connection with the database\"\"\"\n\n    try:\n        session.close()\n    except OperationalError as e:\n        raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])", "title": ""}
{"_id": "d14419", "text": "def load_files(files):\n    \"\"\"Load and execute a python file.\"\"\"\n\n    for py_file in files:\n        LOG.debug(\"exec %s\", py_file)\n        execfile(py_file, globals(), locals())", "title": ""}
{"_id": "d14420", "text": "def close(self):\n        \"\"\"Flush the file and close it.\n\n        A closed file cannot be written any more. Calling\n        :meth:`close` more than once is allowed.\n        \"\"\"\n        if not self._closed:\n            self.__flush()\n            object.__setattr__(self, \"_closed\", True)", "title": ""}
{"_id": "d14421", "text": "def isnumber(*args):\n    \"\"\"Checks if value is an integer, long integer or float.\n\n    NOTE: Treats booleans as numbers, where True=1 and False=0.\n    \"\"\"\n    return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))", "title": ""}
{"_id": "d14422", "text": "def socket_close(self):\n        \"\"\"Close our socket.\"\"\"\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET", "title": ""}
{"_id": "d14423", "text": "def _get_local_ip():\n        \"\"\"\n        Get the local ip of this device\n\n        :return: Ip of this computer\n        :rtype: str\n        \"\"\"\n        return set([x[4][0] for x in socket.getaddrinfo(\n            socket.gethostname(),\n            80,\n            socket.AF_INET\n        )]).pop()", "title": ""}
{"_id": "d14424", "text": "def lin_interp(x, rangeX, rangeY):\n    \"\"\"\n    Interpolate linearly variable x in rangeX onto rangeY.\n    \"\"\"\n    s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])\n    y = rangeY[0] * (1 - s) + rangeY[1] * s\n    return y", "title": ""}
{"_id": "d14425", "text": "def checkbox_uncheck(self, force_check=False):\n        \"\"\"\n        Wrapper to uncheck a checkbox\n        \"\"\"\n        if self.get_attribute('checked'):\n            self.click(force_click=force_check)", "title": ""}
{"_id": "d14426", "text": "def median(data):\n    \"\"\"Calculate the median of a list.\"\"\"\n    data.sort()\n    num_values = len(data)\n    half = num_values // 2\n    if num_values % 2:\n        return data[half]\n    return 0.5 * (data[half-1] + data[half])", "title": ""}
{"_id": "d14427", "text": "def isTestCaseDisabled(test_case_class, method_name):\n    \"\"\"\n    I check to see if a method on a TestCase has been disabled via nose's\n    convention for disabling a TestCase.  This makes it so that users can\n    mix nose's parameterized tests with green as a runner.\n    \"\"\"\n    test_method = getattr(test_case_class, method_name)\n    return getattr(test_method, \"__test__\", 'not nose') is False", "title": ""}
{"_id": "d14428", "text": "def set_cursor_position(self, position):\n        \"\"\"Set cursor position\"\"\"\n        position = self.get_position(position)\n        cursor = self.textCursor()\n        cursor.setPosition(position)\n        self.setTextCursor(cursor)\n        self.ensureCursorVisible()", "title": ""}
{"_id": "d14429", "text": "def test(ctx, all=False, verbose=False):\n    \"\"\"Run the tests.\"\"\"\n    cmd = 'tox' if all else 'py.test'\n    if verbose:\n        cmd += ' -v'\n    return ctx.run(cmd, pty=True).return_code", "title": ""}
{"_id": "d14430", "text": "def get_selected_values(self, selection):\n        \"\"\"Return a list of values for the given selection.\"\"\"\n        return [v for b, v in self._choices if b & selection]", "title": ""}
{"_id": "d14431", "text": "def __call__(self, actual_value, expect):\n        \"\"\"Main entry point for assertions (called by the wrapper).\n        expect is a function the wrapper class uses to assert a given match.\n        \"\"\"\n        self._expect = expect\n        if self.expected_value is NO_ARG:\n            return self.asserts(actual_value)\n        return self.asserts(actual_value, self.expected_value)", "title": ""}
{"_id": "d14432", "text": "def save_excel(self, fd):\n        \"\"\" Saves the case as an Excel spreadsheet.\n        \"\"\"\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)", "title": ""}
{"_id": "d14433", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d14434", "text": "def is_valid_file(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.exists(arg):\n        parser.error(\"The file %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d14435", "text": "def update(self, params):\n        \"\"\"Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device.\n        \"\"\"\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "title": ""}
{"_id": "d14436", "text": "def _begins_with_one_of(sentence, parts_of_speech):\n    \"\"\"Return True if the sentence or fragment begins with one of the parts of\n    speech in the list, else False\"\"\"\n    doc = nlp(sentence)\n    if doc[0].tag_ in parts_of_speech:\n        return True\n    return False", "title": ""}
{"_id": "d14437", "text": "def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None):\n        \"\"\"\n        Perform a chunked PUT request to url with requests.session\n        This is specifically to upload files.\n        \"\"\"\n        res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert)\n        return res.text, res.status_code", "title": ""}
{"_id": "d14438", "text": "def EvalBinomialPmf(k, n, p):\n    \"\"\"Evaluates the binomial pmf.\n\n    Returns the probabily of k successes in n trials with probability p.\n    \"\"\"\n    return scipy.stats.binom.pmf(k, n, p)", "title": ""}
{"_id": "d14439", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d14440", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d14441", "text": "def compare(a, b):\n    \"\"\"\n     Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))\n    \"\"\"\n    s=0\n    for i in range(len(a)):\n        s=s+abs(a[i]-b[i])\n    return s", "title": ""}
{"_id": "d14442", "text": "def hflip(img):\n    \"\"\"Horizontally flip the given PIL Image.\n\n    Args:\n        img (PIL Image): Image to be flipped.\n\n    Returns:\n        PIL Image:  Horizontall flipped image.\n    \"\"\"\n    if not _is_pil_image(img):\n        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n    return img.transpose(Image.FLIP_LEFT_RIGHT)", "title": ""}
{"_id": "d14443", "text": "def ex(self, cmd):\n        \"\"\"Execute a normal python statement in user namespace.\"\"\"\n        with self.builtin_trap:\n            exec cmd in self.user_global_ns, self.user_ns", "title": ""}
{"_id": "d14444", "text": "def get_creation_datetime(filepath):\n    \"\"\"\n    Get the date that a file was created.\n\n    Parameters\n    ----------\n    filepath : str\n\n    Returns\n    -------\n    creation_datetime : datetime.datetime or None\n    \"\"\"\n    if platform.system() == 'Windows':\n        return datetime.fromtimestamp(os.path.getctime(filepath))\n    else:\n        stat = os.stat(filepath)\n        try:\n            return datetime.fromtimestamp(stat.st_birthtime)\n        except AttributeError:\n            # We're probably on Linux. No easy way to get creation dates here,\n            # so we'll settle for when its content was last modified.\n            return None", "title": ""}
{"_id": "d14445", "text": "def _fill_array_from_list(the_list, the_array):\n        \"\"\"Fill an `array` from a `list`\"\"\"\n        for i, val in enumerate(the_list):\n            the_array[i] = val\n        return the_array", "title": ""}
{"_id": "d14446", "text": "def main(argv=None):\n  \"\"\"Run a Tensorflow model on the Iris dataset.\"\"\"\n  args = parse_arguments(sys.argv if argv is None else argv)\n\n  tf.logging.set_verbosity(tf.logging.INFO)\n  learn_runner.run(\n      experiment_fn=get_experiment_fn(args),\n      output_dir=args.job_dir)", "title": ""}
{"_id": "d14447", "text": "def _sort_lambda(sortedby='cpu_percent',\n                 sortedby_secondary='memory_percent'):\n    \"\"\"Return a sort lambda function for the sortedbykey\"\"\"\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", "title": ""}
{"_id": "d14448", "text": "def sample_colormap(cmap_name, n_samples):\n    \"\"\"\n    Sample a colormap from matplotlib\n    \"\"\"\n    colors = []\n    colormap = cm.cmap_d[cmap_name]\n    for i in np.linspace(0, 1, n_samples):\n        colors.append(colormap(i))\n\n    return colors", "title": ""}
{"_id": "d14449", "text": "def calculate_size(name, count):\n    \"\"\" Calculates the request payload size\"\"\"\n    data_size = 0\n    data_size += calculate_size_str(name)\n    data_size += INT_SIZE_IN_BYTES\n    return data_size", "title": ""}
{"_id": "d14450", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d14451", "text": "def polyline(self, arr):\n        \"\"\"Draw a set of lines\"\"\"\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])", "title": ""}
{"_id": "d14452", "text": "def colorize(string, color, *args, **kwargs):\n    \"\"\"\n    Implements string formatting along with color specified in colorama.Fore\n    \"\"\"\n    string = string.format(*args, **kwargs)\n    return color + string + colorama.Fore.RESET", "title": ""}
{"_id": "d14453", "text": "def multiply(traj):\n    \"\"\"Sophisticated simulation of multiplication\"\"\"\n    z=traj.x*traj.y\n    traj.f_add_result('z',z=z, comment='I am the product of two reals!')", "title": ""}
{"_id": "d14454", "text": "def isetdiff_flags(list1, list2):\n    \"\"\"\n    move to util_iter\n    \"\"\"\n    set2 = set(list2)\n    return (item not in set2 for item in list1)", "title": ""}
{"_id": "d14455", "text": "def column_names(self, table):\n      \"\"\"An iterable of column names, for a particular table or\n      view.\"\"\"\n\n      table_info = self.execute(\n        u'PRAGMA table_info(%s)' % quote(table))\n      return (column['name'] for column in table_info)", "title": ""}
{"_id": "d14456", "text": "def matchfieldnames(field_a, field_b):\n    \"\"\"Check match between two strings, ignoring case and spaces/underscores.\n    \n    Parameters\n    ----------\n    a : str\n    b : str\n    \n    Returns\n    -------\n    bool\n    \n    \"\"\"\n    normalised_a = field_a.replace(' ', '_').lower()\n    normalised_b = field_b.replace(' ', '_').lower()\n    \n    return normalised_a == normalised_b", "title": ""}
{"_id": "d14457", "text": "def filter_regex(names, regex):\n    \"\"\"\n    Return a tuple of strings that match the regular expression pattern.\n    \"\"\"\n    return tuple(name for name in names\n                 if regex.search(name) is not None)", "title": ""}
{"_id": "d14458", "text": "def assert_looks_like(first, second, msg=None):\n    \"\"\" Compare two strings if all contiguous whitespace is coalesced. \"\"\"\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))", "title": ""}
{"_id": "d14459", "text": "def constraint_range_dict(self,*args,**kwargs):\n        \"\"\" \n            Creates a list of dictionaries which each give a constraint for a certain\n            section of the dimension.\n\n            bins arguments overwrites resolution\n        \"\"\"\n        bins = self.bins(*args,**kwargs)\n        return [{self.name+'__gte': a,self.name+'__lt': b} for a,b in zip(bins[:-1],bins[1:])]\n        space = self.space(*args,**kwargs)\n        resolution = space[1] - space[0]\n        return [{self.name+'__gte': s,self.name+'__lt': s+resolution} for s in space]", "title": ""}
{"_id": "d14460", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d14461", "text": "def Date(value):\n    \"\"\"Custom type for managing dates in the command-line.\"\"\"\n    from datetime import datetime\n    try:\n        return datetime(*reversed([int(val) for val in value.split('/')]))\n    except Exception as err:\n        raise argparse.ArgumentTypeError(\"invalid date '%s'\" % value)", "title": ""}
{"_id": "d14462", "text": "def compare_dict(da, db):\n    \"\"\"\n    Compare differencs from two dicts\n    \"\"\"\n    sa = set(da.items())\n    sb = set(db.items())\n    \n    diff = sa & sb\n    return dict(sa - diff), dict(sb - diff)", "title": ""}
{"_id": "d14463", "text": "def assert_list(self, putative_list, expected_type=string_types, key_arg=None):\n    \"\"\"\n    :API: public\n    \"\"\"\n    return assert_list(putative_list, expected_type, key_arg=key_arg,\n                       raise_type=lambda msg: TargetDefinitionException(self, msg))", "title": ""}
{"_id": "d14464", "text": "def compare(string1, string2):\n    \"\"\"Compare two strings while protecting against timing attacks\n\n    :param str string1: the first string\n    :param str string2: the second string\n\n    :returns: True if the strings are equal, False if not\n    :rtype: :obj:`bool`\n    \"\"\"\n    if len(string1) != len(string2):\n        return False\n    result = True\n    for c1, c2 in izip(string1, string2):\n        result &= c1 == c2\n    return result", "title": ""}
{"_id": "d14465", "text": "def print_display_png(o):\n    \"\"\"\n    A function to display sympy expression using display style LaTeX in PNG.\n    \"\"\"\n    s = latex(o, mode='plain')\n    s = s.strip('$')\n    # As matplotlib does not support display style, dvipng backend is\n    # used here.\n    png = latex_to_png('$$%s$$' % s, backend='dvipng')\n    return png", "title": ""}
{"_id": "d14466", "text": "def __similarity(s1, s2, ngrams_fn, n=3):\n    \"\"\"\n        The fraction of n-grams matching between two sequences\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            float: the fraction of n-grams matching\n    \"\"\"\n    ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n))\n    matches = ngrams1.intersection(ngrams2)\n    return 2 * len(matches) / (len(ngrams1) + len(ngrams2))", "title": ""}
{"_id": "d14467", "text": "def __complex__(self):\n        \"\"\"Called to implement the built-in function complex().\"\"\"\n        if self._t != 99 or self.key != ['re', 'im']:\n            return complex(float(self))\n        return complex(float(self.re), float(self.im))", "title": ""}
{"_id": "d14468", "text": "def extract_pdfminer(self, filename, **kwargs):\n        \"\"\"Extract text from pdfs using pdfminer.\"\"\"\n        stdout, _ = self.run(['pdf2txt.py', filename])\n        return stdout", "title": ""}
{"_id": "d14469", "text": "def _pdf_at_peak(self):\n    \"\"\"Pdf evaluated at the peak.\"\"\"\n    return (self.peak - self.low) / (self.high - self.low)", "title": ""}
{"_id": "d14470", "text": "def is_valid(number):\n    \"\"\"determines whether the card number is valid.\"\"\"\n    n = str(number)\n    if not n.isdigit():\n        return False\n    return int(n[-1]) == get_check_digit(n[:-1])", "title": ""}
{"_id": "d14471", "text": "def items(self, section_name):\n        \"\"\":return: list((option, value), ...) pairs of all items in the given section\"\"\"\n        return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']", "title": ""}
{"_id": "d14472", "text": "def validate_email(email):\n    \"\"\"\n    Validates an email address\n    Source: Himanshu Shankar (https://github.com/iamhssingh)\n    Parameters\n    ----------\n    email: str\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    from django.core.validators import validate_email\n    from django.core.exceptions import ValidationError\n    try:\n        validate_email(email)\n        return True\n    except ValidationError:\n        return False", "title": ""}
{"_id": "d14473", "text": "def is_valid_file(parser,arg):\n\t\"\"\"verify the validity of the given file. Never trust the End-User\"\"\"\n\tif not os.path.exists(arg):\n       \t\tparser.error(\"File %s not found\"%arg)\n\telse:\n\t       \treturn arg", "title": ""}
{"_id": "d14474", "text": "def __connect():\n    \"\"\"\n    Connect to a redis instance.\n    \"\"\"\n    global redis_instance\n    if use_tcp_socket:\n        redis_instance = redis.StrictRedis(host=hostname, port=port)\n    else:\n        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "title": ""}
{"_id": "d14475", "text": "def is_valid_file(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.exists(arg):\n        parser.error(\"The file %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d14476", "text": "def _read_stdin():\n    \"\"\"\n    Generator for reading from standard input in nonblocking mode.\n\n    Other ways of reading from ``stdin`` in python waits, until the buffer is\n    big enough, or until EOF character is sent.\n\n    This functions yields immediately after each line.\n    \"\"\"\n    line = sys.stdin.readline()\n    while line:\n        yield line\n        line = sys.stdin.readline()", "title": ""}
{"_id": "d14477", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d14478", "text": "def read(self):\n        \"\"\"Iterate over all JSON input (Generator)\"\"\"\n\n        for line in self.io.read():\n            with self.parse_line(line) as j:\n                yield j", "title": ""}
{"_id": "d14479", "text": "def get_code(module):\n    \"\"\"\n    Compile and return a Module's code object.\n    \"\"\"\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()", "title": ""}
{"_id": "d14480", "text": "def stringify_dict_contents(dct):\n    \"\"\"Turn dict keys and values into native strings.\"\"\"\n    return {\n        str_if_nested_or_str(k): str_if_nested_or_str(v)\n        for k, v in dct.items()\n    }", "title": ""}
{"_id": "d14481", "text": "def prettyprint(d):\n        \"\"\"Print dicttree in Json-like format. keys are sorted\n        \"\"\"\n        print(json.dumps(d, sort_keys=True, \n                         indent=4, separators=(\",\" , \": \")))", "title": ""}
{"_id": "d14482", "text": "def _parse_canonical_int64(doc):\n    \"\"\"Decode a JSON int64 to bson.int64.Int64.\"\"\"\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)", "title": ""}
{"_id": "d14483", "text": "def is_int(value):\n    \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n    if isinstance(value, bool):\n        return False\n    try:\n        int(value)\n        return True\n    except (ValueError, TypeError):\n        return False", "title": ""}
{"_id": "d14484", "text": "def zoom_cv(x,z):\n    \"\"\" Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. \"\"\"\n    if z==0: return x\n    r,c,*_ = x.shape\n    M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.)\n    return cv2.warpAffine(x,M,(c,r))", "title": ""}
{"_id": "d14485", "text": "def find_commons(lists):\n    \"\"\"Finds common values\n\n    :param lists: List of lists\n    :return: List of values that are in common between inner lists\n    \"\"\"\n    others = lists[1:]\n    return [\n        val\n        for val in lists[0]\n        if is_in_all(val, others)\n    ]", "title": ""}
{"_id": "d14486", "text": "def _get_compiled_ext():\n    \"\"\"Official way to get the extension of compiled files (.pyc or .pyo)\"\"\"\n    for ext, mode, typ in imp.get_suffixes():\n        if typ == imp.PY_COMPILED:\n            return ext", "title": ""}
{"_id": "d14487", "text": "def not0(a):\n    \"\"\"Return u if u!= 0, return 1 if u == 0\"\"\"\n    return matrix(list(map(lambda x: 1 if x == 0 else x, a)), a.size)", "title": ""}
{"_id": "d14488", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d14489", "text": "def count_rows_with_nans(X):\n    \"\"\"Count the number of rows in 2D arrays that contain any nan values.\"\"\"\n    if X.ndim == 2:\n        return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()", "title": ""}
{"_id": "d14490", "text": "def link(self, mu, dist):\n        \"\"\"\n        glm link function\n        this is useful for going from mu to the linear prediction\n\n        Parameters\n        ----------\n        mu : array-like of legth n\n        dist : Distribution instance\n\n        Returns\n        -------\n        lp : np.array of length n\n        \"\"\"\n        return np.log(mu) - np.log(dist.levels - mu)", "title": ""}
{"_id": "d14491", "text": "def lines(self):\n        \"\"\"\n\n        :return:\n        \"\"\"\n        if self._lines is None:\n            self._lines = self.obj.content.splitlines()\n        return self._lines", "title": ""}
{"_id": "d14492", "text": "def coverage():\n    \"\"\"check code coverage quickly with the default Python\"\"\"\n    run(\"coverage run --source {PROJECT_NAME} -m py.test\".format(PROJECT_NAME=PROJECT_NAME))\n    run(\"coverage report -m\")\n    run(\"coverage html\")\n\n    webbrowser.open('file://' + os.path.realpath(\"htmlcov/index.html\"), new=2)", "title": ""}
{"_id": "d14493", "text": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "title": ""}
{"_id": "d14494", "text": "def md_to_text(content):\n    \"\"\" Converts markdown content to text \"\"\"\n    text = None\n    html = markdown.markdown(content)\n    if html:\n        text = html_to_text(content)\n    return text", "title": ""}
{"_id": "d14495", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d14496", "text": "def format_result(input):\n        \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n        \"\"\"\n        items = list(iteritems(input))\n        return OrderedDict(sorted(items, key=lambda x: x[0]))", "title": ""}
{"_id": "d14497", "text": "def kill(self):\n        \"\"\"Kill the browser.\n\n        This is useful when the browser is stuck.\n        \"\"\"\n        if self.process:\n            self.process.kill()\n            self.process.wait()", "title": ""}
{"_id": "d14498", "text": "def exit(exit_code=0):\n  r\"\"\"A function to support exiting from exit hooks.\n\n  Could also be used to exit from the calling scripts in a thread safe manner.\n  \"\"\"\n  core.processExitHooks()\n\n  if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook\n    sys.stderr.flush()\n    sys.stdout.flush()\n    os._exit(exit_code) #pylint: disable=W0212\n\n  sys.exit(exit_code)", "title": ""}
{"_id": "d14499", "text": "def vectorsToMatrix(aa, bb):\n    \"\"\"\n    Performs the vector multiplication of the elements of two vectors, constructing the 3x3 matrix.\n    :param aa: One vector of size 3\n    :param bb: Another vector of size 3\n    :return: A 3x3 matrix M composed of the products of the elements of aa and bb :\n     M_ij = aa_i * bb_j\n    \"\"\"\n    MM = np.zeros([3, 3], np.float)\n    for ii in range(3):\n        for jj in range(3):\n            MM[ii, jj] = aa[ii] * bb[jj]\n    return MM", "title": ""}
{"_id": "d14500", "text": "def int2str(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from integers to strings\"\"\"\n    return NumConv(radix, alphabet).int2str(num)", "title": ""}
{"_id": "d14501", "text": "def create_rot2d(angle):\n    \"\"\"Create 2D rotation matrix\"\"\"\n    ca = math.cos(angle)\n    sa = math.sin(angle)\n    return np.array([[ca, -sa], [sa, ca]])", "title": ""}
{"_id": "d14502", "text": "def packagenameify(s):\n  \"\"\"\n  Makes a package name\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('.')[-1:])", "title": ""}
{"_id": "d14503", "text": "def from_json_str(cls, json_str):\n    \"\"\"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.\n    \"\"\"\n    return cls.from_json(json.loads(json_str, cls=JsonDecoder))", "title": ""}
{"_id": "d14504", "text": "def scipy_sparse_to_spmatrix(A):\n    \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP", "title": ""}
{"_id": "d14505", "text": "def build_service_class(metadata):\n    \"\"\"Generate a service class for the service contained in the specified metadata class.\"\"\"\n    i = importlib.import_module(metadata)\n    service = i.service\n    env = get_jinja_env()\n    service_template = env.get_template('service.py.jinja2')\n    with open(api_path(service.name.lower()), 'w') as t:\n        t.write(service_template.render(service_md=service))", "title": ""}
{"_id": "d14506", "text": "def get_next_scheduled_time(cron_string):\n    \"\"\"Calculate the next scheduled time by creating a crontab object\n    with a cron string\"\"\"\n    itr = croniter.croniter(cron_string, datetime.utcnow())\n    return itr.get_next(datetime)", "title": ""}
{"_id": "d14507", "text": "def _trim(image):\n    \"\"\"Trim a PIL image and remove white space.\"\"\"\n    background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n    diff = PIL.ImageChops.difference(image, background)\n    diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n    bbox = diff.getbbox()\n    if bbox:\n        image = image.crop(bbox)\n    return image", "title": ""}
{"_id": "d14508", "text": "def on_close(self, evt):\n    \"\"\"\n    Pop-up menu and wx.EVT_CLOSE closing event\n    \"\"\"\n    self.stop() # DoseWatcher\n    if evt.EventObject is not self: # Avoid deadlocks\n      self.Close() # wx.Frame\n    evt.Skip()", "title": ""}
{"_id": "d14509", "text": "def _mean_absolute_error(y, y_pred, w):\n    \"\"\"Calculate the mean absolute error.\"\"\"\n    return np.average(np.abs(y_pred - y), weights=w)", "title": ""}
{"_id": "d14510", "text": "def xeval(source, optimize=True):\n    \"\"\"Compiles to native Python bytecode and runs program, returning the\n    topmost value on the stack.\n\n    Args:\n        optimize: Whether to optimize the code after parsing it.\n\n    Returns:\n        None: If the stack is empty\n        obj: If the stack contains a single value\n        [obj, obj, ...]: If the stack contains many values\n    \"\"\"\n    native = xcompile(source, optimize=optimize)\n    return native()", "title": ""}
{"_id": "d14511", "text": "def yank(event):\n    \"\"\"\n    Paste before cursor.\n    \"\"\"\n    event.current_buffer.paste_clipboard_data(\n        event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)", "title": ""}
{"_id": "d14512", "text": "def Parse(text):\n  \"\"\"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.\n  \"\"\"\n  precondition.AssertType(text, Text)\n\n  if compatibility.PY2:\n    text = text.encode(\"utf-8\")\n\n  return yaml.safe_load(text)", "title": ""}
{"_id": "d14513", "text": "def _monitor_callback_wrapper(callback):\n    \"\"\"A wrapper for the user-defined handle.\"\"\"\n    def callback_handle(name, array, _):\n        \"\"\" ctypes function \"\"\"\n        callback(name, array)\n    return callback_handle", "title": ""}
{"_id": "d14514", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d14515", "text": "def cint32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):\n        return np.fromiter(cptr, dtype=np.int32, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d14516", "text": "def _run_asyncio(loop, zmq_context):\n    \"\"\"\n    Run asyncio (should be called in a thread) and close the loop and the zmq context when the thread ends\n    :param loop:\n    :param zmq_context:\n    :return:\n    \"\"\"\n    try:\n        asyncio.set_event_loop(loop)\n        loop.run_forever()\n    except:\n        pass\n    finally:\n        loop.close()\n        zmq_context.destroy(1000)", "title": ""}
{"_id": "d14517", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d14518", "text": "def cfloat32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n        return np.fromiter(cptr, dtype=np.float32, count=length)\n    else:\n        raise RuntimeError('Expected float pointer')", "title": ""}
{"_id": "d14519", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d14520", "text": "def is_defined(self, objtxt, force_import=False):\n        \"\"\"Return True if object is defined\"\"\"\n        return self.interpreter.is_defined(objtxt, force_import)", "title": ""}
{"_id": "d14521", "text": "def validate(self, obj):\n        \"\"\" Raises django.core.exceptions.ValidationError if any validation error exists \"\"\"\n\n        if not isinstance(obj, self.model_class):\n            raise ValidationError('Invalid object(%s) for service %s' % (type(obj), type(self)))\n        LOG.debug(u'Object %s state: %s', self.model_class, obj.__dict__)\n        obj.full_clean()", "title": ""}
{"_id": "d14522", "text": "def contains_geometric_info(var):\n    \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)", "title": ""}
{"_id": "d14523", "text": "def _idx_col2rowm(d):\n    \"\"\"Generate indexes to change from col-major to row-major ordering\"\"\"\n    if 0 == len(d):\n        return 1\n    if 1 == len(d):\n        return np.arange(d[0])\n    # order='F' indicates column-major ordering\n    idx = np.array(np.arange(np.prod(d))).reshape(d, order='F').T\n    return idx.flatten(order='F')", "title": ""}
{"_id": "d14524", "text": "def is_date_type(cls):\n    \"\"\"Return True if the class is a date type.\"\"\"\n    if not isinstance(cls, type):\n        return False\n    return issubclass(cls, date) and not issubclass(cls, datetime)", "title": ""}
{"_id": "d14525", "text": "def notin(arg, values):\n    \"\"\"\n    Like isin, but checks whether this expression's value(s) are not\n    contained in the passed values. See isin docs for full usage.\n    \"\"\"\n    op = ops.NotContains(arg, values)\n    return op.to_expr()", "title": ""}
{"_id": "d14526", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d14527", "text": "def error_rate(predictions, labels):\n  \"\"\"Return the error rate based on dense predictions and 1-hot labels.\"\"\"\n  return 100.0 - (\n      100.0 *\n      np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) /\n      predictions.shape[0])", "title": ""}
{"_id": "d14528", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d14529", "text": "def createdb():\n    \"\"\"Create database tables from sqlalchemy models\"\"\"\n    manager.db.engine.echo = True\n    manager.db.create_all()\n    set_alembic_revision()", "title": ""}
{"_id": "d14530", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d14531", "text": "def cmd_reindex():\n    \"\"\"Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.\n\n    The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until\n    the rename succeeds.\n    \"\"\"\n    db = connect(args.database)\n    for idx in args.indexes:\n        pg_reindex(db, idx)", "title": ""}
{"_id": "d14532", "text": "def is_port_open(port, host=\"127.0.0.1\"):\n    \"\"\"\n    Check if a port is open\n    :param port:\n    :param host:\n    :return bool:\n    \"\"\"\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    try:\n        s.connect((host, int(port)))\n        s.shutdown(2)\n        return True\n    except Exception as e:\n        return False", "title": ""}
{"_id": "d14533", "text": "def extend(self, iterable):\n        \"\"\"Extend the list by appending all the items in the given list.\"\"\"\n        return super(Collection, self).extend(\n            self._ensure_iterable_is_valid(iterable))", "title": ""}
{"_id": "d14534", "text": "def is_power_of_2(num):\n    \"\"\"Return whether `num` is a power of two\"\"\"\n    log = math.log2(num)\n    return int(log) == float(log)", "title": ""}
{"_id": "d14535", "text": "def ci(a, which=95, axis=None):\n    \"\"\"Return a percentile range from an array of values.\"\"\"\n    p = 50 - which / 2, 50 + which / 2\n    return percentiles(a, p, axis)", "title": ""}
{"_id": "d14536", "text": "def cmp_contents(filename1, filename2):\n    \"\"\" Returns True if contents of the files are the same\n\n    Parameters\n    ----------\n    filename1 : str\n        filename of first file to compare\n    filename2 : str\n        filename of second file to compare\n\n    Returns\n    -------\n    tf : bool\n        True if binary contents of `filename1` is same as binary contents of\n        `filename2`, False otherwise.\n    \"\"\"\n    with open_readable(filename1, 'rb') as fobj:\n        contents1 = fobj.read()\n    with open_readable(filename2, 'rb') as fobj:\n        contents2 = fobj.read()\n    return contents1 == contents2", "title": ""}
{"_id": "d14537", "text": "def transform_from_rot_trans(R, t):\n    \"\"\"Transforation matrix from rotation matrix and translation vector.\"\"\"\n    R = R.reshape(3, 3)\n    t = t.reshape(3, 1)\n    return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))", "title": ""}
{"_id": "d14538", "text": "def is_client(self):\n        \"\"\"Return True if Glances is running in client mode.\"\"\"\n        return (self.args.client or self.args.browser) and not self.args.server", "title": ""}
{"_id": "d14539", "text": "def _linear_interpolation(x, X, Y):\n    \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n    \"\"\"\n    return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "title": ""}
{"_id": "d14540", "text": "def _is_utf_8(txt):\n    \"\"\"\n    Check a string is utf-8 encoded\n\n    :param bytes txt: utf-8 string\n    :return: Whether the string\\\n    is utf-8 encoded or not\n    :rtype: bool\n    \"\"\"\n    assert isinstance(txt, six.binary_type)\n\n    try:\n        _ = six.text_type(txt, 'utf-8')\n    except (TypeError, UnicodeEncodeError):\n        return False\n    else:\n        return True", "title": ""}
{"_id": "d14541", "text": "def loganalytics_data_plane_client(cli_ctx, _):\n    \"\"\"Initialize Log Analytics data client for use with CLI.\"\"\"\n    from .vendored_sdks.loganalytics import LogAnalyticsDataClient\n    from azure.cli.core._profile import Profile\n    profile = Profile(cli_ctx=cli_ctx)\n    cred, _, _ = profile.get_login_credentials(\n        resource=\"https://api.loganalytics.io\")\n    return LogAnalyticsDataClient(cred)", "title": ""}
{"_id": "d14542", "text": "def validate(self, val):\n        \"\"\"\n        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.\n        \"\"\"\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))", "title": ""}
{"_id": "d14543", "text": "def token_accuracy(labels, outputs):\n  \"\"\"Compute tokenwise (elementwise) accuracy.\n\n  Args:\n    labels: ground-truth labels, shape=(batch, seq_length)\n    outputs: predicted tokens, shape=(batch, seq_length)\n  Returns:\n    Two ops, one for getting the current average accuracy and another for\n    updating the running average estimate.\n  \"\"\"\n  weights = tf.to_float(tf.not_equal(labels, 0))\n  return tf.metrics.accuracy(labels, outputs, weights=weights)", "title": ""}
{"_id": "d14544", "text": "def isin(self, column, compare_list):\n        \"\"\"\n        Returns a boolean list where each elements is whether that element in the column is in the compare_list.\n\n        :param column: single column name, does not work for multiple columns\n        :param compare_list: list of items to compare to\n        :return: list of booleans\n        \"\"\"\n        return [x in compare_list for x in self._data[self._columns.index(column)]]", "title": ""}
{"_id": "d14545", "text": "def to_dotfile(self):\n        \"\"\" Writes a DOT graphviz file of the domain structure, and returns the filename\"\"\"\n        domain = self.get_domain()\n        filename = \"%s.dot\" % (self.__class__.__name__)\n        nx.write_dot(domain, filename)\n        return filename", "title": ""}
{"_id": "d14546", "text": "def check(self, var):\n        \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n        if not isinstance(var, _str_type): return False\n        return _enum_mangle(var) in self._consts", "title": ""}
{"_id": "d14547", "text": "def add_bg(img, padding, color=COL_WHITE):\n    \"\"\"\n    Adds a padding to the given image as background of specified color\n\n    :param img: Input image.\n    :param padding: constant padding around the image.\n    :param color: background color that needs to filled for the newly padded region.\n    :return: New image with background.\n    \"\"\"\n    img = gray3(img)\n    h, w, d = img.shape\n    new_img = np.ones((h + 2*padding, w + 2*padding, d)) * color[:d]\n    new_img = new_img.astype(np.uint8)\n    set_img_box(new_img, (padding, padding, w, h), img)\n    return new_img", "title": ""}
{"_id": "d14548", "text": "def is_element_present(driver, selector, by=By.CSS_SELECTOR):\n    \"\"\"\n    Returns whether the specified element selector is present 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 present)\n    \"\"\"\n    try:\n        driver.find_element(by=by, value=selector)\n        return True\n    except Exception:\n        return False", "title": ""}
{"_id": "d14549", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d14550", "text": "def instance_contains(container, item):\n    \"\"\"Search into instance attributes, properties and return values of no-args methods.\"\"\"\n    return item in (member for _, member in inspect.getmembers(container))", "title": ""}
{"_id": "d14551", "text": "def deep_update(d, u):\n  \"\"\"Deeply updates a dictionary. List values are concatenated.\n\n  Args:\n    d (dict): First dictionary which will be updated\n    u (dict): Second dictionary use to extend the first one\n\n  Returns:\n    dict: The merge dictionary\n\n  \"\"\"\n\n  for k, v in u.items():\n    if isinstance(v, Mapping):\n      d[k] = deep_update(d.get(k, {}), v)\n    elif isinstance(v, list):\n      existing_elements = d.get(k, [])\n      d[k] = existing_elements + [ele for ele in v if ele not in existing_elements]\n    else:\n      d[k] = v\n\n  return d", "title": ""}
{"_id": "d14552", "text": "def url_syntax_check(url):  # pragma: no cover\n    \"\"\"\n    Check the syntax of the given URL.\n\n    :param url: The URL to check the syntax for.\n    :type url: str\n\n    :return: The syntax validity.\n    :rtype: bool\n\n    .. warning::\n        If an empty or a non-string :code:`url` is given, we return :code:`None`.\n    \"\"\"\n\n    if url and isinstance(url, str):\n        # The given URL is not empty nor None.\n        # and\n        # * The given URL is a string.\n\n        # We silently load the configuration.\n        load_config(True)\n\n        return Check(url).is_url_valid()\n\n    # We return None, there is nothing to check.\n    return None", "title": ""}
{"_id": "d14553", "text": "def strip_comment_marker(text):\n    \"\"\" Strip # markers at the front of a block of comment text.\n    \"\"\"\n    lines = []\n    for line in text.splitlines():\n        lines.append(line.lstrip('#'))\n    text = textwrap.dedent('\\n'.join(lines))\n    return text", "title": ""}
{"_id": "d14554", "text": "def _clear(self):\n        \"\"\"Resets all assigned data for the current message.\"\"\"\n        self._finished = False\n        self._measurement = None\n        self._message = None\n        self._message_body = None", "title": ""}
{"_id": "d14555", "text": "def add_suffix(fullname, suffix):\n    \"\"\" Add suffix to a full file name\"\"\"\n    name, ext = os.path.splitext(fullname)\n    return name + '_' + suffix + ext", "title": ""}
{"_id": "d14556", "text": "def trim(self):\n        \"\"\"Clear not used counters\"\"\"\n        for key, value in list(iteritems(self.counters)):\n            if value.empty():\n                del self.counters[key]", "title": ""}
{"_id": "d14557", "text": "def adjacency(tree):\n    \"\"\"\n    Construct the adjacency matrix of the tree\n    :param tree:\n    :return:\n    \"\"\"\n    dd = ids(tree)\n    N = len(dd)\n    A = np.zeros((N, N))\n\n    def _adj(node):\n        if np.isscalar(node):\n            return\n        elif isinstance(node, tuple) and len(node) == 2:\n            A[dd[node], dd[node[0]]] = 1\n            A[dd[node[0]], dd[node]] = 1\n            _adj(node[0])\n\n            A[dd[node], dd[node[1]]] = 1\n            A[dd[node[1]], dd[node]] = 1\n            _adj(node[1])\n\n    _adj(tree)\n    return A", "title": ""}
{"_id": "d14558", "text": "def paste(cmd=paste_cmd, stdout=PIPE):\n    \"\"\"Returns system clipboard contents.\n    \"\"\"\n    return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')", "title": ""}
{"_id": "d14559", "text": "def adjacency(tree):\n    \"\"\"\n    Construct the adjacency matrix of the tree\n    :param tree:\n    :return:\n    \"\"\"\n    dd = ids(tree)\n    N = len(dd)\n    A = np.zeros((N, N))\n\n    def _adj(node):\n        if np.isscalar(node):\n            return\n        elif isinstance(node, tuple) and len(node) == 2:\n            A[dd[node], dd[node[0]]] = 1\n            A[dd[node[0]], dd[node]] = 1\n            _adj(node[0])\n\n            A[dd[node], dd[node[1]]] = 1\n            A[dd[node[1]], dd[node]] = 1\n            _adj(node[1])\n\n    _adj(tree)\n    return A", "title": ""}
{"_id": "d14560", "text": "def clone(src, **kwargs):\n    \"\"\"Clones object with optionally overridden fields\"\"\"\n    obj = object.__new__(type(src))\n    obj.__dict__.update(src.__dict__)\n    obj.__dict__.update(kwargs)\n    return obj", "title": ""}
{"_id": "d14561", "text": "def managepy(cmd, extra=None):\n    \"\"\"Run manage.py using this component's specific Django settings\"\"\"\n\n    extra = extra.split() if extra else []\n    run_django_cli(['invoke', cmd] + extra)", "title": ""}
{"_id": "d14562", "text": "def activate():\n    \"\"\"\n    Usage:\n      containment activate\n    \"\"\"\n    # This is derived from the clone\n    cli = CommandLineInterface()\n    cli.ensure_config()\n    cli.write_dockerfile()\n    cli.build()\n    cli.run()", "title": ""}
{"_id": "d14563", "text": "def ansi(color, text):\n    \"\"\"Wrap text in an ansi escape sequence\"\"\"\n    code = COLOR_CODES[color]\n    return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)", "title": ""}
{"_id": "d14564", "text": "def file_read(filename):\n    \"\"\"Read a file and close it.  Returns the file source.\"\"\"\n    fobj = open(filename,'r');\n    source = fobj.read();\n    fobj.close()\n    return source", "title": ""}
{"_id": "d14565", "text": "def mimetype(self):\n        \"\"\"MIME type of the asset.\"\"\"\n        return (self.environment.mimetypes.get(self.format_extension) or\n                self.compiler_mimetype or 'application/octet-stream')", "title": ""}
{"_id": "d14566", "text": "def socket_close(self):\n        \"\"\"Close our socket.\"\"\"\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET", "title": ""}
{"_id": "d14567", "text": "def ts_func(f):\n    \"\"\"\n    This wraps a function that would normally only accept an array\n    and allows it to operate on a DataFrame. Useful for applying\n    numpy functions to DataFrames.\n    \"\"\"\n    def wrap_func(df, *args):\n        # TODO: should vectorize to apply over all columns?\n        return Chromatogram(f(df.values, *args), df.index, df.columns)\n    return wrap_func", "title": ""}
{"_id": "d14568", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d14569", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d14570", "text": "def generate_hash(self, length=30):\n        \"\"\" Generate random string of given length \"\"\"\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", "title": ""}
{"_id": "d14571", "text": "def apply(f, obj, *args, **kwargs):\n    \"\"\"Apply a function in parallel to each element of the input\"\"\"\n    return vectorize(f)(obj, *args, **kwargs)", "title": ""}
{"_id": "d14572", "text": "def angle_between_vectors(x, y):\n    \"\"\" Compute the angle between vector x and y \"\"\"\n    dp = dot_product(x, y)\n    if dp == 0:\n        return 0\n    xm = magnitude(x)\n    ym = magnitude(y)\n    return math.acos(dp / (xm*ym)) * (180. / math.pi)", "title": ""}
{"_id": "d14573", "text": "def transform(self, df):\n        \"\"\"\n        Transforms a DataFrame in place. Computes all outputs of the DataFrame.\n\n        Args:\n            df (pandas.DataFrame): DataFrame to transform.\n        \"\"\"\n        for name, function in self.outputs:\n            df[name] = function(df)", "title": ""}
{"_id": "d14574", "text": "def has_multiline_items(maybe_list: Optional[Sequence[str]]):\n    \"\"\"Check whether one of the items in the list has multiple lines.\"\"\"\n    return maybe_list and any(is_multiline(item) for item in maybe_list)", "title": ""}
{"_id": "d14575", "text": "def apply_conditional_styles(self, cbfct):\n        \"\"\"\n        Ability to provide dynamic styling of the cell based on its value.\n        :param cbfct: function(cell_value) should return a dict of format commands to apply to that cell\n        :return: self\n        \"\"\"\n        for ridx in range(self.nrows):\n            for cidx in range(self.ncols):\n                fmts = cbfct(self.actual_values.iloc[ridx, cidx])\n                fmts and self.iloc[ridx, cidx].apply_styles(fmts)\n        return self", "title": ""}
{"_id": "d14576", "text": "def do_exit(self, arg):\n        \"\"\"Exit the shell session.\"\"\"\n\n        if self.current:\n            self.current.close()\n        self.resource_manager.close()\n        del self.resource_manager\n        return True", "title": ""}
{"_id": "d14577", "text": "def SegmentMin(a, ids):\n    \"\"\"\n    Segmented min op.\n    \"\"\"\n    func = lambda idxs: np.amin(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d14578", "text": "def random_id(length):\n    \"\"\"Generates a random ID of given length\"\"\"\n\n    def char():\n        \"\"\"Generate single random char\"\"\"\n\n        return random.choice(string.ascii_letters + string.digits)\n\n    return \"\".join(char() for _ in range(length))", "title": ""}
{"_id": "d14579", "text": "def maxId(self):\n        \"\"\"int: current max id of objects\"\"\"\n        if len(self.model.db) == 0:\n            return 0\n\n        return max(map(lambda obj: obj[\"id\"], self.model.db))", "title": ""}
{"_id": "d14580", "text": "def _join(verb):\n    \"\"\"\n    Join helper\n    \"\"\"\n    data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n    # Preserve x groups\n    if isinstance(verb.x, GroupedDataFrame):\n        data.plydata_groups = list(verb.x.plydata_groups)\n    return data", "title": ""}
{"_id": "d14581", "text": "def locked_delete(self):\n        \"\"\"Delete credentials from the SQLAlchemy datastore.\"\"\"\n        filters = {self.key_name: self.key_value}\n        self.session.query(self.model_class).filter_by(**filters).delete()", "title": ""}
{"_id": "d14582", "text": "def rpc_fix_code(self, source, directory):\n        \"\"\"Formats Python code to conform to the PEP 8 style guide.\n\n        \"\"\"\n        source = get_source(source)\n        return fix_code(source, directory)", "title": ""}
{"_id": "d14583", "text": "def get_average_length_of_string(strings):\n    \"\"\"Computes average length of words\n\n    :param strings: list of words\n    :return: Average length of word on list\n    \"\"\"\n    if not strings:\n        return 0\n\n    return sum(len(word) for word in strings) / len(strings)", "title": ""}
{"_id": "d14584", "text": "def listified_tokenizer(source):\n    \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n    io_obj = io.StringIO(source)\n    return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]", "title": ""}
{"_id": "d14585", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d14586", "text": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "title": ""}
{"_id": "d14587", "text": "def create_alias(self):\n        \"\"\"Create lambda alias with env name and points it to $LATEST.\"\"\"\n        LOG.info('Creating alias %s', self.env)\n\n        try:\n            self.lambda_client.create_alias(\n                FunctionName=self.app_name,\n                Name=self.env,\n                FunctionVersion='$LATEST',\n                Description='Alias for {}'.format(self.env))\n        except boto3.exceptions.botocore.exceptions.ClientError as error:\n            LOG.debug('Create alias error: %s', error)\n            LOG.info(\"Alias creation failed. Retrying...\")\n            raise", "title": ""}
{"_id": "d14588", "text": "def alter_change_column(self, table, column, field):\n        \"\"\"Support change columns.\"\"\"\n        return self._update_column(table, column, lambda a, b: b)", "title": ""}
{"_id": "d14589", "text": "def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key):\n    \"\"\"Creates an AWS Chalice project for deployment to AWS Lambda.\"\"\"\n    from canari.commands.create_aws_lambda import create_aws_lambda\n    create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key)", "title": ""}
{"_id": "d14590", "text": "def rgba_bytes_tuple(self, x):\n        \"\"\"Provides the color corresponding to value `x` in the\n        form of a tuple (R,G,B,A) with int values between 0 and 255.\n        \"\"\"\n        return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))", "title": ""}
{"_id": "d14591", "text": "def list_rds(region, filter_by_kwargs):\n    \"\"\"List all RDS thingys.\"\"\"\n    conn = boto.rds.connect_to_region(region)\n    instances = conn.get_all_dbinstances()\n    return lookup(instances, filter_by=filter_by_kwargs)", "title": ""}
{"_id": "d14592", "text": "def cmyk(c, m, y, k):\n    \"\"\"\n    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.\n    \"\"\"\n    return Color(\"cmyk\", c, m, y, k)", "title": ""}
{"_id": "d14593", "text": "def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):\n    \"\"\"Extract a ALZIP archive.\"\"\"\n    return [cmd, '-d', outdir, archive]", "title": ""}
{"_id": "d14594", "text": "def html(header_rows):\n    \"\"\"\n    Convert a list of tuples describing a table into a HTML string\n    \"\"\"\n    name = 'table%d' % next(tablecounter)\n    return HtmlTable([map(str, row) for row in header_rows], name).render()", "title": ""}
{"_id": "d14595", "text": "def bytes_base64(x):\n    \"\"\"Turn bytes into base64\"\"\"\n    if six.PY2:\n        return base64.encodestring(x).replace('\\n', '')\n    return base64.encodebytes(bytes_encode(x)).replace(b'\\n', b'')", "title": ""}
{"_id": "d14596", "text": "def _merge_meta(model1, model2):\n    \"\"\"Simple merge of samplesets.\"\"\"\n    w1 = _get_meta(model1)\n    w2 = _get_meta(model2)\n    return metadata.merge(w1, w2, metadata_conflicts='silent')", "title": ""}
{"_id": "d14597", "text": "def _updateItemComboBoxIndex(self, item, column, num):\n        \"\"\"Callback for comboboxes: notifies us that a combobox for the given item and column has changed\"\"\"\n        item._combobox_current_index[column] = num\n        item._combobox_current_value[column] = item._combobox_option_list[column][num][0]", "title": ""}
{"_id": "d14598", "text": "def multi_pop(d, *args):\n    \"\"\" pops multiple keys off a dict like object \"\"\"\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval", "title": ""}
{"_id": "d14599", "text": "def onchange(self, value):\n        \"\"\"Called when a new DropDownItem gets selected.\n        \"\"\"\n        log.debug('combo box. selected %s' % value)\n        self.select_by_value(value)\n        return (value, )", "title": ""}
{"_id": "d14600", "text": "def hidden_cursor(self):\n        \"\"\"Return a context manager that hides the cursor while inside it and\n        makes it visible on leaving.\"\"\"\n        self.stream.write(self.hide_cursor)\n        try:\n            yield\n        finally:\n            self.stream.write(self.normal_cursor)", "title": ""}
{"_id": "d14601", "text": "def clean_whitespace(string, compact=False):\n    \"\"\"Return string with compressed whitespace.\"\"\"\n    for a, b in (('\\r\\n', '\\n'), ('\\r', '\\n'), ('\\n\\n', '\\n'),\n                 ('\\t', ' '), ('  ', ' ')):\n        string = string.replace(a, b)\n    if compact:\n        for a, b in (('\\n', ' '), ('[ ', '['),\n                     ('  ', ' '), ('  ', ' '), ('  ', ' ')):\n            string = string.replace(a, b)\n    return string.strip()", "title": ""}
{"_id": "d14602", "text": "def cpp_checker(code, working_directory):\n    \"\"\"Return checker.\"\"\"\n    return gcc_checker(code, '.cpp',\n                       [os.getenv('CXX', 'g++'), '-std=c++0x'] + INCLUDE_FLAGS,\n                       working_directory=working_directory)", "title": ""}
{"_id": "d14603", "text": "def clean_whitespace(string, compact=False):\n    \"\"\"Return string with compressed whitespace.\"\"\"\n    for a, b in (('\\r\\n', '\\n'), ('\\r', '\\n'), ('\\n\\n', '\\n'),\n                 ('\\t', ' '), ('  ', ' ')):\n        string = string.replace(a, b)\n    if compact:\n        for a, b in (('\\n', ' '), ('[ ', '['),\n                     ('  ', ' '), ('  ', ' '), ('  ', ' ')):\n            string = string.replace(a, b)\n    return string.strip()", "title": ""}
{"_id": "d14604", "text": "def ver_to_tuple(value):\n    \"\"\"\n    Convert version like string to a tuple of integers.\n    \"\"\"\n    return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "title": ""}
{"_id": "d14605", "text": "def vector_distance(a, b):\n    \"\"\"The Euclidean distance between two vectors.\"\"\"\n    a = np.array(a)\n    b = np.array(b)\n    return np.linalg.norm(a - b)", "title": ""}
{"_id": "d14606", "text": "def getBuffer(x):\n    \"\"\"\n    Copy @x into a (modifiable) ctypes byte array\n    \"\"\"\n    b = bytes(x)\n    return (c_ubyte * len(b)).from_buffer_copy(bytes(x))", "title": ""}
{"_id": "d14607", "text": "def compose_all(tups):\n  \"\"\"Compose all given tuples together.\"\"\"\n  from . import ast  # I weep for humanity\n  return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))", "title": ""}
{"_id": "d14608", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d14609", "text": "def config_parser_to_dict(config_parser):\n    \"\"\"\n    Convert a ConfigParser to a dictionary.\n    \"\"\"\n    response = {}\n\n    for section in config_parser.sections():\n        for option in config_parser.options(section):\n            response.setdefault(section, {})[option] = config_parser.get(section, option)\n\n    return response", "title": ""}
{"_id": "d14610", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d14611", "text": "def list_string_to_dict(string):\n    \"\"\"Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.\"\"\"\n    dictionary = {}\n    for idx, c in enumerate(string):\n        dictionary.update({c: idx})\n    return dictionary", "title": ""}
{"_id": "d14612", "text": "def dot(self, w):\n        \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n        return sum([x * y for x, y in zip(self, w)])", "title": ""}
{"_id": "d14613", "text": "def fromiterable(cls, itr):\n        \"\"\"Initialize from iterable\"\"\"\n        x, y, z = itr\n        return cls(x, y, z)", "title": ""}
{"_id": "d14614", "text": "def dot(self, w):\n        \"\"\"Return the dotproduct between self and another vector.\"\"\"\n\n        return sum([x * y for x, y in zip(self, w)])", "title": ""}
{"_id": "d14615", "text": "def time2seconds(t):\n    \"\"\"Returns seconds since 0h00.\"\"\"\n    return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6", "title": ""}
{"_id": "d14616", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d14617", "text": "def string_to_float_list(string_var):\n        \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n        try:\n            return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n        except:\n            return [float(s) for s in string_var.strip('[').strip(']').split(',')]", "title": ""}
{"_id": "d14618", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d14619", "text": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n    \"\"\"Convolve 2d gaussian.\"\"\"\n    result = scipy.ndimage.filters.correlate1d(\n        image, gaussian_kernel_1d, axis=0)\n    result = scipy.ndimage.filters.correlate1d(\n        result, gaussian_kernel_1d, axis=1)\n    return result", "title": ""}
{"_id": "d14620", "text": "def n_choose_k(n, k):\n    \"\"\" get the number of quartets as n-choose-k. This is used\n    in equal splits to decide whether a split should be exhaustively sampled\n    or randomly sampled. Edges near tips can be exhaustive while highly nested\n    edges probably have too many quartets\n    \"\"\"\n    return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1))", "title": ""}
{"_id": "d14621", "text": "def __copy__(self):\n        \"\"\"A magic method to implement shallow copy behavior.\"\"\"\n        return self.__class__.load(self.dump(), context=self.context)", "title": ""}
{"_id": "d14622", "text": "def stddev(values, meanval=None):  #from AI: A Modern Appproach\n    \"\"\"The standard deviation of a set of values.\n    Pass in the mean if you already know it.\"\"\"\n    if meanval == None: meanval = mean(values)\n    return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) )", "title": ""}
{"_id": "d14623", "text": "def normalize(self, dt, is_dst=False):\n        \"\"\"Correct the timezone information on the given datetime\"\"\"\n        if dt.tzinfo is self:\n            return dt\n        if dt.tzinfo is None:\n            raise ValueError('Naive time - no tzinfo set')\n        return dt.astimezone(self)", "title": ""}
{"_id": "d14624", "text": "def covariance(self,pt0,pt1):\n        \"\"\" get the covarince between two points implied by Vario2d\n\n        Parameters\n        ----------\n        pt0 : (iterable of len 2)\n            first point x and y\n        pt1 : (iterable of len 2)\n            second point x and y\n\n        Returns\n        -------\n        cov : float\n            covariance between pt0 and pt1\n\n        \"\"\"\n\n        x = np.array([pt0[0],pt1[0]])\n        y = np.array([pt0[1],pt1[1]])\n        names = [\"n1\",\"n2\"]\n        return self.covariance_matrix(x,y,names=names).x[0,1]", "title": ""}
{"_id": "d14625", "text": "def inverse(self):\n        \"\"\"\n        Returns inverse of transformation.\n        \"\"\"\n        invr = np.linalg.inv(self.affine_matrix)\n        return SymmOp(invr)", "title": ""}
{"_id": "d14626", "text": "def covariance(self,pt0,pt1):\n        \"\"\" get the covarince between two points implied by Vario2d\n\n        Parameters\n        ----------\n        pt0 : (iterable of len 2)\n            first point x and y\n        pt1 : (iterable of len 2)\n            second point x and y\n\n        Returns\n        -------\n        cov : float\n            covariance between pt0 and pt1\n\n        \"\"\"\n\n        x = np.array([pt0[0],pt1[0]])\n        y = np.array([pt0[1],pt1[1]])\n        names = [\"n1\",\"n2\"]\n        return self.covariance_matrix(x,y,names=names).x[0,1]", "title": ""}
{"_id": "d14627", "text": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "title": ""}
{"_id": "d14628", "text": "def build_parser():\n    \"\"\"Build the script's argument parser.\"\"\"\n\n    parser = argparse.ArgumentParser(description=\"The IOTile task supervisor\")\n    parser.add_argument('-c', '--config', help=\"config json with options\")\n    parser.add_argument('-v', '--verbose', action=\"count\", default=0, help=\"Increase logging verbosity\")\n\n    return parser", "title": ""}
{"_id": "d14629", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d14630", "text": "def get_dt_list(fn_list):\n    \"\"\"Get list of datetime objects, extracted from a filename\n    \"\"\"\n    dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])\n    return dt_list", "title": ""}
{"_id": "d14631", "text": "def ExecuteRaw(self, position, command):\n    \"\"\"Send a command string to gdb.\"\"\"\n    self.EnsureGdbPosition(position[0], None, None)\n    return gdb.execute(command, to_string=True)", "title": ""}
{"_id": "d14632", "text": "def subscribe_to_quorum_channel(self):\n        \"\"\"In case the experiment enforces a quorum, listen for notifications\n        before creating Partipant objects.\n        \"\"\"\n        from dallinger.experiment_server.sockets import chat_backend\n\n        self.log(\"Bot subscribing to quorum channel.\")\n        chat_backend.subscribe(self, \"quorum\")", "title": ""}
{"_id": "d14633", "text": "def print_latex(o):\n    \"\"\"A function to generate the latex representation of sympy\n    expressions.\"\"\"\n    if can_print_latex(o):\n        s = latex(o, mode='plain')\n        s = s.replace('\\\\dag','\\\\dagger')\n        s = s.strip('$')\n        return '$$%s$$' % s\n    # Fallback to the string printer\n    return None", "title": ""}
{"_id": "d14634", "text": "def _string_hash(s):\n    \"\"\"String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).\"\"\"\n    h = 5381\n    for c in s:\n        h = h * 33 + ord(c)\n    return h", "title": ""}
{"_id": "d14635", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d14636", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d14637", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d14638", "text": "def trans_from_matrix(matrix):\n    \"\"\" Convert a vtk matrix to a numpy.ndarray \"\"\"\n    t = np.zeros((4, 4))\n    for i in range(4):\n        for j in range(4):\n            t[i, j] = matrix.GetElement(i, j)\n    return t", "title": ""}
{"_id": "d14639", "text": "def get_mod_time(self, path):\n        \"\"\"\n        Returns a datetime object representing the last time the file was modified\n\n        :param path: remote file path\n        :type path: string\n        \"\"\"\n        conn = self.get_conn()\n        ftp_mdtm = conn.sendcmd('MDTM ' + path)\n        time_val = ftp_mdtm[4:]\n        # time_val optionally has microseconds\n        try:\n            return datetime.datetime.strptime(time_val, \"%Y%m%d%H%M%S.%f\")\n        except ValueError:\n            return datetime.datetime.strptime(time_val, '%Y%m%d%H%M%S')", "title": ""}
{"_id": "d14640", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d14641", "text": "def restart_program():\n    \"\"\"\n    DOES NOT WORK WELL WITH MOPIDY\n    Hack from\n    https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program\n    to support updating the settings, since mopidy is not able to do that yet\n    Restarts the current program\n    Note: this function does not return. Any cleanup action (like\n    saving data) must be done before calling this function\n    \"\"\"\n\n    python = sys.executable\n    os.execl(python, python, * sys.argv)", "title": ""}
{"_id": "d14642", "text": "def set_as_object(self, value):\n        \"\"\"\n        Sets a new value to map element\n\n        :param value: a new element or map value.\n        \"\"\"\n        self.clear()\n        map = MapConverter.to_map(value)\n        self.append(map)", "title": ""}
{"_id": "d14643", "text": "def construct_from_string(cls, string):\n        \"\"\"\n        Construction from a string, raise a TypeError if not\n        possible\n        \"\"\"\n        if string == cls.name:\n            return cls()\n        raise TypeError(\"Cannot construct a '{}' from \"\n                        \"'{}'\".format(cls, string))", "title": ""}
{"_id": "d14644", "text": "def _update_font_style(self, font_style):\n        \"\"\"Updates font style widget\n\n        Parameters\n        ----------\n\n        font_style: Integer\n        \\tButton down iif font_style == wx.FONTSTYLE_ITALIC\n\n        \"\"\"\n\n        toggle_state = font_style & wx.FONTSTYLE_ITALIC == wx.FONTSTYLE_ITALIC\n\n        self.ToggleTool(wx.FONTFLAG_ITALIC, toggle_state)", "title": ""}
{"_id": "d14645", "text": "def string_to_list(string, sep=\",\", filter_empty=False):\n    \"\"\"Transforma una string con elementos separados por `sep` en una lista.\"\"\"\n    return [value.strip() for value in string.split(sep)\n            if (not filter_empty or value)]", "title": ""}
{"_id": "d14646", "text": "def _histplot_op(ax, data, **kwargs):\n    \"\"\"Add a histogram for the data to the axes.\"\"\"\n    bins = get_bins(data)\n    ax.hist(data, bins=bins, align=\"left\", density=True, **kwargs)\n    return ax", "title": ""}
{"_id": "d14647", "text": "def _single_page_pdf(page):\n    \"\"\"Construct a single page PDF from the provided page in memory\"\"\"\n    pdf = Pdf.new()\n    pdf.pages.append(page)\n    bio = BytesIO()\n    pdf.save(bio)\n    bio.seek(0)\n    return bio.read()", "title": ""}
{"_id": "d14648", "text": "def norm_vec(vector):\n    \"\"\"Normalize the length of a vector to one\"\"\"\n    assert len(vector) == 3\n    v = np.array(vector)\n    return v/np.sqrt(np.sum(v**2))", "title": ""}
{"_id": "d14649", "text": "def from_json_str(cls, json_str):\n    \"\"\"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.\n    \"\"\"\n    return cls.from_json(json.loads(json_str, cls=JsonDecoder))", "title": ""}
{"_id": "d14650", "text": "def start():\n    \"\"\"Starts the web server.\"\"\"\n    global app\n    bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n               debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n               quiet=conf.WebQuiet)", "title": ""}
{"_id": "d14651", "text": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "title": ""}
{"_id": "d14652", "text": "def start():\n    \"\"\"Starts the web server.\"\"\"\n    global app\n    bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n               debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n               quiet=conf.WebQuiet)", "title": ""}
{"_id": "d14653", "text": "def construct_from_string(cls, string):\n        \"\"\"\n        Construction from a string, raise a TypeError if not\n        possible\n        \"\"\"\n        if string == cls.name:\n            return cls()\n        raise TypeError(\"Cannot construct a '{}' from \"\n                        \"'{}'\".format(cls, string))", "title": ""}
{"_id": "d14654", "text": "def safe_setattr(obj, name, value):\n    \"\"\"Attempt to setattr but catch AttributeErrors.\"\"\"\n    try:\n        setattr(obj, name, value)\n        return True\n    except AttributeError:\n        return False", "title": ""}
{"_id": "d14655", "text": "def add_matplotlib_cmap(cm, name=None):\n    \"\"\"Add a matplotlib colormap.\"\"\"\n    global cmaps\n    cmap = matplotlib_to_ginga_cmap(cm, name=name)\n    cmaps[cmap.name] = cmap", "title": ""}
{"_id": "d14656", "text": "def camel_to_(s):\n    \"\"\"\n    Convert CamelCase to camel_case\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', s)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d14657", "text": "def _tab(content):\n    \"\"\"\n    Helper funcation that converts text-based get response\n    to tab separated values for additional manipulation.\n    \"\"\"\n    response = _data_frame(content).to_csv(index=False,sep='\\t')\n    return response", "title": ""}
{"_id": "d14658", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d14659", "text": "def cint32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):\n        return np.fromiter(cptr, dtype=np.int32, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d14660", "text": "def cartesian_product(arrays, flat=True, copy=False):\n    \"\"\"\n    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.\n    \"\"\"\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)", "title": ""}
{"_id": "d14661", "text": "def cfloat64_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\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')", "title": ""}
{"_id": "d14662", "text": "def to_snake_case(name):\n    \"\"\" Given a name in camelCase return in snake_case \"\"\"\n    s1 = FIRST_CAP_REGEX.sub(r'\\1_\\2', name)\n    return ALL_CAP_REGEX.sub(r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d14663", "text": "def cleanup_lib(self):\n        \"\"\" unload the previously loaded shared library \"\"\"\n        if not self.using_openmp:\n            #this if statement is necessary because shared libraries that use\n            #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP\n            logging.debug('unloading shared library')\n            _ctypes.dlclose(self.lib._handle)", "title": ""}
{"_id": "d14664", "text": "def _convert_to_array(array_like, dtype):\n        \"\"\"\n        Convert Matrix attributes which are array-like or buffer to array.\n        \"\"\"\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)", "title": ""}
{"_id": "d14665", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d14666", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d14667", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d14668", "text": "def expect_comment_end(self):\n        \"\"\"Expect a comment end and return the match object.\n        \"\"\"\n        match = self._expect_match('#}', COMMENT_END_PATTERN)\n        self.advance(match.end())", "title": ""}
{"_id": "d14669", "text": "def round_corner(radius, fill):\n    \"\"\"Draw a round corner\"\"\"\n    corner = Image.new('L', (radius, radius), 0)  # (0, 0, 0, 0))\n    draw = ImageDraw.Draw(corner)\n    draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill)\n    return corner", "title": ""}
{"_id": "d14670", "text": "def struct2dict(struct):\n    \"\"\"convert a ctypes structure to a dictionary\"\"\"\n    return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}", "title": ""}
{"_id": "d14671", "text": "def SetValue(self, row, col, value):\n        \"\"\"\n        Set value in the pandas DataFrame\n        \"\"\"\n        self.dataframe.iloc[row, col] = value", "title": ""}
{"_id": "d14672", "text": "def to_identifier(s):\n  \"\"\"\n  Convert snake_case to camel_case.\n  \"\"\"\n  if s.startswith('GPS'):\n      s = 'Gps' + s[3:]\n  return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s", "title": ""}
{"_id": "d14673", "text": "def convert_time_string(date_str):\n    \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n    dt, _, _ = date_str.partition(\".\")\n    dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n    return dt", "title": ""}
{"_id": "d14674", "text": "def strip_columns(tab):\n    \"\"\"Strip whitespace from string columns.\"\"\"\n    for colname in tab.colnames:\n        if tab[colname].dtype.kind in ['S', 'U']:\n            tab[colname] = np.core.defchararray.strip(tab[colname])", "title": ""}
{"_id": "d14675", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d14676", "text": "def load_jsonf(fpath, encoding):\n    \"\"\"\n    :param unicode fpath:\n    :param unicode encoding:\n    :rtype: dict | list\n    \"\"\"\n    with codecs.open(fpath, encoding=encoding) as f:\n        return json.load(f)", "title": ""}
{"_id": "d14677", "text": "def iso_to_datetime(date):\n    \"\"\" Convert ISO 8601 time format to datetime format\n\n    This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.\n    ``datetime.datetime(2017,9,14,0,0)``\n\n    :param date: date in ISO 8601 format\n    :type date: str\n    :return: datetime instance\n    :rtype: datetime\n    \"\"\"\n    chunks = list(map(int, date.split('T')[0].split('-')))\n    return datetime.datetime(chunks[0], chunks[1], chunks[2])", "title": ""}
{"_id": "d14678", "text": "def __repr__(self):\n    \"\"\"Returns a stringified representation of this object.\"\"\"\n    return str({'name': self._name, 'watts': self._watts,\n                'type': self._output_type, 'id': self._integration_id})", "title": ""}
{"_id": "d14679", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d14680", "text": "def classnameify(s):\n  \"\"\"\n  Makes a classname\n  \"\"\"\n  return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))", "title": ""}
{"_id": "d14681", "text": "def now(self):\n\t\t\"\"\"\n\t\tReturn a :py:class:`datetime.datetime` instance representing the current time.\n\n\t\t:rtype: :py:class:`datetime.datetime`\n\t\t\"\"\"\n\t\tif self.use_utc:\n\t\t\treturn datetime.datetime.utcnow()\n\t\telse:\n\t\t\treturn datetime.datetime.now()", "title": ""}
{"_id": "d14682", "text": "def _idx_col2rowm(d):\n    \"\"\"Generate indexes to change from col-major to row-major ordering\"\"\"\n    if 0 == len(d):\n        return 1\n    if 1 == len(d):\n        return np.arange(d[0])\n    # order='F' indicates column-major ordering\n    idx = np.array(np.arange(np.prod(d))).reshape(d, order='F').T\n    return idx.flatten(order='F')", "title": ""}
{"_id": "d14683", "text": "def this_week():\n        \"\"\" Return start and end date of the current week. \"\"\"\n        since = TODAY + delta(weekday=MONDAY(-1))\n        until = since + delta(weeks=1)\n        return Date(since), Date(until)", "title": ""}
{"_id": "d14684", "text": "def setHSV(self, pixel, hsv):\n        \"\"\"Set single pixel to HSV tuple\"\"\"\n        color = conversions.hsv2rgb(hsv)\n        self._set_base(pixel, color)", "title": ""}
{"_id": "d14685", "text": "def parse_timestamp(timestamp):\n    \"\"\"Parse ISO8601 timestamps given by github API.\"\"\"\n    dt = dateutil.parser.parse(timestamp)\n    return dt.astimezone(dateutil.tz.tzutc())", "title": ""}
{"_id": "d14686", "text": "def tick(self):\n        \"\"\"Add one tick to progress bar\"\"\"\n        self.current += 1\n        if self.current == self.factor:\n            sys.stdout.write('+')\n            sys.stdout.flush()\n            self.current = 0", "title": ""}
{"_id": "d14687", "text": "def datetime_to_timezone(date, tz=\"UTC\"):\n    \"\"\" convert naive datetime to timezone-aware datetime \"\"\"\n    if not date.tzinfo:\n        date = date.replace(tzinfo=timezone(get_timezone()))\n    return date.astimezone(timezone(tz))", "title": ""}
{"_id": "d14688", "text": "def input(self, prompt, default=None, show_default=True):\n        \"\"\"Provide a command prompt.\"\"\"\n        return click.prompt(prompt, default=default, show_default=show_default)", "title": ""}
{"_id": "d14689", "text": "def get_naive(dt):\n  \"\"\"Gets a naive datetime from a datetime.\n\n  datetime_tz objects can't just have tzinfo replaced with None, you need to\n  call asdatetime.\n\n  Args:\n    dt: datetime object.\n\n  Returns:\n    datetime object without any timezone information.\n  \"\"\"\n  if not dt.tzinfo:\n    return dt\n  if hasattr(dt, \"asdatetime\"):\n    return dt.asdatetime()\n  return dt.replace(tzinfo=None)", "title": ""}
{"_id": "d14690", "text": "def activate_subplot(numPlot):\n    \"\"\"Make subplot *numPlot* active on the canvas.\n\n    Use this if a simple ``subplot(numRows, numCols, numPlot)``\n    overwrites the subplot instead of activating it.\n    \"\"\"\n    # see http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg07156.html\n    from pylab import gcf, axes\n    numPlot -= 1  # index is 0-based, plots are 1-based\n    return axes(gcf().get_axes()[numPlot])", "title": ""}
{"_id": "d14691", "text": "def parse_timestamp(timestamp):\n    \"\"\"Parse ISO8601 timestamps given by github API.\"\"\"\n    dt = dateutil.parser.parse(timestamp)\n    return dt.astimezone(dateutil.tz.tzutc())", "title": ""}
{"_id": "d14692", "text": "def inc_date(date_obj, num, date_fmt):\n    \"\"\"Increment the date by a certain number and return date object.\n    as the specific string format.\n    \"\"\"\n    return (date_obj + timedelta(days=num)).strftime(date_fmt)", "title": ""}
{"_id": "d14693", "text": "def last_month():\n        \"\"\" Return start and end date of this month. \"\"\"\n        since = TODAY + delta(day=1, months=-1)\n        until = since + delta(months=1)\n        return Date(since), Date(until)", "title": ""}
{"_id": "d14694", "text": "def select_down(self):\n        \"\"\"move cursor down\"\"\"\n        r, c = self._index\n        self._select_index(r+1, c)", "title": ""}
{"_id": "d14695", "text": "def QA_util_datetime_to_strdate(dt):\n    \"\"\"\n    :param dt:  pythone datetime.datetime\n    :return:  1999-02-01 string type\n    \"\"\"\n    strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n    return strdate", "title": ""}
{"_id": "d14696", "text": "def round_sig(x, sig):\n    \"\"\"Round the number to the specified number of significant figures\"\"\"\n    return round(x, sig - int(floor(log10(abs(x)))) - 1)", "title": ""}
{"_id": "d14697", "text": "def robust_int(v):\n    \"\"\"Parse an int robustly, ignoring commas and other cruft. \"\"\"\n\n    if isinstance(v, int):\n        return v\n\n    if isinstance(v, float):\n        return int(v)\n\n    v = str(v).replace(',', '')\n\n    if not v:\n        return None\n\n    return int(v)", "title": ""}
{"_id": "d14698", "text": "def fromtimestamp(cls, timestamp):\n    \"\"\"Returns a datetime object of a given timestamp (in local tz).\"\"\"\n    d = cls.utcfromtimestamp(timestamp)\n    return d.astimezone(localtz())", "title": ""}
{"_id": "d14699", "text": "def to_str(s):\n    \"\"\"\n    Convert bytes and non-string into Python 3 str\n    \"\"\"\n    if isinstance(s, bytes):\n        s = s.decode('utf-8')\n    elif not isinstance(s, str):\n        s = str(s)\n    return s", "title": ""}
{"_id": "d14700", "text": "def today(year=None):\n    \"\"\"this day, last year\"\"\"\n    return datetime.date(int(year), _date.month, _date.day) if year else _date", "title": ""}
{"_id": "d14701", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d14702", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d14703", "text": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    \"\"\"\n    Appends a PDF to a pyPDF writer. Legacy interface.\n    \"\"\"\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)", "title": ""}
{"_id": "d14704", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d14705", "text": "def _iterable_to_varargs_method(func):\n    \"\"\"decorator to convert a method taking a iterable to a *args one\"\"\"\n    def wrapped(self, *args, **kwargs):\n        return func(self, args, **kwargs)\n    return wrapped", "title": ""}
{"_id": "d14706", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d14707", "text": "def set_default(self, key, value):\n        \"\"\"Set the default value for this key.\n        Default only used when no value is provided by the user via\n        arg, config or env.\n        \"\"\"\n        k = self._real_key(key.lower())\n        self._defaults[k] = value", "title": ""}
{"_id": "d14708", "text": "def is_int_type(val):\n    \"\"\"Return True if `val` is of integer type.\"\"\"\n    try:               # Python 2\n        return isinstance(val, (int, long))\n    except NameError:  # Python 3\n        return isinstance(val, int)", "title": ""}
{"_id": "d14709", "text": "def empty(self, start=None, stop=None):\n\t\t\"\"\"Empty the range from start to stop.\n\n\t\tLike delete, but no Error is raised if the entire range isn't mapped.\n\t\t\"\"\"\n\t\tself.set(NOT_SET, start=start, stop=stop)", "title": ""}
{"_id": "d14710", "text": "def matrix_at_check(self, original, loc, tokens):\n        \"\"\"Check for Python 3.5 matrix multiplication.\"\"\"\n        return self.check_py(\"35\", \"matrix multiplication\", original, loc, tokens)", "title": ""}
{"_id": "d14711", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d14712", "text": "def is_timestamp(obj):\n    \"\"\"\n    Yaml either have automatically converted it to a datetime object\n    or it is a string that will be validated later.\n    \"\"\"\n    return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)", "title": ""}
{"_id": "d14713", "text": "def clear_global(self):\n        \"\"\"Clear only any cached global data.\n\n        \"\"\"\n        vname = self.varname\n        logger.debug(f'global clearning {vname}')\n        if vname in globals():\n            logger.debug('removing global instance var: {}'.format(vname))\n            del globals()[vname]", "title": ""}
{"_id": "d14714", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d14715", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d14716", "text": "def _get_mtime():\n    \"\"\"\n    Get the modified time of the RPM Database.\n\n    Returns:\n        Unix ticks\n    \"\"\"\n    return os.path.exists(RPM_PATH) and int(os.path.getmtime(RPM_PATH)) or 0", "title": ""}
{"_id": "d14717", "text": "def del_object_from_parent(self):\n        \"\"\" Delete object from parent object. \"\"\"\n        if self.parent:\n            self.parent.objects.pop(self.ref)", "title": ""}
{"_id": "d14718", "text": "def close(*args, **kwargs):\n    r\"\"\"Close last created figure, alias to ``plt.close()``.\"\"\"\n    _, plt, _ = _import_plt()\n    plt.close(*args, **kwargs)", "title": ""}
{"_id": "d14719", "text": "def up(self):\n        \"\"\"Go up in stack and return True if top frame\"\"\"\n        if self.frame:\n            self.frame = self.frame.f_back\n            return self.frame is None", "title": ""}
{"_id": "d14720", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d14721", "text": "def is_square_matrix(mat):\n    \"\"\"Test if an array is a square matrix.\"\"\"\n    mat = np.array(mat)\n    if mat.ndim != 2:\n        return False\n    shape = mat.shape\n    return shape[0] == shape[1]", "title": ""}
{"_id": "d14722", "text": "def invalidate_cache(cpu, address, size):\n        \"\"\" remove decoded instruction from instruction cache \"\"\"\n        cache = cpu.instruction_cache\n        for offset in range(size):\n            if address + offset in cache:\n                del cache[address + offset]", "title": ""}
{"_id": "d14723", "text": "def _is_one_arg_pos_call(call):\n    \"\"\"Is this a call with exactly 1 argument,\n    where that argument is positional?\n    \"\"\"\n    return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords", "title": ""}
{"_id": "d14724", "text": "def __exit__(self, *args):\n        \"\"\"Redirect stdout back to the original stdout.\"\"\"\n        sys.stdout = self._orig\n        self._devnull.close()", "title": ""}
{"_id": "d14725", "text": "def is_int_type(val):\n    \"\"\"Return True if `val` is of integer type.\"\"\"\n    try:               # Python 2\n        return isinstance(val, (int, long))\n    except NameError:  # Python 3\n        return isinstance(val, int)", "title": ""}
{"_id": "d14726", "text": "def _sanitize(text):\n    \"\"\"Return sanitized Eidos text field for human readability.\"\"\"\n    d = {'-LRB-': '(', '-RRB-': ')'}\n    return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text)", "title": ""}
{"_id": "d14727", "text": "def _IsDirectory(parent, item):\n  \"\"\"Helper that returns if parent/item is a directory.\"\"\"\n  return tf.io.gfile.isdir(os.path.join(parent, item))", "title": ""}
{"_id": "d14728", "text": "def from_json(cls, json_str):\n        \"\"\"Deserialize the object from a JSON string.\"\"\"\n        d = json.loads(json_str)\n        return cls.from_dict(d)", "title": ""}
{"_id": "d14729", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d14730", "text": "def dispose_orm():\n    \"\"\" Properly close pooled database connections \"\"\"\n    log.debug(\"Disposing DB connection pool (PID %s)\", os.getpid())\n    global engine\n    global Session\n\n    if Session:\n        Session.remove()\n        Session = None\n    if engine:\n        engine.dispose()\n        engine = None", "title": ""}
{"_id": "d14731", "text": "def is_iter_non_string(obj):\n    \"\"\"test if object is a list or tuple\"\"\"\n    if isinstance(obj, list) or isinstance(obj, tuple):\n        return True\n    return False", "title": ""}
{"_id": "d14732", "text": "def lock_file(f, block=False):\n    \"\"\"\n    If block=False (the default), die hard and fast if another process has\n    already grabbed the lock for this file.\n\n    If block=True, wait for the lock to be released, then continue.\n    \"\"\"\n    try:\n        flags = fcntl.LOCK_EX\n        if not block:\n            flags |= fcntl.LOCK_NB\n        fcntl.flock(f.fileno(), flags)\n    except IOError as e:\n        if e.errno in (errno.EACCES, errno.EAGAIN):\n            raise SystemExit(\"ERROR: %s is locked by another process.\" %\n                             f.name)\n        raise", "title": ""}
{"_id": "d14733", "text": "def is_valid_row(cls, row):\n        \"\"\"Indicates whether or not the given row contains valid data.\"\"\"\n        for k in row.keys():\n            if row[k] is None:\n                return False\n        return True", "title": ""}
{"_id": "d14734", "text": "def stdin_readable():\n    \"\"\"Determine whether stdin has any data to read.\"\"\"\n    if not WINDOWS:\n        try:\n            return bool(select([sys.stdin], [], [], 0)[0])\n        except Exception:\n            logger.log_exc()\n    try:\n        return not sys.stdin.isatty()\n    except Exception:\n        logger.log_exc()\n    return False", "title": ""}
{"_id": "d14735", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d14736", "text": "def empty_tree(input_list):\n    \"\"\"Recursively iterate through values in nested lists.\"\"\"\n    for item in input_list:\n        if not isinstance(item, list) or not empty_tree(item):\n            return False\n    return True", "title": ""}
{"_id": "d14737", "text": "def _valid_table_name(name):\n    \"\"\"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 _\n    \"\"\"\n\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\n    else:\n        return True", "title": ""}
{"_id": "d14738", "text": "def _is_proper_sequence(seq):\n    \"\"\"Returns is seq is sequence and not string.\"\"\"\n    return (isinstance(seq, collections.abc.Sequence) and\n            not isinstance(seq, str))", "title": ""}
{"_id": "d14739", "text": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n    \"\"\"\n    http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n    \"\"\"\n    fft = np.fft.fft(data)\n    # n = len(data)\n    # timestep = 1.0 / fs\n    # freq = np.fft.fftfreq(n, d=timestep)\n    bp = fft.copy()\n\n    # Zero out fft coefficients\n    # bp[10:-10] = 0\n\n    # Normalise\n    # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n    bp *= fft.dot(fft) / bp.dot(bp)\n\n    # must multipy by 2 to get the correct amplitude\n    ibp = 12 * np.fft.ifft(bp)\n    return ibp", "title": ""}
{"_id": "d14740", "text": "def has_common(self, other):\n        \"\"\"Return set of common words between two word sets.\"\"\"\n        if not isinstance(other, WordSet):\n            raise ValueError('Can compare only WordSets')\n        return self.term_set & other.term_set", "title": ""}
{"_id": "d14741", "text": "def test_value(self, value):\n        \"\"\"Test if value is an instance of float.\"\"\"\n        if not isinstance(value, float):\n            raise ValueError('expected float value: ' + str(type(value)))", "title": ""}
{"_id": "d14742", "text": "def dictapply(d, fn):\n    \"\"\"\n    apply a function to all non-dict values in a dictionary\n    \"\"\"\n    for k, v in d.items():\n        if isinstance(v, dict):\n            v = dictapply(v, fn)\n        else:\n            d[k] = fn(v)\n    return d", "title": ""}
{"_id": "d14743", "text": "def count_(self):\n        \"\"\"\n        Returns the number of rows of the main dataframe\n        \"\"\"\n        try:\n            num = len(self.df.index)\n        except Exception as e:\n            self.err(e, \"Can not count data\")\n            return\n        return num", "title": ""}
{"_id": "d14744", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d14745", "text": "def is_client(self):\n        \"\"\"Return True if Glances is running in client mode.\"\"\"\n        return (self.args.client or self.args.browser) and not self.args.server", "title": ""}
{"_id": "d14746", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d14747", "text": "def get_file_size(filename):\n    \"\"\"\n    Get the file size of a given file\n\n    :param filename: string: pathname of a file\n    :return: human readable filesize\n    \"\"\"\n    if os.path.isfile(filename):\n        return convert_size(os.path.getsize(filename))\n    return None", "title": ""}
{"_id": "d14748", "text": "def multi_pop(d, *args):\n    \"\"\" pops multiple keys off a dict like object \"\"\"\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval", "title": ""}
{"_id": "d14749", "text": "def safe_delete(filename):\n  \"\"\"Delete a file safely. If it's not present, no-op.\"\"\"\n  try:\n    os.unlink(filename)\n  except OSError as e:\n    if e.errno != errno.ENOENT:\n      raise", "title": ""}
{"_id": "d14750", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d14751", "text": "def timeit(self, metric, func, *args, **kwargs):\n        \"\"\"Time execution of callable and emit metric then return result.\"\"\"\n        return metrics.timeit(metric, func, *args, **kwargs)", "title": ""}
{"_id": "d14752", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d14753", "text": "def _call_retry(self, force_retry):\n        \"\"\"Call request and retry up to max_attempts times (or none if self.max_attempts=1)\"\"\"\n        last_exception = None\n        for i in range(self.max_attempts):\n            try:\n                log.info(\"Calling %s %s\" % (self.method, self.url))\n                response = self.requests_method(\n                    self.url,\n                    data=self.data,\n                    params=self.params,\n                    headers=self.headers,\n                    timeout=(self.connect_timeout, self.read_timeout),\n                    verify=self.verify_ssl,\n                )\n\n                if response is None:\n                    log.warn(\"Got response None\")\n                    if self._method_is_safe_to_retry():\n                        delay = 0.5 + i * 0.5\n                        log.info(\"Waiting %s sec and Retrying since call is a %s\" % (delay, self.method))\n                        time.sleep(delay)\n                        continue\n                    else:\n                        raise PyMacaronCoreException(\"Call %s %s returned empty response\" % (self.method, self.url))\n\n                return response\n\n            except Exception as e:\n\n                last_exception = e\n\n                retry = force_retry\n\n                if isinstance(e, ReadTimeout):\n                    # Log enough to help debugging...\n                    log.warn(\"Got a ReadTimeout calling %s %s\" % (self.method, self.url))\n                    log.warn(\"Exception was: %s\" % str(e))\n                    resp = e.response\n                    if not resp:\n                        log.info(\"Requests error has no response.\")\n                        # TODO: retry=True? Is it really safe?\n                    else:\n                        b = resp.content\n                        log.info(\"Requests has a response with content: \" + pprint.pformat(b))\n                    if self._method_is_safe_to_retry():\n                        # It is safe to retry\n                        log.info(\"Retrying since call is a %s\" % self.method)\n                        retry = True\n\n                elif isinstance(e, ConnectTimeout):\n                    log.warn(\"Got a ConnectTimeout calling %s %s\" % (self.method, self.url))\n                    log.warn(\"Exception was: %s\" % str(e))\n                    # ConnectTimeouts are safe to retry whatever the call...\n                    retry = True\n\n                if retry:\n                    continue\n                else:\n                    raise e\n\n        # max_attempts has been reached: propagate the last received Exception\n        if not last_exception:\n            last_exception = Exception(\"Reached max-attempts (%s). Giving up calling %s %s\" % (self.max_attempts, self.method, self.url))\n        raise last_exception", "title": ""}
{"_id": "d14754", "text": "def _file_exists(path, filename):\n  \"\"\"Checks if the filename exists under the path.\"\"\"\n  return os.path.isfile(os.path.join(path, filename))", "title": ""}
{"_id": "d14755", "text": "def multidict_to_dict(d):\n    \"\"\"\n    Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with\n    list values\n    :param d: a MultiDict or MultiValueDict instance\n    :return: a dict instance\n    \"\"\"\n    return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))", "title": ""}
{"_id": "d14756", "text": "def _check_valid_key(self, key):\n        \"\"\"Checks if a key is valid and raises a ValueError if its not.\n\n        When in need of checking a key for validity, always use this\n        method if possible.\n\n        :param key: The key to be checked\n        \"\"\"\n        if not isinstance(key, key_type):\n            raise ValueError('%r is not a valid key type' % key)\n        if not VALID_KEY_RE.match(key):\n            raise ValueError('%r contains illegal characters' % key)", "title": ""}
{"_id": "d14757", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d14758", "text": "def _ws_on_close(self, ws: websocket.WebSocketApp):\n        \"\"\"Callback for closing the websocket connection\n\n        Args:\n            ws: websocket connection (now closed)\n        \"\"\"\n        self.connected = False\n        self.logger.error('Websocket closed')\n        self._reconnect_websocket()", "title": ""}
{"_id": "d14759", "text": "def to_bipartite_matrix(A):\n    \"\"\"Returns the adjacency matrix of a bipartite graph whose biadjacency\n    matrix is `A`.\n\n    `A` must be a NumPy array.\n\n    If `A` has **m** rows and **n** columns, then the returned matrix has **m +\n    n** rows and columns.\n\n    \"\"\"\n    m, n = A.shape\n    return four_blocks(zeros(m, m), A, A.T, zeros(n, n))", "title": ""}
{"_id": "d14760", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d14761", "text": "def convert_string(string):\n    \"\"\"Convert string to int, float or bool.\n    \"\"\"\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", "title": ""}
{"_id": "d14762", "text": "def is_non_empty_string(input_string):\n    \"\"\"\n    Validate if non empty string\n\n    :param input_string: Input is a *str*.\n    :return: True if input is string and non empty.\n       Raise :exc:`Exception` otherwise.\n    \"\"\"\n    try:\n        if not input_string.strip():\n            raise ValueError()\n    except AttributeError as error:\n        raise TypeError(error)\n\n    return True", "title": ""}
{"_id": "d14763", "text": "def get_serialize_format(self, mimetype):\n\t\t\"\"\" Get the serialization format for the given mimetype \"\"\"\n\t\tformat = self.formats.get(mimetype, None)\n\t\tif format is None:\n\t\t\tformat = formats.get(mimetype, None)\n\t\treturn format", "title": ""}
{"_id": "d14764", "text": "def equal(obj1, obj2):\n    \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n    Comparable.log(obj1, obj2, '==')\n    equality = obj1.equality(obj2)\n    Comparable.log(obj1, obj2, '==', result=equality)\n    return equality", "title": ""}
{"_id": "d14765", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d14766", "text": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "title": ""}
{"_id": "d14767", "text": "def parse_value(self, value):\n        \"\"\"Cast value to `bool`.\"\"\"\n        parsed = super(BoolField, self).parse_value(value)\n        return bool(parsed) if parsed is not None else None", "title": ""}
{"_id": "d14768", "text": "def run(self, value):\n        \"\"\" Determines if value value is empty.\n        Keyword arguments:\n        value str -- the value of the associated field to compare\n        \"\"\"\n        if self.pass_ and not value.strip():\n            return True\n\n        if not value:\n            return False\n        return True", "title": ""}
{"_id": "d14769", "text": "def tree_render(request, upy_context, vars_dictionary):\n    \"\"\"\n    It renders template defined in upy_context's page passed in arguments\n    \"\"\"\n    page = upy_context['PAGE']\n    return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))", "title": ""}
{"_id": "d14770", "text": "def is_punctuation(text):\n    \"\"\"Check if given string is a punctuation\"\"\"\n    return not (text.lower() in config.AVRO_VOWELS or\n                text.lower() in config.AVRO_CONSONANTS)", "title": ""}
{"_id": "d14771", "text": "def static_urls_js():\n    \"\"\"\n    Add global variables to JavaScript about the location and latest version of\n    transpiled files.\n    Usage::\n        {% static_urls_js %}\n    \"\"\"\n    if apps.is_installed('django.contrib.staticfiles'):\n        from django.contrib.staticfiles.storage import staticfiles_storage\n        static_base_url = staticfiles_storage.base_url\n    else:\n        static_base_url = PrefixNode.handle_simple(\"STATIC_URL\")\n    transpile_base_url = urljoin(static_base_url, 'js/transpile/')\n    return {\n        'static_base_url': static_base_url,\n        'transpile_base_url': transpile_base_url,\n        'version': LAST_RUN['version']\n    }", "title": ""}
{"_id": "d14772", "text": "def set_executable(filename):\n    \"\"\"Set the exectuable bit on the given filename\"\"\"\n    st = os.stat(filename)\n    os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d14773", "text": "def see_doc(obj_with_doc):\n    \"\"\"Copy docstring from existing object to the decorated callable.\"\"\"\n    def decorator(fn):\n        fn.__doc__ = obj_with_doc.__doc__\n        return fn\n    return decorator", "title": ""}
{"_id": "d14774", "text": "def check_clang_apply_replacements_binary(args):\n  \"\"\"Checks if invoking supplied clang-apply-replacements binary works.\"\"\"\n  try:\n    subprocess.check_call([args.clang_apply_replacements_binary, '--version'])\n  except:\n    print('Unable to run clang-apply-replacements. Is clang-apply-replacements '\n          'binary correctly specified?', file=sys.stderr)\n    traceback.print_exc()\n    sys.exit(1)", "title": ""}
{"_id": "d14775", "text": "def close_all_but_this(self):\n        \"\"\"Close all files but the current one\"\"\"\n        self.close_all_right()\n        for i in range(0, self.get_stack_count()-1  ):\n            self.close_file(0)", "title": ""}
{"_id": "d14776", "text": "def smartSum(x,key,value):\n    \"\"\" create a new page in x if key is not a page of x\n        otherwise add value to x[key] \"\"\"\n    if key not in list(x.keys()):\n        x[key] = value\n    else:   x[key]+=value", "title": ""}
{"_id": "d14777", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d14778", "text": "def next (self):    # File-like object.\n\n        \"\"\"This is to support iterators over a file-like object.\n        \"\"\"\n\n        result = self.readline()\n        if result == self._empty_buffer:\n            raise StopIteration\n        return result", "title": ""}
{"_id": "d14779", "text": "def close(self):\n        \"\"\"Closes the serial port.\"\"\"\n        if self.pyb and self.pyb.serial:\n            self.pyb.serial.close()\n        self.pyb = None", "title": ""}
{"_id": "d14780", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d14781", "text": "def get_closest_index(myList, myNumber):\n    \"\"\"\n    Assumes myList is sorted. Returns closest value to myNumber.\n    If two numbers are equally close, return the smallest number.\n\n    Parameters\n    ----------\n    myList : array\n        The list in which to find the closest value to myNumber\n    myNumber : float\n        The number to find the closest to in MyList\n\n    Returns\n    -------\n    closest_values_index : int\n        The index in the array of the number closest to myNumber in myList\n    \"\"\"\n    closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n    return closest_values_index", "title": ""}
{"_id": "d14782", "text": "def dot_v2(vec1, vec2):\n    \"\"\"Return the dot product of two vectors\"\"\"\n\n    return vec1.x * vec2.x + vec1.y * vec2.y", "title": ""}
{"_id": "d14783", "text": "def clear():\n    \"\"\"Clears the console.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        call(\"cls\", shell=True)\n    else:\n        call(\"clear\", shell=True)", "title": ""}
{"_id": "d14784", "text": "def downsample_with_striding(array, factor):\n    \"\"\"Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x.\n    \"\"\"\n    return array[tuple(np.s_[::f] for f in factor)]", "title": ""}
{"_id": "d14785", "text": "def add(self, entity):\n\t\t\"\"\"\n\t\tAdds the supplied dict as a new entity\n\t\t\"\"\"\n\t\tresult = self._http_req('connections', method='POST', payload=entity)\n\t\tstatus = result['status']\n\t\tif not status==201:\n\t\t\traise ServiceRegistryError(status,\"Couldn't add entity\")\n\n\t\tself.debug(0x01,result)\n\t\treturn result['decoded']", "title": ""}
{"_id": "d14786", "text": "def polyline(self, arr):\n        \"\"\"Draw a set of lines\"\"\"\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])", "title": ""}
{"_id": "d14787", "text": "def accel_next(self, *args):\n        \"\"\"Callback to go to the next tab. Called by the accel key.\n        \"\"\"\n        if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n            self.get_notebook().set_current_page(0)\n        else:\n            self.get_notebook().next_page()\n        return True", "title": ""}
{"_id": "d14788", "text": "def safe_dump(data, stream=None, **kwds):\n    \"\"\"implementation of safe dumper using Ordered Dict Yaml Dumper\"\"\"\n    return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)", "title": ""}
{"_id": "d14789", "text": "def flatten_list(l):\n    \"\"\" Nested lists to single-level list, does not split strings\"\"\"\n    return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))", "title": ""}
{"_id": "d14790", "text": "def display_pil_image(im):\n   \"\"\"Displayhook function for PIL Images, rendered as PNG.\"\"\"\n   from IPython.core import display\n   b = BytesIO()\n   im.save(b, format='png')\n   data = b.getvalue()\n\n   ip_img = display.Image(data=data, format='png', embed=True)\n   return ip_img._repr_png_()", "title": ""}
{"_id": "d14791", "text": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"React to a docstring event and append contracts to it.\"\"\"\n    # pylint: disable=unused-argument\n    # pylint: disable=too-many-arguments\n    lines.extend(_format_contracts(what=what, obj=obj))", "title": ""}
{"_id": "d14792", "text": "def load_member(fqn):\n    \"\"\"Loads and returns a class for a given fully qualified name.\"\"\"\n    modulename, member_name = split_fqn(fqn)\n    module = __import__(modulename, globals(), locals(), member_name)\n    return getattr(module, member_name)", "title": ""}
{"_id": "d14793", "text": "def camel_to_underscore(string):\n    \"\"\"Convert camelcase to lowercase and underscore.\n\n    Recipe from http://stackoverflow.com/a/1176023\n\n    Args:\n        string (str): The string to convert.\n\n    Returns:\n        str: The converted string.\n    \"\"\"\n    string = FIRST_CAP_RE.sub(r'\\1_\\2', string)\n    return ALL_CAP_RE.sub(r'\\1_\\2', string).lower()", "title": ""}
{"_id": "d14794", "text": "def encode_list(dynamizer, value):\n    \"\"\" Encode a list for the DynamoDB format \"\"\"\n    encoded_list = []\n    dict(map(dynamizer.raw_encode, value))\n    for v in value:\n        encoded_type, encoded_value = dynamizer.raw_encode(v)\n        encoded_list.append({\n            encoded_type: encoded_value,\n        })\n    return 'L', encoded_list", "title": ""}
{"_id": "d14795", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d14796", "text": "def datetime_to_ms(dt):\n    \"\"\"\n    Converts a datetime to a millisecond accuracy timestamp\n    \"\"\"\n    seconds = calendar.timegm(dt.utctimetuple())\n    return seconds * 1000 + int(dt.microsecond / 1000)", "title": ""}
{"_id": "d14797", "text": "def intersect(d1, d2):\n    \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n    return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "title": ""}
{"_id": "d14798", "text": "def add_index_alias(es, index_name, alias_name):\n    \"\"\"Add index alias to index_name\"\"\"\n\n    es.indices.put_alias(index=index_name, name=terms_alias)", "title": ""}
{"_id": "d14799", "text": "def compare(string1, string2):\n    \"\"\"Compare two strings while protecting against timing attacks\n\n    :param str string1: the first string\n    :param str string2: the second string\n\n    :returns: True if the strings are equal, False if not\n    :rtype: :obj:`bool`\n    \"\"\"\n    if len(string1) != len(string2):\n        return False\n    result = True\n    for c1, c2 in izip(string1, string2):\n        result &= c1 == c2\n    return result", "title": ""}
{"_id": "d14800", "text": "def all_documents(index=INDEX_NAME):\n    \"\"\"\n    Get all documents from the given index.\n\n    Returns full Elasticsearch objects so you can get metadata too.\n    \"\"\"\n    query = {\n        'query': {\n            'match_all': {}\n        }\n    }\n    for result in raw_query(query, index=index):\n        yield result", "title": ""}
{"_id": "d14801", "text": "def is_int(string):\n    \"\"\"\n    Checks if a string is an integer. If the string value is an integer\n    return True, otherwise return False. \n    \n    Args:\n        string: a string to test.\n\n    Returns: \n        boolean\n    \"\"\"\n    try:\n        a = float(string)\n        b = int(a)\n    except ValueError:\n        return False\n    else:\n        return a == b", "title": ""}
{"_id": "d14802", "text": "def all_documents(index=INDEX_NAME):\n    \"\"\"\n    Get all documents from the given index.\n\n    Returns full Elasticsearch objects so you can get metadata too.\n    \"\"\"\n    query = {\n        'query': {\n            'match_all': {}\n        }\n    }\n    for result in raw_query(query, index=index):\n        yield result", "title": ""}
{"_id": "d14803", "text": "def compute_ssim(image1, image2, gaussian_kernel_sigma=1.5,\n                 gaussian_kernel_width=11):\n    \"\"\"Computes SSIM.\n\n    Args:\n      im1: First PIL Image object to compare.\n      im2: Second PIL Image object to compare.\n\n    Returns:\n      SSIM float value.\n    \"\"\"\n    gaussian_kernel_1d = get_gaussian_kernel(\n        gaussian_kernel_width, gaussian_kernel_sigma)\n    return SSIM(image1, gaussian_kernel_1d).ssim_value(image2)", "title": ""}
{"_id": "d14804", "text": "def get_average_color(colors):\n    \"\"\"Calculate the average color from the list of colors, where each color\n    is a 3-tuple of (r, g, b) values.\n    \"\"\"\n    c = reduce(color_reducer, colors)\n    total = len(colors)\n    return tuple(v / total for v in c)", "title": ""}
{"_id": "d14805", "text": "def set_strict(self, value):\n        \"\"\"\n        Set the strict mode active/disable\n\n        :param value:\n        :type value: bool\n        \"\"\"\n        assert isinstance(value, bool)\n        self.__settings.set_strict(value)", "title": ""}
{"_id": "d14806", "text": "def distance_matrix(trains1, trains2, cos, tau):\n    \"\"\"\n    Return the *bipartite* (rectangular) distance matrix between the observations in the first and the second list.\n\n    Convenience function; equivalent to ``dissimilarity_matrix(trains1, trains2, cos, tau, \"distance\")``. Refer to :func:`pymuvr.dissimilarity_matrix` for full documentation.\n    \"\"\"\n    return dissimilarity_matrix(trains1, trains2, cos, tau, \"distance\")", "title": ""}
{"_id": "d14807", "text": "def get_enum_from_name(self, enum_name):\n        \"\"\"\n            Return an enum from a name\n        Args:\n            enum_name (str): name of the enum\n        Returns:\n            Enum\n        \"\"\"\n        return next((e for e in self.enums if e.name == enum_name), None)", "title": ""}
{"_id": "d14808", "text": "def _cal_dist2center(X, center):\n    \"\"\" Calculate the SSE to the cluster center\n    \"\"\"\n    dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')\n    return(np.sum(dmemb2cen))", "title": ""}
{"_id": "d14809", "text": "def get_enum_from_name(self, enum_name):\n        \"\"\"\n            Return an enum from a name\n        Args:\n            enum_name (str): name of the enum\n        Returns:\n            Enum\n        \"\"\"\n        return next((e for e in self.enums if e.name == enum_name), None)", "title": ""}
{"_id": "d14810", "text": "def accuracy(conf_matrix):\n  \"\"\"\n  Given a confusion matrix, returns the accuracy.\n  Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml\n  \"\"\"\n  total, correct = 0.0, 0.0\n  for true_response, guess_dict in conf_matrix.items():\n    for guess, count in guess_dict.items():\n      if true_response == guess:\n        correct += count\n      total += count\n  return correct/total", "title": ""}
{"_id": "d14811", "text": "def EnumValueName(self, enum, value):\n    \"\"\"Returns the string name of an enum value.\n\n    This is just a small helper method to simplify a common operation.\n\n    Args:\n      enum: string name of the Enum.\n      value: int, value of the enum.\n\n    Returns:\n      string name of the enum value.\n\n    Raises:\n      KeyError if either the Enum doesn't exist or the value is not a valid\n        value for the enum.\n    \"\"\"\n    return self.enum_types_by_name[enum].values_by_number[value].name", "title": ""}
{"_id": "d14812", "text": "def accuracy(conf_matrix):\n  \"\"\"\n  Given a confusion matrix, returns the accuracy.\n  Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml\n  \"\"\"\n  total, correct = 0.0, 0.0\n  for true_response, guess_dict in conf_matrix.items():\n    for guess, count in guess_dict.items():\n      if true_response == guess:\n        correct += count\n      total += count\n  return correct/total", "title": ""}
{"_id": "d14813", "text": "def write_enum(fo, datum, schema):\n    \"\"\"An enum is encoded by a int, representing the zero-based position of\n    the symbol in the schema.\"\"\"\n    index = schema['symbols'].index(datum)\n    write_int(fo, index)", "title": ""}
{"_id": "d14814", "text": "def confusion_matrix(self):\n        \"\"\"Confusion matrix plot\n        \"\"\"\n        return plot.confusion_matrix(self.y_true, self.y_pred,\n                                     self.target_names, ax=_gen_ax())", "title": ""}
{"_id": "d14815", "text": "def launched():\n    \"\"\"Test whether the current python environment is the correct lore env.\n\n    :return:  :any:`True` if the environment is launched\n    :rtype: bool\n    \"\"\"\n    if not PREFIX:\n        return False\n\n    return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)", "title": ""}
{"_id": "d14816", "text": "def native_conn(self):\n        \"\"\"Native connection object.\"\"\"\n        if self.__native is None:\n            self.__native = self._get_connection()\n\n        return self.__native", "title": ""}
{"_id": "d14817", "text": "def raise_os_error(_errno, path=None):\n    \"\"\"\n    Helper for raising the correct exception under Python 3 while still\n    being able to raise the same common exception class in Python 2.7.\n    \"\"\"\n\n    msg = \"%s: '%s'\" % (strerror(_errno), path) if path else strerror(_errno)\n    raise OSError(_errno, msg)", "title": ""}
{"_id": "d14818", "text": "def _make_cmd_list(cmd_list):\n    \"\"\"\n    Helper function to easily create the proper json formated string from a list of strs\n    :param cmd_list: list of strings\n    :return: str json formatted\n    \"\"\"\n    cmd = ''\n    for i in cmd_list:\n        cmd = cmd + '\"' + i + '\",'\n    cmd = cmd[:-1]\n    return cmd", "title": ""}
{"_id": "d14819", "text": "def quote(s, unsafe='/'):\n    \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n    encoded value as the value.\"\"\"\n    res = s.replace('%', '%25')\n    for c in unsafe:\n        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n    return res", "title": ""}
{"_id": "d14820", "text": "def eintr_retry(exc_type, f, *args, **kwargs):\n    \"\"\"Calls a function.  If an error of the given exception type with\n    interrupted system call (EINTR) occurs calls the function again.\n    \"\"\"\n    while True:\n        try:\n            return f(*args, **kwargs)\n        except exc_type as exc:\n            if exc.errno != EINTR:\n                raise\n        else:\n            break", "title": ""}
{"_id": "d14821", "text": "def asynchronous(function, event):\n    \"\"\"\n    Runs the function asynchronously taking care of exceptions.\n    \"\"\"\n    thread = Thread(target=synchronous, args=(function, event))\n    thread.daemon = True\n    thread.start()", "title": ""}
{"_id": "d14822", "text": "def get_number(s, cast=int):\n    \"\"\"\n    Try to get a number out of a string, and cast it.\n    \"\"\"\n    import string\n    d = \"\".join(x for x in str(s) if x in string.digits)\n    return cast(d)", "title": ""}
{"_id": "d14823", "text": "def _expand(self, str, local_vars={}):\n        \"\"\"Expand $vars in a string.\"\"\"\n        return ninja_syntax.expand(str, self.vars, local_vars)", "title": ""}
{"_id": "d14824", "text": "def str2bytes(x):\n  \"\"\"Convert input argument to bytes\"\"\"\n  if type(x) is bytes:\n    return x\n  elif type(x) is str:\n    return bytes([ ord(i) for i in x ])\n  else:\n    return str2bytes(str(x))", "title": ""}
{"_id": "d14825", "text": "def end_block(self):\n        \"\"\"Ends an indentation block, leaving an empty line afterwards\"\"\"\n        self.current_indent -= 1\n\n        # If we did not add a new line automatically yet, now it's the time!\n        if not self.auto_added_line:\n            self.writeln()\n            self.auto_added_line = True", "title": ""}
{"_id": "d14826", "text": "def copy(self):\n\t\t\"\"\"Return a shallow copy.\"\"\"\n\t\treturn self.__class__(self.operations.copy(), self.collection, self.document)", "title": ""}
{"_id": "d14827", "text": "def cli(yamlfile, directory, out, classname, format):\n    \"\"\" Generate graphviz representations of the biolink model \"\"\"\n    DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)", "title": ""}
{"_id": "d14828", "text": "def tanimoto_coefficient(a, b):\n    \"\"\"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.\n    \"\"\"\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))])", "title": ""}
{"_id": "d14829", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d14830", "text": "def empty_line_count_at_the_end(self):\n        \"\"\"\n        Return number of empty lines at the end of the document.\n        \"\"\"\n        count = 0\n        for line in self.lines[::-1]:\n            if not line or line.isspace():\n                count += 1\n            else:\n                break\n\n        return count", "title": ""}
{"_id": "d14831", "text": "def update(self, other_dict):\n        \"\"\"update() extends rather than replaces existing key lists.\"\"\"\n        for key, value in iter_multi_items(other_dict):\n            MultiDict.add(self, key, value)", "title": ""}
{"_id": "d14832", "text": "def num_leaves(tree):\n    \"\"\"Determine the number of leaves in a tree\"\"\"\n    if tree.is_leaf:\n        return 1\n    else:\n        return num_leaves(tree.left_child) + num_leaves(tree.right_child)", "title": ""}
{"_id": "d14833", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d14834", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d14835", "text": "def _extract_node_text(node):\n    \"\"\"Extract text from a given lxml node.\"\"\"\n\n    texts = map(\n        six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n    )\n    return \" \".join(text for text in texts if text)", "title": ""}
{"_id": "d14836", "text": "def best(self):\n        \"\"\"\n        Returns the element with the highest probability.\n        \"\"\"\n        b = (-1e999999, None)\n        for k, c in iteritems(self.counts):\n            b = max(b, (c, k))\n        return b[1]", "title": ""}
{"_id": "d14837", "text": "def jaccard(c_1, c_2):\n    \"\"\"\n    Calculates the Jaccard similarity between two sets of nodes. Called by mroc.\n\n    Inputs:  - c_1: Community (set of nodes) 1.\n             - c_2: Community (set of nodes) 2.\n\n    Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.\n    \"\"\"\n    nom = np.intersect1d(c_1, c_2).size\n    denom = np.union1d(c_1, c_2).size\n    return nom/denom", "title": ""}
{"_id": "d14838", "text": "def array_dim(arr):\n    \"\"\"Return the size of a multidimansional array.\n    \"\"\"\n    dim = []\n    while True:\n        try:\n            dim.append(len(arr))\n            arr = arr[0]\n        except TypeError:\n            return dim", "title": ""}
{"_id": "d14839", "text": "def stft(func=None, **kwparams):\n  \"\"\"\n  Short Time Fourier Transform for real data keeping the full FFT block.\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,\n              inverse_transform=lambda *args: numpy.fft.ifft(*args).real)\n\n  See ``stft.base`` docs for more.\n  \"\"\"\n  from numpy.fft import fft, ifft\n  ifft_r = lambda *args: ifft(*args).real\n  return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)", "title": ""}
{"_id": "d14840", "text": "def covariance(self,pt0,pt1):\n        \"\"\" get the covarince between two points implied by Vario2d\n\n        Parameters\n        ----------\n        pt0 : (iterable of len 2)\n            first point x and y\n        pt1 : (iterable of len 2)\n            second point x and y\n\n        Returns\n        -------\n        cov : float\n            covariance between pt0 and pt1\n\n        \"\"\"\n\n        x = np.array([pt0[0],pt1[0]])\n        y = np.array([pt0[1],pt1[1]])\n        names = [\"n1\",\"n2\"]\n        return self.covariance_matrix(x,y,names=names).x[0,1]", "title": ""}
{"_id": "d14841", "text": "def Output(self):\n    \"\"\"Output all sections of the page.\"\"\"\n    self.Open()\n    self.Header()\n    self.Body()\n    self.Footer()", "title": ""}
{"_id": "d14842", "text": "def coerce(self, value):\n        \"\"\"Convert from whatever is given to a list of scalars for the lookup_field.\"\"\"\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]", "title": ""}
{"_id": "d14843", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d14844", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d14845", "text": "def file_writelines_flush_sync(path, lines):\n    \"\"\"\n    Fill file at @path with @lines then flush all buffers\n    (Python and system buffers)\n    \"\"\"\n    fp = open(path, 'w')\n    try:\n        fp.writelines(lines)\n        flush_sync_file_object(fp)\n    finally:\n        fp.close()", "title": ""}
{"_id": "d14846", "text": "def __copy__(self):\n        \"\"\"A magic method to implement shallow copy behavior.\"\"\"\n        return self.__class__.load(self.dump(), context=self.context)", "title": ""}
{"_id": "d14847", "text": "def get_lines(handle, line):\n    \"\"\"\n    Get zero-indexed line from an open file-like.\n    \"\"\"\n    for i, l in enumerate(handle):\n        if i == line:\n            return l", "title": ""}
{"_id": "d14848", "text": "def mkdir(dir, enter):\n    \"\"\"Create directory with template for topic of the current environment\n\n    \"\"\"\n\n    if not os.path.exists(dir):\n        os.makedirs(dir)", "title": ""}
{"_id": "d14849", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d14850", "text": "def write_file(filename, content):\n    \"\"\"Create the file with the given content\"\"\"\n    print 'Generating {0}'.format(filename)\n    with open(filename, 'wb') as out_f:\n        out_f.write(content)", "title": ""}
{"_id": "d14851", "text": "def make_file_read_only(file_path):\n    \"\"\"\n    Removes the write permissions for the given file for owner, groups and others.\n\n    :param file_path: The file whose privileges are revoked.\n    :raise FileNotFoundError: If the given file does not exist.\n    \"\"\"\n    old_permissions = os.stat(file_path).st_mode\n    os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)", "title": ""}
{"_id": "d14852", "text": "def beta_pdf(x, a, b):\n  \"\"\"Beta distirbution probability density function.\"\"\"\n  bc = 1 / beta(a, b)\n  fc = x ** (a - 1)\n  sc = (1 - x) ** (b - 1)\n  return bc * fc * sc", "title": ""}
{"_id": "d14853", "text": "def file_read(filename):\n    \"\"\"Read a file and close it.  Returns the file source.\"\"\"\n    fobj = open(filename,'r');\n    source = fobj.read();\n    fobj.close()\n    return source", "title": ""}
{"_id": "d14854", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d14855", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d14856", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d14857", "text": "def _fill_array_from_list(the_list, the_array):\n        \"\"\"Fill an `array` from a `list`\"\"\"\n        for i, val in enumerate(the_list):\n            the_array[i] = val\n        return the_array", "title": ""}
{"_id": "d14858", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d14859", "text": "def fillna(series_or_arr, missing_value=0.0):\n    \"\"\"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.\n    \"\"\"\n\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\n    return series_or_arr", "title": ""}
{"_id": "d14860", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d14861", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d14862", "text": "def a2s(a):\n    \"\"\"\n     convert 3,3 a matrix to 6 element \"s\" list  (see Tauxe 1998)\n    \"\"\"\n    s = np.zeros((6,), 'f')  # make the a matrix\n    for i in range(3):\n        s[i] = a[i][i]\n    s[3] = a[0][1]\n    s[4] = a[1][2]\n    s[5] = a[0][2]\n    return s", "title": ""}
{"_id": "d14863", "text": "def str2int(string_with_int):\n    \"\"\" Collect digits from a string \"\"\"\n    return int(\"\".join([char for char in string_with_int if char in string.digits]) or 0)", "title": ""}
{"_id": "d14864", "text": "def sp_rand(m,n,a):\n    \"\"\"\n    Generates an mxn sparse 'd' matrix with round(a*m*n) nonzeros.\n    \"\"\"\n    if m == 0 or n == 0: return spmatrix([], [], [], (m,n))\n    nnz = min(max(0, int(round(a*m*n))), m*n)\n    nz = matrix(random.sample(range(m*n), nnz), tc='i')\n    return spmatrix(normal(nnz,1), nz%m, matrix([int(ii) for ii in nz/m]), (m,n))", "title": ""}
{"_id": "d14865", "text": "def filter_dict_by_key(d, keys):\n    \"\"\"Filter the dict *d* to remove keys not in *keys*.\"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d14866", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d14867", "text": "def flattened_nested_key_indices(nested_dict):\n    \"\"\"\n    Combine the outer and inner keys of nested dictionaries into a single\n    ordering.\n    \"\"\"\n    outer_keys, inner_keys = collect_nested_keys(nested_dict)\n    combined_keys = list(sorted(set(outer_keys + inner_keys)))\n    return {k: i for (i, k) in enumerate(combined_keys)}", "title": ""}
{"_id": "d14868", "text": "def split_every(n, iterable):\n    \"\"\"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.\"\"\"\n    items = iter(iterable)\n    return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))", "title": ""}
{"_id": "d14869", "text": "def highpass(cutoff):\n  \"\"\"\n  This strategy uses an exponential approximation for cut-off frequency\n  calculation, found by matching the one-pole Laplace lowpass filter\n  and mirroring the resulting filter to get a highpass.\n  \"\"\"\n  R = thub(exp(cutoff - pi), 2)\n  return (1 - R) / (1 + R * z ** -1)", "title": ""}
{"_id": "d14870", "text": "def add_column(filename,column,formula,force=False):\n    \"\"\" Add a column to a FITS file.\n\n    ADW: Could this be replaced by a ftool?\n    \"\"\"\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\n    logger.debug('  Evaluating formula: %s'%formula)\n    col = eval(formula)\n\n    col = np.asarray(col,dtype=[(column,col.dtype)])\n    insert_columns(filename,col,force=force)\n    return True", "title": ""}
{"_id": "d14871", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d14872", "text": "def default_static_path():\n    \"\"\"\n        Return the path to the javascript bundle\n    \"\"\"\n    fdir = os.path.dirname(__file__)\n    return os.path.abspath(os.path.join(fdir, '../assets/'))", "title": ""}
{"_id": "d14873", "text": "def Timestamp(year, month, day, hour, minute, second):\n    \"\"\"Constructs an object holding a datetime/timestamp value.\"\"\"\n    return datetime.datetime(year, month, day, hour, minute, second)", "title": ""}
{"_id": "d14874", "text": "def initialize_api(flask_app):\n    \"\"\"Initialize an API.\"\"\"\n    if not flask_restplus:\n        return\n\n    api = flask_restplus.Api(version=\"1.0\", title=\"My Example API\")\n    api.add_resource(HelloWorld, \"/hello\")\n\n    blueprint = flask.Blueprint(\"api\", __name__, url_prefix=\"/api\")\n    api.init_app(blueprint)\n    flask_app.register_blueprint(blueprint)", "title": ""}
{"_id": "d14875", "text": "def from_json(cls, json_doc):\n        \"\"\"Parse a JSON string and build an entity.\"\"\"\n        try:\n            d = json.load(json_doc)\n        except AttributeError:  # catch the read() error\n            d = json.loads(json_doc)\n\n        return cls.from_dict(d)", "title": ""}
{"_id": "d14876", "text": "def logout(cache):\n    \"\"\"\n    Logs out the current session by removing it from the cache. This is\n    expected to only occur when a session has\n    \"\"\"\n    cache.set(flask.session['auth0_key'], None)\n    flask.session.clear()\n    return True", "title": ""}
{"_id": "d14877", "text": "async def restart(request):\n    \"\"\"\n    Returns OK, then waits approximately 1 second and restarts container\n    \"\"\"\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\"})", "title": ""}
{"_id": "d14878", "text": "def lambda_failure_response(*args):\n        \"\"\"\n        Helper function to create a Lambda Failure Response\n\n        :return: A Flask Response\n        \"\"\"\n        response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)\n        return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)", "title": ""}
{"_id": "d14879", "text": "def pointer(self):\n        \"\"\"Get a ctypes void pointer to the memory mapped region.\n\n        :type: ctypes.c_void_p\n        \"\"\"\n        return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)", "title": ""}
{"_id": "d14880", "text": "def rstjinja(app, docname, source):\n    \"\"\"\n    Render our pages as a jinja template for fancy templating goodness.\n    \"\"\"\n    # Make sure we're outputting HTML\n    if app.builder.format != 'html':\n        return\n    src = source[0]\n    rendered = app.builder.templates.render_string(\n        src, app.config.html_context\n    )\n    source[0] = rendered", "title": ""}
{"_id": "d14881", "text": "def cumsum(inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1, len(newlist)):\n        newlist[i] = newlist[i] + newlist[i - 1]\n    return newlist", "title": ""}
{"_id": "d14882", "text": "def handleFlaskPostRequest(flaskRequest, endpoint):\n    \"\"\"\n    Handles the specified flask request for one of the POST URLS\n    Invokes the specified endpoint to generate a response.\n    \"\"\"\n    if flaskRequest.method == \"POST\":\n        return handleHttpPost(flaskRequest, endpoint)\n    elif flaskRequest.method == \"OPTIONS\":\n        return handleHttpOptions()\n    else:\n        raise exceptions.MethodNotAllowedException()", "title": ""}
{"_id": "d14883", "text": "def screen_cv2(self):\n        \"\"\"cv2 Image of current window screen\"\"\"\n        pil_image = self.screen.convert('RGB')\n        cv2_image = np.array(pil_image)\n        pil_image.close()\n        # Convert RGB to BGR \n        cv2_image = cv2_image[:, :, ::-1]\n        return cv2_image", "title": ""}
{"_id": "d14884", "text": "def init_app(self, app):\n        \"\"\"Initialize Flask application.\"\"\"\n        app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True)", "title": ""}
{"_id": "d14885", "text": "def multidict_to_dict(d):\n    \"\"\"\n    Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with\n    list values\n    :param d: a MultiDict or MultiValueDict instance\n    :return: a dict instance\n    \"\"\"\n    return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))", "title": ""}
{"_id": "d14886", "text": "def _join(verb):\n    \"\"\"\n    Join helper\n    \"\"\"\n    data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n    # Preserve x groups\n    if isinstance(verb.x, GroupedDataFrame):\n        data.plydata_groups = list(verb.x.plydata_groups)\n    return data", "title": ""}
{"_id": "d14887", "text": "def pretty_print_post(req):\n    \"\"\"Helper to print a \"prepared\" query. Useful to debug a POST query.\n\n    However pay attention at the formatting used in\n    this function because it is programmed to be pretty\n    printed and may differ from the actual request.\n    \"\"\"\n    print(('{}\\n{}\\n{}\\n\\n{}'.format(\n        '-----------START-----------',\n        req.method + ' ' + req.url,\n        '\\n'.join('{}: {}'.format(k, v) for k, v in list(req.headers.items())),\n        req.body,\n    )))", "title": ""}
{"_id": "d14888", "text": "def get_unique_indices(df, axis=1):\n    \"\"\"\n\n    :param df:\n    :param axis:\n    :return:\n    \"\"\"\n    return dict(zip(df.columns.names, dif.columns.levels))", "title": ""}
{"_id": "d14889", "text": "def make_coord_dict(coord):\n    \"\"\"helper function to make a dict from a coordinate for logging\"\"\"\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    )", "title": ""}
{"_id": "d14890", "text": "def do_restart(self, line):\n        \"\"\"Request that the Outstation perform a cold restart. Command syntax is: restart\"\"\"\n        self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)", "title": ""}
{"_id": "d14891", "text": "def convert_time_string(date_str):\n    \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n    dt, _, _ = date_str.partition(\".\")\n    dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n    return dt", "title": ""}
{"_id": "d14892", "text": "def mimetype(self):\n        \"\"\"MIME type of the asset.\"\"\"\n        return (self.environment.mimetypes.get(self.format_extension) or\n                self.compiler_mimetype or 'application/octet-stream')", "title": ""}
{"_id": "d14893", "text": "def parse(self, s):\n        \"\"\"\n        Parses a date string formatted like ``YYYY-MM-DD``.\n        \"\"\"\n        return datetime.datetime.strptime(s, self.date_format).date()", "title": ""}
{"_id": "d14894", "text": "def get_handler(self, *args, **options):\n        \"\"\"\n        Returns the default WSGI handler for the runner.\n        \"\"\"\n        handler = get_internal_wsgi_application()\n        from django.contrib.staticfiles.handlers import StaticFilesHandler\n        return StaticFilesHandler(handler)", "title": ""}
{"_id": "d14895", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d14896", "text": "def get_handler(self, *args, **options):\n        \"\"\"\n        Returns the default WSGI handler for the runner.\n        \"\"\"\n        handler = get_internal_wsgi_application()\n        from django.contrib.staticfiles.handlers import StaticFilesHandler\n        return StaticFilesHandler(handler)", "title": ""}
{"_id": "d14897", "text": "def date_to_datetime(x):\n    \"\"\"Convert a date into a datetime\"\"\"\n    if not isinstance(x, datetime) and isinstance(x, date):\n        return datetime.combine(x, time())\n    return x", "title": ""}
{"_id": "d14898", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d14899", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d14900", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d14901", "text": "def this_quarter():\n        \"\"\" Return start and end date of this quarter. \"\"\"\n        since = TODAY + delta(day=1)\n        while since.month % 3 != 0:\n            since -= delta(months=1)\n        until = since + delta(months=3)\n        return Date(since), Date(until)", "title": ""}
{"_id": "d14902", "text": "def setLib(self, lib):\n        \"\"\" Copy the lib items into our font. \"\"\"\n        for name, item in lib.items():\n            self.font.lib[name] = item", "title": ""}
{"_id": "d14903", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d14904", "text": "def _enter_plotting(self, fontsize=9):\n        \"\"\"assumes that a figure is open \"\"\"\n        # interactive_status = matplotlib.is_interactive()\n        self.original_fontsize = pyplot.rcParams['font.size']\n        pyplot.rcParams['font.size'] = fontsize\n        pyplot.hold(False)  # opens a figure window, if non exists\n        pyplot.ioff()", "title": ""}
{"_id": "d14905", "text": "def cric__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n    model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4)\n\n    # we want to explain the raw probability outputs of the trees\n    model.predict = lambda X: model.predict_proba(X)[:,1]\n    \n    return model", "title": ""}
{"_id": "d14906", "text": "def count_levels(value):\n    \"\"\"\n        Count how many levels are in a dict:\n        scalar, list etc = 0\n        {} = 0\n        {'a':1} = 1\n        {'a' : {'b' : 1}} = 2\n        etc...\n    \"\"\"\n    if not isinstance(value, dict) or len(value) == 0:\n        return 0\n    elif len(value) == 0:\n        return 0 #An emptu dict has 0\n    else:\n        nextval = list(value.values())[0]\n        return 1 + count_levels(nextval)", "title": ""}
{"_id": "d14907", "text": "def list_of(cls):\n    \"\"\"\n    Returns a function that checks that each element in a\n    list is of a specific type.\n    \"\"\"\n    return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)", "title": ""}
{"_id": "d14908", "text": "def __del__(self):\n        \"\"\"Frees all resources.\n        \"\"\"\n        if hasattr(self, '_Api'):\n            self._Api.close()\n\n        self._Logger.info('object destroyed')", "title": ""}
{"_id": "d14909", "text": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Like `pretty` but print to stdout.\n    \"\"\"\n    printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    sys.stdout.write(newline)\n    sys.stdout.flush()", "title": ""}
{"_id": "d14910", "text": "def lighting(im, b, c):\n    \"\"\" Adjust image balance and contrast \"\"\"\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)", "title": ""}
{"_id": "d14911", "text": "def fixed(ctx, number, decimals=2, no_commas=False):\n    \"\"\"\n    Formats the given number in decimal format using a period and commas\n    \"\"\"\n    value = _round(ctx, number, decimals)\n    format_str = '{:f}' if no_commas else '{:,f}'\n    return format_str.format(value)", "title": ""}
{"_id": "d14912", "text": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "title": ""}
{"_id": "d14913", "text": "def format_float(value): # not used\n    \"\"\"Modified form of the 'g' format specifier.\n    \"\"\"\n    string = \"{:g}\".format(value).replace(\"e+\", \"e\")\n    string = re.sub(\"e(-?)0*(\\d+)\", r\"e\\1\\2\", string)\n    return string", "title": ""}
{"_id": "d14914", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d14915", "text": "def pprint(self, seconds):\n        \"\"\"\n        Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds\n\n        :param seconds:  The time in seconds.\n        \"\"\"\n        return (\"%d:%02d:%02d.%03d\", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))", "title": ""}
{"_id": "d14916", "text": "def delete(self, name):\n        \"\"\"\n        Deletes the named entry in the cache.\n        :param name: the name.\n        :return: true if it is deleted.\n        \"\"\"\n        if name in self._cache:\n            del self._cache[name]\n            self.writeCache()\n            # TODO clean files\n            return True\n        return False", "title": ""}
{"_id": "d14917", "text": "def fmt_sz(intval):\n    \"\"\" Format a byte sized value.\n    \"\"\"\n    try:\n        return fmt.human_size(intval)\n    except (ValueError, TypeError):\n        return \"N/A\".rjust(len(fmt.human_size(0)))", "title": ""}
{"_id": "d14918", "text": "def remove_this_tlink(self,tlink_id):\n        \"\"\"\n        Removes the tlink for the given tlink identifier\n        @type tlink_id: string\n        @param tlink_id: the tlink identifier to be removed\n        \"\"\"\n        for tlink in self.get_tlinks():\n            if tlink.get_id() == tlink_id:\n                self.node.remove(tlink.get_node())\n                break", "title": ""}
{"_id": "d14919", "text": "def rotation_from_quaternion(q_wxyz):\n        \"\"\"Convert quaternion array to rotation matrix.\n\n        Parameters\n        ----------\n        q_wxyz : :obj:`numpy.ndarray` of float\n            A quaternion in wxyz order.\n\n        Returns\n        -------\n        :obj:`numpy.ndarray` of float\n            A 3x3 rotation matrix made from the quaternion.\n        \"\"\"\n        q_xyzw = np.array([q_wxyz[1], q_wxyz[2], q_wxyz[3], q_wxyz[0]])\n        R = transformations.quaternion_matrix(q_xyzw)[:3,:3]\n        return R", "title": ""}
{"_id": "d14920", "text": "def rm(venv_name):\n    \"\"\" Removes the venv by name \"\"\"\n    inenv = InenvManager()\n    venv = inenv.get_venv(venv_name)\n    click.confirm(\"Delete dir {}\".format(venv.path))\n    shutil.rmtree(venv.path)", "title": ""}
{"_id": "d14921", "text": "def convert_tstamp(response):\n\t\"\"\"\n\tConvert a Stripe API timestamp response (unix epoch) to a native datetime.\n\n\t:rtype: datetime\n\t\"\"\"\n\tif response is None:\n\t\t# Allow passing None to convert_tstamp()\n\t\treturn response\n\n\t# Overrides the set timezone to UTC - I think...\n\ttz = timezone.utc if settings.USE_TZ else None\n\n\treturn datetime.datetime.fromtimestamp(response, tz)", "title": ""}
{"_id": "d14922", "text": "def trim(self):\n        \"\"\"Clear not used counters\"\"\"\n        for key, value in list(iteritems(self.counters)):\n            if value.empty():\n                del self.counters[key]", "title": ""}
{"_id": "d14923", "text": "def connect():\n    \"\"\"Connect to FTP server, login and return an ftplib.FTP instance.\"\"\"\n    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS\n    ftp = ftp_class(timeout=TIMEOUT)\n    ftp.connect(HOST, PORT)\n    ftp.login(USER, PASSWORD)\n    if SSL:\n        ftp.prot_p()  # secure data connection\n    return ftp", "title": ""}
{"_id": "d14924", "text": "def safe_delete(filename):\n  \"\"\"Delete a file safely. If it's not present, no-op.\"\"\"\n  try:\n    os.unlink(filename)\n  except OSError as e:\n    if e.errno != errno.ENOENT:\n      raise", "title": ""}
{"_id": "d14925", "text": "def remove_from_lib(self, name):\n        \"\"\" Remove an object from the bin folder. \"\"\"\n        self.__remove_path(os.path.join(self.root_dir, \"lib\", name))", "title": ""}
{"_id": "d14926", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d14927", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d14928", "text": "def first_unique_char(s):\n    \"\"\"\n    :type s: str\n    :rtype: int\n    \"\"\"\n    if (len(s) == 1):\n        return 0\n    ban = []\n    for i in range(len(s)):\n        if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:\n            return i\n        else:\n            ban.append(s[i])\n    return -1", "title": ""}
{"_id": "d14929", "text": "def safe_delete(filename):\n  \"\"\"Delete a file safely. If it's not present, no-op.\"\"\"\n  try:\n    os.unlink(filename)\n  except OSError as e:\n    if e.errno != errno.ENOENT:\n      raise", "title": ""}
{"_id": "d14930", "text": "def removeFromRegistery(obj) :\n\t\"\"\"Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory\n\ttaken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects,\n\tcascades to free the registeries of related rabalists also\"\"\"\n\t\n\tif isRabaObject(obj) :\n\t\t_unregisterRabaObjectInstance(obj)\n\telif isRabaList(obj) :\n\t\t_unregisterRabaListInstance(obj)", "title": ""}
{"_id": "d14931", "text": "def ex(self, cmd):\n        \"\"\"Execute a normal python statement in user namespace.\"\"\"\n        with self.builtin_trap:\n            exec cmd in self.user_global_ns, self.user_ns", "title": ""}
{"_id": "d14932", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d14933", "text": "def user_exists(username):\n    \"\"\"Check if a user exists\"\"\"\n    try:\n        pwd.getpwnam(username)\n        user_exists = True\n    except KeyError:\n        user_exists = False\n    return user_exists", "title": ""}
{"_id": "d14934", "text": "def delete_object_from_file(file_name, save_key, file_location):\n    \"\"\"\n    Function to delete objects from a shelve\n    Args:\n        file_name: Shelve storage file name\n        save_key: The name of the key the item is stored in\n        file_location: The location of the file, derive from the os module\n\n    Returns:\n\n    \"\"\"\n    file = __os.path.join(file_location, file_name)\n    shelve_store = __shelve.open(file)\n    del shelve_store[save_key]\n    shelve_store.close()", "title": ""}
{"_id": "d14935", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d14936", "text": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "title": ""}
{"_id": "d14937", "text": "def get_incomplete_path(filename):\n  \"\"\"Returns a temporary filename based on filename.\"\"\"\n  random_suffix = \"\".join(\n      random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n  return filename + \".incomplete\" + random_suffix", "title": ""}
{"_id": "d14938", "text": "def is_int_type(val):\n    \"\"\"Return True if `val` is of integer type.\"\"\"\n    try:               # Python 2\n        return isinstance(val, (int, long))\n    except NameError:  # Python 3\n        return isinstance(val, int)", "title": ""}
{"_id": "d14939", "text": "def list_get(l, idx, default=None):\n    \"\"\"\n    Get from a list with an optional default value.\n    \"\"\"\n    try:\n        if l[idx]:\n            return l[idx]\n        else:\n            return default\n    except IndexError:\n        return default", "title": ""}
{"_id": "d14940", "text": "def estimate_complexity(self, x,y,z,n):\n        \"\"\" \n        calculates a rough guess of runtime based on product of parameters \n        \"\"\"\n        num_calculations = x * y * z * n\n        run_time = num_calculations / 100000  # a 2014 PC does about 100k calcs in a second (guess based on prior logs)\n        return self.show_time_as_short_string(run_time)", "title": ""}
{"_id": "d14941", "text": "def _get_str_columns(sf):\n    \"\"\"\n    Returns a list of names of columns that are string type.\n    \"\"\"\n    return [name for name in sf.column_names() if sf[name].dtype == str]", "title": ""}
{"_id": "d14942", "text": "def isSquare(matrix):\n    \"\"\"Check that ``matrix`` is square.\n\n    Returns\n    =======\n    is_square : bool\n        ``True`` if ``matrix`` is square, ``False`` otherwise.\n\n    \"\"\"\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", "title": ""}
{"_id": "d14943", "text": "def search_for_tweets_about(user_id, params):\n    \"\"\" Search twitter API \"\"\"\n    url = \"https://api.twitter.com/1.1/search/tweets.json\"\n    response = make_twitter_request(url, user_id, params)\n    return process_tweets(response.json()[\"statuses\"])", "title": ""}
{"_id": "d14944", "text": "def is_hex_string(string):\n    \"\"\"Check if the string is only composed of hex characters.\"\"\"\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", "title": ""}
{"_id": "d14945", "text": "def getHeaders(self):\n        \"\"\"\n         Get the headers of this DataFrame.\n\n         Returns:\n            The headers of this DataFrame.\n        \"\"\"\n        headers = self._impl.getHeaders()\n        return tuple(\n            headers.getIndex(i) for i in range(self._impl.getNumCols())\n        )", "title": ""}
{"_id": "d14946", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d14947", "text": "def caller_locals():\n    \"\"\"Get the local variables in the caller's frame.\"\"\"\n    import inspect\n    frame = inspect.currentframe()\n    try:\n        return frame.f_back.f_back.f_locals\n    finally:\n        del frame", "title": ""}
{"_id": "d14948", "text": "def multi_pop(d, *args):\n    \"\"\" pops multiple keys off a dict like object \"\"\"\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval", "title": ""}
{"_id": "d14949", "text": "def __dir__(self):\n        u\"\"\"Returns a list of children and available helper methods.\"\"\"\n        return sorted(self.keys() | {m for m in dir(self.__class__) if m.startswith('to_')})", "title": ""}
{"_id": "d14950", "text": "def get_flat_size(self):\n        \"\"\"Returns the total length of all of the flattened variables.\n\n        Returns:\n            The length of all flattened variables concatenated.\n        \"\"\"\n        return sum(\n            np.prod(v.get_shape().as_list()) for v in self.variables.values())", "title": ""}
{"_id": "d14951", "text": "def get_tablenames(cur):\n    \"\"\" Conveinience: \"\"\"\n    cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n    tablename_list_ = cur.fetchall()\n    tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]\n    return tablename_list", "title": ""}
{"_id": "d14952", "text": "def me(self):\n        \"\"\"Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.\"\"\"\n        return self.guild.me if self.guild is not None else self.bot.user", "title": ""}
{"_id": "d14953", "text": "def current_memory_usage():\n    \"\"\"\n    Returns this programs current memory usage in bytes\n    \"\"\"\n    import psutil\n    proc = psutil.Process(os.getpid())\n    #meminfo = proc.get_memory_info()\n    meminfo = proc.memory_info()\n    rss = meminfo[0]  # Resident Set Size / Mem Usage\n    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA\n    return rss", "title": ""}
{"_id": "d14954", "text": "def get_chat_member(self, user_id):\n        \"\"\"\n        Get information about a member of a chat.\n\n        :param int user_id: Unique identifier of the target user\n        \"\"\"\n        return self.bot.api_call(\n            \"getChatMember\", chat_id=str(self.id), user_id=str(user_id)\n        )", "title": ""}
{"_id": "d14955", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d14956", "text": "def get_encoding(binary):\n    \"\"\"Return the encoding type.\"\"\"\n\n    try:\n        from chardet import detect\n    except ImportError:\n        LOGGER.error(\"Please install the 'chardet' module\")\n        sys.exit(1)\n\n    encoding = detect(binary).get('encoding')\n\n    return 'iso-8859-1' if encoding == 'CP949' else encoding", "title": ""}
{"_id": "d14957", "text": "def get_last_or_frame_exception():\n    \"\"\"Intended to be used going into post mortem routines.  If\n    sys.last_traceback is set, we will return that and assume that\n    this is what post-mortem will want. If sys.last_traceback has not\n    been set, then perhaps we *about* to raise an error and are\n    fielding an exception. So assume that sys.exc_info()[2]\n    is where we want to look.\"\"\"\n\n    try:\n        if inspect.istraceback(sys.last_traceback):\n            # We do have a traceback so prefer that.\n            return sys.last_type, sys.last_value, sys.last_traceback\n    except AttributeError:\n        pass\n    return sys.exc_info()", "title": ""}
{"_id": "d14958", "text": "def paste(cmd=paste_cmd, stdout=PIPE):\n    \"\"\"Returns system clipboard contents.\n    \"\"\"\n    return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')", "title": ""}
{"_id": "d14959", "text": "def confirm_credential_display(force=False):\n    if force:\n        return True\n\n    msg = \"\"\"\n    [WARNING] Your credential is about to be displayed on screen.\n    If this is really what you want, type 'y' and press enter.\"\"\"\n\n    result = click.confirm(text=msg)\n    return result", "title": ""}
{"_id": "d14960", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d14961", "text": "def get_distance_matrix(x):\n    \"\"\"Get distance matrix given a matrix. Used in testing.\"\"\"\n    square = nd.sum(x ** 2.0, axis=1, keepdims=True)\n    distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))\n    return nd.sqrt(distance_square)", "title": ""}
{"_id": "d14962", "text": "def dict_hash(dct):\n    \"\"\"Return a hash of the contents of a dictionary\"\"\"\n    dct_s = json.dumps(dct, sort_keys=True)\n\n    try:\n        m = md5(dct_s)\n    except TypeError:\n        m = md5(dct_s.encode())\n\n    return m.hexdigest()", "title": ""}
{"_id": "d14963", "text": "def safe_call(cls, method, *args):\n        \"\"\" Call a remote api method but don't raise if an error occurred.\"\"\"\n        return cls.call(method, *args, safe=True)", "title": ""}
{"_id": "d14964", "text": "def direct2dDistance(self, point):\n        \"\"\"consider the distance between two mapPoints, ignoring all terrain, pathing issues\"\"\"\n        if not isinstance(point, MapPoint): return 0.0\n        return  ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula", "title": ""}
{"_id": "d14965", "text": "def clone(src, **kwargs):\n    \"\"\"Clones object with optionally overridden fields\"\"\"\n    obj = object.__new__(type(src))\n    obj.__dict__.update(src.__dict__)\n    obj.__dict__.update(kwargs)\n    return obj", "title": ""}
{"_id": "d14966", "text": "def dict_pop_or(d, key, default=None):\n    \"\"\" Try popping a key from a dict.\n        Instead of raising KeyError, just return the default value.\n    \"\"\"\n    val = default\n    with suppress(KeyError):\n        val = d.pop(key)\n    return val", "title": ""}
{"_id": "d14967", "text": "def load_from_file(module_path):\n    \"\"\"\n    Load a python module from its absolute filesystem path\n\n    Borrowed from django-cms\n    \"\"\"\n    from imp import load_module, PY_SOURCE\n\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", "title": ""}
{"_id": "d14968", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d14969", "text": "def get_parent_folder_name(file_path):\n    \"\"\"Finds parent folder of file\n\n    :param file_path: path\n    :return: Name of folder container\n    \"\"\"\n    return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-1]", "title": ""}
{"_id": "d14970", "text": "def _is_start(event, node, tagName):  # pylint: disable=invalid-name\n    \"\"\"Return true if (event, node) is a start event for tagname.\"\"\"\n\n    return event == pulldom.START_ELEMENT and node.tagName == tagName", "title": ""}
{"_id": "d14971", "text": "def find_geom(geom, geoms):\n    \"\"\"\n    Returns the index of a geometry in a list of geometries avoiding\n    expensive equality checks of `in` operator.\n    \"\"\"\n    for i, g in enumerate(geoms):\n        if g is geom:\n            return i", "title": ""}
{"_id": "d14972", "text": "def _index2n(self, index):\n        \"\"\"\n\n        :param index: index convention\n        :return: n\n        \"\"\"\n        n_float = np.sqrt(index + 1) - 1\n        n_int = int(n_float)\n        if n_int == n_float:\n            n = n_int\n        else:\n            n = n_int + 1\n        return n", "title": ""}
{"_id": "d14973", "text": "def bisect_index(a, x):\n    \"\"\" Find the leftmost index of an element in a list using binary search.\n\n    Parameters\n    ----------\n    a: list\n        A sorted list.\n    x: arbitrary\n        The element.\n\n    Returns\n    -------\n    int\n        The index.\n\n    \"\"\"\n    i = bisect.bisect_left(a, x)\n    if i != len(a) and a[i] == x:\n        return i\n    raise ValueError", "title": ""}
{"_id": "d14974", "text": "def peak_memory_usage():\n    \"\"\"Return peak memory usage in MB\"\"\"\n    if sys.platform.startswith('win'):\n        p = psutil.Process()\n        return p.memory_info().peak_wset / 1024 / 1024\n\n    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n    factor_mb = 1 / 1024\n    if sys.platform == 'darwin':\n        factor_mb = 1 / (1024 * 1024)\n    return mem * factor_mb", "title": ""}
{"_id": "d14975", "text": "def get_substring_idxs(substr, string):\n    \"\"\"\n    Return a list of indexes of substr. If substr not found, list is\n    empty.\n\n    Arguments:\n        substr (str): Substring to match.\n        string (str): String to match in.\n\n    Returns:\n        list of int: Start indices of substr.\n    \"\"\"\n    return [match.start() for match in re.finditer(substr, string)]", "title": ""}
{"_id": "d14976", "text": "def to_basestring(value):\n    \"\"\"Converts a string argument to a subclass of basestring.\n\n    In python2, byte and unicode strings are mostly interchangeable,\n    so functions that deal with a user-supplied argument in combination\n    with ascii string constants can use either and should return the type\n    the user supplied.  In python3, the two types are not interchangeable,\n    so this method is needed to convert byte strings to unicode.\n    \"\"\"\n    if isinstance(value, _BASESTRING_TYPES):\n        return value\n    assert isinstance(value, bytes)\n    return value.decode(\"utf-8\")", "title": ""}
{"_id": "d14977", "text": "def string_to_int( s ):\n  \"\"\"Convert a string of bytes into an integer, as per X9.62.\"\"\"\n  result = 0\n  for c in s:\n    if not isinstance(c, int): c = ord( c )\n    result = 256 * result + c\n  return result", "title": ""}
{"_id": "d14978", "text": "def Output(self):\n    \"\"\"Output all sections of the page.\"\"\"\n    self.Open()\n    self.Header()\n    self.Body()\n    self.Footer()", "title": ""}
{"_id": "d14979", "text": "def get_by(self, name):\n    \"\"\"get element by name\"\"\"\n    return next((item for item in self if item.name == name), None)", "title": ""}
{"_id": "d14980", "text": "def graph_from_dot_file(path):\n    \"\"\"Load graph as defined by a DOT file.\n    \n    The file is assumed to be in DOT format. It will\n    be loaded, parsed and a Dot class will be returned, \n    representing the graph.\n    \"\"\"\n    \n    fd = file(path, 'rb')\n    data = fd.read()\n    fd.close()\n    \n    return graph_from_dot_data(data)", "title": ""}
{"_id": "d14981", "text": "def _lookup_enum_in_ns(namespace, value):\n    \"\"\"Return the attribute of namespace corresponding to value.\"\"\"\n    for attribute in dir(namespace):\n        if getattr(namespace, attribute) == value:\n            return attribute", "title": ""}
{"_id": "d14982", "text": "def dot_v2(vec1, vec2):\n    \"\"\"Return the dot product of two vectors\"\"\"\n\n    return vec1.x * vec2.x + vec1.y * vec2.y", "title": ""}
{"_id": "d14983", "text": "def apply_kwargs(func, **kwargs):\n    \"\"\"Call *func* with kwargs, but only those kwargs that it accepts.\n    \"\"\"\n    new_kwargs = {}\n    params = signature(func).parameters\n    for param_name in params.keys():\n        if param_name in kwargs:\n            new_kwargs[param_name] = kwargs[param_name]\n    return func(**new_kwargs)", "title": ""}
{"_id": "d14984", "text": "def _intermediary_to_dot(tables, relationships):\n    \"\"\" Returns the dot source representing the database in a string. \"\"\"\n    t = '\\n'.join(t.to_dot() for t in tables)\n    r = '\\n'.join(r.to_dot() for r in relationships)\n    return '{}\\n{}\\n{}\\n}}'.format(GRAPH_BEGINNING, t, r)", "title": ""}
{"_id": "d14985", "text": "def prevmonday(num):\n    \"\"\"\n    Return unix SECOND timestamp of \"num\" mondays ago\n    \"\"\"\n    today = get_today()\n    lastmonday = today - timedelta(days=today.weekday(), weeks=num)\n    return lastmonday", "title": ""}
{"_id": "d14986", "text": "def draw(self, mode=\"triangles\"):\n        \"\"\" Draw collection \"\"\"\n\n        gl.glDepthMask(0)\n        Collection.draw(self, mode)\n        gl.glDepthMask(1)", "title": ""}
{"_id": "d14987", "text": "def tail(self, n=10):\n        \"\"\"\n        Get an SArray that contains the last n elements in the SArray.\n\n        Parameters\n        ----------\n        n : int\n            The number of elements to fetch\n\n        Returns\n        -------\n        out : SArray\n            A new SArray which contains the last n rows of the current SArray.\n        \"\"\"\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.tail(n))", "title": ""}
{"_id": "d14988", "text": "def purge_duplicates(list_in):\n    \"\"\"Remove duplicates from list while preserving order.\n\n    Parameters\n    ----------\n    list_in: Iterable\n\n    Returns\n    -------\n    list\n        List of first occurences in order\n    \"\"\"\n    _list = []\n    for item in list_in:\n        if item not in _list:\n            _list.append(item)\n    return _list", "title": ""}
{"_id": "d14989", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d14990", "text": "def _histplot_bins(column, bins=100):\n    \"\"\"Helper to get bins for histplot.\"\"\"\n    col_min = np.min(column)\n    col_max = np.max(column)\n    return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))", "title": ""}
{"_id": "d14991", "text": "def get_language(self):\n        \"\"\"\n        Get the language parameter from the current request.\n        \"\"\"\n        return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object))", "title": ""}
{"_id": "d14992", "text": "def are_equal_xml(a_xml, b_xml):\n    \"\"\"Normalize and compare XML documents for equality. The document may or may not be\n    a DataONE type.\n\n    Args:\n      a_xml: str\n      b_xml: str\n        XML documents to compare for equality.\n\n    Returns:\n      bool: ``True`` if the XML documents are semantically equivalent.\n\n    \"\"\"\n    a_dom = xml.dom.minidom.parseString(a_xml)\n    b_dom = xml.dom.minidom.parseString(b_xml)\n    return are_equal_elements(a_dom.documentElement, b_dom.documentElement)", "title": ""}
{"_id": "d14993", "text": "def fetch(table, cols=\"*\", where=(), group=\"\", order=(), limit=(), **kwargs):\n    \"\"\"Convenience wrapper for database SELECT and fetch all.\"\"\"\n    return select(table, cols, where, group, order, limit, **kwargs).fetchall()", "title": ""}
{"_id": "d14994", "text": "def get_max(qs, field):\n    \"\"\"\n    get max for queryset.\n\n    qs: queryset\n    field: The field name to max.\n    \"\"\"\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0", "title": ""}
{"_id": "d14995", "text": "def deleteAll(self):\n        \"\"\"\n        Deletes whole Solr index. Use with care.\n        \"\"\"\n        for core in self.endpoints:\n            self._send_solr_command(self.endpoints[core], \"{\\\"delete\\\": { \\\"query\\\" : \\\"*:*\\\"}}\")", "title": ""}
{"_id": "d14996", "text": "def get_free_memory_win():\n    \"\"\"Return current free memory on the machine for windows.\n\n    Warning : this script is really not robust\n    Return in MB unit\n    \"\"\"\n    stat = MEMORYSTATUSEX()\n    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))\n    return int(stat.ullAvailPhys / 1024 / 1024)", "title": ""}
{"_id": "d14997", "text": "def matrixTimesVector(MM, aa):\n    \"\"\"\n\n    :param MM: A matrix of size 3x3\n    :param aa: A vector of size 3\n    :return: A vector of size 3 which is the product of the matrix by the vector\n    \"\"\"\n    bb = np.zeros(3, np.float)\n    for ii in range(3):\n        bb[ii] = np.sum(MM[ii, :] * aa)\n    return bb", "title": ""}
{"_id": "d14998", "text": "def remove_bad(string):\n    \"\"\"\n    remove problem characters from string\n    \"\"\"\n    remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n    for c in remove:\n        string = string.replace(c, '_')\n    return string", "title": ""}
{"_id": "d14999", "text": "def get_last_modified_timestamp(self):\n        \"\"\"\n        Looks at the files in a git root directory and grabs the last modified timestamp\n        \"\"\"\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", "title": ""}
{"_id": "d15000", "text": "def validate_email(email):\n    \"\"\"\n    Validates an email address\n    Source: Himanshu Shankar (https://github.com/iamhssingh)\n    Parameters\n    ----------\n    email: str\n\n    Returns\n    -------\n    bool\n    \"\"\"\n    from django.core.validators import validate_email\n    from django.core.exceptions import ValidationError\n    try:\n        validate_email(email)\n        return True\n    except ValidationError:\n        return False", "title": ""}
{"_id": "d15001", "text": "def get_model(name):\n    \"\"\"\n    Convert a model's verbose name to the model class. This allows us to\n    use the models verbose name in steps.\n    \"\"\"\n\n    model = MODELS.get(name.lower(), None)\n\n    assert model, \"Could not locate model by name '%s'\" % name\n\n    return model", "title": ""}
{"_id": "d15002", "text": "def read_string_from_file(path, encoding=\"utf8\"):\n  \"\"\"\n  Read entire contents of file into a string.\n  \"\"\"\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value", "title": ""}
{"_id": "d15003", "text": "def current_timestamp():\n    \"\"\"Returns current time as ISO8601 formatted string in the Zulu TZ\"\"\"\n    now = datetime.utcnow()\n    timestamp = now.isoformat()[0:19] + 'Z'\n\n    debug(\"generated timestamp: {now}\".format(now=timestamp))\n\n    return timestamp", "title": ""}
{"_id": "d15004", "text": "def session_to_epoch(timestamp):\n    \"\"\" converts Synergy Timestamp for session to UTC zone seconds since epoch \"\"\"\n    utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()\n    return calendar.timegm(utc_timetuple)", "title": ""}
{"_id": "d15005", "text": "def dimensions(self):\n        \"\"\"Get width and height of a PDF\"\"\"\n        size = self.pdf.getPage(0).mediaBox\n        return {'w': float(size[2]), 'h': float(size[3])}", "title": ""}
{"_id": "d15006", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d15007", "text": "def hex_to_rgb(h):\n    \"\"\" Returns 0 to 1 rgb from a hex list or tuple \"\"\"\n    h = h.lstrip('#')\n    return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4))", "title": ""}
{"_id": "d15008", "text": "def _escape(s):\n    \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n    e = s\n    e = e.replace('\\\\', '\\\\\\\\')\n    e = e.replace('\\n', '\\\\n')\n    e = e.replace('\\r', '\\\\r')\n    e = e.replace(\"'\", \"\\\\'\")\n    e = e.replace('\"', '\\\\\"')\n    return e", "title": ""}
{"_id": "d15009", "text": "def remove_ext(fname):\n    \"\"\"Removes the extension from a filename\n    \"\"\"\n    bn = os.path.basename(fname)\n    return os.path.splitext(bn)[0]", "title": ""}
{"_id": "d15010", "text": "def _cdf(self, xloc, dist, base, cache):\n        \"\"\"Cumulative distribution function.\"\"\"\n        return evaluation.evaluate_forward(dist, base**xloc, cache=cache)", "title": ""}
{"_id": "d15011", "text": "def getdefaultencoding():\n    \"\"\"Return IPython's guess for the default encoding for bytes as text.\n\n    Asks for stdin.encoding first, to match the calling Terminal, but that\n    is often None for subprocesses.  Fall back on locale.getpreferredencoding()\n    which should be a sensible platform default (that respects LANG environment),\n    and finally to sys.getdefaultencoding() which is the most conservative option,\n    and usually ASCII.\n    \"\"\"\n    enc = get_stream_enc(sys.stdin)\n    if not enc or enc=='ascii':\n        try:\n            # There are reports of getpreferredencoding raising errors\n            # in some cases, which may well be fixed, but let's be conservative here.\n            enc = locale.getpreferredencoding()\n        except Exception:\n            pass\n    return enc or sys.getdefaultencoding()", "title": ""}
{"_id": "d15012", "text": "def equal(obj1, obj2):\n    \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n    Comparable.log(obj1, obj2, '==')\n    equality = obj1.equality(obj2)\n    Comparable.log(obj1, obj2, '==', result=equality)\n    return equality", "title": ""}
{"_id": "d15013", "text": "def get_size(objects):\n    \"\"\"Compute the total size of all elements in objects.\"\"\"\n    res = 0\n    for o in objects:\n        try:\n            res += _getsizeof(o)\n        except AttributeError:\n            print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n    return res", "title": ""}
{"_id": "d15014", "text": "def run(self):\n        \"\"\"Run the event loop.\"\"\"\n        self.signal_init()\n        self.listen_init()\n        self.logger.info('starting')\n        self.loop.start()", "title": ""}
{"_id": "d15015", "text": "def monthly(date=datetime.date.today()):\n    \"\"\"\n    Take a date object and return the first day of the month.\n    \"\"\"\n    return datetime.date(date.year, date.month, 1)", "title": ""}
{"_id": "d15016", "text": "def previous_quarter(d):\n    \"\"\"\n    Retrieve the previous quarter for dt\n    \"\"\"\n    from django_toolkit.datetime_util import quarter as datetime_quarter\n    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )", "title": ""}
{"_id": "d15017", "text": "def findfirst(f, coll):\n    \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n    result = list(dropwhile(f, coll))\n    return result[0] if result else None", "title": ""}
{"_id": "d15018", "text": "def isTestCaseDisabled(test_case_class, method_name):\n    \"\"\"\n    I check to see if a method on a TestCase has been disabled via nose's\n    convention for disabling a TestCase.  This makes it so that users can\n    mix nose's parameterized tests with green as a runner.\n    \"\"\"\n    test_method = getattr(test_case_class, method_name)\n    return getattr(test_method, \"__test__\", 'not nose') is False", "title": ""}
{"_id": "d15019", "text": "def _get_item_position(self, idx):\n        \"\"\"Return a tuple of (start, end) indices of an item from its index.\"\"\"\n        start = 0 if idx == 0 else self._index[idx - 1] + 1\n        end = self._index[idx]\n        return start, end", "title": ""}
{"_id": "d15020", "text": "def to_dataframe(products):\n        \"\"\"Return the products from a query response as a Pandas DataFrame\n        with the values in their appropriate Python types.\n        \"\"\"\n        try:\n            import pandas as pd\n        except ImportError:\n            raise ImportError(\"to_dataframe requires the optional dependency Pandas.\")\n\n        return pd.DataFrame.from_dict(products, orient='index')", "title": ""}
{"_id": "d15021", "text": "def index(self, elem):\n        \"\"\"Find the index of elem in the reversed iterator.\"\"\"\n        return _coconut.len(self._iter) - self._iter.index(elem) - 1", "title": ""}
{"_id": "d15022", "text": "def convert_time_string(date_str):\n    \"\"\" Change a date string from the format 2018-08-15T23:55:17 into a datetime object \"\"\"\n    dt, _, _ = date_str.partition(\".\")\n    dt = datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n    return dt", "title": ""}
{"_id": "d15023", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d15024", "text": "def AmericanDateToEpoch(self, date_str):\n    \"\"\"Take a US format date and return epoch.\"\"\"\n    try:\n      epoch = time.strptime(date_str, \"%m/%d/%Y\")\n      return int(calendar.timegm(epoch)) * 1000000\n    except ValueError:\n      return 0", "title": ""}
{"_id": "d15025", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d15026", "text": "def string_to_genomic_range(rstring):\n  \"\"\" Convert a string to a genomic range\n\n  :param rstring: string representing a genomic range chr1:801-900\n  :type rstring:\n  :returns: object representing the string\n  :rtype: GenomicRange\n  \"\"\"\n  m = re.match('([^:]+):(\\d+)-(\\d+)',rstring)\n  if not m: \n    sys.stderr.write(\"ERROR: problem with range string \"+rstring+\"\\n\")\n  return GenomicRange(m.group(1),int(m.group(2)),int(m.group(3)))", "title": ""}
{"_id": "d15027", "text": "def convert_2_utc(self, datetime_, timezone):\n        \"\"\"convert to datetime to UTC offset.\"\"\"\n\n        datetime_ = self.tz_mapper[timezone].localize(datetime_)\n        return datetime_.astimezone(pytz.UTC)", "title": ""}
{"_id": "d15028", "text": "def listified_tokenizer(source):\n    \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n    io_obj = io.StringIO(source)\n    return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]", "title": ""}
{"_id": "d15029", "text": "def intty(cls):\n        \"\"\" Check if we are in a tty. \"\"\"\n        # XXX: temporary hack until we can detect if we are in a pipe or not\n        return True\n\n        if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():\n            return True\n\n        return False", "title": ""}
{"_id": "d15030", "text": "def code_from_ipynb(nb, markdown=False):\n    \"\"\"\n    Get the code for a given notebook\n\n    nb is passed in as a dictionary that's a parsed ipynb file\n    \"\"\"\n    code = PREAMBLE\n    for cell in nb['cells']:\n        if cell['cell_type'] == 'code':\n            # transform the input to executable Python\n            code += ''.join(cell['source'])\n        if cell['cell_type'] == 'markdown':\n            code += '\\n# ' + '# '.join(cell['source'])\n        # We want a blank newline after each cell's output.\n        # And the last line of source doesn't have a newline usually.\n        code += '\\n\\n'\n    return code", "title": ""}
{"_id": "d15031", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d15032", "text": "def computeFactorial(n):\n    \"\"\"\n    computes factorial of n\n    \"\"\"\n    sleep_walk(10)\n    ret = 1\n    for i in range(n):\n        ret = ret * (i + 1)\n    return ret", "title": ""}
{"_id": "d15033", "text": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "title": ""}
{"_id": "d15034", "text": "def get_mnist(data_type=\"train\", location=\"/tmp/mnist\"):\n    \"\"\"\n    Get mnist dataset with features and label as ndarray.\n    Data would be downloaded automatically if it doesn't present at the specific location.\n\n    :param data_type: \"train\" for training data and \"test\" for testing data.\n    :param location: Location to store mnist dataset.\n    :return: (features: ndarray, label: ndarray)\n    \"\"\"\n    X, Y = mnist.read_data_sets(location, data_type)\n    return X, Y + 1", "title": ""}
{"_id": "d15035", "text": "def get_value(key, obj, default=missing):\n    \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n    if isinstance(key, int):\n        return _get_value_for_key(key, obj, default)\n    return _get_value_for_keys(key.split('.'), obj, default)", "title": ""}
{"_id": "d15036", "text": "def c_str(string):\n    \"\"\"\"Convert a python string to C string.\"\"\"\n    if not isinstance(string, str):\n        string = string.decode('ascii')\n    return ctypes.c_char_p(string.encode('utf-8'))", "title": ""}
{"_id": "d15037", "text": "def get_inputs_from_cm(index, cm):\n    \"\"\"Return indices of inputs to the node with the given index.\"\"\"\n    return tuple(i for i in range(cm.shape[0]) if cm[i][index])", "title": ""}
{"_id": "d15038", "text": "def software_fibonacci(n):\n    \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n    a, b = 0, 1\n    for i in range(n):\n        a, b = b, a + b\n    return a", "title": ""}
{"_id": "d15039", "text": "def _read_stream_for_size(stream, buf_size=65536):\n    \"\"\"Reads a stream discarding the data read and returns its size.\"\"\"\n    size = 0\n    while True:\n        buf = stream.read(buf_size)\n        size += len(buf)\n        if not buf:\n            break\n    return size", "title": ""}
{"_id": "d15040", "text": "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)", "title": ""}
{"_id": "d15041", "text": "def save_dot(self, fd):\n        \"\"\" Saves a representation of the case in the Graphviz DOT language.\n        \"\"\"\n        from pylon.io import DotWriter\n        DotWriter(self).write(fd)", "title": ""}
{"_id": "d15042", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d15043", "text": "def _column_resized(self, col, old_width, new_width):\n        \"\"\"Update the column width.\"\"\"\n        self.dataTable.setColumnWidth(col, new_width)\n        self._update_layout()", "title": ""}
{"_id": "d15044", "text": "def clean_dataframe(df):\n    \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n    df = df.fillna(method='ffill')\n    df = df.fillna(0.0)\n    return df", "title": ""}
{"_id": "d15045", "text": "def gcall(func, *args, **kwargs):\n    \"\"\"\n    Calls a function, with the given arguments inside Gtk's main loop.\n    Example::\n        gcall(lbl.set_text, \"foo\")\n\n    If this call would be made in a thread there could be problems, using\n    it inside Gtk's main loop makes it thread safe.\n    \"\"\"\n    def idle():\n        with gdk.lock:\n            return bool(func(*args, **kwargs))\n    return gobject.idle_add(idle)", "title": ""}
{"_id": "d15046", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d15047", "text": "def np_hash(a):\n    \"\"\"Return a hash of a NumPy array.\"\"\"\n    if a is None:\n        return hash(None)\n    # Ensure that hashes are equal whatever the ordering in memory (C or\n    # Fortran)\n    a = np.ascontiguousarray(a)\n    # Compute the digest and return a decimal int\n    return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)", "title": ""}
{"_id": "d15048", "text": "def tuple_search(t, i, v):\n    \"\"\"\n    Search tuple array by index and value\n    :param t: tuple array\n    :param i: index of the value in each tuple\n    :param v: value\n    :return: the first tuple in the array with the specific index / value\n    \"\"\"\n    for e in t:\n        if e[i] == v:\n            return e\n    return None", "title": ""}
{"_id": "d15049", "text": "def top(n, width=WIDTH, style=STYLE):\n    \"\"\"Prints the top row of a table\"\"\"\n    return hrule(n, width, linestyle=STYLES[style].top)", "title": ""}
{"_id": "d15050", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d15051", "text": "def equal(list1, list2):\n    \"\"\" takes flags returns indexes of True values \"\"\"\n    return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]", "title": ""}
{"_id": "d15052", "text": "def update_index(index):\n    \"\"\"Re-index every document in a named index.\"\"\"\n    logger.info(\"Updating search index: '%s'\", index)\n    client = get_client()\n    responses = []\n    for model in get_index_models(index):\n        logger.info(\"Updating search index model: '%s'\", model.search_doc_type)\n        objects = model.objects.get_search_queryset(index).iterator()\n        actions = bulk_actions(objects, index=index, action=\"index\")\n        response = helpers.bulk(client, actions, chunk_size=get_setting(\"chunk_size\"))\n        responses.append(response)\n    return responses", "title": ""}
{"_id": "d15053", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d15054", "text": "def hide(self):\n        \"\"\"Hide the window.\"\"\"\n        self.tk.withdraw()\n        self._visible = False\n        if self._modal:\n            self.tk.grab_release()", "title": ""}
{"_id": "d15055", "text": "def local_minima(img, min_distance = 4):\n    r\"\"\"\n    Returns all local minima from an image.\n    \n    Parameters\n    ----------\n    img : array_like\n        The image.\n    min_distance : integer\n        The minimal distance between the minimas in voxels. If it is less, only the lower minima is returned.\n    \n    Returns\n    -------\n    indices : sequence\n        List of all minima indices.\n    values : sequence\n        List of all minima values.\n    \"\"\"\n    # @TODO: Write a unittest for this.\n    fits = numpy.asarray(img)\n    minfits = minimum_filter(fits, size=min_distance) # default mode is reflect\n    minima_mask = fits == minfits\n    good_indices = numpy.transpose(minima_mask.nonzero())\n    good_fits = fits[minima_mask]\n    order = good_fits.argsort()\n    return good_indices[order], good_fits[order]", "title": ""}
{"_id": "d15056", "text": "def oplot(self, x, y, **kw):\n        \"\"\"generic plotting method, overplotting any existing plot \"\"\"\n        self.panel.oplot(x, y, **kw)", "title": ""}
{"_id": "d15057", "text": "def _factor_generator(n):\n    \"\"\"\n    From a given natural integer, returns the prime factors and their multiplicity\n    :param n: Natural integer\n    :return:\n    \"\"\"\n    p = prime_factors(n)\n    factors = {}\n    for p1 in p:\n        try:\n            factors[p1] += 1\n        except KeyError:\n            factors[p1] = 1\n    return factors", "title": ""}
{"_id": "d15058", "text": "def retrieve_by_id(self, id_):\n        \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n        items_with_id = [item for item in self if item.id == int(id_)]\n        if len(items_with_id) == 1:\n            return items_with_id[0].retrieve()", "title": ""}
{"_id": "d15059", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d15060", "text": "def readline(self):\n        \"\"\"Get the next line including the newline or '' on EOF.\"\"\"\n        self.lineno += 1\n        if self._buffer:\n            return self._buffer.pop()\n        else:\n            return self.input.readline()", "title": ""}
{"_id": "d15061", "text": "def union_overlapping(intervals):\n    \"\"\"Union any overlapping intervals in the given set.\"\"\"\n    disjoint_intervals = []\n\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\n    return disjoint_intervals", "title": ""}
{"_id": "d15062", "text": "def init():\n    \"\"\"\n    Execute init tasks for all components (virtualenv, pip).\n    \"\"\"\n    print(yellow(\"# Setting up environment...\\n\", True))\n    virtualenv.init()\n    virtualenv.update_requirements()\n    print(green(\"\\n# DONE.\", True))\n    print(green(\"Type \") + green(\"activate\", True) + green(\" to enable your virtual environment.\"))", "title": ""}
{"_id": "d15063", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d15064", "text": "def ratelimit_remaining(self):\n        \"\"\"Number of requests before GitHub imposes a ratelimit.\n\n        :returns: int\n        \"\"\"\n        json = self._json(self._get(self._github_url + '/rate_limit'), 200)\n        core = json.get('resources', {}).get('core', {})\n        self._remaining = core.get('remaining', 0)\n        return self._remaining", "title": ""}
{"_id": "d15065", "text": "def _sim_fill(r1, r2, imsize):\n    \"\"\"\n        calculate the fill similarity over the image\n    \"\"\"\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", "title": ""}
{"_id": "d15066", "text": "def is_sparse_vector(x):\n    \"\"\" x is a 2D sparse matrix with it's first shape equal to 1.\n    \"\"\"\n    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1", "title": ""}
{"_id": "d15067", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d15068", "text": "def fit_gaussian(x, y, yerr, p0):\n    \"\"\" Fit a Gaussian to the data \"\"\"\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", "title": ""}
{"_id": "d15069", "text": "def bytes_to_str(s, encoding='utf-8'):\n    \"\"\"Returns a str if a bytes object is given.\"\"\"\n    if six.PY3 and isinstance(s, bytes):\n        return s.decode(encoding)\n    return s", "title": ""}
{"_id": "d15070", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d15071", "text": "def go_to_parent_directory(self):\n        \"\"\"Go to parent directory\"\"\"\n        self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))", "title": ""}
{"_id": "d15072", "text": "def old_pad(s):\n    \"\"\"\n    Pads an input string to a given block size.\n    :param s: string\n    :returns: The padded string.\n    \"\"\"\n    if len(s) % OLD_BLOCK_SIZE == 0:\n        return s\n\n    return Padding.appendPadding(s, blocksize=OLD_BLOCK_SIZE)", "title": ""}
{"_id": "d15073", "text": "def split_into_words(s):\n  \"\"\"Split a sentence into list of words.\"\"\"\n  s = re.sub(r\"\\W+\", \" \", s)\n  s = re.sub(r\"[_0-9]+\", \" \", s)\n  return s.split()", "title": ""}
{"_id": "d15074", "text": "def rewrap(s, width=COLS):\n    \"\"\" Join all lines from input string and wrap it at specified width \"\"\"\n    s = ' '.join([l.strip() for l in s.strip().split('\\n')])\n    return '\\n'.join(textwrap.wrap(s, width))", "title": ""}
{"_id": "d15075", "text": "def lower_ext(abspath):\n    \"\"\"Convert file extension to lowercase.\n    \"\"\"\n    fname, ext = os.path.splitext(abspath)\n    return fname + ext.lower()", "title": ""}
{"_id": "d15076", "text": "def flatten(nested):\n    \"\"\" Return a flatten version of the nested argument \"\"\"\n    flat_return = list()\n\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\n    __inner_flat(nested,flat_return)\n\n    return flat_return", "title": ""}
{"_id": "d15077", "text": "def is_valid_url(url):\n    \"\"\"Checks if a given string is an url\"\"\"\n    pieces = urlparse(url)\n    return all([pieces.scheme, pieces.netloc])", "title": ""}
{"_id": "d15078", "text": "def enable_writes(self):\n        \"\"\"Restores the state of the batched queue for writing.\"\"\"\n        self.write_buffer = []\n        self.flush_lock = threading.RLock()\n        self.flush_thread = FlushThread(self.max_batch_time,\n                                        self._flush_writes)", "title": ""}
{"_id": "d15079", "text": "def find_lt(a, x):\n    \"\"\"Find rightmost value less than x\"\"\"\n    i = bisect.bisect_left(a, x)\n    if i:\n        return a[i-1]\n    raise ValueError", "title": ""}
{"_id": "d15080", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d15081", "text": "def has_overlaps(self):\n        \"\"\"\n        :returns: True if one or more range in the list overlaps with another\n        :rtype: bool\n        \"\"\"\n        sorted_list = sorted(self)\n        for i in range(0, len(sorted_list) - 1):\n            if sorted_list[i].overlaps(sorted_list[i + 1]):\n                return True\n        return False", "title": ""}
{"_id": "d15082", "text": "def __call__(self, _):\n        \"\"\"Update the progressbar.\"\"\"\n        if self.iter % self.step == 0:\n            self.pbar.update(self.step)\n\n        self.iter += 1", "title": ""}
{"_id": "d15083", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d15084", "text": "def combine(self, a, b):\n        \"\"\"A generator that combines two iterables.\"\"\"\n\n        for l in (a, b):\n            for x in l:\n                yield x", "title": ""}
{"_id": "d15085", "text": "def is_serializable(obj):\n    \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool\n    \"\"\"\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')", "title": ""}
{"_id": "d15086", "text": "def _delete_local(self, filename):\n        \"\"\"Deletes the specified file from the local filesystem.\"\"\"\n\n        if os.path.exists(filename):\n            os.remove(filename)", "title": ""}
{"_id": "d15087", "text": "def clear():\n    \"\"\"Clears the console.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        call(\"cls\", shell=True)\n    else:\n        call(\"clear\", shell=True)", "title": ""}
{"_id": "d15088", "text": "def login(self, username, password=None, token=None):\n        \"\"\"Login user for protected API calls.\"\"\"\n        self.session.basic_auth(username, password)", "title": ""}
{"_id": "d15089", "text": "def bit_clone( bits ):\n    \"\"\"\n    Clone a bitset\n    \"\"\"\n    new = BitSet( bits.size )\n    new.ior( bits )\n    return new", "title": ""}
{"_id": "d15090", "text": "def get_year_start(day=None):\n    \"\"\"Returns January 1 of the given year.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(month=1).replace(day=1)", "title": ""}
{"_id": "d15091", "text": "def feature_union_concat(Xs, nsamples, weights):\n    \"\"\"Apply weights and concatenate outputs from a FeatureUnion\"\"\"\n    if any(x is FIT_FAILURE for x in Xs):\n        return FIT_FAILURE\n    Xs = [X if w is None else X * w for X, w in zip(Xs, weights) if X is not None]\n    if not Xs:\n        return np.zeros((nsamples, 0))\n    if any(sparse.issparse(f) for f in Xs):\n        return sparse.hstack(Xs).tocsr()\n    return np.hstack(Xs)", "title": ""}
{"_id": "d15092", "text": "def fixed(ctx, number, decimals=2, no_commas=False):\n    \"\"\"\n    Formats the given number in decimal format using a period and commas\n    \"\"\"\n    value = _round(ctx, number, decimals)\n    format_str = '{:f}' if no_commas else '{:,f}'\n    return format_str.format(value)", "title": ""}
{"_id": "d15093", "text": "def from_pb(cls, pb):\n        \"\"\"Instantiate the object from a protocol buffer.\n\n        Args:\n            pb (protobuf)\n\n        Save a reference to the protocol buffer on the object.\n        \"\"\"\n        obj = cls._from_pb(pb)\n        obj._pb = pb\n        return obj", "title": ""}
{"_id": "d15094", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d15095", "text": "def _get_wow64():\n    \"\"\"\n    Determines if the current process is running in Windows-On-Windows 64 bits.\n\n    @rtype:  bool\n    @return: C{True} of the current process is a 32 bit program running in a\n        64 bit version of Windows, C{False} if it's either a 32 bit program\n        in a 32 bit Windows or a 64 bit program in a 64 bit Windows.\n    \"\"\"\n    # Try to determine if the debugger itself is running on WOW64.\n    # On error assume False.\n    if bits == 64:\n        wow64 = False\n    else:\n        try:\n            wow64 = IsWow64Process( GetCurrentProcess() )\n        except Exception:\n            wow64 = False\n    return wow64", "title": ""}
{"_id": "d15096", "text": "def get_lons_from_cartesian(x__, y__):\n    \"\"\"Get longitudes from cartesian coordinates.\n    \"\"\"\n    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)", "title": ""}
{"_id": "d15097", "text": "def raise_os_error(_errno, path=None):\n    \"\"\"\n    Helper for raising the correct exception under Python 3 while still\n    being able to raise the same common exception class in Python 2.7.\n    \"\"\"\n\n    msg = \"%s: '%s'\" % (strerror(_errno), path) if path else strerror(_errno)\n    raise OSError(_errno, msg)", "title": ""}
{"_id": "d15098", "text": "def stft(func=None, **kwparams):\n  \"\"\"\n  Short Time Fourier Transform for real data keeping the full FFT block.\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,\n              inverse_transform=lambda *args: numpy.fft.ifft(*args).real)\n\n  See ``stft.base`` docs for more.\n  \"\"\"\n  from numpy.fft import fft, ifft\n  ifft_r = lambda *args: ifft(*args).real\n  return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)", "title": ""}
{"_id": "d15099", "text": "def strip_spaces(s):\n    \"\"\" Strip excess spaces from a string \"\"\"\n    return u\" \".join([c for c in s.split(u' ') if c])", "title": ""}
{"_id": "d15100", "text": "def set_timeout(scope, timeout):\n    \"\"\"\n    Defines the time after which Exscript fails if it does not receive a\n    prompt from the remote host.\n\n    :type  timeout: int\n    :param timeout: The timeout in seconds.\n    \"\"\"\n    conn = scope.get('__connection__')\n    conn.set_timeout(int(timeout[0]))\n    return True", "title": ""}
{"_id": "d15101", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d15102", "text": "def _get_printable_columns(columns, row):\n    \"\"\"Return only the part of the row which should be printed.\n    \"\"\"\n    if not columns:\n        return row\n\n    # Extract the column values, in the order specified.\n    return tuple(row[c] for c in columns)", "title": ""}
{"_id": "d15103", "text": "def _stdin_(p):\n    \"\"\"Takes input from user. Works for Python 2 and 3.\"\"\"\n    _v = sys.version[0]\n    return input(p) if _v is '3' else raw_input(p)", "title": ""}
{"_id": "d15104", "text": "def _send_file(self, filename):\n        \"\"\"\n        Sends a file via FTP.\n        \"\"\"\n        # pylint: disable=E1101\n        ftp = ftplib.FTP(host=self.host)\n        ftp.login(user=self.user, passwd=self.password)\n        ftp.set_pasv(True)\n        ftp.storbinary(\"STOR %s\" % os.path.basename(filename),\n            file(filename, 'rb'))", "title": ""}
{"_id": "d15105", "text": "def many_until1(these, term):\n    \"\"\"Like many_until but must consume at least one of these.\n    \"\"\"\n    first = [these()]\n    these_results, term_result = many_until(these, term)\n    return (first + these_results, term_result)", "title": ""}
{"_id": "d15106", "text": "def write_file(filename, content):\n    \"\"\"Create the file with the given content\"\"\"\n    print 'Generating {0}'.format(filename)\n    with open(filename, 'wb') as out_f:\n        out_f.write(content)", "title": ""}
{"_id": "d15107", "text": "def smooth_gaussian(image, sigma=1):\n    \"\"\"Returns Gaussian smoothed image.\n\n    :param image: numpy array or :class:`jicimagelib.image.Image`\n    :param sigma: standard deviation\n    :returns: :class:`jicimagelib.image.Image`\n    \"\"\"\n    return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode=\"nearest\")", "title": ""}
{"_id": "d15108", "text": "def uniform_noise(points):\n    \"\"\"Init a uniform noise variable.\"\"\"\n    return np.random.rand(1) * np.random.uniform(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d15109", "text": "def _uniqueid(n=30):\n    \"\"\"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\n    \"\"\"\n    return ''.join(random.SystemRandom().choice(\n                   string.ascii_uppercase + string.ascii_lowercase)\n                   for _ in range(n))", "title": ""}
{"_id": "d15110", "text": "def get_var(self, name):\n        \"\"\" Returns the variable set with the given name.\n        \"\"\"\n        for var in self.vars:\n            if var.name == name:\n                return var\n        else:\n            raise ValueError", "title": ""}
{"_id": "d15111", "text": "def daterange(start_date, end_date):\n    \"\"\"\n    Yield one date per day from starting date to ending date.\n\n    Args:\n        start_date (date): starting date.\n        end_date (date): ending date.\n\n    Yields:\n        date: a date for each day within the range.\n    \"\"\"\n    for n in range(int((end_date - start_date).days)):\n        yield start_date + timedelta(n)", "title": ""}
{"_id": "d15112", "text": "def get_property(self, filename):\n        \"\"\"Opens the file and reads the value\"\"\"\n\n        with open(self.filepath(filename)) as f:\n            return f.read().strip()", "title": ""}
{"_id": "d15113", "text": "def generate(env):\n    \"\"\"Add Builders and construction variables for SGI MIPS C++ to an Environment.\"\"\"\n\n    cplusplus.generate(env)\n\n    env['CXX']         = 'CC'\n    env['CXXFLAGS']    = SCons.Util.CLVar('-LANG:std')\n    env['SHCXX']       = '$CXX'\n    env['SHOBJSUFFIX'] = '.o'\n    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1", "title": ""}
{"_id": "d15114", "text": "def convert_2_utc(self, datetime_, timezone):\n        \"\"\"convert to datetime to UTC offset.\"\"\"\n\n        datetime_ = self.tz_mapper[timezone].localize(datetime_)\n        return datetime_.astimezone(pytz.UTC)", "title": ""}
{"_id": "d15115", "text": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "title": ""}
{"_id": "d15116", "text": "def get_uniques(l):\n    \"\"\" Returns a list with no repeated elements.\n    \"\"\"\n    result = []\n\n    for i in l:\n        if i not in result:\n            result.append(i)\n\n    return result", "title": ""}
{"_id": "d15117", "text": "def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):\n    \"\"\"A quick and dirty way to get a unique string\"\"\"\n    return ''.join(random.choice(chars) for x in xrange(size))", "title": ""}
{"_id": "d15118", "text": "def asMaskedArray(self):\n        \"\"\" Creates converts to a masked array\n        \"\"\"\n        return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)", "title": ""}
{"_id": "d15119", "text": "def sha1(s):\n    \"\"\" Returns a sha1 of the given string\n    \"\"\"\n    h = hashlib.new('sha1')\n    h.update(s)\n    return h.hexdigest()", "title": ""}
{"_id": "d15120", "text": "def _weighted_selection(l, n):\n    \"\"\"\n        Selects  n random elements from a list of (weight, item) tuples.\n        Based on code snippet by Nick Johnson\n    \"\"\"\n    cuml = []\n    items = []\n    total_weight = 0.0\n    for weight, item in l:\n        total_weight += weight\n        cuml.append(total_weight)\n        items.append(item)\n\n    return [items[bisect.bisect(cuml, random.random()*total_weight)] for _ in range(n)]", "title": ""}
{"_id": "d15121", "text": "def flattened_nested_key_indices(nested_dict):\n    \"\"\"\n    Combine the outer and inner keys of nested dictionaries into a single\n    ordering.\n    \"\"\"\n    outer_keys, inner_keys = collect_nested_keys(nested_dict)\n    combined_keys = list(sorted(set(outer_keys + inner_keys)))\n    return {k: i for (i, k) in enumerate(combined_keys)}", "title": ""}
{"_id": "d15122", "text": "def move_to_start(self, column_label):\n        \"\"\"Move a column to the first in order.\"\"\"\n        self._columns.move_to_end(column_label, last=False)\n        return self", "title": ""}
{"_id": "d15123", "text": "def list_apis(awsclient):\n    \"\"\"List APIs in account.\"\"\"\n    client_api = awsclient.get_client('apigateway')\n\n    apis = client_api.get_rest_apis()['items']\n\n    for api in apis:\n        print(json2table(api))", "title": ""}
{"_id": "d15124", "text": "def normalize_array(lst):\n    \"\"\"Normalizes list\n\n    :param lst: Array of floats\n    :return: Normalized (in [0, 1]) input array\n    \"\"\"\n    np_arr = np.array(lst)\n    x_normalized = np_arr / np_arr.max(axis=0)\n    return list(x_normalized)", "title": ""}
{"_id": "d15125", "text": "def files_changed():\n    \"\"\"\n    Return the list of file changed in the current branch compared to `master`\n    \"\"\"\n    with chdir(get_root()):\n        result = run_command('git diff --name-only master...', capture='out')\n    changed_files = result.stdout.splitlines()\n\n    # Remove empty lines\n    return [f for f in changed_files if f]", "title": ""}
{"_id": "d15126", "text": "def prettyprint(d):\n        \"\"\"Print dicttree in Json-like format. keys are sorted\n        \"\"\"\n        print(json.dumps(d, sort_keys=True, \n                         indent=4, separators=(\",\" , \": \")))", "title": ""}
{"_id": "d15127", "text": "def from_string(cls, s):\n        \"\"\"Return a `Status` instance from its string representation.\"\"\"\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)", "title": ""}
{"_id": "d15128", "text": "def _get_name(column_like):\n    \"\"\"\n    Get the name from a column-like SQLAlchemy expression.\n\n    Works for Columns and Cast expressions.\n    \"\"\"\n    if isinstance(column_like, Column):\n        return column_like.name\n    elif isinstance(column_like, Cast):\n        return column_like.clause.name", "title": ""}
{"_id": "d15129", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d15130", "text": "def _reload(self, force=False):\n        \"\"\"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.\n        \"\"\"\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()", "title": ""}
{"_id": "d15131", "text": "def commits_with_message(message):\n    \"\"\"All commits with that message (in current branch)\"\"\"\n    output = log(\"--grep '%s'\" % message, oneline=True, quiet=True)\n    lines = output.splitlines()\n    return [l.split(' ', 1)[0] for l in lines]", "title": ""}
{"_id": "d15132", "text": "def replaceNewlines(string, newlineChar):\n\t\"\"\"There's probably a way to do this with string functions but I was lazy.\n\t\tReplace all instances of \\r or \\n in a string with something else.\"\"\"\n\tif newlineChar in string:\n\t\tsegments = string.split(newlineChar)\n\t\tstring = \"\"\n\t\tfor segment in segments:\n\t\t\tstring += segment\n\treturn string", "title": ""}
{"_id": "d15133", "text": "def get_grid_spatial_dimensions(self, variable):\n        \"\"\"Returns (width, height) for the given variable\"\"\"\n\n        data = self.open_dataset(self.service).variables[variable.variable]\n        dimensions = list(data.dimensions)\n        return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.index(variable.y_dimension)]", "title": ""}
{"_id": "d15134", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d15135", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d15136", "text": "def autozoom(self, n=None):\n        \"\"\"\n        Auto-scales the axes to fit all the data in plot index n. If n == None,\n        auto-scale everyone.\n        \"\"\"\n        if n==None:\n            for p in self.plot_widgets: p.autoRange()\n        else:        self.plot_widgets[n].autoRange()\n\n        return self", "title": ""}
{"_id": "d15137", "text": "def horz_dpi(self):\n        \"\"\"\n        Integer dots per inch for the width of this image. Defaults to 72\n        when not present in the file, as is often the case.\n        \"\"\"\n        pHYs = self._chunks.pHYs\n        if pHYs is None:\n            return 72\n        return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)", "title": ""}
{"_id": "d15138", "text": "def _selectItem(self, index):\n        \"\"\"Select item in the list\n        \"\"\"\n        self._selectedIndex = index\n        self.setCurrentIndex(self.model().createIndex(index, 0))", "title": ""}
{"_id": "d15139", "text": "def get_abi3_suffix():\n    \"\"\"Return the file extension for an abi3-compliant Extension()\"\"\"\n    for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION):\n        if '.abi3' in suffix:  # Unix\n            return suffix\n        elif suffix == '.pyd':  # Windows\n            return suffix", "title": ""}
{"_id": "d15140", "text": "def print_env_info(key, out=sys.stderr):\n    \"\"\"If given environment key is defined, print it out.\"\"\"\n    value = os.getenv(key)\n    if value is not None:\n        print(key, \"=\", repr(value), file=out)", "title": ""}
{"_id": "d15141", "text": "def get_file_size(fileobj):\n    \"\"\"\n    Returns the size of a file-like object.\n    \"\"\"\n    currpos = fileobj.tell()\n    fileobj.seek(0, 2)\n    total_size = fileobj.tell()\n    fileobj.seek(currpos)\n    return total_size", "title": ""}
{"_id": "d15142", "text": "def Sum(a, axis, keep_dims):\n    \"\"\"\n    Sum reduction op.\n    \"\"\"\n    return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                  keepdims=keep_dims),", "title": ""}
{"_id": "d15143", "text": "def get_winfunc(libname, funcname, restype=None, argtypes=(), _libcache={}):\n    \"\"\"Retrieve a function from a library/DLL, and set the data types.\"\"\"\n    if libname not in _libcache:\n        _libcache[libname] = windll.LoadLibrary(libname)\n    func = getattr(_libcache[libname], funcname)\n    func.argtypes = argtypes\n    func.restype = restype\n    return func", "title": ""}
{"_id": "d15144", "text": "def contains_empty(features):\n    \"\"\"Check features data are not empty\n\n    :param features: The features data to check.\n    :type features: list of numpy arrays.\n\n    :return: True if one of the array is empty, False else.\n\n    \"\"\"\n    if not features:\n        return True\n    for feature in features:\n        if feature.shape[0] == 0:\n            return True\n    return False", "title": ""}
{"_id": "d15145", "text": "def _get_gid(name):\n    \"\"\"Returns a gid, given a group name.\"\"\"\n    if getgrnam is None or name is None:\n        return None\n    try:\n        result = getgrnam(name)\n    except KeyError:\n        result = None\n    if result is not None:\n        return result[2]\n    return None", "title": ""}
{"_id": "d15146", "text": "def terminate(self):\n    \"\"\"Override of PantsService.terminate() that cleans up when the Pailgun server is terminated.\"\"\"\n    # Tear down the Pailgun TCPServer.\n    if self.pailgun:\n      self.pailgun.server_close()\n\n    super(PailgunService, self).terminate()", "title": ""}
{"_id": "d15147", "text": "def retrieve_by_id(self, id_):\n        \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n        items_with_id = [item for item in self if item.id == int(id_)]\n        if len(items_with_id) == 1:\n            return items_with_id[0].retrieve()", "title": ""}
{"_id": "d15148", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d15149", "text": "def series_index(self, series):\n        \"\"\"\n        Return the integer index of *series* in this sequence.\n        \"\"\"\n        for idx, s in enumerate(self):\n            if series is s:\n                return idx\n        raise ValueError('series not in chart data object')", "title": ""}
{"_id": "d15150", "text": "def object_as_dict(obj):\n    \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n    Based on https://stackoverflow.com/a/37350445/1579058\n    \"\"\"\n    return {c.key: getattr(obj, c.key)\n            for c in inspect(obj).mapper.column_attrs}", "title": ""}
{"_id": "d15151", "text": "def _find_first_of(line, substrings):\n    \"\"\"Find earliest occurrence of one of substrings in line.\n\n    Returns pair of index and found substring, or (-1, None)\n    if no occurrences of any of substrings were found in line.\n    \"\"\"\n    starts = ((line.find(i), i) for i in substrings)\n    found = [(i, sub) for i, sub in starts if i != -1]\n    if found:\n        return min(found)\n    else:\n        return -1, None", "title": ""}
{"_id": "d15152", "text": "def retrieve_by_id(self, id_):\n        \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n        items_with_id = [item for item in self if item.id == int(id_)]\n        if len(items_with_id) == 1:\n            return items_with_id[0].retrieve()", "title": ""}
{"_id": "d15153", "text": "def get_substring_idxs(substr, string):\n    \"\"\"\n    Return a list of indexes of substr. If substr not found, list is\n    empty.\n\n    Arguments:\n        substr (str): Substring to match.\n        string (str): String to match in.\n\n    Returns:\n        list of int: Start indices of substr.\n    \"\"\"\n    return [match.start() for match in re.finditer(substr, string)]", "title": ""}
{"_id": "d15154", "text": "def _get_url(url):\n    \"\"\"Retrieve requested URL\"\"\"\n    try:\n        data = HTTP_SESSION.get(url, stream=True)\n        data.raise_for_status()\n    except requests.exceptions.RequestException as exc:\n        raise FetcherException(exc)\n\n    return data", "title": ""}
{"_id": "d15155", "text": "def get_last_id(self, cur, table='reaction'):\n        \"\"\"\n        Get the id of the last written row in table\n\n        Parameters\n        ----------\n        cur: database connection().cursor() object\n        table: str\n            'reaction', 'publication', 'publication_system', 'reaction_system'\n\n        Returns: id\n        \"\"\"\n        cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n                    .format(table))\n        result = cur.fetchone()\n        if result is not None:\n            id = result[0]\n        else:\n            id = 0\n        return id", "title": ""}
{"_id": "d15156", "text": "def unapostrophe(text):\n    \"\"\"Strip apostrophe and 's' from the end of a string.\"\"\"\n    text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)\n    return text", "title": ""}
{"_id": "d15157", "text": "def tail(self, n=10):\n        \"\"\"\n        Get an SArray that contains the last n elements in the SArray.\n\n        Parameters\n        ----------\n        n : int\n            The number of elements to fetch\n\n        Returns\n        -------\n        out : SArray\n            A new SArray which contains the last n rows of the current SArray.\n        \"\"\"\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.tail(n))", "title": ""}
{"_id": "d15158", "text": "def open_as_pillow(filename):\n    \"\"\" This way can delete file immediately \"\"\"\n    with __sys_open(filename, 'rb') as f:\n        data = BytesIO(f.read())\n        return Image.open(data)", "title": ""}
{"_id": "d15159", "text": "def get_methods(*objs):\n    \"\"\" Return the names of all callable attributes of an object\"\"\"\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    )", "title": ""}
{"_id": "d15160", "text": "async def i2c_write_request(self, command):\n        \"\"\"\n        This method performs an I2C write at a given I2C address,\n        :param command: {\"method\": \"i2c_write_request\", \"params\": [I2C_DEVICE_ADDRESS, [DATA_TO_WRITE]]}\n        :returns:No return message.\n        \"\"\"\n        device_address = int(command[0])\n        params = command[1]\n        params = [int(i) for i in params]\n        await self.core.i2c_write_request(device_address, params)", "title": ""}
{"_id": "d15161", "text": "def object_as_dict(obj):\n    \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n    Based on https://stackoverflow.com/a/37350445/1579058\n    \"\"\"\n    return {c.key: getattr(obj, c.key)\n            for c in inspect(obj).mapper.column_attrs}", "title": ""}
{"_id": "d15162", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d15163", "text": "def call_out(command):\n  \"\"\"\n  Run the given command (with shell=False) and return a tuple of\n  (int returncode, str output). Strip the output of enclosing whitespace.\n  \"\"\"\n  # start external command process\n  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n  # get outputs\n  out, _ = p.communicate()\n\n  return p.returncode, out.strip()", "title": ""}
{"_id": "d15164", "text": "def _check_conversion(key, valid_dict):\n    \"\"\"Check for existence of key in dict, return value or raise error\"\"\"\n    if key not in valid_dict and key not in valid_dict.values():\n        # Only show users the nice string values\n        keys = [v for v in valid_dict.keys() if isinstance(v, string_types)]\n        raise ValueError('value must be one of %s, not %s' % (keys, key))\n    return valid_dict[key] if key in valid_dict else key", "title": ""}
{"_id": "d15165", "text": "def GetPythonLibraryDirectoryPath():\n  \"\"\"Retrieves the Python library directory path.\"\"\"\n  path = sysconfig.get_python_lib(True)\n  _, _, path = path.rpartition(sysconfig.PREFIX)\n\n  if path.startswith(os.sep):\n    path = path[1:]\n\n  return path", "title": ""}
{"_id": "d15166", "text": "def ismatch(text, pattern):\n    \"\"\"Test whether text contains string or matches regex.\"\"\"\n\n    if hasattr(pattern, 'search'):\n        return pattern.search(text) is not None\n    else:\n        return pattern in text if Config.options.case_sensitive \\\n            else pattern.lower() in text.lower()", "title": ""}
{"_id": "d15167", "text": "def get_pid_list():\n    \"\"\"Returns a list of PIDs currently running on the system.\"\"\"\n    pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]\n    return pids", "title": ""}
{"_id": "d15168", "text": "def file_found(filename,force):\n    \"\"\"Check if a file exists\"\"\"\n    if os.path.exists(filename) and not force:\n        logger.info(\"Found %s; skipping...\"%filename)\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d15169", "text": "def static_get_type_attr(t, name):\n    \"\"\"\n    Get a type attribute statically, circumventing the descriptor protocol.\n    \"\"\"\n    for type_ in t.mro():\n        try:\n            return vars(type_)[name]\n        except KeyError:\n            pass\n    raise AttributeError(name)", "title": ""}
{"_id": "d15170", "text": "def starts_with_prefix_in_list(text, prefixes):\n    \"\"\"\n    Return True if the given string starts with one of the prefixes in the given list, otherwise\n    return False.\n\n    Arguments:\n        text (str): Text to check for prefixes.\n        prefixes (list): List of prefixes to check for.\n\n    Returns:\n        bool: True if the given text starts with any of the given prefixes, otherwise False.\n    \"\"\"\n    for prefix in prefixes:\n        if text.startswith(prefix):\n            return True\n    return False", "title": ""}
{"_id": "d15171", "text": "def GetPythonLibraryDirectoryPath():\n  \"\"\"Retrieves the Python library directory path.\"\"\"\n  path = sysconfig.get_python_lib(True)\n  _, _, path = path.rpartition(sysconfig.PREFIX)\n\n  if path.startswith(os.sep):\n    path = path[1:]\n\n  return path", "title": ""}
{"_id": "d15172", "text": "def from_string(cls, string):\n        \"\"\"\n        Simply logs a warning if the desired enum value is not found.\n\n        :param string:\n        :return:\n        \"\"\"\n\n        # find enum value\n        for attr in dir(cls):\n            value = getattr(cls, attr)\n            if value == string:\n                return value\n\n        # if not found, log warning and return the value passed in\n        logger.warning(\"{} is not a valid enum value for {}.\".format(string, cls.__name__))\n        return string", "title": ""}
{"_id": "d15173", "text": "def rm_empty_indices(*args):\n    \"\"\"\n    Remove unwanted list indices. First argument is the list\n    of indices to remove. Other elements are the lists\n    to trim.\n    \"\"\"\n    rm_inds = args[0]\n\n    if not rm_inds:\n        return args[1:]\n\n    keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n    return [[a[i] for i in keep_inds] for a in args[1:]]", "title": ""}
{"_id": "d15174", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d15175", "text": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "title": ""}
{"_id": "d15176", "text": "def get_buffer(self, data_np, header, format, output=None):\n        \"\"\"Get image as a buffer in (format).\n        Format should be 'jpeg', 'png', etc.\n        \"\"\"\n        if not have_pil:\n            raise Exception(\"Install PIL to use this method\")\n        image = PILimage.fromarray(data_np)\n        buf = output\n        if buf is None:\n            buf = BytesIO()\n        image.save(buf, format)\n        return buf", "title": ""}
{"_id": "d15177", "text": "def getScreenDims(self):\n        \"\"\"returns a tuple that contains (screen_width,screen_height)\n        \"\"\"\n        width = ale_lib.getScreenWidth(self.obj)\n        height = ale_lib.getScreenHeight(self.obj)\n        return (width,height)", "title": ""}
{"_id": "d15178", "text": "def is_same_shape(self, other_im, check_channels=False):\n        \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n        Parameters\n        ----------\n        other_im : :obj:`Image`\n            image to compare\n        check_channels : bool\n            whether or not to check equality of the channels\n\n        Returns\n        -------\n        bool\n            True if the images are the same shape, False otherwise\n        \"\"\"\n        if self.height == other_im.height and self.width == other_im.width:\n            if check_channels and self.channels != other_im.channels:\n                return False\n            return True\n        return False", "title": ""}
{"_id": "d15179", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d15180", "text": "def region_from_segment(image, segment):\n    \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n    x, y, w, h = segment\n    return image[y:y + h, x:x + w]", "title": ""}
{"_id": "d15181", "text": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "title": ""}
{"_id": "d15182", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d15183", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d15184", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d15185", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d15186", "text": "def setup_path():\n    \"\"\"Sets up the python include paths to include src\"\"\"\n    import os.path; import sys\n\n    if sys.argv[0]:\n        top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n        sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n        pass\n    return", "title": ""}
{"_id": "d15187", "text": "def get_month_start(day=None):\n    \"\"\"Returns the first day of the given month.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(day=1)", "title": ""}
{"_id": "d15188", "text": "def end_block(self):\n        \"\"\"Ends an indentation block, leaving an empty line afterwards\"\"\"\n        self.current_indent -= 1\n\n        # If we did not add a new line automatically yet, now it's the time!\n        if not self.auto_added_line:\n            self.writeln()\n            self.auto_added_line = True", "title": ""}
{"_id": "d15189", "text": "def find_nearest_index(arr, value):\n    \"\"\"For a given value, the function finds the nearest value\n    in the array and returns its index.\"\"\"\n    arr = np.array(arr)\n    index = (abs(arr-value)).argmin()\n    return index", "title": ""}
{"_id": "d15190", "text": "def end_block(self):\n        \"\"\"Ends an indentation block, leaving an empty line afterwards\"\"\"\n        self.current_indent -= 1\n\n        # If we did not add a new line automatically yet, now it's the time!\n        if not self.auto_added_line:\n            self.writeln()\n            self.auto_added_line = True", "title": ""}
{"_id": "d15191", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d15192", "text": "def _remove_from_index(index, obj):\n    \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n    try:\n        index.value_map[indexed_value(index, obj)].remove(obj.id)\n    except KeyError:\n        pass", "title": ""}
{"_id": "d15193", "text": "def hstrlen(self, name, key):\n        \"\"\"\n        Return the number of bytes stored in the value of ``key``\n        within hash ``name``\n        \"\"\"\n        with self.pipe as pipe:\n            return pipe.hstrlen(self.redis_key(name), key)", "title": ""}
{"_id": "d15194", "text": "def get_index_nested(x, i):\n    \"\"\"\n    Description:\n        Returns the first index of the array (vector) x containing the value i.\n    Parameters:\n        x: one-dimensional array\n        i: search value\n    \"\"\"\n    for ind in range(len(x)):\n        if i == x[ind]:\n            return ind\n    return -1", "title": ""}
{"_id": "d15195", "text": "def _get_column_by_db_name(cls, name):\n        \"\"\"\n        Returns the column, mapped by db_field name\n        \"\"\"\n        return cls._columns.get(cls._db_map.get(name, name))", "title": ""}
{"_id": "d15196", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d15197", "text": "def get_previous_month(self):\n        \"\"\"Returns date range for the previous full month.\"\"\"\n        end = utils.get_month_start() - relativedelta(days=1)\n        end = utils.to_datetime(end)\n        start = utils.get_month_start(end)\n        return start, end", "title": ""}
{"_id": "d15198", "text": "def listified_tokenizer(source):\n    \"\"\"Tokenizes *source* and returns the tokens as a list of lists.\"\"\"\n    io_obj = io.StringIO(source)\n    return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]", "title": ""}
{"_id": "d15199", "text": "def ex(self, cmd):\n        \"\"\"Execute a normal python statement in user namespace.\"\"\"\n        with self.builtin_trap:\n            exec cmd in self.user_global_ns, self.user_ns", "title": ""}
{"_id": "d15200", "text": "def unique_element(ll):\n    \"\"\" returns unique elements from a list preserving the original order \"\"\"\n    seen = {}\n    result = []\n    for item in ll:\n        if item in seen:\n            continue\n        seen[item] = 1\n        result.append(item)\n    return result", "title": ""}
{"_id": "d15201", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d15202", "text": "def _get_device_id(self, bus):\n        \"\"\"\n        Find the device id\n        \"\"\"\n        _dbus = bus.get(SERVICE_BUS, PATH)\n        devices = _dbus.devices()\n\n        if self.device is None and self.device_id is None and len(devices) == 1:\n            return devices[0]\n\n        for id in devices:\n            self._dev = bus.get(SERVICE_BUS, DEVICE_PATH + \"/%s\" % id)\n            if self.device == self._dev.name:\n                return id\n\n        return None", "title": ""}
{"_id": "d15203", "text": "def add_parent(self, parent):\n        \"\"\"\n        Adds self as child of parent, then adds parent.\n        \"\"\"\n        parent.add_child(self)\n        self.parent = parent\n        return parent", "title": ""}
{"_id": "d15204", "text": "def print(*a):\n    \"\"\" print just one that returns what you give it instead of None \"\"\"\n    try:\n        _print(*a)\n        return a[0] if len(a) == 1 else a\n    except:\n        _print(*a)", "title": ""}
{"_id": "d15205", "text": "def add_noise(Y, sigma):\n    \"\"\"Adds noise to Y\"\"\"\n    return Y + np.random.normal(0, sigma, Y.shape)", "title": ""}
{"_id": "d15206", "text": "def plot_target(target, ax):\n    \"\"\"Ajoute la target au plot\"\"\"\n    ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)", "title": ""}
{"_id": "d15207", "text": "def props(cls):\n    \"\"\"\n    Class method that returns all defined arguments within the class.\n    \n    Returns:\n      A dictionary containing all action defined arguments (if any).\n    \"\"\"\n    return {k:v for (k, v) in inspect.getmembers(cls) if type(v) is Argument}", "title": ""}
{"_id": "d15208", "text": "def are_in_interval(s, l, r, border = 'included'):\n        \"\"\"\n        Checks whether all number in the sequence s lie inside the interval formed by\n        l and r.\n        \"\"\"\n        return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s])", "title": ""}
{"_id": "d15209", "text": "def get_public_members(obj):\n    \"\"\"\n    Retrieves a list of member-like objects (members or properties) that are\n    publically exposed.\n\n    :param obj: The object to probe.\n    :return:    A list of strings.\n    \"\"\"\n    return {attr: getattr(obj, attr) for attr in dir(obj)\n            if not attr.startswith(\"_\")\n            and not hasattr(getattr(obj, attr), '__call__')}", "title": ""}
{"_id": "d15210", "text": "def format_time(time):\n    \"\"\" Formats the given time into HH:MM:SS \"\"\"\n    h, r = divmod(time / 1000, 3600)\n    m, s = divmod(r, 60)\n\n    return \"%02d:%02d:%02d\" % (h, m, s)", "title": ""}
{"_id": "d15211", "text": "def extract_vars_above(*names):\n    \"\"\"Extract a set of variables by name from another frame.\n\n    Similar to extractVars(), but with a specified depth of 1, so that names\n    are exctracted exactly from above the caller.\n\n    This is simply a convenience function so that the very common case (for us)\n    of skipping exactly 1 frame doesn't have to construct a special dict for\n    keyword passing.\"\"\"\n\n    callerNS = sys._getframe(2).f_locals\n    return dict((k,callerNS[k]) for k in names)", "title": ""}
{"_id": "d15212", "text": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "title": ""}
{"_id": "d15213", "text": "def from_dict(cls, d):\n        \"\"\"Create an instance from a dictionary.\"\"\"\n        return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})", "title": ""}
{"_id": "d15214", "text": "def go_to_parent_directory(self):\n        \"\"\"Go to parent directory\"\"\"\n        self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))", "title": ""}
{"_id": "d15215", "text": "def spline_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):\n    \"\"\"A datetime-version that takes datetime object list as x_axis\n    \"\"\"\n    numeric_datetime_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_axis\n    ]\n\n    numeric_datetime_new_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_new_axis\n    ]\n\n    return spline_interpolate(\n        numeric_datetime_axis, y_axis, numeric_datetime_new_axis)", "title": ""}
{"_id": "d15216", "text": "def gettext(self, string, domain=None, **variables):\n        \"\"\"Translate a string with the current locale.\"\"\"\n        t = self.get_translations(domain)\n        return t.ugettext(string) % variables", "title": ""}
{"_id": "d15217", "text": "def MatrixInverse(a, adj):\n    \"\"\"\n    Matrix inversion op.\n    \"\"\"\n    return np.linalg.inv(a if not adj else _adjoint(a)),", "title": ""}
{"_id": "d15218", "text": "def _get_local_ip():\n        \"\"\"\n        Get the local ip of this device\n\n        :return: Ip of this computer\n        :rtype: str\n        \"\"\"\n        return set([x[4][0] for x in socket.getaddrinfo(\n            socket.gethostname(),\n            80,\n            socket.AF_INET\n        )]).pop()", "title": ""}
{"_id": "d15219", "text": "def __call__(self, args):\n        \"\"\"Execute the user function.\"\"\"\n        window, ij = args\n        return self.user_func(srcs, window, ij, global_args), window", "title": ""}
{"_id": "d15220", "text": "def l2_norm(params):\n    \"\"\"Computes l2 norm of params by flattening them into a vector.\"\"\"\n    flattened, _ = flatten(params)\n    return np.dot(flattened, flattened)", "title": ""}
{"_id": "d15221", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d15222", "text": "def connect(self, A, B, distance=1):\n        \"\"\"Add a link from A and B of given distance, and also add the inverse\n        link if the graph is undirected.\"\"\"\n        self.connect1(A, B, distance)\n        if not self.directed: self.connect1(B, A, distance)", "title": ""}
{"_id": "d15223", "text": "def url_read_text(url, verbose=True):\n    r\"\"\"\n    Directly reads text data from url\n    \"\"\"\n    data = url_read(url, verbose)\n    text = data.decode('utf8')\n    return text", "title": ""}
{"_id": "d15224", "text": "def draw_graph(G: nx.DiGraph, filename: str):\n    \"\"\" Draw a networkx graph with Pygraphviz. \"\"\"\n    A = to_agraph(G)\n    A.graph_attr[\"rankdir\"] = \"LR\"\n    A.draw(filename, prog=\"dot\")", "title": ""}
{"_id": "d15225", "text": "def check_int(integer):\n    \"\"\"\n    Check if number is integer or not.\n\n    :param integer: Number as str\n    :return: Boolean\n    \"\"\"\n    if not isinstance(integer, str):\n        return False\n    if integer[0] in ('-', '+'):\n        return integer[1:].isdigit()\n    return integer.isdigit()", "title": ""}
{"_id": "d15226", "text": "def search_script_directory(self, path):\n        \"\"\"\n        Recursively loop through a directory to find all python\n        script files. When one is found, it is analyzed for import statements\n        :param path: string\n        :return: generator\n        \"\"\"\n        for subdir, dirs, files in os.walk(path):\n            for file_name in files:\n                if file_name.endswith(\".py\"):\n                    self.search_script_file(subdir, file_name)", "title": ""}
{"_id": "d15227", "text": "def on_windows ():\n    \"\"\" Returns true if running on windows, whether in cygwin or not.\n    \"\"\"\n    if bjam.variable(\"NT\"):\n        return True\n\n    elif bjam.variable(\"UNIX\"):\n\n        uname = bjam.variable(\"JAMUNAME\")\n        if uname and uname[0].startswith(\"CYGWIN\"):\n            return True\n\n    return False", "title": ""}
{"_id": "d15228", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d15229", "text": "def parse_timestamp(timestamp):\n    \"\"\"Parse ISO8601 timestamps given by github API.\"\"\"\n    dt = dateutil.parser.parse(timestamp)\n    return dt.astimezone(dateutil.tz.tzutc())", "title": ""}
{"_id": "d15230", "text": "def end_table_header(self):\n        r\"\"\"End the table header which will appear on every page.\"\"\"\n\n        if self.header:\n            msg = \"Table already has a header\"\n            raise TableError(msg)\n\n        self.header = True\n\n        self.append(Command(r'endhead'))", "title": ""}
{"_id": "d15231", "text": "def __iter__(self):\n        \"\"\"\n        Iterate through tree, leaves first\n\n        following http://stackoverflow.com/questions/6914803/python-iterator-through-tree-with-list-of-children\n        \"\"\"\n        for node in chain(*imap(iter, self.children)):\n            yield node\n        yield self", "title": ""}
{"_id": "d15232", "text": "def is_symbol(string):\n    \"\"\"\n    Return true if the string is a mathematical symbol.\n    \"\"\"\n    return (\n        is_int(string) or is_float(string) or\n        is_constant(string) or is_unary(string) or\n        is_binary(string) or\n        (string == '(') or (string == ')')\n    )", "title": ""}
{"_id": "d15233", "text": "def tab(self, output):\n        \"\"\"Output data in excel-compatible tab-delimited format\"\"\"\n        import csv\n        csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab)\n        csvwriter.writerows(output)", "title": ""}
{"_id": "d15234", "text": "def _skip_frame(self):\n        \"\"\"Skip the next time frame\"\"\"\n        for line in self._f:\n            if line == 'ITEM: ATOMS\\n':\n                break\n        for i in range(self.num_atoms):\n            next(self._f)", "title": ""}
{"_id": "d15235", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d15236", "text": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "title": ""}
{"_id": "d15237", "text": "def _clean_up_name(self, name):\n        \"\"\"\n        Cleans up the name according to the rules specified in this exact\n        function. Uses self.naughty, a list of naughty characters.\n        \"\"\"\n        for n in self.naughty: name = name.replace(n, '_')\n        return name", "title": ""}
{"_id": "d15238", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d15239", "text": "def round_to_n(x, n):\n    \"\"\"\n    Round to sig figs\n    \"\"\"\n    return round(x, -int(np.floor(np.log10(x))) + (n - 1))", "title": ""}
{"_id": "d15240", "text": "def next (self):    # File-like object.\n\n        \"\"\"This is to support iterators over a file-like object.\n        \"\"\"\n\n        result = self.readline()\n        if result == self._empty_buffer:\n            raise StopIteration\n        return result", "title": ""}
{"_id": "d15241", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d15242", "text": "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)", "title": ""}
{"_id": "d15243", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d15244", "text": "def assert_single_element(iterable):\n  \"\"\"Get the single element of `iterable`, or raise an error.\n\n  :raise: :class:`StopIteration` if there is no element.\n  :raise: :class:`ValueError` if there is more than one element.\n  \"\"\"\n  it = iter(iterable)\n  first_item = next(it)\n\n  try:\n    next(it)\n  except StopIteration:\n    return first_item\n\n  raise ValueError(\"iterable {!r} has more than one element.\".format(iterable))", "title": ""}
{"_id": "d15245", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d15246", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d15247", "text": "def __get_xml_text(root):\n    \"\"\" Return the text for the given root node (xml.dom.minidom). \"\"\"\n    txt = \"\"\n    for e in root.childNodes:\n        if (e.nodeType == e.TEXT_NODE):\n            txt += e.data\n    return txt", "title": ""}
{"_id": "d15248", "text": "def iterparse(source, events=('end',), remove_comments=True, **kw):\n    \"\"\"Thin wrapper around ElementTree.iterparse\"\"\"\n    return ElementTree.iterparse(source, events, SourceLineParser(), **kw)", "title": ""}
{"_id": "d15249", "text": "def get_encoding(binary):\n    \"\"\"Return the encoding type.\"\"\"\n\n    try:\n        from chardet import detect\n    except ImportError:\n        LOGGER.error(\"Please install the 'chardet' module\")\n        sys.exit(1)\n\n    encoding = detect(binary).get('encoding')\n\n    return 'iso-8859-1' if encoding == 'CP949' else encoding", "title": ""}
{"_id": "d15250", "text": "def iter_with_last(iterable):\n    \"\"\"\n    :return: generator of tuples (isLastFlag, item)\n    \"\"\"\n    # Ensure it's an iterator and get the first field\n    iterable = iter(iterable)\n    prev = next(iterable)\n    for item in iterable:\n        # Lag by one item so I know I'm not at the end\n        yield False, prev\n        prev = item\n    # Last item\n    yield True, prev", "title": ""}
{"_id": "d15251", "text": "def conv_dict(self):\n        \"\"\"dictionary of conversion\"\"\"\n        return dict(integer=self.integer, real=self.real, no_type=self.no_type)", "title": ""}
{"_id": "d15252", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d15253", "text": "def help_for_command(command):\n    \"\"\"Get the help text (signature + docstring) for a command (function).\"\"\"\n    help_text = pydoc.text.document(command)\n    # remove backspaces\n    return re.subn('.\\\\x08', '', help_text)[0]", "title": ""}
{"_id": "d15254", "text": "def render_template(env, filename, values=None):\n    \"\"\"\n    Render a jinja template\n    \"\"\"\n    if not values:\n        values = {}\n    tmpl = env.get_template(filename)\n    return tmpl.render(values)", "title": ""}
{"_id": "d15255", "text": "def get_absolute_path(*args):\n    \"\"\"Transform relative pathnames into absolute pathnames.\"\"\"\n    directory = os.path.dirname(os.path.abspath(__file__))\n    return os.path.join(directory, *args)", "title": ""}
{"_id": "d15256", "text": "def render_template(template_name, **context):\n    \"\"\"Render a template into a response.\"\"\"\n    tmpl = jinja_env.get_template(template_name)\n    context[\"url_for\"] = url_for\n    return Response(tmpl.render(context), mimetype=\"text/html\")", "title": ""}
{"_id": "d15257", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d15258", "text": "async def join(self, ctx, *, channel: discord.VoiceChannel):\n        \"\"\"Joins a voice channel\"\"\"\n\n        if ctx.voice_client is not None:\n            return await ctx.voice_client.move_to(channel)\n\n        await channel.connect()", "title": ""}
{"_id": "d15259", "text": "def gaussian_variogram_model(m, d):\n    \"\"\"Gaussian model, m is [psill, range, nugget]\"\"\"\n    psill = float(m[0])\n    range_ = float(m[1])\n    nugget = float(m[2])\n    return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget", "title": ""}
{"_id": "d15260", "text": "def _grammatical_join_filter(l, arg=None):\n    \"\"\"\n    :param l: List of strings to join\n    :param arg: A pipe-separated list of final_join (\" and \") and\n    initial_join (\", \") strings. For example\n    :return: A string that grammatically concatenates the items in the list.\n    \"\"\"\n    if not arg:\n        arg = \" and |, \"\n    try:\n        final_join, initial_joins = arg.split(\"|\")\n    except ValueError:\n        final_join = arg\n        initial_joins = \", \"\n    return grammatical_join(l, initial_joins, final_join)", "title": ""}
{"_id": "d15261", "text": "def fast_exit(code):\n    \"\"\"Exit without garbage collection, this speeds up exit by about 10ms for\n    things like bash completion.\n    \"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(code)", "title": ""}
{"_id": "d15262", "text": "def flatten_dict_join_keys(dct, join_symbol=\" \"):\n    \"\"\" Flatten dict with defined key join symbol.\n\n    :param dct: dict to flatten\n    :param join_symbol: default value is \" \"\n    :return:\n    \"\"\"\n    return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )", "title": ""}
{"_id": "d15263", "text": "def get_unique_indices(df, axis=1):\n    \"\"\"\n\n    :param df:\n    :param axis:\n    :return:\n    \"\"\"\n    return dict(zip(df.columns.names, dif.columns.levels))", "title": ""}
{"_id": "d15264", "text": "def flatten_dict_join_keys(dct, join_symbol=\" \"):\n    \"\"\" Flatten dict with defined key join symbol.\n\n    :param dct: dict to flatten\n    :param join_symbol: default value is \" \"\n    :return:\n    \"\"\"\n    return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )", "title": ""}
{"_id": "d15265", "text": "def lcumsum (inlist):\n    \"\"\"\nReturns a list consisting of the cumulative sum of the items in the\npassed list.\n\nUsage:   lcumsum(inlist)\n\"\"\"\n    newlist = copy.deepcopy(inlist)\n    for i in range(1,len(newlist)):\n        newlist[i] = newlist[i] + newlist[i-1]\n    return newlist", "title": ""}
{"_id": "d15266", "text": "def get_join_cols(by_entry):\n  \"\"\" helper function used for joins\n  builds left and right join list for join function\n  \"\"\"\n  left_cols = []\n  right_cols = []\n  for col in by_entry:\n    if isinstance(col, str):\n      left_cols.append(col)\n      right_cols.append(col)\n    else:\n      left_cols.append(col[0])\n      right_cols.append(col[1])\n  return left_cols, right_cols", "title": ""}
{"_id": "d15267", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d15268", "text": "def _default(self, obj):\n        \"\"\" return a serialized version of obj or raise a TypeError\n\n        :param obj:\n        :return: Serialized version of obj\n        \"\"\"\n        return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj)", "title": ""}
{"_id": "d15269", "text": "def unique(iterable):\n    \"\"\" Returns a list copy in which each item occurs only once (in-order).\n    \"\"\"\n    seen = set()\n    return [x for x in iterable if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d15270", "text": "def json_dumps(self, obj):\n        \"\"\"Serializer for consistency\"\"\"\n        return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))", "title": ""}
{"_id": "d15271", "text": "def join(mapping, bind, values):\n    \"\"\" Merge all the strings. Put space between them. \"\"\"\n    return [' '.join([six.text_type(v) for v in values if v is not None])]", "title": ""}
{"_id": "d15272", "text": "def json_dumps(self, obj):\n        \"\"\"Serializer for consistency\"\"\"\n        return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))", "title": ""}
{"_id": "d15273", "text": "def kill(self):\n        \"\"\"Kill the browser.\n\n        This is useful when the browser is stuck.\n        \"\"\"\n        if self.process:\n            self.process.kill()\n            self.process.wait()", "title": ""}
{"_id": "d15274", "text": "def to_json(obj):\n    \"\"\"Return a json string representing the python object obj.\"\"\"\n    i = StringIO.StringIO()\n    w = Writer(i, encoding='UTF-8')\n    w.write_value(obj)\n    return i.getvalue()", "title": ""}
{"_id": "d15275", "text": "def retrieve_by_id(self, id_):\n        \"\"\"Return a JSSObject for the element with ID id_\"\"\"\n        items_with_id = [item for item in self if item.id == int(id_)]\n        if len(items_with_id) == 1:\n            return items_with_id[0].retrieve()", "title": ""}
{"_id": "d15276", "text": "def parse_json(filename):\n    \"\"\" Parse a JSON file\n        First remove comments and then use the json module package\n        Comments look like :\n            // ...\n        or\n            /*\n            ...\n            */\n    \"\"\"\n    # Regular expression for comments\n    comment_re = re.compile(\n        '(^)?[^\\S\\n]*/(?:\\*(.*?)\\*/[^\\S\\n]*|/[^\\n]*)($)?',\n        re.DOTALL | re.MULTILINE\n    )\n\n    with open(filename) as f:\n        content = ''.join(f.readlines())\n\n        ## Looking for comments\n        match = comment_re.search(content)\n        while match:\n            # single line comment\n            content = content[:match.start()] + content[match.end():]\n            match = comment_re.search(content)\n\n        # Return json file\n        return json.loads(content)", "title": ""}
{"_id": "d15277", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d15278", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d15279", "text": "def next (self):    # File-like object.\n\n        \"\"\"This is to support iterators over a file-like object.\n        \"\"\"\n\n        result = self.readline()\n        if result == self._empty_buffer:\n            raise StopIteration\n        return result", "title": ""}
{"_id": "d15280", "text": "def _time_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, datetime.time):\n        value = value.isoformat()\n    return value", "title": ""}
{"_id": "d15281", "text": "def setup():\n    \"\"\"Setup pins\"\"\"\n    print(\"Simple drive\")\n    board.set_pin_mode(L_CTRL_1, Constants.OUTPUT)\n    board.set_pin_mode(L_CTRL_2, Constants.OUTPUT)\n    board.set_pin_mode(PWM_L, Constants.PWM)\n    board.set_pin_mode(R_CTRL_1, Constants.OUTPUT)\n    board.set_pin_mode(R_CTRL_2, Constants.OUTPUT)\n    board.set_pin_mode(PWM_R, Constants.PWM)", "title": ""}
{"_id": "d15282", "text": "def task_property_present_predicate(service, task, prop):\n    \"\"\" True if the json_element passed is present for the task specified.\n    \"\"\"\n    try:\n        response = get_service_task(service, task)\n    except Exception as e:\n        pass\n\n    return (response is not None) and (prop in response)", "title": ""}
{"_id": "d15283", "text": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n        \"\"\"Set foreground- and background colors and intensity.\"\"\"\n        raise NotImplementedError", "title": ""}
{"_id": "d15284", "text": "def validate(payload, schema):\n    \"\"\"Validate `payload` against `schema`, returning an error list.\n\n    jsonschema provides lots of information in it's errors, but it can be a bit\n    of work to extract all the information.\n    \"\"\"\n    v = jsonschema.Draft4Validator(\n        schema, format_checker=jsonschema.FormatChecker())\n    error_list = []\n    for error in v.iter_errors(payload):\n        message = error.message\n        location = '/' + '/'.join([str(c) for c in error.absolute_path])\n        error_list.append(message + ' at ' + location)\n    return error_list", "title": ""}
{"_id": "d15285", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d15286", "text": "def go_to_line(self, line):\n        \"\"\"\n        Moves the text cursor to given line.\n\n        :param line: Line to go to.\n        :type line: int\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        cursor = self.textCursor()\n        cursor.setPosition(self.document().findBlockByNumber(line - 1).position())\n        self.setTextCursor(cursor)\n        return True", "title": ""}
{"_id": "d15287", "text": "def _write_color_ansi (fp, text, color):\n    \"\"\"Colorize text with given color.\"\"\"\n    fp.write(esc_ansicolor(color))\n    fp.write(text)\n    fp.write(AnsiReset)", "title": ""}
{"_id": "d15288", "text": "def drop_trailing_zeros(num):\n    \"\"\"\n    Drops the trailing zeros in a float that is printed.\n    \"\"\"\n    txt = '%f' %(num)\n    txt = txt.rstrip('0')\n    if txt.endswith('.'):\n        txt = txt[:-1]\n    return txt", "title": ""}
{"_id": "d15289", "text": "def weekly(date=datetime.date.today()):\n    \"\"\"\n    Weeks start are fixes at Monday for now.\n    \"\"\"\n    return date - datetime.timedelta(days=date.weekday())", "title": ""}
{"_id": "d15290", "text": "def kill_process_children(pid):\n    \"\"\"Find and kill child processes of a process.\n\n    :param pid: PID of parent process (process ID)\n    :return: Nothing\n    \"\"\"\n    if sys.platform == \"darwin\":\n        kill_process_children_osx(pid)\n    elif sys.platform == \"linux\":\n        kill_process_children_unix(pid)\n    else:\n        pass", "title": ""}
{"_id": "d15291", "text": "def setLib(self, lib):\n        \"\"\" Copy the lib items into our font. \"\"\"\n        for name, item in lib.items():\n            self.font.lib[name] = item", "title": ""}
{"_id": "d15292", "text": "def kill_process(process):\n    \"\"\"Kill the process group associated with the given process. (posix)\"\"\"\n    logger = logging.getLogger('xenon')\n    logger.info('Terminating Xenon-GRPC server.')\n    os.kill(process.pid, signal.SIGINT)\n    process.wait()", "title": ""}
{"_id": "d15293", "text": "def __init__(self, filename, mode, encoding=None):\n        \"\"\"Use the specified filename for streamed logging.\"\"\"\n        FileHandler.__init__(self, filename, mode, encoding)\n        self.mode = mode\n        self.encoding = encoding", "title": ""}
{"_id": "d15294", "text": "def kill_process(process):\n    \"\"\"Kill the process group associated with the given process. (posix)\"\"\"\n    logger = logging.getLogger('xenon')\n    logger.info('Terminating Xenon-GRPC server.')\n    os.kill(process.pid, signal.SIGINT)\n    process.wait()", "title": ""}
{"_id": "d15295", "text": "def install_postgres(user=None, dbname=None, password=None):\n    \"\"\"Install Postgres on remote\"\"\"\n    execute(pydiploy.django.install_postgres_server,\n            user=user, dbname=dbname, password=password)", "title": ""}
{"_id": "d15296", "text": "def l2_norm(arr):\n    \"\"\"\n    The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n    dot product of the vector.\n    \"\"\"\n    arr = np.asarray(arr)\n    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "title": ""}
{"_id": "d15297", "text": "def register_plugin(self):\n        \"\"\"Register plugin in Spyder's main window\"\"\"\n        self.main.restore_scrollbar_position.connect(\n                                               self.restore_scrollbar_position)\n        self.main.add_dockwidget(self)", "title": ""}
{"_id": "d15298", "text": "def l2_norm(arr):\n    \"\"\"\n    The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n    dot product of the vector.\n    \"\"\"\n    arr = np.asarray(arr)\n    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "title": ""}
{"_id": "d15299", "text": "def append_text(self, txt):\n        \"\"\" adds a line of text to a file \"\"\"\n        with open(self.fullname, \"a\") as myfile:\n            myfile.write(txt)", "title": ""}
{"_id": "d15300", "text": "def download_file_from_bucket(self, bucket, file_path, key):\n        \"\"\" Download file from S3 Bucket \"\"\"\n        with open(file_path, 'wb') as data:\n            self.__s3.download_fileobj(bucket, key, data)\n            return file_path", "title": ""}
{"_id": "d15301", "text": "def _pad(self, text):\n        \"\"\"Pad the 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", "title": ""}
{"_id": "d15302", "text": "def make_lambda(call):\n    \"\"\"Wrap an AST Call node to lambda expression node.\n    call: ast.Call node\n    \"\"\"\n    empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n    return ast.Lambda(args=empty_args, body=call)", "title": ""}
{"_id": "d15303", "text": "def robust_int(v):\n    \"\"\"Parse an int robustly, ignoring commas and other cruft. \"\"\"\n\n    if isinstance(v, int):\n        return v\n\n    if isinstance(v, float):\n        return int(v)\n\n    v = str(v).replace(',', '')\n\n    if not v:\n        return None\n\n    return int(v)", "title": ""}
{"_id": "d15304", "text": "def get_tail(self):\n        \"\"\"Gets tail\n\n        :return: Tail of linked list\n        \"\"\"\n        node = self.head\n        last_node = self.head\n\n        while node is not None:\n            last_node = node\n            node = node.next_node\n\n        return last_node", "title": ""}
{"_id": "d15305", "text": "def AddAccuracy(model, softmax, label):\n    \"\"\"Adds an accuracy op to the model\"\"\"\n    accuracy = brew.accuracy(model, [softmax, label], \"accuracy\")\n    return accuracy", "title": ""}
{"_id": "d15306", "text": "def end_index(self):\n        \"\"\"Return the 1-based index of the last item on this page.\"\"\"\n        paginator = self.paginator\n        # Special case for the last page because there can be orphans.\n        if self.number == paginator.num_pages:\n            return paginator.count\n        return (self.number - 1) * paginator.per_page + paginator.first_page", "title": ""}
{"_id": "d15307", "text": "def append(self, item):\n        \"\"\" append item and print it to stdout \"\"\"\n        print(item)\n        super(MyList, self).append(item)", "title": ""}
{"_id": "d15308", "text": "def xyz2lonlat(x, y, z):\n    \"\"\"Convert cartesian to lon lat.\"\"\"\n    lon = xu.rad2deg(xu.arctan2(y, x))\n    lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2)))\n    return lon, lat", "title": ""}
{"_id": "d15309", "text": "def filter_contour(imageFile, opFile):\n    \"\"\" convert an image by applying a contour \"\"\"\n    im = Image.open(imageFile)\n    im1 = im.filter(ImageFilter.CONTOUR)\n    im1.save(opFile)", "title": ""}
{"_id": "d15310", "text": "def make_coord_dict(coord):\n    \"\"\"helper function to make a dict from a coordinate for logging\"\"\"\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    )", "title": ""}
{"_id": "d15311", "text": "def dictapply(d, fn):\n    \"\"\"\n    apply a function to all non-dict values in a dictionary\n    \"\"\"\n    for k, v in d.items():\n        if isinstance(v, dict):\n            v = dictapply(v, fn)\n        else:\n            d[k] = fn(v)\n    return d", "title": ""}
{"_id": "d15312", "text": "def tree_predict(x, root, proba=False, regression=False):\n    \"\"\"Predicts a probabilities/value/label for the sample x.\n    \"\"\"\n\n    if isinstance(root, Leaf):\n        if proba:\n            return root.probabilities\n        elif regression:\n            return root.mean\n        else:\n            return root.most_frequent\n\n    if root.question.match(x):\n        return tree_predict(x, root.true_branch, proba=proba, regression=regression)\n    else:\n        return tree_predict(x, root.false_branch, proba=proba, regression=regression)", "title": ""}
{"_id": "d15313", "text": "def load_files(files):\n    \"\"\"Load and execute a python file.\"\"\"\n\n    for py_file in files:\n        LOG.debug(\"exec %s\", py_file)\n        execfile(py_file, globals(), locals())", "title": ""}
{"_id": "d15314", "text": "def minimise_xyz(xyz):\n    \"\"\"Minimise an (x, y, z) coordinate.\"\"\"\n    x, y, z = xyz\n    m = max(min(x, y), min(max(x, y), z))\n    return (x-m, y-m, z-m)", "title": ""}
{"_id": "d15315", "text": "def download_file(save_path, file_url):\n    \"\"\" Download file from http url link \"\"\"\n\n    r = requests.get(file_url)  # create HTTP response object\n\n    with open(save_path, 'wb') as f:\n        f.write(r.content)\n\n    return save_path", "title": ""}
{"_id": "d15316", "text": "def stop(pid):\n    \"\"\"Shut down a specific process.\n\n    Args:\n      pid: the pid of the process to shutdown.\n    \"\"\"\n    if psutil.pid_exists(pid):\n      try:\n        p = psutil.Process(pid)\n        p.kill()\n      except Exception:\n        pass", "title": ""}
{"_id": "d15317", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d15318", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d15319", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d15320", "text": "def get_by(self, name):\n    \"\"\"get element by name\"\"\"\n    return next((item for item in self if item.name == name), None)", "title": ""}
{"_id": "d15321", "text": "def should_be_hidden_as_cause(exc):\n    \"\"\" Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error \"\"\"\n    # reduced traceback in case of HasWrongType (instance_of checks)\n    from valid8.validation_lib.types import HasWrongType, IsWrongType\n    return isinstance(exc, (HasWrongType, IsWrongType))", "title": ""}
{"_id": "d15322", "text": "def _calculate_distance(latlon1, latlon2):\n    \"\"\"Calculates the distance between two points on earth.\n    \"\"\"\n    lat1, lon1 = latlon1\n    lat2, lon2 = latlon2\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    R = 6371  # radius of the earth in kilometers\n    a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2\n    c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180\n    return c", "title": ""}
{"_id": "d15323", "text": "def items(cls):\n        \"\"\"\n        All values for this enum\n        :return: list of tuples\n\n        \"\"\"\n        return [\n            cls.PRECIPITATION,\n            cls.WIND,\n            cls.TEMPERATURE,\n            cls.PRESSURE\n        ]", "title": ""}
{"_id": "d15324", "text": "def dot_v3(v, w):\n    \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n    return sum([x * y for x, y in zip(v, w)])", "title": ""}
{"_id": "d15325", "text": "def from_json_list(cls, api_client, data):\n        \"\"\"Convert a list of JSON values to a list of models\n        \"\"\"\n        return [cls.from_json(api_client, item) for item in data]", "title": ""}
{"_id": "d15326", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d15327", "text": "def getPrimeFactors(n):\n    \"\"\"\n    Get all the prime factor of given integer\n    @param n integer\n    @return list [1, ..., n]\n    \"\"\"\n    lo = [1]\n    n2 = n // 2\n    k = 2\n    for k in range(2, n2 + 1):\n        if (n // k)*k == n:\n            lo.append(k)\n    return lo + [n, ]", "title": ""}
{"_id": "d15328", "text": "def euclidean(c1, c2):\n    \"\"\"Square of the euclidean distance\"\"\"\n    diffs = ((i - j) for i, j in zip(c1, c2))\n    return sum(x * x for x in diffs)", "title": ""}
{"_id": "d15329", "text": "def chunk_list(l, n):\n    \"\"\"Return `n` size lists from a given list `l`\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d15330", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d15331", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d15332", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d15333", "text": "def list2string (inlist,delimit=' '):\n    \"\"\"\nConverts a 1D list to a single long string for file output, using\nthe string.join function.\n\nUsage:   list2string (inlist,delimit=' ')\nReturns: the string created from inlist\n\"\"\"\n    stringlist = [makestr(_) for _ in inlist]\n    return string.join(stringlist,delimit)", "title": ""}
{"_id": "d15334", "text": "def _call(callable_obj, arg_names, namespace):\n    \"\"\"Actually calls the callable with the namespace parsed from the command\n    line.\n\n    Args:\n        callable_obj: a callable object\n        arg_names: name of the function arguments\n        namespace: the namespace object parsed from the command line\n    \"\"\"\n    arguments = {arg_name: getattr(namespace, arg_name)\n                 for arg_name in arg_names}\n    return callable_obj(**arguments)", "title": ""}
{"_id": "d15335", "text": "def from_json_str(cls, json_str):\n    \"\"\"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.\n    \"\"\"\n    return cls.from_json(json.loads(json_str, cls=JsonDecoder))", "title": ""}
{"_id": "d15336", "text": "def eval_script(self, expr):\n    \"\"\" Evaluates a piece of Javascript in the context of the current page and\n    returns its value. \"\"\"\n    ret = self.conn.issue_command(\"Evaluate\", expr)\n    return json.loads(\"[%s]\" % ret)[0]", "title": ""}
{"_id": "d15337", "text": "def main(args=sys.argv):\n    \"\"\"\n    main entry point for the jardiff CLI\n    \"\"\"\n\n    parser = create_optparser(args[0])\n    return cli(parser.parse_args(args[1:]))", "title": ""}
{"_id": "d15338", "text": "def fn_min(self, a, axis=None):\n        \"\"\"\n        Return the minimum of an array, ignoring any NaNs.\n\n        :param a: The array.\n        :return: The minimum value of the array.\n        \"\"\"\n\n        return numpy.nanmin(self._to_ndarray(a), axis=axis)", "title": ""}
{"_id": "d15339", "text": "def load(obj, cls, default_factory):\n    \"\"\"Create or load an object if necessary.\n\n    Parameters\n    ----------\n    obj : `object` or `dict` or `None`\n    cls : `type`\n    default_factory : `function`\n\n    Returns\n    -------\n    `object`\n    \"\"\"\n    if obj is None:\n        return default_factory()\n    if isinstance(obj, dict):\n        return cls.load(obj)\n    return obj", "title": ""}
{"_id": "d15340", "text": "def datetime_from_str(string):\n    \"\"\"\n\n    Args:\n        string: string of the form YYMMDD-HH_MM_SS, e.g 160930-18_43_01\n\n    Returns: a datetime object\n\n    \"\"\"\n\n\n    return datetime.datetime(year=2000+int(string[0:2]), month=int(string[2:4]), day=int(string[4:6]), hour=int(string[7:9]), minute=int(string[10:12]),second=int(string[13:15]))", "title": ""}
{"_id": "d15341", "text": "def open_json(file_name):\n    \"\"\"\n    returns json contents as string\n    \"\"\"\n    with open(file_name, \"r\") as json_data:\n        data = json.load(json_data)\n        return data", "title": ""}
{"_id": "d15342", "text": "def mixedcase(path):\n    \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n    words = path.split('_')\n    return words[0] + ''.join(word.title() for word in words[1:])", "title": ""}
{"_id": "d15343", "text": "def load(cls, fname):\n        \"\"\"\n        Loads the flow from a JSON file.\n\n        :param fname: the file to load\n        :type fname: str\n        :return: the flow\n        :rtype: Flow\n        \"\"\"\n        with open(fname) as f:\n            content = f.readlines()\n        return Flow.from_json(''.join(content))", "title": ""}
{"_id": "d15344", "text": "def camel_case_from_underscores(string):\n    \"\"\"generate a CamelCase string from an underscore_string.\"\"\"\n    components = string.split('_')\n    string = ''\n    for component in components:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d15345", "text": "def load_graph_from_rdf(fname):\n    \"\"\" reads an RDF file into a graph \"\"\"\n    print(\"reading RDF from \" + fname + \"....\")\n    store = Graph()\n    store.parse(fname, format=\"n3\")\n    print(\"Loaded \" + str(len(store)) + \" tuples\")\n    return store", "title": ""}
{"_id": "d15346", "text": "def mixedcase(path):\n    \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n    words = path.split('_')\n    return words[0] + ''.join(word.title() for word in words[1:])", "title": ""}
{"_id": "d15347", "text": "def read_raw(data_path):\n    \"\"\"\n    Parameters\n    ----------\n    data_path : str\n    \"\"\"\n    with open(data_path, 'rb') as f:\n        data = pickle.load(f)\n    return data", "title": ""}
{"_id": "d15348", "text": "def mixedcase(path):\n    \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n    words = path.split('_')\n    return words[0] + ''.join(word.title() for word in words[1:])", "title": ""}
{"_id": "d15349", "text": "def bisect_index(a, x):\n    \"\"\" Find the leftmost index of an element in a list using binary search.\n\n    Parameters\n    ----------\n    a: list\n        A sorted list.\n    x: arbitrary\n        The element.\n\n    Returns\n    -------\n    int\n        The index.\n\n    \"\"\"\n    i = bisect.bisect_left(a, x)\n    if i != len(a) and a[i] == x:\n        return i\n    raise ValueError", "title": ""}
{"_id": "d15350", "text": "def to_binary(s, encoding='utf8'):\n    \"\"\"Portable cast function.\n\n    In python 2 the ``str`` function which is used to coerce objects to bytes does not\n    accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n    :param s: object to be converted to binary_type\n    :return: binary_type instance, representing s.\n    \"\"\"\n    if PY3:  # pragma: no cover\n        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n    return binary_type(s)", "title": ""}
{"_id": "d15351", "text": "def find_console_handler(logger):\n    \"\"\"Return a stream handler, if it exists.\"\"\"\n    for handler in logger.handlers:\n        if (isinstance(handler, logging.StreamHandler) and\n                handler.stream == sys.stderr):\n            return handler", "title": ""}
{"_id": "d15352", "text": "def _datetime_to_date(arg):\n    \"\"\"\n    convert datetime/str to date\n    :param arg:\n    :return:\n    \"\"\"\n    _arg = parse(arg)\n    if isinstance(_arg, datetime.datetime):\n        _arg = _arg.date()\n    return _arg", "title": ""}
{"_id": "d15353", "text": "def __enter__(self):\n        \"\"\"Enable the download log filter.\"\"\"\n        self.logger = logging.getLogger('pip.download')\n        self.logger.addFilter(self)", "title": ""}
{"_id": "d15354", "text": "def update_dict(obj, dict, attributes):\n    \"\"\"Update dict with fields from obj.attributes.\n\n    :param obj: the object updated into dict\n    :param dict: the result dictionary\n    :param attributes: a list of attributes belonging to obj\n    \"\"\"\n    for attribute in attributes:\n        if hasattr(obj, attribute) and getattr(obj, attribute) is not None:\n            dict[attribute] = getattr(obj, attribute)", "title": ""}
{"_id": "d15355", "text": "def clog(color):\n    \"\"\"Same to ``log``, but this one centralizes the message first.\"\"\"\n    logger = log(color)\n    return lambda msg: logger(centralize(msg).rstrip())", "title": ""}
{"_id": "d15356", "text": "def _normalize_numpy_indices(i):\n    \"\"\"Normalize the index in case it is a numpy integer or boolean\n    array.\"\"\"\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", "title": ""}
{"_id": "d15357", "text": "def format(self, record, *args, **kwargs):\n        \"\"\"\n        Format a message in the log\n\n        Act like the normal format, but indent anything that is a\n        newline within the message.\n\n        \"\"\"\n        return logging.Formatter.format(\n            self, record, *args, **kwargs).replace('\\n', '\\n' + ' ' * 8)", "title": ""}
{"_id": "d15358", "text": "def convert_types(cls, value):\n        \"\"\"\n        Takes a value from MSSQL, and converts it to a value that's safe for\n        JSON/Google Cloud Storage/BigQuery.\n        \"\"\"\n        if isinstance(value, decimal.Decimal):\n            return float(value)\n        else:\n            return value", "title": ""}
{"_id": "d15359", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d15360", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d15361", "text": "def format_time(time):\n    \"\"\" Formats the given time into HH:MM:SS \"\"\"\n    h, r = divmod(time / 1000, 3600)\n    m, s = divmod(r, 60)\n\n    return \"%02d:%02d:%02d\" % (h, m, s)", "title": ""}
{"_id": "d15362", "text": "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d15363", "text": "def as_tuple(self, value):\n        \"\"\"Utility function which converts lists to tuples.\"\"\"\n        if isinstance(value, list):\n            value = tuple(value)\n        return value", "title": ""}
{"_id": "d15364", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d15365", "text": "def set_index(self, index):\n        \"\"\" Sets the pd dataframe index of all dataframes in the system to index\n        \"\"\"\n        for df in self.get_DataFrame(data=True, with_population=False):\n            df.index = index", "title": ""}
{"_id": "d15366", "text": "def set_executable(filename):\n    \"\"\"Set the exectuable bit on the given filename\"\"\"\n    st = os.stat(filename)\n    os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d15367", "text": "def get_obj(ref):\n    \"\"\"Get object from string reference.\"\"\"\n    oid = int(ref)\n    return server.id2ref.get(oid) or server.id2obj[oid]", "title": ""}
{"_id": "d15368", "text": "def forward(self, step):\n        \"\"\"Move the turtle forward.\n\n        :param step: Integer. Distance to move forward.\n        \"\"\"\n        x = self.pos_x + math.cos(math.radians(self.rotation)) * step\n        y = self.pos_y + math.sin(math.radians(self.rotation)) * step\n        prev_brush_state = self.brush_on\n        self.brush_on = True\n        self.move(x, y)\n        self.brush_on = prev_brush_state", "title": ""}
{"_id": "d15369", "text": "def polyline(self, arr):\n        \"\"\"Draw a set of lines\"\"\"\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])", "title": ""}
{"_id": "d15370", "text": "def _to_java_object_rdd(rdd):\n    \"\"\" Return a 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.\n    \"\"\"\n    rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n    return rdd.ctx._jvm.org.apache.spark.mllib.api.python.SerDe.pythonToJava(rdd._jrdd, True)", "title": ""}
{"_id": "d15371", "text": "def mock_add_spec(self, spec, spec_set=False):\n        \"\"\"Add a spec to a mock. `spec` can either be an object or a\n        list of strings. Only attributes on the `spec` can be fetched as\n        attributes from the mock.\n\n        If `spec_set` is True then only attributes on the spec can be set.\"\"\"\n        self._mock_add_spec(spec, spec_set)\n        self._mock_set_magics()", "title": ""}
{"_id": "d15372", "text": "def screen(self, width, height, colorDepth):\n        \"\"\"\n        @summary: record resize event of screen (maybe first event)\n        @param width: {int} width of screen\n        @param height: {int} height of screen\n        @param colorDepth: {int} colorDepth\n        \"\"\"\n        screenEvent = ScreenEvent()\n        screenEvent.width.value = width\n        screenEvent.height.value = height\n        screenEvent.colorDepth.value = colorDepth\n        self.rec(screenEvent)", "title": ""}
{"_id": "d15373", "text": "def get_subject(self, msg):\n        \"\"\"Extracts the subject line from an EmailMessage object.\"\"\"\n\n        text, encoding = decode_header(msg['subject'])[-1]\n\n        try:\n            text = text.decode(encoding)\n\n        # If it's already decoded, ignore error\n        except AttributeError:\n            pass\n\n        return text", "title": ""}
{"_id": "d15374", "text": "def to_list(var):\n    \"\"\"Checks if given value is a list, tries to convert, if it is not.\"\"\"\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", "title": ""}
{"_id": "d15375", "text": "def iflatten(L):\n    \"\"\"Iterative flatten.\"\"\"\n    for sublist in L:\n        if hasattr(sublist, '__iter__'):\n            for item in iflatten(sublist): yield item\n        else: yield sublist", "title": ""}
{"_id": "d15376", "text": "def to_str(s):\n    \"\"\"\n    Convert bytes and non-string into Python 3 str\n    \"\"\"\n    if isinstance(s, bytes):\n        s = s.decode('utf-8')\n    elif not isinstance(s, str):\n        s = str(s)\n    return s", "title": ""}
{"_id": "d15377", "text": "def wait_run_in_executor(func, *args, **kwargs):\n    \"\"\"\n    Run blocking code in a different thread and wait\n    for the result.\n\n    :param func: Run this function in a different thread\n    :param args: Parameters of the function\n    :param kwargs: Keyword parameters of the function\n    :returns: Return the result of the function\n    \"\"\"\n\n    loop = asyncio.get_event_loop()\n    future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs))\n    yield from asyncio.wait([future])\n    return future.result()", "title": ""}
{"_id": "d15378", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d15379", "text": "def make_symmetric(dict):\n    \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n    for key, value in list(dict.items()):\n        dict[value] = key\n    return dict", "title": ""}
{"_id": "d15380", "text": "def std_datestr(self, datestr):\n        \"\"\"Reformat a date string to standard format.\n        \"\"\"\n        return date.strftime(\n                self.str2date(datestr), self.std_dateformat)", "title": ""}
{"_id": "d15381", "text": "def list_of_lists_to_dict(l):\n    \"\"\" Convert list of key,value lists to dict\n\n    [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n    {'id': [1, 2, 3], 'foo': [4]}\n    \"\"\"\n    d = {}\n    for key, val in l:\n        d.setdefault(key, []).append(val)\n    return d", "title": ""}
{"_id": "d15382", "text": "def file_found(filename,force):\n    \"\"\"Check if a file exists\"\"\"\n    if os.path.exists(filename) and not force:\n        logger.info(\"Found %s; skipping...\"%filename)\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d15383", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d15384", "text": "def _columns_for_table(table_name):\n    \"\"\"\n    Return all of the columns registered for a given table.\n\n    Parameters\n    ----------\n    table_name : str\n\n    Returns\n    -------\n    columns : dict of column wrappers\n        Keys will be column names.\n\n    \"\"\"\n    return {cname: col\n            for (tname, cname), col in _COLUMNS.items()\n            if tname == table_name}", "title": ""}
{"_id": "d15385", "text": "def get_naive(dt):\n  \"\"\"Gets a naive datetime from a datetime.\n\n  datetime_tz objects can't just have tzinfo replaced with None, you need to\n  call asdatetime.\n\n  Args:\n    dt: datetime object.\n\n  Returns:\n    datetime object without any timezone information.\n  \"\"\"\n  if not dt.tzinfo:\n    return dt\n  if hasattr(dt, \"asdatetime\"):\n    return dt.asdatetime()\n  return dt.replace(tzinfo=None)", "title": ""}
{"_id": "d15386", "text": "def unicode_is_ascii(u_string):\n    \"\"\"Determine if unicode string only contains ASCII characters.\n\n    :param str u_string: unicode string to check. Must be unicode\n        and not Python 2 `str`.\n    :rtype: bool\n    \"\"\"\n    assert isinstance(u_string, str)\n    try:\n        u_string.encode('ascii')\n        return True\n    except UnicodeEncodeError:\n        return False", "title": ""}
{"_id": "d15387", "text": "def makedirs(path):\n    \"\"\"\n    Create directories if they do not exist, otherwise do nothing.\n\n    Return path for convenience\n    \"\"\"\n    if not os.path.isdir(path):\n        os.makedirs(path)\n    return path", "title": ""}
{"_id": "d15388", "text": "def _validate_pos(df):\n    \"\"\"Validates the returned positional object\n    \"\"\"\n    assert isinstance(df, pd.DataFrame)\n    assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n    assert df.position.dtype == np.dtype(\"int64\")\n    assert df.strand.dtype == np.dtype(\"O\")\n    assert df.seqname.dtype == np.dtype(\"O\")\n    return df", "title": ""}
{"_id": "d15389", "text": "def transpose(table):\n    \"\"\"\n    transpose matrix\n    \"\"\"\n    t = []\n    for i in range(0, len(table[0])):\n        t.append([row[i] for row in table])\n    return t", "title": ""}
{"_id": "d15390", "text": "def set_as_object(self, value):\n        \"\"\"\n        Sets a new value to map element\n\n        :param value: a new element or map value.\n        \"\"\"\n        self.clear()\n        map = MapConverter.to_map(value)\n        self.append(map)", "title": ""}
{"_id": "d15391", "text": "def _check_color_dim(val):\n    \"\"\"Ensure val is Nx(n_col), usually Nx3\"\"\"\n    val = np.atleast_2d(val)\n    if val.shape[1] not in (3, 4):\n        raise RuntimeError('Value must have second dimension of size 3 or 4')\n    return val, val.shape[1]", "title": ""}
{"_id": "d15392", "text": "def match_paren(self, tokens, item):\n        \"\"\"Matches a paren.\"\"\"\n        match, = tokens\n        return self.match(match, item)", "title": ""}
{"_id": "d15393", "text": "def equal(obj1, obj2):\n    \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n    Comparable.log(obj1, obj2, '==')\n    equality = obj1.equality(obj2)\n    Comparable.log(obj1, obj2, '==', result=equality)\n    return equality", "title": ""}
{"_id": "d15394", "text": "def file_matches(filename, patterns):\n    \"\"\"Does this filename match any of the patterns?\"\"\"\n    return any(fnmatch.fnmatch(filename, pat) for pat in patterns)", "title": ""}
{"_id": "d15395", "text": "def is_valid_image_extension(file_path):\n    \"\"\"is_valid_image_extension.\"\"\"\n    valid_extensions = ['.jpeg', '.jpg', '.gif', '.png']\n    _, extension = os.path.splitext(file_path)\n    return extension.lower() in valid_extensions", "title": ""}
{"_id": "d15396", "text": "def set_title(self, title, **kwargs):\n        \"\"\"Sets the title on the underlying matplotlib AxesSubplot.\"\"\"\n        ax = self.get_axes()\n        ax.set_title(title, **kwargs)", "title": ""}
{"_id": "d15397", "text": "def is_builtin_css_function(name):\n    \"\"\"Returns whether the given `name` looks like the name of a builtin CSS\n    function.\n\n    Unrecognized functions not in this list produce warnings.\n    \"\"\"\n    name = name.replace('_', '-')\n\n    if name in BUILTIN_FUNCTIONS:\n        return True\n\n    # Vendor-specific functions (-foo-bar) are always okay\n    if name[0] == '-' and '-' in name[1:]:\n        return True\n\n    return False", "title": ""}
{"_id": "d15398", "text": "def _linear_seaborn_(self, label=None, style=None, opts=None):\n        \"\"\"\n        Returns a Seaborn linear regression plot\n        \"\"\"\n        xticks, yticks = self._get_ticks(opts)\n        try:\n            fig = sns.lmplot(self.x, self.y, data=self.df)\n            fig = self._set_with_height(fig, opts)\n            return fig\n        except Exception as e:\n            self.err(e, self.linear_,\n                     \"Can not draw linear regression chart\")", "title": ""}
{"_id": "d15399", "text": "def map_wrap(f):\n    \"\"\"Wrap standard function to easily pass into 'map' processing.\n    \"\"\"\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        return f(*args, **kwargs)\n    return wrapper", "title": ""}
{"_id": "d15400", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d15401", "text": "def is_iter_non_string(obj):\n    \"\"\"test if object is a list or tuple\"\"\"\n    if isinstance(obj, list) or isinstance(obj, tuple):\n        return True\n    return False", "title": ""}
{"_id": "d15402", "text": "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig", "title": ""}
{"_id": "d15403", "text": "def set_value(self, value):\n        \"\"\"Set value of the checkbox.\n\n        Parameters\n        ----------\n        value : bool\n            value for the checkbox\n\n        \"\"\"\n        if value:\n            self.setChecked(Qt.Checked)\n        else:\n            self.setChecked(Qt.Unchecked)", "title": ""}
{"_id": "d15404", "text": "def raise_figure_window(f=0):\n    \"\"\"\n    Raises the supplied figure number or figure window.\n    \"\"\"\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()", "title": ""}
{"_id": "d15405", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d15406", "text": "def extent(self):\n        \"\"\"Helper for matplotlib imshow\"\"\"\n        return (\n            self.intervals[1].pix1 - 0.5,\n            self.intervals[1].pix2 - 0.5,\n            self.intervals[0].pix1 - 0.5,\n            self.intervals[0].pix2 - 0.5,\n        )", "title": ""}
{"_id": "d15407", "text": "def exists(self, filepath):\n        \"\"\"Determines if the specified file/folder exists, even if it\n        is on a remote server.\"\"\"\n        if self.is_ssh(filepath):\n            self._check_ftp()\n            remotepath = self._get_remote(filepath)\n            try:\n                self.ftp.stat(remotepath)\n            except IOError as e:\n                if e.errno == errno.ENOENT:\n                    return False\n            else:\n                return True\n        else:\n            return os.path.exists(filepath)", "title": ""}
{"_id": "d15408", "text": "def plot(self):\n        \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n        plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "title": ""}
{"_id": "d15409", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d15410", "text": "def set_ylimits(self, row, column, min=None, max=None):\n        \"\"\"Set y-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_ylimits(min, max)", "title": ""}
{"_id": "d15411", "text": "def is_same_dict(d1, d2):\n    \"\"\"Test two dictionary is equal on values. (ignore order)\n    \"\"\"\n    for k, v in d1.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d2[k])\n        else:\n            assert d1[k] == d2[k]\n\n    for k, v in d2.items():\n        if isinstance(v, dict):\n            is_same_dict(v, d1[k])\n        else:\n            assert d1[k] == d2[k]", "title": ""}
{"_id": "d15412", "text": "def roots(self):\n    \"\"\"\n    Returns a list with all roots. Needs Numpy.\n    \"\"\"\n    import numpy as np\n    return np.roots(list(self.values())[::-1]).tolist()", "title": ""}
{"_id": "d15413", "text": "def boxes_intersect(box1, box2):\n    \"\"\"Determines if two rectangles, each input as a tuple\n        (xmin, xmax, ymin, ymax), intersect.\"\"\"\n    xmin1, xmax1, ymin1, ymax1 = box1\n    xmin2, xmax2, ymin2, ymax2 = box2\n    if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \\\n            interval_intersection_width(ymin1, ymax1, ymin2, ymax2):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d15414", "text": "def copy(a):\n    \"\"\" Copy an array to the shared memory. \n\n        Notes\n        -----\n        copy is not always necessary because the private memory is always copy-on-write.\n\n        Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory\n    \"\"\"\n    shared = anonymousmemmap(a.shape, dtype=a.dtype)\n    shared[:] = a[:]\n    return shared", "title": ""}
{"_id": "d15415", "text": "def _is_iterable(item):\n    \"\"\" Checks if an item is iterable (list, tuple, generator), but not string \"\"\"\n    return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)", "title": ""}
{"_id": "d15416", "text": "def machine_info():\n    \"\"\"Retrieve core and memory information for the current machine.\n    \"\"\"\n    import psutil\n    BYTES_IN_GIG = 1073741824.0\n    free_bytes = psutil.virtual_memory().total\n    return [{\"memory\": float(\"%.1f\" % (free_bytes / BYTES_IN_GIG)), \"cores\": multiprocessing.cpu_count(),\n             \"name\": socket.gethostname()}]", "title": ""}
{"_id": "d15417", "text": "def is_string(val):\n    \"\"\"Determines whether the passed value is a string, safe for 2/3.\"\"\"\n    try:\n        basestring\n    except NameError:\n        return isinstance(val, str)\n    return isinstance(val, basestring)", "title": ""}
{"_id": "d15418", "text": "def with_defaults(method, nparams, defaults=None):\n  \"\"\"Call method with nparams positional parameters, all non-specified defaults are passed None.\n\n  :method: the method to call\n  :nparams: the number of parameters the function expects\n  :defaults: the default values to pass in for the last len(defaults) params\n  \"\"\"\n  args = [None] * nparams if not defaults else defaults + max(nparams - len(defaults), 0) * [None]\n  return method(*args)", "title": ""}
{"_id": "d15419", "text": "def is_same_nick(self, left, right):\n        \"\"\" Check if given nicknames are equal in the server's case mapping. \"\"\"\n        return self.normalize(left) == self.normalize(right)", "title": ""}
{"_id": "d15420", "text": "def _file_type(self, field):\n        \"\"\" Returns file type for given file field.\n        \n        Args:\n            field (str): File field\n\n        Returns:\n            string. File type\n        \"\"\"\n        type = mimetypes.guess_type(self._files[field])[0]\n        return type.encode(\"utf-8\") if isinstance(type, unicode) else str(type)", "title": ""}
{"_id": "d15421", "text": "def is_date(thing):\n    \"\"\"Checks if the given thing represents a date\n\n    :param thing: The object to check if it is a date\n    :type thing: arbitrary object\n    :returns: True if we have a date object\n    :rtype: bool\n    \"\"\"\n    # known date types\n    date_types = (datetime.datetime,\n                  datetime.date,\n                  DateTime)\n    return isinstance(thing, date_types)", "title": ""}
{"_id": "d15422", "text": "def update_one(self, query, doc):\n        \"\"\"\n        Updates one element of the collection\n\n        :param query: dictionary representing the mongo query\n        :param doc: dictionary representing the item to be updated\n        :return: UpdateResult\n        \"\"\"\n        if self.table is None:\n            self.build_table()\n\n        if u\"$set\" in doc:\n            doc = doc[u\"$set\"]\n\n        allcond = self.parse_query(query)\n\n        try:\n            result = self.table.update(doc, allcond)\n        except:\n            # TODO: check table.update result\n            # check what pymongo does in that case\n            result = None\n\n        return UpdateResult(raw_result=result)", "title": ""}
{"_id": "d15423", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d15424", "text": "def last_month():\n        \"\"\" Return start and end date of this month. \"\"\"\n        since = TODAY + delta(day=1, months=-1)\n        until = since + delta(months=1)\n        return Date(since), Date(until)", "title": ""}
{"_id": "d15425", "text": "def _is_image_sequenced(image):\n    \"\"\"Determine if the image is a sequenced image.\"\"\"\n    try:\n        image.seek(1)\n        image.seek(0)\n        result = True\n    except EOFError:\n        result = False\n\n    return result", "title": ""}
{"_id": "d15426", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d15427", "text": "def is_readable_dir(path):\n  \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n  return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d15428", "text": "def moving_average(array, n=3):\n    \"\"\"\n    Calculates the moving average of an array.\n\n    Parameters\n    ----------\n    array : array\n        The array to have the moving average taken of\n    n : int\n        The number of points of moving average to take\n    \n    Returns\n    -------\n    MovingAverageArray : array\n        The n-point moving average of the input array\n    \"\"\"\n    ret = _np.cumsum(array, dtype=float)\n    ret[n:] = ret[n:] - ret[:-n]\n    return ret[n - 1:] / n", "title": ""}
{"_id": "d15429", "text": "def memory_used(self):\n        \"\"\"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.\n        \"\"\"\n        if self._end_memory:\n            memory_used = self._end_memory - self._start_memory\n            return memory_used\n        else:\n            return None", "title": ""}
{"_id": "d15430", "text": "def Min(a, axis, keep_dims):\n    \"\"\"\n    Min reduction op.\n    \"\"\"\n    return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d15431", "text": "def check_update():\n    \"\"\"\n    Check for app updates and print/log them.\n    \"\"\"\n    logging.info('Check for app updates.')\n    try:\n        update = updater.check_for_app_updates()\n    except Exception:\n        logging.exception('Check for updates failed.')\n        return\n    if update:\n        print(\"!!! UPDATE AVAILABLE !!!\\n\"\n              \"\" + static_data.PROJECT_URL + \"\\n\\n\")\n        logging.info(\"Update available: \" + static_data.PROJECT_URL)\n    else:\n        logging.info(\"No update available.\")", "title": ""}
{"_id": "d15432", "text": "def load(self):\n        \"\"\"Load proxy list from configured proxy source\"\"\"\n        self._list = self._source.load()\n        self._list_iter = itertools.cycle(self._list)", "title": ""}
{"_id": "d15433", "text": "def string_input(prompt=''):\n    \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n    v = sys.version[0]\n    if v == '3':\n        return input(prompt)\n    else:\n        return raw_input(prompt)", "title": ""}
{"_id": "d15434", "text": "def compute_capture(args):\n    x, y, w, h, params = args\n    \"\"\"Callable function for the multiprocessing pool.\"\"\"\n    return x, y, mandelbrot_capture(x, y, w, h, params)", "title": ""}
{"_id": "d15435", "text": "def created_today(self):\n        \"\"\"Return True if created today.\"\"\"\n        if self.datetime.date() == datetime.today().date():\n            return True\n        return False", "title": ""}
{"_id": "d15436", "text": "def kill_mprocess(process):\n    \"\"\"kill process\n    Args:\n        process - Popen object for process\n    \"\"\"\n    if process and proc_alive(process):\n        process.terminate()\n        process.communicate()\n    return not proc_alive(process)", "title": ""}
{"_id": "d15437", "text": "def assert_valid_input(cls, tag):\n        \"\"\"Check if valid input tag or document.\"\"\"\n\n        # Fail on unexpected types.\n        if not cls.is_tag(tag):\n            raise TypeError(\"Expected a BeautifulSoup 'Tag', but instead recieved type {}\".format(type(tag)))", "title": ""}
{"_id": "d15438", "text": "def timeout_thread_handler(timeout, stop_event):\n    \"\"\"A background thread to kill the process if it takes too long.\n\n    Args:\n        timeout (float): The number of seconds to wait before killing\n            the process.\n        stop_event (Event): An optional event to cleanly stop the background\n            thread if required during testing.\n    \"\"\"\n\n    stop_happened = stop_event.wait(timeout)\n    if stop_happened is False:\n        print(\"Killing program due to %f second timeout\" % timeout)\n\n    os._exit(2)", "title": ""}
{"_id": "d15439", "text": "def has_common(self, other):\n        \"\"\"Return set of common words between two word sets.\"\"\"\n        if not isinstance(other, WordSet):\n            raise ValueError('Can compare only WordSets')\n        return self.term_set & other.term_set", "title": ""}
{"_id": "d15440", "text": "def pause(self):\n        \"\"\"Pause the music\"\"\"\n        mixer.music.pause()\n        self.pause_time = self.get_time()\n        self.paused = True", "title": ""}
{"_id": "d15441", "text": "def autoconvert(string):\n    \"\"\"Try to convert variables into datatypes.\"\"\"\n    for fn in (boolify, int, float):\n        try:\n            return fn(string)\n        except ValueError:\n            pass\n    return string", "title": ""}
{"_id": "d15442", "text": "def autoconvert(string):\n    \"\"\"Try to convert variables into datatypes.\"\"\"\n    for fn in (boolify, int, float):\n        try:\n            return fn(string)\n        except ValueError:\n            pass\n    return string", "title": ""}
{"_id": "d15443", "text": "def type(self):\n        \"\"\"Returns type of the data for the given FeatureType.\"\"\"\n        if self is FeatureType.TIMESTAMP:\n            return list\n        if self is FeatureType.BBOX:\n            return BBox\n        return dict", "title": ""}
{"_id": "d15444", "text": "def isstring(value):\n    \"\"\"Report whether the given value is a byte or unicode string.\"\"\"\n    classes = (str, bytes) if pyutils.PY3 else basestring  # noqa: F821\n    return isinstance(value, classes)", "title": ""}
{"_id": "d15445", "text": "def chmod_plus_w(path):\n  \"\"\"Equivalent of unix `chmod +w path`\"\"\"\n  path_mode = os.stat(path).st_mode\n  path_mode &= int('777', 8)\n  path_mode |= stat.S_IWRITE\n  os.chmod(path, path_mode)", "title": ""}
{"_id": "d15446", "text": "def object_as_dict(obj):\n    \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n    Based on https://stackoverflow.com/a/37350445/1579058\n    \"\"\"\n    return {c.key: getattr(obj, c.key)\n            for c in inspect(obj).mapper.column_attrs}", "title": ""}
{"_id": "d15447", "text": "def random_choice(sequence):\n    \"\"\" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. \"\"\"\n    return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)", "title": ""}
{"_id": "d15448", "text": "def object_as_dict(obj):\n    \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n    Based on https://stackoverflow.com/a/37350445/1579058\n    \"\"\"\n    return {c.key: getattr(obj, c.key)\n            for c in inspect(obj).mapper.column_attrs}", "title": ""}
{"_id": "d15449", "text": "def first_unique_char(s):\n    \"\"\"\n    :type s: str\n    :rtype: int\n    \"\"\"\n    if (len(s) == 1):\n        return 0\n    ban = []\n    for i in range(len(s)):\n        if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:\n            return i\n        else:\n            ban.append(s[i])\n    return -1", "title": ""}
{"_id": "d15450", "text": "def load_object_by_name(object_name):\n    \"\"\"Load an object from a module by name\"\"\"\n    mod_name, attr = object_name.rsplit('.', 1)\n    mod = import_module(mod_name)\n    return getattr(mod, attr)", "title": ""}
{"_id": "d15451", "text": "def erase(self):\n        \"\"\"White out the progress bar.\"\"\"\n        with self._at_last_line():\n            self.stream.write(self._term.clear_eol)\n        self.stream.flush()", "title": ""}
{"_id": "d15452", "text": "def dictify(a_named_tuple):\n    \"\"\"Transform a named tuple into a dictionary\"\"\"\n    return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)", "title": ""}
{"_id": "d15453", "text": "def __clear_buffers(self):\n        \"\"\"Clears the input and output buffers\"\"\"\n        try:\n            self._port.reset_input_buffer()\n            self._port.reset_output_buffer()\n        except AttributeError:\n            #pySerial 2.7\n            self._port.flushInput()\n            self._port.flushOutput()", "title": ""}
{"_id": "d15454", "text": "def index_nearest(array, value):\n    \"\"\"\n    Finds index of nearest value in array.\n\n    Args:\n        array: numpy array\n        value:\n\n    Returns:\n        int\n\n    http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array\n    \"\"\"\n    idx = (np.abs(array-value)).argmin()\n    return idx", "title": ""}
{"_id": "d15455", "text": "def raise_figure_window(f=0):\n    \"\"\"\n    Raises the supplied figure number or figure window.\n    \"\"\"\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()", "title": ""}
{"_id": "d15456", "text": "def from_dict(cls, d):\n        \"\"\"Create an instance from a dictionary.\"\"\"\n        return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})", "title": ""}
{"_id": "d15457", "text": "def stop_refresh(self):\n        \"\"\"Stop redrawing the canvas at the previously set timed interval.\n        \"\"\"\n        self.logger.debug(\"stopping timed refresh\")\n        self.rf_flags['done'] = True\n        self.rf_timer.clear()", "title": ""}
{"_id": "d15458", "text": "def make_file_read_only(file_path):\n    \"\"\"\n    Removes the write permissions for the given file for owner, groups and others.\n\n    :param file_path: The file whose privileges are revoked.\n    :raise FileNotFoundError: If the given file does not exist.\n    \"\"\"\n    old_permissions = os.stat(file_path).st_mode\n    os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)", "title": ""}
{"_id": "d15459", "text": "def norm(x, mu, sigma=1.0):\n    \"\"\" Scipy norm function \"\"\"\n    return stats.norm(loc=mu, scale=sigma).pdf(x)", "title": ""}
{"_id": "d15460", "text": "def clear():\n    \"\"\"Clears the console.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        call(\"cls\", shell=True)\n    else:\n        call(\"clear\", shell=True)", "title": ""}
{"_id": "d15461", "text": "def accel_next(self, *args):\n        \"\"\"Callback to go to the next tab. Called by the accel key.\n        \"\"\"\n        if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n            self.get_notebook().set_current_page(0)\n        else:\n            self.get_notebook().next_page()\n        return True", "title": ""}
{"_id": "d15462", "text": "def normalize(im, invert=False, scale=None, dtype=np.float64):\n    \"\"\"\n    Normalize a field to a (min, max) exposure range, default is (0, 255).\n    (min, max) exposure values. Invert the image if requested.\n    \"\"\"\n    if dtype not in {np.float16, np.float32, np.float64}:\n        raise ValueError('dtype must be numpy.float16, float32, or float64.')\n    out = im.astype('float').copy()\n\n    scale = scale or (0.0, 255.0)\n    l, u = (float(i) for i in scale)\n    out = (out - l) / (u - l)\n    if invert:\n        out = -out + (out.max() + out.min())\n    return out.astype(dtype)", "title": ""}
{"_id": "d15463", "text": "def cleanup(self, app):\n        \"\"\"Close all connections.\"\"\"\n        if hasattr(self.database.obj, 'close_all'):\n            self.database.close_all()", "title": ""}
{"_id": "d15464", "text": "def _normalize(mat: np.ndarray):\n    \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "title": ""}
{"_id": "d15465", "text": "def _close(self):\n        \"\"\"\n        Closes the client connection to the database.\n        \"\"\"\n        if self.connection:\n            with self.wrap_database_errors:\n                self.connection.client.close()", "title": ""}
{"_id": "d15466", "text": "def _normalize(obj):\n    \"\"\"\n    Normalize dicts and lists\n\n    :param obj:\n    :return: normalized object\n    \"\"\"\n    if isinstance(obj, list):\n        return [_normalize(item) for item in obj]\n    elif isinstance(obj, dict):\n        return {k: _normalize(v) for k, v in obj.items() if v is not None}\n    elif hasattr(obj, 'to_python'):\n        return obj.to_python()\n    return obj", "title": ""}
{"_id": "d15467", "text": "def pascal_row(n):\n    \"\"\" Returns n-th row of Pascal's triangle\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", "title": ""}
{"_id": "d15468", "text": "def run(self):\n        \"\"\"\n        Runs the unit test framework. Can be overridden to run anything.\n        Returns True on passing and False on failure.\n        \"\"\"\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", "title": ""}
{"_id": "d15469", "text": "def place(self):\n        \"\"\"Place this container's canvas onto the parent container's canvas.\"\"\"\n        self.place_children()\n        self.canvas.append(self.parent.canvas,\n                           float(self.left), float(self.top))", "title": ""}
{"_id": "d15470", "text": "def test(nose_argsuments):\n    \"\"\" Run application tests \"\"\"\n    from nose import run\n\n    params = ['__main__', '-c', 'nose.ini']\n    params.extend(nose_argsuments)\n    run(argv=params)", "title": ""}
{"_id": "d15471", "text": "def merge_dict(data, *args):\n    \"\"\"Merge any number of dictionaries\n    \"\"\"\n    results = {}\n    for current in (data,) + args:\n        results.update(current)\n    return results", "title": ""}
{"_id": "d15472", "text": "def wait_until_exit(self):\n        \"\"\" Wait until thread exit\n\n            Used for testing purpose only\n        \"\"\"\n\n        if self._timeout is None:\n            raise Exception(\"Thread will never exit. Use stop or specify timeout when starting it!\")\n\n        self._thread.join()\n        self.stop()", "title": ""}
{"_id": "d15473", "text": "def equal(obj1, obj2):\n    \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n    Comparable.log(obj1, obj2, '==')\n    equality = obj1.equality(obj2)\n    Comparable.log(obj1, obj2, '==', result=equality)\n    return equality", "title": ""}
{"_id": "d15474", "text": "def cfloat32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n        return np.fromiter(cptr, dtype=np.float32, count=length)\n    else:\n        raise RuntimeError('Expected float pointer')", "title": ""}
{"_id": "d15475", "text": "def euclidean(x, y):\n    \"\"\"Standard euclidean distance.\n\n    ..math::\n        D(x, y) = \\sqrt{\\sum_i (x_i - y_i)^2}\n    \"\"\"\n    result = 0.0\n    for i in range(x.shape[0]):\n        result += (x[i] - y[i]) ** 2\n    return np.sqrt(result)", "title": ""}
{"_id": "d15476", "text": "def compute_number_edges(function):\n    \"\"\"\n    Compute the number of edges of the CFG\n    Args:\n        function (core.declarations.function.Function)\n    Returns:\n        int\n    \"\"\"\n    n = 0\n    for node in function.nodes:\n        n += len(node.sons)\n    return n", "title": ""}
{"_id": "d15477", "text": "def bytesize(arr):\n    \"\"\"\n    Returns the memory byte size of a Numpy array as an integer.\n    \"\"\"\n    byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize\n    return byte_size", "title": ""}
{"_id": "d15478", "text": "def count(data, axis=None):\n    \"\"\"Count the number of non-NA in this array along the given axis or axes\n    \"\"\"\n    return np.sum(np.logical_not(isnull(data)), axis=axis)", "title": ""}
{"_id": "d15479", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d15480", "text": "def length(self):\n        \"\"\"Array of vector lengths\"\"\"\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "title": ""}
{"_id": "d15481", "text": "def covstr(s):\n  \"\"\" convert string to int or float. \"\"\"\n  try:\n    ret = int(s)\n  except ValueError:\n    ret = float(s)\n  return ret", "title": ""}
{"_id": "d15482", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d15483", "text": "def main(ctx, connection):\n    \"\"\"Command line interface for PyBEL.\"\"\"\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()", "title": ""}
{"_id": "d15484", "text": "def run(context, port):\n    \"\"\" Run the Webserver/SocketIO and app\n    \"\"\"\n    global ctx\n    ctx = context\n    app.run(port=port)", "title": ""}
{"_id": "d15485", "text": "def length(self):\n        \"\"\"Array of vector lengths\"\"\"\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "title": ""}
{"_id": "d15486", "text": "def solr_to_date(d):\n    \"\"\" converts YYYY-MM-DDT00:00:00Z to DD-MM-YYYY \"\"\"\n    return \"{day}:{m}:{y}\".format(y=d[:4], m=d[5:7], day=d[8:10]) if d else d", "title": ""}
{"_id": "d15487", "text": "def find_nearest_index(arr, value):\n    \"\"\"For a given value, the function finds the nearest value\n    in the array and returns its index.\"\"\"\n    arr = np.array(arr)\n    index = (abs(arr-value)).argmin()\n    return index", "title": ""}
{"_id": "d15488", "text": "def mag(z):\n    \"\"\"Get the magnitude of a vector.\"\"\"\n    if isinstance(z[0], np.ndarray):\n        return np.array(list(map(np.linalg.norm, z)))\n    else:\n        return np.linalg.norm(z)", "title": ""}
{"_id": "d15489", "text": "def total_regular_pixels_from_mask(mask):\n    \"\"\"Compute the total number of unmasked regular pixels in a masks.\"\"\"\n\n    total_regular_pixels = 0\n\n    for y in range(mask.shape[0]):\n        for x in range(mask.shape[1]):\n            if not mask[y, x]:\n                total_regular_pixels += 1\n\n    return total_regular_pixels", "title": ""}
{"_id": "d15490", "text": "def Max(a, axis, keep_dims):\n    \"\"\"\n    Max reduction op.\n    \"\"\"\n    return np.amax(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),", "title": ""}
{"_id": "d15491", "text": "def line_count(fn):\n    \"\"\" Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)\n    \"\"\"\n\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1", "title": ""}
{"_id": "d15492", "text": "def save_json(object, handle, indent=2):\n    \"\"\"Save object as json on CNS.\"\"\"\n    obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder)\n    handle.write(obj_json)", "title": ""}
{"_id": "d15493", "text": "def wordfreq(text, is_filename=False):\n    \"\"\"Return a dictionary of words and word counts in a string.\"\"\"\n    if is_filename:\n        with open(text) as f:\n            text = f.read()\n    freqs = {}\n    for word in text.split():\n        lword = word.lower()\n        freqs[lword] = freqs.get(lword, 0) + 1\n    return freqs", "title": ""}
{"_id": "d15494", "text": "def bytes_base64(x):\n    \"\"\"Turn bytes into base64\"\"\"\n    if six.PY2:\n        return base64.encodestring(x).replace('\\n', '')\n    return base64.encodebytes(bytes_encode(x)).replace(b'\\n', b'')", "title": ""}
{"_id": "d15495", "text": "def count_rows(self, table_name):\n        \"\"\"Return the number of entries in a table by counting them.\"\"\"\n        self.table_must_exist(table_name)\n        query = \"SELECT COUNT (*) FROM `%s`\" % table_name.lower()\n        self.own_cursor.execute(query)\n        return int(self.own_cursor.fetchone()[0])", "title": ""}
{"_id": "d15496", "text": "def get_list_from_file(file_name):\n    \"\"\"read the lines from a file into a list\"\"\"\n    with open(file_name, mode='r', encoding='utf-8') as f1:\n        lst = f1.readlines()\n    return lst", "title": ""}
{"_id": "d15497", "text": "def debug(sequence):\n    \"\"\"\n    adds information to the sequence for better debugging, currently only\n    an index property on each point in the sequence.\n    \"\"\"\n    points = []\n    for i, p in enumerate(sequence):\n        copy = Point(p)\n        copy['index'] = i\n        points.append(copy)\n    return sequence.__class__(points)", "title": ""}
{"_id": "d15498", "text": "def make_temp(text):\n        \"\"\"\n        Creates a temprorary file and writes the `text` into it\n        \"\"\"\n        import tempfile\n        (handle, path) = tempfile.mkstemp(text=True)\n        os.close(handle)\n        afile = File(path)\n        afile.write(text)\n        return afile", "title": ""}
{"_id": "d15499", "text": "def shader_string(body, glsl_version='450 core'):\n    \"\"\"\n    Call this method from a function that defines a literal shader string as the \"body\" argument.\n    Dresses up a shader string in three ways:\n        1) Insert #version at the top\n        2) Insert #line number declaration\n        3) un-indents\n    The line number information can help debug glsl compile errors.\n    The version string needs to be the very first characters in the shader,\n    which can be distracting, requiring backslashes or other tricks.\n    The unindenting allows you to type the shader code at a pleasing indent level\n    in your python method, while still creating an unindented GLSL string at the end.\n    \"\"\"\n    line_count = len(body.split('\\n'))\n    line_number = inspect.currentframe().f_back.f_lineno + 1 - line_count\n    return \"\"\"\\\n#version %s\n%s\n\"\"\" % (glsl_version, shader_substring(body, stack_frame=2))", "title": ""}
{"_id": "d15500", "text": "def sometimesish(fn):\n    \"\"\"\n    Has a 50/50 chance of calling a function\n    \"\"\"\n    def wrapped(*args, **kwargs):\n        if random.randint(1, 2) == 1:\n            return fn(*args, **kwargs)\n\n    return wrapped", "title": ""}
{"_id": "d15501", "text": "def help(self, level=0):\n        \"\"\"return the usage string for available options \"\"\"\n        self.cmdline_parser.formatter.output_level = level\n        with _patch_optparse():\n            return self.cmdline_parser.format_help()", "title": ""}
{"_id": "d15502", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d15503", "text": "def perl_cmd():\n    \"\"\"Retrieve path to locally installed conda Perl or first in PATH.\n    \"\"\"\n    perl = which(os.path.join(get_bcbio_bin(), \"perl\"))\n    if perl:\n        return perl\n    else:\n        return which(\"perl\")", "title": ""}
{"_id": "d15504", "text": "def dumped(text, level, indent=2):\n    \"\"\"Put curly brackets round an indented text\"\"\"\n    return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "title": ""}
{"_id": "d15505", "text": "def cli(yamlfile, directory, out, classname, format):\n    \"\"\" Generate graphviz representations of the biolink model \"\"\"\n    DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)", "title": ""}
{"_id": "d15506", "text": "def format_op_hdr():\n    \"\"\"\n    Build the header\n    \"\"\"\n    txt = 'Base Filename'.ljust(36) + ' '\n    txt += 'Lines'.rjust(7) + ' '\n    txt += 'Words'.rjust(7) + '  '\n    txt += 'Unique'.ljust(8) + ''\n    return txt", "title": ""}
{"_id": "d15507", "text": "def resize_image_with_crop_or_pad(img, target_height, target_width):\n    \"\"\"\n    Crops and/or pads an image to a target width and height.\n\n    Resizes an image to a target width and height by either cropping the image or padding it with zeros.\n\n    NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom right)\n\n    :param img: Numpy array representing the image.\n    :param target_height: Target height.\n    :param target_width: Target width.\n    :return: The cropped and padded image.\n    \"\"\"\n    h, w = target_height, target_width\n    max_h, max_w, c = img.shape\n\n    # crop\n    img = crop_center(img, min(max_h, h), min(max_w, w))\n\n    # pad\n    padded_img = np.zeros(shape=(h, w, c), dtype=img.dtype)\n    padded_img[:img.shape[0], :img.shape[1], :img.shape[2]] = img\n\n    return padded_img", "title": ""}
{"_id": "d15508", "text": "def interface_direct_class(data_class):\n    \"\"\"help to direct to the correct interface interacting with DB by class name only\"\"\"\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", "title": ""}
{"_id": "d15509", "text": "def zero_pad(m, n=1):\n    \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n    return np.pad(m, (n, n), mode='constant', constant_values=[0])", "title": ""}
{"_id": "d15510", "text": "def chunked(l, n):\n    \"\"\"Chunk one big list into few small lists.\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d15511", "text": "def dcounts(self):\n        \"\"\"\n        :return: a data frame with names and distinct counts and fractions for all columns in the database\n        \"\"\"\n        print(\"WARNING: Distinct value count for all tables can take a long time...\", file=sys.stderr)\n        sys.stderr.flush()\n\n        data = []\n        for t in self.tables():\n            for c in t.columns():\n                data.append([t.name(), c.name(), c.dcount(), t.size(), c.dcount() / float(t.size())])\n        df = pd.DataFrame(data, columns=[\"table\", \"column\", \"distinct\", \"size\", \"fraction\"])\n        return df", "title": ""}
{"_id": "d15512", "text": "def _remove_empty_items(d, required):\n  \"\"\"Return a new dict with any empty items removed.\n\n  Note that this is not a deep check. If d contains a dictionary which\n  itself contains empty items, those are never checked.\n\n  This method exists to make to_serializable() functions cleaner.\n  We could revisit this some day, but for now, the serialized objects are\n  stripped of empty values to keep the output YAML more compact.\n\n  Args:\n    d: a dictionary\n    required: list of required keys (for example, TaskDescriptors always emit\n      the \"task-id\", even if None)\n\n  Returns:\n    A dictionary with empty items removed.\n  \"\"\"\n\n  new_dict = {}\n  for k, v in d.items():\n    if k in required:\n      new_dict[k] = v\n    elif isinstance(v, int) or v:\n      # \"if v\" would suppress emitting int(0)\n      new_dict[k] = v\n\n  return new_dict", "title": ""}
{"_id": "d15513", "text": "def ms_panset(self, viewer, event, data_x, data_y,\n                  msg=True):\n        \"\"\"An interactive way to set the pan position.  The location\n        (data_x, data_y) will be centered in the window.\n        \"\"\"\n        if self.canpan and (event.state == 'down'):\n            self._panset(viewer, data_x, data_y, msg=msg)\n        return True", "title": ""}
{"_id": "d15514", "text": "def disassemble_file(filename, outstream=None):\n    \"\"\"\n    disassemble Python byte-code file (.pyc)\n\n    If given a Python source file (\".py\") file, we'll\n    try to find the corresponding compiled object.\n    \"\"\"\n    filename = check_object_path(filename)\n    (version, timestamp, magic_int, co, is_pypy,\n     source_size) = load_module(filename)\n    if type(co) == list:\n        for con in co:\n            disco(version, con, outstream)\n    else:\n        disco(version, co, outstream, is_pypy=is_pypy)\n    co = None", "title": ""}
{"_id": "d15515", "text": "def load_results(result_files, options, run_set_id=None, columns=None,\n                 columns_relevant_for_diff=set()):\n    \"\"\"Version of load_result for multiple input files that will be loaded concurrently.\"\"\"\n    return parallel.map(\n        load_result,\n        result_files,\n        itertools.repeat(options),\n        itertools.repeat(run_set_id),\n        itertools.repeat(columns),\n        itertools.repeat(columns_relevant_for_diff))", "title": ""}
{"_id": "d15516", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d15517", "text": "def expandvars_dict(settings):\n    \"\"\"Expands all environment variables in a settings dictionary.\"\"\"\n    return dict(\n        (key, os.path.expandvars(value))\n        for key, value in settings.iteritems()\n    )", "title": ""}
{"_id": "d15518", "text": "def Bernstein(n, k):\n    \"\"\"Bernstein polynomial.\n\n    \"\"\"\n    coeff = binom(n, k)\n\n    def _bpoly(x):\n        return coeff * x ** k * (1 - x) ** (n - k)\n\n    return _bpoly", "title": ""}
{"_id": "d15519", "text": "def from_pb(cls, pb):\n        \"\"\"Instantiate the object from a protocol buffer.\n\n        Args:\n            pb (protobuf)\n\n        Save a reference to the protocol buffer on the object.\n        \"\"\"\n        obj = cls._from_pb(pb)\n        obj._pb = pb\n        return obj", "title": ""}
{"_id": "d15520", "text": "def get_table_width(table):\n    \"\"\"\n    Gets the width of the table that would be printed.\n    :rtype: ``int``\n    \"\"\"\n    columns = transpose_table(prepare_rows(table))\n    widths = [max(len(cell) for cell in column) for column in columns]\n    return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')", "title": ""}
{"_id": "d15521", "text": "def parse(self):\n        \"\"\"\n        Parse file specified by constructor.\n        \"\"\"\n        f = open(self.parse_log_path, \"r\")\n        self.parse2(f)\n        f.close()", "title": ""}
{"_id": "d15522", "text": "def main(idle):\n    \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n    while True:\n\n        LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n        time.sleep(idle)", "title": ""}
{"_id": "d15523", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d15524", "text": "def _delete_local(self, filename):\n        \"\"\"Deletes the specified file from the local filesystem.\"\"\"\n\n        if os.path.exists(filename):\n            os.remove(filename)", "title": ""}
{"_id": "d15525", "text": "def _parse_single_response(cls, response_data):\n        \"\"\"de-serialize a JSON-RPC Response/error\n\n        :Returns: | [result, id] for Responses\n        :Raises:  | RPCFault+derivates for error-packages/faults, RPCParseError, RPCInvalidRPC\n        \"\"\"\n\n        if not isinstance(response_data, dict):\n            raise errors.RPCInvalidRequest(\"No valid RPC-package.\")\n\n        if \"id\" not in response_data:\n            raise errors.RPCInvalidRequest(\"\"\"Invalid Response, \"id\" missing.\"\"\")\n\n        request_id = response_data['id']\n\n        if \"jsonrpc\" not in response_data:\n            raise errors.RPCInvalidRequest(\"\"\"Invalid Response, \"jsonrpc\" missing.\"\"\", request_id)\n        if not isinstance(response_data[\"jsonrpc\"], (str, unicode)):\n            raise errors.RPCInvalidRequest(\"\"\"Invalid Response, \"jsonrpc\" must be a string.\"\"\")\n        if response_data[\"jsonrpc\"] != \"2.0\":\n            raise errors.RPCInvalidRequest(\"\"\"Invalid jsonrpc version.\"\"\", request_id)\n\n        error = response_data.get('error', None)\n        result = response_data.get('result', None)\n\n        if error and result:\n            raise errors.RPCInvalidRequest(\"\"\"Invalid Response, only \"result\" OR \"error\" allowed.\"\"\", request_id)\n\n        if error:\n            if not isinstance(error, dict):\n                raise errors.RPCInvalidRequest(\"Invalid Response, invalid error-object.\", request_id)\n\n            if not (\"code\" in error and \"message\" in error):\n                raise errors.RPCInvalidRequest(\"Invalid Response, invalid error-object.\", request_id)\n\n            error_data = error.get(\"data\", None)\n\n            if error['code'] in errors.ERROR_CODE_CLASS_MAP:\n                raise errors.ERROR_CODE_CLASS_MAP[error['code']](error_data, request_id)\n            else:\n                error_object = errors.RPCFault(error_data, request_id)\n                error_object.error_code = error['code']\n                error_object.message = error['message']\n                raise error_object\n\n        return result, request_id", "title": ""}
{"_id": "d15526", "text": "def trim(self):\n        \"\"\"Clear not used counters\"\"\"\n        for key, value in list(iteritems(self.counters)):\n            if value.empty():\n                del self.counters[key]", "title": ""}
{"_id": "d15527", "text": "def xml_str_to_dict(s):\n    \"\"\" Transforms an XML string it to python-zimbra dict format\n\n    For format, see:\n      https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n    :param: a string, containing XML\n    :returns: a dict, with python-zimbra format\n    \"\"\"\n    xml = minidom.parseString(s)\n    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)", "title": ""}
{"_id": "d15528", "text": "def delete_all_eggs(self):\n        \"\"\" delete all the eggs in the directory specified \"\"\"\n        path_to_delete = os.path.join(self.egg_directory, \"lib\", \"python\")\n        if os.path.exists(path_to_delete):\n            shutil.rmtree(path_to_delete)", "title": ""}
{"_id": "d15529", "text": "def __str__(self):\n    \"\"\"Returns a pretty-printed string for this object.\"\"\"\n    return 'Output name: \"%s\" watts: %d type: \"%s\" id: %d' % (\n        self._name, self._watts, self._output_type, self._integration_id)", "title": ""}
{"_id": "d15530", "text": "def distinct(l):\n    \"\"\"\n    Return a list where the duplicates have been removed.\n\n    Args:\n        l (list): the list to filter.\n\n    Returns:\n        list: the same list without duplicates.\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return (_ for _ in l if not (_ in seen or seen_add(_)))", "title": ""}
{"_id": "d15531", "text": "def safe_call(cls, method, *args):\n        \"\"\" Call a remote api method but don't raise if an error occurred.\"\"\"\n        return cls.call(method, *args, safe=True)", "title": ""}
{"_id": "d15532", "text": "def get_height_for_line(self, lineno):\n        \"\"\"\n        Return the height of the given line.\n        (The height that it would take, if this line became visible.)\n        \"\"\"\n        if self.wrap_lines:\n            return self.ui_content.get_height_for_line(lineno, self.window_width)\n        else:\n            return 1", "title": ""}
{"_id": "d15533", "text": "def grandparent_path(self):\n        \"\"\" return grandparent's path string \"\"\"\n        return os.path.basename(os.path.join(self.path, '../..'))", "title": ""}
{"_id": "d15534", "text": "def get_best_encoding(stream):\n    \"\"\"Returns the default stream encoding if not found.\"\"\"\n    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()\n    if is_ascii_encoding(rv):\n        return 'utf-8'\n    return rv", "title": ""}
{"_id": "d15535", "text": "def get_size_in_bytes(self, handle):\n        \"\"\"Return the size in bytes.\"\"\"\n        fpath = self._fpath_from_handle(handle)\n        return os.stat(fpath).st_size", "title": ""}
{"_id": "d15536", "text": "def watched_extension(extension):\n    \"\"\"Return True if the given extension is one of the watched extensions\"\"\"\n    for ext in hamlpy.VALID_EXTENSIONS:\n        if extension.endswith('.' + ext):\n            return True\n    return False", "title": ""}
{"_id": "d15537", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d15538", "text": "def region_from_segment(image, segment):\n    \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n    x, y, w, h = segment\n    return image[y:y + h, x:x + w]", "title": ""}
{"_id": "d15539", "text": "def set_trace():\n    \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n    # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n    pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "title": ""}
{"_id": "d15540", "text": "def _calculate_similarity(c):\n    \"\"\"Get a similarity matrix of % of shared sequence\n\n    :param c: cluster object\n\n    :return ma: similarity matrix\n    \"\"\"\n    ma = {}\n    for idc in c:\n        set1 = _get_seqs(c[idc])\n        [ma.update({(idc, idc2): _common(set1, _get_seqs(c[idc2]), idc, idc2)}) for idc2 in c if idc != idc2 and (idc2, idc) not in ma]\n    # logger.debug(\"_calculate_similarity_ %s\" % ma)\n    return ma", "title": ""}
{"_id": "d15541", "text": "def load(self, filename='classifier.dump'):\n        \"\"\"\n        Unpickles the classifier used\n        \"\"\"\n        ifile = open(filename, 'r+')\n        self.classifier = pickle.load(ifile)\n        ifile.close()", "title": ""}
{"_id": "d15542", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d15543", "text": "def unpickle_file(picklefile, **kwargs):\n    \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)", "title": ""}
{"_id": "d15544", "text": "def _string_width(self, s):\n        \"\"\"Get width of a string in the current font\"\"\"\n        s = str(s)\n        w = 0\n        for i in s:\n            w += self.character_widths[i]\n        return w * self.font_size / 1000.0", "title": ""}
{"_id": "d15545", "text": "def to_pydatetime(self):\n        \"\"\"\n        Converts datetimeoffset object into Python's datetime.datetime object\n        @return: time zone aware datetime.datetime\n        \"\"\"\n        dt = datetime.datetime.combine(self._date.to_pydate(), self._time.to_pytime())\n        from .tz import FixedOffsetTimezone\n        return dt.replace(tzinfo=_utc).astimezone(FixedOffsetTimezone(self._offset))", "title": ""}
{"_id": "d15546", "text": "def bundle_dir():\n    \"\"\"Handle resource management within an executable file.\"\"\"\n    if frozen():\n        directory = sys._MEIPASS\n    else:\n        directory = os.path.dirname(os.path.abspath(stack()[1][1]))\n    if os.path.exists(directory):\n        return directory", "title": ""}
{"_id": "d15547", "text": "def add_matplotlib_cmap(cm, name=None):\n    \"\"\"Add a matplotlib colormap.\"\"\"\n    global cmaps\n    cmap = matplotlib_to_ginga_cmap(cm, name=name)\n    cmaps[cmap.name] = cmap", "title": ""}
{"_id": "d15548", "text": "def disable_cert_validation():\n    \"\"\"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.\n\n    \"\"\"\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", "title": ""}
{"_id": "d15549", "text": "def human__decision_tree():\n    \"\"\" Decision Tree\n    \"\"\"\n\n    # build data\n    N = 1000000\n    M = 3\n    X = np.zeros((N,M))\n    X.shape\n    y = np.zeros(N)\n    X[0, 0] = 1\n    y[0] = 8\n    X[1, 1] = 1\n    y[1] = 8\n    X[2, 0:2] = 1\n    y[2] = 4\n\n    # fit model\n    xor_model = sklearn.tree.DecisionTreeRegressor(max_depth=2)\n    xor_model.fit(X, y)\n\n    return xor_model", "title": ""}
{"_id": "d15550", "text": "def print_images(self, *printable_images):\n        \"\"\"\n        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\n        \"\"\"\n        printable_image = reduce(lambda x, y: x.append(y), list(printable_images))\n        self.print_image(printable_image)", "title": ""}
{"_id": "d15551", "text": "def plotfft(s, fmax, doplot=False):\n    \"\"\"\n    -----\n    Brief\n    -----\n    This functions computes the Fast Fourier Transform of a signal, returning the frequency and magnitude values.\n\n    -----------\n    Description\n    -----------\n    Fast Fourier Transform (FFT) is a method to computationally calculate the Fourier Transform of discrete finite\n    signals. This transform converts the time domain signal into a frequency domain signal by abdicating the temporal\n    dimension.\n\n    This function computes the FFT of the input signal and returns the frequency and respective amplitude values.\n\n    ----------\n    Parameters\n    ----------\n    s: array-like\n      the input signal.\n    fmax: int\n      the sampling frequency.\n    doplot: boolean\n      a variable to indicate whether the plot is done or not.\n\n    Returns\n    -------\n    f: array-like\n      the frequency values (xx axis)\n    fs: array-like\n      the amplitude of the frequency values (yy axis)\n    \"\"\"\n\n    fs = abs(numpy.fft.fft(s))\n    f = numpy.linspace(0, fmax / 2, len(s) / 2)\n    if doplot:\n        plot(list(f[1:int(len(s) / 2)]), list(fs[1:int(len(s) / 2)]))\n    return f[1:int(len(s) / 2)].copy(), fs[1:int(len(s) / 2)].copy()", "title": ""}
{"_id": "d15552", "text": "def get_unique_indices(df, axis=1):\n    \"\"\"\n\n    :param df:\n    :param axis:\n    :return:\n    \"\"\"\n    return dict(zip(df.columns.names, dif.columns.levels))", "title": ""}
{"_id": "d15553", "text": "def multi_pop(d, *args):\n    \"\"\" pops multiple keys off a dict like object \"\"\"\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval", "title": ""}
{"_id": "d15554", "text": "def computeFactorial(n):\n    \"\"\"\n    computes factorial of n\n    \"\"\"\n    sleep_walk(10)\n    ret = 1\n    for i in range(n):\n        ret = ret * (i + 1)\n    return ret", "title": ""}
{"_id": "d15555", "text": "def auth_request(self, url, headers, body):\n        \"\"\"Perform auth request for token.\"\"\"\n\n        return self.req.post(url, headers, body=body)", "title": ""}
{"_id": "d15556", "text": "def _comment(string):\n    \"\"\"return string as a comment\"\"\"\n    lines = [line.strip() for line in string.splitlines()]\n    return \"# \" + (\"%s# \" % linesep).join(lines)", "title": ""}
{"_id": "d15557", "text": "def psql(sql, show=True):\n    \"\"\"\n    Runs SQL against the project's database.\n    \"\"\"\n    out = postgres('psql -c \"%s\"' % sql)\n    if show:\n        print_command(sql)\n    return out", "title": ""}
{"_id": "d15558", "text": "def download_url(url, filename, headers):\n    \"\"\"Download a file from `url` to `filename`.\"\"\"\n    ensure_dirs(filename)\n    response = requests.get(url, headers=headers, stream=True)\n    if response.status_code == 200:\n        with open(filename, 'wb') as f:\n            for chunk in response.iter_content(16 * 1024):\n                f.write(chunk)", "title": ""}
{"_id": "d15559", "text": "def dictfetchall(cursor):\n    \"\"\"Returns all rows from a cursor as a dict (rather than a headerless table)\n\n    From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/\n    \"\"\"\n    desc = cursor.description\n    return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]", "title": ""}
{"_id": "d15560", "text": "def vline(self, x, y, height, color):\n        \"\"\"Draw a vertical line up to a given length.\"\"\"\n        self.rect(x, y, 1, height, color, fill=True)", "title": ""}
{"_id": "d15561", "text": "def exit(exit_code=0):\n  r\"\"\"A function to support exiting from exit hooks.\n\n  Could also be used to exit from the calling scripts in a thread safe manner.\n  \"\"\"\n  core.processExitHooks()\n\n  if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook\n    sys.stderr.flush()\n    sys.stdout.flush()\n    os._exit(exit_code) #pylint: disable=W0212\n\n  sys.exit(exit_code)", "title": ""}
{"_id": "d15562", "text": "def destroy(self):\n        \"\"\" Destroy the SQLStepQueue tables in the database \"\"\"\n        with self._db_conn() as conn:\n            for table_name in self._tables:\n                conn.execute('DROP TABLE IF EXISTS %s' % table_name)\n        return self", "title": ""}
{"_id": "d15563", "text": "def _do_auto_predict(machine, X, *args):\n    \"\"\"Performs an automatic prediction for the specified machine and returns\n    the predicted values.\n    \"\"\"\n    if auto_predict and hasattr(machine, \"predict\"):\n        return machine.predict(X)", "title": ""}
{"_id": "d15564", "text": "def has_edit_permission(self, request):\n        \"\"\" Can edit this object \"\"\"\n        return request.user.is_authenticated and request.user.is_active and request.user.is_staff", "title": ""}
{"_id": "d15565", "text": "def pretty_dict_str(d, indent=2):\n    \"\"\"shows JSON indented representation of d\"\"\"\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()", "title": ""}
{"_id": "d15566", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d15567", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d15568", "text": "def do_forceescape(value):\n    \"\"\"Enforce HTML escaping.  This will probably double escape variables.\"\"\"\n    if hasattr(value, '__html__'):\n        value = value.__html__()\n    return escape(text_type(value))", "title": ""}
{"_id": "d15569", "text": "def get_previous(self):\n        \"\"\"Get the billing cycle prior to this one. May return None\"\"\"\n        return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()", "title": ""}
{"_id": "d15570", "text": "def go_to_new_line(self):\n        \"\"\"Go to the end of the current line and create a new line\"\"\"\n        self.stdkey_end(False, False)\n        self.insert_text(self.get_line_separator())", "title": ""}
{"_id": "d15571", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d15572", "text": "def go_to_new_line(self):\n        \"\"\"Go to the end of the current line and create a new line\"\"\"\n        self.stdkey_end(False, False)\n        self.insert_text(self.get_line_separator())", "title": ""}
{"_id": "d15573", "text": "def imp_print(self, text, end):\n\t\t\"\"\"Directly send utf8 bytes to stdout\"\"\"\n\t\tsys.stdout.write((text + end).encode(\"utf-8\"))", "title": ""}
{"_id": "d15574", "text": "def All(sequence):\n  \"\"\"\n  :param sequence: Any sequence whose elements can be evaluated as booleans.\n  :returns: true if all elements of the sequence satisfy True and x.\n  \"\"\"\n  return bool(reduce(lambda x, y: x and y, sequence, True))", "title": ""}
{"_id": "d15575", "text": "def _get_printable_columns(columns, row):\n    \"\"\"Return only the part of the row which should be printed.\n    \"\"\"\n    if not columns:\n        return row\n\n    # Extract the column values, in the order specified.\n    return tuple(row[c] for c in columns)", "title": ""}
{"_id": "d15576", "text": "def print(*a):\n    \"\"\" print just one that returns what you give it instead of None \"\"\"\n    try:\n        _print(*a)\n        return a[0] if len(a) == 1 else a\n    except:\n        _print(*a)", "title": ""}
{"_id": "d15577", "text": "def _quit(self, *args):\n        \"\"\" quit crash \"\"\"\n        self.logger.warn('Bye!')\n        sys.exit(self.exit())", "title": ""}
{"_id": "d15578", "text": "def timeit(output):\n    \"\"\"\n    If output is string, then print the string and also time used\n    \"\"\"\n    b = time.time()\n    yield\n    print output, 'time used: %.3fs' % (time.time()-b)", "title": ""}
{"_id": "d15579", "text": "def _expand(self, str, local_vars={}):\n        \"\"\"Expand $vars in a string.\"\"\"\n        return ninja_syntax.expand(str, self.vars, local_vars)", "title": ""}
{"_id": "d15580", "text": "def format_time(timestamp):\n    \"\"\"Formats timestamp to human readable format\"\"\"\n    format_string = '%Y_%m_%d_%Hh%Mm%Ss'\n    formatted_time = datetime.datetime.fromtimestamp(timestamp).strftime(format_string)\n    return formatted_time", "title": ""}
{"_id": "d15581", "text": "def executable_exists(executable):\n    \"\"\"Test if an executable is available on the system.\"\"\"\n    for directory in os.getenv(\"PATH\").split(\":\"):\n        if os.path.exists(os.path.join(directory, executable)):\n            return True\n    return False", "title": ""}
{"_id": "d15582", "text": "def pout(msg, log=None):\n    \"\"\"Print 'msg' to stdout, and option 'log' at info level.\"\"\"\n    _print(msg, sys.stdout, log_func=log.info if log else None)", "title": ""}
{"_id": "d15583", "text": "def extract_table_names(query):\n    \"\"\" Extract table names from an SQL query. \"\"\"\n    # a good old fashioned regex. turns out this worked better than actually parsing the code\n    tables_blocks = re.findall(r'(?:FROM|JOIN)\\s+(\\w+(?:\\s*,\\s*\\w+)*)', query, re.IGNORECASE)\n    tables = [tbl\n              for block in tables_blocks\n              for tbl in re.findall(r'\\w+', block)]\n    return set(tables)", "title": ""}
{"_id": "d15584", "text": "def print_tree(self, indent=2):\n        \"\"\" print_tree: prints out structure of tree\n            Args: indent (int): What level of indentation at which to start printing\n            Returns: None\n        \"\"\"\n        config.LOGGER.info(\"{indent}{data}\".format(indent=\"   \" * indent, data=str(self)))\n        for child in self.children:\n            child.print_tree(indent + 1)", "title": ""}
{"_id": "d15585", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d15586", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d15587", "text": "def iflatten(L):\n    \"\"\"Iterative flatten.\"\"\"\n    for sublist in L:\n        if hasattr(sublist, '__iter__'):\n            for item in iflatten(sublist): yield item\n        else: yield sublist", "title": ""}
{"_id": "d15588", "text": "def longest_run_1d(arr):\n    \"\"\"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.\n    \"\"\"\n    v, rl = rle_1d(arr)[:2]\n    return np.where(v, rl, 0).max()", "title": ""}
{"_id": "d15589", "text": "def imflip(img, direction='horizontal'):\n    \"\"\"Flip an image horizontally or vertically.\n\n    Args:\n        img (ndarray): Image to be flipped.\n        direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n    Returns:\n        ndarray: The flipped image.\n    \"\"\"\n    assert direction in ['horizontal', 'vertical']\n    if direction == 'horizontal':\n        return np.flip(img, axis=1)\n    else:\n        return np.flip(img, axis=0)", "title": ""}
{"_id": "d15590", "text": "def build_docs(directory):\n    \"\"\"Builds sphinx docs from a given directory.\"\"\"\n    os.chdir(directory)\n    process = subprocess.Popen([\"make\", \"html\"], cwd=directory)\n    process.communicate()", "title": ""}
{"_id": "d15591", "text": "def dedupe_list(l):\n    \"\"\"Remove duplicates from a list preserving the order.\n\n    We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n    the order, which hinders testability and does not work for lists with\n    unhashable elements.\n    \"\"\"\n    result = []\n\n    for el in l:\n        if el not in result:\n            result.append(el)\n\n    return result", "title": ""}
{"_id": "d15592", "text": "def _chunk_write(chunk, local_file, progress):\n    \"\"\"Write a chunk to file and update the progress bar\"\"\"\n    local_file.write(chunk)\n    progress.update_with_increment_value(len(chunk))", "title": ""}
{"_id": "d15593", "text": "def safe_int_conv(number):\n    \"\"\"Safely convert a single number to integer.\"\"\"\n    try:\n        return int(np.array(number).astype(int, casting='safe'))\n    except TypeError:\n        raise ValueError('cannot safely convert {} to integer'.format(number))", "title": ""}
{"_id": "d15594", "text": "def getpackagepath():\n    \"\"\"\n     *Get the root path for this python package - used in unit testing code*\n    \"\"\"\n    moduleDirectory = os.path.dirname(__file__)\n    packagePath = os.path.dirname(__file__) + \"/../\"\n\n    return packagePath", "title": ""}
{"_id": "d15595", "text": "def hash_iterable(it):\n\t\"\"\"Perform a O(1) memory hash of an iterable of arbitrary length.\n\n\thash(tuple(it)) creates a temporary tuple containing all values from it\n\twhich could be a problem if it is large.\n\n\tSee discussion at:\n\thttps://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ\n\t\"\"\"\n\thash_value = hash(type(it))\n\tfor value in it:\n\t\thash_value = hash((hash_value, value))\n\treturn hash_value", "title": ""}
{"_id": "d15596", "text": "def _normal_prompt(self):\n        \"\"\"\n        Flushes the prompt before requesting the input\n\n        :return: The command line\n        \"\"\"\n        sys.stdout.write(self.__get_ps1())\n        sys.stdout.flush()\n        return safe_input()", "title": ""}
{"_id": "d15597", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d15598", "text": "def write_only_property(f):\n    \"\"\"\n    @write_only_property decorator. Creates a property (descriptor attribute)\n    that accepts assignment, but not getattr (use in an expression).\n    \"\"\"\n    docstring = f.__doc__\n\n    return property(fset=f, doc=docstring)", "title": ""}
{"_id": "d15599", "text": "def _rnd_datetime(self, start, end):\n        \"\"\"Internal random datetime generator.\n        \"\"\"\n        return self.from_utctimestamp(\n            random.randint(\n                int(self.to_utctimestamp(start)),\n                int(self.to_utctimestamp(end)),\n            )\n        )", "title": ""}
{"_id": "d15600", "text": "def message_from_string(s, *args, **kws):\n    \"\"\"Parse a string into a Message object model.\n\n    Optional _class and strict are passed to the Parser constructor.\n    \"\"\"\n    from future.backports.email.parser import Parser\n    return Parser(*args, **kws).parsestr(s)", "title": ""}
{"_id": "d15601", "text": "def _unique_id(self, prefix):\n        \"\"\"\n        Generate a unique (within the graph) identifer\n        internal to graph generation.\n        \"\"\"\n        _id = self._id_gen\n        self._id_gen += 1\n        return prefix + str(_id)", "title": ""}
{"_id": "d15602", "text": "def getEdges(npArr):\n  \"\"\"get np array of bin edges\"\"\"\n  edges = np.concatenate(([0], npArr[:,0] + npArr[:,2]))\n  return np.array([Decimal(str(i)) for i in edges])", "title": ""}
{"_id": "d15603", "text": "def _get_random_id():\n    \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n    symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(symbols) for _ in range(15))", "title": ""}
{"_id": "d15604", "text": "def add_arrow(self, x1, y1, x2, y2, **kws):\n        \"\"\"add arrow to plot\"\"\"\n        self.panel.add_arrow(x1, y1, x2, y2, **kws)", "title": ""}
{"_id": "d15605", "text": "def ci(a, which=95, axis=None):\n    \"\"\"Return a percentile range from an array of values.\"\"\"\n    p = 50 - which / 2, 50 + which / 2\n    return percentiles(a, p, axis)", "title": ""}
{"_id": "d15606", "text": "def get_callable_documentation(the_callable):\n    \"\"\"Return a string with the callable signature and its docstring.\n\n    :param the_callable: the callable to be analyzed.\n    :type the_callable: function/callable.\n    :return: the signature.\n    \"\"\"\n    return wrap_text_in_a_box(\n        title=get_callable_signature_as_string(the_callable),\n        body=(getattr(the_callable, '__doc__') or 'No documentation').replace(\n            '\\n', '\\n\\n'),\n        style='ascii_double')", "title": ""}
{"_id": "d15607", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d15608", "text": "def main(output=None, error=None, verbose=False):\n    \"\"\" The main (cli) interface for the pylint runner. \"\"\"\n    runner = Runner(args=[\"--verbose\"] if verbose is not False else None)\n    runner.run(output, error)", "title": ""}
{"_id": "d15609", "text": "def wget(url):\n    \"\"\"\n    Download the page into a string\n    \"\"\"\n    import urllib.parse\n    request = urllib.request.urlopen(url)\n    filestring = request.read()\n    return filestring", "title": ""}
{"_id": "d15610", "text": "def update_one(self, query, doc):\n        \"\"\"\n        Updates one element of the collection\n\n        :param query: dictionary representing the mongo query\n        :param doc: dictionary representing the item to be updated\n        :return: UpdateResult\n        \"\"\"\n        if self.table is None:\n            self.build_table()\n\n        if u\"$set\" in doc:\n            doc = doc[u\"$set\"]\n\n        allcond = self.parse_query(query)\n\n        try:\n            result = self.table.update(doc, allcond)\n        except:\n            # TODO: check table.update result\n            # check what pymongo does in that case\n            result = None\n\n        return UpdateResult(raw_result=result)", "title": ""}
{"_id": "d15611", "text": "def compose(*parameter_functions):\n  \"\"\"Composes multiple modification functions in order.\n\n  Args:\n    *parameter_functions: The functions to compose.\n\n  Returns:\n    A parameter modification function that consists of applying all the provided\n    functions.\n  \"\"\"\n  def composed_fn(var_name, variable, phase):\n    for fn in parameter_functions:\n      variable = fn(var_name, variable, phase)\n    return variable\n  return composed_fn", "title": ""}
{"_id": "d15612", "text": "def from_pydatetime(cls, pydatetime):\n        \"\"\"\n        Creates sql datetime2 object from Python datetime object\n        ignoring timezone\n        @param pydatetime: Python datetime object\n        @return: sql datetime2 object\n        \"\"\"\n        return cls(date=Date.from_pydate(pydatetime.date),\n                   time=Time.from_pytime(pydatetime.time))", "title": ""}
{"_id": "d15613", "text": "def list_files(directory):\n    \"\"\"Returns all files in a given directory\n    \"\"\"\n    return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]", "title": ""}
{"_id": "d15614", "text": "def cover(session):\n    \"\"\"Run the final coverage report.\n    This outputs the coverage report aggregating coverage from the unit\n    test runs (not system test runs), and then erases coverage data.\n    \"\"\"\n    session.interpreter = 'python3.6'\n    session.install('coverage', 'pytest-cov')\n    session.run('coverage', 'report', '--show-missing', '--fail-under=100')\n    session.run('coverage', 'erase')", "title": ""}
{"_id": "d15615", "text": "def get_font_list():\n    \"\"\"Returns a sorted list of all system font names\"\"\"\n\n    font_map = pangocairo.cairo_font_map_get_default()\n    font_list = [f.get_name() for f in font_map.list_families()]\n    font_list.sort()\n\n    return font_list", "title": ""}
{"_id": "d15616", "text": "def run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv. Return result code.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tresult_code = __import__('pytest').main()\n\t\t\tif result_code:\n\t\t\t\traise SystemExit(result_code)", "title": ""}
{"_id": "d15617", "text": "def money(min=0, max=10):\n    \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n    value = random.choice(range(min * 100, max * 100))\n    return \"%1.2f\" % (float(value) / 100)", "title": ""}
{"_id": "d15618", "text": "def contextMenuEvent(self, event):\n        \"\"\"Reimplement Qt method\"\"\"\n        self.menu.popup(event.globalPos())\n        event.accept()", "title": ""}
{"_id": "d15619", "text": "async def sysinfo(dev: Device):\n    \"\"\"Print out system information (version, MAC addrs).\"\"\"\n    click.echo(await dev.get_system_info())\n    click.echo(await dev.get_interface_information())", "title": ""}
{"_id": "d15620", "text": "def remove_parameter(self, name):\n\t\t\"\"\" Remove the specified parameter from this query\n\n\t\t:param name: name of a parameter to remove\n\t\t:return: None\n\t\t\"\"\"\n\t\tif name in self.__query:\n\t\t\tself.__query.pop(name)", "title": ""}
{"_id": "d15621", "text": "def combinations(l):\n    \"\"\"Pure-Python implementation of itertools.combinations(l, 2).\"\"\"\n    result = []\n    for x in xrange(len(l) - 1):\n        ls = l[x + 1:]\n        for y in ls:\n            result.append((l[x], y))\n    return result", "title": ""}
{"_id": "d15622", "text": "def bbox(self):\n        \"\"\"BBox\"\"\"\n        return self.left, self.top, self.right, self.bottom", "title": ""}
{"_id": "d15623", "text": "def PopTask(self):\n    \"\"\"Retrieves and removes the first task from the heap.\n\n    Returns:\n      Task: the task or None if the heap is empty.\n    \"\"\"\n    try:\n      _, task = heapq.heappop(self._heap)\n\n    except IndexError:\n      return None\n    self._task_identifiers.remove(task.identifier)\n    return task", "title": ""}
{"_id": "d15624", "text": "def parse_cookies(self, req, name, field):\n        \"\"\"Pull the value from the cookiejar.\"\"\"\n        return core.get_value(req.COOKIES, name, field)", "title": ""}
{"_id": "d15625", "text": "def random_color(_min=MIN_COLOR, _max=MAX_COLOR):\n    \"\"\"Returns a random color between min and max.\"\"\"\n    return color(random.randint(_min, _max))", "title": ""}
{"_id": "d15626", "text": "def sample_correlations(self):\n        \"\"\"Returns an `ExpMatrix` containing all pairwise sample correlations.\n\n        Returns\n        -------\n        `ExpMatrix`\n            The sample correlation matrix.\n\n        \"\"\"\n        C = np.corrcoef(self.X.T)\n        corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)\n        return corr_matrix", "title": ""}
{"_id": "d15627", "text": "def get_incomplete_path(filename):\n  \"\"\"Returns a temporary filename based on filename.\"\"\"\n  random_suffix = \"\".join(\n      random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n  return filename + \".incomplete\" + random_suffix", "title": ""}
{"_id": "d15628", "text": "def shape(self):\n        \"\"\"Compute the shape of the dataset as (rows, cols).\"\"\"\n        if not self.data:\n            return (0, 0)\n        return (len(self.data), len(self.dimensions))", "title": ""}
{"_id": "d15629", "text": "def rnormal(mu, tau, size=None):\n    \"\"\"\n    Random normal variates.\n    \"\"\"\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)", "title": ""}
{"_id": "d15630", "text": "def get_file_name(url):\n  \"\"\"Returns file name of file at given url.\"\"\"\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'", "title": ""}
{"_id": "d15631", "text": "def rlognormal(mu, tau, size=None):\n    \"\"\"\n    Return random lognormal variates.\n    \"\"\"\n\n    return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "title": ""}
{"_id": "d15632", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d15633", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d15634", "text": "def get_offset_topic_partition_count(kafka_config):\n    \"\"\"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.\"\"\"\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])", "title": ""}
{"_id": "d15635", "text": "def add_range(self, sequence, begin, end):\n    \"\"\"Add a read_range primitive\"\"\"\n    sequence.parser_tree = parsing.Range(self.value(begin).strip(\"'\"),\n                                         self.value(end).strip(\"'\"))\n    return True", "title": ""}
{"_id": "d15636", "text": "def getScriptLocation():\n\t\"\"\"Helper function to get the location of a Python file.\"\"\"\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location", "title": ""}
{"_id": "d15637", "text": "def max_values(args):\n    \"\"\" Return possible range for max function. \"\"\"\n    return Interval(max(x.low for x in args), max(x.high for x in args))", "title": ""}
{"_id": "d15638", "text": "def get_last_modified_timestamp(self):\n        \"\"\"\n        Looks at the files in a git root directory and grabs the last modified timestamp\n        \"\"\"\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", "title": ""}
{"_id": "d15639", "text": "def camel_to_snake_case(name):\n    \"\"\"Takes a camelCased string and converts to snake_case.\"\"\"\n    pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])'\n    return '_'.join(map(str.lower, re.findall(pattern, name)))", "title": ""}
{"_id": "d15640", "text": "def runcode(code):\n\t\"\"\"Run the given code line by line with printing, as list of lines, and return variable 'ans'.\"\"\"\n\tfor line in code:\n\t\tprint('# '+line)\n\t\texec(line,globals())\n\tprint('# return ans')\n\treturn ans", "title": ""}
{"_id": "d15641", "text": "def read_utf8(fh, byteorder, dtype, count, offsetsize):\n    \"\"\"Read tag data from file and return as unicode string.\"\"\"\n    return fh.read(count).decode('utf-8')", "title": ""}
{"_id": "d15642", "text": "def run_cmd(command, verbose=True, shell='/bin/bash'):\n    \"\"\"internal helper function to run shell commands and get output\"\"\"\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 full output including empty lines\n        return output\n    return [line for line in output if line.strip()]", "title": ""}
{"_id": "d15643", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d15644", "text": "def import_js(path, lib_name, globals):\n    \"\"\"Imports from javascript source file.\n      globals is your globals()\"\"\"\n    with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:\n        js = f.read()\n    e = EvalJs()\n    e.execute(js)\n    var = e.context['var']\n    globals[lib_name] = var.to_python()", "title": ""}
{"_id": "d15645", "text": "def file_to_str(fname):\n    \"\"\"\n    Read a file into a string\n    PRE: fname is a small file (to avoid hogging memory and its discontents)\n    \"\"\"\n    data = None\n    # rU = read with Universal line terminator\n    with open(fname, 'rU') as fd:\n        data = fd.read()\n    return data", "title": ""}
{"_id": "d15646", "text": "def dedup(seq):\n    \"\"\"Remove duplicates from a list while keeping order.\"\"\"\n    seen = set()\n    for item in seq:\n        if item not in seen:\n            seen.add(item)\n            yield item", "title": ""}
{"_id": "d15647", "text": "def loads(string):\n  \"\"\"\n  Deserializes Java objects and primitive data serialized by ObjectOutputStream\n  from a string.\n  \"\"\"\n  f = StringIO.StringIO(string)\n  marshaller = JavaObjectUnmarshaller(f)\n  marshaller.add_transformer(DefaultObjectTransformer())\n  return marshaller.readObject()", "title": ""}
{"_id": "d15648", "text": "def _run_cmd_get_output(cmd):\n    \"\"\"Runs a shell command, returns console output.\n\n    Mimics python3's subprocess.getoutput\n    \"\"\"\n    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n    out, err = process.communicate()\n    return out or err", "title": ""}
{"_id": "d15649", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d15650", "text": "def _calc_dir_size(path):\n    \"\"\"\n    Calculate size of all files in `path`.\n\n    Args:\n        path (str): Path to the directory.\n\n    Returns:\n        int: Size of the directory in bytes.\n    \"\"\"\n    dir_size = 0\n    for (root, dirs, files) in os.walk(path):\n        for fn in files:\n            full_fn = os.path.join(root, fn)\n            dir_size += os.path.getsize(full_fn)\n\n    return dir_size", "title": ""}
{"_id": "d15651", "text": "def standard_input():\n    \"\"\"Generator that yields lines from standard input.\"\"\"\n    with click.get_text_stream(\"stdin\") as stdin:\n        while stdin.readable():\n            line = stdin.readline()\n            if line:\n                yield line.strip().encode(\"utf-8\")", "title": ""}
{"_id": "d15652", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d15653", "text": "def import_public_rsa_key_from_file(filename):\n    \"\"\"\n    Read a public RSA 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.rsa.RSAPublicKey instance\n    \"\"\"\n    with open(filename, \"rb\") as key_file:\n        public_key = serialization.load_pem_public_key(\n            key_file.read(),\n            backend=default_backend())\n    return public_key", "title": ""}
{"_id": "d15654", "text": "def cat_acc(y_true, y_pred):\n    \"\"\"Categorical accuracy\n    \"\"\"\n    return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))", "title": ""}
{"_id": "d15655", "text": "def camel_to_underscore(string):\n    \"\"\"Convert camelcase to lowercase and underscore.\n\n    Recipe from http://stackoverflow.com/a/1176023\n\n    Args:\n        string (str): The string to convert.\n\n    Returns:\n        str: The converted string.\n    \"\"\"\n    string = FIRST_CAP_RE.sub(r'\\1_\\2', string)\n    return ALL_CAP_RE.sub(r'\\1_\\2', string).lower()", "title": ""}
{"_id": "d15656", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d15657", "text": "def recursively_update(d, d2):\n  \"\"\"dict.update but which merges child dicts (dict2 takes precedence where there's conflict).\"\"\"\n  for k, v in d2.items():\n    if k in d:\n      if isinstance(v, dict):\n        recursively_update(d[k], v)\n        continue\n    d[k] = v", "title": ""}
{"_id": "d15658", "text": "def entropy(string):\n    \"\"\"Compute entropy on the string\"\"\"\n    p, lns = Counter(string), float(len(string))\n    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())", "title": ""}
{"_id": "d15659", "text": "def __connect():\n    \"\"\"\n    Connect to a redis instance.\n    \"\"\"\n    global redis_instance\n    if use_tcp_socket:\n        redis_instance = redis.StrictRedis(host=hostname, port=port)\n    else:\n        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "title": ""}
{"_id": "d15660", "text": "def _regex_span(_regex, _str, case_insensitive=True):\n    \"\"\"Return all matches in an input string.\n    :rtype : regex.match.span\n    :param _regex: A regular expression pattern.\n    :param _str: Text on which to run the pattern.\n    \"\"\"\n    if case_insensitive:\n        flags = regex.IGNORECASE | regex.FULLCASE | regex.VERSION1\n    else:\n        flags = regex.VERSION1\n    comp = regex.compile(_regex, flags=flags)\n    matches = comp.finditer(_str)\n    for match in matches:\n        yield match", "title": ""}
{"_id": "d15661", "text": "def __contains__(self, key):\n        \"\"\"Return ``True`` if *key* is present, else ``False``.\"\"\"\n        pickled_key = self._pickle_key(key)\n        return bool(self.redis.hexists(self.key, pickled_key))", "title": ""}
{"_id": "d15662", "text": "def getTypeStr(_type):\n  r\"\"\"Gets the string representation of the given type.\n  \"\"\"\n  if isinstance(_type, CustomType):\n    return str(_type)\n\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n\n  return ''", "title": ""}
{"_id": "d15663", "text": "def values(self):\n        \"\"\" :see::meth:RedisMap.keys \"\"\"\n        for val in self._client.hvals(self.key_prefix):\n            yield self._loads(val)", "title": ""}
{"_id": "d15664", "text": "def get_instance(key, expire=None):\n    \"\"\"Return an instance of RedisSet.\"\"\"\n    global _instances\n    try:\n        instance = _instances[key]\n    except KeyError:\n        instance = RedisSet(\n            key,\n            _redis,\n            expire=expire\n        )\n        _instances[key] = instance\n\n    return instance", "title": ""}
{"_id": "d15665", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d15666", "text": "def __setitem__(self, field, value):\n        \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n        return self._client.hset(self.key_prefix, field, self._dumps(value))", "title": ""}
{"_id": "d15667", "text": "def get_week_start_end_day():\n    \"\"\"\n    Get the week start date and end date\n    \"\"\"\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))", "title": ""}
{"_id": "d15668", "text": "def __repr__(self):\n    \"\"\"Returns a stringified representation of this object.\"\"\"\n    return str({'name': self._name, 'watts': self._watts,\n                'type': self._output_type, 'id': self._integration_id})", "title": ""}
{"_id": "d15669", "text": "def _defaultdict(dct, fallback=_illegal_character):\n    \"\"\"Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is\n    accessed.\n    \"\"\"\n    out = defaultdict(lambda: fallback)\n    for k, v in six.iteritems(dct):\n        out[k] = v\n    return out", "title": ""}
{"_id": "d15670", "text": "def unapostrophe(text):\n    \"\"\"Strip apostrophe and 's' from the end of a string.\"\"\"\n    text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)\n    return text", "title": ""}
{"_id": "d15671", "text": "def _validate_input_data(self, data, request):\n        \"\"\" Validate input data.\n\n        :param request: the HTTP request\n        :param data: the parsed data\n        :return: if validation is performed and succeeds the data is converted\n                 into whatever format the validation uses (by default Django's\n                 Forms) If not, the data is returned unchanged.\n        :raises: HttpStatusCodeError if data is not valid\n        \"\"\"\n\n        validator = self._get_input_validator(request)\n        if isinstance(data, (list, tuple)):\n            return map(validator.validate, data)\n        else:\n            return validator.validate(data)", "title": ""}
{"_id": "d15672", "text": "def ismatch(text, pattern):\n    \"\"\"Test whether text contains string or matches regex.\"\"\"\n\n    if hasattr(pattern, 'search'):\n        return pattern.search(text) is not None\n    else:\n        return pattern in text if Config.options.case_sensitive \\\n            else pattern.lower() in text.lower()", "title": ""}
{"_id": "d15673", "text": "def get_numbers(s):\n    \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n    result = map(int, re.findall(r'[0-9]+', unicode(s)))\n    return result + [1] * (2 - len(result))", "title": ""}
{"_id": "d15674", "text": "def now_time(str=False):\n    \"\"\"Get the current time.\"\"\"\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()", "title": ""}
{"_id": "d15675", "text": "def camel_to_snake_case(name):\n    \"\"\"Takes a camelCased string and converts to snake_case.\"\"\"\n    pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])'\n    return '_'.join(map(str.lower, re.findall(pattern, name)))", "title": ""}
{"_id": "d15676", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d15677", "text": "def GetValueByName(self, name):\n    \"\"\"Retrieves a value by name.\n\n    Value names are not unique and pyregf provides first match for the value.\n\n    Args:\n      name (str): name of the value or an empty string for the default value.\n\n    Returns:\n      WinRegistryValue: Windows Registry value if a corresponding value was\n          found or None if not.\n    \"\"\"\n    pyregf_value = self._pyregf_key.get_value_by_name(name)\n    if not pyregf_value:\n      return None\n\n    return REGFWinRegistryValue(pyregf_value)", "title": ""}
{"_id": "d15678", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d15679", "text": "def find_number(regex, s):\n    \"\"\"Find a number using a given regular expression.\n    If the string cannot be found, returns None.\n    The regex should contain one matching group, \n    as only the result of the first group is returned.\n    The group should only contain numeric characters ([0-9]+).\n    \n    s - The string to search.\n    regex - A string containing the regular expression.\n    \n    Returns an integer or None.\n    \"\"\"\n    result = find_string(regex, s)\n    if result is None:\n        return None\n    return int(result)", "title": ""}
{"_id": "d15680", "text": "def hide(self):\n        \"\"\"Hides the main window of the terminal and sets the visible\n        flag to False.\n        \"\"\"\n        if not HidePrevention(self.window).may_hide():\n            return\n        self.hidden = True\n        self.get_widget('window-root').unstick()\n        self.window.hide()", "title": ""}
{"_id": "d15681", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d15682", "text": "def strip_comment_marker(text):\n    \"\"\" Strip # markers at the front of a block of comment text.\n    \"\"\"\n    lines = []\n    for line in text.splitlines():\n        lines.append(line.lstrip('#'))\n    text = textwrap.dedent('\\n'.join(lines))\n    return text", "title": ""}
{"_id": "d15683", "text": "def filter_dict_by_key(d, keys):\n    \"\"\"Filter the dict *d* to remove keys not in *keys*.\"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d15684", "text": "def table_nan_locs(table):\n    \"\"\"\n    from http://stackoverflow.com/a/14033137/623735\n    # gets the indices of the rows with nan values in a dataframe\n    pd.isnull(df).any(1).nonzero()[0]\n    \"\"\"\n    ans = []\n    for rownum, row in enumerate(table):\n        try:\n            if pd.isnull(row).any():\n                colnums = pd.isnull(row).nonzero()[0]\n                ans += [(rownum, colnum) for colnum in colnums]\n        except AttributeError:  # table is really just a sequence of scalars\n            if pd.isnull(row):\n                ans += [(rownum, 0)]\n    return ans", "title": ""}
{"_id": "d15685", "text": "def strip_sdist_extras(filelist):\n    \"\"\"Strip generated files that are only present in source distributions.\n\n    We also strip files that are ignored for other reasons, like\n    command line arguments, setup.cfg rules or MANIFEST.in rules.\n    \"\"\"\n    return [name for name in filelist\n            if not file_matches(name, IGNORE)\n            and not file_matches_regexps(name, IGNORE_REGEXPS)]", "title": ""}
{"_id": "d15686", "text": "def coverage(ctx, opts=\"\"):\n    \"\"\"\n    Execute all tests (normal and slow) with coverage enabled.\n    \"\"\"\n    return test(ctx, coverage=True, include_slow=True, opts=opts)", "title": ""}
{"_id": "d15687", "text": "def _remove_blank(l):\n        \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n        ret = []\n        for i, _ in enumerate(l):\n            if l[i] == 0:\n                break\n            ret.append(l[i])\n        return ret", "title": ""}
{"_id": "d15688", "text": "def init_checks_registry():\n    \"\"\"Register all globally visible functions.\n\n    The first argument name is either 'physical_line' or 'logical_line'.\n    \"\"\"\n    mod = inspect.getmodule(register_check)\n    for (name, function) in inspect.getmembers(mod, inspect.isfunction):\n        register_check(function)", "title": ""}
{"_id": "d15689", "text": "def unpunctuate(s, *, char_blacklist=string.punctuation):\n    \"\"\" Remove punctuation from string s. \"\"\"\n    # remove punctuation\n    s = \"\".join(c for c in s if c not in char_blacklist)\n    # remove consecutive spaces\n    return \" \".join(filter(None, s.split(\" \")))", "title": ""}
{"_id": "d15690", "text": "def interpolate_logscale_single(start, end, coefficient):\n    \"\"\" Cosine interpolation \"\"\"\n    return np.exp(np.log(start) + (np.log(end) - np.log(start)) * coefficient)", "title": ""}
{"_id": "d15691", "text": "def __normalize_list(self, msg):\n        \"\"\"Split message to list by commas and trim whitespace.\"\"\"\n        if isinstance(msg, list):\n            msg = \"\".join(msg)\n        return list(map(lambda x: x.strip(), msg.split(\",\")))", "title": ""}
{"_id": "d15692", "text": "def _normal_prompt(self):\n        \"\"\"\n        Flushes the prompt before requesting the input\n\n        :return: The command line\n        \"\"\"\n        sys.stdout.write(self.__get_ps1())\n        sys.stdout.flush()\n        return safe_input()", "title": ""}
{"_id": "d15693", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d15694", "text": "def open01(x, limit=1.e-6):\n    \"\"\"Constrain numbers to (0,1) interval\"\"\"\n    try:\n        return np.array([min(max(y, limit), 1. - limit) for y in x])\n    except TypeError:\n        return min(max(x, limit), 1. - limit)", "title": ""}
{"_id": "d15695", "text": "def pop (self, key):\n        \"\"\"Remove key from dict and return value.\"\"\"\n        if key in self._keys:\n            self._keys.remove(key)\n        super(ListDict, self).pop(key)", "title": ""}
{"_id": "d15696", "text": "def roundClosestValid(val, res, decimals=None):\n        \"\"\" round to closest resolution \"\"\"\n        if decimals is None and \".\" in str(res):\n            decimals = len(str(res).split('.')[1])\n\n        return round(round(val / res) * res, decimals)", "title": ""}
{"_id": "d15697", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d15698", "text": "def apply_fit(xy,coeffs):\n    \"\"\" Apply the coefficients from a linear fit to\n        an array of x,y positions.\n\n        The coeffs come from the 'coeffs' member of the\n        'fit_arrays()' output.\n    \"\"\"\n    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]\n    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]\n\n    return x_new,y_new", "title": ""}
{"_id": "d15699", "text": "def clean_py_files(path):\n    \"\"\"\n    Removes all .py files.\n\n    :param path: the path\n    :return: None\n    \"\"\"\n\n    for dirname, subdirlist, filelist in os.walk(path):\n\n        for f in filelist:\n            if f.endswith('py'):\n                os.remove(os.path.join(dirname, f))", "title": ""}
{"_id": "d15700", "text": "def get_param_names(cls):\n        \"\"\"Returns a list of plottable CBC parameter variables\"\"\"\n        return [m[0] for m in inspect.getmembers(cls) \\\n            if type(m[1]) == property]", "title": ""}
{"_id": "d15701", "text": "def prune(self, n):\n        \"\"\"prune all but the first (=best) n items\"\"\"\n        if self.minimize:\n            self.data = self.data[:n]\n        else:\n            self.data = self.data[-1 * n:]", "title": ""}
{"_id": "d15702", "text": "def graph_from_dot_file(path):\n    \"\"\"Load graph as defined by a DOT file.\n    \n    The file is assumed to be in DOT format. It will\n    be loaded, parsed and a Dot class will be returned, \n    representing the graph.\n    \"\"\"\n    \n    fd = file(path, 'rb')\n    data = fd.read()\n    fd.close()\n    \n    return graph_from_dot_data(data)", "title": ""}
{"_id": "d15703", "text": "def strip_html(string, keep_tag_content=False):\n    \"\"\"\n    Remove html code contained into the given string.\n\n    :param string: String to manipulate.\n    :type string: str\n    :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).\n    :type keep_tag_content: bool\n    :return: String with html removed.\n    :rtype: str\n    \"\"\"\n    r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE\n    return r.sub('', string)", "title": ""}
{"_id": "d15704", "text": "def pop(h):\n    \"\"\"Pop the heap value from the heap.\"\"\"\n    n = h.size() - 1\n    h.swap(0, n)\n    down(h, 0, n)\n    return h.pop()", "title": ""}
{"_id": "d15705", "text": "def remove_legend(ax=None):\n    \"\"\"Remove legend for axes or gca.\n\n    See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n    \"\"\"\n    from pylab import gca, draw\n    if ax is None:\n        ax = gca()\n    ax.legend_ = None\n    draw()", "title": ""}
{"_id": "d15706", "text": "def print_log(text, *colors):\n    \"\"\"Print a log message to standard error.\"\"\"\n    sys.stderr.write(sprint(\"{}: {}\".format(script_name, text), *colors) + \"\\n\")", "title": ""}
{"_id": "d15707", "text": "def replaceNewlines(string, newlineChar):\n\t\"\"\"There's probably a way to do this with string functions but I was lazy.\n\t\tReplace all instances of \\r or \\n in a string with something else.\"\"\"\n\tif newlineChar in string:\n\t\tsegments = string.split(newlineChar)\n\t\tstring = \"\"\n\t\tfor segment in segments:\n\t\t\tstring += segment\n\treturn string", "title": ""}
{"_id": "d15708", "text": "def next(self):\n        \"\"\"Provides hook for Python2 iterator functionality.\"\"\"\n        _LOGGER.debug(\"reading next\")\n        if self.closed:\n            _LOGGER.debug(\"stream is closed\")\n            raise StopIteration()\n\n        line = self.readline()\n        if not line:\n            _LOGGER.debug(\"nothing more to read\")\n            raise StopIteration()\n\n        return line", "title": ""}
{"_id": "d15709", "text": "def replaceNewlines(string, newlineChar):\n\t\"\"\"There's probably a way to do this with string functions but I was lazy.\n\t\tReplace all instances of \\r or \\n in a string with something else.\"\"\"\n\tif newlineChar in string:\n\t\tsegments = string.split(newlineChar)\n\t\tstring = \"\"\n\t\tfor segment in segments:\n\t\t\tstring += segment\n\treturn string", "title": ""}
{"_id": "d15710", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d15711", "text": "def clean(self, text):\n        \"\"\"Remove all unwanted characters from text.\"\"\"\n        return ''.join([c for c in text if c in self.alphabet])", "title": ""}
{"_id": "d15712", "text": "def PyplotHistogram():\n    \"\"\"\n    =============================================================\n    Demo of the histogram (hist) function with multiple data sets\n    =============================================================\n\n    Plot histogram with multiple sample sets and demonstrate:\n\n        * Use of legend with multiple sample sets\n        * Stacked bars\n        * Step curve with no fill\n        * Data sets of different sample sizes\n\n    Selecting different bin counts and sizes can significantly affect the\n    shape of a histogram. The Astropy docs have a great section on how to\n    select these parameters:\n    http://docs.astropy.org/en/stable/visualization/histogram.html\n    \"\"\"\n\n    import numpy as np\n    import matplotlib.pyplot as plt\n\n    np.random.seed(0)\n\n    n_bins = 10\n    x = np.random.randn(1000, 3)\n\n    fig, axes = plt.subplots(nrows=2, ncols=2)\n    ax0, ax1, ax2, ax3 = axes.flatten()\n\n    colors = ['red', 'tan', 'lime']\n    ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)\n    ax0.legend(prop={'size': 10})\n    ax0.set_title('bars with legend')\n\n    ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)\n    ax1.set_title('stacked bar')\n\n    ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)\n    ax2.set_title('stack step (unfilled)')\n\n    # Make a multiple-histogram of data-sets with different length.\n    x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]\n    ax3.hist(x_multi, n_bins, histtype='bar')\n    ax3.set_title('different sample sizes')\n\n    fig.tight_layout()\n    return fig", "title": ""}
{"_id": "d15713", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d15714", "text": "def _heappush_max(heap, item):\n    \"\"\" why is this not in heapq \"\"\"\n    heap.append(item)\n    heapq._siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d15715", "text": "def _remove_keywords(d):\n    \"\"\"\n    copy the dict, filter_keywords\n\n    Parameters\n    ----------\n    d : dict\n    \"\"\"\n    return { k:v for k, v in iteritems(d) if k not in RESERVED }", "title": ""}
{"_id": "d15716", "text": "def this_week():\n        \"\"\" Return start and end date of the current week. \"\"\"\n        since = TODAY + delta(weekday=MONDAY(-1))\n        until = since + delta(weeks=1)\n        return Date(since), Date(until)", "title": ""}
{"_id": "d15717", "text": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "title": ""}
{"_id": "d15718", "text": "def __grid_widgets(self):\n        \"\"\"Places all the child widgets in the appropriate positions.\"\"\"\n        scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n        self._canvas.grid(row=0, column=1, sticky=\"nswe\")\n        self._scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")", "title": ""}
{"_id": "d15719", "text": "def unescape(str):\n    \"\"\"Undoes the effects of the escape() function.\"\"\"\n    out = ''\n    prev_backslash = False\n    for char in str:\n        if not prev_backslash and char == '\\\\':\n            prev_backslash = True\n            continue\n        out += char\n        prev_backslash = False\n    return out", "title": ""}
{"_id": "d15720", "text": "def retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n\t\"\"\"\n\tGiven a callable func, trap the indicated exceptions\n\tfor up to 'retries' times, invoking cleanup on the\n\texception. On the final attempt, allow any exceptions\n\tto propagate.\n\t\"\"\"\n\tattempts = count() if retries == float('inf') else range(retries)\n\tfor attempt in attempts:\n\t\ttry:\n\t\t\treturn func()\n\t\texcept trap:\n\t\t\tcleanup()\n\n\treturn func()", "title": ""}
{"_id": "d15721", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d15722", "text": "def str2int(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n    return NumConv(radix, alphabet).str2int(num)", "title": ""}
{"_id": "d15723", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d15724", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d15725", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d15726", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d15727", "text": "async def sysinfo(dev: Device):\n    \"\"\"Print out system information (version, MAC addrs).\"\"\"\n    click.echo(await dev.get_system_info())\n    click.echo(await dev.get_interface_information())", "title": ""}
{"_id": "d15728", "text": "def _arrayFromBytes(dataBytes, metadata):\n    \"\"\"Generates and returns a numpy array from raw data bytes.\n\n    :param bytes: raw data bytes as generated by ``numpy.ndarray.tobytes()``\n    :param metadata: a dictionary containing the data type and optionally the\n        shape parameter to reconstruct a ``numpy.array`` from the raw data\n        bytes. ``{\"dtype\": \"float64\", \"shape\": (2, 3)}``\n\n    :returns: ``numpy.array``\n    \"\"\"\n    array = numpy.fromstring(dataBytes, dtype=numpy.typeDict[metadata['dtype']])\n    if 'shape' in metadata:\n        array = array.reshape(metadata['shape'])\n    return array", "title": ""}
{"_id": "d15729", "text": "def dir_exists(self):\n        \"\"\"\n        Makes a ``HEAD`` requests to the URI.\n\n        :returns: ``True`` if status code is 2xx.\n        \"\"\"\n\n        r = requests.request(self.method if self.method else 'HEAD', self.url, **self.storage_args)\n        try: r.raise_for_status()\n        except Exception: return False\n\n        return True", "title": ""}
{"_id": "d15730", "text": "def csv_matrix_print(classes, table):\n    \"\"\"\n    Return matrix as csv data.\n\n    :param classes: classes list\n    :type classes:list\n    :param table: table\n    :type table:dict\n    :return:\n    \"\"\"\n    result = \"\"\n    classes.sort()\n    for i in classes:\n        for j in classes:\n            result += str(table[i][j]) + \",\"\n        result = result[:-1] + \"\\n\"\n    return result[:-1]", "title": ""}
{"_id": "d15731", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d15732", "text": "def getFunction(self):\n        \"\"\"Called by remote workers. Useful to populate main module globals()\n        for interactive shells. Retrieves the serialized function.\"\"\"\n        return functionFactory(\n            self.code,\n            self.name,\n            self.defaults,\n            self.globals,\n            self.imports,\n        )", "title": ""}
{"_id": "d15733", "text": "def make_post_request(self, url, auth, json_payload):\n        \"\"\"This function executes the request with the provided\n        json payload and return the json response\"\"\"\n        response = requests.post(url, auth=auth, json=json_payload)\n        return response.json()", "title": ""}
{"_id": "d15734", "text": "def login(self, username, password=None, token=None):\n        \"\"\"Login user for protected API calls.\"\"\"\n        self.session.basic_auth(username, password)", "title": ""}
{"_id": "d15735", "text": "def scale_image(image, new_width):\n    \"\"\"Resizes an image preserving the aspect ratio.\n    \"\"\"\n    (original_width, original_height) = image.size\n    aspect_ratio = original_height/float(original_width)\n    new_height = int(aspect_ratio * new_width)\n\n    # This scales it wider than tall, since characters are biased\n    new_image = image.resize((new_width*2, new_height))\n    return new_image", "title": ""}
{"_id": "d15736", "text": "def requests_request(method, url, **kwargs):\n    \"\"\"Requests-mock requests.request wrapper.\"\"\"\n    session = local_sessions.session\n    response = session.request(method=method, url=url, **kwargs)\n    session.close()\n    return response", "title": ""}
{"_id": "d15737", "text": "def to_camel(s):\n    \"\"\"\n    :param string s: under_scored string to be CamelCased\n    :return: CamelCase version of input\n    :rtype: str\n    \"\"\"\n    # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n    return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "title": ""}
{"_id": "d15738", "text": "def reset_params(self):\n        \"\"\"Reset all parameters to their default values.\"\"\"\n        self.__params = dict([p, None] for p in self.param_names)\n        self.set_params(self.param_defaults)", "title": ""}
{"_id": "d15739", "text": "def make_post_request(self, url, auth, json_payload):\n        \"\"\"This function executes the request with the provided\n        json payload and return the json response\"\"\"\n        response = requests.post(url, auth=auth, json=json_payload)\n        return response.json()", "title": ""}
{"_id": "d15740", "text": "def arr_to_vector(arr):\n    \"\"\"Reshape a multidimensional array to a vector.\n    \"\"\"\n    dim = array_dim(arr)\n    tmp_arr = []\n    for n in range(len(dim) - 1):\n        for inner in arr:\n            for i in inner:\n                tmp_arr.append(i)\n        arr = tmp_arr\n        tmp_arr = []\n    return arr", "title": ""}
{"_id": "d15741", "text": "def _digits(minval, maxval):\n    \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n    if minval == maxval:\n        return 3\n    else:\n        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "title": ""}
{"_id": "d15742", "text": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "title": ""}
{"_id": "d15743", "text": "def positive_integer(anon, obj, field, val):\n    \"\"\"\n    Returns a random positive integer (for a Django PositiveIntegerField)\n    \"\"\"\n    return anon.faker.positive_integer(field=field)", "title": ""}
{"_id": "d15744", "text": "def get_func_name(func):\n    \"\"\"Return a name which includes the module name and function name.\"\"\"\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n\n    return func_name", "title": ""}
{"_id": "d15745", "text": "def fix_call(callable, *args, **kw):\n    \"\"\"\n    Call ``callable(*args, **kw)`` fixing any type errors that come out.\n    \"\"\"\n    try:\n        val = callable(*args, **kw)\n    except TypeError:\n        exc_info = fix_type_error(None, callable, args, kw)\n        reraise(*exc_info)\n    return val", "title": ""}
{"_id": "d15746", "text": "def distinct(l):\n    \"\"\"\n    Return a list where the duplicates have been removed.\n\n    Args:\n        l (list): the list to filter.\n\n    Returns:\n        list: the same list without duplicates.\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return (_ for _ in l if not (_ in seen or seen_add(_)))", "title": ""}
{"_id": "d15747", "text": "def print_result_from_timeit(stmt='pass', setup='pass', number=1000000):\n    \"\"\"\n    Clean function to know how much time took the execution of one statement\n    \"\"\"\n    units = [\"s\", \"ms\", \"us\", \"ns\"]\n    duration = timeit(stmt, setup, number=int(number))\n    avg_duration = duration / float(number)\n    thousands = int(math.floor(math.log(avg_duration, 1000)))\n\n    print(\"Total time: %fs. Average run: %.3f%s.\" % (\n        duration, avg_duration * (1000 ** -thousands), units[-thousands]))", "title": ""}
{"_id": "d15748", "text": "def _find(string, sub_string, start_index):\n    \"\"\"Return index of sub_string in string.\n\n    Raise TokenError if sub_string is not found.\n    \"\"\"\n    result = string.find(sub_string, start_index)\n    if result == -1:\n        raise TokenError(\"expected '{0}'\".format(sub_string))\n    return result", "title": ""}
{"_id": "d15749", "text": "def return_letters_from_string(text):\n    \"\"\"Get letters from string only.\"\"\"\n    out = \"\"\n    for letter in text:\n        if letter.isalpha():\n            out += letter\n    return out", "title": ""}
{"_id": "d15750", "text": "def move_back(self, dt):\n        \"\"\" If called after an update, the sprite can move back\n        \"\"\"\n        self._position = self._old_position\n        self.rect.topleft = self._position\n        self.feet.midbottom = self.rect.midbottom", "title": ""}
{"_id": "d15751", "text": "def binSearch(arr, val):\n  \"\"\" \n  Function for running binary search on a sorted list.\n\n  :param arr: (list) a sorted list of integers to search\n  :param val: (int)  a integer to search for in the sorted array\n  :returns: (int) the index of the element if it is found and -1 otherwise.\n  \"\"\"\n  i = bisect_left(arr, val)\n  if i != len(arr) and arr[i] == val:\n    return i\n  return -1", "title": ""}
{"_id": "d15752", "text": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "title": ""}
{"_id": "d15753", "text": "def find_nearest_index(arr, value):\n    \"\"\"For a given value, the function finds the nearest value\n    in the array and returns its index.\"\"\"\n    arr = np.array(arr)\n    index = (abs(arr-value)).argmin()\n    return index", "title": ""}
{"_id": "d15754", "text": "def multiply(self, number):\n        \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n        return self.from_list([x * number for x in self.to_list()])", "title": ""}
{"_id": "d15755", "text": "def closest(xarr, val):\n    \"\"\" Return the index of the closest in xarr to value val \"\"\"\n    idx_closest = np.argmin(np.abs(np.array(xarr) - val))\n    return idx_closest", "title": ""}
{"_id": "d15756", "text": "def v_normalize(v):\n    \"\"\"\n    Normalizes the given vector.\n    \n    The vector given may have any number of dimensions.\n    \"\"\"\n    vmag = v_magnitude(v)\n    return [ v[i]/vmag  for i in range(len(v)) ]", "title": ""}
{"_id": "d15757", "text": "def invertDictMapping(d):\n    \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n    inv_map = {}\n    for k, v in d.items():\n        inv_map[v] = inv_map.get(v, [])\n        inv_map[v].append(k)\n    return inv_map", "title": ""}
{"_id": "d15758", "text": "def load(filename):\n    \"\"\"\n    Load the state from the given file, moving to the file's directory during\n    load (temporarily, moving back after loaded)\n\n    Parameters\n    ----------\n    filename : string\n        name of the file to open, should be a .pkl file\n    \"\"\"\n    path, name = os.path.split(filename)\n    path = path or '.'\n\n    with util.indir(path):\n        return pickle.load(open(name, 'rb'))", "title": ""}
{"_id": "d15759", "text": "def rotation_matrix(sigma):\n    \"\"\"\n\n    https://en.wikipedia.org/wiki/Rotation_matrix\n\n    \"\"\"\n\n    radians = sigma * np.pi / 180.0\n\n    r11 = np.cos(radians)\n    r12 = -np.sin(radians)\n    r21 = np.sin(radians)\n    r22 = np.cos(radians)\n\n    R = np.array([[r11, r12], [r21, r22]])\n\n    return R", "title": ""}
{"_id": "d15760", "text": "def readme(filename, encoding='utf8'):\n    \"\"\"\n    Read the contents of a file\n    \"\"\"\n\n    with io.open(filename, encoding=encoding) as source:\n        return source.read()", "title": ""}
{"_id": "d15761", "text": "def _saferound(value, decimal_places):\n    \"\"\"\n    Rounds a float value off to the desired precision\n    \"\"\"\n    try:\n        f = float(value)\n    except ValueError:\n        return ''\n    format = '%%.%df' % decimal_places\n    return format % f", "title": ""}
{"_id": "d15762", "text": "def bin_open(fname: str):\n    \"\"\"\n    Returns a file descriptor for a plain text or gzipped file, binary read mode\n    for subprocess interaction.\n\n    :param fname: The filename to open.\n    :return: File descriptor in binary read mode.\n    \"\"\"\n    if fname.endswith(\".gz\"):\n        return gzip.open(fname, \"rb\")\n    return open(fname, \"rb\")", "title": ""}
{"_id": "d15763", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d15764", "text": "def jsonify(symbol):\n    \"\"\" returns json format for symbol \"\"\"\n    try:\n        # all symbols have a toJson method, try it\n        return json.dumps(symbol.toJson(), indent='  ')\n    except AttributeError:\n        pass\n    return json.dumps(symbol, indent='  ')", "title": ""}
{"_id": "d15765", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d15766", "text": "def _visual_width(line):\n    \"\"\"Get the the number of columns required to display a string\"\"\"\n\n    return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, \"\", line))", "title": ""}
{"_id": "d15767", "text": "def price_rounding(price, decimals=2):\n    \"\"\"Takes a decimal price and rounds to a number of decimal places\"\"\"\n    try:\n        exponent = D('.' + decimals * '0')\n    except InvalidOperation:\n        # Currencies with no decimal places, ex. JPY, HUF\n        exponent = D()\n    return price.quantize(exponent, rounding=ROUND_UP)", "title": ""}
{"_id": "d15768", "text": "def copy_image_on_background(image, color=WHITE):\n    \"\"\"\n    Create a new image by copying the image on a *color* background.\n\n    Args:\n        image (PIL.Image.Image): Image to copy\n        color (tuple): Background color usually WHITE or BLACK\n\n    Returns:\n        PIL.Image.Image\n\n    \"\"\"\n    background = Image.new(\"RGB\", image.size, color)\n    background.paste(image, mask=image.split()[3])\n    return background", "title": ""}
{"_id": "d15769", "text": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "title": ""}
{"_id": "d15770", "text": "def pstd(self, *args, **kwargs):\n        \"\"\" Console to STDOUT \"\"\"\n        kwargs['file'] = self.out\n        self.print(*args, **kwargs)\n        sys.stdout.flush()", "title": ""}
{"_id": "d15771", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d15772", "text": "def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to be padded.\n\n        Returns:\n            PIL Image: Padded image.\n        \"\"\"\n        return F.pad(img, self.padding, self.fill, self.padding_mode)", "title": ""}
{"_id": "d15773", "text": "def get_as_string(self, s3_path, encoding='utf-8'):\n        \"\"\"\n        Get the contents of an object stored in S3 as string.\n\n        :param s3_path: URL for target S3 location\n        :param encoding: Encoding to decode bytes to string\n        :return: File contents as a string\n        \"\"\"\n        content = self.get_as_bytes(s3_path)\n        return content.decode(encoding)", "title": ""}
{"_id": "d15774", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d15775", "text": "def base64ToImage(imgData, out_path, out_file):\n        \"\"\" converts a base64 string to a file \"\"\"\n        fh = open(os.path.join(out_path, out_file), \"wb\")\n        fh.write(imgData.decode('base64'))\n        fh.close()\n        del fh\n        return os.path.join(out_path, out_file)", "title": ""}
{"_id": "d15776", "text": "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig", "title": ""}
{"_id": "d15777", "text": "def draw(graph, fname):\n    \"\"\"Draw a graph and save it into a file\"\"\"\n    ag = networkx.nx_agraph.to_agraph(graph)\n    ag.draw(fname, prog='dot')", "title": ""}
{"_id": "d15778", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d15779", "text": "def _sslobj(sock):\n    \"\"\"Returns the underlying PySLLSocket object with which the C extension\n    functions interface.\n\n    \"\"\"\n    pass\n    if isinstance(sock._sslobj, _ssl._SSLSocket):\n        return sock._sslobj\n    else:\n        return sock._sslobj._sslobj", "title": ""}
{"_id": "d15780", "text": "def see_doc(obj_with_doc):\n    \"\"\"Copy docstring from existing object to the decorated callable.\"\"\"\n    def decorator(fn):\n        fn.__doc__ = obj_with_doc.__doc__\n        return fn\n    return decorator", "title": ""}
{"_id": "d15781", "text": "def scatter(self, *args, **kwargs):\n        \"\"\"Add a scatter plot.\"\"\"\n        cls = _make_class(ScatterVisual,\n                          _default_marker=kwargs.pop('marker', None),\n                          )\n        return self._add_item(cls, *args, **kwargs)", "title": ""}
{"_id": "d15782", "text": "def printdict(adict):\n    \"\"\"printdict\"\"\"\n    dlist = list(adict.keys())\n    dlist.sort()\n    for i in range(0, len(dlist)):\n        print(dlist[i], adict[dlist[i]])", "title": ""}
{"_id": "d15783", "text": "def _cho_factor(A, lower=True, check_finite=True):\n    \"\"\"Implementaton of :func:`scipy.linalg.cho_factor` using\n    a function supported in cupy.\"\"\"\n\n    return cp.linalg.cholesky(A), True", "title": ""}
{"_id": "d15784", "text": "def csv_matrix_print(classes, table):\n    \"\"\"\n    Return matrix as csv data.\n\n    :param classes: classes list\n    :type classes:list\n    :param table: table\n    :type table:dict\n    :return:\n    \"\"\"\n    result = \"\"\n    classes.sort()\n    for i in classes:\n        for j in classes:\n            result += str(table[i][j]) + \",\"\n        result = result[:-1] + \"\\n\"\n    return result[:-1]", "title": ""}
{"_id": "d15785", "text": "def ex(self, cmd):\n        \"\"\"Execute a normal python statement in user namespace.\"\"\"\n        with self.builtin_trap:\n            exec cmd in self.user_global_ns, self.user_ns", "title": ""}
{"_id": "d15786", "text": "def printdict(adict):\n    \"\"\"printdict\"\"\"\n    dlist = list(adict.keys())\n    dlist.sort()\n    for i in range(0, len(dlist)):\n        print(dlist[i], adict[dlist[i]])", "title": ""}
{"_id": "d15787", "text": "def handle_logging(self):\n        \"\"\"\n        To allow devs to log as early as possible, logging will already be\n        handled here\n        \"\"\"\n\n        configure_logging(self.get_scrapy_options())\n\n        # Disable duplicates\n        self.__scrapy_options[\"LOG_ENABLED\"] = False\n\n        # Now, after log-level is correctly set, lets log them.\n        for msg in self.log_output:\n            if msg[\"level\"] is \"error\":\n                self.log.error(msg[\"msg\"])\n            elif msg[\"level\"] is \"info\":\n                self.log.info(msg[\"msg\"])\n            elif msg[\"level\"] is \"debug\":\n                self.log.debug(msg[\"msg\"])", "title": ""}
{"_id": "d15788", "text": "def translate_index_to_position(self, index):\n        \"\"\"\n        Given an index for the text, return the corresponding (row, col) tuple.\n        (0-based. Returns (0, 0) for index=0.)\n        \"\"\"\n        # Find start of this line.\n        row, row_index = self._find_line_start_index(index)\n        col = index - row_index\n\n        return row, col", "title": ""}
{"_id": "d15789", "text": "def printc(cls, txt, color=colors.red):\n        \"\"\"Print in color.\"\"\"\n        print(cls.color_txt(txt, color))", "title": ""}
{"_id": "d15790", "text": "def time2seconds(t):\n    \"\"\"Returns seconds since 0h00.\"\"\"\n    return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6", "title": ""}
{"_id": "d15791", "text": "def format_exception(e):\n    \"\"\"Returns a string containing the type and text of the exception.\n\n    \"\"\"\n    from .utils.printing import fill\n    return '\\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))", "title": ""}
{"_id": "d15792", "text": "def json(body, charset='utf-8', **kwargs):\n    \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n    return json_converter.loads(text(body, charset=charset))", "title": ""}
{"_id": "d15793", "text": "def on_mouse_motion(self, x, y, dx, dy):\n        \"\"\"\n        Pyglet specific mouse motion callback.\n        Forwards and traslates the event to the example\n        \"\"\"\n        # Screen coordinates relative to the lower-left corner\n        # so we have to flip the y axis to make this consistent with\n        # other window libraries\n        self.example.mouse_position_event(x, self.buffer_height - y)", "title": ""}
{"_id": "d15794", "text": "def _file_exists(path, filename):\n  \"\"\"Checks if the filename exists under the path.\"\"\"\n  return os.path.isfile(os.path.join(path, filename))", "title": ""}
{"_id": "d15795", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d15796", "text": "def is_delimiter(line):\n    \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n    return bool(line) and line[0] in punctuation and line[0]*len(line) == line", "title": ""}
{"_id": "d15797", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d15798", "text": "def full(self):\n        \"\"\"Return True if the queue is full\"\"\"\n        if not self.size: return False\n        return len(self.pq) == (self.size + self.removed_count)", "title": ""}
{"_id": "d15799", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d15800", "text": "def selecttrue(table, field, complement=False):\n    \"\"\"Select rows where the given field evaluates `True`.\"\"\"\n\n    return select(table, field, lambda v: bool(v), complement=complement)", "title": ""}
{"_id": "d15801", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d15802", "text": "def adapt_array(arr):\n    \"\"\"\n    Adapts a Numpy array into an ARRAY string to put into the database.\n\n    Parameters\n    ----------\n    arr: array\n        The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file.\n\n    Returns\n    -------\n    ARRAY\n            The adapted array object\n\n    \"\"\"\n    out = io.BytesIO()\n    np.save(out, arr), out.seek(0)\n    return buffer(out.read())", "title": ""}
{"_id": "d15803", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d15804", "text": "def from_series(cls, series):\n        \"\"\"Convert a pandas.Series into an xarray.DataArray.\n\n        If the series's index is a MultiIndex, it will be expanded into a\n        tensor product of one-dimensional coordinates (filling in missing\n        values with NaN). Thus this operation should be the inverse of the\n        `to_series` method.\n        \"\"\"\n        # TODO: add a 'name' parameter\n        name = series.name\n        df = pd.DataFrame({name: series})\n        ds = Dataset.from_dataframe(df)\n        return ds[name]", "title": ""}
{"_id": "d15805", "text": "def ReadTif(tifFile):\n        \"\"\"Reads a tif file to a 2D NumPy array\"\"\"\n        img = Image.open(tifFile)\n        img = np.array(img)\n        return img", "title": ""}
{"_id": "d15806", "text": "def describe_unique_1d(series):\n    \"\"\"Compute summary statistics of a unique (`S_TYPE_UNIQUE`) variable (a Series).\n\n    Parameters\n    ----------\n    series : Series\n        The variable to describe.\n\n    Returns\n    -------\n    Series\n        The description of the variable as a Series with index being stats keys.\n    \"\"\"\n    return pd.Series([base.S_TYPE_UNIQUE], index=['type'], name=series.name)", "title": ""}
{"_id": "d15807", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d15808", "text": "def register_service(self, service):\n        \"\"\"\n            Register service into the system. Called by Services.\n        \"\"\"\n        if service not in self.services:\n            self.services.append(service)", "title": ""}
{"_id": "d15809", "text": "def get_list_from_file(file_name):\n    \"\"\"read the lines from a file into a list\"\"\"\n    with open(file_name, mode='r', encoding='utf-8') as f1:\n        lst = f1.readlines()\n    return lst", "title": ""}
{"_id": "d15810", "text": "def to_snake_case(text):\n    \"\"\"Convert to snake case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d15811", "text": "def get_list_from_file(file_name):\n    \"\"\"read the lines from a file into a list\"\"\"\n    with open(file_name, mode='r', encoding='utf-8') as f1:\n        lst = f1.readlines()\n    return lst", "title": ""}
{"_id": "d15812", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d15813", "text": "def load_data(filename):\n    \"\"\"\n    :rtype : numpy matrix\n    \"\"\"\n    data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n    return data.as_matrix()", "title": ""}
{"_id": "d15814", "text": "def unique(iterable):\n    \"\"\" Returns a list copy in which each item occurs only once (in-order).\n    \"\"\"\n    seen = set()\n    return [x for x in iterable if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d15815", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d15816", "text": "def setPixel(self, x, y, color):\n        \"\"\"Set the pixel at (x,y) to the integers in sequence 'color'.\"\"\"\n        return _fitz.Pixmap_setPixel(self, x, y, color)", "title": ""}
{"_id": "d15817", "text": "def lighting(im, b, c):\n    \"\"\" Adjust image balance and contrast \"\"\"\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)", "title": ""}
{"_id": "d15818", "text": "def reseed_random(seed):\n    \"\"\"Reseed factory.fuzzy's random generator.\"\"\"\n    r = random.Random(seed)\n    random_internal_state = r.getstate()\n    set_random_state(random_internal_state)", "title": ""}
{"_id": "d15819", "text": "def round_sig(x, sig):\n    \"\"\"Round the number to the specified number of significant figures\"\"\"\n    return round(x, sig - int(floor(log10(abs(x)))) - 1)", "title": ""}
{"_id": "d15820", "text": "def __isub__(self, other):\n        \"\"\"Remove all elements of another set from this RangeSet.\"\"\"\n        self._binary_sanity_check(other)\n        set.difference_update(self, other)\n        return self", "title": ""}
{"_id": "d15821", "text": "def getTuple(self):\n        \"\"\" Returns the shape of the region as (x, y, w, h) \"\"\"\n        return (self.x, self.y, self.w, self.h)", "title": ""}
{"_id": "d15822", "text": "def set_font_size(self, size):\n        \"\"\"Convenience method for just changing font size.\"\"\"\n        if self.font.font_size == size:\n            pass\n        else:\n            self.font._set_size(size)", "title": ""}
{"_id": "d15823", "text": "def update_screen(self):\n        \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n        self.clock.tick(self.FPS)\n        pygame.display.update()", "title": ""}
{"_id": "d15824", "text": "def remove_ext(fname):\n    \"\"\"Removes the extension from a filename\n    \"\"\"\n    bn = os.path.basename(fname)\n    return os.path.splitext(bn)[0]", "title": ""}
{"_id": "d15825", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d15826", "text": "def main(argv, version=DEFAULT_VERSION):\n    \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n    tarball = download_setuptools()\n    _install(tarball, _build_install_args(argv))", "title": ""}
{"_id": "d15827", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d15828", "text": "def get_closest_index(myList, myNumber):\n    \"\"\"\n    Assumes myList is sorted. Returns closest value to myNumber.\n    If two numbers are equally close, return the smallest number.\n\n    Parameters\n    ----------\n    myList : array\n        The list in which to find the closest value to myNumber\n    myNumber : float\n        The number to find the closest to in MyList\n\n    Returns\n    -------\n    closest_values_index : int\n        The index in the array of the number closest to myNumber in myList\n    \"\"\"\n    closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n    return closest_values_index", "title": ""}
{"_id": "d15829", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d15830", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d15831", "text": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "title": ""}
{"_id": "d15832", "text": "def safe_rmtree(directory):\n  \"\"\"Delete a directory if it's present. If it's not present, no-op.\"\"\"\n  if os.path.exists(directory):\n    shutil.rmtree(directory, True)", "title": ""}
{"_id": "d15833", "text": "def signal_handler(signal_name, frame):\n    \"\"\"Quit signal handler.\"\"\"\n    sys.stdout.flush()\n    print(\"\\nSIGINT in frame signal received. Quitting...\")\n    sys.stdout.flush()\n    sys.exit(0)", "title": ""}
{"_id": "d15834", "text": "def cleanLines(source, lineSep=os.linesep):\n    \"\"\"\n    :param source: some iterable source (list, file, etc)\n    :param lineSep: string of separators (chars) that must be removed\n    :return: list of non empty lines with removed separators\n    \"\"\"\n    stripped = (line.strip(lineSep) for line in source)\n    return (line for line in stripped if len(line) != 0)", "title": ""}
{"_id": "d15835", "text": "def remove_dups(seq):\n    \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d15836", "text": "def __delitem__(self, resource):\n        \"\"\"Remove resource instance from internal cache\"\"\"\n        self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None)", "title": ""}
{"_id": "d15837", "text": "def partial_fit(self, X, y=None, classes=None, **fit_params):\n        \"\"\"Fit the module.\n\n        If the module is initialized, it is not re-initialized, which\n        means that this method should be used if you want to continue\n        training a model (warm start).\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        classes : array, sahpe (n_classes,)\n          Solely for sklearn compatibility, currently unused.\n\n        **fit_params : dict\n          Additional parameters passed to the ``forward`` method of\n          the module and to the ``self.train_split`` call.\n\n        \"\"\"\n        if not self.initialized_:\n            self.initialize()\n\n        self.notify('on_train_begin', X=X, y=y)\n        try:\n            self.fit_loop(X, y, **fit_params)\n        except KeyboardInterrupt:\n            pass\n        self.notify('on_train_end', X=X, y=y)\n        return self", "title": ""}
{"_id": "d15838", "text": "def split_comma_argument(comma_sep_str):\n    \"\"\"Split a comma separated option into a list.\"\"\"\n    terms = []\n    for term in comma_sep_str.split(','):\n        if term:\n            terms.append(term)\n    return terms", "title": ""}
{"_id": "d15839", "text": "def getbyteslice(self, start, end):\n        \"\"\"Direct access to byte data.\"\"\"\n        c = self._rawarray[start:end]\n        return c", "title": ""}
{"_id": "d15840", "text": "def _remove_empty_items(d, required):\n  \"\"\"Return a new dict with any empty items removed.\n\n  Note that this is not a deep check. If d contains a dictionary which\n  itself contains empty items, those are never checked.\n\n  This method exists to make to_serializable() functions cleaner.\n  We could revisit this some day, but for now, the serialized objects are\n  stripped of empty values to keep the output YAML more compact.\n\n  Args:\n    d: a dictionary\n    required: list of required keys (for example, TaskDescriptors always emit\n      the \"task-id\", even if None)\n\n  Returns:\n    A dictionary with empty items removed.\n  \"\"\"\n\n  new_dict = {}\n  for k, v in d.items():\n    if k in required:\n      new_dict[k] = v\n    elif isinstance(v, int) or v:\n      # \"if v\" would suppress emitting int(0)\n      new_dict[k] = v\n\n  return new_dict", "title": ""}
{"_id": "d15841", "text": "def getbyteslice(self, start, end):\n        \"\"\"Direct access to byte data.\"\"\"\n        c = self._rawarray[start:end]\n        return c", "title": ""}
{"_id": "d15842", "text": "def clean_colnames(df):\n    \"\"\" Cleans the column names on a DataFrame\n    Parameters:\n    df - DataFrame\n        The DataFrame to clean\n    \"\"\"\n    col_list = []\n    for index in range(_dutils.cols(df)):\n        col_list.append(df.columns[index].strip().lower().replace(' ','_'))\n    df.columns = col_list", "title": ""}
{"_id": "d15843", "text": "def partition(a, sz): \n    \"\"\"splits iterables a in equal parts of size sz\"\"\"\n    return [a[i:i+sz] for i in range(0, len(a), sz)]", "title": ""}
{"_id": "d15844", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d15845", "text": "def chunks(iterable, chunk):\n    \"\"\"Yield successive n-sized chunks from an iterable.\"\"\"\n    for i in range(0, len(iterable), chunk):\n        yield iterable[i:i + chunk]", "title": ""}
{"_id": "d15846", "text": "def retry_test(func):\n    \"\"\"Retries the passed function 3 times before failing\"\"\"\n    success = False\n    ex = Exception(\"Unknown\")\n    for i in six.moves.range(3):\n        try:\n            result = func()\n        except Exception as e:\n            time.sleep(1)\n            ex = e\n        else:\n            success = True\n            break\n    if not success:\n        raise ex\n    assert success\n    return result", "title": ""}
{"_id": "d15847", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d15848", "text": "def dashrepl(value):\n    \"\"\"\n    Replace any non-word characters with a dash.\n    \"\"\"\n    patt = re.compile(r'\\W', re.UNICODE)\n    return re.sub(patt, '-', value)", "title": ""}
{"_id": "d15849", "text": "def smooth_array(array, amount=1):\n    \"\"\"\n\n    Returns the nearest-neighbor (+/- amount) smoothed array.\n    This does not modify the array or slice off the funny end points.\n\n    \"\"\"\n    if amount==0: return array\n\n    # we have to store the old values in a temp array to keep the\n    # smoothing from affecting the smoothing\n    new_array = _n.array(array)\n\n    for n in range(len(array)):\n        new_array[n] = smooth(array, n, amount)\n\n    return new_array", "title": ""}
{"_id": "d15850", "text": "def underscore(text):\n    \"\"\"Converts text that may be camelcased into an underscored format\"\"\"\n    return UNDERSCORE[1].sub(r'\\1_\\2', UNDERSCORE[0].sub(r'\\1_\\2', text)).lower()", "title": ""}
{"_id": "d15851", "text": "def algo_exp(x, m, t, b):\n    \"\"\"mono-exponential curve.\"\"\"\n    return m*np.exp(-t*x)+b", "title": ""}
{"_id": "d15852", "text": "def replace_all(filepath, searchExp, replaceExp):\n    \"\"\"\n    Replace all the ocurrences (in a file) of a string with another value.\n    \"\"\"\n    for line in fileinput.input(filepath, inplace=1):\n        if searchExp in line:\n            line = line.replace(searchExp, replaceExp)\n        sys.stdout.write(line)", "title": ""}
{"_id": "d15853", "text": "def _stdout_raw(self, s):\n        \"\"\"Writes the string to stdout\"\"\"\n        print(s, end='', file=sys.stdout)\n        sys.stdout.flush()", "title": ""}
{"_id": "d15854", "text": "def get_neg_infinity(dtype):\n    \"\"\"Return an appropriate positive infinity for this dtype.\n\n    Parameters\n    ----------\n    dtype : np.dtype\n\n    Returns\n    -------\n    fill_value : positive infinity value corresponding to this dtype.\n    \"\"\"\n    if issubclass(dtype.type, (np.floating, np.integer)):\n        return -np.inf\n\n    if issubclass(dtype.type, np.complexfloating):\n        return -np.inf - 1j * np.inf\n\n    return NINF", "title": ""}
{"_id": "d15855", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d15856", "text": "def _sanitize(text):\n    \"\"\"Return sanitized Eidos text field for human readability.\"\"\"\n    d = {'-LRB-': '(', '-RRB-': ')'}\n    return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text)", "title": ""}
{"_id": "d15857", "text": "def unique_list_dicts(dlist, key):\n    \"\"\"Return a list of dictionaries which are sorted for only unique entries.\n\n    :param dlist:\n    :param key:\n    :return list:\n    \"\"\"\n\n    return list(dict((val[key], val) for val in dlist).values())", "title": ""}
{"_id": "d15858", "text": "def _maybe_fill(arr, fill_value=np.nan):\n    \"\"\"\n    if we have a compatible fill_value and arr dtype, then fill\n    \"\"\"\n    if _isna_compat(arr, fill_value):\n        arr.fill(fill_value)\n    return arr", "title": ""}
{"_id": "d15859", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d15860", "text": "def internal_reset(self):\n        \"\"\"\n        internal state reset.\n        used e.g. in unittests\n        \"\"\"\n        log.critical(\"PIA internal_reset()\")\n        self.empty_key_toggle = True\n        self.current_input_char = None\n        self.input_repead = 0", "title": ""}
{"_id": "d15861", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d15862", "text": "def cmd_reindex():\n    \"\"\"Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.\n\n    The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until\n    the rename succeeds.\n    \"\"\"\n    db = connect(args.database)\n    for idx in args.indexes:\n        pg_reindex(db, idx)", "title": ""}
{"_id": "d15863", "text": "def returns(self):\n        \"\"\"The return type for this method in a JSON-compatible format.\n\n        This handles the special case of ``None`` which allows ``type(None)`` also.\n\n        :rtype: str | None\n        \"\"\"\n        return_type = self.signature.return_type\n        none_type = type(None)\n        if return_type is not None and return_type is not none_type:\n            return return_type.__name__", "title": ""}
{"_id": "d15864", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d15865", "text": "def Fsphere(q, R):\n    \"\"\"Scattering form-factor amplitude of a sphere normalized to F(q=0)=V\n\n    Inputs:\n    -------\n        ``q``: independent variable\n        ``R``: sphere radius\n\n    Formula:\n    --------\n        ``4*pi/q^3 * (sin(qR) - qR*cos(qR))``\n    \"\"\"\n    return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R * np.cos(q * R))", "title": ""}
{"_id": "d15866", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d15867", "text": "def process_docstring(app, what, name, obj, options, lines):\n    \"\"\"Process the docstring for a given python object.\n\n    Called when autodoc has read and processed a docstring. `lines` is a list\n    of docstring lines that `_process_docstring` modifies in place to change\n    what Sphinx outputs.\n\n    The following settings in conf.py control what styles of docstrings will\n    be parsed:\n\n    * ``napoleon_google_docstring`` -- parse Google style docstrings\n    * ``napoleon_numpy_docstring`` -- parse NumPy style docstrings\n\n    Parameters\n    ----------\n    app : sphinx.application.Sphinx\n        Application object representing the Sphinx process.\n    what : str\n        A string specifying the type of the object to which the docstring\n        belongs. Valid values: \"module\", \"class\", \"exception\", \"function\",\n        \"method\", \"attribute\".\n    name : str\n        The fully qualified name of the object.\n    obj : module, class, exception, function, method, or attribute\n        The object to which the docstring belongs.\n    options : sphinx.ext.autodoc.Options\n        The options given to the directive: an object with attributes\n        inherited_members, undoc_members, show_inheritance and noindex that\n        are True if the flag option of same name was given to the auto\n        directive.\n    lines : list of str\n        The lines of the docstring, see above.\n\n        .. note:: `lines` is modified *in place*\n\n    Notes\n    -----\n    This function is (to most parts) taken from the :mod:`sphinx.ext.napoleon`\n    module, sphinx version 1.3.1, and adapted to the classes defined here\"\"\"\n    result_lines = lines\n    if app.config.napoleon_numpy_docstring:\n        docstring = ExtendedNumpyDocstring(\n            result_lines, app.config, app, what, name, obj, options)\n        result_lines = docstring.lines()\n    if app.config.napoleon_google_docstring:\n        docstring = ExtendedGoogleDocstring(\n            result_lines, app.config, app, what, name, obj, options)\n        result_lines = docstring.lines()\n\n    lines[:] = result_lines[:]", "title": ""}
{"_id": "d15868", "text": "def parse_code(url):\n    \"\"\"\n    Parse the code parameter from the a URL\n\n    :param str url: URL to parse\n    :return: code query parameter\n    :rtype: str\n    \"\"\"\n    result = urlparse(url)\n    query = parse_qs(result.query)\n    return query['code']", "title": ""}
{"_id": "d15869", "text": "def partition(a, sz): \n    \"\"\"splits iterables a in equal parts of size sz\"\"\"\n    return [a[i:i+sz] for i in range(0, len(a), sz)]", "title": ""}
{"_id": "d15870", "text": "def json_response(data, status=200):\n    \"\"\"Return a JsonResponse. Make sure you have django installed first.\"\"\"\n    from django.http import JsonResponse\n    return JsonResponse(data=data, status=status, safe=isinstance(data, dict))", "title": ""}
{"_id": "d15871", "text": "def chunked(l, n):\n    \"\"\"Chunk one big list into few small lists.\"\"\"\n    return [l[i:i + n] for i in range(0, len(l), n)]", "title": ""}
{"_id": "d15872", "text": "def prompt_yes_or_no(message):\n    \"\"\" prompt_yes_or_no: Prompt user to reply with a y/n response\n        Args: None\n        Returns: None\n    \"\"\"\n    user_input = input(\"{} [y/n]:\".format(message)).lower()\n    if user_input.startswith(\"y\"):\n        return True\n    elif user_input.startswith(\"n\"):\n        return False\n    else:\n        return prompt_yes_or_no(message)", "title": ""}
{"_id": "d15873", "text": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "title": ""}
{"_id": "d15874", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d15875", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d15876", "text": "def get_sql(query):\n    \"\"\" Returns the sql query \"\"\"\n    sql = str(query.statement.compile(dialect=sqlite.dialect(),\n                                      compile_kwargs={\"literal_binds\": True}))\n    return sql", "title": ""}
{"_id": "d15877", "text": "def rotate_point(xorigin, yorigin, x, y, angle):\n    \"\"\"Rotate the given point by angle\n    \"\"\"\n    rotx = (x - xorigin) * np.cos(angle) - (y - yorigin) * np.sin(angle)\n    roty = (x - yorigin) * np.sin(angle) + (y - yorigin) * np.cos(angle)\n    return rotx, roty", "title": ""}
{"_id": "d15878", "text": "def forceupdate(self, *args, **kw):\n        \"\"\"Like a bulk :meth:`forceput`.\"\"\"\n        self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)", "title": ""}
{"_id": "d15879", "text": "def _shutdown_transport(self):\n        \"\"\"Unwrap a Python 2.6 SSL socket, so we can call shutdown()\"\"\"\n        if self.sock is not None:\n            try:\n                unwrap = self.sock.unwrap\n            except AttributeError:\n                return\n            try:\n                self.sock = unwrap()\n            except ValueError:\n                # Failure within SSL might mean unwrap exists but socket is not\n                # deemed wrapped\n                pass", "title": ""}
{"_id": "d15880", "text": "def rotateImage(img, angle):\n    \"\"\"\n\n    querries scipy.ndimage.rotate routine\n    :param img: image to be rotated\n    :param angle: angle to be rotated (radian)\n    :return: rotated image\n    \"\"\"\n    imgR = scipy.ndimage.rotate(img, angle, reshape=False)\n    return imgR", "title": ""}
{"_id": "d15881", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d15882", "text": "def round_figures(x, n):\n    \"\"\"Returns x rounded to n significant figures.\"\"\"\n    return round(x, int(n - math.ceil(math.log10(abs(x)))))", "title": ""}
{"_id": "d15883", "text": "def start():\n    \"\"\"Starts the web server.\"\"\"\n    global app\n    bottle.run(app, host=conf.WebHost, port=conf.WebPort,\n               debug=conf.WebAutoReload, reloader=conf.WebAutoReload,\n               quiet=conf.WebQuiet)", "title": ""}
{"_id": "d15884", "text": "def round_sig(x, sig):\n    \"\"\"Round the number to the specified number of significant figures\"\"\"\n    return round(x, sig - int(floor(log10(abs(x)))) - 1)", "title": ""}
{"_id": "d15885", "text": "def _callable_once(func):\n    \"\"\" Returns a function that is only callable once; any other call will do nothing \"\"\"\n\n    def once(*args, **kwargs):\n        if not once.called:\n            once.called = True\n            return func(*args, **kwargs)\n\n    once.called = False\n    return once", "title": ""}
{"_id": "d15886", "text": "def command_py2to3(args):\n    \"\"\"\n    Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n    \"\"\"\n    from lib2to3.main import main\n    sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "title": ""}
{"_id": "d15887", "text": "def getFunction(self):\n        \"\"\"Called by remote workers. Useful to populate main module globals()\n        for interactive shells. Retrieves the serialized function.\"\"\"\n        return functionFactory(\n            self.code,\n            self.name,\n            self.defaults,\n            self.globals,\n            self.imports,\n        )", "title": ""}
{"_id": "d15888", "text": "def get_code(module):\n    \"\"\"\n    Compile and return a Module's code object.\n    \"\"\"\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()", "title": ""}
{"_id": "d15889", "text": "def _session_set(self, key, value):\n        \"\"\"\n        Saves a value to session.\n        \"\"\"\n\n        self.session[self._session_key(key)] = value", "title": ""}
{"_id": "d15890", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d15891", "text": "def __str__(self):\n        \"\"\"Executes self.function to convert LazyString instance to a real\n        str.\"\"\"\n        if not hasattr(self, '_str'):\n            self._str=self.function(*self.args, **self.kwargs)\n        return self._str", "title": ""}
{"_id": "d15892", "text": "def write_json_corpus(documents, fnm):\n    \"\"\"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.\n    \"\"\"\n    with codecs.open(fnm, 'wb', 'ascii') as f:\n        for document in documents:\n            f.write(json.dumps(document) + '\\n')\n    return documents", "title": ""}
{"_id": "d15893", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d15894", "text": "def save_keras_definition(keras_model, path):\n    \"\"\"\n    Save a Keras model definition to JSON with given path\n    \"\"\"\n    model_json = keras_model.to_json()\n    with open(path, \"w\") as json_file:\n        json_file.write(model_json)", "title": ""}
{"_id": "d15895", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d15896", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d15897", "text": "def file_to_png(fp):\n\t\"\"\"Convert an image to PNG format with Pillow.\n\t\n\t:arg file-like fp: The image file.\n\t:rtype: bytes\n\t\"\"\"\n\timport PIL.Image # pylint: disable=import-error\n\twith io.BytesIO() as dest:\n\t\tPIL.Image.open(fp).save(dest, \"PNG\", optimize=True)\n\t\treturn dest.getvalue()", "title": ""}
{"_id": "d15898", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d15899", "text": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "title": ""}
{"_id": "d15900", "text": "def clean_float(v):\n    \"\"\"Remove commas from a float\"\"\"\n\n    if v is None or not str(v).strip():\n        return None\n\n    return float(str(v).replace(',', ''))", "title": ""}
{"_id": "d15901", "text": "def test():        \n    \"\"\"Local test.\"\"\"\n    from spyder.utils.qthelpers import qapplication\n    app = qapplication()\n    dlg = ProjectDialog(None)\n    dlg.show()\n    sys.exit(app.exec_())", "title": ""}
{"_id": "d15902", "text": "def findLastCharIndexMatching(text, func):\n    \"\"\" Return index of last character in string for which func(char) evaluates to True. \"\"\"\n    for i in range(len(text) - 1, -1, -1):\n      if func(text[i]):\n        return i", "title": ""}
{"_id": "d15903", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d15904", "text": "def unique_element(ll):\n    \"\"\" returns unique elements from a list preserving the original order \"\"\"\n    seen = {}\n    result = []\n    for item in ll:\n        if item in seen:\n            continue\n        seen[item] = 1\n        result.append(item)\n    return result", "title": ""}
{"_id": "d15905", "text": "def _count_leading_whitespace(text):\n  \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n  idx = 0\n  for idx, char in enumerate(text):\n    if not char.isspace():\n      return idx\n  return idx + 1", "title": ""}
{"_id": "d15906", "text": "def close(self):\n        \"\"\"Close child subprocess\"\"\"\n        if self._subprocess is not None:\n            os.killpg(self._subprocess.pid, signal.SIGTERM)\n            self._subprocess = None", "title": ""}
{"_id": "d15907", "text": "def _convert_to_float_if_possible(s):\n    \"\"\"\n    A small helper function to convert a string to a numeric value\n    if appropriate\n\n    :param s: the string to be converted\n    :type s: str\n    \"\"\"\n    try:\n        ret = float(s)\n    except (ValueError, TypeError):\n        ret = s\n    return ret", "title": ""}
{"_id": "d15908", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d15909", "text": "def lin_interp(x, rangeX, rangeY):\n    \"\"\"\n    Interpolate linearly variable x in rangeX onto rangeY.\n    \"\"\"\n    s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])\n    y = rangeY[0] * (1 - s) + rangeY[1] * s\n    return y", "title": ""}
{"_id": "d15910", "text": "def process_kill(pid, sig=None):\n    \"\"\"Send signal to process.\n    \"\"\"\n    sig = sig or signal.SIGTERM\n    os.kill(pid, sig)", "title": ""}
{"_id": "d15911", "text": "def parse_case_snake_to_camel(snake, upper_first=True):\n\t\"\"\"\n\tConvert a string from snake_case to CamelCase.\n\n\t:param str snake: The snake_case string to convert.\n\t:param bool upper_first: Whether or not to capitalize the first\n\t\tcharacter of the string.\n\t:return: The CamelCase version of string.\n\t:rtype: str\n\t\"\"\"\n\tsnake = snake.split('_')\n\tfirst_part = snake[0]\n\tif upper_first:\n\t\tfirst_part = first_part.title()\n\treturn first_part + ''.join(word.title() for word in snake[1:])", "title": ""}
{"_id": "d15912", "text": "def destroy(self):\n\t\t\"\"\"Finish up a session.\n\t\t\"\"\"\n\t\tif self.session_type == 'bash':\n\t\t\t# TODO: does this work/handle already being logged out/logged in deep OK?\n\t\t\tself.logout()\n\t\telif self.session_type == 'vagrant':\n\t\t\t# TODO: does this work/handle already being logged out/logged in deep OK?\n\t\t\tself.logout()", "title": ""}
{"_id": "d15913", "text": "def fail(message=None, exit_status=None):\n    \"\"\"Prints the specified message and exits the program with the specified\n    exit status.\n\n    \"\"\"\n    print('Error:', message, file=sys.stderr)\n    sys.exit(exit_status or 1)", "title": ""}
{"_id": "d15914", "text": "def text_remove_empty_lines(text):\n    \"\"\"\n    Whitespace normalization:\n\n      - Strip empty lines\n      - Strip trailing whitespace\n    \"\"\"\n    lines = [ line.rstrip()  for line in text.splitlines()  if line.strip() ]\n    return \"\\n\".join(lines)", "title": ""}
{"_id": "d15915", "text": "def ylim(self, low, high, index=1):\n        \"\"\"Set yaxis limits.\n\n        Parameters\n        ----------\n        low : number\n        high : number\n        index : int, optional\n\n        Returns\n        -------\n        Chart\n\n        \"\"\"\n        self.layout['yaxis' + str(index)]['range'] = [low, high]\n        return self", "title": ""}
{"_id": "d15916", "text": "def _repr_strip(mystring):\n    \"\"\"\n    Returns the string without any initial or final quotes.\n    \"\"\"\n    r = repr(mystring)\n    if r.startswith(\"'\") and r.endswith(\"'\"):\n        return r[1:-1]\n    else:\n        return r", "title": ""}
{"_id": "d15917", "text": "def ylim(self, low, high, index=1):\n        \"\"\"Set yaxis limits.\n\n        Parameters\n        ----------\n        low : number\n        high : number\n        index : int, optional\n\n        Returns\n        -------\n        Chart\n\n        \"\"\"\n        self.layout['yaxis' + str(index)]['range'] = [low, high]\n        return self", "title": ""}
{"_id": "d15918", "text": "def barray(iterlines):\n    \"\"\"\n    Array of bytes\n    \"\"\"\n    lst = [line.encode('utf-8') for line in iterlines]\n    arr = numpy.array(lst)\n    return arr", "title": ""}
{"_id": "d15919", "text": "def set_gradclip_const(self, min_value, max_value):\n        \"\"\"\n        Configure constant clipping settings.\n\n\n        :param min_value: the minimum value to clip by\n        :param max_value: the maxmimum value to clip by\n        \"\"\"\n        callBigDlFunc(self.bigdl_type, \"setConstantClip\", self.value, min_value, max_value)", "title": ""}
{"_id": "d15920", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d15921", "text": "def connect(self):\n        \"\"\"Connects to the given host\"\"\"\n        self.socket = socket.create_connection(self.address, self.timeout)", "title": ""}
{"_id": "d15922", "text": "def kill_all(self, kill_signal, kill_shell=False):\n        \"\"\"Kill all running processes.\"\"\"\n        for key in self.processes.keys():\n            self.kill_process(key, kill_signal, kill_shell)", "title": ""}
{"_id": "d15923", "text": "def set_cursor_position(self, position):\n        \"\"\"Set cursor position\"\"\"\n        position = self.get_position(position)\n        cursor = self.textCursor()\n        cursor.setPosition(position)\n        self.setTextCursor(cursor)\n        self.ensureCursorVisible()", "title": ""}
{"_id": "d15924", "text": "def _finish(self):\n        \"\"\"\n        Closes and waits for subprocess to exit.\n        \"\"\"\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", "title": ""}
{"_id": "d15925", "text": "def _set_axis_limits(self, which, lims, d, scale, reverse=False):\n        \"\"\"Private method for setting axis limits.\n\n        Sets the axis limits on each axis for an individual plot.\n\n        Args:\n            which (str): The indicator of which part of the plots\n                to adjust. This currently handles `x` and `y`.\n            lims (len-2 list of floats): The limits for the axis.\n            d (float): Amount to increment by between the limits.\n            scale (str): Scale of the axis. Either `log` or `lin`.\n            reverse (bool, optional): If True, reverse the axis tick marks. Default is False.\n\n        \"\"\"\n        setattr(self.limits, which + 'lims', lims)\n        setattr(self.limits, 'd' + which, d)\n        setattr(self.limits, which + 'scale', scale)\n\n        if reverse:\n            setattr(self.limits, 'reverse_' + which + '_axis', True)\n        return", "title": ""}
{"_id": "d15926", "text": "def downsample_with_striding(array, factor):\n    \"\"\"Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x.\n    \"\"\"\n    return array[tuple(np.s_[::f] for f in factor)]", "title": ""}
{"_id": "d15927", "text": "def relative_path(path):\n    \"\"\"\n    Return the given path relative to this file.\n    \"\"\"\n    return os.path.join(os.path.dirname(__file__), path)", "title": ""}
{"_id": "d15928", "text": "def dropna(self, subset=None):\n        \"\"\"Remove missing values according to Baloo's convention.\n\n        Parameters\n        ----------\n        subset : list of str, optional\n            Which columns to check for missing values in.\n\n        Returns\n        -------\n        DataFrame\n            DataFrame with no null values in columns.\n\n        \"\"\"\n        subset = check_and_obtain_subset_columns(subset, self)\n        not_nas = [v.notna() for v in self[subset]._iter()]\n        and_filter = reduce(lambda x, y: x & y, not_nas)\n\n        return self[and_filter]", "title": ""}
{"_id": "d15929", "text": "def GetPythonLibraryDirectoryPath():\n  \"\"\"Retrieves the Python library directory path.\"\"\"\n  path = sysconfig.get_python_lib(True)\n  _, _, path = path.rpartition(sysconfig.PREFIX)\n\n  if path.startswith(os.sep):\n    path = path[1:]\n\n  return path", "title": ""}
{"_id": "d15930", "text": "def dump_parent(self, obj):\n        \"\"\"Dump the parent of a PID.\"\"\"\n        if not self._is_parent(obj):\n            return self._dump_relative(obj.pid)\n        return None", "title": ""}
{"_id": "d15931", "text": "def title(msg):\n    \"\"\"Sets the title of the console window.\"\"\"\n    if sys.platform.startswith(\"win\"):\n        ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "title": ""}
{"_id": "d15932", "text": "def disown(cmd):\n    \"\"\"Call a system command in the background,\n       disown it and hide it's output.\"\"\"\n    subprocess.Popen(cmd,\n                     stdout=subprocess.DEVNULL,\n                     stderr=subprocess.DEVNULL)", "title": ""}
{"_id": "d15933", "text": "def sort_fn_list(fn_list):\n    \"\"\"Sort input filename list by datetime\n    \"\"\"\n    dt_list = get_dt_list(fn_list)\n    fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]\n    return fn_list_sort", "title": ""}
{"_id": "d15934", "text": "def test_SVD(pca):\n    \"\"\"\n    Function to test the validity of singular\n    value decomposition by reconstructing original\n    data.\n    \"\"\"\n    _ = pca\n    rec = N.dot(_.U,N.dot(_.sigma,_.V))\n    assert N.allclose(_.arr,rec)", "title": ""}
{"_id": "d15935", "text": "def sort_data(data, cols):\n    \"\"\"Sort `data` rows and order columns\"\"\"\n    return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "title": ""}
{"_id": "d15936", "text": "def inside_softimage():\n    \"\"\"Returns a boolean indicating if the code is executed 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", "title": ""}
{"_id": "d15937", "text": "def set_float(self, option, value):\n        \"\"\"Set a float option.\n\n            Args:\n                option (str): name of option.\n                value (float): value of the option.\n\n            Raises:\n                TypeError: Value must be a float.\n        \"\"\"\n        if not isinstance(value, float):\n            raise TypeError(\"Value must be a float\")\n        self.options[option] = value", "title": ""}
{"_id": "d15938", "text": "def symbols():\n    \"\"\"Return a list of symbols.\"\"\"\n    symbols = []\n    for line in symbols_stream():\n        symbols.append(line.decode('utf-8').strip())\n    return symbols", "title": ""}
{"_id": "d15939", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d15940", "text": "def fn_abs(self, value):\n        \"\"\"\n        Return the absolute value of a number.\n\n        :param value: The number.\n        :return: The absolute value of the number.\n        \"\"\"\n\n        if is_ndarray(value):\n            return numpy.absolute(value)\n        else:\n            return abs(value)", "title": ""}
{"_id": "d15941", "text": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "title": ""}
{"_id": "d15942", "text": "def main(argv=None):\n  \"\"\"Run a Tensorflow model on the Iris dataset.\"\"\"\n  args = parse_arguments(sys.argv if argv is None else argv)\n\n  tf.logging.set_verbosity(tf.logging.INFO)\n  learn_runner.run(\n      experiment_fn=get_experiment_fn(args),\n      output_dir=args.job_dir)", "title": ""}
{"_id": "d15943", "text": "def column_stack_2d(data):\n    \"\"\"Perform column-stacking on a list of 2d data blocks.\"\"\"\n    return list(list(itt.chain.from_iterable(_)) for _ in zip(*data))", "title": ""}
{"_id": "d15944", "text": "def is_integer(obj):\n    \"\"\"Is this an integer.\n\n    :param object obj:\n    :return:\n    \"\"\"\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))", "title": ""}
{"_id": "d15945", "text": "def server(port):\n    \"\"\"Start the Django dev server.\"\"\"\n    args = ['python', 'manage.py', 'runserver']\n    if port:\n        args.append(port)\n    run.main(args)", "title": ""}
{"_id": "d15946", "text": "def _writable_dir(path):\n    \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n    return os.path.isdir(path) and os.access(path, os.W_OK)", "title": ""}
{"_id": "d15947", "text": "def timeout_thread_handler(timeout, stop_event):\n    \"\"\"A background thread to kill the process if it takes too long.\n\n    Args:\n        timeout (float): The number of seconds to wait before killing\n            the process.\n        stop_event (Event): An optional event to cleanly stop the background\n            thread if required during testing.\n    \"\"\"\n\n    stop_happened = stop_event.wait(timeout)\n    if stop_happened is False:\n        print(\"Killing program due to %f second timeout\" % timeout)\n\n    os._exit(2)", "title": ""}
{"_id": "d15948", "text": "def remove_stopped_threads (self):\n        \"\"\"Remove the stopped threads from the internal thread list.\"\"\"\n        self.threads = [t for t in self.threads if t.is_alive()]", "title": ""}
{"_id": "d15949", "text": "def open_store_variable(self, name, var):\n        \"\"\"Turn CDMRemote variable into something like a numpy.ndarray.\"\"\"\n        data = indexing.LazilyOuterIndexedArray(CDMArrayWrapper(name, self))\n        return Variable(var.dimensions, data, {a: getattr(var, a) for a in var.ncattrs()})", "title": ""}
{"_id": "d15950", "text": "def normalize_time(timestamp):\n    \"\"\"Normalize time in arbitrary timezone to UTC naive object.\"\"\"\n    offset = timestamp.utcoffset()\n    if offset is None:\n        return timestamp\n    return timestamp.replace(tzinfo=None) - offset", "title": ""}
{"_id": "d15951", "text": "def on_error(e):  # pragma: no cover\n    \"\"\"Error handler\n\n    RuntimeError or ValueError exceptions raised by commands will be handled\n    by this function.\n    \"\"\"\n    exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'}\n    sys.stderr.write('{}: {}\\n'.format(exname[e.__class__.__name__], str(e)))\n    sys.stderr.write('See file slam_error.log for additional details.\\n')\n    sys.exit(1)", "title": ""}
{"_id": "d15952", "text": "def prevmonday(num):\n    \"\"\"\n    Return unix SECOND timestamp of \"num\" mondays ago\n    \"\"\"\n    today = get_today()\n    lastmonday = today - timedelta(days=today.weekday(), weeks=num)\n    return lastmonday", "title": ""}
{"_id": "d15953", "text": "def _listify(collection):\n        \"\"\"This is a workaround where Collections are no longer iterable\n        when using JPype.\"\"\"\n        new_list = []\n        for index in range(len(collection)):\n            new_list.append(collection[index])\n        return new_list", "title": ""}
{"_id": "d15954", "text": "def _shutdown_proc(p, timeout):\n  \"\"\"Wait for a proc to shut down, then terminate or kill it after `timeout`.\"\"\"\n  freq = 10  # how often to check per second\n  for _ in range(1 + timeout * freq):\n    ret = p.poll()\n    if ret is not None:\n      logging.info(\"Shutdown gracefully.\")\n      return ret\n    time.sleep(1 / freq)\n  logging.warning(\"Killing the process.\")\n  p.kill()\n  return p.wait()", "title": ""}
{"_id": "d15955", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d15956", "text": "def to_unix(cls, timestamp):\n        \"\"\" Wrapper over time module to produce Unix epoch time as a float \"\"\"\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", "title": ""}
{"_id": "d15957", "text": "def _repr_strip(mystring):\n    \"\"\"\n    Returns the string without any initial or final quotes.\n    \"\"\"\n    r = repr(mystring)\n    if r.startswith(\"'\") and r.endswith(\"'\"):\n        return r[1:-1]\n    else:\n        return r", "title": ""}
{"_id": "d15958", "text": "def normalize_time(timestamp):\n    \"\"\"Normalize time in arbitrary timezone to UTC naive object.\"\"\"\n    offset = timestamp.utcoffset()\n    if offset is None:\n        return timestamp\n    return timestamp.replace(tzinfo=None) - offset", "title": ""}
{"_id": "d15959", "text": "def split(s):\n  \"\"\"Uses dynamic programming to infer the location of spaces in a string without spaces.\"\"\"\n  l = [_split(x) for x in _SPLIT_RE.split(s)]\n  return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d15960", "text": "def __run(self):\n    \"\"\"Hacked run function, which installs the trace.\"\"\"\n    sys.settrace(self.globaltrace)\n    self.__run_backup()\n    self.run = self.__run_backup", "title": ""}
{"_id": "d15961", "text": "def to_snake_case(s):\n    \"\"\"Converts camel-case identifiers to snake-case.\"\"\"\n    return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)", "title": ""}
{"_id": "d15962", "text": "def keyReleaseEvent(self, event):\n        \"\"\"\n        Pyqt specific key release callback function.\n        Translates and forwards events to :py:func:`keyboard_event`.\n        \"\"\"\n        self.keyboard_event(event.key(), self.keys.ACTION_RELEASE, 0)", "title": ""}
{"_id": "d15963", "text": "def _swap_rows(self, i, j):\n        \"\"\"Swap i and j rows\n\n        As the side effect, determinant flips.\n\n        \"\"\"\n\n        L = np.eye(3, dtype='intc')\n        L[i, i] = 0\n        L[j, j] = 0\n        L[i, j] = 1\n        L[j, i] = 1\n        self._L.append(L.copy())\n        self._A = np.dot(L, self._A)", "title": ""}
{"_id": "d15964", "text": "def input(self, prompt, default=None, show_default=True):\n        \"\"\"Provide a command prompt.\"\"\"\n        return click.prompt(prompt, default=default, show_default=show_default)", "title": ""}
{"_id": "d15965", "text": "def askopenfilename(**kwargs):\n    \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n    try:\n        from Tkinter import Tk\n        import tkFileDialog as filedialog\n    except ImportError:\n        from tkinter import Tk, filedialog\n    root = Tk()\n    root.withdraw()\n    root.update()\n    filenames = filedialog.askopenfilename(**kwargs)\n    root.destroy()\n    return filenames", "title": ""}
{"_id": "d15966", "text": "def get_dt_list(fn_list):\n    \"\"\"Get list of datetime objects, extracted from a filename\n    \"\"\"\n    dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])\n    return dt_list", "title": ""}
{"_id": "d15967", "text": "def toggle_word_wrap(self):\n        \"\"\"\n        Toggles document word wrap.\n\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        self.setWordWrapMode(not self.wordWrapMode() and QTextOption.WordWrap or QTextOption.NoWrap)\n        return True", "title": ""}
{"_id": "d15968", "text": "def unique_inverse(item_list):\n    \"\"\"\n    Like np.unique(item_list, return_inverse=True)\n    \"\"\"\n    import utool as ut\n    unique_items = ut.unique(item_list)\n    inverse = list_alignment(unique_items, item_list)\n    return unique_items, inverse", "title": ""}
{"_id": "d15969", "text": "def hide(self):\n        \"\"\"Hide the window.\"\"\"\n        self.tk.withdraw()\n        self._visible = False\n        if self._modal:\n            self.tk.grab_release()", "title": ""}
{"_id": "d15970", "text": "def forward(self, step):\n        \"\"\"Move the turtle forward.\n\n        :param step: Integer. Distance to move forward.\n        \"\"\"\n        x = self.pos_x + math.cos(math.radians(self.rotation)) * step\n        y = self.pos_y + math.sin(math.radians(self.rotation)) * step\n        prev_brush_state = self.brush_on\n        self.brush_on = True\n        self.move(x, y)\n        self.brush_on = prev_brush_state", "title": ""}
{"_id": "d15971", "text": "def empty(self):\n        \"\"\"remove all children from the widget\"\"\"\n        for k in list(self.children.keys()):\n            self.remove_child(self.children[k])", "title": ""}
{"_id": "d15972", "text": "def set_stop_handler(self):\n        \"\"\"\n        Initializes functions that are invoked when the user or OS wants to kill this process.\n        :return:\n        \"\"\"\n        signal.signal(signal.SIGTERM, self.graceful_stop)\n        signal.signal(signal.SIGABRT, self.graceful_stop)\n        signal.signal(signal.SIGINT, self.graceful_stop)", "title": ""}
{"_id": "d15973", "text": "def __init__(self, master=None, compound=tk.RIGHT, autohidescrollbar=True, **kwargs):\n        \"\"\"\n        Create a Listbox with a vertical scrollbar.\n\n        :param master: master widget\n        :type master: widget\n        :param compound: side for the Scrollbar to be on (:obj:`tk.LEFT` or :obj:`tk.RIGHT`)\n        :type compound: str\n        :param autohidescrollbar: whether to use an :class:`~ttkwidgets.AutoHideScrollbar` or a :class:`ttk.Scrollbar`\n        :type autohidescrollbar: bool\n        :param kwargs: keyword arguments passed on to the :class:`tk.Listbox` initializer\n        \"\"\"\n        ttk.Frame.__init__(self, master)\n        self.columnconfigure(1, weight=1)\n        self.rowconfigure(0, weight=1)\n        self.listbox = tk.Listbox(self, **kwargs)\n        if autohidescrollbar:\n            self.scrollbar = AutoHideScrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n        else:\n            self.scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n        self.config_listbox(yscrollcommand=self.scrollbar.set)\n        if compound is not tk.LEFT and compound is not tk.RIGHT:\n            raise ValueError(\"Invalid compound value passed: {0}\".format(compound))\n        self.__compound = compound\n        self._grid_widgets()", "title": ""}
{"_id": "d15974", "text": "def select_default(self):\n        \"\"\"\n        Resets the combo box to the original \"selected\" value from the\n        constructor (or the first value if no selected value was specified).\n        \"\"\"\n        if self._default is None:\n            if not self._set_option_by_index(0):\n                utils.error_format(self.description + \"\\n\" +\n                \"Unable to select default option as the Combo is empty\")\n\n        else:\n            if not self._set_option(self._default):\n                utils.error_format( self.description + \"\\n\" +\n                \"Unable to select default option as it doesnt exist in the Combo\")", "title": ""}
{"_id": "d15975", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d15976", "text": "def get_host_power_status(self):\n        \"\"\"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.\n        \"\"\"\n        sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n        return GET_POWER_STATE_MAP.get(sushy_system.power_state)", "title": ""}
{"_id": "d15977", "text": "def timed_call(func, *args, log_level='DEBUG', **kwargs):\n    \"\"\"Logs a function's run time\n\n    :param func: The function to run\n    :param args: The args to pass to the function\n    :param kwargs: The keyword args to pass to the function\n    :param log_level: The log level at which to print the run time\n    :return: The function's return value\n    \"\"\"\n    start = time()\n    r = func(*args, **kwargs)\n    t = time() - start\n    log(log_level, \"Call to '{}' took {:0.6f}s\".format(func.__name__, t))\n    return r", "title": ""}
{"_id": "d15978", "text": "def _is_image_sequenced(image):\n    \"\"\"Determine if the image is a sequenced image.\"\"\"\n    try:\n        image.seek(1)\n        image.seek(0)\n        result = True\n    except EOFError:\n        result = False\n\n    return result", "title": ""}
{"_id": "d15979", "text": "def sent2features(sentence, template):\n    \"\"\" extract features in a sentence\n\n    :type sentence: list of token, each token is a list of tag\n    \"\"\"\n    return [word2features(sentence, i, template) for i in range(len(sentence))]", "title": ""}
{"_id": "d15980", "text": "def _namematcher(regex):\n    \"\"\"Checks if a target name matches with an input regular expression.\"\"\"\n\n    matcher = re_compile(regex)\n\n    def match(target):\n        target_name = getattr(target, '__name__', '')\n        result = matcher.match(target_name)\n        return result\n\n    return match", "title": ""}
{"_id": "d15981", "text": "def _unjsonify(x, isattributes=False):\n    \"\"\"Convert JSON string to an ordered defaultdict.\"\"\"\n    if isattributes:\n        obj = json.loads(x)\n        return dict_class(obj)\n    return json.loads(x)", "title": ""}
{"_id": "d15982", "text": "def eglInitialize(display):\n    \"\"\" Initialize EGL and return EGL version tuple.\n    \"\"\"\n    majorVersion = (_c_int*1)()\n    minorVersion = (_c_int*1)()\n    res = _lib.eglInitialize(display, majorVersion, minorVersion)\n    if res == EGL_FALSE:\n        raise RuntimeError('Could not initialize')\n    return majorVersion[0], minorVersion[0]", "title": ""}
{"_id": "d15983", "text": "def get_last_or_frame_exception():\n    \"\"\"Intended to be used going into post mortem routines.  If\n    sys.last_traceback is set, we will return that and assume that\n    this is what post-mortem will want. If sys.last_traceback has not\n    been set, then perhaps we *about* to raise an error and are\n    fielding an exception. So assume that sys.exc_info()[2]\n    is where we want to look.\"\"\"\n\n    try:\n        if inspect.istraceback(sys.last_traceback):\n            # We do have a traceback so prefer that.\n            return sys.last_type, sys.last_value, sys.last_traceback\n    except AttributeError:\n        pass\n    return sys.exc_info()", "title": ""}
{"_id": "d15984", "text": "def mouse_move_event(self, event):\n        \"\"\"\n        Forward mouse cursor position events to the example\n        \"\"\"\n        self.example.mouse_position_event(event.x(), event.y())", "title": ""}
{"_id": "d15985", "text": "def list2dict(lst):\n    \"\"\"Takes a list of (key,value) pairs and turns it into a dict.\"\"\"\n\n    dic = {}\n    for k,v in lst: dic[k] = v\n    return dic", "title": ""}
{"_id": "d15986", "text": "def path_to_list(pathstr):\n    \"\"\"Conver a path string to a list of path elements.\"\"\"\n    return [elem for elem in pathstr.split(os.path.pathsep) if elem]", "title": ""}
{"_id": "d15987", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d15988", "text": "def normalize_enum_constant(s):\n    \"\"\"Return enum constant `s` converted to a canonical snake-case.\"\"\"\n    if s.islower(): return s\n    if s.isupper(): return s.lower()\n    return \"\".join(ch if ch.islower() else \"_\" + ch.lower() for ch in s).strip(\"_\")", "title": ""}
{"_id": "d15989", "text": "def string_to_float_list(string_var):\n        \"\"\"Pull comma separated string values out of a text file and converts them to float list\"\"\"\n        try:\n            return [float(s) for s in string_var.strip('[').strip(']').split(', ')]\n        except:\n            return [float(s) for s in string_var.strip('[').strip(']').split(',')]", "title": ""}
{"_id": "d15990", "text": "def sf01(arr):\n    \"\"\"\n    swap and then flatten axes 0 and 1\n    \"\"\"\n    s = arr.shape\n    return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])", "title": ""}
{"_id": "d15991", "text": "def to_bytes(s, encoding=\"utf-8\"):\n    \"\"\"Convert a string to bytes.\"\"\"\n    if isinstance(s, six.binary_type):\n        return s\n    if six.PY3:\n        return bytes(s, encoding)\n    return s.encode(encoding)", "title": ""}
{"_id": "d15992", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d15993", "text": "def intToBin(i):\n    \"\"\" Integer to two bytes \"\"\"\n    # divide in two parts (bytes)\n    i1 = i % 256\n    i2 = int(i / 256)\n    # make string (little endian)\n    return i.to_bytes(2, byteorder='little')", "title": ""}
{"_id": "d15994", "text": "def size(self):\n        \"\"\"\n        Recursively find size of a tree. Slow.\n        \"\"\"\n\n        if self is NULL:\n            return 0\n        return 1 + self.left.size() + self.right.size()", "title": ""}
{"_id": "d15995", "text": "def should_skip_logging(func):\n    \"\"\"\n    Should we skip logging for this handler?\n\n    \"\"\"\n    disabled = strtobool(request.headers.get(\"x-request-nolog\", \"false\"))\n    return disabled or getattr(func, SKIP_LOGGING, False)", "title": ""}
{"_id": "d15996", "text": "def cleanup_nodes(doc):\n    \"\"\"\n    Remove text nodes containing only whitespace\n    \"\"\"\n    for node in doc.documentElement.childNodes:\n        if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():\n            doc.documentElement.removeChild(node)\n    return doc", "title": ""}
{"_id": "d15997", "text": "def stdout_to_results(s):\n    \"\"\"Turns the multi-line output of a benchmark process into\n    a sequence of BenchmarkResult instances.\"\"\"\n    results = s.strip().split('\\n')\n    return [BenchmarkResult(*r.split()) for r in results]", "title": ""}
{"_id": "d15998", "text": "def _remove_blank(l):\n        \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n        ret = []\n        for i, _ in enumerate(l):\n            if l[i] == 0:\n                break\n            ret.append(l[i])\n        return ret", "title": ""}
{"_id": "d15999", "text": "def get_neg_infinity(dtype):\n    \"\"\"Return an appropriate positive infinity for this dtype.\n\n    Parameters\n    ----------\n    dtype : np.dtype\n\n    Returns\n    -------\n    fill_value : positive infinity value corresponding to this dtype.\n    \"\"\"\n    if issubclass(dtype.type, (np.floating, np.integer)):\n        return -np.inf\n\n    if issubclass(dtype.type, np.complexfloating):\n        return -np.inf - 1j * np.inf\n\n    return NINF", "title": ""}
{"_id": "d16000", "text": "def retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n\t\"\"\"\n\tGiven a callable func, trap the indicated exceptions\n\tfor up to 'retries' times, invoking cleanup on the\n\texception. On the final attempt, allow any exceptions\n\tto propagate.\n\t\"\"\"\n\tattempts = count() if retries == float('inf') else range(retries)\n\tfor attempt in attempts:\n\t\ttry:\n\t\t\treturn func()\n\t\texcept trap:\n\t\t\tcleanup()\n\n\treturn func()", "title": ""}
{"_id": "d16001", "text": "def union(self, other):\n        \"\"\"Return a new set which is the union of I{self} and I{other}.\n\n        @param other: the other set\n        @type other: Set object\n        @rtype: the same type as I{self}\n        \"\"\"\n\n        obj = self._clone()\n        obj.union_update(other)\n        return obj", "title": ""}
{"_id": "d16002", "text": "def set_scrollbars_cb(self, w, tf):\n        \"\"\"This callback is invoked when the user checks the 'Use Scrollbars'\n        box in the preferences pane.\"\"\"\n        scrollbars = 'on' if tf else 'off'\n        self.t_.set(scrollbars=scrollbars)", "title": ""}
{"_id": "d16003", "text": "def install_from_zip(url):\n    \"\"\"Download and unzip from url.\"\"\"\n    fname = 'tmp.zip'\n    downlad_file(url, fname)\n    unzip_file(fname)\n    print(\"Removing {}\".format(fname))\n    os.unlink(fname)", "title": ""}
{"_id": "d16004", "text": "def tuple_check(*args, func=None):\n    \"\"\"Check if arguments are tuple type.\"\"\"\n    func = func or inspect.stack()[2][3]\n    for var in args:\n        if not isinstance(var, (tuple, collections.abc.Sequence)):\n            name = type(var).__name__\n            raise TupleError(\n                f'Function {func} expected tuple, {name} got instead.')", "title": ""}
{"_id": "d16005", "text": "def min_values(args):\n    \"\"\" Return possible range for min function. \"\"\"\n    return Interval(min(x.low for x in args), min(x.high for x in args))", "title": ""}
{"_id": "d16006", "text": "def md_to_text(content):\n    \"\"\" Converts markdown content to text \"\"\"\n    text = None\n    html = markdown.markdown(content)\n    if html:\n        text = html_to_text(content)\n    return text", "title": ""}
{"_id": "d16007", "text": "def unit_ball_L2(shape):\n  \"\"\"A tensorflow variable tranfomed to be constrained in a L2 unit ball.\n\n  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n  they are strong attacks. We are not yet confident in this code.\n  \"\"\"\n  x = tf.Variable(tf.zeros(shape))\n  return constrain_L2(x)", "title": ""}
{"_id": "d16008", "text": "def list_of_dict(self):\n        \"\"\"\n        This will convert the data from a list of list to a list of dictionary\n        :return: list of dict\n        \"\"\"\n        ret = []\n        for row in self:\n            ret.append(dict([(self._col_names[i], row[i]) for i in\n                             range(len(self._col_names))]))\n        return ReprListDict(ret, col_names=self._col_names,\n                            col_types=self._col_types,\n                            width_limit=self._width_limit,\n                            digits=self._digits,\n                            convert_unicode=self._convert_unicode)", "title": ""}
{"_id": "d16009", "text": "def copy_and_update(dictionary, update):\n    \"\"\"Returns an updated copy of the dictionary without modifying the original\"\"\"\n    newdict = dictionary.copy()\n    newdict.update(update)\n    return newdict", "title": ""}
{"_id": "d16010", "text": "def uri_to_iri_parts(path, query, fragment):\n    r\"\"\"\n    Converts a URI parts to corresponding IRI parts in a given charset.\n\n    Examples for URI versus IRI:\n\n    :param path: The path of URI to convert.\n    :param query: The query string of URI to convert.\n    :param fragment: The fragment of URI to convert.\n    \"\"\"\n    path = url_unquote(path, '%/;?')\n    query = url_unquote(query, '%;/?:@&=+,$#')\n    fragment = url_unquote(fragment, '%;/?:@&=+,$#')\n    return path, query, fragment", "title": ""}
{"_id": "d16011", "text": "def _help():\n    \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n    statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n    print statement.strip()", "title": ""}
{"_id": "d16012", "text": "def twitter_timeline(screen_name, since_id=None):\n    \"\"\" Return relevant twitter timeline \"\"\"\n    consumer_key = twitter_credential('consumer_key')\n    consumer_secret = twitter_credential('consumer_secret')\n    access_token = twitter_credential('access_token')\n    access_token_secret = twitter_credential('access_secret')\n    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n    auth.set_access_token(access_token, access_token_secret)\n    api = tweepy.API(auth)\n    return get_all_tweets(screen_name, api, since_id)", "title": ""}
{"_id": "d16013", "text": "def get_input(input_func, input_str):\n    \"\"\"\n    Get input from the user given an input function and an input string\n    \"\"\"\n    val = input_func(\"Please enter your {0}: \".format(input_str))\n    while not val or not len(val.strip()):\n        val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n    return val", "title": ""}
{"_id": "d16014", "text": "def check_str(obj):\n        \"\"\" Returns a string for various input types \"\"\"\n        if isinstance(obj, str):\n            return obj\n        if isinstance(obj, float):\n            return str(int(obj))\n        else:\n            return str(obj)", "title": ""}
{"_id": "d16015", "text": "def str2int(string_with_int):\n    \"\"\" Collect digits from a string \"\"\"\n    return int(\"\".join([char for char in string_with_int if char in string.digits]) or 0)", "title": ""}
{"_id": "d16016", "text": "def parse_parameter(value):\n    \"\"\"\n    @return: The best approximation of a type of the given value.\n    \"\"\"\n    if any((isinstance(value, float), isinstance(value, int), isinstance(value, bool))):\n        return value\n\n    try:\n        return int(value)\n    except ValueError:\n        try:\n            return float(value)\n        except ValueError:\n            if value in string_aliases.true_boolean_aliases:\n                return True\n            elif value in string_aliases.false_boolean_aliases:\n                return False\n            else:\n                return str(value)", "title": ""}
{"_id": "d16017", "text": "def notin(arg, values):\n    \"\"\"\n    Like isin, but checks whether this expression's value(s) are not\n    contained in the passed values. See isin docs for full usage.\n    \"\"\"\n    op = ops.NotContains(arg, values)\n    return op.to_expr()", "title": ""}
{"_id": "d16018", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d16019", "text": "def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,\ncontent=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):\n    \"\"\"\n    HTTP response for not-authorized access (status code 403)\n    \"\"\"\n    return AccessFailedResponse(request, template, content, content_type, status=401)", "title": ""}
{"_id": "d16020", "text": "def subscribe(self, handler):\n        \"\"\"Adds a new event handler.\"\"\"\n        assert callable(handler), \"Invalid handler %s\" % handler\n        self.handlers.append(handler)", "title": ""}
{"_id": "d16021", "text": "def get_page_text(self, page):\n        \"\"\"\n        Downloads and returns the full text of a particular page\n        in the document.\n        \"\"\"\n        url = self.get_page_text_url(page)\n        return self._get_url(url)", "title": ""}
{"_id": "d16022", "text": "def get_form_bound_field(form, field_name):\n    \"\"\"\n    Intends to get the bound field from the form regarding the field name\n\n    :param form: Django Form: django form instance\n    :param field_name: str: name of the field in form instance\n    :return: Django Form bound field\n    \"\"\"\n    field = form.fields[field_name]\n    field = field.get_bound_field(form, field_name)\n    return field", "title": ""}
{"_id": "d16023", "text": "def set_scrollregion(self, event=None):\n        \"\"\" Set the scroll region on the canvas\"\"\"\n        self.canvas.configure(scrollregion=self.canvas.bbox('all'))", "title": ""}
{"_id": "d16024", "text": "def union_overlapping(intervals):\n    \"\"\"Union any overlapping intervals in the given set.\"\"\"\n    disjoint_intervals = []\n\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\n    return disjoint_intervals", "title": ""}
{"_id": "d16025", "text": "def print_latex(o):\n    \"\"\"A function to generate the latex representation of sympy\n    expressions.\"\"\"\n    if can_print_latex(o):\n        s = latex(o, mode='plain')\n        s = s.replace('\\\\dag','\\\\dagger')\n        s = s.strip('$')\n        return '$$%s$$' % s\n    # Fallback to the string printer\n    return None", "title": ""}
{"_id": "d16026", "text": "def flatten_union(table):\n    \"\"\"Extract all union queries from `table`.\n\n    Parameters\n    ----------\n    table : TableExpr\n\n    Returns\n    -------\n    Iterable[Union[TableExpr, bool]]\n    \"\"\"\n    op = table.op()\n    if isinstance(op, ops.Union):\n        return toolz.concatv(\n            flatten_union(op.left), [op.distinct], flatten_union(op.right)\n        )\n    return [table]", "title": ""}
{"_id": "d16027", "text": "def comment (self, s, **args):\n        \"\"\"Write GML comment.\"\"\"\n        self.writeln(s=u'comment \"%s\"' % s, **args)", "title": ""}
{"_id": "d16028", "text": "def page_title(step, title):\n    \"\"\"\n    Check that the page title matches the given one.\n    \"\"\"\n\n    with AssertContextManager(step):\n        assert_equals(world.browser.title, title)", "title": ""}
{"_id": "d16029", "text": "def setdefault(obj, field, default):\n    \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n    setattr(obj, field, getattr(obj, field, default))", "title": ""}
{"_id": "d16030", "text": "def test():  # pragma: no cover\n    \"\"\"Execute the unit tests on an installed copy of unyt.\n\n    Note that this function requires pytest to run. If pytest is not\n    installed this function will raise ImportError.\n    \"\"\"\n    import pytest\n    import os\n\n    pytest.main([os.path.dirname(os.path.abspath(__file__))])", "title": ""}
{"_id": "d16031", "text": "def script_repr(val,imports,prefix,settings):\n    \"\"\"\n    Variant of repr() designed for generating a runnable script.\n\n    Instances of types that require special handling can use the\n    script_repr_reg dictionary. Using the type as a key, add a\n    function that returns a suitable representation of instances of\n    that type, and adds the required import statement.\n\n    The repr of a parameter can be suppressed by returning None from\n    the appropriate hook in script_repr_reg.\n    \"\"\"\n    return pprint(val,imports,prefix,settings,unknown_value=None,\n                  qualify=True,separator=\"\\n\")", "title": ""}
{"_id": "d16032", "text": "def write_str2file(pathname, astr):\n    \"\"\"writes a string to file\"\"\"\n    fname = pathname\n    fhandle = open(fname, 'wb')\n    fhandle.write(astr)\n    fhandle.close()", "title": ""}
{"_id": "d16033", "text": "def assert_redirect(self, response, expected_url=None):\n        \"\"\"\n        assertRedirects from Django TestCase follows the redirects chains,\n        this assertion does not - which is more like real unit testing\n        \"\"\"\n        self.assertIn(\n            response.status_code,\n            self.redirect_codes,\n            self._get_redirect_assertion_message(response),\n        )\n        if expected_url:\n            location_header = response._headers.get('location', None)\n            self.assertEqual(\n                location_header,\n                ('Location', str(expected_url)),\n                'Response should redirect to {0}, but it redirects to {1} instead'.format(\n                    expected_url,\n                    location_header[1],\n                )\n            )", "title": ""}
{"_id": "d16034", "text": "def _write_separator(self):\n        \"\"\"\n        Inserts a horizontal (commented) line tot the generated code.\n        \"\"\"\n        tmp = self._page_width - ((4 * self.__indent_level) + 2)\n        self._write_line('# ' + ('-' * tmp))", "title": ""}
{"_id": "d16035", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d16036", "text": "def extract_zip(zip_path, target_folder):\n    \"\"\"\n    Extract the content of the zip-file at `zip_path` into `target_folder`.\n    \"\"\"\n    with zipfile.ZipFile(zip_path) as archive:\n        archive.extractall(target_folder)", "title": ""}
{"_id": "d16037", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d16038", "text": "def save_excel(self, fd):\n        \"\"\" Saves the case as an Excel spreadsheet.\n        \"\"\"\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)", "title": ""}
{"_id": "d16039", "text": "def _keys_to_camel_case(self, obj):\n        \"\"\"\n        Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary.\n\n        :param obj: Dictionary to convert keys to camel case.\n        :return: Dictionary with the input values and all keys in camel case\n        \"\"\"\n        return dict((to_camel_case(key), value) for (key, value) in obj.items())", "title": ""}
{"_id": "d16040", "text": "def top(n, width=WIDTH, style=STYLE):\n    \"\"\"Prints the top row of a table\"\"\"\n    return hrule(n, width, linestyle=STYLES[style].top)", "title": ""}
{"_id": "d16041", "text": "def set_global(node: Node, key: str, value: Any):\n    \"\"\"Adds passed value to node's globals\"\"\"\n    node.node_globals[key] = value", "title": ""}
{"_id": "d16042", "text": "def handle_exception(error):\n        \"\"\"Simple method for handling exceptions raised by `PyBankID`.\n\n        :param flask_pybankid.FlaskPyBankIDError error: The exception to handle.\n        :return: The exception represented as a dictionary.\n        :rtype: dict\n\n        \"\"\"\n        response = jsonify(error.to_dict())\n        response.status_code = error.status_code\n        return response", "title": ""}
{"_id": "d16043", "text": "def update_context(self, ctx):\n        \"\"\" updates the query context with this clauses values \"\"\"\n        assert isinstance(ctx, dict)\n        ctx[str(self.context_id)] = self.value", "title": ""}
{"_id": "d16044", "text": "def get_encoding(binary):\n    \"\"\"Return the encoding type.\"\"\"\n\n    try:\n        from chardet import detect\n    except ImportError:\n        LOGGER.error(\"Please install the 'chardet' module\")\n        sys.exit(1)\n\n    encoding = detect(binary).get('encoding')\n\n    return 'iso-8859-1' if encoding == 'CP949' else encoding", "title": ""}
{"_id": "d16045", "text": "def get_url_args(url):\n    \"\"\" Returns a dictionary from a URL params \"\"\"\n    url_data = urllib.parse.urlparse(url)\n    arg_dict = urllib.parse.parse_qs(url_data.query)\n    return arg_dict", "title": ""}
{"_id": "d16046", "text": "def clear_list_value(self, value):\n        \"\"\"\n        Clean the argument value to eliminate None or Falsy values if needed.\n        \"\"\"\n        # Don't go any further: this value is empty.\n        if not value:\n            return self.empty_value\n        # Clean empty items if wanted\n        if self.clean_empty:\n            value = [v for v in value if v]\n        return value or self.empty_value", "title": ""}
{"_id": "d16047", "text": "def get_url_file_name(url):\n    \"\"\"Get the file name from an url\n    \n    Parameters\n    ----------\n    url : str\n\n    Returns\n    -------\n    str\n        The file name \n    \"\"\"\n\n    assert isinstance(url, (str, _oldstr))\n    return urlparse.urlparse(url).path.split('/')[-1]", "title": ""}
{"_id": "d16048", "text": "def table_exists(cursor, tablename, schema='public'):\n    query = \"\"\"\n    SELECT EXISTS (\n        SELECT 1\n        FROM information_schema.tables\n        WHERE table_schema = %s\n        AND table_name = %s\n    )\"\"\"\n    cursor.execute(query, (schema, tablename))\n    res = cursor.fetchone()[0]\n    return res", "title": ""}
{"_id": "d16049", "text": "def _fill_array_from_list(the_list, the_array):\n        \"\"\"Fill an `array` from a `list`\"\"\"\n        for i, val in enumerate(the_list):\n            the_array[i] = val\n        return the_array", "title": ""}
{"_id": "d16050", "text": "def isString(s):\n    \"\"\"Convenience method that works with all 2.x versions of Python\n    to determine whether or not something is stringlike.\"\"\"\n    try:\n        return isinstance(s, unicode) or isinstance(s, basestring)\n    except NameError:\n        return isinstance(s, str)", "title": ""}
{"_id": "d16051", "text": "def list_formatter(handler, item, value):\n    \"\"\"Format list.\"\"\"\n    return u', '.join(str(v) for v in value)", "title": ""}
{"_id": "d16052", "text": "def average_gradient(data, *kwargs):\n    \"\"\" Compute average gradient norm of an image\n    \"\"\"\n    return np.average(np.array(np.gradient(data))**2)", "title": ""}
{"_id": "d16053", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d16054", "text": "def dfs_recursive(graph, node, seen):\n    \"\"\"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|)`\n    \"\"\"\n    seen[node] = True\n    for neighbor in graph[node]:\n        if not seen[neighbor]:\n            dfs_recursive(graph, neighbor, seen)", "title": ""}
{"_id": "d16055", "text": "def Proxy(f):\n  \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n\n  return Wrapped", "title": ""}
{"_id": "d16056", "text": "def bbox(self):\n        \"\"\"\n        The minimal `~photutils.aperture.BoundingBox` for the cutout\n        region with respect to the original (large) image.\n        \"\"\"\n\n        return BoundingBox(self.slices[1].start, self.slices[1].stop,\n                           self.slices[0].start, self.slices[0].stop)", "title": ""}
{"_id": "d16057", "text": "def prompt(*args, **kwargs):\n    \"\"\"Prompt the user for input and handle any abort exceptions.\"\"\"\n    try:\n        return click.prompt(*args, **kwargs)\n    except click.Abort:\n        return False", "title": ""}
{"_id": "d16058", "text": "def find_one(cls, *args, **kw):\n\t\t\"\"\"Get a single document from the collection this class is bound to.\n\t\t\n\t\tAdditional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional\n\t\tparameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword\n\t\targuments passed along with minor transformation.\n\t\t\n\t\tAutomatically calls `to_mongo` with the retrieved data.\n\t\t\n\t\thttps://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one\n\t\t\"\"\"\n\t\t\n\t\tif len(args) == 1 and not isinstance(args[0], Filter):\n\t\t\targs = (getattr(cls, cls.__pk__) == args[0], )\n\t\t\n\t\tDoc, collection, query, options = cls._prepare_find(*args, **kw)\n\t\tresult = Doc.from_mongo(collection.find_one(query, **options))\n\t\t\n\t\treturn result", "title": ""}
{"_id": "d16059", "text": "def generate_user_token(self, user, salt=None):\n        \"\"\"Generates a unique token associated to the user\n        \"\"\"\n        return self.token_serializer.dumps(str(user.id), salt=salt)", "title": ""}
{"_id": "d16060", "text": "def exp_fit_fun(x, a, tau, c):\n    \"\"\"Function used to fit the exponential decay.\"\"\"\n    # pylint: disable=invalid-name\n    return a * np.exp(-x / tau) + c", "title": ""}
{"_id": "d16061", "text": "def random_string(string_length=10):\n    \"\"\"Returns a random string of length string_length.\"\"\"\n    random = str(uuid.uuid4())  # Convert UUID format to a Python string.\n    random = random.upper()  # Make all characters uppercase.\n    random = random.replace(\"-\", \"\")  # Remove the UUID '-'.\n    return random[0:string_length]", "title": ""}
{"_id": "d16062", "text": "def end_index(self):\n        \"\"\"\n        Returns the 1-based index of the last object on this page,\n        relative to total objects found (hits).\n        \"\"\"\n        return ((self.number - 1) * self.paginator.per_page +\n            len(self.object_list))", "title": ""}
{"_id": "d16063", "text": "def bool_str(string):\n    \"\"\"Returns a boolean from a string imput of 'true' or 'false'\"\"\"\n    if string not in BOOL_STRS:\n        raise ValueError('Invalid boolean string: \"{}\"'.format(string))\n    return True if string == 'true' else False", "title": ""}
{"_id": "d16064", "text": "def quote(self, s):\n        \"\"\"Return a shell-escaped version of the string s.\"\"\"\n\n        if six.PY2:\n            from pipes import quote\n        else:\n            from shlex import quote\n\n        return quote(s)", "title": ""}
{"_id": "d16065", "text": "def is_valid(data):\n        \"\"\"\n        Checks if the input data is a Swagger document\n\n        :param dict data: Data to be validated\n        :return: True, if data is a Swagger\n        \"\"\"\n        return bool(data) and \\\n            isinstance(data, dict) and \\\n            bool(data.get(\"swagger\")) and \\\n            isinstance(data.get('paths'), dict)", "title": ""}
{"_id": "d16066", "text": "def ynticks(self, nticks, index=1):\n        \"\"\"Set the number of ticks.\"\"\"\n        self.layout['yaxis' + str(index)]['nticks'] = nticks\n        return self", "title": ""}
{"_id": "d16067", "text": "def __len__(self):\n        \"\"\" This will equal 124 for the V1 database. \"\"\"\n        length = 0\n        for typ, siz, _ in self.format:\n            length += siz\n        return length", "title": ""}
{"_id": "d16068", "text": "def _set_lastpage(self):\n        \"\"\"Calculate value of class attribute ``last_page``.\"\"\"\n        self.last_page = (len(self._page_data) - 1) // self.screen.page_size", "title": ""}
{"_id": "d16069", "text": "def venv():\n    \"\"\"Install venv + deps.\"\"\"\n    try:\n        import virtualenv  # NOQA\n    except ImportError:\n        sh(\"%s -m pip install virtualenv\" % PYTHON)\n    if not os.path.isdir(\"venv\"):\n        sh(\"%s -m virtualenv venv\" % PYTHON)\n    sh(\"venv\\\\Scripts\\\\pip install -r %s\" % (REQUIREMENTS_TXT))", "title": ""}
{"_id": "d16070", "text": "def ServerLoggingStartupInit():\n  \"\"\"Initialize the server logging configuration.\"\"\"\n  global LOGGER\n  if local_log:\n    logging.debug(\"Using local LogInit from %s\", local_log)\n    local_log.LogInit()\n    logging.debug(\"Using local AppLogInit from %s\", local_log)\n    LOGGER = local_log.AppLogInit()\n  else:\n    LogInit()\n    LOGGER = AppLogInit()", "title": ""}
{"_id": "d16071", "text": "def init():\n    \"\"\"\n    Execute init tasks for all components (virtualenv, pip).\n    \"\"\"\n    print(yellow(\"# Setting up environment...\\n\", True))\n    virtualenv.init()\n    virtualenv.update_requirements()\n    print(green(\"\\n# DONE.\", True))\n    print(green(\"Type \") + green(\"activate\", True) + green(\" to enable your virtual environment.\"))", "title": ""}
{"_id": "d16072", "text": "def _py2_and_3_joiner(sep, joinable):\n    \"\"\"\n    Allow '\\n'.join(...) statements to work in Py2 and Py3.\n    :param sep:\n    :param joinable:\n    :return:\n    \"\"\"\n    if ISPY3:\n        sep = bytes(sep, DEFAULT_ENCODING)\n    joined = sep.join(joinable)\n    return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined", "title": ""}
{"_id": "d16073", "text": "def csort(objs, key):\n    \"\"\"Order-preserving sorting function.\"\"\"\n    idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n    return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "title": ""}
{"_id": "d16074", "text": "def put_text(self, key, text):\n        \"\"\"Put the text into the storage associated with the key.\"\"\"\n        with open(key, \"w\") as fh:\n            fh.write(text)", "title": ""}
{"_id": "d16075", "text": "def destroy_webdriver(driver):\n    \"\"\"\n    Destroy a driver\n    \"\"\"\n\n    # This is some very flaky code in selenium. Hence the retries\n    # and catch-all exceptions\n    try:\n        retry_call(driver.close, tries=2)\n    except Exception:\n        pass\n    try:\n        driver.quit()\n    except Exception:\n        pass", "title": ""}
{"_id": "d16076", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d16077", "text": "def kill(self):\n        \"\"\"Kill the browser.\n\n        This is useful when the browser is stuck.\n        \"\"\"\n        if self.process:\n            self.process.kill()\n            self.process.wait()", "title": ""}
{"_id": "d16078", "text": "def build_code(self, lang, body):\n        \"\"\"Wrap text with markdown specific flavour.\"\"\"\n        self.out.append(\"```\" + lang)\n        self.build_markdown(lang, body)\n        self.out.append(\"```\")", "title": ""}
{"_id": "d16079", "text": "def check_by_selector(self, selector):\n    \"\"\"Check the checkbox matching the CSS selector.\"\"\"\n    elem = find_element_by_jquery(world.browser, selector)\n    if not elem.is_selected():\n        elem.click()", "title": ""}
{"_id": "d16080", "text": "def IPYTHON_MAIN():\n    \"\"\"Decide if the Ipython command line is running code.\"\"\"\n    import pkg_resources\n\n    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]\n    return (\n        getattr(runner_frame, \"function\", None)\n        == pkg_resources.load_entry_point(\"ipython\", \"console_scripts\", \"ipython\").__name__\n    )", "title": ""}
{"_id": "d16081", "text": "def _checkSize(self):\n        \"\"\"Automatically resizes widget to display at most max_height_items items\"\"\"\n        if self._item_height is not None:\n            sz = min(self._max_height_items, self.count()) * self._item_height + 5\n            sz = max(sz, 20)\n            self.setMinimumSize(0, sz)\n            self.setMaximumSize(1000000, sz)\n            self.resize(self.width(), sz)", "title": ""}
{"_id": "d16082", "text": "def fast_distinct(self):\n        \"\"\"\n        Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n        this method provides alternative to the standard distinct method.\n        :return: qs with unique objects\n        \"\"\"\n        return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "title": ""}
{"_id": "d16083", "text": "def __grid_widgets(self):\n        \"\"\"Places all the child widgets in the appropriate positions.\"\"\"\n        scrollbar_column = 0 if self.__compound is tk.LEFT else 2\n        self._canvas.grid(row=0, column=1, sticky=\"nswe\")\n        self._scrollbar.grid(row=0, column=scrollbar_column, sticky=\"ns\")", "title": ""}
{"_id": "d16084", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d16085", "text": "def retry_on_signal(function):\n    \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n    while True:\n        try:\n            return function()\n        except EnvironmentError, e:\n            if e.errno != errno.EINTR:\n                raise", "title": ""}
{"_id": "d16086", "text": "def all_equal(arg1,arg2):\n    \"\"\"\n    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.\n    \"\"\"\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", "title": ""}
{"_id": "d16087", "text": "def __init__(self, encoding='utf-8'):\n    \"\"\"Initializes an stdin input reader.\n\n    Args:\n      encoding (Optional[str]): input encoding.\n    \"\"\"\n    super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)", "title": ""}
{"_id": "d16088", "text": "def check_alert(self, text):\n    \"\"\"\n    Assert an alert is showing with the given text.\n    \"\"\"\n\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        # PhantomJS is kinda poor\n        pass", "title": ""}
{"_id": "d16089", "text": "def write_fits(self, fitsfile):\n        \"\"\"Write the ROI model to a FITS file.\"\"\"\n\n        tab = self.create_table()\n        hdu_data = fits.table_to_hdu(tab)\n        hdus = [fits.PrimaryHDU(), hdu_data]\n        fits_utils.write_hdus(hdus, fitsfile)", "title": ""}
{"_id": "d16090", "text": "def each_img(img_dir):\n    \"\"\"\n    Reads and iterates through each image file in the given directory\n    \"\"\"\n    for fname in utils.each_img(img_dir):\n        fname = os.path.join(img_dir, fname)\n        yield cv.imread(fname), fname", "title": ""}
{"_id": "d16091", "text": "def save_dict_to_file(filename, dictionary):\n  \"\"\"Saves dictionary as CSV file.\"\"\"\n  with open(filename, 'w') as f:\n    writer = csv.writer(f)\n    for k, v in iteritems(dictionary):\n      writer.writerow([str(k), str(v)])", "title": ""}
{"_id": "d16092", "text": "def path_distance(points):\n    \"\"\"\n    Compute the path distance from given set of points\n    \"\"\"\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))", "title": ""}
{"_id": "d16093", "text": "def series_table_row_offset(self, series):\n        \"\"\"\n        Return the number of rows preceding the data table for *series* in\n        the Excel worksheet.\n        \"\"\"\n        title_and_spacer_rows = series.index * 2\n        data_point_rows = series.data_point_offset\n        return title_and_spacer_rows + data_point_rows", "title": ""}
{"_id": "d16094", "text": "def extract_words(lines):\n    \"\"\"\n    Extract from the given iterable of lines the list of words.\n\n    :param lines: an iterable of lines;\n    :return: a generator of words of lines.\n    \"\"\"\n    for line in lines:\n        for word in re.findall(r\"\\w+\", line):\n            yield word", "title": ""}
{"_id": "d16095", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d16096", "text": "def __next__(self, reward, ask_id, lbl):\n        \"\"\"For Python3 compatibility of generator.\"\"\"\n        return self.next(reward, ask_id, lbl)", "title": ""}
{"_id": "d16097", "text": "def element_to_string(element, include_declaration=True, encoding=DEFAULT_ENCODING, method='xml'):\n    \"\"\" :return: the string value of the element or element tree \"\"\"\n\n    if isinstance(element, ElementTree):\n        element = element.getroot()\n    elif not isinstance(element, ElementType):\n        element = get_element(element)\n\n    if element is None:\n        return u''\n\n    element_as_string = tostring(element, encoding, method).decode(encoding=encoding)\n    if include_declaration:\n        return element_as_string\n    else:\n        return strip_xml_declaration(element_as_string)", "title": ""}
{"_id": "d16098", "text": "def group_by(iterable, key_func):\n    \"\"\"Wrap itertools.groupby to make life easier.\"\"\"\n    groups = (\n        list(sub) for key, sub in groupby(iterable, key_func)\n    )\n    return zip(groups, groups)", "title": ""}
{"_id": "d16099", "text": "def _get_minidom_tag_value(station, tag_name):\n    \"\"\"get a value from a tag (if it exists)\"\"\"\n    tag = station.getElementsByTagName(tag_name)[0].firstChild\n    if tag:\n        return tag.nodeValue\n\n    return None", "title": ""}
{"_id": "d16100", "text": "def jaccard(c_1, c_2):\n    \"\"\"\n    Calculates the Jaccard similarity between two sets of nodes. Called by mroc.\n\n    Inputs:  - c_1: Community (set of nodes) 1.\n             - c_2: Community (set of nodes) 2.\n\n    Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.\n    \"\"\"\n    nom = np.intersect1d(c_1, c_2).size\n    denom = np.union1d(c_1, c_2).size\n    return nom/denom", "title": ""}
{"_id": "d16101", "text": "def required_attributes(element, *attributes):\n    \"\"\"Check element for required attributes. Raise ``NotValidXmlException`` on error.\n\n    :param element: ElementTree element\n    :param attributes: list of attributes names to check\n    :raises NotValidXmlException: if some argument is missing\n    \"\"\"\n    if not reduce(lambda still_valid, param: still_valid and param in element.attrib, attributes, True):\n        raise NotValidXmlException(msg_err_missing_attributes(element.tag, *attributes))", "title": ""}
{"_id": "d16102", "text": "def xml_str_to_dict(s):\n    \"\"\" Transforms an XML string it to python-zimbra dict format\n\n    For format, see:\n      https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n    :param: a string, containing XML\n    :returns: a dict, with python-zimbra format\n    \"\"\"\n    xml = minidom.parseString(s)\n    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)", "title": ""}
{"_id": "d16103", "text": "def send(self, topic, *args, **kwargs):\n        \"\"\"\n        Appends the prefix to the topic before sendingf\n        \"\"\"\n        prefix_topic = self.heroku_kafka.prefix_topic(topic)\n        return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs)", "title": ""}
{"_id": "d16104", "text": "def root_parent(self, category=None):\n        \"\"\" Returns the topmost parent of the current category. \"\"\"\n        return next(filter(lambda c: c.is_root, self.hierarchy()))", "title": ""}
{"_id": "d16105", "text": "def best(self):\n        \"\"\"\n        Returns the element with the highest probability.\n        \"\"\"\n        b = (-1e999999, None)\n        for k, c in iteritems(self.counts):\n            b = max(b, (c, k))\n        return b[1]", "title": ""}
{"_id": "d16106", "text": "def _Open(self, hostname, port):\n    \"\"\"Opens the RPC communication channel for clients.\n\n    Args:\n      hostname (str): hostname or IP address to connect to for requests.\n      port (int): port to connect to for requests.\n\n    Returns:\n      bool: True if the communication channel was successfully opened.\n    \"\"\"\n    try:\n      self._xmlrpc_server = SimpleXMLRPCServer.SimpleXMLRPCServer(\n          (hostname, port), logRequests=False, allow_none=True)\n    except SocketServer.socket.error as exception:\n      logger.warning((\n          'Unable to bind a RPC server on {0:s}:{1:d} with error: '\n          '{2!s}').format(hostname, port, exception))\n      return False\n\n    self._xmlrpc_server.register_function(\n        self._callback, self._RPC_FUNCTION_NAME)\n    return True", "title": ""}
{"_id": "d16107", "text": "def predict(self, X):\n        \"\"\"Predict the class for X.\n\n        The predicted class for each sample in X is returned.\n\n        Parameters\n        ----------\n        X : List of ndarrays, one for each training example.\n            Each training example's shape is (string1_len,\n            string2_len, n_features), where string1_len and\n            string2_len are the length of the two training strings and\n            n_features the number of features.\n\n        Returns\n        -------\n        y : iterable of shape = [n_samples]\n            The predicted classes.\n\n        \"\"\"\n        return [self.classes[prediction.argmax()] for prediction in self.predict_proba(X)]", "title": ""}
{"_id": "d16108", "text": "def xor(a, b):\n        \"\"\"Bitwise xor on equal length bytearrays.\"\"\"\n        return bytearray(i ^ j for i, j in zip(a, b))", "title": ""}
{"_id": "d16109", "text": "def stop(pid):\n    \"\"\"Shut down a specific process.\n\n    Args:\n      pid: the pid of the process to shutdown.\n    \"\"\"\n    if psutil.pid_exists(pid):\n      try:\n        p = psutil.Process(pid)\n        p.kill()\n      except Exception:\n        pass", "title": ""}
{"_id": "d16110", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d16111", "text": "def timeout_thread_handler(timeout, stop_event):\n    \"\"\"A background thread to kill the process if it takes too long.\n\n    Args:\n        timeout (float): The number of seconds to wait before killing\n            the process.\n        stop_event (Event): An optional event to cleanly stop the background\n            thread if required during testing.\n    \"\"\"\n\n    stop_happened = stop_event.wait(timeout)\n    if stop_happened is False:\n        print(\"Killing program due to %f second timeout\" % timeout)\n\n    os._exit(2)", "title": ""}
{"_id": "d16112", "text": "def ParseMany(text):\n  \"\"\"Parses many YAML documents into a list of Python objects.\n\n  Args:\n    text: A YAML source with multiple documents embedded.\n\n  Returns:\n    A list of Python data structures corresponding to the YAML documents.\n  \"\"\"\n  precondition.AssertType(text, Text)\n\n  if compatibility.PY2:\n    text = text.encode(\"utf-8\")\n\n  return list(yaml.safe_load_all(text))", "title": ""}
{"_id": "d16113", "text": "def timeout_thread_handler(timeout, stop_event):\n    \"\"\"A background thread to kill the process if it takes too long.\n\n    Args:\n        timeout (float): The number of seconds to wait before killing\n            the process.\n        stop_event (Event): An optional event to cleanly stop the background\n            thread if required during testing.\n    \"\"\"\n\n    stop_happened = stop_event.wait(timeout)\n    if stop_happened is False:\n        print(\"Killing program due to %f second timeout\" % timeout)\n\n    os._exit(2)", "title": ""}
{"_id": "d16114", "text": "def safe_dump(data, stream=None, **kwds):\n    \"\"\"implementation of safe dumper using Ordered Dict Yaml Dumper\"\"\"\n    return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)", "title": ""}
{"_id": "d16115", "text": "def cli_command_quit(self, msg):\n        \"\"\"\\\n        kills the child and exits\n        \"\"\"\n        if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:\n            self.sprocess.proc.kill()\n        else:\n            sys.exit(0)", "title": ""}
{"_id": "d16116", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d16117", "text": "def kill_test_logger(logger):\n    \"\"\"Cleans up a test logger object by removing all of its handlers.\n\n    Args:\n        logger: The logging object to clean up.\n    \"\"\"\n    for h in list(logger.handlers):\n        logger.removeHandler(h)\n        if isinstance(h, logging.FileHandler):\n            h.close()", "title": ""}
{"_id": "d16118", "text": "def trap_exceptions(results, handler, exceptions=Exception):\n\t\"\"\"\n\tIterate through the results, but if an exception occurs, stop\n\tprocessing the results and instead replace\n\tthe results with the output from the exception handler.\n\t\"\"\"\n\ttry:\n\t\tfor result in results:\n\t\t\tyield result\n\texcept exceptions as exc:\n\t\tfor result in always_iterable(handler(exc)):\n\t\t\tyield result", "title": ""}
{"_id": "d16119", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d16120", "text": "def connected_socket(address, timeout=3):\n    \"\"\" yields a connected socket \"\"\"\n    sock = socket.create_connection(address, timeout)\n    yield sock\n    sock.close()", "title": ""}
{"_id": "d16121", "text": "def value_left(self, other):\n    \"\"\"\n    Returns the value of the other type instance to use in an\n    operator method, namely when the method's instance is on the\n    left side of the expression.\n    \"\"\"\n    return other.value if isinstance(other, self.__class__) else other", "title": ""}
{"_id": "d16122", "text": "def _return_result(self, done):\n        \"\"\"Called set the returned future's state that of the future\n        we yielded, and set the current future for the iterator.\n        \"\"\"\n        chain_future(done, self._running_future)\n\n        self.current_future = done\n        self.current_index = self._unfinished.pop(done)", "title": ""}
{"_id": "d16123", "text": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Like `pretty` but print to stdout.\n    \"\"\"\n    printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    sys.stdout.write(newline)\n    sys.stdout.flush()", "title": ""}
{"_id": "d16124", "text": "def unzip_file_to_dir(path_to_zip, output_directory):\n    \"\"\"\n    Extract a ZIP archive to a directory\n    \"\"\"\n    z = ZipFile(path_to_zip, 'r')\n    z.extractall(output_directory)\n    z.close()", "title": ""}
{"_id": "d16125", "text": "def _get_xy_scaling_parameters(self):\n        \"\"\"Get the X/Y coordinate limits for the full resulting image\"\"\"\n        return self.mx, self.bx, self.my, self.by", "title": ""}
{"_id": "d16126", "text": "def open01(x, limit=1.e-6):\n    \"\"\"Constrain numbers to (0,1) interval\"\"\"\n    try:\n        return np.array([min(max(y, limit), 1. - limit) for y in x])\n    except TypeError:\n        return min(max(x, limit), 1. - limit)", "title": ""}
{"_id": "d16127", "text": "def init_mq(self):\n        \"\"\"Init connection and consumer with openstack mq.\"\"\"\n        mq = self.init_connection()\n        self.init_consumer(mq)\n        return mq.connection", "title": ""}
{"_id": "d16128", "text": "def _on_text_changed(self):\n        \"\"\" Adjust dirty flag depending on editor's content \"\"\"\n        if not self._cleaning:\n            ln = TextHelper(self).cursor_position()[0]\n            self._modified_lines.add(ln)", "title": ""}
{"_id": "d16129", "text": "def qsize(self):\n        \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n        self.mutex.acquire()\n        n = self._qsize()\n        self.mutex.release()\n        return n", "title": ""}
{"_id": "d16130", "text": "def _linearInterpolationTransformMatrix(matrix1, matrix2, value):\n    \"\"\" Linear, 'oldstyle' interpolation of the transform matrix.\"\"\"\n    return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))", "title": ""}
{"_id": "d16131", "text": "def clean(some_string, uppercase=False):\n    \"\"\"\n    helper to clean up an input string\n    \"\"\"\n    if uppercase:\n        return some_string.strip().upper()\n    else:\n        return some_string.strip().lower()", "title": ""}
{"_id": "d16132", "text": "def stack_as_string():\n    \"\"\"\n    stack_as_string\n    \"\"\"\n    if sys.version_info.major == 3:\n        stack = io.StringIO()\n    else:\n        stack = io.BytesIO()\n\n    traceback.print_stack(file=stack)\n    stack.seek(0)\n    stack = stack.read()\n    return stack", "title": ""}
{"_id": "d16133", "text": "def qsize(self):\n        \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n        self.mutex.acquire()\n        n = self._qsize()\n        self.mutex.release()\n        return n", "title": ""}
{"_id": "d16134", "text": "def get_previous_month(self):\n        \"\"\"Returns date range for the previous full month.\"\"\"\n        end = utils.get_month_start() - relativedelta(days=1)\n        end = utils.to_datetime(end)\n        start = utils.get_month_start(end)\n        return start, end", "title": ""}
{"_id": "d16135", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d16136", "text": "def append_position_to_token_list(token_list):\n    \"\"\"Converts a list of Token into a list of Token, asuming size == 1\"\"\"\n    return [PositionToken(value.content, value.gd, index, index+1) for (index, value) in enumerate(token_list)]", "title": ""}
{"_id": "d16137", "text": "def ms_to_datetime(ms):\n    \"\"\"\n    Converts a millisecond accuracy timestamp to a datetime\n    \"\"\"\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)", "title": ""}
{"_id": "d16138", "text": "def display_list_by_prefix(names_list, starting_spaces=0):\n  \"\"\"Creates a help string for names_list grouped by prefix.\"\"\"\n  cur_prefix, result_lines = None, []\n  space = \" \" * starting_spaces\n  for name in sorted(names_list):\n    split = name.split(\"_\", 1)\n    prefix = split[0]\n    if cur_prefix != prefix:\n      result_lines.append(space + prefix + \":\")\n      cur_prefix = prefix\n    result_lines.append(space + \"  * \" + name)\n  return \"\\n\".join(result_lines)", "title": ""}
{"_id": "d16139", "text": "def _get_random_id():\n    \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n    symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n    return ''.join(random.choice(symbols) for _ in range(15))", "title": ""}
{"_id": "d16140", "text": "def is_iterable(value):\n    \"\"\"must be an iterable (list, array, tuple)\"\"\"\n    return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "title": ""}
{"_id": "d16141", "text": "def cint32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes int pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):\n        return np.fromiter(cptr, dtype=np.int32, count=length)\n    else:\n        raise RuntimeError('Expected int pointer')", "title": ""}
{"_id": "d16142", "text": "def flatten_array(grid):\n    \"\"\"\n    Takes a multi-dimensional array and returns a 1 dimensional array with the\n    same contents.\n    \"\"\"\n    grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))]\n    while type(grid[0]) is list:\n        grid = flatten_array(grid)\n    return grid", "title": ""}
{"_id": "d16143", "text": "def get_md5_for_file(file):\n    \"\"\"Get the md5 hash for a file.\n\n    :param file: the file to get the md5 hash for\n    \"\"\"\n    md5 = hashlib.md5()\n\n    while True:\n        data = file.read(md5.block_size)\n\n        if not data:\n            break\n\n        md5.update(data)\n\n    return md5.hexdigest()", "title": ""}
{"_id": "d16144", "text": "def _get_compiled_ext():\n    \"\"\"Official way to get the extension of compiled files (.pyc or .pyo)\"\"\"\n    for ext, mode, typ in imp.get_suffixes():\n        if typ == imp.PY_COMPILED:\n            return ext", "title": ""}
{"_id": "d16145", "text": "def get_iter_string_reader(stdin):\n    \"\"\" return an iterator that returns a chunk of a string every time it is\n    called.  notice that even though bufsize_type might be line buffered, we're\n    not doing any line buffering here.  that's because our StreamBufferer\n    handles all buffering.  we just need to return a reasonable-sized chunk. \"\"\"\n    bufsize = 1024\n    iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))\n    return get_iter_chunk_reader(iter_str)", "title": ""}
{"_id": "d16146", "text": "def _get_all_constants():\n    \"\"\"\n    Get list of all uppercase, non-private globals (doesn't start with ``_``).\n\n    Returns:\n        list: Uppercase names defined in `globals()` (variables from this \\\n              module).\n    \"\"\"\n    return [\n        key for key in globals().keys()\n        if all([\n            not key.startswith(\"_\"),          # publicly accesible\n            key.upper() == key,               # uppercase\n            type(globals()[key]) in _ALLOWED  # and with type from _ALLOWED\n        ])\n    ]", "title": ""}
{"_id": "d16147", "text": "def dedupe_list(l):\n    \"\"\"Remove duplicates from a list preserving the order.\n\n    We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n    the order, which hinders testability and does not work for lists with\n    unhashable elements.\n    \"\"\"\n    result = []\n\n    for el in l:\n        if el not in result:\n            result.append(el)\n\n    return result", "title": ""}
{"_id": "d16148", "text": "def recarray(self):\n        \"\"\"Returns data as :class:`numpy.recarray`.\"\"\"\n        return numpy.rec.fromrecords(self.records, names=self.names)", "title": ""}
{"_id": "d16149", "text": "def ip_address_list(ips):\n    \"\"\" IP address range validation and expansion. \"\"\"\n    # first, try it as a single IP address\n    try:\n        return ip_address(ips)\n    except ValueError:\n        pass\n    # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it\n    return list(ipaddress.ip_network(u(ips)).hosts())", "title": ""}
{"_id": "d16150", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d16151", "text": "def polite_string(a_string):\n    \"\"\"Returns a \"proper\" string that should work in both Py3/Py2\"\"\"\n    if is_py3() and hasattr(a_string, 'decode'):\n        try:\n            return a_string.decode('utf-8')\n        except UnicodeDecodeError:\n            return a_string\n\n    return a_string", "title": ""}
{"_id": "d16152", "text": "def import_js(path, lib_name, globals):\n    \"\"\"Imports from javascript source file.\n      globals is your globals()\"\"\"\n    with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:\n        js = f.read()\n    e = EvalJs()\n    e.execute(js)\n    var = e.context['var']\n    globals[lib_name] = var.to_python()", "title": ""}
{"_id": "d16153", "text": "def paste(cmd=paste_cmd, stdout=PIPE):\n    \"\"\"Returns system clipboard contents.\n    \"\"\"\n    return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')", "title": ""}
{"_id": "d16154", "text": "def Load(file):\n    \"\"\" Loads a model from specified file \"\"\"\n    with open(file, 'rb') as file:\n        model = dill.load(file)\n        return model", "title": ""}
{"_id": "d16155", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d16156", "text": "def load_yaml(filepath):\n    \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n    with open(filepath) as f:\n        txt = f.read()\n    return yaml.load(txt)", "title": ""}
{"_id": "d16157", "text": "def delete_lines(self):\n        \"\"\"\n        Deletes the document lines under cursor.\n\n        :return: Method success.\n        :rtype: bool\n        \"\"\"\n\n        cursor = self.textCursor()\n        self.__select_text_under_cursor_blocks(cursor)\n        cursor.removeSelectedText()\n        cursor.deleteChar()\n        return True", "title": ""}
{"_id": "d16158", "text": "def __enter__(self):\n        \"\"\"Acquire a lock on the output file, prevents collisions between multiple runs.\"\"\"\n        self.fd = open(self.filename, 'a')\n        fcntl.lockf(self.fd, fcntl.LOCK_EX)\n        return self.fd", "title": ""}
{"_id": "d16159", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d16160", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d16161", "text": "def _run_cmd_get_output(cmd):\n    \"\"\"Runs a shell command, returns console output.\n\n    Mimics python3's subprocess.getoutput\n    \"\"\"\n    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n    out, err = process.communicate()\n    return out or err", "title": ""}
{"_id": "d16162", "text": "def cric__lasso():\n    \"\"\" Lasso Regression\n    \"\"\"\n    model = sklearn.linear_model.LogisticRegression(penalty=\"l1\", C=0.002)\n\n    # we want to explain the raw probability outputs of the trees\n    model.predict = lambda X: model.predict_proba(X)[:,1]\n    \n    return model", "title": ""}
{"_id": "d16163", "text": "def unique(transactions):\n    \"\"\" Remove any duplicate entries. \"\"\"\n    seen = set()\n    # TODO: Handle comments\n    return [x for x in transactions if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d16164", "text": "def survival(value=t, lam=lam, f=failure):\n    \"\"\"Exponential survival likelihood, accounting for censoring\"\"\"\n    return sum(f * log(lam) - lam * value)", "title": ""}
{"_id": "d16165", "text": "def to_identifier(s):\n  \"\"\"\n  Convert snake_case to camel_case.\n  \"\"\"\n  if s.startswith('GPS'):\n      s = 'Gps' + s[3:]\n  return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s", "title": ""}
{"_id": "d16166", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d16167", "text": "def get_table_columns(dbconn, tablename):\n    \"\"\"\n    Return a list of tuples specifying the column name and type\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n    info = cur.fetchall()\n    cols = [(i[1], i[2]) for i in info]\n    return cols", "title": ""}
{"_id": "d16168", "text": "def strip_spaces(s):\n    \"\"\" Strip excess spaces from a string \"\"\"\n    return u\" \".join([c for c in s.split(u' ') if c])", "title": ""}
{"_id": "d16169", "text": "def is_non_empty_string(input_string):\n    \"\"\"\n    Validate if non empty string\n\n    :param input_string: Input is a *str*.\n    :return: True if input is string and non empty.\n       Raise :exc:`Exception` otherwise.\n    \"\"\"\n    try:\n        if not input_string.strip():\n            raise ValueError()\n    except AttributeError as error:\n        raise TypeError(error)\n\n    return True", "title": ""}
{"_id": "d16170", "text": "def _unordered_iterator(self):\n        \"\"\"\n        Return the value of each QuerySet, but also add the '#' property to each\n        return item.\n        \"\"\"\n        for i, qs in zip(self._queryset_idxs, self._querysets):\n            for item in qs:\n                setattr(item, '#', i)\n                yield item", "title": ""}
{"_id": "d16171", "text": "def handle_qbytearray(obj, encoding):\n    \"\"\"Qt/Python2/3 compatibility helper.\"\"\"\n    if isinstance(obj, QByteArray):\n        obj = obj.data()\n\n    return to_text_string(obj, encoding=encoding)", "title": ""}
{"_id": "d16172", "text": "def searchlast(self,n=10):\n        \"\"\"Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.\"\"\"            \n        solutions = deque([], n)\n        for solution in self:\n            solutions.append(solution)\n        return solutions", "title": ""}
{"_id": "d16173", "text": "def osx_clipboard_get():\n    \"\"\" Get the clipboard's text on OS X.\n    \"\"\"\n    p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],\n        stdout=subprocess.PIPE)\n    text, stderr = p.communicate()\n    # Text comes in with old Mac \\r line endings. Change them to \\n.\n    text = text.replace('\\r', '\\n')\n    return text", "title": ""}
{"_id": "d16174", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d16175", "text": "def magnitude(X):\n    \"\"\"Magnitude of a complex matrix.\"\"\"\n    r = np.real(X)\n    i = np.imag(X)\n    return np.sqrt(r * r + i * i);", "title": ""}
{"_id": "d16176", "text": "def pack_triples_numpy(triples):\n    \"\"\"Packs a list of triple indexes into a 2D numpy array.\"\"\"\n    if len(triples) == 0:\n        return np.array([], dtype=np.int64)\n    return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)", "title": ""}
{"_id": "d16177", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d16178", "text": "def positive_integer(anon, obj, field, val):\n    \"\"\"\n    Returns a random positive integer (for a Django PositiveIntegerField)\n    \"\"\"\n    return anon.faker.positive_integer(field=field)", "title": ""}
{"_id": "d16179", "text": "def str_dict(some_dict):\n    \"\"\"Convert dict of ascii str/unicode to dict of str, if necessary\"\"\"\n    return {str(k): str(v) for k, v in some_dict.items()}", "title": ""}
{"_id": "d16180", "text": "def runiform(lower, upper, size=None):\n    \"\"\"\n    Random uniform variates.\n    \"\"\"\n    return np.random.uniform(lower, upper, size)", "title": ""}
{"_id": "d16181", "text": "def stringify_dict_contents(dct):\n    \"\"\"Turn dict keys and values into native strings.\"\"\"\n    return {\n        str_if_nested_or_str(k): str_if_nested_or_str(v)\n        for k, v in dct.items()\n    }", "title": ""}
{"_id": "d16182", "text": "def range(self, chromosome, start, stop, exact=False):\n        \"\"\"\n        Shortcut to do range filters on genomic datasets.\n        \"\"\"\n        return self._clone(\n            filters=[GenomicFilter(chromosome, start, stop, exact)])", "title": ""}
{"_id": "d16183", "text": "def get_neg_infinity(dtype):\n    \"\"\"Return an appropriate positive infinity for this dtype.\n\n    Parameters\n    ----------\n    dtype : np.dtype\n\n    Returns\n    -------\n    fill_value : positive infinity value corresponding to this dtype.\n    \"\"\"\n    if issubclass(dtype.type, (np.floating, np.integer)):\n        return -np.inf\n\n    if issubclass(dtype.type, np.complexfloating):\n        return -np.inf - 1j * np.inf\n\n    return NINF", "title": ""}
{"_id": "d16184", "text": "def open_json(file_name):\n    \"\"\"\n    returns json contents as string\n    \"\"\"\n    with open(file_name, \"r\") as json_data:\n        data = json.load(json_data)\n        return data", "title": ""}
{"_id": "d16185", "text": "def strToBool(val):\n    \"\"\"\n    Helper function to turn a string representation of \"true\" into\n    boolean True.\n    \"\"\"\n    if isinstance(val, str):\n        val = val.lower()\n\n    return val in ['true', 'on', 'yes', True]", "title": ""}
{"_id": "d16186", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d16187", "text": "def parse_date(s):\n    \"\"\"Fast %Y-%m-%d parsing.\"\"\"\n    try:\n        return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10]))\n    except ValueError:  # other accepted format used in one-day data set\n        return datetime.datetime.strptime(s, '%d %B %Y').date()", "title": ""}
{"_id": "d16188", "text": "def read_numpy(fd, byte_order, dtype, count):\n    \"\"\"Read tag data from file and return as numpy array.\"\"\"\n    return numpy.fromfile(fd, byte_order+dtype[-1], count)", "title": ""}
{"_id": "d16189", "text": "def _clear(self):\n        \"\"\"\n        Helper that clears the composition.\n        \"\"\"\n        draw = ImageDraw.Draw(self._background_image)\n        draw.rectangle(self._device.bounding_box,\n                       fill=\"black\")\n        del draw", "title": ""}
{"_id": "d16190", "text": "def import_public_rsa_key_from_file(filename):\n    \"\"\"\n    Read a public RSA 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.rsa.RSAPublicKey instance\n    \"\"\"\n    with open(filename, \"rb\") as key_file:\n        public_key = serialization.load_pem_public_key(\n            key_file.read(),\n            backend=default_backend())\n    return public_key", "title": ""}
{"_id": "d16191", "text": "def mouse_move_event(self, event):\n        \"\"\"\n        Forward mouse cursor position events to the example\n        \"\"\"\n        self.example.mouse_position_event(event.x(), event.y())", "title": ""}
{"_id": "d16192", "text": "def get_as_bytes(self, s3_path):\n        \"\"\"\n        Get the contents of an object stored in S3 as bytes\n\n        :param s3_path: URL for target S3 location\n        :return: File contents as pure bytes\n        \"\"\"\n        (bucket, key) = self._path_to_bucket_and_key(s3_path)\n        obj = self.s3.Object(bucket, key)\n        contents = obj.get()['Body'].read()\n        return contents", "title": ""}
{"_id": "d16193", "text": "def load_data(filename):\n    \"\"\"\n    :rtype : numpy matrix\n    \"\"\"\n    data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n    return data.as_matrix()", "title": ""}
{"_id": "d16194", "text": "def _readuntil(f, end=_TYPE_END):\n\t\"\"\"Helper function to read bytes until a certain end byte is hit\"\"\"\n\tbuf = bytearray()\n\tbyte = f.read(1)\n\twhile byte != end:\n\t\tif byte == b'':\n\t\t\traise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))\n\t\tbuf += byte\n\t\tbyte = f.read(1)\n\treturn buf", "title": ""}
{"_id": "d16195", "text": "def hash_producer(*args, **kwargs):\n    \"\"\" Returns a random hash for a confirmation secret. \"\"\"\n    return hashlib.md5(six.text_type(uuid.uuid4()).encode('utf-8')).hexdigest()", "title": ""}
{"_id": "d16196", "text": "def load_yaml(filepath):\n    \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n    with open(filepath) as f:\n        txt = f.read()\n    return yaml.load(txt)", "title": ""}
{"_id": "d16197", "text": "def to_camel(s):\n    \"\"\"\n    :param string s: under_scored string to be CamelCased\n    :return: CamelCase version of input\n    :rtype: str\n    \"\"\"\n    # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n    return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "title": ""}
{"_id": "d16198", "text": "def read_dict_from_file(file_path):\n    \"\"\"\n    Read a dictionary of strings from a file\n    \"\"\"\n    with open(file_path) as file:\n        lines = file.read().splitlines()\n\n    obj = {}\n    for line in lines:\n        key, value = line.split(':', maxsplit=1)\n        obj[key] = eval(value)\n\n    return obj", "title": ""}
{"_id": "d16199", "text": "def get_translucent_cmap(r, g, b):\n\n    class TranslucentCmap(BaseColormap):\n        glsl_map = \"\"\"\n        vec4 translucent_fire(float t) {{\n            return vec4({0}, {1}, {2}, t);\n        }}\n        \"\"\".format(r, g, b)\n\n    return TranslucentCmap()", "title": ""}
{"_id": "d16200", "text": "def get_jsonparsed_data(url):\n    \"\"\"Receive the content of ``url``, parse it as JSON and return the\n       object.\n    \"\"\"\n    response = urlopen(url)\n    data = response.read().decode('utf-8')\n    return json.loads(data)", "title": ""}
{"_id": "d16201", "text": "def reduce_freqs(freqlist):\n    \"\"\"\n    Add up a list of freq counts to get the total counts.\n    \"\"\"\n    allfreqs = np.zeros_like(freqlist[0])\n    for f in freqlist:\n        allfreqs += f\n    return allfreqs", "title": ""}
{"_id": "d16202", "text": "def __setitem__(self, field, value):\n        \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n        return self._client.hset(self.key_prefix, field, self._dumps(value))", "title": ""}
{"_id": "d16203", "text": "def get_from_human_key(self, key):\n        \"\"\"Return the key (aka database value) of a human key (aka Python identifier).\"\"\"\n        if key in self._identifier_map:\n            return self._identifier_map[key]\n        raise KeyError(key)", "title": ""}
{"_id": "d16204", "text": "def retrieve_import_alias_mapping(names_list):\n    \"\"\"Creates a dictionary mapping aliases to their respective name.\n    import_alias_names is used in module_definitions.py and visit_Call\"\"\"\n    import_alias_names = dict()\n\n    for alias in names_list:\n        if alias.asname:\n            import_alias_names[alias.asname] = alias.name\n    return import_alias_names", "title": ""}
{"_id": "d16205", "text": "def get_unixtime_registered(self):\n        \"\"\"Returns the user's registration date as a UNIX timestamp.\"\"\"\n\n        doc = self._request(self.ws_prefix + \".getInfo\", True)\n\n        return int(doc.getElementsByTagName(\"registered\")[0].getAttribute(\"unixtime\"))", "title": ""}
{"_id": "d16206", "text": "def heappush_max(heap, item):\n    \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n    heap.append(item)\n    _siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d16207", "text": "def split_comma_argument(comma_sep_str):\n    \"\"\"Split a comma separated option into a list.\"\"\"\n    terms = []\n    for term in comma_sep_str.split(','):\n        if term:\n            terms.append(term)\n    return terms", "title": ""}
{"_id": "d16208", "text": "def _multiline_width(multiline_s, line_width_fn=len):\n    \"\"\"Visible width of a potentially multiline content.\"\"\"\n    return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "title": ""}
{"_id": "d16209", "text": "def input_dir(self):\n        \"\"\"\n        :returns: absolute path to where the job.ini is\n        \"\"\"\n        return os.path.abspath(os.path.dirname(self.inputs['job_ini']))", "title": ""}
{"_id": "d16210", "text": "def shader_string(body, glsl_version='450 core'):\n    \"\"\"\n    Call this method from a function that defines a literal shader string as the \"body\" argument.\n    Dresses up a shader string in three ways:\n        1) Insert #version at the top\n        2) Insert #line number declaration\n        3) un-indents\n    The line number information can help debug glsl compile errors.\n    The version string needs to be the very first characters in the shader,\n    which can be distracting, requiring backslashes or other tricks.\n    The unindenting allows you to type the shader code at a pleasing indent level\n    in your python method, while still creating an unindented GLSL string at the end.\n    \"\"\"\n    line_count = len(body.split('\\n'))\n    line_number = inspect.currentframe().f_back.f_lineno + 1 - line_count\n    return \"\"\"\\\n#version %s\n%s\n\"\"\" % (glsl_version, shader_substring(body, stack_frame=2))", "title": ""}
{"_id": "d16211", "text": "def softplus(attrs, inputs, proto_obj):\n    \"\"\"Applies the sofplus activation function element-wise to the input.\"\"\"\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs", "title": ""}
{"_id": "d16212", "text": "def get_remote_content(filepath):\n        \"\"\" A handy wrapper to get a remote file content \"\"\"\n        with hide('running'):\n            temp = BytesIO()\n            get(filepath, temp)\n            content = temp.getvalue().decode('utf-8')\n        return content.strip()", "title": ""}
{"_id": "d16213", "text": "def __len__(self):\n        \"\"\" This will equal 124 for the V1 database. \"\"\"\n        length = 0\n        for typ, siz, _ in self.format:\n            length += siz\n        return length", "title": ""}
{"_id": "d16214", "text": "def remove_bad(string):\n    \"\"\"\n    remove problem characters from string\n    \"\"\"\n    remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n    for c in remove:\n        string = string.replace(c, '_')\n    return string", "title": ""}
{"_id": "d16215", "text": "def array_bytes(array):\n    \"\"\" Estimates the memory of the supplied array in bytes \"\"\"\n    return np.product(array.shape)*np.dtype(array.dtype).itemsize", "title": ""}
{"_id": "d16216", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d16217", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d16218", "text": "def strip_accents(string):\n    \"\"\"\n    Strip all the accents from the string\n    \"\"\"\n    return u''.join(\n        (character for character in unicodedata.normalize('NFD', string)\n         if unicodedata.category(character) != 'Mn'))", "title": ""}
{"_id": "d16219", "text": "def IsBinary(self, filename):\n\t\t\"\"\"Returns true if the guessed mimetyped isnt't in text group.\"\"\"\n\t\tmimetype = mimetypes.guess_type(filename)[0]\n\t\tif not mimetype:\n\t\t\treturn False  # e.g. README, \"real\" binaries usually have an extension\n\t\t# special case for text files which don't start with text/\n\t\tif mimetype in TEXT_MIMETYPES:\n\t\t\treturn False\n\t\treturn not mimetype.startswith(\"text/\")", "title": ""}
{"_id": "d16220", "text": "def remove_punctuation(text, exceptions=[]):\n    \"\"\"\n    Return a string with punctuation removed.\n\n    Parameters:\n        text (str): The text to remove punctuation from.\n        exceptions (list): List of symbols to keep in the given text.\n\n    Return:\n        str: The input text without the punctuation.\n    \"\"\"\n\n    all_but = [\n        r'\\w',\n        r'\\s'\n    ]\n\n    all_but.extend(exceptions)\n\n    pattern = '[^{}]'.format(''.join(all_but))\n\n    return re.sub(pattern, '', text)", "title": ""}
{"_id": "d16221", "text": "def SegmentMin(a, ids):\n    \"\"\"\n    Segmented min op.\n    \"\"\"\n    func = lambda idxs: np.amin(a[idxs], axis=0)\n    return seg_map(func, a, ids),", "title": ""}
{"_id": "d16222", "text": "def remove_bad(string):\n    \"\"\"\n    remove problem characters from string\n    \"\"\"\n    remove = [':', ',', '(', ')', ' ', '|', ';', '\\'']\n    for c in remove:\n        string = string.replace(c, '_')\n    return string", "title": ""}
{"_id": "d16223", "text": "def copy_and_update(dictionary, update):\n    \"\"\"Returns an updated copy of the dictionary without modifying the original\"\"\"\n    newdict = dictionary.copy()\n    newdict.update(update)\n    return newdict", "title": ""}
{"_id": "d16224", "text": "def slugify(string):\n    \"\"\"\n    Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.\n\n\n    Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python\n    \"\"\"\n    string = re.sub('[^\\w .-]', '', string)\n    string = string.replace(\" \", \"-\")\n    return string", "title": ""}
{"_id": "d16225", "text": "def find_one_by_id(self, _id):\n        \"\"\"\n        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\n\n        \"\"\"\n        document = (yield self.collection.find_one({\"_id\": ObjectId(_id)}))\n        raise Return(self._obj_cursor_to_dictionary(document))", "title": ""}
{"_id": "d16226", "text": "def strip_spaces(value, sep=None, join=True):\n    \"\"\"Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.\"\"\"\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", "title": ""}
{"_id": "d16227", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d16228", "text": "def __normalize_list(self, msg):\n        \"\"\"Split message to list by commas and trim whitespace.\"\"\"\n        if isinstance(msg, list):\n            msg = \"\".join(msg)\n        return list(map(lambda x: x.strip(), msg.split(\",\")))", "title": ""}
{"_id": "d16229", "text": "def mostCommonItem(lst):\n    \"\"\"Choose the most common item from the list, or the first item if all\n    items are unique.\"\"\"\n    # This elegant solution from: http://stackoverflow.com/a/1518632/1760218\n    lst = [l for l in lst if l]\n    if lst:\n        return max(set(lst), key=lst.count)\n    else:\n        return None", "title": ""}
{"_id": "d16230", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d16231", "text": "def moving_average(array, n=3):\n    \"\"\"\n    Calculates the moving average of an array.\n\n    Parameters\n    ----------\n    array : array\n        The array to have the moving average taken of\n    n : int\n        The number of points of moving average to take\n    \n    Returns\n    -------\n    MovingAverageArray : array\n        The n-point moving average of the input array\n    \"\"\"\n    ret = _np.cumsum(array, dtype=float)\n    ret[n:] = ret[n:] - ret[:-n]\n    return ret[n - 1:] / n", "title": ""}
{"_id": "d16232", "text": "def remove_dups(seq):\n    \"\"\"remove duplicates from a sequence, preserving order\"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d16233", "text": "def reduce_multiline(string):\n    \"\"\"\n    reduces a multiline string to a single line of text.\n\n\n    args:\n        string: the text to reduce\n    \"\"\"\n    string = str(string)\n    return \" \".join([item.strip()\n                     for item in string.split(\"\\n\")\n                     if item.strip()])", "title": ""}
{"_id": "d16234", "text": "def get_element_with_id(self, id):\n        \"\"\"Return the element with the specified ID.\"\"\"\n        # Should we maintain a hashmap of ids to make this more efficient? Probably overkill.\n        # TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)\n        return next((el for el in self.elements if el.id == id), None)", "title": ""}
{"_id": "d16235", "text": "def store_many(self, sql, values):\n        \"\"\"Abstraction over executemany method\"\"\"\n        cursor = self.get_cursor()\n        cursor.executemany(sql, values)\n        self.conn.commit()", "title": ""}
{"_id": "d16236", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d16237", "text": "def matrixTimesVector(MM, aa):\n    \"\"\"\n\n    :param MM: A matrix of size 3x3\n    :param aa: A vector of size 3\n    :return: A vector of size 3 which is the product of the matrix by the vector\n    \"\"\"\n    bb = np.zeros(3, np.float)\n    for ii in range(3):\n        bb[ii] = np.sum(MM[ii, :] * aa)\n    return bb", "title": ""}
{"_id": "d16238", "text": "def unique(_list):\n    \"\"\"\n    Makes the list have unique items only and maintains the order\n\n    list(set()) won't provide that\n\n    :type _list list\n    :rtype: list\n    \"\"\"\n    ret = []\n\n    for item in _list:\n        if item not in ret:\n            ret.append(item)\n\n    return ret", "title": ""}
{"_id": "d16239", "text": "def multiply(self, number):\n        \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n        return self.from_list([x * number for x in self.to_list()])", "title": ""}
{"_id": "d16240", "text": "def clean_py_files(path):\n    \"\"\"\n    Removes all .py files.\n\n    :param path: the path\n    :return: None\n    \"\"\"\n\n    for dirname, subdirlist, filelist in os.walk(path):\n\n        for f in filelist:\n            if f.endswith('py'):\n                os.remove(os.path.join(dirname, f))", "title": ""}
{"_id": "d16241", "text": "def validate_string_list(lst):\n    \"\"\"Validate that the input is a list of strings.\n\n    Raises ValueError if not.\"\"\"\n    if not isinstance(lst, list):\n        raise ValueError('input %r must be a list' % lst)\n    for x in lst:\n        if not isinstance(x, basestring):\n            raise ValueError('element %r in list must be a string' % x)", "title": ""}
{"_id": "d16242", "text": "def strip_accents(text):\n    \"\"\"\n    Strip agents from a string.\n    \"\"\"\n\n    normalized_str = unicodedata.normalize('NFD', text)\n\n    return ''.join([\n        c for c in normalized_str if unicodedata.category(c) != 'Mn'])", "title": ""}
{"_id": "d16243", "text": "def close( self ):\n        \"\"\"\n        Close the db and release memory\n        \"\"\"\n        if self.db is not None:\n            self.db.commit()\n            self.db.close()\n            self.db = None\n\n        return", "title": ""}
{"_id": "d16244", "text": "def normalize_value(text):\n    \"\"\"\n    This removes newlines and multiple spaces from a string.\n    \"\"\"\n    result = text.replace('\\n', ' ')\n    result = re.subn('[ ]{2,}', ' ', result)[0]\n    return result", "title": ""}
{"_id": "d16245", "text": "def get_url_file_name(url):\n    \"\"\"Get the file name from an url\n    \n    Parameters\n    ----------\n    url : str\n\n    Returns\n    -------\n    str\n        The file name \n    \"\"\"\n\n    assert isinstance(url, (str, _oldstr))\n    return urlparse.urlparse(url).path.split('/')[-1]", "title": ""}
{"_id": "d16246", "text": "def strip_accents(s):\n    \"\"\"\n    Strip accents to prepare for slugification.\n    \"\"\"\n    nfkd = unicodedata.normalize('NFKD', unicode(s))\n    return u''.join(ch for ch in nfkd if not unicodedata.combining(ch))", "title": ""}
{"_id": "d16247", "text": "def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n        \"\"\"\n        ``numpy.ndarray`` dumper.\n        \"\"\"\n        return {\"$\" + class_name: self._json_convert(obj.tolist())}", "title": ""}
{"_id": "d16248", "text": "def drop_empty(rows):\n    \"\"\"Transpose the columns into rows, remove all of the rows that are empty after the first cell, then\n    transpose back. The result is that columns that have a header but no data in the body are removed, assuming\n    the header is the first row. \"\"\"\n    return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])", "title": ""}
{"_id": "d16249", "text": "def find_nearest_index(arr, value):\n    \"\"\"For a given value, the function finds the nearest value\n    in the array and returns its index.\"\"\"\n    arr = np.array(arr)\n    index = (abs(arr-value)).argmin()\n    return index", "title": ""}
{"_id": "d16250", "text": "def rm_keys_from_dict(d, keys):\n    \"\"\"\n    Given a dictionary and a key list, remove any data in the dictionary with the given keys.\n\n    :param dict d: Metadata\n    :param list keys: Keys to be removed\n    :return dict d: Metadata\n    \"\"\"\n    # Loop for each key given\n    for key in keys:\n        # Is the key in the dictionary?\n        if key in d:\n            try:\n                d.pop(key, None)\n            except KeyError:\n                # Not concerned with an error. Keep going.\n                pass\n    return d", "title": ""}
{"_id": "d16251", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d16252", "text": "def software_fibonacci(n):\n    \"\"\" a normal old python function to return the Nth fibonacci number. \"\"\"\n    a, b = 0, 1\n    for i in range(n):\n        a, b = b, a + b\n    return a", "title": ""}
{"_id": "d16253", "text": "def _breakRemNewlines(tag):\n\t\"\"\"non-recursively break spaces and remove newlines in the tag\"\"\"\n\tfor i,c in enumerate(tag.contents):\n\t\tif type(c) != bs4.element.NavigableString:\n\t\t\tcontinue\n\t\tc.replace_with(re.sub(r' {2,}', ' ', c).replace('\\n',''))", "title": ""}
{"_id": "d16254", "text": "def forget_xy(t):\n  \"\"\"Ignore sizes of dimensions (1, 2) of a 4d tensor in shape inference.\n\n  This allows using smaller input sizes, which create an invalid graph at higher\n  layers (for example because a spatial dimension becomes smaller than a conv\n  filter) when we only use early parts of it.\n  \"\"\"\n  shape = (t.shape[0], None, None, t.shape[3])\n  return tf.placeholder_with_default(t, shape)", "title": ""}
{"_id": "d16255", "text": "def text_cleanup(data, key, last_type):\n    \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data", "title": ""}
{"_id": "d16256", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d16257", "text": "def _remove_blank(l):\n        \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n        ret = []\n        for i, _ in enumerate(l):\n            if l[i] == 0:\n                break\n            ret.append(l[i])\n        return ret", "title": ""}
{"_id": "d16258", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d16259", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d16260", "text": "def cell_normalize(data):\n    \"\"\"\n    Returns the data where the expression is normalized so that the total\n    count per cell is equal.\n    \"\"\"\n    if sparse.issparse(data):\n        data = sparse.csc_matrix(data.astype(float))\n        # normalize in-place\n        sparse_cell_normalize(data.data,\n                data.indices,\n                data.indptr,\n                data.shape[1],\n                data.shape[0])\n        return data\n    data_norm = data.astype(float)\n    total_umis = []\n    for i in range(data.shape[1]):\n        di = data_norm[:,i]\n        total_umis.append(di.sum())\n        di /= total_umis[i]\n    med = np.median(total_umis)\n    data_norm *= med\n    return data_norm", "title": ""}
{"_id": "d16261", "text": "def _str_to_list(s):\n    \"\"\"Converts a comma separated string to a list\"\"\"\n    _list = s.split(\",\")\n    return list(map(lambda i: i.lstrip(), _list))", "title": ""}
{"_id": "d16262", "text": "def phase_correct_first(spec, freq, k):\n    \"\"\"\n    First order phase correction.\n\n    Parameters\n    ----------\n    spec : float array\n        The spectrum to be corrected.\n\n    freq : float array\n        The frequency axis.\n\n    k : float\n        The slope of the phase correction as a function of frequency.\n\n    Returns\n    -------\n    The phase-corrected spectrum.\n\n    Notes\n    -----\n    [Keeler2005] Keeler, J (2005). Understanding NMR Spectroscopy, 2nd\n        edition. Wiley. Page 88\n\n    \"\"\"\n    c_factor = np.exp(-1j * k * freq)\n    c_factor = c_factor.reshape((len(spec.shape) -1) * (1,) + c_factor.shape)\n    return spec * c_factor", "title": ""}
{"_id": "d16263", "text": "def wordify(text):\n    \"\"\"Generate a list of words given text, removing punctuation.\n\n    Parameters\n    ----------\n    text : unicode\n        A piece of english text.\n\n    Returns\n    -------\n    words : list\n        List of words.\n    \"\"\"\n    stopset = set(nltk.corpus.stopwords.words('english'))\n    tokens = nltk.WordPunctTokenizer().tokenize(text)\n    return [w for w in tokens if w not in stopset]", "title": ""}
{"_id": "d16264", "text": "def series_table_row_offset(self, series):\n        \"\"\"\n        Return the number of rows preceding the data table for *series* in\n        the Excel worksheet.\n        \"\"\"\n        title_and_spacer_rows = series.index * 2\n        data_point_rows = series.data_point_offset\n        return title_and_spacer_rows + data_point_rows", "title": ""}
{"_id": "d16265", "text": "def myreplace(astr, thefind, thereplace):\n    \"\"\"in string astr replace all occurences of thefind with thereplace\"\"\"\n    alist = astr.split(thefind)\n    new_s = alist.split(thereplace)\n    return new_s", "title": ""}
{"_id": "d16266", "text": "def series_table_row_offset(self, series):\n        \"\"\"\n        Return the number of rows preceding the data table for *series* in\n        the Excel worksheet.\n        \"\"\"\n        title_and_spacer_rows = series.index * 2\n        data_point_rows = series.data_point_offset\n        return title_and_spacer_rows + data_point_rows", "title": ""}
{"_id": "d16267", "text": "def subn_filter(s, find, replace, count=0):\n    \"\"\"A non-optimal implementation of a regex filter\"\"\"\n    return re.gsub(find, replace, count, s)", "title": ""}
{"_id": "d16268", "text": "def clean_with_zeros(self,x):\n        \"\"\" set nan and inf rows from x to zero\"\"\"\n        x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0\n        return x", "title": ""}
{"_id": "d16269", "text": "def read_array(path, mmap_mode=None):\n    \"\"\"Read a .npy array.\"\"\"\n    file_ext = op.splitext(path)[1]\n    if file_ext == '.npy':\n        return np.load(path, mmap_mode=mmap_mode)\n    raise NotImplementedError(\"The file extension `{}` \".format(file_ext) +\n                              \"is not currently supported.\")", "title": ""}
{"_id": "d16270", "text": "def escape_tex(value):\n  \"\"\"\n  Make text tex safe\n  \"\"\"\n  newval = value\n  for pattern, replacement in LATEX_SUBS:\n    newval = pattern.sub(replacement, newval)\n  return newval", "title": ""}
{"_id": "d16271", "text": "def index_nearest(value, array):\n    \"\"\"\n    expects a _n.array\n    returns the global minimum of (value-array)^2\n    \"\"\"\n\n    a = (array-value)**2\n    return index(a.min(), a)", "title": ""}
{"_id": "d16272", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d16273", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d16274", "text": "def unapostrophe(text):\n    \"\"\"Strip apostrophe and 's' from the end of a string.\"\"\"\n    text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)\n    return text", "title": ""}
{"_id": "d16275", "text": "def parse_querystring(self, req, name, field):\n        \"\"\"Pull a querystring value from the request.\"\"\"\n        return core.get_value(req.args, name, field)", "title": ""}
{"_id": "d16276", "text": "def is_serializable(obj):\n    \"\"\"Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool\n    \"\"\"\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')", "title": ""}
{"_id": "d16277", "text": "def device_state(device_id):\n    \"\"\" Get device state via HTTP GET. \"\"\"\n    if device_id not in devices:\n        return jsonify(success=False)\n    return jsonify(state=devices[device_id].state)", "title": ""}
{"_id": "d16278", "text": "def get_readonly_fields(self, request, obj=None):\n        \"\"\"Set all fields readonly.\"\"\"\n        return list(self.readonly_fields) + [field.name for field in obj._meta.fields]", "title": ""}
{"_id": "d16279", "text": "def resample(grid, wl, flux):\n    \"\"\" Resample spectrum onto desired grid \"\"\"\n    flux_rs = (interpolate.interp1d(wl, flux))(grid)\n    return flux_rs", "title": ""}
{"_id": "d16280", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d16281", "text": "def downsample_with_striding(array, factor):\n    \"\"\"Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x.\n    \"\"\"\n    return array[tuple(np.s_[::f] for f in factor)]", "title": ""}
{"_id": "d16282", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d16283", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d16284", "text": "def utime(self, *args, **kwargs):\n        \"\"\" Set the access and modified times of the file specified by path. \"\"\"\n        os.utime(self.extended_path, *args, **kwargs)", "title": ""}
{"_id": "d16285", "text": "def batchify(data, batch_size):\n    \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n    nbatch = data.shape[0] // batch_size\n    data = data[:nbatch * batch_size]\n    data = data.reshape((batch_size, nbatch)).T\n    return data", "title": ""}
{"_id": "d16286", "text": "def unpickle_file(picklefile, **kwargs):\n    \"\"\"Helper function to unpickle data from `picklefile`.\"\"\"\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)", "title": ""}
{"_id": "d16287", "text": "def batchify(data, batch_size):\n    \"\"\"Reshape data into (num_example, batch_size)\"\"\"\n    nbatch = data.shape[0] // batch_size\n    data = data[:nbatch * batch_size]\n    data = data.reshape((batch_size, nbatch)).T\n    return data", "title": ""}
{"_id": "d16288", "text": "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)", "title": ""}
{"_id": "d16289", "text": "def render_none(self, context, result):\n\t\t\"\"\"Render empty responses.\"\"\"\n\t\tcontext.response.body = b''\n\t\tdel context.response.content_length\n\t\treturn True", "title": ""}
{"_id": "d16290", "text": "def getfirstline(file, default):\n    \"\"\"\n    Returns the first line of a file.\n    \"\"\"\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\n    return default", "title": ""}
{"_id": "d16291", "text": "def do_restart(self, line):\n        \"\"\"\n        Attempt to restart the bot.\n        \"\"\"\n        self.bot._frame = 0\n        self.bot._namespace.clear()\n        self.bot._namespace.update(self.bot._initial_namespace)", "title": ""}
{"_id": "d16292", "text": "def execfile(fname, variables):\n    \"\"\" This is builtin in python2, but we have to roll our own on py3. \"\"\"\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)", "title": ""}
{"_id": "d16293", "text": "def extract_module_locals(depth=0):\n    \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n    f = sys._getframe(depth + 1)\n    global_ns = f.f_globals\n    module = sys.modules[global_ns['__name__']]\n    return (module, f.f_locals)", "title": ""}
{"_id": "d16294", "text": "def read(*args):\n    \"\"\"Reads complete file contents.\"\"\"\n    return io.open(os.path.join(HERE, *args), encoding=\"utf-8\").read()", "title": ""}
{"_id": "d16295", "text": "def get_class_method(cls_or_inst, method_name):\n    \"\"\"\n    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.\n    \"\"\"\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", "title": ""}
{"_id": "d16296", "text": "def imdecode(image_path):\n    \"\"\"Return BGR image read by opencv\"\"\"\n    import os\n    assert os.path.exists(image_path), image_path + ' not found'\n    im = cv2.imread(image_path)\n    return im", "title": ""}
{"_id": "d16297", "text": "def items(self):\n    \"\"\"Return a list of the (name, value) pairs of the enum.\n\n    These are returned in the order they were defined in the .proto file.\n    \"\"\"\n    return [(value_descriptor.name, value_descriptor.number)\n            for value_descriptor in self._enum_type.values]", "title": ""}
{"_id": "d16298", "text": "def _openpyxl_read_xl(xl_path: str):\n    \"\"\" Use openpyxl to read an Excel file. \"\"\"\n    try:\n        wb = load_workbook(filename=xl_path, read_only=True)\n    except:\n        raise\n    else:\n        return wb", "title": ""}
{"_id": "d16299", "text": "def get_column_keys_and_names(table):\n    \"\"\"\n    Return a generator of tuples k, c such that k is the name of the python attribute for\n    the column and c is the name of the column in the sql table.\n    \"\"\"\n    ins = inspect(table)\n    return ((k, c.name) for k, c in ins.mapper.c.items())", "title": ""}
{"_id": "d16300", "text": "def naturalsortkey(s):\n    \"\"\"Natural sort order\"\"\"\n    return [int(part) if part.isdigit() else part\n            for part in re.split('([0-9]+)', s)]", "title": ""}
{"_id": "d16301", "text": "def get_X0(X):\n    \"\"\" Return zero-th element of a one-element data container.\n    \"\"\"\n    if pandas_available and isinstance(X, pd.DataFrame):\n        assert len(X) == 1\n        x = np.array(X.iloc[0])\n    else:\n        x, = X\n    return x", "title": ""}
{"_id": "d16302", "text": "def project(self, other):\n        \"\"\"Return one vector projected on the vector other\"\"\"\n        n = other.normalized()\n        return self.dot(n) * n", "title": ""}
{"_id": "d16303", "text": "def preprocess(string):\n    \"\"\"\n    Preprocess string to transform all diacritics and remove other special characters than appropriate\n    \n    :param string:\n    :return:\n    \"\"\"\n    string = unicode(string, encoding=\"utf-8\")\n    # convert diacritics to simpler forms\n    string = regex1.sub(lambda x: accents[x.group()], string)\n    # remove all rest of the unwanted characters\n    return regex2.sub('', string).encode('utf-8')", "title": ""}
{"_id": "d16304", "text": "def timestamp(format=DATEFMT, timezone='Africa/Johannesburg'):\n    \"\"\" Return current datetime with timezone applied\n        [all timezones] print sorted(pytz.all_timezones) \"\"\"\n\n    return formatdate(datetime.now(tz=pytz.timezone(timezone)))", "title": ""}
{"_id": "d16305", "text": "def _try_lookup(table, value, default = \"\"):\n    \"\"\" try to get a string from the lookup table, return \"\" instead of key\n    error\n    \"\"\"\n    try:\n        string = table[ value ]\n    except KeyError:\n        string = default\n    return string", "title": ""}
{"_id": "d16306", "text": "def write_pid_file():\n    \"\"\"Write a file with the PID of this server instance.\n\n    Call when setting up a command line testserver.\n    \"\"\"\n    pidfile = os.path.basename(sys.argv[0])[:-3] + '.pid'  # strip .py, add .pid\n    with open(pidfile, 'w') as fh:\n        fh.write(\"%d\\n\" % os.getpid())\n        fh.close()", "title": ""}
{"_id": "d16307", "text": "def inverse(d):\n    \"\"\"\n    reverse the k:v pairs\n    \"\"\"\n    output = {}\n    for k, v in unwrap(d).items():\n        output[v] = output.get(v, [])\n        output[v].append(k)\n    return output", "title": ""}
{"_id": "d16308", "text": "def region_from_segment(image, segment):\n    \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n    x, y, w, h = segment\n    return image[y:y + h, x:x + w]", "title": ""}
{"_id": "d16309", "text": "def _round_half_hour(record):\n    \"\"\"\n    Round a time DOWN to half nearest half-hour.\n    \"\"\"\n    k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))\n    return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)", "title": ""}
{"_id": "d16310", "text": "def unpack2D(_x):\n    \"\"\"\n        Helper function for splitting 2D data into x and y component to make\n        equations simpler\n    \"\"\"\n    _x = np.atleast_2d(_x)\n    x = _x[:, 0]\n    y = _x[:, 1]\n    return x, y", "title": ""}
{"_id": "d16311", "text": "def __round_time(self, dt):\n    \"\"\"Round a datetime object to a multiple of a timedelta\n    dt : datetime.datetime object, default now.\n    \"\"\"\n    round_to = self._resolution.total_seconds()\n    seconds  = (dt - dt.min).seconds\n    rounding = (seconds + round_to / 2) // round_to * round_to\n    return dt + timedelta(0, rounding - seconds, -dt.microsecond)", "title": ""}
{"_id": "d16312", "text": "def resize_image_with_crop_or_pad(img, target_height, target_width):\n    \"\"\"\n    Crops and/or pads an image to a target width and height.\n\n    Resizes an image to a target width and height by either cropping the image or padding it with zeros.\n\n    NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom right)\n\n    :param img: Numpy array representing the image.\n    :param target_height: Target height.\n    :param target_width: Target width.\n    :return: The cropped and padded image.\n    \"\"\"\n    h, w = target_height, target_width\n    max_h, max_w, c = img.shape\n\n    # crop\n    img = crop_center(img, min(max_h, h), min(max_w, w))\n\n    # pad\n    padded_img = np.zeros(shape=(h, w, c), dtype=img.dtype)\n    padded_img[:img.shape[0], :img.shape[1], :img.shape[2]] = img\n\n    return padded_img", "title": ""}
{"_id": "d16313", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d16314", "text": "def _parse(self, date_str, format='%Y-%m-%d'):\n        \"\"\"\n        helper function for parsing FRED date string into datetime\n        \"\"\"\n        rv = pd.to_datetime(date_str, format=format)\n        if hasattr(rv, 'to_pydatetime'):\n            rv = rv.to_pydatetime()\n        return rv", "title": ""}
{"_id": "d16315", "text": "def home():\n    \"\"\"Temporary helper function to link to the API routes\"\"\"\n    return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \\\n        HTTPStatus.OK", "title": ""}
{"_id": "d16316", "text": "def parse_comments_for_file(filename):\n    \"\"\"\n    Return a list of all parsed comments in a file.  Mostly for testing &\n    interactive use.\n    \"\"\"\n    return [parse_comment(strip_stars(comment), next_line)\n            for comment, next_line in get_doc_comments(read_file(filename))]", "title": ""}
{"_id": "d16317", "text": "def is_valid_row(cls, row):\n        \"\"\"Indicates whether or not the given row contains valid data.\"\"\"\n        for k in row.keys():\n            if row[k] is None:\n                return False\n        return True", "title": ""}
{"_id": "d16318", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d16319", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d16320", "text": "def run(self):\n        \"\"\"Run the event loop.\"\"\"\n        self.signal_init()\n        self.listen_init()\n        self.logger.info('starting')\n        self.loop.start()", "title": ""}
{"_id": "d16321", "text": "def dict_jsonp(param):\n    \"\"\"Convert the parameter into a dictionary before calling jsonp, if it's not already one\"\"\"\n    if not isinstance(param, dict):\n        param = dict(param)\n    return jsonp(param)", "title": ""}
{"_id": "d16322", "text": "def file_read(filename):\n    \"\"\"Read a file and close it.  Returns the file source.\"\"\"\n    fobj = open(filename,'r');\n    source = fobj.read();\n    fobj.close()\n    return source", "title": ""}
{"_id": "d16323", "text": "def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):\n\t\t\"\"\"Calls the specified Trigger of another Area with the optionally given parameters.\n\n\t\tArgs:\n\t\t\ttarget: The name of the target Area.\n\t\t\ttrigger: The name of the Trigger.\n\t\t\tparameters: The parameters of the function call.\n\t\t\"\"\"\n\t\tpass", "title": ""}
{"_id": "d16324", "text": "def cat_acc(y_true, y_pred):\n    \"\"\"Categorical accuracy\n    \"\"\"\n    return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))", "title": ""}
{"_id": "d16325", "text": "def tanimoto_coefficient(a, b):\n    \"\"\"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.\n    \"\"\"\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))])", "title": ""}
{"_id": "d16326", "text": "def flatten(l, types=(list, float)):\n    \"\"\"\n    Flat nested list of lists into a single list.\n    \"\"\"\n    l = [item if isinstance(item, types) else [item] for item in l]\n    return [item for sublist in l for item in sublist]", "title": ""}
{"_id": "d16327", "text": "def dft(blk, freqs, normalize=True):\n  \"\"\"\n  Complex non-optimized Discrete Fourier Transform\n\n  Finds the DFT for values in a given frequency list, in order, over the data\n  block seen as periodic.\n\n  Parameters\n  ----------\n  blk :\n    An iterable with well-defined length. Don't use this function with Stream\n    objects!\n  freqs :\n    List of frequencies to find the DFT, in rad/sample. FFT implementations\n    like numpy.fft.ftt finds the coefficients for N frequencies equally\n    spaced as ``line(N, 0, 2 * pi, finish=False)`` for N frequencies.\n  normalize :\n    If True (default), the coefficient sums are divided by ``len(blk)``,\n    and the coefficient for the DC level (frequency equals to zero) is the\n    mean of the block. If False, that coefficient would be the sum of the\n    data in the block.\n\n  Returns\n  -------\n  A list of DFT values for each frequency, in the same order that they appear\n  in the freqs input.\n\n  Note\n  ----\n  This isn't a FFT implementation, and performs :math:`O(M . N)` float\n  pointing operations, with :math:`M` and :math:`N` equals to the length of\n  the inputs. This function can find the DFT for any specific frequency, with\n  no need for zero padding or finding all frequencies in a linearly spaced\n  band grid with N frequency bins at once.\n\n  \"\"\"\n  dft_data = (sum(xn * cexp(-1j * n * f) for n, xn in enumerate(blk))\n                                         for f in freqs)\n  if normalize:\n    lblk = len(blk)\n    return [v / lblk for v in dft_data]\n  return list(dft_data)", "title": ""}
{"_id": "d16328", "text": "def pickle_save(thing,fname):\n    \"\"\"save something to a pickle file\"\"\"\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    return thing", "title": ""}
{"_id": "d16329", "text": "def replace_list(items, match, replacement):\n    \"\"\"Replaces occurrences of a match string in a given list of strings and returns\n    a list of new strings. The match string can be a regex expression.\n\n    Args:\n        items (list):       the list of strings to modify.\n        match (str):        the search expression.\n        replacement (str):  the string to replace with.\n    \"\"\"\n    return [replace(item, match, replacement) for item in items]", "title": ""}
{"_id": "d16330", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d16331", "text": "def plot_decision_boundary(model, X, y, step=0.1, figsize=(10, 8), alpha=0.4, size=20):\n    \"\"\"Plots the classification decision boundary of `model` on `X` with labels `y`.\n    Using numpy and matplotlib.\n    \"\"\"\n\n    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n    xx, yy = np.meshgrid(np.arange(x_min, x_max, step),\n                         np.arange(y_min, y_max, step))\n\n    f, ax = plt.subplots(figsize=figsize)\n    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])\n    Z = Z.reshape(xx.shape)\n\n    ax.contourf(xx, yy, Z, alpha=alpha)\n    ax.scatter(X[:, 0], X[:, 1], c=y, s=size, edgecolor='k')\n    plt.show()", "title": ""}
{"_id": "d16332", "text": "def plot_and_save(self, **kwargs):\n        \"\"\"Used when the plot method defined does not create a figure nor calls save_plot\n        Then the plot method has to use self.fig\"\"\"\n        self.fig = pyplot.figure()\n        self.plot()\n        self.axes = pyplot.gca()\n        self.save_plot(self.fig, self.axes, **kwargs)\n        pyplot.close(self.fig)", "title": ""}
{"_id": "d16333", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d16334", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d16335", "text": "def _deserialize(cls, key, value, fields):\n        \"\"\" Marshal incoming data into Python objects.\"\"\"\n        converter = cls._get_converter_for_field(key, None, fields)\n        return converter.deserialize(value)", "title": ""}
{"_id": "d16336", "text": "def generate_write_yaml_to_file(file_name):\n    \"\"\" generate a method to write the configuration in yaml to the method desired \"\"\"\n    def write_yaml(config):\n        with open(file_name, 'w+') as fh:\n            fh.write(yaml.dump(config))\n    return write_yaml", "title": ""}
{"_id": "d16337", "text": "def print_bintree(tree, indent='  '):\n    \"\"\"print a binary tree\"\"\"\n    for n in sorted(tree.keys()):\n        print \"%s%s\" % (indent * depth(n,tree), n)", "title": ""}
{"_id": "d16338", "text": "def zoom(ax, xy='x', factor=1):\n    \"\"\"Zoom into axis.\n\n    Parameters\n    ----------\n    \"\"\"\n    limits = ax.get_xlim() if xy == 'x' else ax.get_ylim()\n    new_limits = (0.5*(limits[0] + limits[1])\n                  + 1./factor * np.array((-0.5, 0.5)) * (limits[1] - limits[0]))\n    if xy == 'x':\n        ax.set_xlim(new_limits)\n    else:\n        ax.set_ylim(new_limits)", "title": ""}
{"_id": "d16339", "text": "def raw_print(*args, **kw):\n    \"\"\"Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()", "title": ""}
{"_id": "d16340", "text": "def page_guiref(arg_s=None):\n    \"\"\"Show a basic reference about the GUI Console.\"\"\"\n    from IPython.core import page\n    page.page(gui_reference, auto_html=True)", "title": ""}
{"_id": "d16341", "text": "def pprint_for_ordereddict():\n    \"\"\"\n    Context manager that causes pprint() to print OrderedDict objects as nicely\n    as standard Python dictionary objects.\n    \"\"\"\n    od_saved = OrderedDict.__repr__\n    try:\n        OrderedDict.__repr__ = dict.__repr__\n        yield\n    finally:\n        OrderedDict.__repr__ = od_saved", "title": ""}
{"_id": "d16342", "text": "def ex(self, cmd):\n        \"\"\"Execute a normal python statement in user namespace.\"\"\"\n        with self.builtin_trap:\n            exec cmd in self.user_global_ns, self.user_ns", "title": ""}
{"_id": "d16343", "text": "def geturl(self):\n        \"\"\"\n        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.\n        \"\"\"\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", "title": ""}
{"_id": "d16344", "text": "def _elapsed(self):\n        \"\"\" Returns elapsed time at update. \"\"\"\n        self.last_time = time.time()\n        return self.last_time - self.start", "title": ""}
{"_id": "d16345", "text": "def PythonPercentFormat(format_str):\n  \"\"\"Use Python % format strings as template format specifiers.\"\"\"\n\n  if format_str.startswith('printf '):\n    fmt = format_str[len('printf '):]\n    return lambda value: fmt % value\n  else:\n    return None", "title": ""}
{"_id": "d16346", "text": "def rowlenselect(table, n, complement=False):\n    \"\"\"Select rows of length `n`.\"\"\"\n\n    where = lambda row: len(row) == n\n    return select(table, where, complement=complement)", "title": ""}
{"_id": "d16347", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d16348", "text": "def _pick_attrs(attrs, keys):\n    \"\"\" Return attrs with keys in keys list\n    \"\"\"\n    return dict((k, v) for k, v in attrs.items() if k in keys)", "title": ""}
{"_id": "d16349", "text": "def _screen(self, s, newline=False):\n        \"\"\"Print something on screen when self.verbose == True\"\"\"\n        if self.verbose:\n            if newline:\n                print(s)\n            else:\n                print(s, end=' ')", "title": ""}
{"_id": "d16350", "text": "def gen_text(env: TextIOBase, package: str, tmpl: str):\n    \"\"\"Create output from Jinja template.\"\"\"\n    if env:\n        env_args = json_datetime.load(env)\n    else:\n        env_args = {}\n    jinja_env = template.setup(package)\n    echo(jinja_env.get_template(tmpl).render(**env_args))", "title": ""}
{"_id": "d16351", "text": "def dot_v3(v, w):\n    \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n    return sum([x * y for x, y in zip(v, w)])", "title": ""}
{"_id": "d16352", "text": "def _get_url(url):\n    \"\"\"Retrieve requested URL\"\"\"\n    try:\n        data = HTTP_SESSION.get(url, stream=True)\n        data.raise_for_status()\n    except requests.exceptions.RequestException as exc:\n        raise FetcherException(exc)\n\n    return data", "title": ""}
{"_id": "d16353", "text": "def _cumprod(l):\n  \"\"\"Cumulative product of a list.\n\n  Args:\n    l: a list of integers\n  Returns:\n    a list with one more element (starting with 1)\n  \"\"\"\n  ret = [1]\n  for item in l:\n    ret.append(ret[-1] * item)\n  return ret", "title": ""}
{"_id": "d16354", "text": "def image_set_aspect(aspect=1.0, axes=\"gca\"):\n    \"\"\"\n    sets the aspect ratio of the current zoom level of the imshow image\n    \"\"\"\n    if axes is \"gca\": axes = _pylab.gca()\n\n    e = axes.get_images()[0].get_extent()\n    axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)", "title": ""}
{"_id": "d16355", "text": "def string_input(prompt=''):\n    \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n    v = sys.version[0]\n    if v == '3':\n        return input(prompt)\n    else:\n        return raw_input(prompt)", "title": ""}
{"_id": "d16356", "text": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "title": ""}
{"_id": "d16357", "text": "def MessageToDict(message,\n                  including_default_value_fields=False,\n                  preserving_proto_field_name=False):\n  \"\"\"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.\n  \"\"\"\n  printer = _Printer(including_default_value_fields,\n                     preserving_proto_field_name)\n  # pylint: disable=protected-access\n  return printer._MessageToJsonObject(message)", "title": ""}
{"_id": "d16358", "text": "def setPixel(self, x, y, color):\n        \"\"\"Set the pixel at (x,y) to the integers in sequence 'color'.\"\"\"\n        return _fitz.Pixmap_setPixel(self, x, y, color)", "title": ""}
{"_id": "d16359", "text": "def _GetFieldByName(message_descriptor, field_name):\n  \"\"\"Returns a field descriptor by field name.\n\n  Args:\n    message_descriptor: A Descriptor describing all fields in message.\n    field_name: The name of the field to retrieve.\n  Returns:\n    The field descriptor associated with the field name.\n  \"\"\"\n  try:\n    return message_descriptor.fields_by_name[field_name]\n  except KeyError:\n    raise ValueError('Protocol message %s has no \"%s\" field.' %\n                     (message_descriptor.name, field_name))", "title": ""}
{"_id": "d16360", "text": "def _prepare_proxy(self, conn):\n        \"\"\"\n        Establish tunnel connection early, because otherwise httplib\n        would improperly set Host: header to proxy's IP:port.\n        \"\"\"\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n        conn.connect()", "title": ""}
{"_id": "d16361", "text": "def toJson(protoObject, indent=None):\n    \"\"\"\n    Serialises a protobuf object as json\n    \"\"\"\n    # Using the internal method because this way we can reformat the JSON\n    js = json_format.MessageToDict(protoObject, False)\n    return json.dumps(js, indent=indent)", "title": ""}
{"_id": "d16362", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d16363", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d16364", "text": "def update(self, **kwargs):\n    \"\"\"Creates or updates a property for the instance for each parameter.\"\"\"\n    for key, value in kwargs.items():\n      setattr(self, key, value)", "title": ""}
{"_id": "d16365", "text": "def _add_hash(source):\n    \"\"\"Add a leading hash '#' at the beginning of every line in the source.\"\"\"\n    source = '\\n'.join('# ' + line.rstrip()\n                       for line in source.splitlines())\n    return source", "title": ""}
{"_id": "d16366", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d16367", "text": "def make_unique_ngrams(s, n):\n    \"\"\"Make a set of unique n-grams from a string.\"\"\"\n    return set(s[i:i + n] for i in range(len(s) - n + 1))", "title": ""}
{"_id": "d16368", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d16369", "text": "def objectproxy_realaddress(obj):\n    \"\"\"\n    Obtain a real address as an integer from an objectproxy.\n    \"\"\"\n    voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)\n    return C.addressof(C.c_char.from_buffer(voidp))", "title": ""}
{"_id": "d16370", "text": "def finish_plot():\n    \"\"\"Helper for plotting.\"\"\"\n    plt.legend()\n    plt.grid(color='0.7')\n    plt.xlabel('x')\n    plt.ylabel('y')\n    plt.show()", "title": ""}
{"_id": "d16371", "text": "def resources(self):\n        \"\"\"Retrieve contents of each page of PDF\"\"\"\n        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]", "title": ""}
{"_id": "d16372", "text": "def smallest_signed_angle(source, target):\n    \"\"\"Find the smallest angle going from angle `source` to angle `target`.\"\"\"\n    dth = target - source\n    dth = (dth + np.pi) % (2.0 * np.pi) - np.pi\n    return dth", "title": ""}
{"_id": "d16373", "text": "def closeEvent(self, event):\n        \"\"\"closeEvent reimplementation\"\"\"\n        if self.closing(True):\n            event.accept()\n        else:\n            event.ignore()", "title": ""}
{"_id": "d16374", "text": "def distance_to_line(a, b, p):\n    \"\"\"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\n    \"\"\"\n    return distance(closest_point(a, b, p), p)", "title": ""}
{"_id": "d16375", "text": "def dump_json(obj):\n    \"\"\"Dump Python object as JSON string.\"\"\"\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)", "title": ""}
{"_id": "d16376", "text": "def sine_wave(frequency):\n  \"\"\"Emit a sine wave at the given frequency.\"\"\"\n  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])\n  ts = xs / FLAGS.sample_rate\n  return tf.sin(2 * math.pi * frequency * ts)", "title": ""}
{"_id": "d16377", "text": "def string_input(prompt=''):\n    \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n    v = sys.version[0]\n    if v == '3':\n        return input(prompt)\n    else:\n        return raw_input(prompt)", "title": ""}
{"_id": "d16378", "text": "def full_s(self):\n        \"\"\" Get the full singular value matrix of self\n\n        Returns\n        -------\n        Matrix : Matrix\n\n        \"\"\"\n        x = np.zeros((self.shape),dtype=np.float32)\n\n        x[:self.s.shape[0],:self.s.shape[0]] = self.s.as_2d\n        s = Matrix(x=x, row_names=self.row_names,\n                          col_names=self.col_names, isdiagonal=False,\n                          autoalign=False)\n        return s", "title": ""}
{"_id": "d16379", "text": "def bound_symbols(self):\n        \"\"\"Set of bound SymPy symbols contained within the equation.\"\"\"\n        try:\n            lhs_syms = self.lhs.bound_symbols\n        except AttributeError:\n            lhs_syms = set()\n        try:\n            rhs_syms = self.rhs.bound_symbols\n        except AttributeError:\n            rhs_syms = set()\n        return lhs_syms | rhs_syms", "title": ""}
{"_id": "d16380", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d16381", "text": "def is_scalar(value):\n    \"\"\"Test if the given value is a scalar.\n\n    This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n    Args:\n        value: the value to test for being a scalar value\n\n    Returns:\n        boolean: if the given value is a scalar or not\n    \"\"\"\n    return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))", "title": ""}
{"_id": "d16382", "text": "def calculate_size(name, function):\n    \"\"\" Calculates the request payload size\"\"\"\n    data_size = 0\n    data_size += calculate_size_str(name)\n    data_size += calculate_size_data(function)\n    return data_size", "title": ""}
{"_id": "d16383", "text": "def _transform_triple_numpy(x):\n    \"\"\"Transform triple index into a 1-D numpy array.\"\"\"\n    return np.array([x.head, x.relation, x.tail], dtype=np.int64)", "title": ""}
{"_id": "d16384", "text": "def iget_list_column_slice(list_, start=None, stop=None, stride=None):\n    \"\"\" iterator version of get_list_column \"\"\"\n    if isinstance(start, slice):\n        slice_ = start\n    else:\n        slice_ = slice(start, stop, stride)\n    return (row[slice_] for row in list_)", "title": ""}
{"_id": "d16385", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d16386", "text": "def MatrixSolve(a, rhs, adj):\n    \"\"\"\n    Matrix solve op.\n    \"\"\"\n    return np.linalg.solve(a if not adj else _adjoint(a), rhs),", "title": ""}
{"_id": "d16387", "text": "def py3round(number):\n    \"\"\"Unified rounding in all python versions.\"\"\"\n    if abs(round(number) - number) == 0.5:\n        return int(2.0 * round(number / 2.0))\n\n    return int(round(number))", "title": ""}
{"_id": "d16388", "text": "def naturalsortkey(s):\n    \"\"\"Natural sort order\"\"\"\n    return [int(part) if part.isdigit() else part\n            for part in re.split('([0-9]+)', s)]", "title": ""}
{"_id": "d16389", "text": "def to_dicts(recarray):\n    \"\"\"convert record array to a dictionaries\"\"\"\n    for rec in recarray:\n        yield dict(zip(recarray.dtype.names, rec.tolist()))", "title": ""}
{"_id": "d16390", "text": "def unique_list(lst):\n    \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n    uniq = []\n    for item in lst:\n        if item not in uniq:\n            uniq.append(item)\n    return uniq", "title": ""}
{"_id": "d16391", "text": "def create_rot2d(angle):\n    \"\"\"Create 2D rotation matrix\"\"\"\n    ca = math.cos(angle)\n    sa = math.sin(angle)\n    return np.array([[ca, -sa], [sa, ca]])", "title": ""}
{"_id": "d16392", "text": "def naturalsortkey(s):\n    \"\"\"Natural sort order\"\"\"\n    return [int(part) if part.isdigit() else part\n            for part in re.split('([0-9]+)', s)]", "title": ""}
{"_id": "d16393", "text": "def naturalsortkey(s):\n    \"\"\"Natural sort order\"\"\"\n    return [int(part) if part.isdigit() else part\n            for part in re.split('([0-9]+)', s)]", "title": ""}
{"_id": "d16394", "text": "def ub_to_str(string):\n    \"\"\"\n    converts py2 unicode / py3 bytestring into str\n    Args:\n        string (unicode, byte_string): string to be converted\n        \n    Returns:\n        (str)\n    \"\"\"\n    if not isinstance(string, str):\n        if six.PY2:\n            return str(string)\n        else:\n            return string.decode()\n    return string", "title": ""}
{"_id": "d16395", "text": "def sort_by_name(self):\n        \"\"\"Sort list elements by name.\"\"\"\n        super(JSSObjectList, self).sort(key=lambda k: k.name)", "title": ""}
{"_id": "d16396", "text": "def _histplot_bins(column, bins=100):\n    \"\"\"Helper to get bins for histplot.\"\"\"\n    col_min = np.min(column)\n    col_max = np.max(column)\n    return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))", "title": ""}
{"_id": "d16397", "text": "def socket_close(self):\n        \"\"\"Close our socket.\"\"\"\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET", "title": ""}
{"_id": "d16398", "text": "def schunk(string, size):\n    \"\"\"Splits string into n sized chunks.\"\"\"\n    return [string[i:i+size] for i in range(0, len(string), size)]", "title": ""}
{"_id": "d16399", "text": "def _dictfetchall(self, cursor):\n        \"\"\" Return all rows from a cursor as a dict. \"\"\"\n        columns = [col[0] for col in cursor.description]\n        return [\n            dict(zip(columns, row))\n            for row in cursor.fetchall()\n        ]", "title": ""}
{"_id": "d16400", "text": "def _split(string, splitters):\n    \"\"\"Splits a string into parts at multiple characters\"\"\"\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", "title": ""}
{"_id": "d16401", "text": "def guess_media_type(filepath):\n    \"\"\"Returns the media-type of the file at the given ``filepath``\"\"\"\n    o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath])\n    o = o.strip()\n    return o", "title": ""}
{"_id": "d16402", "text": "def _split(string, splitters):\n    \"\"\"Splits a string into parts at multiple characters\"\"\"\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", "title": ""}
{"_id": "d16403", "text": "def mouse_get_pos():\n    \"\"\"\n\n    :return:\n    \"\"\"\n    p = POINT()\n    AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))\n    return p.x, p.y", "title": ""}
{"_id": "d16404", "text": "def cleanLines(source, lineSep=os.linesep):\n    \"\"\"\n    :param source: some iterable source (list, file, etc)\n    :param lineSep: string of separators (chars) that must be removed\n    :return: list of non empty lines with removed separators\n    \"\"\"\n    stripped = (line.strip(lineSep) for line in source)\n    return (line for line in stripped if len(line) != 0)", "title": ""}
{"_id": "d16405", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d16406", "text": "def _parse_string_to_list_of_pairs(s, seconds_to_int=False):\n  r\"\"\"Parses a string into a list of pairs.\n\n  In the input string, each pair is separated by a colon, and the delimiters\n  between pairs are any of \" ,.;\".\n\n  e.g. \"rows:32,cols:32\"\n\n  Args:\n    s: str to parse.\n    seconds_to_int: Boolean. If True, then the second elements are returned\n      as integers;  otherwise they are strings.\n\n  Returns:\n    List of tuple pairs.\n\n  Raises:\n    ValueError: Badly formatted string.\n  \"\"\"\n  ret = []\n  for p in [s.split(\":\") for s in re.sub(\"[,.;]\", \" \", s).split()]:\n    if len(p) != 2:\n      raise ValueError(\"bad input to _parse_string_to_list_of_pairs %s\" % s)\n    if seconds_to_int:\n      ret.append((p[0], int(p[1])))\n    else:\n      ret.append(tuple(p))\n  return ret", "title": ""}
{"_id": "d16407", "text": "def _get_or_create_stack(name):\n  \"\"\"Returns a thread local stack uniquified by the given name.\"\"\"\n  stack = getattr(_LOCAL_STACKS, name, None)\n  if stack is None:\n    stack = []\n    setattr(_LOCAL_STACKS, name, stack)\n  return stack", "title": ""}
{"_id": "d16408", "text": "def chunks(arr, size):\n    \"\"\"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`\n    \"\"\"\n    for i in _range(0, len(arr), size):\n        yield arr[i:i+size]", "title": ""}
{"_id": "d16409", "text": "def calling_logger(height=1):\n    \"\"\" Obtain a logger for the calling module.\n\n    Uses the inspect module to find the name of the calling function and its\n    position in the module hierarchy. With the optional height argument, logs\n    for caller's caller, and so forth.\n\n    see: http://stackoverflow.com/a/900404/48251\n    \"\"\"\n    stack = inspect.stack()\n    height = min(len(stack) - 1, height)\n    caller = stack[height]\n    scope = caller[0].f_globals\n    path = scope['__name__']\n    if path == '__main__':\n        path = scope['__package__'] or os.path.basename(sys.argv[0])\n    return logging.getLogger(path)", "title": ""}
{"_id": "d16410", "text": "def callproc(self, name, params, param_types=None):\n    \"\"\"Calls a procedure.\n\n    :param name: the name of the procedure\n    :param params: a list or tuple of parameters to pass to the procedure.\n    :param param_types: a list or tuple of type names. If given, each param will be cast via\n                        sql_writers typecast method. This is useful to disambiguate procedure calls\n                        when several parameters are null and therefore cause overload resoluation\n                        issues.\n    :return: a 2-tuple of (cursor, params)\n    \"\"\"\n\n    if param_types:\n      placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t)\n                      for t in param_types]\n    else:\n      placeholders = [self.sql_writer.to_placeholder() for p in params]\n\n    # TODO: This may be Postgres specific...\n    qs = \"select * from {0}({1});\".format(name, \", \".join(placeholders))\n    return self.execute(qs, params), params", "title": ""}
{"_id": "d16411", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d16412", "text": "def wipe(self):\n        \"\"\" Wipe the store\n        \"\"\"\n        query = \"DELETE FROM {}\".format(self.__tablename__)\n        connection = sqlite3.connect(self.sqlite_file)\n        cursor = connection.cursor()\n        cursor.execute(query)\n        connection.commit()", "title": ""}
{"_id": "d16413", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d16414", "text": "def sqliteRowsToDicts(sqliteRows):\n    \"\"\"\n    Unpacks sqlite rows as returned by fetchall\n    into an array of simple dicts.\n\n    :param sqliteRows: array of rows returned from fetchall DB call\n    :return:  array of dicts, keyed by the column names.\n    \"\"\"\n    return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "title": ""}
{"_id": "d16415", "text": "def loadb(b):\n    \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n    assert isinstance(b, (bytes, bytearray))\n    return std_json.loads(b.decode('utf-8'))", "title": ""}
{"_id": "d16416", "text": "def _heapify_max(x):\n    \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n    n = len(x)\n    for i in reversed(range(n//2)):\n        _siftup_max(x, i)", "title": ""}
{"_id": "d16417", "text": "def readCommaList(fileList):\n    \"\"\" Return a list of the files with the commas removed. \"\"\"\n    names=fileList.split(',')\n    fileList=[]\n    for item in names:\n        fileList.append(item)\n    return fileList", "title": ""}
{"_id": "d16418", "text": "def dumps(obj):\n    \"\"\"Outputs json with formatting edits + object handling.\"\"\"\n    return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)", "title": ""}
{"_id": "d16419", "text": "def _repr_strip(mystring):\n    \"\"\"\n    Returns the string without any initial or final quotes.\n    \"\"\"\n    r = repr(mystring)\n    if r.startswith(\"'\") and r.endswith(\"'\"):\n        return r[1:-1]\n    else:\n        return r", "title": ""}
{"_id": "d16420", "text": "def _heapify_max(x):\n    \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n    n = len(x)\n    for i in reversed(range(n//2)):\n        _siftup_max(x, i)", "title": ""}
{"_id": "d16421", "text": "def surface(self, zdata, **kwargs):\n        \"\"\"Show a 3D surface plot.\n\n        Extra keyword arguments are passed to `SurfacePlot()`.\n\n        Parameters\n        ----------\n        zdata : array-like\n            A 2D array of the surface Z values.\n\n        \"\"\"\n        self._configure_3d()\n        surf = scene.SurfacePlot(z=zdata, **kwargs)\n        self.view.add(surf)\n        self.view.camera.set_range()\n        return surf", "title": ""}
{"_id": "d16422", "text": "def Softsign(a):\n    \"\"\"\n    Softsign op.\n    \"\"\"\n    return np.divide(a, np.add(np.abs(a), 1)),", "title": ""}
{"_id": "d16423", "text": "def _encode_gif(images, fps):\n  \"\"\"Encodes numpy images into gif string.\n\n  Args:\n    images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape\n      `[time, height, width, channels]` where `channels` is 1 or 3.\n    fps: frames per second of the animation\n\n  Returns:\n    The encoded gif string.\n\n  Raises:\n    IOError: If the ffmpeg command returns an error.\n  \"\"\"\n  writer = WholeVideoWriter(fps)\n  writer.write_multi(images)\n  return writer.finish()", "title": ""}
{"_id": "d16424", "text": "def timeout_thread_handler(timeout, stop_event):\n    \"\"\"A background thread to kill the process if it takes too long.\n\n    Args:\n        timeout (float): The number of seconds to wait before killing\n            the process.\n        stop_event (Event): An optional event to cleanly stop the background\n            thread if required during testing.\n    \"\"\"\n\n    stop_happened = stop_event.wait(timeout)\n    if stop_happened is False:\n        print(\"Killing program due to %f second timeout\" % timeout)\n\n    os._exit(2)", "title": ""}
{"_id": "d16425", "text": "def main(idle):\n    \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n    while True:\n\n        LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n        time.sleep(idle)", "title": ""}
{"_id": "d16426", "text": "def stop_logging():\n    \"\"\"Stop logging to logfile and console.\"\"\"\n    from . import log\n    logger = logging.getLogger(\"gromacs\")\n    logger.info(\"GromacsWrapper %s STOPPED logging\", get_version())\n    log.clear_handlers(logger)", "title": ""}
{"_id": "d16427", "text": "def get_oauth_token():\n    \"\"\"Retrieve a simple OAuth Token for use with the local http client.\"\"\"\n    url = \"{0}/token\".format(DEFAULT_ORIGIN[\"Origin\"])\n    r = s.get(url=url)\n    return r.json()[\"t\"]", "title": ""}
{"_id": "d16428", "text": "def stop(self, reason=None):\n        \"\"\"Shutdown the service with a reason.\"\"\"\n        self.logger.info('stopping')\n        self.loop.stop(pyev.EVBREAK_ALL)", "title": ""}
{"_id": "d16429", "text": "def update(packages, env=None, user=None):\n    \"\"\"\n    Update conda packages in a conda env\n\n    Attributes\n    ----------\n        packages: list of packages comma delimited\n    \"\"\"\n    packages = ' '.join(packages.split(','))\n    cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user)\n    return _execcmd(cmd, user=user)", "title": ""}
{"_id": "d16430", "text": "def _kw(keywords):\n    \"\"\"Turn list of keywords into dictionary.\"\"\"\n    r = {}\n    for k, v in keywords:\n        r[k] = v\n    return r", "title": ""}
{"_id": "d16431", "text": "def logv(msg, *args, **kwargs):\n    \"\"\"\n    Print out a log message, only if verbose mode.\n    \"\"\"\n    if settings.VERBOSE:\n        log(msg, *args, **kwargs)", "title": ""}
{"_id": "d16432", "text": "def join(mapping, bind, values):\n    \"\"\" Merge all the strings. Put space between them. \"\"\"\n    return [' '.join([six.text_type(v) for v in values if v is not None])]", "title": ""}
{"_id": "d16433", "text": "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d16434", "text": "def _encode_bool(name, value, dummy0, dummy1):\n    \"\"\"Encode a python boolean (True/False).\"\"\"\n    return b\"\\x08\" + name + (value and b\"\\x01\" or b\"\\x00\")", "title": ""}
{"_id": "d16435", "text": "def set_as_object(self, value):\n        \"\"\"\n        Sets a new value to map element\n\n        :param value: a new element or map value.\n        \"\"\"\n        self.clear()\n        map = MapConverter.to_map(value)\n        self.append(map)", "title": ""}
{"_id": "d16436", "text": "def text_width(string, font_name, font_size):\n    \"\"\"Determine with width in pixels of string.\"\"\"\n    return stringWidth(string, fontName=font_name, fontSize=font_size)", "title": ""}
{"_id": "d16437", "text": "def activate(self):\n        \"\"\"Store ipython references in the __builtin__ namespace.\"\"\"\n\n        add_builtin = self.add_builtin\n        for name, func in self.auto_builtins.iteritems():\n            add_builtin(name, func)", "title": ""}
{"_id": "d16438", "text": "def __repr__(self):\n        \"\"\"Return list-lookalike of representation string of objects\"\"\"\n        strings = []\n        for currItem in self:\n            strings.append(\"%s\" % currItem)\n        return \"(%s)\" % (\", \".join(strings))", "title": ""}
{"_id": "d16439", "text": "def add_to_enum(self, clsdict):\n        \"\"\"\n        Compile XML mappings in addition to base add behavior.\n        \"\"\"\n        super(XmlMappedEnumMember, self).add_to_enum(clsdict)\n        self.register_xml_mapping(clsdict)", "title": ""}
{"_id": "d16440", "text": "def get_category(self):\n        \"\"\"Get the category of the item.\n\n        :return: the category of the item.\n        :returntype: `unicode`\"\"\"\n        var = self.xmlnode.prop(\"category\")\n        if not var:\n            var = \"?\"\n        return var.decode(\"utf-8\")", "title": ""}
{"_id": "d16441", "text": "def get_adjacent_matrix(self):\n        \"\"\"Get adjacency matrix.\n\n        Returns:\n            :param adj: adjacency matrix\n            :type adj: np.ndarray\n        \"\"\"\n        edges = self.edges\n        num_edges = len(edges) + 1\n        adj = np.zeros([num_edges, num_edges])\n\n        for k in range(num_edges - 1):\n            adj[edges[k].L, edges[k].R] = 1\n            adj[edges[k].R, edges[k].L] = 1\n\n        return adj", "title": ""}
{"_id": "d16442", "text": "def energy_string_to_float( string ):\n    \"\"\"\n    Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n    Args:\n        string (str): The string to convert.\n  \n    Return\n        (float) \n    \"\"\"\n    energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n    return float( energy_re.match( string ).group(0) )", "title": ""}
{"_id": "d16443", "text": "def as_dict(self):\n        \"\"\"Package up the public attributes as a dict.\"\"\"\n        attrs = vars(self)\n        return {key: attrs[key] for key in attrs if not key.startswith('_')}", "title": ""}
{"_id": "d16444", "text": "def do_striptags(value):\n    \"\"\"Strip SGML/XML tags and replace adjacent whitespace by one space.\n    \"\"\"\n    if hasattr(value, '__html__'):\n        value = value.__html__()\n    return Markup(unicode(value)).striptags()", "title": ""}
{"_id": "d16445", "text": "def dictfetchall(cursor):\n    \"\"\"Returns all rows from a cursor as a dict (rather than a headerless table)\n\n    From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/\n    \"\"\"\n    desc = cursor.description\n    return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]", "title": ""}
{"_id": "d16446", "text": "def text_cleanup(data, key, last_type):\n    \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data", "title": ""}
{"_id": "d16447", "text": "def isbinary(*args):\n    \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n    return all(map(lambda c: isnumber(c) or isbool(c), args))", "title": ""}
{"_id": "d16448", "text": "def __run_spark_submit(lane_yaml, dist_dir, spark_home, spark_args, silent):\n    \"\"\"\n    Submits the packaged application to spark using a `spark-submit` subprocess\n\n    Parameters\n    ----------\n    lane_yaml (str): Path to the YAML lane definition file\n    dist_dir (str): Path to the directory where the packaged code is located\n    spark_args (str): String of any additional spark config args to be passed when submitting\n    silent (bool): Flag indicating whether job output should be printed to console\n    \"\"\"\n    # spark-submit binary\n    cmd = ['spark-submit' if spark_home is None else os.path.join(spark_home, 'bin/spark-submit')]\n\n    # Supplied spark arguments\n    if spark_args:\n        cmd += spark_args\n\n    # Packaged App & lane\n    cmd += ['--py-files', 'libs.zip,_framework.zip,tasks.zip', 'main.py']\n    cmd += ['--lane', lane_yaml]\n\n    logging.info('Submitting to Spark')\n    logging.debug(str(cmd))\n\n    # Submit\n    devnull = open(os.devnull, 'w')\n    outp = {'stderr': STDOUT, 'stdout': devnull} if silent else {}\n    call(cmd, cwd=dist_dir, env=MY_ENV, **outp)\n    devnull.close()", "title": ""}
{"_id": "d16449", "text": "def angle(x, y):\n    \"\"\"Return the angle between vectors a and b in degrees.\"\"\"\n    return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi", "title": ""}
{"_id": "d16450", "text": "def set_title(self, title, **kwargs):\n        \"\"\"Sets the title on the underlying matplotlib AxesSubplot.\"\"\"\n        ax = self.get_axes()\n        ax.set_title(title, **kwargs)", "title": ""}
{"_id": "d16451", "text": "def write_login(collector, image, **kwargs):\n    \"\"\"Login to a docker registry with write permissions\"\"\"\n    docker_api = collector.configuration[\"harpoon\"].docker_api\n    collector.configuration[\"authentication\"].login(docker_api, image, is_pushing=True, global_docker=True)", "title": ""}
{"_id": "d16452", "text": "def correspond(text):\n    \"\"\"Communicate with the child process without closing stdin.\"\"\"\n    subproc.stdin.write(text)\n    subproc.stdin.flush()\n    return drain()", "title": ""}
{"_id": "d16453", "text": "def dictapply(d, fn):\n    \"\"\"\n    apply a function to all non-dict values in a dictionary\n    \"\"\"\n    for k, v in d.items():\n        if isinstance(v, dict):\n            v = dictapply(v, fn)\n        else:\n            d[k] = fn(v)\n    return d", "title": ""}
{"_id": "d16454", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d16455", "text": "def dictapply(d, fn):\n    \"\"\"\n    apply a function to all non-dict values in a dictionary\n    \"\"\"\n    for k, v in d.items():\n        if isinstance(v, dict):\n            v = dictapply(v, fn)\n        else:\n            d[k] = fn(v)\n    return d", "title": ""}
{"_id": "d16456", "text": "def _varargs_to_iterable_method(func):\n    \"\"\"decorator to convert a *args method to one taking a iterable\"\"\"\n    def wrapped(self, iterable, **kwargs):\n        return func(self, *iterable, **kwargs)\n    return wrapped", "title": ""}
{"_id": "d16457", "text": "def redirect(cls, request, response):\n        \"\"\"Redirect to the canonical URI for this resource.\"\"\"\n        if cls.meta.legacy_redirect:\n            if request.method in ('GET', 'HEAD',):\n                # A SAFE request is allowed to redirect using a 301\n                response.status = http.client.MOVED_PERMANENTLY\n\n            else:\n                # All other requests must use a 307\n                response.status = http.client.TEMPORARY_REDIRECT\n\n        else:\n            # Modern redirects are allowed. Let's have some fun.\n            # Hopefully you're client supports this.\n            # The RFC explicitly discourages UserAgent sniffing.\n            response.status = http.client.PERMANENT_REDIRECT\n\n        # Terminate the connection.\n        response.close()", "title": ""}
{"_id": "d16458", "text": "def _replace_variables(data, variables):\n    \"\"\"Replace the format variables in all items of data.\"\"\"\n    formatter = string.Formatter()\n    return [formatter.vformat(item, [], variables) for item in data]", "title": ""}
{"_id": "d16459", "text": "def format_exc(*exc_info):\n    \"\"\"Show exception with traceback.\"\"\"\n    typ, exc, tb = exc_info or sys.exc_info()\n    error = traceback.format_exception(typ, exc, tb)\n    return \"\".join(error)", "title": ""}
{"_id": "d16460", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d16461", "text": "def string_to_identity(identity_str):\n    \"\"\"Parse string into Identity dictionary.\"\"\"\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}", "title": ""}
{"_id": "d16462", "text": "def get_tri_area(pts):\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d16463", "text": "def datetime_match(data, dts):\n    \"\"\"\n    matching of datetimes in time columns for data filtering\n    \"\"\"\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)", "title": ""}
{"_id": "d16464", "text": "def register_action(action):\n  \"\"\"\n  Adds an action to the parser cli.\n\n  :param action(BaseAction): a subclass of the BaseAction class\n  \"\"\"\n  sub = _subparsers.add_parser(action.meta('cmd'), help=action.meta('help'))\n  sub.set_defaults(cmd=action.meta('cmd'))\n  for (name, arg) in action.props().items():\n    sub.add_argument(arg.name, arg.flag, **arg.options)\n    _actions[action.meta('cmd')] = action", "title": ""}
{"_id": "d16465", "text": "def _uniquify(_list):\n    \"\"\"Remove duplicates in a list.\"\"\"\n    seen = set()\n    result = []\n    for x in _list:\n        if x not in seen:\n            result.append(x)\n            seen.add(x)\n    return result", "title": ""}
{"_id": "d16466", "text": "def parse_command_args():\n    \"\"\"Command line parser.\"\"\"\n    parser = argparse.ArgumentParser(description='Register PB devices.')\n    parser.add_argument('num_pb', type=int,\n                        help='Number of PBs devices to register.')\n    return parser.parse_args()", "title": ""}
{"_id": "d16467", "text": "def tuple_check(*args, func=None):\n    \"\"\"Check if arguments are tuple type.\"\"\"\n    func = func or inspect.stack()[2][3]\n    for var in args:\n        if not isinstance(var, (tuple, collections.abc.Sequence)):\n            name = type(var).__name__\n            raise TupleError(\n                f'Function {func} expected tuple, {name} got instead.')", "title": ""}
{"_id": "d16468", "text": "def kwargs_to_string(kwargs):\n    \"\"\"\n    Given a set of kwargs, turns them into a string which can then be passed to a command.\n    :param kwargs: kwargs from a function call.\n    :return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.\n    \"\"\"\n    outstr = ''\n    for arg in kwargs:\n        outstr += ' -{} {}'.format(arg, kwargs[arg])\n    return outstr", "title": ""}
{"_id": "d16469", "text": "def process_wait(process, timeout=0):\n    \"\"\"\n    Pauses script execution until a given process exists.\n    :param process:\n    :param timeout:\n    :return:\n    \"\"\"\n    ret = AUTO_IT.AU3_ProcessWait(LPCWSTR(process), INT(timeout))\n    return ret", "title": ""}
{"_id": "d16470", "text": "def _most_common(iterable):\n    \"\"\"Returns the most common element in `iterable`.\"\"\"\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)", "title": ""}
{"_id": "d16471", "text": "def unit_ball_L2(shape):\n  \"\"\"A tensorflow variable tranfomed to be constrained in a L2 unit ball.\n\n  EXPERIMENTAL: Do not use for adverserial examples if you need to be confident\n  they are strong attacks. We are not yet confident in this code.\n  \"\"\"\n  x = tf.Variable(tf.zeros(shape))\n  return constrain_L2(x)", "title": ""}
{"_id": "d16472", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d16473", "text": "def transformer_tall_pretrain_lm_tpu_adafactor():\n  \"\"\"Hparams for transformer on LM pretraining (with 64k vocab) on TPU.\"\"\"\n  hparams = transformer_tall_pretrain_lm()\n  update_hparams_for_tpu(hparams)\n  hparams.max_length = 1024\n  # For multi-problem on TPU we need it in absolute examples.\n  hparams.batch_size = 8\n  hparams.multiproblem_vocab_size = 2**16\n  return hparams", "title": ""}
{"_id": "d16474", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d16475", "text": "def is_timestamp(instance):\n    \"\"\"Validates data is a timestamp\"\"\"\n    if not isinstance(instance, (int, str)):\n        return True\n    return datetime.fromtimestamp(int(instance))", "title": ""}
{"_id": "d16476", "text": "def from_array(cls, arr):\n        \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n        return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "title": ""}
{"_id": "d16477", "text": "def is_lazy_iterable(obj):\n    \"\"\"\n    Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n    \"\"\"\n    return isinstance(obj,\n        (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))", "title": ""}
{"_id": "d16478", "text": "def connection_lost(self, exc):\n        \"\"\"Called when asyncio.Protocol loses the network connection.\"\"\"\n        if exc is None:\n            self.log.warning('eof from receiver?')\n        else:\n            self.log.warning('Lost connection to receiver: %s', exc)\n\n        self.transport = None\n\n        if self._connection_lost_callback:\n            self._loop.call_soon(self._connection_lost_callback)", "title": ""}
{"_id": "d16479", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d16480", "text": "def connection_lost(self, exc):\n        \"\"\"Called when asyncio.Protocol loses the network connection.\"\"\"\n        if exc is None:\n            self.log.warning('eof from receiver?')\n        else:\n            self.log.warning('Lost connection to receiver: %s', exc)\n\n        self.transport = None\n\n        if self._connection_lost_callback:\n            self._loop.call_soon(self._connection_lost_callback)", "title": ""}
{"_id": "d16481", "text": "def average(iterator):\n    \"\"\"Iterative mean.\"\"\"\n    count = 0\n    total = 0\n    for num in iterator:\n        count += 1\n        total += num\n    return float(total)/count", "title": ""}
{"_id": "d16482", "text": "def StringIO(*args, **kwargs):\n    \"\"\"StringIO constructor shim for the async wrapper.\"\"\"\n    raw = sync_io.StringIO(*args, **kwargs)\n    return AsyncStringIOWrapper(raw)", "title": ""}
{"_id": "d16483", "text": "def convert_timezone(obj, timezone):\n    \"\"\"Convert `obj` to the timezone `timezone`.\n\n    Parameters\n    ----------\n    obj : datetime.date or datetime.datetime\n\n    Returns\n    -------\n    type(obj)\n    \"\"\"\n    if timezone is None:\n        return obj.replace(tzinfo=None)\n    return pytz.timezone(timezone).localize(obj)", "title": ""}
{"_id": "d16484", "text": "async def write(self, data):\n        \"\"\"\n        :py:func:`asyncio.coroutine`\n\n        :py:meth:`aioftp.StreamIO.write` proxy\n        \"\"\"\n        await self.wait(\"write\")\n        start = _now()\n        await super().write(data)\n        self.append(\"write\", data, start)", "title": ""}
{"_id": "d16485", "text": "def yview(self, *args):\n        \"\"\"Update inplace widgets position when doing vertical scroll\"\"\"\n        self.after_idle(self.__updateWnds)\n        ttk.Treeview.yview(self, *args)", "title": ""}
{"_id": "d16486", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d16487", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d16488", "text": "def Distance(lat1, lon1, lat2, lon2):\n    \"\"\"Get distance between pairs of lat-lon points\"\"\"\n\n    az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)\n    return az21, dist", "title": ""}
{"_id": "d16489", "text": "def codebox(msg=\"\", title=\" \", text=\"\"):\n    \"\"\"\n    Display some text in a monospaced font, with no line wrapping.\n    This function is suitable for displaying code and text that is\n    formatted using spaces.\n\n    The text parameter should be a string, or a list or tuple of lines to be\n    displayed in the textbox.\n\n    :param str msg: the msg to be displayed\n    :param str title: the window title\n    :param str text: what to display in the textbox\n    \"\"\"\n    return tb.textbox(msg, title, text, codebox=1)", "title": ""}
{"_id": "d16490", "text": "def pp_xml(body):\n    \"\"\"Pretty print format some XML so it's readable.\"\"\"\n    pretty = xml.dom.minidom.parseString(body)\n    return pretty.toprettyxml(indent=\"  \")", "title": ""}
{"_id": "d16491", "text": "def isetdiff_flags(list1, list2):\n    \"\"\"\n    move to util_iter\n    \"\"\"\n    set2 = set(list2)\n    return (item not in set2 for item in list1)", "title": ""}
{"_id": "d16492", "text": "def csv_to_dicts(file, header=None):\n    \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n    with open(file) as csvfile:\n        return [row for row in csv.DictReader(csvfile, fieldnames=header)]", "title": ""}
{"_id": "d16493", "text": "def printComparison(results, class_or_prop):\n\t\"\"\"\n\tprint(out the results of the comparison using a nice table)\n\t\"\"\"\n\n\tdata = []\n\n\tRow = namedtuple('Row',[class_or_prop,'VALIDATED'])\n\n\tfor k,v in sorted(results.items(), key=lambda x: x[1]):\n\t\tdata += [Row(k, str(v))]\n\n\tpprinttable(data)", "title": ""}
{"_id": "d16494", "text": "def rgb2gray(img):\n    \"\"\"Converts an RGB image to grayscale using matlab's algorithm.\"\"\"\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", "title": ""}
{"_id": "d16495", "text": "def xmltreefromfile(filename):\n    \"\"\"Internal function to read an XML file\"\"\"\n    try:\n        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n    except TypeError:\n        return ElementTree.parse(filename, ElementTree.XMLParser())", "title": ""}
{"_id": "d16496", "text": "def val_to_bin(edges, x):\n    \"\"\"Convert axis coordinate to bin index.\"\"\"\n    ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n    return ibin", "title": ""}
{"_id": "d16497", "text": "def split_long_sentence(sentence, words_per_line):\n    \"\"\"Takes a sentence and adds a newline every \"words_per_line\" words.\n\n    Parameters\n    ----------\n    sentence: str\n        Sentene to split\n    words_per_line: double\n        Add a newline every this many words\n    \"\"\"\n    words = sentence.split(' ')\n    split_sentence = ''\n    for i in range(len(words)):\n        split_sentence = split_sentence + words[i]\n        if (i+1) % words_per_line == 0:\n            split_sentence = split_sentence + '\\n'\n        elif i != len(words) - 1:\n            split_sentence = split_sentence + \" \"\n    return split_sentence", "title": ""}
{"_id": "d16498", "text": "def hook_focus_events(self):\n        \"\"\" Install the hooks for focus events.\n\n        This method may be overridden by subclasses as needed.\n\n        \"\"\"\n        widget = self.widget\n        widget.focusInEvent = self.focusInEvent\n        widget.focusOutEvent = self.focusOutEvent", "title": ""}
{"_id": "d16499", "text": "def mouse_move_event(self, event):\n        \"\"\"\n        Forward mouse cursor position events to the example\n        \"\"\"\n        self.example.mouse_position_event(event.x(), event.y())", "title": ""}
{"_id": "d16500", "text": "def to_dicts(recarray):\n    \"\"\"convert record array to a dictionaries\"\"\"\n    for rec in recarray:\n        yield dict(zip(recarray.dtype.names, rec.tolist()))", "title": ""}
{"_id": "d16501", "text": "def needs_update(self, cache_key):\n    \"\"\"Check if the given cached item is invalid.\n\n    :param cache_key: A CacheKey object (as returned by CacheKeyGenerator.key_for().\n    :returns: True if the cached version of the item is out of date.\n    \"\"\"\n    if not self.cacheable(cache_key):\n      # An uncacheable CacheKey is always out of date.\n      return True\n\n    return self._read_sha(cache_key) != cache_key.hash", "title": ""}
{"_id": "d16502", "text": "def _trim(self, somestr):\n        \"\"\" Trim left-right given string \"\"\"\n        tmp = RE_LSPACES.sub(\"\", somestr)\n        tmp = RE_TSPACES.sub(\"\", tmp)\n        return str(tmp)", "title": ""}
{"_id": "d16503", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d16504", "text": "def update(self, params):\n        \"\"\"Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device.\n        \"\"\"\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "title": ""}
{"_id": "d16505", "text": "def be_array_from_bytes(fmt, data):\n    \"\"\"\n    Reads an array from bytestring with big-endian data.\n    \"\"\"\n    arr = array.array(str(fmt), data)\n    return fix_byteorder(arr)", "title": ""}
{"_id": "d16506", "text": "async def packets_from_tshark(self, packet_callback, packet_count=None, close_tshark=True):\n        \"\"\"\n        A coroutine which creates a tshark process, runs the given callback on each packet that is received from it and\n        closes the process when it is done.\n\n        Do not use interactively. Can be used in order to insert packets into your own eventloop.\n        \"\"\"\n        tshark_process = await self._get_tshark_process(packet_count=packet_count)\n        try:\n            await self._go_through_packets_from_fd(tshark_process.stdout, packet_callback, packet_count=packet_count)\n        except StopCapture:\n            pass\n        finally:\n            if close_tshark:\n                await self._close_async()", "title": ""}
{"_id": "d16507", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d16508", "text": "def _to_array(value):\n    \"\"\"As a convenience, turn Python lists and tuples into NumPy arrays.\"\"\"\n    if isinstance(value, (tuple, list)):\n        return array(value)\n    elif isinstance(value, (float, int)):\n        return np.float64(value)\n    else:\n        return value", "title": ""}
{"_id": "d16509", "text": "def cast_bytes(s, encoding=None):\n    \"\"\"Source: https://github.com/ipython/ipython_genutils\"\"\"\n    if not isinstance(s, bytes):\n        return encode(s, encoding)\n    return s", "title": ""}
{"_id": "d16510", "text": "def to_binary(s, encoding='utf8'):\n    \"\"\"Portable cast function.\n\n    In python 2 the ``str`` function which is used to coerce objects to bytes does not\n    accept an encoding argument, whereas python 3's ``bytes`` function requires one.\n\n    :param s: object to be converted to binary_type\n    :return: binary_type instance, representing s.\n    \"\"\"\n    if PY3:  # pragma: no cover\n        return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)\n    return binary_type(s)", "title": ""}
{"_id": "d16511", "text": "def bin_to_int(string):\n    \"\"\"Convert a one element byte string to signed int for python 2 support.\"\"\"\n    if isinstance(string, str):\n        return struct.unpack(\"b\", string)[0]\n    else:\n        return struct.unpack(\"b\", bytes([string]))[0]", "title": ""}
{"_id": "d16512", "text": "def s2b(s):\n    \"\"\"\n    String to binary.\n    \"\"\"\n    ret = []\n    for c in s:\n        ret.append(bin(ord(c))[2:].zfill(8))\n    return \"\".join(ret)", "title": ""}
{"_id": "d16513", "text": "def _bytes_to_json(value):\n    \"\"\"Coerce 'value' to an JSON-compatible representation.\"\"\"\n    if isinstance(value, bytes):\n        value = base64.standard_b64encode(value).decode(\"ascii\")\n    return value", "title": ""}
{"_id": "d16514", "text": "def time2seconds(t):\n    \"\"\"Returns seconds since 0h00.\"\"\"\n    return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6", "title": ""}
{"_id": "d16515", "text": "def check_clang_apply_replacements_binary(args):\n  \"\"\"Checks if invoking supplied clang-apply-replacements binary works.\"\"\"\n  try:\n    subprocess.check_call([args.clang_apply_replacements_binary, '--version'])\n  except:\n    print('Unable to run clang-apply-replacements. Is clang-apply-replacements '\n          'binary correctly specified?', file=sys.stderr)\n    traceback.print_exc()\n    sys.exit(1)", "title": ""}
{"_id": "d16516", "text": "def runiform(lower, upper, size=None):\n    \"\"\"\n    Random uniform variates.\n    \"\"\"\n    return np.random.uniform(lower, upper, size)", "title": ""}
{"_id": "d16517", "text": "def getCachedDataKey(engineVersionHash, key):\n\t\t\"\"\"\n\t\tRetrieves the cached data value for the specified engine version hash and dictionary key\n\t\t\"\"\"\n\t\tcacheFile = CachedDataManager._cacheFileForHash(engineVersionHash)\n\t\treturn JsonDataManager(cacheFile).getKey(key)", "title": ""}
{"_id": "d16518", "text": "def uniq(seq):\n    \"\"\" Return a copy of seq without duplicates. \"\"\"\n    seen = set()\n    return [x for x in seq if str(x) not in seen and not seen.add(str(x))]", "title": ""}
{"_id": "d16519", "text": "def Distance(lat1, lon1, lat2, lon2):\n    \"\"\"Get distance between pairs of lat-lon points\"\"\"\n\n    az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)\n    return az21, dist", "title": ""}
{"_id": "d16520", "text": "def get_labels(labels):\n    \"\"\"Create unique labels.\"\"\"\n    label_u = unique_labels(labels)\n    label_u_line = [i + \"_line\" for i in label_u]\n    return label_u, label_u_line", "title": ""}
{"_id": "d16521", "text": "def get_tri_area(pts):\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d16522", "text": "def remove_duplicates(seq):\n    \"\"\"\n    Return unique elements from list while preserving order.\n    From https://stackoverflow.com/a/480227/2589328\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d16523", "text": "def var(series):\n    \"\"\"\n    Returns the variance of values in a series.\n\n    Args:\n        series (pandas.Series): column to summarize.\n    \"\"\"\n    if np.issubdtype(series.dtype, np.number):\n        return series.var()\n    else:\n        return np.nan", "title": ""}
{"_id": "d16524", "text": "def uniquify_list(L):\n    \"\"\"Same order unique list using only a list compression.\"\"\"\n    return [e for i, e in enumerate(L) if L.index(e) == i]", "title": ""}
{"_id": "d16525", "text": "def sequence_molecular_weight(seq):\n    \"\"\"Returns the molecular weight of the polypeptide sequence.\n\n    Notes\n    -----\n    Units = Daltons\n\n    Parameters\n    ----------\n    seq : str\n        Sequence of amino acids.\n    \"\"\"\n    if 'X' in seq:\n        warnings.warn(_nc_warning_str, NoncanonicalWarning)\n    return sum(\n        [residue_mwt[aa] * n for aa, n in Counter(seq).items()]) + water_mass", "title": ""}
{"_id": "d16526", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d16527", "text": "def do(self):\n        \"\"\"\n        Set a restore point (copy the object), then call the method.\n        :return: obj.do_method(*args)\n        \"\"\"\n        self.restore_point = self.obj.copy()\n        return self.do_method(self.obj, *self.args)", "title": ""}
{"_id": "d16528", "text": "def __unixify(self, s):\n        \"\"\" stupid windows. converts the backslash to forwardslash for consistency \"\"\"\n        return os.path.normpath(s).replace(os.sep, \"/\")", "title": ""}
{"_id": "d16529", "text": "def python(string: str):\n        \"\"\"\n            :param string: String can be type, resource or python case\n        \"\"\"\n        return underscore(singularize(string) if Naming._pluralize(string) else string)", "title": ""}
{"_id": "d16530", "text": "def update(self):\n        \"\"\"Update all visuals in the attached canvas.\"\"\"\n        if not self.canvas:\n            return\n        for visual in self.canvas.visuals:\n            self.update_program(visual.program)\n        self.canvas.update()", "title": ""}
{"_id": "d16531", "text": "def min_or_none(val1, val2):\n    \"\"\"Returns min(val1, val2) returning None only if both values are None\"\"\"\n    return min(val1, val2, key=lambda x: sys.maxint if x is None else x)", "title": ""}
{"_id": "d16532", "text": "def read_credentials(fname):\n    \"\"\"\n    read a simple text file from a private location to get\n    username and password\n    \"\"\"\n    with open(fname, 'r') as f:\n        username = f.readline().strip('\\n')\n        password = f.readline().strip('\\n')\n    return username, password", "title": ""}
{"_id": "d16533", "text": "def _parallel_compare_helper(class_obj, pairs, x, x_link=None):\n    \"\"\"Internal function to overcome pickling problem in python2.\"\"\"\n    return class_obj._compute(pairs, x, x_link)", "title": ""}
{"_id": "d16534", "text": "def transformer_tall_pretrain_lm_tpu_adafactor():\n  \"\"\"Hparams for transformer on LM pretraining (with 64k vocab) on TPU.\"\"\"\n  hparams = transformer_tall_pretrain_lm()\n  update_hparams_for_tpu(hparams)\n  hparams.max_length = 1024\n  # For multi-problem on TPU we need it in absolute examples.\n  hparams.batch_size = 8\n  hparams.multiproblem_vocab_size = 2**16\n  return hparams", "title": ""}
{"_id": "d16535", "text": "def out_shape_from_array(arr):\n    \"\"\"Get the output shape from an array.\"\"\"\n    arr = np.asarray(arr)\n    if arr.ndim == 1:\n        return arr.shape\n    else:\n        return (arr.shape[1],)", "title": ""}
{"_id": "d16536", "text": "def isnumber(*args):\n    \"\"\"Checks if value is an integer, long integer or float.\n\n    NOTE: Treats booleans as numbers, where True=1 and False=0.\n    \"\"\"\n    return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))", "title": ""}
{"_id": "d16537", "text": "def clear(self):\n        \"\"\"Clear the displayed image.\"\"\"\n        self._imgobj = None\n        try:\n            # See if there is an image on the canvas\n            self.canvas.delete_object_by_tag(self._canvas_img_tag)\n            self.redraw()\n        except KeyError:\n            pass", "title": ""}
{"_id": "d16538", "text": "def send(socket, data, num_bytes=20):\n    \"\"\"Send data to specified socket.\n\n\n    :param socket: open socket instance\n    :param data: data to send\n    :param num_bytes: number of bytes to read\n\n    :return: received data\n    \"\"\"\n    pickled_data = pickle.dumps(data, -1)\n    length = str(len(pickled_data)).zfill(num_bytes)\n    socket.sendall(length.encode())\n    socket.sendall(pickled_data)", "title": ""}
{"_id": "d16539", "text": "def decamelise(text):\n    \"\"\"Convert CamelCase to lower_and_underscore.\"\"\"\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()", "title": ""}
{"_id": "d16540", "text": "def _request_modify_dns_record(self, record):\n        \"\"\"Sends Modify_DNS_Record request\"\"\"\n        return self._request_internal(\"Modify_DNS_Record\",\n                                      domain=self.domain,\n                                      record=record)", "title": ""}
{"_id": "d16541", "text": "def is_equal_strings_ignore_case(first, second):\n    \"\"\"The function compares strings ignoring case\"\"\"\n    if first and second:\n        return first.upper() == second.upper()\n    else:\n        return not (first or second)", "title": ""}
{"_id": "d16542", "text": "def hclust_linearize(U):\n    \"\"\"Sorts the rows of a matrix by hierarchical clustering.\n\n    Parameters:\n        U (ndarray) : matrix of data\n\n    Returns:\n        prm (ndarray) : permutation of the rows\n    \"\"\"\n\n    from scipy.cluster import hierarchy\n    Z = hierarchy.ward(U)\n    return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))", "title": ""}
{"_id": "d16543", "text": "def convert_array(array):\n    \"\"\"\n    Converts an ARRAY string stored in the database back into a Numpy array.\n\n    Parameters\n    ----------\n    array: ARRAY\n        The array object to be converted back into a Numpy array.\n\n    Returns\n    -------\n    array\n            The converted Numpy array.\n\n    \"\"\"\n    out = io.BytesIO(array)\n    out.seek(0)\n    return np.load(out)", "title": ""}
{"_id": "d16544", "text": "def ask_str(question: str, default: str = None):\n    \"\"\"Asks for a simple string\"\"\"\n    default_q = \" [default: {0}]: \".format(\n        default) if default is not None else \"\"\n    answer = input(\"{0} [{1}]: \".format(question, default_q))\n\n    if answer == \"\":\n        return default\n    return answer", "title": ""}
{"_id": "d16545", "text": "def col_rename(df,col_name,new_col_name):\n    \"\"\" Changes a column name in a DataFrame\n    Parameters:\n    df - DataFrame\n        DataFrame to operate on\n    col_name - string\n        Name of column to change\n    new_col_name - string\n        New name of column\n    \"\"\"\n    col_list = list(df.columns)\n    for index,value in enumerate(col_list):\n        if value == col_name:\n            col_list[index] = new_col_name\n            break\n    df.columns = col_list", "title": ""}
{"_id": "d16546", "text": "def get_ctype(rtype, cfunc, *args):\n    \"\"\" 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\n    \"\"\"\n    val_p = backend.ffi.new(rtype)\n    args = args + (val_p,)\n    cfunc(*args)\n    return val_p[0]", "title": ""}
{"_id": "d16547", "text": "def convert_str_to_datetime(df, *, column: str, format: str):\n    \"\"\"\n    Convert string column into datetime column\n\n    ---\n\n    ### Parameters\n\n    *mandatory :*\n    - `column` (*str*): name of the column to format\n    - `format` (*str*): current format of the values (see [available formats](\n    https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))\n    \"\"\"\n    df[column] = pd.to_datetime(df[column], format=format)\n    return df", "title": ""}
{"_id": "d16548", "text": "def _openResources(self):\n        \"\"\" Uses numpy.load to open the underlying file\n        \"\"\"\n        arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n        check_is_an_array(arr)\n        self._array = arr", "title": ""}
{"_id": "d16549", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d16550", "text": "def do_exit(self, arg):\n        \"\"\"Exit the shell session.\"\"\"\n\n        if self.current:\n            self.current.close()\n        self.resource_manager.close()\n        del self.resource_manager\n        return True", "title": ""}
{"_id": "d16551", "text": "def get_year_start(day=None):\n    \"\"\"Returns January 1 of the given year.\"\"\"\n    day = add_timezone(day or datetime.date.today())\n    return day.replace(month=1).replace(day=1)", "title": ""}
{"_id": "d16552", "text": "def print_matrix(X, decimals=1):\n    \"\"\"Pretty printing for numpy matrix X\"\"\"\n    for row in np.round(X, decimals=decimals):\n        print(row)", "title": ""}
{"_id": "d16553", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d16554", "text": "def CleanseComments(line):\n  \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n  Args:\n    line: A line of C++ source.\n\n  Returns:\n    The line with single-line comments removed.\n  \"\"\"\n  commentpos = line.find('//')\n  if commentpos != -1 and not IsCppString(line[:commentpos]):\n    line = line[:commentpos].rstrip()\n  # get rid of /* ... */\n  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "title": ""}
{"_id": "d16555", "text": "def set_cursor(self, x, y):\n        \"\"\"\n        Sets the cursor to the desired position.\n\n        :param x: X position\n        :param y: Y position\n        \"\"\"\n        curses.curs_set(1)\n        self.screen.move(y, x)", "title": ""}
{"_id": "d16556", "text": "def _remove_duplicate_files(xs):\n    \"\"\"Remove files specified multiple times in a list.\n    \"\"\"\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", "title": ""}
{"_id": "d16557", "text": "def process_result_value(self, value, dialect):\n        \"\"\"convert value from json to a python object\"\"\"\n        if value is not None:\n            value = simplejson.loads(value)\n        return value", "title": ""}
{"_id": "d16558", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d16559", "text": "def _zeep_to_dict(cls, obj):\n        \"\"\"Convert a zeep object to a dictionary.\"\"\"\n        res = serialize_object(obj)\n        res = cls._get_non_empty_dict(res)\n        return res", "title": ""}
{"_id": "d16560", "text": "def test(*args):\n    \"\"\"\n    Run unit tests.\n    \"\"\"\n    subprocess.call([\"py.test-2.7\"] + list(args))\n    subprocess.call([\"py.test-3.4\"] + list(args))", "title": ""}
{"_id": "d16561", "text": "def log_y_cb(self, w, val):\n        \"\"\"Toggle linear/log scale for Y-axis.\"\"\"\n        self.tab_plot.logy = val\n        self.plot_two_columns()", "title": ""}
{"_id": "d16562", "text": "def main(source):\n    \"\"\"\n    For a given command line supplied argument, negotiate the content, parse\n    the schema and then return any issues to stdout or if no schema issues,\n    return success exit code.\n    \"\"\"\n    if source is None:\n        click.echo(\n            \"You need to supply a file or url to a schema to a swagger schema, for\"\n            \"the validator to work.\"\n        )\n        return 1\n    try:\n        load(source)\n        click.echo(\"Validation passed\")\n        return 0\n    except ValidationError as e:\n        raise click.ClickException(str(e))", "title": ""}
{"_id": "d16563", "text": "def hasattrs(object, *names):\n    \"\"\"\n    Takes in an object and a variable length amount of named attributes,\n    and checks to see if the object has each property. If any of the\n    attributes are missing, this returns false.\n\n    :param object: an object that may or may not contain the listed attributes\n    :param names: a variable amount of attribute names to check for\n    :return: True if the object contains each named attribute, false otherwise\n    \"\"\"\n    for name in names:\n        if not hasattr(object, name):\n            return False\n    return True", "title": ""}
{"_id": "d16564", "text": "def set_float(val):\n    \"\"\" utility to set a floating value,\n    useful for converting from strings \"\"\"\n    out = None\n    if not val in (None, ''):\n        try:\n            out = float(val)\n        except ValueError:\n            return None\n        if numpy.isnan(out):\n            out = default\n    return out", "title": ""}
{"_id": "d16565", "text": "def is_timestamp(obj):\n    \"\"\"\n    Yaml either have automatically converted it to a datetime object\n    or it is a string that will be validated later.\n    \"\"\"\n    return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)", "title": ""}
{"_id": "d16566", "text": "def last_day(year=_year, month=_month):\n    \"\"\"\n    get the current month's last day\n    :param year:  default to current year\n    :param month:  default to current month\n    :return: month's last day\n    \"\"\"\n    last_day = calendar.monthrange(year, month)[1]\n    return datetime.date(year=year, month=month, day=last_day)", "title": ""}
{"_id": "d16567", "text": "def check_for_positional_argument(kwargs, name, default=False):\n    \"\"\"\n    @type kwargs: dict\n    @type name: str\n    @type default: bool, int, str\n    @return: bool, int\n    \"\"\"\n    if name in kwargs:\n        if str(kwargs[name]) == \"True\":\n            return True\n        elif str(kwargs[name]) == \"False\":\n            return False\n        else:\n            return kwargs[name]\n\n    return default", "title": ""}
{"_id": "d16568", "text": "def _validate_simple(email):\n        \"\"\"Does a simple validation of an email by matching it to a regexps\n\n        :param email: The email to check\n        :return: The valid Email address\n\n        :raises: ValueError if value is not a valid email\n        \"\"\"\n        name, address = parseaddr(email)\n        if not re.match('[^@]+@[^@]+\\.[^@]+', address):\n            raise ValueError('Invalid email :{email}'.format(email=email))\n        return address", "title": ""}
{"_id": "d16569", "text": "def __contains__ (self, key):\n        \"\"\"Check lowercase key item.\"\"\"\n        assert isinstance(key, basestring)\n        return dict.__contains__(self, key.lower())", "title": ""}
{"_id": "d16570", "text": "def is_image_file_valid(file_path_name):\n    \"\"\"\n    Indicate whether the specified image file is valid or not.\n\n\n    @param file_path_name: absolute path and file name of an image.\n\n\n    @return: ``True`` if the image file is valid, ``False`` if the file is\n        truncated or does not correspond to a supported image.\n    \"\"\"\n    # Image.verify is only implemented for PNG images, and it only verifies\n    # the CRC checksum in the image.  The only way to check from within\n    # Pillow is to load the image in a try/except and check the error.  If\n    # as much info as possible is from the image is needed,\n    # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it\n    # will attempt to parse as much as possible.\n    try:\n        with Image.open(file_path_name) as image:\n            image.load()\n    except IOError:\n        return False\n\n    return True", "title": ""}
{"_id": "d16571", "text": "def is_file_exists_error(e):\n    \"\"\"\n    Returns whether the exception *e* was raised due to an already existing file or directory.\n    \"\"\"\n    if six.PY3:\n        return isinstance(e, FileExistsError)  # noqa: F821\n    else:\n        return isinstance(e, OSError) and e.errno == 17", "title": ""}
{"_id": "d16572", "text": "def do_last(environment, seq):\n    \"\"\"Return the last item of a sequence.\"\"\"\n    try:\n        return next(iter(reversed(seq)))\n    except StopIteration:\n        return environment.undefined('No last item, sequence was empty.')", "title": ""}
{"_id": "d16573", "text": "def stdout_display():\n    \"\"\" Print results straight to stdout \"\"\"\n    if sys.version_info[0] == 2:\n        yield SmartBuffer(sys.stdout)\n    else:\n        yield SmartBuffer(sys.stdout.buffer)", "title": ""}
{"_id": "d16574", "text": "def has_field(mc, field_name):\n    \"\"\"\n    detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:\n    \"\"\"\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True", "title": ""}
{"_id": "d16575", "text": "def readwav(filename):\n    \"\"\"Read a WAV file and returns the data and sample rate\n\n    ::\n\n        from spectrum.io import readwav\n        readwav()\n\n    \"\"\"\n    from scipy.io.wavfile import read as readwav\n    samplerate, signal = readwav(filename)\n    return signal, samplerate", "title": ""}
{"_id": "d16576", "text": "def _rm_name_match(s1, s2):\n  \"\"\"\n  determine whether two sequence names from a repeatmasker alignment match.\n\n  :return: True if they are the same string, or if one forms a substring of the\n           other, else False\n  \"\"\"\n  m_len = min(len(s1), len(s2))\n  return s1[:m_len] == s2[:m_len]", "title": ""}
{"_id": "d16577", "text": "def inside_softimage():\n    \"\"\"Returns a boolean indicating if the code is executed 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", "title": ""}
{"_id": "d16578", "text": "def _name_exists(self, name):\n        \"\"\"\n        Checks if we already have an opened tab with the same name.\n        \"\"\"\n        for i in range(self.count()):\n            if self.tabText(i) == name:\n                return True\n        return False", "title": ""}
{"_id": "d16579", "text": "def set_input_value(self, selector, value):\n        \"\"\"Set the value of the input matched by given selector.\"\"\"\n        script = 'document.querySelector(\"%s\").setAttribute(\"value\", \"%s\")'\n        script = script % (selector, value)\n        self.evaluate(script)", "title": ""}
{"_id": "d16580", "text": "def can_access(self, user):\n        \"\"\"Return whether or not `user` can access a project.\n\n        The project's is_ready field must be set for a user to access.\n\n        \"\"\"\n        return self.class_.is_admin(user) or \\\n            self.is_ready and self.class_ in user.classes", "title": ""}
{"_id": "d16581", "text": "def state(self):\n        \"\"\"Return internal state, useful for testing.\"\"\"\n        return {'c': self.c, 's0': self.s0, 's1': self.s1, 's2': self.s2}", "title": ""}
{"_id": "d16582", "text": "def _check_elements_equal(lst):\n    \"\"\"\n    Returns true if all of the elements in the list are equal.\n    \"\"\"\n    assert isinstance(lst, list), \"Input value must be a list.\"\n    return not lst or lst.count(lst[0]) == len(lst)", "title": ""}
{"_id": "d16583", "text": "def get_single_item(d):\n    \"\"\"Get an item from a dict which contains just one item.\"\"\"\n    assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)\n    return next(six.iteritems(d))", "title": ""}
{"_id": "d16584", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d16585", "text": "def mpl_outside_legend(ax, **kwargs):\n    \"\"\" Places a legend box outside a matplotlib Axes instance. \"\"\"\n    box = ax.get_position()\n    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])\n    # Put a legend to the right of the current axis\n    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)", "title": ""}
{"_id": "d16586", "text": "def _IsDirectory(parent, item):\n  \"\"\"Helper that returns if parent/item is a directory.\"\"\"\n  return tf.io.gfile.isdir(os.path.join(parent, item))", "title": ""}
{"_id": "d16587", "text": "def cli_command_quit(self, msg):\n        \"\"\"\\\n        kills the child and exits\n        \"\"\"\n        if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:\n            self.sprocess.proc.kill()\n        else:\n            sys.exit(0)", "title": ""}
{"_id": "d16588", "text": "def contains_geometric_info(var):\n    \"\"\" Check whether the passed variable is a tuple with two floats or integers \"\"\"\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)", "title": ""}
{"_id": "d16589", "text": "def np_counts(self):\n    \"\"\"Dictionary of noun phrase frequencies in this text.\n    \"\"\"\n    counts = defaultdict(int)\n    for phrase in self.noun_phrases:\n        counts[phrase] += 1\n    return counts", "title": ""}
{"_id": "d16590", "text": "def has_edge(self, p_from, p_to):\n        \"\"\" Returns True when the graph has the given edge. \"\"\"\n        return p_from in self._edges and p_to in self._edges[p_from]", "title": ""}
{"_id": "d16591", "text": "def fft_freqs(n_fft, fs):\n    \"\"\"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.\n    \"\"\"\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)", "title": ""}
{"_id": "d16592", "text": "def watched_extension(extension):\n    \"\"\"Return True if the given extension is one of the watched extensions\"\"\"\n    for ext in hamlpy.VALID_EXTENSIONS:\n        if extension.endswith('.' + ext):\n            return True\n    return False", "title": ""}
{"_id": "d16593", "text": "def rpc_fix_code(self, source, directory):\n        \"\"\"Formats Python code to conform to the PEP 8 style guide.\n\n        \"\"\"\n        source = get_source(source)\n        return fix_code(source, directory)", "title": ""}
{"_id": "d16594", "text": "def check_dependency(self, dependency_path):\n        \"\"\"Check if mtime of dependency_path is greater than stored mtime.\"\"\"\n        stored_hash = self._stamp_file_hashes.get(dependency_path)\n\n        # This file was newly added, or we don't have a file\n        # with stored hashes yet. Assume out of date.\n        if not stored_hash:\n            return False\n\n        return stored_hash == _sha1_for_file(dependency_path)", "title": ""}
{"_id": "d16595", "text": "def is_valid(number):\n    \"\"\"determines whether the card number is valid.\"\"\"\n    n = str(number)\n    if not n.isdigit():\n        return False\n    return int(n[-1]) == get_check_digit(n[:-1])", "title": ""}
{"_id": "d16596", "text": "def contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory", "title": ""}
{"_id": "d16597", "text": "def flatten(l):\n    \"\"\"Flatten a nested list.\"\"\"\n    return sum(map(flatten, l), []) \\\n        if isinstance(l, list) or isinstance(l, tuple) else [l]", "title": ""}
{"_id": "d16598", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d16599", "text": "def get_table(ports):\n    \"\"\"\n    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\n    \"\"\"\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n\n    for port in ports:\n        table.add_row(port)\n\n    return table", "title": ""}
{"_id": "d16600", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d16601", "text": "def _startswith(expr, pat):\n    \"\"\"\n    Return boolean sequence or scalar indicating whether each string in the sequence or scalar\n    starts with passed pattern. Equivalent to str.startswith().\n\n    :param expr:\n    :param pat: Character sequence\n    :return: sequence or scalar\n    \"\"\"\n\n    return _string_op(expr, Startswith, output_type=types.boolean, _pat=pat)", "title": ""}
{"_id": "d16602", "text": "def is_delimiter(line):\n    \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n    return bool(line) and line[0] in punctuation and line[0]*len(line) == line", "title": ""}
{"_id": "d16603", "text": "def csv_matrix_print(classes, table):\n    \"\"\"\n    Return matrix as csv data.\n\n    :param classes: classes list\n    :type classes:list\n    :param table: table\n    :type table:dict\n    :return:\n    \"\"\"\n    result = \"\"\n    classes.sort()\n    for i in classes:\n        for j in classes:\n            result += str(table[i][j]) + \",\"\n        result = result[:-1] + \"\\n\"\n    return result[:-1]", "title": ""}
{"_id": "d16604", "text": "def isin(value, values):\n    \"\"\" Check that value is in values \"\"\"\n    for i, v in enumerate(value):\n        if v not in np.array(values)[:, i]:\n            return False\n    return True", "title": ""}
{"_id": "d16605", "text": "def install_rpm_py():\n    \"\"\"Install RPM Python binding.\"\"\"\n    python_path = sys.executable\n    cmd = '{0} install.py'.format(python_path)\n    exit_status = os.system(cmd)\n    if exit_status != 0:\n        raise Exception('Command failed: {0}'.format(cmd))", "title": ""}
{"_id": "d16606", "text": "def all_strings(arr):\n        \"\"\"\n        Ensures that the argument is a list that either is empty or contains only strings\n        :param arr: list\n        :return:\n        \"\"\"\n        if not isinstance([], list):\n            raise TypeError(\"non-list value found where list is expected\")\n        return all(isinstance(x, str) for x in arr)", "title": ""}
{"_id": "d16607", "text": "def we_are_in_lyon():\n    \"\"\"Check if we are on a Lyon machine\"\"\"\n    import socket\n    try:\n        hostname = socket.gethostname()\n        ip = socket.gethostbyname(hostname)\n    except socket.gaierror:\n        return False\n    return ip.startswith(\"134.158.\")", "title": ""}
{"_id": "d16608", "text": "def _write_json(file, contents):\n    \"\"\"Write a dict to a JSON file.\"\"\"\n    with open(file, 'w') as f:\n        return json.dump(contents, f, indent=2, sort_keys=True)", "title": ""}
{"_id": "d16609", "text": "def is_empty(self):\n    \"\"\"Returns True if this node has no children, or if all of its children are ParseNode instances\n    and are empty.\n    \"\"\"\n    return all(isinstance(c, ParseNode) and c.is_empty for c in self.children)", "title": ""}
{"_id": "d16610", "text": "def _serialize_json(obj, fp):\n    \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n    json.dump(obj, fp, indent=4, default=serialize)", "title": ""}
{"_id": "d16611", "text": "def is_archlinux():\n    \"\"\"return True if the current distribution is running on debian like OS.\"\"\"\n    if platform.system().lower() == 'linux':\n        if platform.linux_distribution() == ('', '', ''):\n            # undefined distribution. Fixed in python 3.\n            if os.path.exists('/etc/arch-release'):\n                return True\n    return False", "title": ""}
{"_id": "d16612", "text": "def is_password_valid(password):\n    \"\"\"\n    Check if a password is valid\n    \"\"\"\n    pattern = re.compile(r\"^.{4,75}$\")\n    return bool(pattern.match(password))", "title": ""}
{"_id": "d16613", "text": "def are_in_interval(s, l, r, border = 'included'):\n        \"\"\"\n        Checks whether all number in the sequence s lie inside the interval formed by\n        l and r.\n        \"\"\"\n        return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s])", "title": ""}
{"_id": "d16614", "text": "def on_close(self, evt):\n    \"\"\"\n    Pop-up menu and wx.EVT_CLOSE closing event\n    \"\"\"\n    self.stop() # DoseWatcher\n    if evt.EventObject is not self: # Avoid deadlocks\n      self.Close() # wx.Frame\n    evt.Skip()", "title": ""}
{"_id": "d16615", "text": "def intty(cls):\n        \"\"\" Check if we are in a tty. \"\"\"\n        # XXX: temporary hack until we can detect if we are in a pipe or not\n        return True\n\n        if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():\n            return True\n\n        return False", "title": ""}
{"_id": "d16616", "text": "def list_view_changed(self, widget, event, data=None):\n        \"\"\"\n        Function shows last rows.\n        \"\"\"\n        adj = self.scrolled_window.get_vadjustment()\n        adj.set_value(adj.get_upper() - adj.get_page_size())", "title": ""}
{"_id": "d16617", "text": "def has_permission(user, permission_name):\n    \"\"\"Check if a user has a given permission.\"\"\"\n    if user and user.is_superuser:\n        return True\n\n    return permission_name in available_perm_names(user)", "title": ""}
{"_id": "d16618", "text": "def check_precomputed_distance_matrix(X):\n    \"\"\"Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.\n    \"\"\"\n    tmp = X.copy()\n    tmp[np.isinf(tmp)] = 1\n    check_array(tmp)", "title": ""}
{"_id": "d16619", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d16620", "text": "def is_valid_row(cls, row):\n        \"\"\"Indicates whether or not the given row contains valid data.\"\"\"\n        for k in row.keys():\n            if row[k] is None:\n                return False\n        return True", "title": ""}
{"_id": "d16621", "text": "def user_in_all_groups(user, groups):\n    \"\"\"Returns True if the given user is in all given groups\"\"\"\n    return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)", "title": ""}
{"_id": "d16622", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d16623", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d16624", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d16625", "text": "def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, convert\n    (in place) ``d[key]`` to a float. If that fails, convert it to ``None``.\n    \"\"\"\n    for d in dict_list:\n        try:\n            d[key] = float(d[key])\n        except ValueError:\n            d[key] = None", "title": ""}
{"_id": "d16626", "text": "def method_caller(method_name, *args, **kwargs):\n\t\"\"\"\n\tReturn a function that will call a named method on the\n\ttarget object with optional positional and keyword\n\targuments.\n\n\t>>> lower = method_caller('lower')\n\t>>> lower('MyString')\n\t'mystring'\n\t\"\"\"\n\tdef call_method(target):\n\t\tfunc = getattr(target, method_name)\n\t\treturn func(*args, **kwargs)\n\treturn call_method", "title": ""}
{"_id": "d16627", "text": "def previous_workday(dt):\n    \"\"\"\n    returns previous weekday used for observances\n    \"\"\"\n    dt -= timedelta(days=1)\n    while dt.weekday() > 4:\n        # Mon-Fri are 0-4\n        dt -= timedelta(days=1)\n    return dt", "title": ""}
{"_id": "d16628", "text": "def __gt__(self, other):\n        \"\"\"Test for greater than.\"\"\"\n        if isinstance(other, Address):\n            return str(self) > str(other)\n        raise TypeError", "title": ""}
{"_id": "d16629", "text": "def batch_split_sentences(self, texts: List[str]) -> List[List[str]]:\n        \"\"\"\n        This method lets you take advantage of spacy's batch processing.\n        Default implementation is to just iterate over the texts and call ``split_sentences``.\n        \"\"\"\n        return [self.split_sentences(text) for text in texts]", "title": ""}
{"_id": "d16630", "text": "def listify(a):\n    \"\"\"\n    Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']\n    \"\"\"\n    if a is None:\n        return []\n    elif not isinstance(a, (tuple, list, np.ndarray)):\n        return [a]\n    return list(a)", "title": ""}
{"_id": "d16631", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d16632", "text": "def list_depth(list_, func=max, _depth=0):\n    \"\"\"\n    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)\n\n    \"\"\"\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", "title": ""}
{"_id": "d16633", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d16634", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d16635", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d16636", "text": "def full(self):\n        \"\"\"Return ``True`` if the queue is full, ``False``\n        otherwise (not reliable!).\n\n        Only applicable if :attr:`maxsize` is set.\n\n        \"\"\"\n        return self.maxsize and len(self.list) >= self.maxsize or False", "title": ""}
{"_id": "d16637", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d16638", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d16639", "text": "def get_pij_matrix(t, diag, A, A_inv):\n    \"\"\"\n    Calculates the probability matrix of substitutions i->j over time t,\n    given the normalised generator diagonalisation.\n\n\n    :param t: time\n    :type t: float\n    :return: probability matrix\n    :rtype: numpy.ndarray\n    \"\"\"\n    return A.dot(np.diag(np.exp(diag * t))).dot(A_inv)", "title": ""}
{"_id": "d16640", "text": "def flush(self):\n        \"\"\"\n        Flush all unwritten data to disk.\n        \"\"\"\n        if self._cache_modified_count > 0:\n            self.storage.write(self.cache)\n            self._cache_modified_count = 0", "title": ""}
{"_id": "d16641", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d16642", "text": "def _sum_cycles_from_tokens(self, tokens: List[str]) -> int:\n        \"\"\"Sum the total number of cycles over a list of tokens.\"\"\"\n        return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))", "title": ""}
{"_id": "d16643", "text": "def __next__(self):\n        \"\"\"\n        :return: int\n        \"\"\"\n        self.current += 1\n        if self.current > self.total:\n            raise StopIteration\n        else:\n            return self.iterable[self.current - 1]", "title": ""}
{"_id": "d16644", "text": "def get_margin(length):\n    \"\"\"Add enough tabs to align in two columns\"\"\"\n    if length > 23:\n        margin_left = \"\\t\"\n        chars = 1\n    elif length > 15:\n        margin_left = \"\\t\\t\"\n        chars = 2\n    elif length > 7:\n        margin_left = \"\\t\\t\\t\"\n        chars = 3\n    else:\n        margin_left = \"\\t\\t\\t\\t\"\n        chars = 4\n    return margin_left", "title": ""}
{"_id": "d16645", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d16646", "text": "def tail(filename, number_of_bytes):\n    \"\"\"Returns the last number_of_bytes of filename\"\"\"\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()", "title": ""}
{"_id": "d16647", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d16648", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d16649", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d16650", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d16651", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d16652", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d16653", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d16654", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d16655", "text": "def indices_to_labels(self, indices: Sequence[int]) -> List[str]:\n        \"\"\" Converts a sequence of indices into their corresponding labels.\"\"\"\n\n        return [(self.INDEX_TO_LABEL[index]) for index in indices]", "title": ""}
{"_id": "d16656", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d16657", "text": "def get_versions(reporev=True):\n    \"\"\"Get version information for components used by Spyder\"\"\"\n    import sys\n    import platform\n\n    import qtpy\n    import qtpy.QtCore\n\n    revision = None\n    if reporev:\n        from spyder.utils import vcs\n        revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n    if not sys.platform == 'darwin':  # To avoid a crash with our Mac app\n        system = platform.system()\n    else:\n        system = 'Darwin'\n\n    return {\n        'spyder': __version__,\n        'python': platform.python_version(),  # \"2.7.3\"\n        'bitness': 64 if sys.maxsize > 2**32 else 32,\n        'qt': qtpy.QtCore.__version__,\n        'qt_api': qtpy.API_NAME,      # PyQt5\n        'qt_api_ver': qtpy.PYQT_VERSION,\n        'system': system,   # Linux, Windows, ...\n        'release': platform.release(),  # XP, 10.6, 2.2.0, etc.\n        'revision': revision,  # '9fdf926eccce'\n    }", "title": ""}
{"_id": "d16658", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d16659", "text": "async def cursor(self) -> Cursor:\n        \"\"\"Create an aiosqlite cursor wrapping a sqlite3 cursor object.\"\"\"\n        return Cursor(self, await self._execute(self._conn.cursor))", "title": ""}
{"_id": "d16660", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d16661", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d16662", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d16663", "text": "def extend(a: dict, b: dict) -> dict:\n    \"\"\"Merge two dicts and return a new dict. Much like subclassing works.\"\"\"\n    res = a.copy()\n    res.update(b)\n    return res", "title": ""}
{"_id": "d16664", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d16665", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d16666", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d16667", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d16668", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d16669", "text": "def read(self, count=0):\n        \"\"\" Read \"\"\"\n        return self.f.read(count) if count > 0 else self.f.read()", "title": ""}
{"_id": "d16670", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d16671", "text": "def obj_in_list_always(target_list, obj):\n    \"\"\"\n    >>> l = [1,1,1]\n    >>> obj_in_list_always(l, 1)\n    True\n    >>> l.append(2)\n    >>> obj_in_list_always(l, 1)\n    False\n    \"\"\"\n    for item in set(target_list):\n        if item is not obj:\n            return False\n    return True", "title": ""}
{"_id": "d16672", "text": "def lowercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the lowercase chars in the given string.\"\"\"\n        return ''.join([c if c.islower() else '' for c in str(string)])", "title": ""}
{"_id": "d16673", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d16674", "text": "def assert_valid_name(name: str) -> str:\n    \"\"\"Uphold the spec rules about naming.\"\"\"\n    error = is_valid_name_error(name)\n    if error:\n        raise error\n    return name", "title": ""}
{"_id": "d16675", "text": "def datetime_iso_format(date):\n    \"\"\"\n    Return an ISO-8601 representation of a datetime object.\n    \"\"\"\n    return \"{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z\".format(\n        date.year, date.month, date.day, date.hour,\n        date.minute, date.second)", "title": ""}
{"_id": "d16676", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d16677", "text": "def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\"\n    Args:\n        x: iterable of strings\n\n    Yields:\n        each string in lower case\n    \"\"\"\n    for string in x:\n        yield string.lower()", "title": ""}
{"_id": "d16678", "text": "def last_commit(self) -> Tuple:\n        \"\"\"Returns a tuple (hash, and commit object)\"\"\"\n        from libs.repos import git\n\n        return git.get_last_commit(repo_path=self.path)", "title": ""}
{"_id": "d16679", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d16680", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d16681", "text": "def lower_camel_case_from_underscores(string):\n    \"\"\"generate a lower-cased camelCase string from an underscore_string.\n    For example: my_variable_name -> myVariableName\"\"\"\n    components = string.split('_')\n    string = components[0]\n    for component in components[1:]:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d16682", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d16683", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d16684", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d16685", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d16686", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d16687", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d16688", "text": "def SetCursorPos(x: int, y: int) -> bool:\n    \"\"\"\n    SetCursorPos from Win32.\n    Set mouse cursor to point x, y.\n    x: int.\n    y: int.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    return bool(ctypes.windll.user32.SetCursorPos(x, y))", "title": ""}
{"_id": "d16689", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d16690", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d16691", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d16692", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d16693", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d16694", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d16695", "text": "def remove_nans_1D(*args) -> tuple:\n    \"\"\"Remove nans in a set of 1D arrays.\n\n    Removes indicies in all arrays if any array is nan at that index.\n    All input arrays must have the same size.\n\n    Parameters\n    ----------\n    args : 1D arrays\n\n    Returns\n    -------\n    tuple\n        Tuple of 1D arrays in same order as given, with nan indicies removed.\n    \"\"\"\n    vals = np.isnan(args[0])\n    for a in args:\n        vals |= np.isnan(a)\n    return tuple(np.array(a)[~vals] for a in args)", "title": ""}
{"_id": "d16696", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d16697", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d16698", "text": "def _latex_format(obj: Any) -> str:\n    \"\"\"Format an object as a latex string.\"\"\"\n    if isinstance(obj, float):\n        try:\n            return sympy.latex(symbolize(obj))\n        except ValueError:\n            return \"{0:.4g}\".format(obj)\n\n    return str(obj)", "title": ""}
{"_id": "d16699", "text": "def is_empty_shape(sh: ShExJ.Shape) -> bool:\n        \"\"\" Determine whether sh has any value \"\"\"\n        return sh.closed is None and sh.expression is None and sh.extra is None and \\\n            sh.semActs is None", "title": ""}
{"_id": "d16700", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d16701", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d16702", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d16703", "text": "def extend(a: dict, b: dict) -> dict:\n    \"\"\"Merge two dicts and return a new dict. Much like subclassing works.\"\"\"\n    res = a.copy()\n    res.update(b)\n    return res", "title": ""}
{"_id": "d16704", "text": "def pmon(month):\n\t\"\"\"\n\tP the month\n\n\t>>> print(pmon('2012-08'))\n\tAugust, 2012\n\t\"\"\"\n\tyear, month = month.split('-')\n\treturn '{month_name}, {year}'.format(\n\t\tmonth_name=calendar.month_name[int(month)],\n\t\tyear=year,\n\t)", "title": ""}
{"_id": "d16705", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d16706", "text": "def _lower(string):\n    \"\"\"Custom lower string function.\n    Examples:\n        FooBar -> foo_bar\n    \"\"\"\n    if not string:\n        return \"\"\n\n    new_string = [string[0].lower()]\n    for char in string[1:]:\n        if char.isupper():\n            new_string.append(\"_\")\n        new_string.append(char.lower())\n\n    return \"\".join(new_string)", "title": ""}
{"_id": "d16707", "text": "def iterate_items(dictish):\n    \"\"\" Return a consistent (key, value) iterable on dict-like objects,\n    including lists of tuple pairs.\n\n    Example:\n\n        >>> list(iterate_items({'a': 1}))\n        [('a', 1)]\n        >>> list(iterate_items([('a', 1), ('b', 2)]))\n        [('a', 1), ('b', 2)]\n    \"\"\"\n    if hasattr(dictish, 'iteritems'):\n        return dictish.iteritems()\n    if hasattr(dictish, 'items'):\n        return dictish.items()\n    return dictish", "title": ""}
{"_id": "d16708", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d16709", "text": "def area (self):\n    \"\"\"area() -> number\n\n    Returns the area of this Polygon.\n    \"\"\"\n    area = 0.0\n    \n    for segment in self.segments():\n      area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2\n\n    return area", "title": ""}
{"_id": "d16710", "text": "def get_day_name(self) -> str:\n        \"\"\" Returns the day name \"\"\"\n        weekday = self.value.isoweekday() - 1\n        return calendar.day_name[weekday]", "title": ""}
{"_id": "d16711", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d16712", "text": "def recall_score(y_true, y_pred, average='micro', suffix=False):\n    \"\"\"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\n    \"\"\"\n    true_entities = set(get_entities(y_true, suffix))\n    pred_entities = set(get_entities(y_pred, suffix))\n\n    nb_correct = len(true_entities & pred_entities)\n    nb_true = len(true_entities)\n\n    score = nb_correct / nb_true if nb_true > 0 else 0\n\n    return score", "title": ""}
{"_id": "d16713", "text": "def is_any_type_set(sett: Set[Type]) -> bool:\n    \"\"\"\n    Helper method to check if a set of types is the {AnyObject} singleton\n\n    :param sett:\n    :return:\n    \"\"\"\n    return len(sett) == 1 and is_any_type(min(sett))", "title": ""}
{"_id": "d16714", "text": "def unzoom_all(self, event=None):\n        \"\"\" zoom out full data range \"\"\"\n        if len(self.conf.zoom_lims) > 0:\n            self.conf.zoom_lims = [self.conf.zoom_lims[0]]\n        self.unzoom(event)", "title": ""}
{"_id": "d16715", "text": "def write_text(filename: str, text: str) -> None:\n    \"\"\"\n    Writes text to a file.\n    \"\"\"\n    with open(filename, 'w') as f:  # type: TextIO\n        print(text, file=f)", "title": ""}
{"_id": "d16716", "text": "def psutil_phymem_usage():\n    \"\"\"\n    Return physical memory usage (float)\n    Requires the cross-platform psutil (>=v0.3) library\n    (https://github.com/giampaolo/psutil)\n    \"\"\"\n    import psutil\n    # This is needed to avoid a deprecation warning error with\n    # newer psutil versions\n    try:\n        percent = psutil.virtual_memory().percent\n    except:\n        percent = psutil.phymem_usage().percent\n    return percent", "title": ""}
{"_id": "d16717", "text": "def right_replace(string, old, new, count=1):\n    \"\"\"\n    Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.\n    For example::\n\n        right_replace('one_two_two', 'two', 'three') -> 'one_two_three'\n    \"\"\"\n    if not string:\n        return string\n    return new.join(string.rsplit(old, count))", "title": ""}
{"_id": "d16718", "text": "def unzoom_all(self, event=None):\n        \"\"\" zoom out full data range \"\"\"\n        if len(self.conf.zoom_lims) > 0:\n            self.conf.zoom_lims = [self.conf.zoom_lims[0]]\n        self.unzoom(event)", "title": ""}
{"_id": "d16719", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d16720", "text": "def exclude(self, *args, **kwargs) -> \"QuerySet\":\n        \"\"\"\n        Same as .filter(), but with appends all args with NOT\n        \"\"\"\n        return self._filter_or_exclude(negate=True, *args, **kwargs)", "title": ""}
{"_id": "d16721", "text": "def camel_to_snake(s: str) -> str:\n    \"\"\"Convert string from camel case to snake case.\"\"\"\n\n    return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()", "title": ""}
{"_id": "d16722", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d16723", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d16724", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d16725", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d16726", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d16727", "text": "def attrname_to_colname_dict(cls) -> Dict[str, str]:\n    \"\"\"\n    Asks an SQLAlchemy class how its attribute names correspond to database\n    column names.\n\n    Args:\n        cls: SQLAlchemy ORM class\n\n    Returns:\n        a dictionary mapping attribute names to database column names\n    \"\"\"\n    attr_col = {}  # type: Dict[str, str]\n    for attrname, column in gen_columns(cls):\n        attr_col[attrname] = column.name\n    return attr_col", "title": ""}
{"_id": "d16728", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d16729", "text": "async def parallel_results(future_map: Sequence[Tuple]) -> Dict:\n    \"\"\"\n    Run parallel execution of futures and return mapping of their results to the provided keys.\n    Just a neat shortcut around ``asyncio.gather()``\n\n    :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )\n    :return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'}\n    \"\"\"\n    ctx_methods = OrderedDict(future_map)\n    fs = list(ctx_methods.values())\n    results = await asyncio.gather(*fs)\n    results = {\n        key: results[idx] for idx, key in enumerate(ctx_methods.keys())\n    }\n    return results", "title": ""}
{"_id": "d16730", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d16731", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d16732", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d16733", "text": "def bytes_hack(buf):\n    \"\"\"\n    Hacky workaround for old installs of the library on systems without python-future that were\n    keeping the 2to3 update from working after auto-update.\n    \"\"\"\n    ub = None\n    if sys.version_info > (3,):\n        ub = buf\n    else:\n        ub = bytes(buf)\n\n    return ub", "title": ""}
{"_id": "d16734", "text": "def get_prop_value(name, props, default=None):\n    # type: (str, Dict[str, Any], Any) -> Any\n    \"\"\"\n    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\n    \"\"\"\n    if not props:\n        return default\n\n    try:\n        return props[name]\n    except KeyError:\n        return default", "title": ""}
{"_id": "d16735", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d16736", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d16737", "text": "def create_pie_chart(self, snapshot, filename=''):\n        \"\"\"\n        Create a pie chart that depicts the distribution of the allocated memory\n        for a given `snapshot`. The chart is saved to `filename`.\n        \"\"\"\n        try:\n            from pylab import figure, title, pie, axes, savefig\n            from pylab import sum as pylab_sum\n        except ImportError:\n            return self.nopylab_msg % (\"pie_chart\")\n\n        # Don't bother illustrating a pie without pieces.\n        if not snapshot.tracked_total:\n            return ''\n\n        classlist = []\n        sizelist = []\n        for k, v in list(snapshot.classes.items()):\n            if v['pct'] > 3.0:\n                classlist.append(k)\n                sizelist.append(v['sum'])\n        sizelist.insert(0, snapshot.asizeof_total - pylab_sum(sizelist))\n        classlist.insert(0, 'Other')\n        #sizelist = [x*0.01 for x in sizelist]\n\n        title(\"Snapshot (%s) Memory Distribution\" % (snapshot.desc))\n        figure(figsize=(8,8))\n        axes([0.1, 0.1, 0.8, 0.8])\n        pie(sizelist, labels=classlist)\n        savefig(filename, dpi=50)\n\n        return self.chart_tag % (self.relative_path(filename))", "title": ""}
{"_id": "d16738", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d16739", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d16740", "text": "def samefile(a: str, b: str) -> bool:\n    \"\"\"Check if two pathes represent the same file.\"\"\"\n    try:\n        return os.path.samefile(a, b)\n    except OSError:\n        return os.path.normpath(a) == os.path.normpath(b)", "title": ""}
{"_id": "d16741", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d16742", "text": "def get_versions(reporev=True):\n    \"\"\"Get version information for components used by Spyder\"\"\"\n    import sys\n    import platform\n\n    import qtpy\n    import qtpy.QtCore\n\n    revision = None\n    if reporev:\n        from spyder.utils import vcs\n        revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n    if not sys.platform == 'darwin':  # To avoid a crash with our Mac app\n        system = platform.system()\n    else:\n        system = 'Darwin'\n\n    return {\n        'spyder': __version__,\n        'python': platform.python_version(),  # \"2.7.3\"\n        'bitness': 64 if sys.maxsize > 2**32 else 32,\n        'qt': qtpy.QtCore.__version__,\n        'qt_api': qtpy.API_NAME,      # PyQt5\n        'qt_api_ver': qtpy.PYQT_VERSION,\n        'system': system,   # Linux, Windows, ...\n        'release': platform.release(),  # XP, 10.6, 2.2.0, etc.\n        'revision': revision,  # '9fdf926eccce'\n    }", "title": ""}
{"_id": "d16743", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d16744", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d16745", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d16746", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d16747", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d16748", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d16749", "text": "def cpu_count() -> int:\n    \"\"\"Returns the number of processors on this machine.\"\"\"\n    if multiprocessing is None:\n        return 1\n    try:\n        return multiprocessing.cpu_count()\n    except NotImplementedError:\n        pass\n    try:\n        return os.sysconf(\"SC_NPROCESSORS_CONF\")\n    except (AttributeError, ValueError):\n        pass\n    gen_log.error(\"Could not detect number of processors; assuming 1\")\n    return 1", "title": ""}
{"_id": "d16750", "text": "def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None:\n    \"\"\"mouse_event from Win32.\"\"\"\n    ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)", "title": ""}
{"_id": "d16751", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d16752", "text": "def _izip(*iterables):\n    \"\"\" Iterate through multiple lists or arrays of equal size \"\"\"\n    # This izip routine is from itertools\n    # izip('ABCD', 'xy') --> Ax By\n\n    iterators = map(iter, iterables)\n    while iterators:\n        yield tuple(map(next, iterators))", "title": ""}
{"_id": "d16753", "text": "def extend(a: dict, b: dict) -> dict:\n    \"\"\"Merge two dicts and return a new dict. Much like subclassing works.\"\"\"\n    res = a.copy()\n    res.update(b)\n    return res", "title": ""}
{"_id": "d16754", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d16755", "text": "def decode_value(stream):\n    \"\"\"Decode the contents of a value from a serialized stream.\n\n    :param stream: Source data stream\n    :type stream: io.BytesIO\n    :returns: Decoded value\n    :rtype: bytes\n    \"\"\"\n    length = decode_length(stream)\n    (value,) = unpack_value(\">{:d}s\".format(length), stream)\n    return value", "title": ""}
{"_id": "d16756", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d16757", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d16758", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d16759", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d16760", "text": "def release_lock():\n    \"\"\"Release lock on compilation directory.\"\"\"\n    get_lock.n_lock -= 1\n    assert get_lock.n_lock >= 0\n    # Only really release lock once all lock requests have ended.\n    if get_lock.lock_is_enabled and get_lock.n_lock == 0:\n        get_lock.start_time = None\n        get_lock.unlocker.unlock()", "title": ""}
{"_id": "d16761", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d16762", "text": "def read(self, start_position: int, size: int) -> memoryview:\n        \"\"\"\n        Return a view into the memory\n        \"\"\"\n        return memoryview(self._bytes)[start_position:start_position + size]", "title": ""}
{"_id": "d16763", "text": "def min(self):\n        \"\"\"\n        :returns the minimum of the column\n        \"\"\"\n        res = self._qexec(\"min(%s)\" % self._name)\n        if len(res) > 0:\n            self._min = res[0][0]\n        return self._min", "title": ""}
{"_id": "d16764", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d16765", "text": "def append_num_column(self, text: str, index: int):\n        \"\"\" Add value to the output row, width based on index \"\"\"\n        width = self.columns[index][\"width\"]\n        return f\"{text:>{width}}\"", "title": ""}
{"_id": "d16766", "text": "def check64bit(current_system=\"python\"):\n    \"\"\"checks if you are on a 64 bit platform\"\"\"\n    if current_system == \"python\":\n        return sys.maxsize > 2147483647\n    elif current_system == \"os\":\n        import platform\n        pm = platform.machine()\n        if pm != \"..\" and pm.endswith('64'):  # recent Python (not Iron)\n            return True\n        else:\n            if 'PROCESSOR_ARCHITEW6432' in os.environ:\n                return True  # 32 bit program running on 64 bit Windows\n            try:\n                # 64 bit Windows 64 bit program\n                return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')\n            except IndexError:\n                pass  # not Windows\n            try:\n                # this often works in Linux\n                return '64' in platform.architecture()[0]\n            except Exception:\n                # is an older version of Python, assume also an older os@\n                # (best we can guess)\n                return False", "title": ""}
{"_id": "d16767", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d16768", "text": "def _gaussian_function(self, datalength: int, values: np.ndarray,\n                           height: int, index: int) -> np.ndarray:\n        \"\"\"\n        i'th Regression Model Gaussian\n\n        :param: len(x)\n        :param: x values\n        :param: height of gaussian\n        :param: position of gaussian\n\n        :return: gaussian bumps over domain\n        \"\"\"\n        return height * np.exp(-(1 / (self.spread_number * datalength)) *\n                               (values - ((datalength / self.function_number) * index)) ** 2)", "title": ""}
{"_id": "d16769", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d16770", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d16771", "text": "def SvcStop(self) -> None:\n        \"\"\"\n        Called when the service is being shut down.\n        \"\"\"\n        # tell the SCM we're shutting down\n        # noinspection PyUnresolvedReferences\n        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n        # fire the stop event\n        win32event.SetEvent(self.h_stop_event)", "title": ""}
{"_id": "d16772", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d16773", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d16774", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d16775", "text": "def _newer(a, b):\n    \"\"\"Inquire whether file a was written since file 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)", "title": ""}
{"_id": "d16776", "text": "def remove_prefix(text, prefix):\n\t\"\"\"\n\tRemove 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'\n\t\"\"\"\n\tnull, prefix, rest = text.rpartition(prefix)\n\treturn rest", "title": ""}
{"_id": "d16777", "text": "def _environment_variables() -> Dict[str, str]:\n    \"\"\"\n    Wraps `os.environ` to filter out non-encodable values.\n    \"\"\"\n    return {key: value\n            for key, value in os.environ.items()\n            if _is_encodable(value)}", "title": ""}
{"_id": "d16778", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d16779", "text": "def truncate_string(value, max_width=None):\n    \"\"\"Truncate string values.\"\"\"\n    if isinstance(value, text_type) and max_width is not None and len(value) > max_width:\n        return value[:max_width]\n    return value", "title": ""}
{"_id": "d16780", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d16781", "text": "def zoom_out(self):\n        \"\"\"Scale the image down by one scale step.\"\"\"\n        if self._scalefactor >= self._sfmin:\n            self._scalefactor -= 1\n            self.scale_image()\n            self._adjust_scrollbar(1/self._scalestep)\n            self.sig_zoom_changed.emit(self.get_scaling())", "title": ""}
{"_id": "d16782", "text": "def __init__(self, enum_obj: Any) -> None:\n        \"\"\"Initialize attributes for informative output.\n\n        :param enum_obj: Enum object.\n        \"\"\"\n        if enum_obj:\n            self.name = enum_obj\n            self.items = ', '.join([str(i) for i in enum_obj])\n        else:\n            self.items = ''", "title": ""}
{"_id": "d16783", "text": "def count(self, elem):\n        \"\"\"\n        Return the number of elements equal to elem present in the queue\n\n        >>> pdeque([1, 2, 1]).count(1)\n        2\n        \"\"\"\n        return self._left_list.count(elem) + self._right_list.count(elem)", "title": ""}
{"_id": "d16784", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d16785", "text": "def to_bool(value: Any) -> bool:\n    \"\"\"Convert string or other Python object to boolean.\n\n    **Rationalle**\n\n    Passing flags is one of the most common cases of using environment vars and\n    as values are strings we need to have an easy way to convert them to\n    boolean Python value.\n\n    Without this function int or float string values can be converted as false\n    positives, e.g. ``bool('0') => True``, but using this function ensure that\n    digit flag be properly converted to boolean value.\n\n    :param value: String or other value.\n    \"\"\"\n    return bool(strtobool(value) if isinstance(value, str) else value)", "title": ""}
{"_id": "d16786", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d16787", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d16788", "text": "def resize(im, short, max_size):\n    \"\"\"\n    only resize input image to target size and return scale\n    :param im: BGR image input by opencv\n    :param short: one dimensional size (the short side)\n    :param max_size: one dimensional max size (the long side)\n    :return: resized image (NDArray) and scale (float)\n    \"\"\"\n    im_shape = im.shape\n    im_size_min = np.min(im_shape[0:2])\n    im_size_max = np.max(im_shape[0:2])\n    im_scale = float(short) / float(im_size_min)\n    # prevent bigger axis from being more than max_size:\n    if np.round(im_scale * im_size_max) > max_size:\n        im_scale = float(max_size) / float(im_size_max)\n    im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)\n    return im, im_scale", "title": ""}
{"_id": "d16789", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d16790", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d16791", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d16792", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d16793", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d16794", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d16795", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d16796", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d16797", "text": "def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':\n        \"\"\"A basis that orders qubits ascending based on a key function.\n\n        Args:\n            key: A function that takes a qubit and returns a key value. The\n                basis will be ordered ascending according to these key values.\n\n\n        Returns:\n            A basis that orders qubits ascending based on a key function.\n        \"\"\"\n        return QubitOrder(lambda qubits: tuple(sorted(qubits, key=key)))", "title": ""}
{"_id": "d16798", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d16799", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d16800", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d16801", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d16802", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d16803", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d16804", "text": "def smooth_image(image, sigma, sigma_in_physical_coordinates=True, FWHM=False, max_kernel_width=32):\n    \"\"\"\n    Smooth an image\n\n    ANTsR function: `smoothImage`\n\n    Arguments\n    ---------\n    image   \n        Image to smooth\n    \n    sigma   \n        Smoothing factor. Can be scalar, in which case the same sigma is applied to each dimension, or a vector of length dim(inimage) to specify a unique smoothness for each dimension.\n    \n    sigma_in_physical_coordinates : boolean  \n        If true, the smoothing factor is in millimeters; if false, it is in pixels.\n    \n    FWHM : boolean    \n        If true, sigma is interpreted as the full-width-half-max (FWHM) of the filter, not the sigma of a Gaussian kernel.\n    \n    max_kernel_width : scalar    \n        Maximum kernel width\n    \n    Returns\n    -------\n    ANTsImage\n    \n    Example\n    -------\n    >>> import ants\n    >>> image = ants.image_read( ants.get_ants_data('r16'))\n    >>> simage = ants.smooth_image(image, (1.2,1.5))\n    \"\"\"\n    if image.components == 1:\n        return _smooth_image_helper(image, sigma, sigma_in_physical_coordinates, FWHM, max_kernel_width)\n    else:\n        imagelist = utils.split_channels(image)\n        newimages = []\n        for image in imagelist:\n            newimage = _smooth_image_helper(image, sigma, sigma_in_physical_coordinates, FWHM, max_kernel_width)\n            newimages.append(newimage)\n        return utils.merge_channels(newimages)", "title": ""}
{"_id": "d16805", "text": "def has_changed (filename):\n    \"\"\"Check if filename has changed since the last check. If this\n    is the first check, assume the file is changed.\"\"\"\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]", "title": ""}
{"_id": "d16806", "text": "def fcast(value: float) -> TensorLike:\n    \"\"\"Cast to float tensor\"\"\"\n    newvalue = tf.cast(value, FTYPE)\n    if DEVICE == 'gpu':\n        newvalue = newvalue.gpu()  # Why is this needed?  # pragma: no cover\n    return newvalue", "title": ""}
{"_id": "d16807", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d16808", "text": "def from_buffer(buffer, mime=False):\n    \"\"\"\n    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'\n    \"\"\"\n    m = _get_magic_type(mime)\n    return m.from_buffer(buffer)", "title": ""}
{"_id": "d16809", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d16810", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d16811", "text": "def __next__(self):\n        \"\"\"\n        :return: int\n        \"\"\"\n        self.current += 1\n        if self.current > self.total:\n            raise StopIteration\n        else:\n            return self.iterable[self.current - 1]", "title": ""}
{"_id": "d16812", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d16813", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d16814", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d16815", "text": "def suppress_stdout():\n    \"\"\"\n    Context manager that suppresses stdout.\n\n    Examples:\n        >>> with suppress_stdout():\n        ...     print('Test print')\n\n        >>> print('test')\n        test\n\n    \"\"\"\n    save_stdout = sys.stdout\n    sys.stdout = DevNull()\n    yield\n    sys.stdout = save_stdout", "title": ""}
{"_id": "d16816", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d16817", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d16818", "text": "def first_location_of_maximum(x):\n    \"\"\"\n    Returns the first location of the maximum 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\n    \"\"\"\n    if not isinstance(x, (np.ndarray, pd.Series)):\n        x = np.asarray(x)\n    return np.argmax(x) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d16819", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d16820", "text": "def method_caller(method_name, *args, **kwargs):\n\t\"\"\"\n\tReturn a function that will call a named method on the\n\ttarget object with optional positional and keyword\n\targuments.\n\n\t>>> lower = method_caller('lower')\n\t>>> lower('MyString')\n\t'mystring'\n\t\"\"\"\n\tdef call_method(target):\n\t\tfunc = getattr(target, method_name)\n\t\treturn func(*args, **kwargs)\n\treturn call_method", "title": ""}
{"_id": "d16821", "text": "def impose_legend_limit(limit=30, axes=\"gca\", **kwargs):\n    \"\"\"\n    This will erase all but, say, 30 of the legend entries and remake the legend.\n    You'll probably have to move it back into your favorite position at this point.\n    \"\"\"\n    if axes==\"gca\": axes = _pylab.gca()\n\n    # make these axes current\n    _pylab.axes(axes)\n\n    # loop over all the lines_pylab.\n    for n in range(0,len(axes.lines)):\n        if n >  limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label(\"_nolegend_\")\n        if n == limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label(\"...\")\n\n    _pylab.legend(**kwargs)", "title": ""}
{"_id": "d16822", "text": "def bytes_hack(buf):\n    \"\"\"\n    Hacky workaround for old installs of the library on systems without python-future that were\n    keeping the 2to3 update from working after auto-update.\n    \"\"\"\n    ub = None\n    if sys.version_info > (3,):\n        ub = buf\n    else:\n        ub = bytes(buf)\n\n    return ub", "title": ""}
{"_id": "d16823", "text": "def multi_split(s, split):\n    # type: (S, Iterable[S]) -> List[S]\n    \"\"\"Splits on multiple given separators.\"\"\"\n    for r in split:\n        s = s.replace(r, \"|\")\n    return [i for i in s.split(\"|\") if len(i) > 0]", "title": ""}
{"_id": "d16824", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d16825", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d16826", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d16827", "text": "def replace_in_list(stringlist: Iterable[str],\n                    replacedict: Dict[str, str]) -> List[str]:\n    \"\"\"\n    Returns a list produced by applying :func:`multiple_replace` to every\n    string in ``stringlist``.\n\n    Args:\n        stringlist: list of source strings\n        replacedict: dictionary mapping \"original\" to \"replacement\" strings\n\n    Returns:\n        list of final strings\n\n    \"\"\"\n    newlist = []\n    for fromstring in stringlist:\n        newlist.append(multiple_replace(fromstring, replacedict))\n    return newlist", "title": ""}
{"_id": "d16828", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d16829", "text": "def convert_bytes_to_ints(in_bytes, num):\n    \"\"\"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\"\"\"\n    dt = numpy.dtype('>i' + str(num))\n    return numpy.frombuffer(in_bytes, dt)", "title": ""}
{"_id": "d16830", "text": "def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:\n        \"\"\"Executes SQL; returns list of first values of each row.\"\"\"\n        rows = self.fetchall(sql, *args)\n        return [row[0] for row in rows]", "title": ""}
{"_id": "d16831", "text": "def read_las(source, closefd=True):\n    \"\"\" Entry point for reading las data in pylas\n\n    Reads the whole file into memory.\n\n    >>> las = read_las(\"pylastests/simple.las\")\n    >>> las.classification\n    array([1, 1, 1, ..., 1, 1, 1], dtype=uint8)\n\n    Parameters\n    ----------\n    source : str or io.BytesIO\n        The source to read data from\n\n    closefd: bool\n            if True and the source is a stream, the function will close it\n            after it is done reading\n\n\n    Returns\n    -------\n    pylas.lasdatas.base.LasBase\n        The object you can interact with to get access to the LAS points & VLRs\n    \"\"\"\n    with open_las(source, closefd=closefd) as reader:\n        return reader.read()", "title": ""}
{"_id": "d16832", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d16833", "text": "def bytes_hack(buf):\n    \"\"\"\n    Hacky workaround for old installs of the library on systems without python-future that were\n    keeping the 2to3 update from working after auto-update.\n    \"\"\"\n    ub = None\n    if sys.version_info > (3,):\n        ub = buf\n    else:\n        ub = bytes(buf)\n\n    return ub", "title": ""}
{"_id": "d16834", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d16835", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d16836", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d16837", "text": "def MoveWindow(handle: int, x: int, y: int, width: int, height: int, repaint: int = 1) -> bool:\n    \"\"\"\n    MoveWindow from Win32.\n    handle: int, the handle of a native window.\n    x: int.\n    y: int.\n    width: int.\n    height: int.\n    repaint: int, use 1 or 0.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    return bool(ctypes.windll.user32.MoveWindow(ctypes.c_void_p(handle), x, y, width, height, repaint))", "title": ""}
{"_id": "d16838", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d16839", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d16840", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d16841", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d16842", "text": "def de_duplicate(items):\n    \"\"\"Remove any duplicate item, preserving order\n\n    >>> de_duplicate([1, 2, 1, 2])\n    [1, 2]\n    \"\"\"\n    result = []\n    for item in items:\n        if item not in result:\n            result.append(item)\n    return result", "title": ""}
{"_id": "d16843", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d16844", "text": "def stop(self) -> None:\n        \"\"\"Stops the analysis as soon as possible.\"\"\"\n        if self._stop and not self._posted_kork:\n            self._stop()\n            self._stop = None", "title": ""}
{"_id": "d16845", "text": "def non_zero_row(arr):\n    \"\"\"\n        0.  Empty row returns False.\n\n            >>> arr = array([])\n            >>> non_zero_row(arr)\n\n            False\n\n        1.  Row with a zero returns False.\n\n            >>> arr = array([1, 4, 3, 0, 5, -1, -2])\n            >>> non_zero_row(arr)\n\n            False\n        2.  Row with no zeros returns True.\n\n            >>> arr = array([-1, -0.1, 0.001, 2])\n            >>> non_zero_row(arr)\n\n            True\n\n        :param arr: array\n        :type arr: numpy array\n        :return empty: If row is completely free of zeros\n        :rtype empty: bool\n    \"\"\"\n\n    if len(arr) == 0:\n        return False\n\n    for item in arr:\n        if item == 0:\n            return False\n\n    return True", "title": ""}
{"_id": "d16846", "text": "def unpackbools(integers, dtype='L'):\n    \"\"\"Yield booleans unpacking integers of dtype bit-length.\n\n    >>> list(unpackbools([42], 'B'))\n    [False, True, False, True, False, True, False, False]\n    \"\"\"\n    atoms = ATOMS[dtype]\n\n    for chunk in integers:\n        for a in atoms:\n            yield not not chunk & a", "title": ""}
{"_id": "d16847", "text": "def is_done(self):\n        \"\"\"True if the last two moves were Pass or if the position is at a move\n        greater than the max depth.\"\"\"\n        return self.position.is_game_over() or self.position.n >= FLAGS.max_game_length", "title": ""}
{"_id": "d16848", "text": "def _generate(self):\n        \"\"\"Parses a file or directory of files into a set of ``Document`` objects.\"\"\"\n        doc_count = 0\n        for fp in self.all_files:\n            for doc in self._get_docs_for_path(fp):\n                yield doc\n                doc_count += 1\n                if doc_count >= self.max_docs:\n                    return", "title": ""}
{"_id": "d16849", "text": "def call_spellchecker(cmd, input_text=None, encoding=None):\n    \"\"\"Call spell checker with arguments.\"\"\"\n\n    process = get_process(cmd)\n\n    # A buffer has been provided\n    if input_text is not None:\n        for line in input_text.splitlines():\n            # Hunspell truncates lines at `0x1fff` (at least on Windows this has been observed)\n            # Avoid truncation by chunking the line on white space and inserting a new line to break it.\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                # Avoid wasted calls to empty strings\n                if chunk and not chunk.isspace():\n                    process.stdin.write(chunk + b'\\n')\n                if offset >= end:\n                    break\n\n    return get_process_output(process, encoding)", "title": ""}
{"_id": "d16850", "text": "def multivariate_normal_tril(x,\n                             dims,\n                             layer_fn=tf.compat.v1.layers.dense,\n                             loc_fn=lambda x: x,\n                             scale_fn=tril_with_diag_softplus_and_shift,\n                             name=None):\n  \"\"\"Constructs a trainable `tfd.MultivariateNormalTriL` distribution.\n\n  This function creates a MultivariateNormal (MVN) with lower-triangular scale\n  matrix. By default the MVN is parameterized via affine transformation of input\n  tensor `x`. Using default args, this function is mathematically equivalent to:\n\n  ```none\n  Y = MVN(loc=matmul(W, x) + b,\n          scale_tril=f(reshape_tril(matmul(M, x) + c)))\n\n  where,\n    W in R^[d, n]\n    M in R^[d*(d+1)/2, n]\n    b in R^d\n    c in R^d\n    f(S) = set_diag(S, softplus(matrix_diag_part(S)) + 1e-5)\n  ```\n\n  Observe that `f` makes the diagonal of the triangular-lower scale matrix be\n  positive and no smaller than `1e-5`.\n\n  #### Examples\n\n  ```python\n  # This example fits a multilinear regression loss.\n  import tensorflow as tf\n  import tensorflow_probability as tfp\n\n  # Create fictitious training data.\n  dtype = np.float32\n  n = 3000    # number of samples\n  x_size = 4  # size of single x\n  y_size = 2  # size of single y\n  def make_training_data():\n    np.random.seed(142)\n    x = np.random.randn(n, x_size).astype(dtype)\n    w = np.random.randn(x_size, y_size).astype(dtype)\n    b = np.random.randn(1, y_size).astype(dtype)\n    true_mean = np.tensordot(x, w, axes=[[-1], [0]]) + b\n    noise = np.random.randn(n, y_size).astype(dtype)\n    y = true_mean + noise\n    return y, x\n  y, x = make_training_data()\n\n  # Build TF graph for fitting MVNTriL maximum likelihood estimator.\n  mvn = tfp.trainable_distributions.multivariate_normal_tril(x, dims=y_size)\n  loss = -tf.reduce_mean(mvn.log_prob(y))\n  train_op = tf.train.AdamOptimizer(learning_rate=2.**-3).minimize(loss)\n  mse = tf.reduce_mean(tf.squared_difference(y, mvn.mean()))\n  init_op = tf.global_variables_initializer()\n\n  # Run graph 1000 times.\n  num_steps = 1000\n  loss_ = np.zeros(num_steps)   # Style: `_` to indicate sess.run result.\n  mse_ = np.zeros(num_steps)\n  with tf.Session() as sess:\n    sess.run(init_op)\n    for it in xrange(loss_.size):\n      _, loss_[it], mse_[it] = sess.run([train_op, loss, mse])\n      if it % 200 == 0 or it == loss_.size - 1:\n        print(\"iteration:{}  loss:{}  mse:{}\".format(it, loss_[it], mse_[it]))\n\n  # ==> iteration:0    loss:38.2020797729  mse:4.17175960541\n  #     iteration:200  loss:2.90179634094  mse:0.990987896919\n  #     iteration:400  loss:2.82727336884  mse:0.990926623344\n  #     iteration:600  loss:2.82726788521  mse:0.990926682949\n  #     iteration:800  loss:2.82726788521  mse:0.990926682949\n  #     iteration:999  loss:2.82726788521  mse:0.990926682949\n  ```\n\n  Args:\n    x: `Tensor` with floating type. Must have statically defined rank and\n      statically known right-most dimension.\n    dims: Scalar, `int`, `Tensor` indicated the MVN event size, i.e., the\n      created MVN will be distribution over length-`dims` vectors.\n    layer_fn: Python `callable` which takes input `x` and `int` scalar `d` and\n      returns a transformation of `x` with shape\n      `tf.concat([tf.shape(x)[:-1], [d]], axis=0)`.\n      Default value: `tf.layers.dense`.\n    loc_fn: Python `callable` which transforms the `loc` parameter. Takes a\n      (batch of) length-`dims` vectors and returns a `Tensor` of same shape and\n      `dtype`.\n      Default value: `lambda x: x`.\n    scale_fn: Python `callable` which transforms the `scale` parameters. Takes a\n      (batch of) length-`dims * (dims + 1) / 2` vectors and returns a\n      lower-triangular `Tensor` of same batch shape with rightmost dimensions\n      having shape `[dims, dims]`.\n      Default value: `tril_with_diag_softplus_and_shift`.\n    name: A `name_scope` name for operations created by this function.\n      Default value: `None` (i.e., \"multivariate_normal_tril\").\n\n  Returns:\n    mvntril: An instance of `tfd.MultivariateNormalTriL`.\n  \"\"\"\n  with tf.compat.v1.name_scope(name, 'multivariate_normal_tril', [x, dims]):\n    x = tf.convert_to_tensor(value=x, name='x')\n    x = layer_fn(x, dims + dims * (dims + 1) // 2)\n    return tfd.MultivariateNormalTriL(\n        loc=loc_fn(x[..., :dims]),\n        scale_tril=scale_fn(x[..., dims:]))", "title": ""}
{"_id": "d16851", "text": "def binary(length):\n    \"\"\"\n        returns a a random string that represent a binary representation\n\n    :param length: number of bits\n    \"\"\"\n    num = randint(1, 999999)\n    mask = '0' * length\n    return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]", "title": ""}
{"_id": "d16852", "text": "def average_arrays(arrays: List[mx.nd.NDArray]) -> mx.nd.NDArray:\n    \"\"\"\n    Take a list of arrays of the same shape and take the element wise average.\n\n    :param arrays: A list of NDArrays with the same shape that will be averaged.\n    :return: The average of the NDArrays in the same context as arrays[0].\n    \"\"\"\n    if not arrays:\n        raise ValueError(\"arrays is empty.\")\n    if len(arrays) == 1:\n        return arrays[0]\n    check_condition(all(arrays[0].shape == a.shape for a in arrays), \"nd array shapes do not match\")\n    return mx.nd.add_n(*arrays) / len(arrays)", "title": ""}
{"_id": "d16853", "text": "def is_running(process_id: int) -> bool:\n    \"\"\"\n    Uses the Unix ``ps`` program to see if a process is running.\n    \"\"\"\n    pstr = str(process_id)\n    encoding = sys.getdefaultencoding()\n    s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE)\n    for line in s.stdout:\n        strline = line.decode(encoding)\n        if pstr in strline:\n            return True\n    return False", "title": ""}
{"_id": "d16854", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d16855", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d16856", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d16857", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d16858", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d16859", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d16860", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d16861", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d16862", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d16863", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d16864", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d16865", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d16866", "text": "def incr(name, value=1, rate=1, tags=None):\n    \"\"\"Increment a metric by value.\n\n    >>> import statsdecor\n    >>> statsdecor.incr('my.metric')\n    \"\"\"\n    client().incr(name, value, rate, tags)", "title": ""}
{"_id": "d16867", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d16868", "text": "def name_is_valid(name):\n    \"\"\"Return True if the dataset name is valid.\n\n    The name can only be 80 characters long.\n    Valid characters: Alpha numeric characters [0-9a-zA-Z]\n    Valid special characters: - _ .\n    \"\"\"\n    # The name can only be 80 characters long.\n    if len(name) > MAX_NAME_LENGTH:\n        return False\n    return bool(NAME_VALID_CHARS_REGEX.match(name))", "title": ""}
{"_id": "d16869", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d16870", "text": "async def async_run(self) -> None:\n        \"\"\"\n        Asynchronously run the worker, does not close connections. Useful when testing.\n        \"\"\"\n        self.main_task = self.loop.create_task(self.main())\n        await self.main_task", "title": ""}
{"_id": "d16871", "text": "def file_uptodate(fname, cmp_fname):\n    \"\"\"Check if a file exists, is non-empty and is more recent than cmp_fname.\n    \"\"\"\n    try:\n        return (file_exists(fname) and file_exists(cmp_fname) and\n                getmtime(fname) >= getmtime(cmp_fname))\n    except OSError:\n        return False", "title": ""}
{"_id": "d16872", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d16873", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d16874", "text": "def __rmatmul__(self, other):\n        \"\"\"\n        Matrix multiplication using binary `@` operator in Python>=3.5.\n        \"\"\"\n        return self.T.dot(np.transpose(other)).T", "title": ""}
{"_id": "d16875", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d16876", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d16877", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d16878", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d16879", "text": "def tsv_escape(x: Any) -> str:\n    \"\"\"\n    Escape data for tab-separated value (TSV) format.\n    \"\"\"\n    if x is None:\n        return \"\"\n    x = str(x)\n    return x.replace(\"\\t\", \"\\\\t\").replace(\"\\n\", \"\\\\n\")", "title": ""}
{"_id": "d16880", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d16881", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d16882", "text": "def get_system_drives():\n    \"\"\"\n    Get the available drive names on the system. Always returns a list.\n    \"\"\"\n    drives = []\n    if os.name == 'nt':\n        import ctypes\n        bitmask = ctypes.windll.kernel32.GetLogicalDrives()\n        letter = ord('A')\n        while bitmask > 0:\n            if bitmask & 1:\n                name = chr(letter) + ':' + os.sep\n                if os.path.isdir(name):\n                    drives.append(name)\n            bitmask >>= 1\n            letter += 1\n    else:\n        current_drive = get_drive(os.getcwd())\n        if current_drive:\n            drive = current_drive\n        else:\n            drive = os.sep\n        drives.append(drive)\n\n    return drives", "title": ""}
{"_id": "d16883", "text": "def area (self):\n    \"\"\"area() -> number\n\n    Returns the area of this Polygon.\n    \"\"\"\n    area = 0.0\n    \n    for segment in self.segments():\n      area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2\n\n    return area", "title": ""}
{"_id": "d16884", "text": "def is_rate_limited(response):\n        \"\"\"\n        Checks if the response has been rate limited by CARTO APIs\n\n        :param response: The response rate limited by CARTO APIs\n        :type response: requests.models.Response class\n\n        :return: Boolean\n        \"\"\"\n        if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and\n                int(response.headers['Retry-After']) >= 0):\n            return True\n\n        return False", "title": ""}
{"_id": "d16885", "text": "def convert_bytes_to_ints(in_bytes, num):\n    \"\"\"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\"\"\"\n    dt = numpy.dtype('>i' + str(num))\n    return numpy.frombuffer(in_bytes, dt)", "title": ""}
{"_id": "d16886", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d16887", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d16888", "text": "def bytes_hack(buf):\n    \"\"\"\n    Hacky workaround for old installs of the library on systems without python-future that were\n    keeping the 2to3 update from working after auto-update.\n    \"\"\"\n    ub = None\n    if sys.version_info > (3,):\n        ub = buf\n    else:\n        ub = bytes(buf)\n\n    return ub", "title": ""}
{"_id": "d16889", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d16890", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d16891", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d16892", "text": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "title": ""}
{"_id": "d16893", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d16894", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d16895", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d16896", "text": "def browse_dialog_dir():\n    \"\"\"\n    Open up a GUI browse dialog window and let to user pick a target directory.\n    :return str: Target directory path\n    \"\"\"\n    _go_to_package()\n    logger_directory.info(\"enter browse_dialog\")\n    _path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)\n    _path = _fix_path_bytes(_path_bytes, file=False)\n    if len(_path) >= 1:\n        _path = _path[0]\n    else:\n        _path = \"\"\n    logger_directory.info(\"chosen path: {}\".format(_path))\n    logger_directory.info(\"exit browse_dialog\")\n    return _path", "title": ""}
{"_id": "d16897", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d16898", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d16899", "text": "def interact(self, container: Container) -> None:\n        \"\"\"\n        Connects to the PTY (pseudo-TTY) for a given container.\n        Blocks until the user exits the PTY.\n        \"\"\"\n        cmd = \"/bin/bash -c 'source /.environment && /bin/bash'\"\n        cmd = \"docker exec -it {} {}\".format(container.id, cmd)\n        subprocess.call(cmd, shell=True)", "title": ""}
{"_id": "d16900", "text": "def lower_camel_case_from_underscores(string):\n    \"\"\"generate a lower-cased camelCase string from an underscore_string.\n    For example: my_variable_name -> myVariableName\"\"\"\n    components = string.split('_')\n    string = components[0]\n    for component in components[1:]:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d16901", "text": "def psutil_phymem_usage():\n    \"\"\"\n    Return physical memory usage (float)\n    Requires the cross-platform psutil (>=v0.3) library\n    (https://github.com/giampaolo/psutil)\n    \"\"\"\n    import psutil\n    # This is needed to avoid a deprecation warning error with\n    # newer psutil versions\n    try:\n        percent = psutil.virtual_memory().percent\n    except:\n        percent = psutil.phymem_usage().percent\n    return percent", "title": ""}
{"_id": "d16902", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d16903", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d16904", "text": "def file_exists(self) -> bool:\n        \"\"\" Check if the settings file exists or not \"\"\"\n        cfg_path = self.file_path\n        assert cfg_path\n\n        return path.isfile(cfg_path)", "title": ""}
{"_id": "d16905", "text": "def _short_repr(obj):\n  \"\"\"Helper function returns a truncated repr() of an object.\"\"\"\n  stringified = pprint.saferepr(obj)\n  if len(stringified) > 200:\n    return '%s... (%d bytes)' % (stringified[:200], len(stringified))\n  return stringified", "title": ""}
{"_id": "d16906", "text": "def release_lock():\n    \"\"\"Release lock on compilation directory.\"\"\"\n    get_lock.n_lock -= 1\n    assert get_lock.n_lock >= 0\n    # Only really release lock once all lock requests have ended.\n    if get_lock.lock_is_enabled and get_lock.n_lock == 0:\n        get_lock.start_time = None\n        get_lock.unlocker.unlock()", "title": ""}
{"_id": "d16907", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d16908", "text": "def prevPlot(self):\n        \"\"\"Moves the displayed plot to the previous one\"\"\"\n        if self.stacker.currentIndex() > 0:\n            self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)", "title": ""}
{"_id": "d16909", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d16910", "text": "def find_duplicates(l: list) -> set:\n    \"\"\"\n    Return the duplicates in a list.\n\n    The function relies on\n    https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n    Parameters\n    ----------\n    l : list\n        Name\n\n    Returns\n    -------\n    set\n        Duplicated values\n\n    >>> find_duplicates([1,2,3])\n    set()\n    >>> find_duplicates([1,2,1])\n    {1}\n    \"\"\"\n    return set([x for x in l if l.count(x) > 1])", "title": ""}
{"_id": "d16911", "text": "def change_bgcolor_enable(self, state):\n        \"\"\"\n        This is implementet so column min/max is only active when bgcolor is\n        \"\"\"\n        self.dataModel.bgcolor(state)\n        self.bgcolor_global.setEnabled(not self.is_series and state > 0)", "title": ""}
{"_id": "d16912", "text": "def sorted_chain(*ranges: Iterable[Tuple[int, int]]) -> List[Tuple[int, int]]:\n    \"\"\"Chain & sort ranges.\"\"\"\n    return sorted(itertools.chain(*ranges))", "title": ""}
{"_id": "d16913", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d16914", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d16915", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d16916", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d16917", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d16918", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d16919", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d16920", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d16921", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d16922", "text": "def remove_nans_1D(*args) -> tuple:\n    \"\"\"Remove nans in a set of 1D arrays.\n\n    Removes indicies in all arrays if any array is nan at that index.\n    All input arrays must have the same size.\n\n    Parameters\n    ----------\n    args : 1D arrays\n\n    Returns\n    -------\n    tuple\n        Tuple of 1D arrays in same order as given, with nan indicies removed.\n    \"\"\"\n    vals = np.isnan(args[0])\n    for a in args:\n        vals |= np.isnan(a)\n    return tuple(np.array(a)[~vals] for a in args)", "title": ""}
{"_id": "d16923", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d16924", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d16925", "text": "def get_pylint_options(config_dir='.'):\n    # type: (str) -> List[str]\n    \"\"\"Checks for local config overrides for `pylint`\n    and add them in the correct `pylint` `options` format.\n\n    :param config_dir:\n    :return: List [str]\n    \"\"\"\n    if PYLINT_CONFIG_NAME in os.listdir(config_dir):\n        pylint_config_path = PYLINT_CONFIG_NAME\n    else:\n        pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH\n\n    return ['--rcfile={}'.format(pylint_config_path)]", "title": ""}
{"_id": "d16926", "text": "def prin(*args, **kwargs):\n    r\"\"\"Like ``print``, but a function. I.e. prints out all arguments as\n    ``print`` would do. Specify output stream like this::\n\n      print('ERROR', `out=\"sys.stderr\"``).\n\n    \"\"\"\n    print >> kwargs.get('out',None), \" \".join([str(arg) for arg in args])", "title": ""}
{"_id": "d16927", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d16928", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d16929", "text": "def validate_django_compatible_with_python():\n    \"\"\"\n    Verify Django 1.11 is present if Python 2.7 is active\n\n    Installation of pinax-cli requires the correct version of Django for\n    the active Python version. If the developer subsequently changes\n    the Python version the installed Django may no longer be compatible.\n    \"\"\"\n    python_version = sys.version[:5]\n    django_version = django.get_version()\n    if sys.version_info == (2, 7) and django_version >= \"2\":\n        click.BadArgumentUsage(\"Please install Django v1.11 for Python {}, or switch to Python >= v3.4\".format(python_version))", "title": ""}
{"_id": "d16930", "text": "def memory_usage():\n    \"\"\"return memory usage of python process in MB\n\n    from\n    http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/\n    psutil is quicker\n\n    >>> isinstance(memory_usage(),float)\n    True\n\n    \"\"\"\n    try:\n        import psutil\n        import os\n    except ImportError:\n        return _memory_usage_ps()\n\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info()[0] / float(2 ** 20)\n    return mem", "title": ""}
{"_id": "d16931", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d16932", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d16933", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d16934", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d16935", "text": "def find_column(token):\n    \"\"\" Compute column:\n            input is the input text string\n            token is a token instance\n    \"\"\"\n    i = token.lexpos\n    input = token.lexer.lexdata\n\n    while i > 0:\n        if input[i - 1] == '\\n':\n            break\n        i -= 1\n\n    column = token.lexpos - i + 1\n\n    return column", "title": ""}
{"_id": "d16936", "text": "def file_uptodate(fname, cmp_fname):\n    \"\"\"Check if a file exists, is non-empty and is more recent than cmp_fname.\n    \"\"\"\n    try:\n        return (file_exists(fname) and file_exists(cmp_fname) and\n                getmtime(fname) >= getmtime(cmp_fname))\n    except OSError:\n        return False", "title": ""}
{"_id": "d16937", "text": "def numeric_part(s):\n    \"\"\"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\n    \"\"\"\n\n    m = re_numeric_part.match(s)\n    if m:\n        return int(m.group(1))\n    return None", "title": ""}
{"_id": "d16938", "text": "def numchannels(samples:np.ndarray) -> int:\n    \"\"\"\n    return the number of channels present in samples\n\n    samples: a numpy array as returned by sndread\n\n    for multichannel audio, samples is always interleaved,\n    meaning that samples[n] returns always a frame, which\n    is either a single scalar for mono audio, or an array\n    for multichannel audio.\n    \"\"\"\n    if len(samples.shape) == 1:\n        return 1\n    else:\n        return samples.shape[1]", "title": ""}
{"_id": "d16939", "text": "def exponential_backoff(attempt: int, cap: int=1200) -> timedelta:\n    \"\"\"Calculate a delay to retry using an exponential backoff algorithm.\n\n    It is an exponential backoff with random jitter to prevent failures\n    from being retried at the same time. It is a good fit for most\n    applications.\n\n    :arg attempt: the number of attempts made\n    :arg cap: maximum delay, defaults to 20 minutes\n    \"\"\"\n    base = 3\n    temp = min(base * 2 ** attempt, cap)\n    return timedelta(seconds=temp / 2 + random.randint(0, temp / 2))", "title": ""}
{"_id": "d16940", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d16941", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d16942", "text": "async def parallel_results(future_map: Sequence[Tuple]) -> Dict:\n    \"\"\"\n    Run parallel execution of futures and return mapping of their results to the provided keys.\n    Just a neat shortcut around ``asyncio.gather()``\n\n    :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )\n    :return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'}\n    \"\"\"\n    ctx_methods = OrderedDict(future_map)\n    fs = list(ctx_methods.values())\n    results = await asyncio.gather(*fs)\n    results = {\n        key: results[idx] for idx, key in enumerate(ctx_methods.keys())\n    }\n    return results", "title": ""}
{"_id": "d16943", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d16944", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d16945", "text": "def check_consistent_length(*arrays):\n    \"\"\"Check that all arrays have consistent first dimensions.\n\n    Checks whether all objects in arrays have the same shape or length.\n\n    Parameters\n    ----------\n    arrays : list or tuple of input objects.\n        Objects that will be checked for consistent length.\n    \"\"\"\n\n    uniques = np.unique([_num_samples(X) for X in arrays if X is not None])\n    if len(uniques) > 1:\n        raise ValueError(\"Found arrays with inconsistent numbers of samples: %s\"\n                         % str(uniques))", "title": ""}
{"_id": "d16946", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d16947", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d16948", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d16949", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d16950", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d16951", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d16952", "text": "def segment_str(text: str, phoneme_inventory: Set[str] = PHONEMES) -> str:\n    \"\"\"\n    Takes as input a string in Kunwinjku and segments it into phoneme-like\n    units based on the standard orthographic rules specified at\n    http://bininjgunwok.org.au/\n    \"\"\"\n\n    text = text.lower()\n    text = segment_into_tokens(text, phoneme_inventory)\n    return text", "title": ""}
{"_id": "d16953", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d16954", "text": "def last_modified(self) -> Optional[datetime.datetime]:\n        \"\"\"The value of Last-Modified HTTP header, or None.\n\n        This header is represented as a `datetime` object.\n        \"\"\"\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", "title": ""}
{"_id": "d16955", "text": "def tofile(self, fileobj):\n\t\t\"\"\"\n\t\twrite a cache object to the fileobj as a lal cache file\n\t\t\"\"\"\n\t\tfor entry in self:\n\t\t\tprint >>fileobj, str(entry)\n\t\tfileobj.close()", "title": ""}
{"_id": "d16956", "text": "def _brief_print_list(lst, limit=7):\n    \"\"\"Print at most `limit` elements of list.\"\"\"\n    lst = list(lst)\n    if len(lst) > limit:\n        return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n            _brief_print_list(lst[-limit//2:], limit)\n    return ', '.join([\"'%s'\"%str(i) for i in lst])", "title": ""}
{"_id": "d16957", "text": "def _tree_line(self, no_type: bool = False) -> str:\n        \"\"\"Return the receiver's contribution to tree diagram.\"\"\"\n        return self._tree_line_prefix() + \" \" + self.iname()", "title": ""}
{"_id": "d16958", "text": "def uconcatenate(arrs, axis=0):\n    \"\"\"Concatenate a sequence of arrays.\n\n    This wrapper around numpy.concatenate preserves units. All input arrays\n    must have the same units.  See the documentation of numpy.concatenate for\n    full details.\n\n    Examples\n    --------\n    >>> from unyt import cm\n    >>> A = [1, 2, 3]*cm\n    >>> B = [2, 3, 4]*cm\n    >>> uconcatenate((A, B))\n    unyt_array([1, 2, 3, 2, 3, 4], 'cm')\n\n    \"\"\"\n    v = np.concatenate(arrs, axis=axis)\n    v = _validate_numpy_wrapper_units(v, arrs)\n    return v", "title": ""}
{"_id": "d16959", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d16960", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d16961", "text": "def camel_to_snake_case(string):\n    \"\"\"Converts 'string' presented in camel case to snake case.\n\n    e.g.: CamelCase => snake_case\n    \"\"\"\n    s = _1.sub(r'\\1_\\2', string)\n    return _2.sub(r'\\1_\\2', s).lower()", "title": ""}
{"_id": "d16962", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d16963", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d16964", "text": "def natural_sort(list_to_sort: Iterable[str]) -> List[str]:\n    \"\"\"\n    Sorts a list of strings case insensitively as well as numerically.\n\n    For example: ['a1', 'A2', 'a3', 'A11', 'a22']\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=natural_keys)\n\n    :param list_to_sort: the list being sorted\n    :return: the list sorted naturally\n    \"\"\"\n    return sorted(list_to_sort, key=natural_keys)", "title": ""}
{"_id": "d16965", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d16966", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d16967", "text": "def are_token_parallel(sequences: Sequence[Sized]) -> bool:\n    \"\"\"\n    Returns True if all sequences in the list have the same length.\n    \"\"\"\n    if not sequences or len(sequences) == 1:\n        return True\n    return all(len(s) == len(sequences[0]) for s in sequences)", "title": ""}
{"_id": "d16968", "text": "def release_lock():\n    \"\"\"Release lock on compilation directory.\"\"\"\n    get_lock.n_lock -= 1\n    assert get_lock.n_lock >= 0\n    # Only really release lock once all lock requests have ended.\n    if get_lock.lock_is_enabled and get_lock.n_lock == 0:\n        get_lock.start_time = None\n        get_lock.unlocker.unlock()", "title": ""}
{"_id": "d16969", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d16970", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d16971", "text": "def margin(text):\n    r\"\"\"Add a margin to both ends of each line in the string.\n\n    Example:\n        >>> margin('line1\\nline2')\n        '  line1  \\n  line2  '\n    \"\"\"\n    lines = str(text).split('\\n')\n    return '\\n'.join('  {}  '.format(l) for l in lines)", "title": ""}
{"_id": "d16972", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d16973", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d16974", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d16975", "text": "def iterate_items(dictish):\n    \"\"\" Return a consistent (key, value) iterable on dict-like objects,\n    including lists of tuple pairs.\n\n    Example:\n\n        >>> list(iterate_items({'a': 1}))\n        [('a', 1)]\n        >>> list(iterate_items([('a', 1), ('b', 2)]))\n        [('a', 1), ('b', 2)]\n    \"\"\"\n    if hasattr(dictish, 'iteritems'):\n        return dictish.iteritems()\n    if hasattr(dictish, 'items'):\n        return dictish.items()\n    return dictish", "title": ""}
{"_id": "d16976", "text": "def closest_values(L):\n    \"\"\"Closest values\n\n    :param L: list of values\n    :returns: two values from L with minimal distance\n    :modifies: the order of L\n    :complexity: O(n log n), for n=len(L)\n    \"\"\"\n    assert len(L) >= 2\n    L.sort()\n    valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L)))\n    return L[argmin - 1], L[argmin]", "title": ""}
{"_id": "d16977", "text": "def is_client(self):\n        \"\"\"Return True if Glances is running in client mode.\"\"\"\n        return (self.args.client or self.args.browser) and not self.args.server", "title": ""}
{"_id": "d16978", "text": "def toStringArray(name, a, width = 0):\n    \"\"\"\n    Returns an array (any sequence of floats, really) as a string.\n    \"\"\"\n    string = name + \": \"\n    cnt = 0\n    for i in a:\n        string += \"%4.2f  \" % i \n        if width > 0 and (cnt + 1) % width == 0:\n            string += '\\n'\n        cnt += 1\n    return string", "title": ""}
{"_id": "d16979", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d16980", "text": "def psutil_phymem_usage():\n    \"\"\"\n    Return physical memory usage (float)\n    Requires the cross-platform psutil (>=v0.3) library\n    (https://github.com/giampaolo/psutil)\n    \"\"\"\n    import psutil\n    # This is needed to avoid a deprecation warning error with\n    # newer psutil versions\n    try:\n        percent = psutil.virtual_memory().percent\n    except:\n        percent = psutil.phymem_usage().percent\n    return percent", "title": ""}
{"_id": "d16981", "text": "def text_coords(string, position):\n    r\"\"\"\n    Transform a simple index into a human-readable position in a string.\n\n    This function accepts a string and an index, and will return a triple of\n    `(lineno, columnno, line)` representing the position through the text. It's\n    useful for displaying a string index in a human-readable way::\n\n        >>> s = \"abcdef\\nghijkl\\nmnopqr\\nstuvwx\\nyz\"\n        >>> text_coords(s, 0)\n        (0, 0, 'abcdef')\n        >>> text_coords(s, 4)\n        (0, 4, 'abcdef')\n        >>> text_coords(s, 6)\n        (0, 6, 'abcdef')\n        >>> text_coords(s, 7)\n        (1, 0, 'ghijkl')\n        >>> text_coords(s, 11)\n        (1, 4, 'ghijkl')\n        >>> text_coords(s, 15)\n        (2, 1, 'mnopqr')\n    \"\"\"\n    line_start = string.rfind('\\n', 0, position) + 1\n    line_end = string.find('\\n', position)\n    lineno = string.count('\\n', 0, position)\n    columnno = position - line_start\n    line = string[line_start:line_end]\n    return (lineno, columnno, line)", "title": ""}
{"_id": "d16982", "text": "def highlight(text: str, color_code: int, bold: bool=False) -> str:\n    \"\"\"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.\n    \"\"\"\n    return '{}\\033[{}m{}\\033[0m'.format(\n        '\\033[1m' if bold else '',\n        color_code,\n        text,)", "title": ""}
{"_id": "d16983", "text": "def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:\n    \"\"\"return the higher parent which is not an AssignName, Tuple or List node\n    \"\"\"\n    while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)):\n        node = node.parent\n    return node", "title": ""}
{"_id": "d16984", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d16985", "text": "def excel_datetime(timestamp, epoch=None):\n    \"\"\"Return datetime object from timestamp in Excel serial format.\n\n    Convert LSM time stamps.\n\n    >>> excel_datetime(40237.029999999795)\n    datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)\n\n    \"\"\"\n    if epoch is None:\n        epoch = datetime.datetime.fromordinal(693594)\n    return epoch + datetime.timedelta(timestamp)", "title": ""}
{"_id": "d16986", "text": "def callable_validator(v: Any) -> AnyCallable:\n    \"\"\"\n    Perform a simple check if the value is callable.\n\n    Note: complete matching of argument type hints and return types is not performed\n    \"\"\"\n    if callable(v):\n        return v\n\n    raise errors.CallableError(value=v)", "title": ""}
{"_id": "d16987", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d16988", "text": "def enum_mark_last(iterable, start=0):\n    \"\"\"\n    Returns a generator over iterable that tells whether the current item is the last one.\n    Usage:\n        >>> iterable = range(10)\n        >>> for index, is_last, item in enum_mark_last(iterable):\n        >>>     print(index, item, end='\\n' if is_last else ', ')\n    \"\"\"\n    it = iter(iterable)\n    count = start\n    try:\n        last = next(it)\n    except StopIteration:\n        return\n    for val in it:\n        yield count, False, last\n        last = val\n        count += 1\n    yield count, True, last", "title": ""}
{"_id": "d16989", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d16990", "text": "def to_iso_string(self) -> str:\n        \"\"\" Returns full ISO string for the given date \"\"\"\n        assert isinstance(self.value, datetime)\n        return datetime.isoformat(self.value)", "title": ""}
{"_id": "d16991", "text": "def _brief_print_list(lst, limit=7):\n    \"\"\"Print at most `limit` elements of list.\"\"\"\n    lst = list(lst)\n    if len(lst) > limit:\n        return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n            _brief_print_list(lst[-limit//2:], limit)\n    return ', '.join([\"'%s'\"%str(i) for i in lst])", "title": ""}
{"_id": "d16992", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d16993", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d16994", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d16995", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d16996", "text": "def clean_all_buckets(self):\n        \"\"\"\n        Removes all buckets from all hashes and their content.\n        \"\"\"\n        bucket_keys = self.redis_object.keys(pattern='nearpy_*')\n        if len(bucket_keys) > 0:\n            self.redis_object.delete(*bucket_keys)", "title": ""}
{"_id": "d16997", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d16998", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d16999", "text": "def output_dir(self, *args) -> str:\n        \"\"\" Directory where to store output \"\"\"\n        return os.path.join(self.project_dir, 'output', *args)", "title": ""}
{"_id": "d17000", "text": "def writable_stream(handle):\n    \"\"\"Test whether a stream can be written to.\n    \"\"\"\n    if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):\n        return handle.writable()\n    try:\n        handle.write(b'')\n    except (io.UnsupportedOperation, IOError):\n        return False\n    else:\n        return True", "title": ""}
{"_id": "d17001", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d17002", "text": "def contains(self, token: str) -> bool:\n        \"\"\"Return if the token is in the list or not.\"\"\"\n        self._validate_token(token)\n        return token in self", "title": ""}
{"_id": "d17003", "text": "def detect_model_num(string):\n    \"\"\"Takes a string related to a model name and extract its model number.\n\n    For example:\n        '000000-bootstrap.index' => 0\n    \"\"\"\n    match = re.match(MODEL_NUM_REGEX, string)\n    if match:\n        return int(match.group())\n    return None", "title": ""}
{"_id": "d17004", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d17005", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d17006", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d17007", "text": "def shape(self) -> Tuple[int, ...]:\n        \"\"\"Shape of histogram's data.\n\n        Returns\n        -------\n        One-element tuple with the number of bins along each axis.\n        \"\"\"\n        return tuple(bins.bin_count for bins in self._binnings)", "title": ""}
{"_id": "d17008", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d17009", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d17010", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17011", "text": "def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:\n    \"\"\"\n    Test if two objects are equal, based on a comparison of the specified\n    attributes ``attrs``.\n    \"\"\"\n    return all(getattr(one, a) == getattr(two, a) for a in attrs)", "title": ""}
{"_id": "d17012", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d17013", "text": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "title": ""}
{"_id": "d17014", "text": "def imt2tup(string):\n    \"\"\"\n    >>> imt2tup('PGA')\n    ('PGA',)\n    >>> imt2tup('SA(1.0)')\n    ('SA', 1.0)\n    >>> imt2tup('SA(1)')\n    ('SA', 1.0)\n    \"\"\"\n    s = string.strip()\n    if not s.endswith(')'):\n        # no parenthesis, PGA is considered the same as PGA()\n        return (s,)\n    name, rest = s.split('(', 1)\n    return (name,) + tuple(float(x) for x in ast.literal_eval(rest[:-1] + ','))", "title": ""}
{"_id": "d17015", "text": "def read(self, count=0):\n        \"\"\" Read \"\"\"\n        return self.f.read(count) if count > 0 else self.f.read()", "title": ""}
{"_id": "d17016", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d17017", "text": "def _store_helper(model: Action, session: Optional[Session] = None) -> None:\n    \"\"\"Help store an action.\"\"\"\n    if session is None:\n        session = _make_session()\n\n    session.add(model)\n    session.commit()\n    session.close()", "title": ""}
{"_id": "d17018", "text": "def _cursorLeft(self):\n        \"\"\" Handles \"cursor left\" events \"\"\"\n        if self.cursorPos > 0:\n            self.cursorPos -= 1\n            sys.stdout.write(console.CURSOR_LEFT)\n            sys.stdout.flush()", "title": ""}
{"_id": "d17019", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d17020", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d17021", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d17022", "text": "def camel_to_snake_case(string):\n    \"\"\"Converts 'string' presented in camel case to snake case.\n\n    e.g.: CamelCase => snake_case\n    \"\"\"\n    s = _1.sub(r'\\1_\\2', string)\n    return _2.sub(r'\\1_\\2', s).lower()", "title": ""}
{"_id": "d17023", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17024", "text": "def parse_reading(val: str) -> Optional[float]:\n    \"\"\" Convert reading value to float (if possible) \"\"\"\n    try:\n        return float(val)\n    except ValueError:\n        logging.warning('Reading of \"%s\" is not a number', val)\n        return None", "title": ""}
{"_id": "d17025", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17026", "text": "def datetime_from_isoformat(value: str):\n    \"\"\"Return a datetime object from an isoformat string.\n\n    Args:\n        value (str): Datetime string in isoformat.\n\n    \"\"\"\n    if sys.version_info >= (3, 7):\n        return datetime.fromisoformat(value)\n\n    return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')", "title": ""}
{"_id": "d17027", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d17028", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17029", "text": "def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity.\"\"\"\n    a, b = set(x), set(y)\n    union = a | b\n\n    if not union:\n        return 0.0\n\n    return len(a & b) / len(union)", "title": ""}
{"_id": "d17030", "text": "def reverse_mapping(mapping):\n\t\"\"\"\n\tFor every key, value pair, return the mapping for the\n\tequivalent value, key pair\n\n\t>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}\n\tTrue\n\t\"\"\"\n\tkeys, values = zip(*mapping.items())\n\treturn dict(zip(values, keys))", "title": ""}
{"_id": "d17031", "text": "def exponential_backoff(attempt: int, cap: int=1200) -> timedelta:\n    \"\"\"Calculate a delay to retry using an exponential backoff algorithm.\n\n    It is an exponential backoff with random jitter to prevent failures\n    from being retried at the same time. It is a good fit for most\n    applications.\n\n    :arg attempt: the number of attempts made\n    :arg cap: maximum delay, defaults to 20 minutes\n    \"\"\"\n    base = 3\n    temp = min(base * 2 ** attempt, cap)\n    return timedelta(seconds=temp / 2 + random.randint(0, temp / 2))", "title": ""}
{"_id": "d17032", "text": "def get_table_names_from_metadata(metadata: MetaData) -> List[str]:\n    \"\"\"\n    Returns all database table names found in an SQLAlchemy :class:`MetaData`\n    object.\n    \"\"\"\n    return [table.name for table in metadata.tables.values()]", "title": ""}
{"_id": "d17033", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d17034", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d17035", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d17036", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d17037", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d17038", "text": "def almost_hermitian(gate: Gate) -> bool:\n    \"\"\"Return true if gate tensor is (almost) Hermitian\"\"\"\n    return np.allclose(asarray(gate.asoperator()),\n                       asarray(gate.H.asoperator()))", "title": ""}
{"_id": "d17039", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d17040", "text": "def sample_normal(mean, var, rng):\n    \"\"\"Sample from independent normal distributions\n\n    Each element is an independent normal distribution.\n\n    Parameters\n    ----------\n    mean : numpy.ndarray\n      Means of the normal distribution. Shape --> (batch_num, sample_dim)\n    var : numpy.ndarray\n      Variance of the normal distribution. Shape --> (batch_num, sample_dim)\n    rng : numpy.random.RandomState\n\n    Returns\n    -------\n    ret : numpy.ndarray\n       The sampling result. Shape --> (batch_num, sample_dim)\n    \"\"\"\n    ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean\n    return ret", "title": ""}
{"_id": "d17041", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d17042", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d17043", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d17044", "text": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "title": ""}
{"_id": "d17045", "text": "def inject_nulls(data: Mapping, field_names) -> dict:\n    \"\"\"Insert None as value for missing fields.\"\"\"\n\n    record = dict()\n\n    for field in field_names:\n        record[field] = data.get(field, None)\n\n    return record", "title": ""}
{"_id": "d17046", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d17047", "text": "def bytes_hack(buf):\n    \"\"\"\n    Hacky workaround for old installs of the library on systems without python-future that were\n    keeping the 2to3 update from working after auto-update.\n    \"\"\"\n    ub = None\n    if sys.version_info > (3,):\n        ub = buf\n    else:\n        ub = bytes(buf)\n\n    return ub", "title": ""}
{"_id": "d17048", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d17049", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d17050", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17051", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17052", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17053", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d17054", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d17055", "text": "def get_deprecation_reason(\n    node: Union[EnumValueDefinitionNode, FieldDefinitionNode]\n) -> Optional[str]:\n    \"\"\"Given a field or enum value node, get deprecation reason as string.\"\"\"\n    from ..execution import get_directive_values\n\n    deprecated = get_directive_values(GraphQLDeprecatedDirective, node)\n    return deprecated[\"reason\"] if deprecated else None", "title": ""}
{"_id": "d17056", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d17057", "text": "def _prm_get_longest_stringsize(string_list):\n        \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n        maxlength = 1\n\n        for stringar in string_list:\n            if isinstance(stringar, np.ndarray):\n                if stringar.ndim > 0:\n                    for string in stringar.ravel():\n                        maxlength = max(len(string), maxlength)\n                else:\n                    maxlength = max(len(stringar.tolist()), maxlength)\n            else:\n                maxlength = max(len(stringar), maxlength)\n\n        # Make the string Col longer than needed in order to allow later on slightly larger strings\n        return int(maxlength * 1.5)", "title": ""}
{"_id": "d17058", "text": "def first_location_of_maximum(x):\n    \"\"\"\n    Returns the first location of the maximum 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\n    \"\"\"\n    if not isinstance(x, (np.ndarray, pd.Series)):\n        x = np.asarray(x)\n    return np.argmax(x) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d17059", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d17060", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d17061", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d17062", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d17063", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d17064", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d17065", "text": "def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):\n        \"\"\"\n        If we're not on the first line (of a multiline input) go a line up,\n        otherwise go back in history. (If nothing is selected.)\n        \"\"\"\n        if self.complete_state:\n            self.complete_previous(count=count)\n        elif self.document.cursor_position_row > 0:\n            self.cursor_up(count=count)\n        elif not self.selection_state:\n            self.history_backward(count=count)\n\n            # Go to the start of the line?\n            if go_to_start_of_line_if_history_changes:\n                self.cursor_position += self.document.get_start_of_line_position()", "title": ""}
{"_id": "d17066", "text": "def to_0d_array(value: Any) -> np.ndarray:\n    \"\"\"Given a value, wrap it in a 0-D numpy.ndarray.\n    \"\"\"\n    if np.isscalar(value) or (isinstance(value, np.ndarray) and\n                              value.ndim == 0):\n        return np.array(value)\n    else:\n        return to_0d_object_array(value)", "title": ""}
{"_id": "d17067", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d17068", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d17069", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d17070", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17071", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d17072", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d17073", "text": "def calculate_dimensions(image, long_side, short_side):\n    \"\"\"Returns the thumbnail dimensions depending on the images format.\"\"\"\n    if image.width >= image.height:\n        return '{0}x{1}'.format(long_side, short_side)\n    return '{0}x{1}'.format(short_side, long_side)", "title": ""}
{"_id": "d17074", "text": "def fmt_camel(name):\n    \"\"\"\n    Converts name to lower camel case. Words are identified by capitalization,\n    dashes, and underscores.\n    \"\"\"\n    words = split_words(name)\n    assert len(words) > 0\n    first = words.pop(0).lower()\n    return first + ''.join([word.capitalize() for word in words])", "title": ""}
{"_id": "d17075", "text": "def from_file(filename, mime=False):\n    \"\"\"\"\n    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'\n    \"\"\"\n    m = _get_magic_type(mime)\n    return m.from_file(filename)", "title": ""}
{"_id": "d17076", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d17077", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d17078", "text": "def _relative_frequency(self, word):\n\t\t\"\"\"Computes the log relative frequency for a word form\"\"\"\n\n\t\tcount = self.type_counts.get(word, 0)\n\t\treturn math.log(count/len(self.type_counts)) if count > 0 else 0", "title": ""}
{"_id": "d17079", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d17080", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d17081", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d17082", "text": "def is_quoted(arg: str) -> bool:\n    \"\"\"\n    Checks if a string is quoted\n    :param arg: the string being checked for quotes\n    :return: True if a string is quoted\n    \"\"\"\n    return len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES", "title": ""}
{"_id": "d17083", "text": "def get_language():\n    \"\"\"\n    Wrapper around Django's `get_language` utility.\n    For Django >= 1.8, `get_language` returns None in case no translation is activate.\n    Here we patch this behavior e.g. for back-end functionality requiring access to translated fields\n    \"\"\"\n    from parler import appsettings\n    language = dj_get_language()\n    if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:\n        return appsettings.PARLER_DEFAULT_LANGUAGE_CODE\n    else:\n        return language", "title": ""}
{"_id": "d17084", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d17085", "text": "def infer_format(filename:str) -> str:\n    \"\"\"Return extension identifying format of given filename\"\"\"\n    _, ext = os.path.splitext(filename)\n    return ext", "title": ""}
{"_id": "d17086", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d17087", "text": "def _find_conda():\n    \"\"\"Find the conda executable robustly across conda versions.\n\n    Returns\n    -------\n    conda : str\n        Path to the conda executable.\n\n    Raises\n    ------\n    IOError\n        If the executable cannot be found in either the CONDA_EXE environment\n        variable or in the PATH.\n\n    Notes\n    -----\n    In POSIX platforms in conda >= 4.4, conda can be set up as a bash function\n    rather than an executable. (This is to enable the syntax\n    ``conda activate env-name``.) In this case, the environment variable\n    ``CONDA_EXE`` contains the path to the conda executable. In other cases,\n    we use standard search for the appropriate name in the PATH.\n\n    See https://github.com/airspeed-velocity/asv/issues/645 for more details.\n    \"\"\"\n    if 'CONDA_EXE' in os.environ:\n        conda = os.environ['CONDA_EXE']\n    else:\n        conda = util.which('conda')\n    return conda", "title": ""}
{"_id": "d17088", "text": "def nTimes(n, f, *args, **kwargs):\n    r\"\"\"Call `f` `n` times with `args` and `kwargs`.\n    Useful e.g. for simplistic timing.\n\n    Examples:\n\n    >>> nTimes(3, sys.stdout.write, 'hallo\\n')\n    hallo\n    hallo\n    hallo\n\n    \"\"\"\n    for i in xrange(n): f(*args, **kwargs)", "title": ""}
{"_id": "d17089", "text": "def elmo_loss2ppl(losses: List[np.ndarray]) -> float:\n    \"\"\" Calculates perplexity by loss\n\n    Args:\n        losses: list of numpy arrays of model losses\n\n    Returns:\n        perplexity : float\n    \"\"\"\n    avg_loss = np.mean(losses)\n    return float(np.exp(avg_loss))", "title": ""}
{"_id": "d17090", "text": "def url_concat(url, args):\n    \"\"\"Concatenate url and argument dictionary regardless of whether\n    url has existing query parameters.\n\n    >>> url_concat(\"http://example.com/foo?a=b\", dict(c=\"d\"))\n    'http://example.com/foo?a=b&c=d'\n    \"\"\"\n    if not args: return url\n    if url[-1] not in ('?', '&'):\n        url += '&' if ('?' in url) else '?'\n    return url + urllib.urlencode(args)", "title": ""}
{"_id": "d17091", "text": "def get_versions(reporev=True):\n    \"\"\"Get version information for components used by Spyder\"\"\"\n    import sys\n    import platform\n\n    import qtpy\n    import qtpy.QtCore\n\n    revision = None\n    if reporev:\n        from spyder.utils import vcs\n        revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n    if not sys.platform == 'darwin':  # To avoid a crash with our Mac app\n        system = platform.system()\n    else:\n        system = 'Darwin'\n\n    return {\n        'spyder': __version__,\n        'python': platform.python_version(),  # \"2.7.3\"\n        'bitness': 64 if sys.maxsize > 2**32 else 32,\n        'qt': qtpy.QtCore.__version__,\n        'qt_api': qtpy.API_NAME,      # PyQt5\n        'qt_api_ver': qtpy.PYQT_VERSION,\n        'system': system,   # Linux, Windows, ...\n        'release': platform.release(),  # XP, 10.6, 2.2.0, etc.\n        'revision': revision,  # '9fdf926eccce'\n    }", "title": ""}
{"_id": "d17092", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d17093", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17094", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d17095", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d17096", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d17097", "text": "def shape(self) -> Tuple[int, ...]:\n        \"\"\"Shape of histogram's data.\n\n        Returns\n        -------\n        One-element tuple with the number of bins along each axis.\n        \"\"\"\n        return tuple(bins.bin_count for bins in self._binnings)", "title": ""}
{"_id": "d17098", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17099", "text": "def pset(iterable=(), pre_size=8):\n    \"\"\"\n    Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that\n    used for :py:func:`pmap`.\n\n    >>> s1 = pset([1, 2, 3, 2])\n    >>> s1\n    pset([1, 2, 3])\n    \"\"\"\n    if not iterable:\n        return _EMPTY_PSET\n\n    return PSet._from_iterable(iterable, pre_size=pre_size)", "title": ""}
{"_id": "d17100", "text": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "title": ""}
{"_id": "d17101", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d17102", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d17103", "text": "def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:\n        \"\"\" Return a json array as a list\n\n        :param value: array\n        :return: array with JsonObj instances removed\n        \"\"\"\n        return [e._as_dict if isinstance(e, JsonObj) else e for e in value]", "title": ""}
{"_id": "d17104", "text": "def __add_method(m: lmap.Map, key: T, method: Method) -> lmap.Map:\n        \"\"\"Swap the methods atom to include method with key.\"\"\"\n        return m.assoc(key, method)", "title": ""}
{"_id": "d17105", "text": "def isfile_notempty(inputfile: str) -> bool:\n        \"\"\"Check if the input filename with path is a file and is not empty.\"\"\"\n        try:\n            return isfile(inputfile) and getsize(inputfile) > 0\n        except TypeError:\n            raise TypeError('inputfile is not a valid type')", "title": ""}
{"_id": "d17106", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17107", "text": "def __iter__(self):\n        \"\"\"Define a generator function and return it\"\"\"\n        def generator():\n            for i, obj in enumerate(self._sequence):\n                if i >= self._limit:\n                    break\n                yield obj\n            raise StopIteration\n        return generator", "title": ""}
{"_id": "d17108", "text": "def clean_int(x) -> int:\n    \"\"\"\n    Returns its parameter as an integer, or raises\n    ``django.forms.ValidationError``.\n    \"\"\"\n    try:\n        return int(x)\n    except ValueError:\n        raise forms.ValidationError(\n            \"Cannot convert to integer: {}\".format(repr(x)))", "title": ""}
{"_id": "d17109", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d17110", "text": "def check64bit(current_system=\"python\"):\n    \"\"\"checks if you are on a 64 bit platform\"\"\"\n    if current_system == \"python\":\n        return sys.maxsize > 2147483647\n    elif current_system == \"os\":\n        import platform\n        pm = platform.machine()\n        if pm != \"..\" and pm.endswith('64'):  # recent Python (not Iron)\n            return True\n        else:\n            if 'PROCESSOR_ARCHITEW6432' in os.environ:\n                return True  # 32 bit program running on 64 bit Windows\n            try:\n                # 64 bit Windows 64 bit program\n                return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')\n            except IndexError:\n                pass  # not Windows\n            try:\n                # this often works in Linux\n                return '64' in platform.architecture()[0]\n            except Exception:\n                # is an older version of Python, assume also an older os@\n                # (best we can guess)\n                return False", "title": ""}
{"_id": "d17111", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d17112", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d17113", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17114", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d17115", "text": "def format_repr(obj, attributes) -> str:\n    \"\"\"Format an object's repr method with specific attributes.\"\"\"\n\n    attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr)))\n                                for attr in attributes))\n    return \"{0}({1})\".format(obj.__class__.__qualname__, attribute_repr)", "title": ""}
{"_id": "d17116", "text": "def _read_words(filename):\n  \"\"\"Reads words from a file.\"\"\"\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()", "title": ""}
{"_id": "d17117", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d17118", "text": "def u16le_list_to_byte_list(data):\n    \"\"\"! @brief Convert a halfword array into a byte array\"\"\"\n    byteData = []\n    for h in data:\n        byteData.extend([h & 0xff, (h >> 8) & 0xff])\n    return byteData", "title": ""}
{"_id": "d17119", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d17120", "text": "def listify(a):\n    \"\"\"\n    Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']\n    \"\"\"\n    if a is None:\n        return []\n    elif not isinstance(a, (tuple, list, np.ndarray)):\n        return [a]\n    return list(a)", "title": ""}
{"_id": "d17121", "text": "def sort_by_modified(files_or_folders: list) -> list:\n    \"\"\"\n    Sort files or folders by modified time\n\n    Args:\n        files_or_folders: list of files or folders\n\n    Returns:\n        list\n    \"\"\"\n    return sorted(files_or_folders, key=os.path.getmtime, reverse=True)", "title": ""}
{"_id": "d17122", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d17123", "text": "def lint(fmt='colorized'):\n    \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\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)", "title": ""}
{"_id": "d17124", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17125", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d17126", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d17127", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17128", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d17129", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d17130", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17131", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d17132", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d17133", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d17134", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d17135", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d17136", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d17137", "text": "def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:\n        \"\"\"Executes SQL; returns list of first values of each row.\"\"\"\n        rows = self.fetchall(sql, *args)\n        return [row[0] for row in rows]", "title": ""}
{"_id": "d17138", "text": "def fcast(value: float) -> TensorLike:\n    \"\"\"Cast to float tensor\"\"\"\n    newvalue = tf.cast(value, FTYPE)\n    if DEVICE == 'gpu':\n        newvalue = newvalue.gpu()  # Why is this needed?  # pragma: no cover\n    return newvalue", "title": ""}
{"_id": "d17139", "text": "def PrintIndented(self, file, ident, code):\n        \"\"\"Takes an array, add indentation to each entry and prints it.\"\"\"\n        for entry in code:\n            print >>file, '%s%s' % (ident, entry)", "title": ""}
{"_id": "d17140", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d17141", "text": "def replace_keys(record: Mapping, key_map: Mapping) -> dict:\n    \"\"\"New record with renamed keys including keys only found in key_map.\"\"\"\n\n    return {key_map[k]: v for k, v in record.items() if k in key_map}", "title": ""}
{"_id": "d17142", "text": "def sort_by_modified(files_or_folders: list) -> list:\n    \"\"\"\n    Sort files or folders by modified time\n\n    Args:\n        files_or_folders: list of files or folders\n\n    Returns:\n        list\n    \"\"\"\n    return sorted(files_or_folders, key=os.path.getmtime, reverse=True)", "title": ""}
{"_id": "d17143", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d17144", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17145", "text": "def lower_camel_case_from_underscores(string):\n    \"\"\"generate a lower-cased camelCase string from an underscore_string.\n    For example: my_variable_name -> myVariableName\"\"\"\n    components = string.split('_')\n    string = components[0]\n    for component in components[1:]:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d17146", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d17147", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d17148", "text": "def valid_substitution(strlen, index):\n    \"\"\"\n    skip performing substitutions that are outside the bounds of the string\n    \"\"\"\n    values = index[0]\n    return all([strlen > i for i in values])", "title": ""}
{"_id": "d17149", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d17150", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d17151", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d17152", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d17153", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d17154", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d17155", "text": "def replace_in_list(stringlist: Iterable[str],\n                    replacedict: Dict[str, str]) -> List[str]:\n    \"\"\"\n    Returns a list produced by applying :func:`multiple_replace` to every\n    string in ``stringlist``.\n\n    Args:\n        stringlist: list of source strings\n        replacedict: dictionary mapping \"original\" to \"replacement\" strings\n\n    Returns:\n        list of final strings\n\n    \"\"\"\n    newlist = []\n    for fromstring in stringlist:\n        newlist.append(multiple_replace(fromstring, replacedict))\n    return newlist", "title": ""}
{"_id": "d17156", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d17157", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d17158", "text": "def dict_of_sets_add(dictionary, key, value):\n    # type: (DictUpperBound, Any, Any) -> None\n    \"\"\"Add value to a set 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 set in dictionary\n\n    Returns:\n        None\n\n    \"\"\"\n    set_objs = dictionary.get(key, set())\n    set_objs.add(value)\n    dictionary[key] = set_objs", "title": ""}
{"_id": "d17159", "text": "def arcball_map_to_sphere(point, center, radius):\n    \"\"\"Return unit sphere coordinates from window coordinates.\"\"\"\n    v0 = (point[0] - center[0]) / radius\n    v1 = (center[1] - point[1]) / radius\n    n = v0*v0 + v1*v1\n    if n > 1.0:\n        # position outside of sphere\n        n = math.sqrt(n)\n        return numpy.array([v0/n, v1/n, 0.0])\n    else:\n        return numpy.array([v0, v1, math.sqrt(1.0 - n)])", "title": ""}
{"_id": "d17160", "text": "def is_rate_limited(response):\n        \"\"\"\n        Checks if the response has been rate limited by CARTO APIs\n\n        :param response: The response rate limited by CARTO APIs\n        :type response: requests.models.Response class\n\n        :return: Boolean\n        \"\"\"\n        if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and\n                int(response.headers['Retry-After']) >= 0):\n            return True\n\n        return False", "title": ""}
{"_id": "d17161", "text": "def _create_empty_array(self, frames, always_2d, dtype):\n        \"\"\"Create an empty array with appropriate shape.\"\"\"\n        import numpy as np\n        if always_2d or self.channels > 1:\n            shape = frames, self.channels\n        else:\n            shape = frames,\n        return np.empty(shape, dtype, order='C')", "title": ""}
{"_id": "d17162", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d17163", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d17164", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d17165", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17166", "text": "def assert_equal(first, second, msg_fmt=\"{msg}\"):\n    \"\"\"Fail unless first equals second, as determined by the '==' operator.\n\n    >>> assert_equal(5, 5.0)\n    >>> assert_equal(\"Hello World!\", \"Goodbye!\")\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'Hello World!' != 'Goodbye!'\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\n    \"\"\"\n\n    if isinstance(first, dict) and isinstance(second, dict):\n        assert_dict_equal(first, second, msg_fmt)\n    elif not first == second:\n        msg = \"{!r} != {!r}\".format(first, second)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))", "title": ""}
{"_id": "d17167", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d17168", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d17169", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d17170", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d17171", "text": "def set_cell_value(cell, value):\n    \"\"\"\n    Convenience method for setting the value of an openpyxl cell\n\n    This is necessary since the value property changed from internal_value\n    to value between version 1.* and 2.*.\n    \"\"\"\n    if OPENPYXL_MAJOR_VERSION > 1:\n        cell.value = value\n    else:\n        cell.internal_value = value", "title": ""}
{"_id": "d17172", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d17173", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17174", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d17175", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d17176", "text": "def _parse_date(string: str) -> datetime.date:\n    \"\"\"Parse an ISO format date (YYYY-mm-dd).\n\n    >>> _parse_date('1990-01-02')\n    datetime.date(1990, 1, 2)\n    \"\"\"\n    return datetime.datetime.strptime(string, '%Y-%m-%d').date()", "title": ""}
{"_id": "d17177", "text": "def hash_file(fileobj):\n    \"\"\"\n    :param fileobj: a file object\n    :return: a hash of the file content\n    \"\"\"\n    hasher = hashlib.md5()\n    buf = fileobj.read(65536)\n    while len(buf) > 0:\n        hasher.update(buf)\n        buf = fileobj.read(65536)\n    return hasher.hexdigest()", "title": ""}
{"_id": "d17178", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d17179", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d17180", "text": "def setup_cache(app: Flask, cache_config) -> Optional[Cache]:\n    \"\"\"Setup the flask-cache on a flask app\"\"\"\n    if cache_config and cache_config.get('CACHE_TYPE') != 'null':\n        return Cache(app, config=cache_config)\n\n    return None", "title": ""}
{"_id": "d17181", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d17182", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17183", "text": "def camel_to_snake(s: str) -> str:\n    \"\"\"Convert string from camel case to snake case.\"\"\"\n\n    return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()", "title": ""}
{"_id": "d17184", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17185", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17186", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d17187", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d17188", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d17189", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d17190", "text": "def in_transaction(self):\n        \"\"\"Check if this database is in a transactional context.\"\"\"\n        if not hasattr(self.local, 'tx'):\n            return False\n        return len(self.local.tx) > 0", "title": ""}
{"_id": "d17191", "text": "def score_small_straight_yatzy(dice: List[int]) -> int:\n    \"\"\"\n    Small straight scoring according to yatzy rules\n    \"\"\"\n    dice_set = set(dice)\n    if _are_two_sets_equal({1, 2, 3, 4, 5}, dice_set):\n        return sum(dice)\n    return 0", "title": ""}
{"_id": "d17192", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d17193", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17194", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d17195", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d17196", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d17197", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d17198", "text": "def process_literal_param(self, value: Optional[List[int]],\n                              dialect: Dialect) -> str:\n        \"\"\"Convert things on the way from Python to the database.\"\"\"\n        retval = self._intlist_to_dbstr(value)\n        return retval", "title": ""}
{"_id": "d17199", "text": "def label_from_bin(buf):\n    \"\"\"\n    Converts binary representation label to integer.\n\n    :param buf: Binary representation of label.\n    :return: MPLS Label and BoS bit.\n    \"\"\"\n\n    mpls_label = type_desc.Int3.to_user(six.binary_type(buf))\n    return mpls_label >> 4, mpls_label & 1", "title": ""}
{"_id": "d17200", "text": "def has_table(self, name):\n        \"\"\"Return ``True`` if the table *name* exists in the database.\"\"\"\n        return len(self.sql(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\",\n                            parameters=(name,), asrecarray=False, cache=False)) > 0", "title": ""}
{"_id": "d17201", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d17202", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d17203", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d17204", "text": "def rl_get_point() -> int:  # pragma: no cover\n    \"\"\"\n    Returns the offset of the current cursor position in rl_line_buffer\n    \"\"\"\n    if rl_type == RlType.GNU:\n        return ctypes.c_int.in_dll(readline_lib, \"rl_point\").value\n\n    elif rl_type == RlType.PYREADLINE:\n        return readline.rl.mode.l_buffer.point\n\n    else:\n        return 0", "title": ""}
{"_id": "d17205", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d17206", "text": "def camel_to_snake(s: str) -> str:\n    \"\"\"Convert string from camel case to snake case.\"\"\"\n\n    return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()", "title": ""}
{"_id": "d17207", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d17208", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d17209", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d17210", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d17211", "text": "def dict_of_sets_add(dictionary, key, value):\n    # type: (DictUpperBound, Any, Any) -> None\n    \"\"\"Add value to a set 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 set in dictionary\n\n    Returns:\n        None\n\n    \"\"\"\n    set_objs = dictionary.get(key, set())\n    set_objs.add(value)\n    dictionary[key] = set_objs", "title": ""}
{"_id": "d17212", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17213", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d17214", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d17215", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d17216", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d17217", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d17218", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d17219", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d17220", "text": "def is_unitary(matrix: np.ndarray) -> bool:\n    \"\"\"\n    A helper function that checks if a matrix is unitary.\n\n    :param matrix: a matrix to test unitarity of\n    :return: true if and only if matrix is unitary\n    \"\"\"\n    rows, cols = matrix.shape\n    if rows != cols:\n        return False\n    return np.allclose(np.eye(rows), matrix.dot(matrix.T.conj()))", "title": ""}
{"_id": "d17221", "text": "def SGT(self, a, b):\n        \"\"\"Signed greater-than comparison\"\"\"\n        # http://gavwood.com/paper.pdf\n        s0, s1 = to_signed(a), to_signed(b)\n        return Operators.ITEBV(256, s0 > s1, 1, 0)", "title": ""}
{"_id": "d17222", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d17223", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17224", "text": "def replaceStrs(s, *args):\n    r\"\"\"Replace all ``(frm, to)`` tuples in `args` in string `s`.\n\n    >>> replaceStrs(\"nothing is better than warm beer\",\n    ...             ('nothing','warm beer'), ('warm beer','nothing'))\n    'warm beer is better than nothing'\n\n    \"\"\"\n    if args == (): return s\n    mapping = dict((frm, to) for frm, to in args)\n    return re.sub(\"|\".join(map(re.escape, mapping.keys())),\n                  lambda match:mapping[match.group(0)], s)", "title": ""}
{"_id": "d17225", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d17226", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d17227", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17228", "text": "def _reshuffle(mat, shape):\n    \"\"\"Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].\"\"\"\n    return np.reshape(\n        np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),\n        (shape[3] * shape[1], shape[0] * shape[2]))", "title": ""}
{"_id": "d17229", "text": "def remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]:\n    \"\"\"Remove all values that are zero.\"\"\"\n    return {\n        label: count\n        for label, count in counter.items()\n        if count\n    }", "title": ""}
{"_id": "d17230", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d17231", "text": "def normcdf(x, log=False):\n    \"\"\"Normal cumulative density function.\"\"\"\n    y = np.atleast_1d(x).copy()\n    flib.normcdf(y)\n    if log:\n        if (y>0).all():\n            return np.log(y)\n        return -np.inf\n    return y", "title": ""}
{"_id": "d17232", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17233", "text": "def _parse_date(string: str) -> datetime.date:\n    \"\"\"Parse an ISO format date (YYYY-mm-dd).\n\n    >>> _parse_date('1990-01-02')\n    datetime.date(1990, 1, 2)\n    \"\"\"\n    return datetime.datetime.strptime(string, '%Y-%m-%d').date()", "title": ""}
{"_id": "d17234", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d17235", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d17236", "text": "def zlib_compress(data):\n    \"\"\"\n    Compress things in a py2/3 safe fashion\n    >>> json_str = '{\"test\": 1}'\n    >>> blob = zlib_compress(json_str)\n    \"\"\"\n    if PY3K:\n        if isinstance(data, str):\n            return zlib.compress(bytes(data, 'utf-8'))\n        return zlib.compress(data)\n    return zlib.compress(data)", "title": ""}
{"_id": "d17237", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d17238", "text": "def get_cursor(self):\n        \"\"\"Return the virtual cursor position.\n\n        The cursor can be moved with the :any:`move` method.\n\n        Returns:\n            Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`\n                will continue from.\n\n        .. seealso:: :any:move`\n        \"\"\"\n        x, y = self._cursor\n        width, height = self.parent.get_size()\n        while x >= width:\n            x -= width\n            y += 1\n        if y >= height and self.scrollMode == 'scroll':\n            y = height - 1\n        return x, y", "title": ""}
{"_id": "d17239", "text": "def file_lines(bblfile:str) -> iter:\n    \"\"\"Yield lines found in given file\"\"\"\n    with open(bblfile) as fd:\n        yield from (line.rstrip() for line in fd if line.rstrip())", "title": ""}
{"_id": "d17240", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d17241", "text": "def _tree_line(self, no_type: bool = False) -> str:\n        \"\"\"Return the receiver's contribution to tree diagram.\"\"\"\n        return self._tree_line_prefix() + \" \" + self.iname()", "title": ""}
{"_id": "d17242", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d17243", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d17244", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d17245", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d17246", "text": "def fcast(value: float) -> TensorLike:\n    \"\"\"Cast to float tensor\"\"\"\n    newvalue = tf.cast(value, FTYPE)\n    if DEVICE == 'gpu':\n        newvalue = newvalue.gpu()  # Why is this needed?  # pragma: no cover\n    return newvalue", "title": ""}
{"_id": "d17247", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d17248", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d17249", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d17250", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d17251", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d17252", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17253", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d17254", "text": "def release_lock():\n    \"\"\"Release lock on compilation directory.\"\"\"\n    get_lock.n_lock -= 1\n    assert get_lock.n_lock >= 0\n    # Only really release lock once all lock requests have ended.\n    if get_lock.lock_is_enabled and get_lock.n_lock == 0:\n        get_lock.start_time = None\n        get_lock.unlocker.unlock()", "title": ""}
{"_id": "d17255", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17256", "text": "def _find_conda():\n    \"\"\"Find the conda executable robustly across conda versions.\n\n    Returns\n    -------\n    conda : str\n        Path to the conda executable.\n\n    Raises\n    ------\n    IOError\n        If the executable cannot be found in either the CONDA_EXE environment\n        variable or in the PATH.\n\n    Notes\n    -----\n    In POSIX platforms in conda >= 4.4, conda can be set up as a bash function\n    rather than an executable. (This is to enable the syntax\n    ``conda activate env-name``.) In this case, the environment variable\n    ``CONDA_EXE`` contains the path to the conda executable. In other cases,\n    we use standard search for the appropriate name in the PATH.\n\n    See https://github.com/airspeed-velocity/asv/issues/645 for more details.\n    \"\"\"\n    if 'CONDA_EXE' in os.environ:\n        conda = os.environ['CONDA_EXE']\n    else:\n        conda = util.which('conda')\n    return conda", "title": ""}
{"_id": "d17257", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17258", "text": "def truncate_string(value, max_width=None):\n    \"\"\"Truncate string values.\"\"\"\n    if isinstance(value, text_type) and max_width is not None and len(value) > max_width:\n        return value[:max_width]\n    return value", "title": ""}
{"_id": "d17259", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d17260", "text": "def split_unit(value):\n    \"\"\" Split a number from its unit\n        1px -> (q, 'px')\n    Args:\n        value (str): input\n    returns:\n        tuple\n    \"\"\"\n    r = re.search('^(\\-?[\\d\\.]+)(.*)$', str(value))\n    return r.groups() if r else ('', '')", "title": ""}
{"_id": "d17261", "text": "def dict_of_sets_add(dictionary, key, value):\n    # type: (DictUpperBound, Any, Any) -> None\n    \"\"\"Add value to a set 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 set in dictionary\n\n    Returns:\n        None\n\n    \"\"\"\n    set_objs = dictionary.get(key, set())\n    set_objs.add(value)\n    dictionary[key] = set_objs", "title": ""}
{"_id": "d17262", "text": "def get_versions(reporev=True):\n    \"\"\"Get version information for components used by Spyder\"\"\"\n    import sys\n    import platform\n\n    import qtpy\n    import qtpy.QtCore\n\n    revision = None\n    if reporev:\n        from spyder.utils import vcs\n        revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n    if not sys.platform == 'darwin':  # To avoid a crash with our Mac app\n        system = platform.system()\n    else:\n        system = 'Darwin'\n\n    return {\n        'spyder': __version__,\n        'python': platform.python_version(),  # \"2.7.3\"\n        'bitness': 64 if sys.maxsize > 2**32 else 32,\n        'qt': qtpy.QtCore.__version__,\n        'qt_api': qtpy.API_NAME,      # PyQt5\n        'qt_api_ver': qtpy.PYQT_VERSION,\n        'system': system,   # Linux, Windows, ...\n        'release': platform.release(),  # XP, 10.6, 2.2.0, etc.\n        'revision': revision,  # '9fdf926eccce'\n    }", "title": ""}
{"_id": "d17263", "text": "def _find_conda():\n    \"\"\"Find the conda executable robustly across conda versions.\n\n    Returns\n    -------\n    conda : str\n        Path to the conda executable.\n\n    Raises\n    ------\n    IOError\n        If the executable cannot be found in either the CONDA_EXE environment\n        variable or in the PATH.\n\n    Notes\n    -----\n    In POSIX platforms in conda >= 4.4, conda can be set up as a bash function\n    rather than an executable. (This is to enable the syntax\n    ``conda activate env-name``.) In this case, the environment variable\n    ``CONDA_EXE`` contains the path to the conda executable. In other cases,\n    we use standard search for the appropriate name in the PATH.\n\n    See https://github.com/airspeed-velocity/asv/issues/645 for more details.\n    \"\"\"\n    if 'CONDA_EXE' in os.environ:\n        conda = os.environ['CONDA_EXE']\n    else:\n        conda = util.which('conda')\n    return conda", "title": ""}
{"_id": "d17264", "text": "def remove_falsy_values(counter: Mapping[Any, int]) -> Mapping[Any, int]:\n    \"\"\"Remove all values that are zero.\"\"\"\n    return {\n        label: count\n        for label, count in counter.items()\n        if count\n    }", "title": ""}
{"_id": "d17265", "text": "def rms(x):\n    \"\"\"\"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\n    \"\"\"\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", "title": ""}
{"_id": "d17266", "text": "def templategetter(tmpl):\n    \"\"\"\n    This is a dirty little template function generator that turns single-brace\n    Mustache-style template strings into functions that interpolate dict keys:\n\n    >>> get_name = templategetter(\"{first} {last}\")\n    >>> get_name({'first': 'Shawn', 'last': 'Allen'})\n    'Shawn Allen'\n    \"\"\"\n    tmpl = tmpl.replace('{', '%(')\n    tmpl = tmpl.replace('}', ')s')\n    return lambda data: tmpl % data", "title": ""}
{"_id": "d17267", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17268", "text": "def to_clipboard(self, excel=True, sep=None, **kwargs):\n        r\"\"\"\n        Copy object to the system clipboard.\n\n        Write a text representation of object to the system clipboard.\n        This can be pasted into Excel, for example.\n\n        Parameters\n        ----------\n        excel : bool, default True\n            - True, use the provided separator, writing in a csv format for\n              allowing easy pasting into excel.\n            - False, write a string representation of the object to the\n              clipboard.\n\n        sep : str, default ``'\\t'``\n            Field delimiter.\n        **kwargs\n            These parameters will be passed to DataFrame.to_csv.\n\n        See Also\n        --------\n        DataFrame.to_csv : Write a DataFrame to a comma-separated values\n            (csv) file.\n        read_clipboard : Read text from clipboard and pass to read_table.\n\n        Notes\n        -----\n        Requirements for your platform.\n\n          - Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules)\n          - Windows : none\n          - OS X : none\n\n        Examples\n        --------\n        Copy the contents of a DataFrame to the clipboard.\n\n        >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])\n        >>> df.to_clipboard(sep=',')\n        ... # Wrote the following to the system clipboard:\n        ... # ,A,B,C\n        ... # 0,1,2,3\n        ... # 1,4,5,6\n\n        We can omit the the index by passing the keyword `index` and setting\n        it to false.\n\n        >>> df.to_clipboard(sep=',', index=False)\n        ... # Wrote the following to the system clipboard:\n        ... # A,B,C\n        ... # 1,2,3\n        ... # 4,5,6\n        \"\"\"\n        from pandas.io import clipboards\n        clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)", "title": ""}
{"_id": "d17269", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17270", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d17271", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d17272", "text": "def get_datatype(self, table: str, column: str) -> str:\n        \"\"\"Returns database SQL datatype for a column: e.g. VARCHAR.\"\"\"\n        return self.flavour.get_datatype(self, table, column).upper()", "title": ""}
{"_id": "d17273", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d17274", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d17275", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d17276", "text": "def SwitchToThisWindow(handle: int) -> None:\n    \"\"\"\n    SwitchToThisWindow from Win32.\n    handle: int, the handle of a native window.\n    \"\"\"\n    ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)", "title": ""}
{"_id": "d17277", "text": "def fcast(value: float) -> TensorLike:\n    \"\"\"Cast to float tensor\"\"\"\n    newvalue = tf.cast(value, FTYPE)\n    if DEVICE == 'gpu':\n        newvalue = newvalue.gpu()  # Why is this needed?  # pragma: no cover\n    return newvalue", "title": ""}
{"_id": "d17278", "text": "def get_versions(reporev=True):\n    \"\"\"Get version information for components used by Spyder\"\"\"\n    import sys\n    import platform\n\n    import qtpy\n    import qtpy.QtCore\n\n    revision = None\n    if reporev:\n        from spyder.utils import vcs\n        revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n    if not sys.platform == 'darwin':  # To avoid a crash with our Mac app\n        system = platform.system()\n    else:\n        system = 'Darwin'\n\n    return {\n        'spyder': __version__,\n        'python': platform.python_version(),  # \"2.7.3\"\n        'bitness': 64 if sys.maxsize > 2**32 else 32,\n        'qt': qtpy.QtCore.__version__,\n        'qt_api': qtpy.API_NAME,      # PyQt5\n        'qt_api_ver': qtpy.PYQT_VERSION,\n        'system': system,   # Linux, Windows, ...\n        'release': platform.release(),  # XP, 10.6, 2.2.0, etc.\n        'revision': revision,  # '9fdf926eccce'\n    }", "title": ""}
{"_id": "d17279", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d17280", "text": "def pretty_dict(d):\n    \"\"\"Return dictionary d's repr but with the items sorted.\n    >>> pretty_dict({'m': 'M', 'a': 'A', 'r': 'R', 'k': 'K'})\n    \"{'a': 'A', 'k': 'K', 'm': 'M', 'r': 'R'}\"\n    >>> pretty_dict({z: C, y: B, x: A})\n    '{x: A, y: B, z: C}'\n    \"\"\"\n    return '{%s}' % ', '.join('%r: %r' % (k, v)\n                              for k, v in sorted(d.items(), key=repr))", "title": ""}
{"_id": "d17281", "text": "def array_to_npy(array_like):  # type: (np.array or Iterable or int or float) -> object\n    \"\"\"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.\n    \"\"\"\n    buffer = BytesIO()\n    np.save(buffer, array_like)\n    return buffer.getvalue()", "title": ""}
{"_id": "d17282", "text": "def read_byte_data(self, addr, cmd):\n        \"\"\"read_byte_data(addr, cmd) -> result\n\n        Perform SMBus Read Byte Data transaction.\n        \"\"\"\n        self._set_addr(addr)\n        res = SMBUS.i2c_smbus_read_byte_data(self._fd, ffi.cast(\"__u8\", cmd))\n        if res == -1:\n            raise IOError(ffi.errno)\n        return res", "title": ""}
{"_id": "d17283", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d17284", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d17285", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d17286", "text": "def _parse_property(self, node):\n        # type: (ElementTree.Element) -> Tuple[str, Any]\n        \"\"\"\n        Parses a property node\n\n        :param node: The property node\n        :return: A (name, value) tuple\n        :raise KeyError: Attribute missing\n        \"\"\"\n        # Get information\n        name = node.attrib[ATTR_NAME]\n        vtype = node.attrib.get(ATTR_VALUE_TYPE, TYPE_STRING)\n\n        # Look for a value as a single child node\n        try:\n            value_node = next(iter(node))\n            value = self._parse_value_node(vtype, value_node)\n        except StopIteration:\n            # Value is an attribute\n            value = self._convert_value(vtype, node.attrib[ATTR_VALUE])\n\n        return name, value", "title": ""}
{"_id": "d17287", "text": "def validate_django_compatible_with_python():\n    \"\"\"\n    Verify Django 1.11 is present if Python 2.7 is active\n\n    Installation of pinax-cli requires the correct version of Django for\n    the active Python version. If the developer subsequently changes\n    the Python version the installed Django may no longer be compatible.\n    \"\"\"\n    python_version = sys.version[:5]\n    django_version = django.get_version()\n    if sys.version_info == (2, 7) and django_version >= \"2\":\n        click.BadArgumentUsage(\"Please install Django v1.11 for Python {}, or switch to Python >= v3.4\".format(python_version))", "title": ""}
{"_id": "d17288", "text": "def is_intersection(g, n):\n    \"\"\"\n    Determine if a node is an intersection\n\n    graph: 1 -->-- 2 -->-- 3\n\n    >>> is_intersection(g, 2)\n    False\n\n    graph:\n     1 -- 2 -- 3\n          |\n          4\n\n    >>> is_intersection(g, 2)\n    True\n\n    Parameters\n    ----------\n    g : networkx DiGraph\n    n : node id\n\n    Returns\n    -------\n    bool\n\n    \"\"\"\n    return len(set(g.predecessors(n) + g.successors(n))) > 2", "title": ""}
{"_id": "d17289", "text": "def interpolate(f1: float, f2: float, factor: float) -> float:\n    \"\"\" Linearly interpolate between two float values. \"\"\"\n    return f1 + (f2 - f1) * factor", "title": ""}
{"_id": "d17290", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d17291", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17292", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d17293", "text": "def reduce(function, initval=None):\n\t\"\"\"\n\tCurried version of the built-in reduce.\n\t\n\t>>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] )\n\t15\n\t\"\"\"\n\tif initval is None:\n\t\treturn lambda s: __builtin__.reduce(function, s)\n\telse:\n\t\treturn lambda s: __builtin__.reduce(function, s, initval)", "title": ""}
{"_id": "d17294", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d17295", "text": "def tsv_escape(x: Any) -> str:\n    \"\"\"\n    Escape data for tab-separated value (TSV) format.\n    \"\"\"\n    if x is None:\n        return \"\"\n    x = str(x)\n    return x.replace(\"\\t\", \"\\\\t\").replace(\"\\n\", \"\\\\n\")", "title": ""}
{"_id": "d17296", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d17297", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d17298", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17299", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d17300", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d17301", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d17302", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17303", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17304", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17305", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d17306", "text": "def _validate_authority_uri_abs_path(host, path):\n        \"\"\"Ensure that path in URL with authority starts with a leading slash.\n\n        Raise ValueError if not.\n        \"\"\"\n        if len(host) > 0 and len(path) > 0 and not path.startswith(\"/\"):\n            raise ValueError(\n                \"Path in a URL with authority \" \"should start with a slash ('/') if set\"\n            )", "title": ""}
{"_id": "d17307", "text": "def warn_if_nans_exist(X):\n    \"\"\"Warn if nans exist in a numpy array.\"\"\"\n    null_count = count_rows_with_nans(X)\n    total = len(X)\n    percent = 100 * null_count / total\n\n    if null_count > 0:\n        warning_message = \\\n            'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n            'complete rows will be plotted.'.format(null_count, total, percent)\n        warnings.warn(warning_message, DataWarning)", "title": ""}
{"_id": "d17308", "text": "def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any],\n                                                 logger: Logger) -> Dict[str, Any]:\n        \"\"\"\n        Implementation of AnyParser API\n        \"\"\"\n        raise Exception('This should never happen, since this parser relies on underlying parsers')", "title": ""}
{"_id": "d17309", "text": "def inverted_dict_of_lists(d):\n    \"\"\"Return a dict where the keys are all the values listed in the values of the original dict\n\n    >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1}\n    True\n    \"\"\"\n    new_dict = {}\n    for (old_key, old_value_list) in viewitems(dict(d)):\n        for new_key in listify(old_value_list):\n            new_dict[new_key] = old_key\n    return new_dict", "title": ""}
{"_id": "d17310", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d17311", "text": "def copy_without_prompts(self):\n        \"\"\"Copy text to clipboard without prompts\"\"\"\n        text = self.get_selected_text()\n        lines = text.split(os.linesep)\n        for index, line in enumerate(lines):\n            if line.startswith('>>> ') or line.startswith('... '):\n                lines[index] = line[4:]\n        text = os.linesep.join(lines)\n        QApplication.clipboard().setText(text)", "title": ""}
{"_id": "d17312", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17313", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d17314", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d17315", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d17316", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d17317", "text": "def hex_to_int(value):\n    \"\"\"\n    Convert hex string like \"\\x0A\\xE3\" to 2787.\n    \"\"\"\n    if version_info.major >= 3:\n        return int.from_bytes(value, \"big\")\n    return int(value.encode(\"hex\"), 16)", "title": ""}
{"_id": "d17318", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d17319", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d17320", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d17321", "text": "def partition_items(count, bin_size):\n\t\"\"\"\n\tGiven the total number of items, determine the number of items that\n\tcan be added to each bin with a limit on the bin size.\n\n\tSo if you want to partition 11 items into groups of 3, you'll want\n\tthree of three and one of two.\n\n\t>>> partition_items(11, 3)\n\t[3, 3, 3, 2]\n\n\tBut if you only have ten items, you'll have two groups of three and\n\ttwo of two.\n\n\t>>> partition_items(10, 3)\n\t[3, 3, 2, 2]\n\t\"\"\"\n\tnum_bins = int(math.ceil(count / float(bin_size)))\n\tbins = [0] * num_bins\n\tfor i in range(count):\n\t\tbins[i % num_bins] += 1\n\treturn bins", "title": ""}
{"_id": "d17322", "text": "def _read_section(self):\n        \"\"\"Read and return an entire section\"\"\"\n        lines = [self._last[self._last.find(\":\")+1:]]\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            lines.append(self._last)\n            self._last = self._f.readline()\n        return lines", "title": ""}
{"_id": "d17323", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17324", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d17325", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d17326", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17327", "text": "def _get_ipv6_from_binary(self, bin_addr):\n        \"\"\"Converts binary address to Ipv6 format.\"\"\"\n\n        hi = bin_addr >> 64\n        lo = bin_addr & 0xFFFFFFFF\n        return socket.inet_ntop(socket.AF_INET6, struct.pack(\"!QQ\", hi, lo))", "title": ""}
{"_id": "d17328", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d17329", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d17330", "text": "def connect_to_database_odbc_access(self,\n                                        dsn: str,\n                                        autocommit: bool = True) -> None:\n        \"\"\"Connects to an Access database via ODBC, with the DSN\n        prespecified.\"\"\"\n        self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,\n                     dsn=dsn, autocommit=autocommit)", "title": ""}
{"_id": "d17331", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d17332", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17333", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d17334", "text": "def has_enumerated_namespace_name(self, namespace: str, name: str) -> bool:\n        \"\"\"Check that the namespace is defined by an enumeration and that the name is a member.\"\"\"\n        return self.has_enumerated_namespace(namespace) and name in self.namespace_to_terms[namespace]", "title": ""}
{"_id": "d17335", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d17336", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d17337", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d17338", "text": "def fcast(value: float) -> TensorLike:\n    \"\"\"Cast to float tensor\"\"\"\n    newvalue = tf.cast(value, FTYPE)\n    if DEVICE == 'gpu':\n        newvalue = newvalue.gpu()  # Why is this needed?  # pragma: no cover\n    return newvalue", "title": ""}
{"_id": "d17339", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d17340", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d17341", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d17342", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d17343", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d17344", "text": "def are_token_parallel(sequences: Sequence[Sized]) -> bool:\n    \"\"\"\n    Returns True if all sequences in the list have the same length.\n    \"\"\"\n    if not sequences or len(sequences) == 1:\n        return True\n    return all(len(s) == len(sequences[0]) for s in sequences)", "title": ""}
{"_id": "d17345", "text": "def full(self):\n        \"\"\"Return ``True`` if the queue is full, ``False``\n        otherwise (not reliable!).\n\n        Only applicable if :attr:`maxsize` is set.\n\n        \"\"\"\n        return self.maxsize and len(self.list) >= self.maxsize or False", "title": ""}
{"_id": "d17346", "text": "def is_iterable(etype) -> bool:\n    \"\"\" Determine whether etype is a List or other iterable \"\"\"\n    return type(etype) is GenericMeta and issubclass(etype.__extra__, Iterable)", "title": ""}
{"_id": "d17347", "text": "def extend(a: dict, b: dict) -> dict:\n    \"\"\"Merge two dicts and return a new dict. Much like subclassing works.\"\"\"\n    res = a.copy()\n    res.update(b)\n    return res", "title": ""}
{"_id": "d17348", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d17349", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d17350", "text": "def de_duplicate(items):\n    \"\"\"Remove any duplicate item, preserving order\n\n    >>> de_duplicate([1, 2, 1, 2])\n    [1, 2]\n    \"\"\"\n    result = []\n    for item in items:\n        if item not in result:\n            result.append(item)\n    return result", "title": ""}
{"_id": "d17351", "text": "def lower_camel_case_from_underscores(string):\n    \"\"\"generate a lower-cased camelCase string from an underscore_string.\n    For example: my_variable_name -> myVariableName\"\"\"\n    components = string.split('_')\n    string = components[0]\n    for component in components[1:]:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d17352", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d17353", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d17354", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d17355", "text": "async def fetchall(self) -> Iterable[sqlite3.Row]:\n        \"\"\"Fetch all remaining rows.\"\"\"\n        return await self._execute(self._cursor.fetchall)", "title": ""}
{"_id": "d17356", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d17357", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d17358", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d17359", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d17360", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d17361", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d17362", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d17363", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17364", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d17365", "text": "def get_line_number(line_map, offset):\n    \"\"\"Find a line number, given a line map and a character offset.\"\"\"\n    for lineno, line_offset in enumerate(line_map, start=1):\n        if line_offset > offset:\n            return lineno\n    return -1", "title": ""}
{"_id": "d17366", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d17367", "text": "def snake_to_camel(value):\n    \"\"\"\n    Converts a snake_case_string to a camelCaseString.\n\n    >>> snake_to_camel(\"foo_bar_baz\")\n    'fooBarBaz'\n    \"\"\"\n    camel = \"\".join(word.title() for word in value.split(\"_\"))\n    return value[:1].lower() + camel[1:]", "title": ""}
{"_id": "d17368", "text": "def ResetConsoleColor() -> bool:\n    \"\"\"\n    Reset to the default text color on console window.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    if sys.stdout:\n        sys.stdout.flush()\n    bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))", "title": ""}
{"_id": "d17369", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d17370", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d17371", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d17372", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d17373", "text": "def getCollectDServer(queue, cfg):\n    \"\"\"Get the appropriate collectd server (multi processed or not)\"\"\"\n    server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer\n    return server(queue, cfg)", "title": ""}
{"_id": "d17374", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d17375", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17376", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d17377", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d17378", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d17379", "text": "def val_mb(valstr: Union[int, str]) -> str:\n    \"\"\"\n    Converts a value in bytes (in string format) to megabytes.\n    \"\"\"\n    try:\n        return \"{:.3f}\".format(int(valstr) / (1024 * 1024))\n    except (TypeError, ValueError):\n        return '?'", "title": ""}
{"_id": "d17380", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d17381", "text": "def moving_average(iterable, n):\n    \"\"\"\n    From Python collections module documentation\n\n    moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0\n    \"\"\"\n    it = iter(iterable)\n    d = collections.deque(itertools.islice(it, n - 1))\n    d.appendleft(0)\n    s = sum(d)\n    for elem in it:\n        s += elem - d.popleft()\n        d.append(elem)\n        yield s / float(n)", "title": ""}
{"_id": "d17382", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d17383", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d17384", "text": "def _close(self):\n        \"\"\"\n        Release the USB interface again.\n        \"\"\"\n        self._usb_handle.releaseInterface()\n        try:\n            # If we're using PyUSB >= 1.0 we can re-attach the kernel driver here.\n            self._usb_handle.dev.attach_kernel_driver(0)\n        except:\n            pass\n        self._usb_int = None\n        self._usb_handle = None\n        return True", "title": ""}
{"_id": "d17385", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d17386", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17387", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d17388", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d17389", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d17390", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d17391", "text": "def dict_of_sets_add(dictionary, key, value):\n    # type: (DictUpperBound, Any, Any) -> None\n    \"\"\"Add value to a set 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 set in dictionary\n\n    Returns:\n        None\n\n    \"\"\"\n    set_objs = dictionary.get(key, set())\n    set_objs.add(value)\n    dictionary[key] = set_objs", "title": ""}
{"_id": "d17392", "text": "def camel_to_snake(s: str) -> str:\n    \"\"\"Convert string from camel case to snake case.\"\"\"\n\n    return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()", "title": ""}
{"_id": "d17393", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17394", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17395", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d17396", "text": "def fmt_camel(name):\n    \"\"\"\n    Converts name to lower camel case. Words are identified by capitalization,\n    dashes, and underscores.\n    \"\"\"\n    words = split_words(name)\n    assert len(words) > 0\n    first = words.pop(0).lower()\n    return first + ''.join([word.capitalize() for word in words])", "title": ""}
{"_id": "d17397", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d17398", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d17399", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d17400", "text": "def method_caller(method_name, *args, **kwargs):\n\t\"\"\"\n\tReturn a function that will call a named method on the\n\ttarget object with optional positional and keyword\n\targuments.\n\n\t>>> lower = method_caller('lower')\n\t>>> lower('MyString')\n\t'mystring'\n\t\"\"\"\n\tdef call_method(target):\n\t\tfunc = getattr(target, method_name)\n\t\treturn func(*args, **kwargs)\n\treturn call_method", "title": ""}
{"_id": "d17401", "text": "def obj_in_list_always(target_list, obj):\n    \"\"\"\n    >>> l = [1,1,1]\n    >>> obj_in_list_always(l, 1)\n    True\n    >>> l.append(2)\n    >>> obj_in_list_always(l, 1)\n    False\n    \"\"\"\n    for item in set(target_list):\n        if item is not obj:\n            return False\n    return True", "title": ""}
{"_id": "d17402", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d17403", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d17404", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d17405", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d17406", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d17407", "text": "def set_cell_value(cell, value):\n    \"\"\"\n    Convenience method for setting the value of an openpyxl cell\n\n    This is necessary since the value property changed from internal_value\n    to value between version 1.* and 2.*.\n    \"\"\"\n    if OPENPYXL_MAJOR_VERSION > 1:\n        cell.value = value\n    else:\n        cell.internal_value = value", "title": ""}
{"_id": "d17408", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17409", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17410", "text": "def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity.\"\"\"\n    a, b = set(x), set(y)\n    union = a | b\n\n    if not union:\n        return 0.0\n\n    return len(a & b) / len(union)", "title": ""}
{"_id": "d17411", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d17412", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17413", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17414", "text": "def __remove_method(m: lmap.Map, key: T) -> lmap.Map:\n        \"\"\"Swap the methods atom to remove method with key.\"\"\"\n        return m.dissoc(key)", "title": ""}
{"_id": "d17415", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d17416", "text": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "title": ""}
{"_id": "d17417", "text": "def looks_like_url(url):\n    \"\"\" 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\n    \"\"\"\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", "title": ""}
{"_id": "d17418", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d17419", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d17420", "text": "def preconnect(self, size=-1):\n        \"\"\"(pre)Connects some or all redis clients inside the pool.\n\n        Args:\n            size (int): number of redis clients to build and to connect\n                (-1 means all clients if pool max_size > -1)\n\n        Raises:\n            ClientError: when size == -1 and pool max_size == -1\n        \"\"\"\n        if size == -1 and self.max_size == -1:\n            raise ClientError(\"size=-1 not allowed with pool max_size=-1\")\n        limit = min(size, self.max_size) if size != -1 else self.max_size\n        clients = yield [self.get_connected_client() for _ in range(0, limit)]\n        for client in clients:\n            self.release_client(client)", "title": ""}
{"_id": "d17421", "text": "def min(self):\n        \"\"\"\n        :returns the minimum of the column\n        \"\"\"\n        res = self._qexec(\"min(%s)\" % self._name)\n        if len(res) > 0:\n            self._min = res[0][0]\n        return self._min", "title": ""}
{"_id": "d17422", "text": "def left_zero_pad(s, blocksize):\n    \"\"\"\n    Left padding with zero bytes to a given block size\n\n    :param s:\n    :param blocksize:\n    :return:\n    \"\"\"\n    if blocksize > 0 and len(s) % blocksize:\n        s = (blocksize - len(s) % blocksize) * b('\\000') + s\n    return s", "title": ""}
{"_id": "d17423", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d17424", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17425", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d17426", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d17427", "text": "def str_upper(x):\n    \"\"\"Converts all strings in a column to uppercase.\n\n    :returns: an expression containing the converted strings.\n\n    Example:\n\n    >>> import vaex\n    >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']\n    >>> df = vaex.from_arrays(text=text)\n    >>> df\n      #  text\n      0  Something\n      1  very pretty\n      2  is coming\n      3  our\n      4  way.\n\n\n    >>> df.text.str.upper()\n    Expression = str_upper(text)\n    Length: 5 dtype: str (expression)\n    ---------------------------------\n    0    SOMETHING\n    1  VERY PRETTY\n    2    IS COMING\n    3          OUR\n    4         WAY.\n\n    \"\"\"\n    sl = _to_string_sequence(x).upper()\n    return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)", "title": ""}
{"_id": "d17428", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d17429", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17430", "text": "def uuid(self, version: int = None) -> str:\n        \"\"\"Generate random UUID.\n\n        :param version: UUID version.\n        :return: UUID\n        \"\"\"\n        bits = self.random.getrandbits(128)\n        return str(uuid.UUID(int=bits, version=version))", "title": ""}
{"_id": "d17431", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d17432", "text": "def setup_cache(app: Flask, cache_config) -> Optional[Cache]:\n    \"\"\"Setup the flask-cache on a flask app\"\"\"\n    if cache_config and cache_config.get('CACHE_TYPE') != 'null':\n        return Cache(app, config=cache_config)\n\n    return None", "title": ""}
{"_id": "d17433", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17434", "text": "def fprint(expr, print_ascii=False):\n    r\"\"\"This function chooses whether to use ascii characters to represent\n    a symbolic expression in the notebook or to use sympy's pprint.\n\n    >>> from sympy import cos\n    >>> omega=Symbol(\"omega\")\n    >>> fprint(cos(omega),print_ascii=True)\n    cos(omega)\n\n\n    \"\"\"\n    if print_ascii:\n        pprint(expr, use_unicode=False, num_columns=120)\n    else:\n        return expr", "title": ""}
{"_id": "d17435", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d17436", "text": "async def fetchall(self) -> Iterable[sqlite3.Row]:\n        \"\"\"Fetch all remaining rows.\"\"\"\n        return await self._execute(self._cursor.fetchall)", "title": ""}
{"_id": "d17437", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d17438", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d17439", "text": "def is_none(string_, default='raise'):\n    \"\"\"\n    Check if a string is equivalent to None.\n\n    Parameters\n    ----------\n    string_ : str\n    default : {'raise', False}\n        Default behaviour if none of the \"None\" strings is detected.\n\n    Returns\n    -------\n    is_none : bool\n\n    Examples\n    --------\n    >>> is_none('2', default=False)\n    False\n    >>> is_none('undefined', default=False)\n    True\n    \"\"\"\n    none = ['none', 'undefined', 'unknown', 'null', '']\n    if string_.lower() in none:\n        return True\n    elif not default:\n        return False\n    else:\n        raise ValueError('The value \\'{}\\' cannot be mapped to none.'\n                         .format(string_))", "title": ""}
{"_id": "d17440", "text": "def samefile(a: str, b: str) -> bool:\n    \"\"\"Check if two pathes represent the same file.\"\"\"\n    try:\n        return os.path.samefile(a, b)\n    except OSError:\n        return os.path.normpath(a) == os.path.normpath(b)", "title": ""}
{"_id": "d17441", "text": "async def login(\n        username: str, password: str, brand: str,\n        websession: ClientSession = None) -> API:\n    \"\"\"Log in to the API.\"\"\"\n    api = API(brand, websession)\n    await api.authenticate(username, password)\n    return api", "title": ""}
{"_id": "d17442", "text": "def should_rollover(self, record: LogRecord) -> bool:\n        \"\"\"\n        Determine if rollover should occur.\n\n        record is not used, as we are just comparing times, but it is needed so\n        the method signatures are the same\n        \"\"\"\n        t = int(time.time())\n        if t >= self.rollover_at:\n            return True\n        return False", "title": ""}
{"_id": "d17443", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d17444", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d17445", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17446", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d17447", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d17448", "text": "def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict:\n        \"\"\"HTTP request method of interface implementation.\"\"\"", "title": ""}
{"_id": "d17449", "text": "def after_epoch(self, **_) -> None:\n        \"\"\"Save/override the latest model after every epoch.\"\"\"\n        SaveEvery.save_model(model=self._model, name_suffix=self._OUTPUT_NAME, on_failure=self._on_save_failure)", "title": ""}
{"_id": "d17450", "text": "def last(self):\n        \"\"\"Last time step available.\n\n        Example:\n            >>> sdat = StagyyData('path/to/run')\n            >>> assert(sdat.steps.last is sdat.steps[-1])\n        \"\"\"\n        if self._last is UNDETERMINED:\n            # not necessarily the last one...\n            self._last = self.sdat.tseries.index[-1]\n        return self[self._last]", "title": ""}
{"_id": "d17451", "text": "def prevPlot(self):\n        \"\"\"Moves the displayed plot to the previous one\"\"\"\n        if self.stacker.currentIndex() > 0:\n            self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)", "title": ""}
{"_id": "d17452", "text": "def decodebytes(input):\n    \"\"\"Decode base64 string to byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _decodebytes_py3(input)\n    return _decodebytes_py2(input)", "title": ""}
{"_id": "d17453", "text": "def check64bit(current_system=\"python\"):\n    \"\"\"checks if you are on a 64 bit platform\"\"\"\n    if current_system == \"python\":\n        return sys.maxsize > 2147483647\n    elif current_system == \"os\":\n        import platform\n        pm = platform.machine()\n        if pm != \"..\" and pm.endswith('64'):  # recent Python (not Iron)\n            return True\n        else:\n            if 'PROCESSOR_ARCHITEW6432' in os.environ:\n                return True  # 32 bit program running on 64 bit Windows\n            try:\n                # 64 bit Windows 64 bit program\n                return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')\n            except IndexError:\n                pass  # not Windows\n            try:\n                # this often works in Linux\n                return '64' in platform.architecture()[0]\n            except Exception:\n                # is an older version of Python, assume also an older os@\n                # (best we can guess)\n                return False", "title": ""}
{"_id": "d17454", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d17455", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d17456", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d17457", "text": "def sortBy(self, keyfunc, ascending=True, numPartitions=None):\n        \"\"\"\n        Sorts this RDD by the given keyfunc\n\n        >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n        >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()\n        [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n        >>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()\n        [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n        \"\"\"\n        return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values()", "title": ""}
{"_id": "d17458", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d17459", "text": "def multiple_replace(string, replacements):\n    # type: (str, Dict[str,str]) -> str\n    \"\"\"Simultaneously replace multiple strigns in a string\n\n    Args:\n        string (str): Input string\n        replacements (Dict[str,str]): Replacements dictionary\n\n    Returns:\n        str: String with replacements\n\n    \"\"\"\n    pattern = re.compile(\"|\".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL)\n    return pattern.sub(lambda x: replacements[x.group(0)], string)", "title": ""}
{"_id": "d17460", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d17461", "text": "def uniqued(iterable):\n    \"\"\"Return unique list of ``iterable`` items preserving order.\n\n    >>> uniqued('spameggs')\n    ['s', 'p', 'a', 'm', 'e', 'g']\n    \"\"\"\n    seen = set()\n    return [item for item in iterable if item not in seen and not seen.add(item)]", "title": ""}
{"_id": "d17462", "text": "def _check_samples_nodups(fnames):\n    \"\"\"Ensure a set of input VCFs do not have duplicate samples.\n    \"\"\"\n    counts = defaultdict(int)\n    for f in fnames:\n        for s in get_samples(f):\n            counts[s] += 1\n    duplicates = [s for s, c in counts.items() if c > 1]\n    if duplicates:\n        raise ValueError(\"Duplicate samples found in inputs %s: %s\" % (duplicates, fnames))", "title": ""}
{"_id": "d17463", "text": "def get_window_dim():\n    \"\"\" gets the dimensions depending on python version and os\"\"\"\n    version = sys.version_info\n\n    if version >= (3, 3):\n        return _size_36()\n    if platform.system() == 'Windows':\n        return _size_windows()\n    return _size_27()", "title": ""}
{"_id": "d17464", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d17465", "text": "def decode_base64(data: str) -> bytes:\n    \"\"\"Decode base64, padding being optional.\n\n    :param data: Base64 data as an ASCII byte string\n    :returns: The decoded byte string.\n    \"\"\"\n    missing_padding = len(data) % 4\n    if missing_padding != 0:\n        data += \"=\" * (4 - missing_padding)\n    return base64.decodebytes(data.encode(\"utf-8\"))", "title": ""}
{"_id": "d17466", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d17467", "text": "def obj_in_list_always(target_list, obj):\n    \"\"\"\n    >>> l = [1,1,1]\n    >>> obj_in_list_always(l, 1)\n    True\n    >>> l.append(2)\n    >>> obj_in_list_always(l, 1)\n    False\n    \"\"\"\n    for item in set(target_list):\n        if item is not obj:\n            return False\n    return True", "title": ""}
{"_id": "d17468", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d17469", "text": "def has_changed (filename):\n    \"\"\"Check if filename has changed since the last check. If this\n    is the first check, assume the file is changed.\"\"\"\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]", "title": ""}
{"_id": "d17470", "text": "def copy_without_prompts(self):\n        \"\"\"Copy text to clipboard without prompts\"\"\"\n        text = self.get_selected_text()\n        lines = text.split(os.linesep)\n        for index, line in enumerate(lines):\n            if line.startswith('>>> ') or line.startswith('... '):\n                lines[index] = line[4:]\n        text = os.linesep.join(lines)\n        QApplication.clipboard().setText(text)", "title": ""}
{"_id": "d17471", "text": "def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type one that inherits from :class:`Numeric`,\n    such as :class:`Float`, :class:`Decimal`?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Numeric)", "title": ""}
{"_id": "d17472", "text": "def warn_if_nans_exist(X):\n    \"\"\"Warn if nans exist in a numpy array.\"\"\"\n    null_count = count_rows_with_nans(X)\n    total = len(X)\n    percent = 100 * null_count / total\n\n    if null_count > 0:\n        warning_message = \\\n            'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n            'complete rows will be plotted.'.format(null_count, total, percent)\n        warnings.warn(warning_message, DataWarning)", "title": ""}
{"_id": "d17473", "text": "def check_lengths(*arrays):\n    \"\"\"\n    tool to ensure input and output data have the same number of samples\n\n    Parameters\n    ----------\n    *arrays : iterable of arrays to be checked\n\n    Returns\n    -------\n    None\n    \"\"\"\n    lengths = [len(array) for array in arrays]\n    if len(np.unique(lengths)) > 1:\n        raise ValueError('Inconsistent data lengths: {}'.format(lengths))", "title": ""}
{"_id": "d17474", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d17475", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d17476", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d17477", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d17478", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d17479", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d17480", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d17481", "text": "def is_any_type_set(sett: Set[Type]) -> bool:\n    \"\"\"\n    Helper method to check if a set of types is the {AnyObject} singleton\n\n    :param sett:\n    :return:\n    \"\"\"\n    return len(sett) == 1 and is_any_type(min(sett))", "title": ""}
{"_id": "d17482", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d17483", "text": "def isfinite(data: mx.nd.NDArray) -> mx.nd.NDArray:\n    \"\"\"Performs an element-wise check to determine if the NDArray contains an infinite element or not.\n       TODO: remove this funciton after upgrade to MXNet 1.4.* in favor of mx.ndarray.contrib.isfinite()\n    \"\"\"\n    is_data_not_nan = data == data\n    is_data_not_infinite = data.abs() != np.inf\n    return mx.nd.logical_and(is_data_not_infinite, is_data_not_nan)", "title": ""}
{"_id": "d17484", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d17485", "text": "def set_range(self, min_val, max_val):\n        \"\"\"Set the range of the colormap to [*min_val*, *max_val*]\n        \"\"\"\n        if min_val > max_val:\n            max_val, min_val = min_val, max_val\n        self.values = (((self.values * 1.0 - self.values.min()) /\n                        (self.values.max() - self.values.min()))\n                       * (max_val - min_val) + min_val)", "title": ""}
{"_id": "d17486", "text": "def closest_values(L):\n    \"\"\"Closest values\n\n    :param L: list of values\n    :returns: two values from L with minimal distance\n    :modifies: the order of L\n    :complexity: O(n log n), for n=len(L)\n    \"\"\"\n    assert len(L) >= 2\n    L.sort()\n    valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L)))\n    return L[argmin - 1], L[argmin]", "title": ""}
{"_id": "d17487", "text": "def execute_sql(self, query):\n        \"\"\"\n        Executes a given query string on an open postgres database.\n\n        \"\"\"\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", "title": ""}
{"_id": "d17488", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d17489", "text": "def is_any_type_set(sett: Set[Type]) -> bool:\n    \"\"\"\n    Helper method to check if a set of types is the {AnyObject} singleton\n\n    :param sett:\n    :return:\n    \"\"\"\n    return len(sett) == 1 and is_any_type(min(sett))", "title": ""}
{"_id": "d17490", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17491", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d17492", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d17493", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d17494", "text": "def str_upper(x):\n    \"\"\"Converts all strings in a column to uppercase.\n\n    :returns: an expression containing the converted strings.\n\n    Example:\n\n    >>> import vaex\n    >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']\n    >>> df = vaex.from_arrays(text=text)\n    >>> df\n      #  text\n      0  Something\n      1  very pretty\n      2  is coming\n      3  our\n      4  way.\n\n\n    >>> df.text.str.upper()\n    Expression = str_upper(text)\n    Length: 5 dtype: str (expression)\n    ---------------------------------\n    0    SOMETHING\n    1  VERY PRETTY\n    2    IS COMING\n    3          OUR\n    4         WAY.\n\n    \"\"\"\n    sl = _to_string_sequence(x).upper()\n    return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)", "title": ""}
{"_id": "d17495", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d17496", "text": "def non_increasing(values):\n    \"\"\"True if values are not increasing.\"\"\"\n    return all(x >= y for x, y in zip(values, values[1:]))", "title": ""}
{"_id": "d17497", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d17498", "text": "def read(self, start_position: int, size: int) -> memoryview:\n        \"\"\"\n        Return a view into the memory\n        \"\"\"\n        return memoryview(self._bytes)[start_position:start_position + size]", "title": ""}
{"_id": "d17499", "text": "def _prm_get_longest_stringsize(string_list):\n        \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n        maxlength = 1\n\n        for stringar in string_list:\n            if isinstance(stringar, np.ndarray):\n                if stringar.ndim > 0:\n                    for string in stringar.ravel():\n                        maxlength = max(len(string), maxlength)\n                else:\n                    maxlength = max(len(stringar.tolist()), maxlength)\n            else:\n                maxlength = max(len(stringar), maxlength)\n\n        # Make the string Col longer than needed in order to allow later on slightly larger strings\n        return int(maxlength * 1.5)", "title": ""}
{"_id": "d17500", "text": "async def stdout(self) -> AsyncGenerator[str, None]:\n        \"\"\"Asynchronous generator for lines from subprocess stdout.\"\"\"\n        await self.wait_running()\n        async for line in self._subprocess.stdout:  # type: ignore\n            yield line", "title": ""}
{"_id": "d17501", "text": "def same_network(atree, btree) -> bool:\n    \"\"\"True if given trees share the same structure of powernodes,\n    independently of (power)node names,\n    and same edge topology between (power)nodes.\n\n    \"\"\"\n    return same_hierarchy(atree, btree) and same_topology(atree, btree)", "title": ""}
{"_id": "d17502", "text": "def is_strict_numeric(n: Node) -> bool:\n    \"\"\" numeric denotes typed literals with datatypes xsd:integer, xsd:decimal, xsd:float, and xsd:double. \"\"\"\n    return is_typed_literal(n) and cast(Literal, n).datatype in [XSD.integer, XSD.decimal, XSD.float, XSD.double]", "title": ""}
{"_id": "d17503", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d17504", "text": "def bytes_hack(buf):\n    \"\"\"\n    Hacky workaround for old installs of the library on systems without python-future that were\n    keeping the 2to3 update from working after auto-update.\n    \"\"\"\n    ub = None\n    if sys.version_info > (3,):\n        ub = buf\n    else:\n        ub = bytes(buf)\n\n    return ub", "title": ""}
{"_id": "d17505", "text": "def camel_to_snake(s: str) -> str:\n    \"\"\"Convert string from camel case to snake case.\"\"\"\n\n    return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()", "title": ""}
{"_id": "d17506", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d17507", "text": "def get_language():\n    \"\"\"\n    Wrapper around Django's `get_language` utility.\n    For Django >= 1.8, `get_language` returns None in case no translation is activate.\n    Here we patch this behavior e.g. for back-end functionality requiring access to translated fields\n    \"\"\"\n    from parler import appsettings\n    language = dj_get_language()\n    if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:\n        return appsettings.PARLER_DEFAULT_LANGUAGE_CODE\n    else:\n        return language", "title": ""}
{"_id": "d17508", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17509", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d17510", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d17511", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17512", "text": "def b64_decode(data: bytes) -> bytes:\n    \"\"\"\n    :param data: Base 64 encoded data to decode.\n    :type data: bytes\n    :return: Base 64 decoded data.\n    :rtype: bytes\n    \"\"\"\n    missing_padding = len(data) % 4\n    if missing_padding != 0:\n        data += b'=' * (4 - missing_padding)\n    return urlsafe_b64decode(data)", "title": ""}
{"_id": "d17513", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17514", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d17515", "text": "def block_diag(*blocks: np.ndarray) -> np.ndarray:\n    \"\"\"Concatenates blocks into a block diagonal matrix.\n\n    Args:\n        *blocks: Square matrices to place along the diagonal of the result.\n\n    Returns:\n        A block diagonal matrix with the given blocks along its diagonal.\n\n    Raises:\n        ValueError: A block isn't square.\n    \"\"\"\n    for b in blocks:\n        if b.shape[0] != b.shape[1]:\n            raise ValueError('Blocks must be square.')\n\n    if not blocks:\n        return np.zeros((0, 0), dtype=np.complex128)\n\n    n = sum(b.shape[0] for b in blocks)\n    dtype = functools.reduce(_merge_dtypes, (b.dtype for b in blocks))\n\n    result = np.zeros(shape=(n, n), dtype=dtype)\n    i = 0\n    for b in blocks:\n        j = i + b.shape[0]\n        result[i:j, i:j] = b\n        i = j\n\n    return result", "title": ""}
{"_id": "d17516", "text": "async def fetchall(self) -> Iterable[sqlite3.Row]:\n        \"\"\"Fetch all remaining rows.\"\"\"\n        return await self._execute(self._cursor.fetchall)", "title": ""}
{"_id": "d17517", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d17518", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d17519", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d17520", "text": "def iterate_items(dictish):\n    \"\"\" Return a consistent (key, value) iterable on dict-like objects,\n    including lists of tuple pairs.\n\n    Example:\n\n        >>> list(iterate_items({'a': 1}))\n        [('a', 1)]\n        >>> list(iterate_items([('a', 1), ('b', 2)]))\n        [('a', 1), ('b', 2)]\n    \"\"\"\n    if hasattr(dictish, 'iteritems'):\n        return dictish.iteritems()\n    if hasattr(dictish, 'items'):\n        return dictish.items()\n    return dictish", "title": ""}
{"_id": "d17521", "text": "def bytes_hack(buf):\n    \"\"\"\n    Hacky workaround for old installs of the library on systems without python-future that were\n    keeping the 2to3 update from working after auto-update.\n    \"\"\"\n    ub = None\n    if sys.version_info > (3,):\n        ub = buf\n    else:\n        ub = bytes(buf)\n\n    return ub", "title": ""}
{"_id": "d17522", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d17523", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d17524", "text": "def get_now_sql_datetime():\n    \"\"\"\n    *A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``*\n\n    **Return:**\n        - ``now`` -- current time and date in MySQL format\n\n    **Usage:**\n        .. code-block:: python \n\n            from fundamentals import times\n            now = times.get_now_sql_datetime()\n            print now\n\n            # OUT: 2016-03-18T11:08:23 \n    \"\"\"\n    ## > IMPORTS ##\n    from datetime import datetime, date, time\n    now = datetime.now()\n    now = now.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\n    return now", "title": ""}
{"_id": "d17525", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d17526", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17527", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d17528", "text": "def lint(fmt='colorized'):\n    \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\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)", "title": ""}
{"_id": "d17529", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d17530", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d17531", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17532", "text": "def sample_normal(mean, var, rng):\n    \"\"\"Sample from independent normal distributions\n\n    Each element is an independent normal distribution.\n\n    Parameters\n    ----------\n    mean : numpy.ndarray\n      Means of the normal distribution. Shape --> (batch_num, sample_dim)\n    var : numpy.ndarray\n      Variance of the normal distribution. Shape --> (batch_num, sample_dim)\n    rng : numpy.random.RandomState\n\n    Returns\n    -------\n    ret : numpy.ndarray\n       The sampling result. Shape --> (batch_num, sample_dim)\n    \"\"\"\n    ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean\n    return ret", "title": ""}
{"_id": "d17533", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17534", "text": "def count(self, elem):\n        \"\"\"\n        Return the number of elements equal to elem present in the queue\n\n        >>> pdeque([1, 2, 1]).count(1)\n        2\n        \"\"\"\n        return self._left_list.count(elem) + self._right_list.count(elem)", "title": ""}
{"_id": "d17535", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d17536", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d17537", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17538", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d17539", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d17540", "text": "def _sum_cycles_from_tokens(self, tokens: List[str]) -> int:\n        \"\"\"Sum the total number of cycles over a list of tokens.\"\"\"\n        return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))", "title": ""}
{"_id": "d17541", "text": "def percentile(sorted_list, percent, key=lambda x: x):\n    \"\"\"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\n    \"\"\"\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])", "title": ""}
{"_id": "d17542", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d17543", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d17544", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d17545", "text": "def fib(n):\n    \"\"\"Fibonacci example function\n\n    Args:\n      n (int): integer\n\n    Returns:\n      int: n-th Fibonacci number\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", "title": ""}
{"_id": "d17546", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17547", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17548", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d17549", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17550", "text": "def try_instance_init(self, instance, late_start=False):\n        \"\"\"Try to \"initialize\" the given module instance.\n\n        :param instance: instance to init\n        :type instance: object\n        :param late_start: If late_start, don't look for last_init_try\n        :type late_start: bool\n        :return: True on successful init. False if instance init method raised any Exception.\n        :rtype: bool\n        \"\"\"\n        try:\n            instance.init_try += 1\n            # Maybe it's a retry\n            if not late_start and instance.init_try > 1:\n                # Do not try until too frequently, or it's too loopy\n                if instance.last_init_try > time.time() - MODULE_INIT_PERIOD:\n                    logger.info(\"Too early to retry initialization, retry period is %d seconds\",\n                                MODULE_INIT_PERIOD)\n                    # logger.info(\"%s / %s\", instance.last_init_try, time.time())\n                    return False\n            instance.last_init_try = time.time()\n\n            logger.info(\"Trying to initialize module: %s\", instance.name)\n\n            # If it's an external module, create/update Queues()\n            if instance.is_external:\n                instance.create_queues(self.daemon.sync_manager)\n\n            # The module instance init function says if initialization is ok\n            if not instance.init():\n                logger.warning(\"Module %s initialisation failed.\", instance.name)\n                return False\n            logger.info(\"Module %s is initialized.\", instance.name)\n        except Exception as exp:  # pylint: disable=broad-except\n            # pragma: no cover, simple protection\n            msg = \"The module instance %s raised an exception \" \\\n                  \"on initialization: %s, I remove it!\" % (instance.name, str(exp))\n            self.configuration_errors.append(msg)\n            logger.error(msg)\n            logger.exception(exp)\n            return False\n\n        return True", "title": ""}
{"_id": "d17551", "text": "def add_colons(s):\n    \"\"\"Add colons after every second digit.\n\n    This function is used in functions to prettify serials.\n\n    >>> add_colons('teststring')\n    'te:st:st:ri:ng'\n    \"\"\"\n    return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)])", "title": ""}
{"_id": "d17552", "text": "def has_jongsung(letter):\n    \"\"\"Check whether this letter contains Jongsung\"\"\"\n    if len(letter) != 1:\n        raise Exception('The target string must be one letter.')\n    if not is_hangul(letter):\n        raise NotHangulException('The target string must be Hangul')\n\n    code = lt.hangul_index(letter)\n    return code % NUM_JONG > 0", "title": ""}
{"_id": "d17553", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d17554", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17555", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d17556", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d17557", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d17558", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d17559", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d17560", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d17561", "text": "def iso_string_to_python_datetime(\n        isostring: str) -> Optional[datetime.datetime]:\n    \"\"\"\n    Takes an ISO-8601 string and returns a ``datetime``.\n    \"\"\"\n    if not isostring:\n        return None  # if you parse() an empty string, you get today's date\n    return dateutil.parser.parse(isostring)", "title": ""}
{"_id": "d17562", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d17563", "text": "def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:\n    \"\"\"\n    Within the dictionary ``d``, find a key that matches (in case-insensitive\n    fashion) the key ``k``, and return it (or ``None`` if there isn't one).\n    \"\"\"\n    for key in d.keys():\n        if k.lower() == key.lower():\n            return key\n    return None", "title": ""}
{"_id": "d17564", "text": "def find_index(segmentation, stroke_id):\n    \"\"\"\n    >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 0)\n    0\n    >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 1)\n    0\n    >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 5)\n    2\n    >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 6)\n    2\n    \"\"\"\n    for i, symbol in enumerate(segmentation):\n        for sid in symbol:\n            if sid == stroke_id:\n                return i\n    return -1", "title": ""}
{"_id": "d17565", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d17566", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d17567", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d17568", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17569", "text": "def check_oneof(**kwargs):\n    \"\"\"Raise ValueError if more than one keyword argument is not none.\n\n    Args:\n        kwargs (dict): The keyword arguments sent to the function.\n\n    Returns: None\n\n    Raises:\n        ValueError: If more than one entry in kwargs is not none.\n    \"\"\"\n    # Sanity check: If no keyword arguments were sent, this is fine.\n    if not kwargs:\n        return None\n\n    not_nones = [val for val in kwargs.values() if val is not None]\n    if len(not_nones) > 1:\n        raise ValueError('Only one of {fields} should be set.'.format(\n            fields=', '.join(sorted(kwargs.keys())),\n        ))", "title": ""}
{"_id": "d17570", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d17571", "text": "def execute(cur, *args):\n    \"\"\"Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)\n    \"\"\"\n    stmt = args[0]\n    if len(args) > 1:\n        stmt = stmt.replace('%', '%%').replace('?', '%r')\n        print(stmt % (args[1]))\n    return cur.execute(*args)", "title": ""}
{"_id": "d17572", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d17573", "text": "def prin(*args, **kwargs):\n    r\"\"\"Like ``print``, but a function. I.e. prints out all arguments as\n    ``print`` would do. Specify output stream like this::\n\n      print('ERROR', `out=\"sys.stderr\"``).\n\n    \"\"\"\n    print >> kwargs.get('out',None), \" \".join([str(arg) for arg in args])", "title": ""}
{"_id": "d17574", "text": "def camelize(key):\n    \"\"\"Convert a python_style_variable_name to lowerCamelCase.\n\n    Examples\n    --------\n    >>> camelize('variable_name')\n    'variableName'\n    >>> camelize('variableName')\n    'variableName'\n    \"\"\"\n    return ''.join(x.capitalize() if i > 0 else x\n                   for i, x in enumerate(key.split('_')))", "title": ""}
{"_id": "d17575", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17576", "text": "def __init__(self, enum_obj: Any) -> None:\n        \"\"\"Initialize attributes for informative output.\n\n        :param enum_obj: Enum object.\n        \"\"\"\n        if enum_obj:\n            self.name = enum_obj\n            self.items = ', '.join([str(i) for i in enum_obj])\n        else:\n            self.items = ''", "title": ""}
{"_id": "d17577", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d17578", "text": "def _groups_of_size(iterable, n, fillvalue=None):\n    \"\"\"Collect data into fixed-length chunks or blocks.\"\"\"\n    # _groups_of_size('ABCDEFG', 3, 'x') --> ABC DEF Gxx\n    args = [iter(iterable)] * n\n    return zip_longest(fillvalue=fillvalue, *args)", "title": ""}
{"_id": "d17579", "text": "def get_versions(reporev=True):\n    \"\"\"Get version information for components used by Spyder\"\"\"\n    import sys\n    import platform\n\n    import qtpy\n    import qtpy.QtCore\n\n    revision = None\n    if reporev:\n        from spyder.utils import vcs\n        revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n    if not sys.platform == 'darwin':  # To avoid a crash with our Mac app\n        system = platform.system()\n    else:\n        system = 'Darwin'\n\n    return {\n        'spyder': __version__,\n        'python': platform.python_version(),  # \"2.7.3\"\n        'bitness': 64 if sys.maxsize > 2**32 else 32,\n        'qt': qtpy.QtCore.__version__,\n        'qt_api': qtpy.API_NAME,      # PyQt5\n        'qt_api_ver': qtpy.PYQT_VERSION,\n        'system': system,   # Linux, Windows, ...\n        'release': platform.release(),  # XP, 10.6, 2.2.0, etc.\n        'revision': revision,  # '9fdf926eccce'\n    }", "title": ""}
{"_id": "d17580", "text": "def long_substring(str_a, str_b):\n    \"\"\"\n    Looks for a longest common string between any two given strings passed\n    :param str_a: str\n    :param str_b: str\n\n    Big Thanks to Pulkit Kathuria(@kevincobain2000) for the function\n    The function is derived from jProcessing toolkit suite\n    \"\"\"\n    data = [str_a, str_b]\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    return substr.strip()", "title": ""}
{"_id": "d17581", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d17582", "text": "def squash(self, a, b):\n        \"\"\"\n        Returns a generator that squashes two iterables into one.\n\n        ```\n        ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or']\n        ```\n        \"\"\"\n\n        return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product(a, b))", "title": ""}
{"_id": "d17583", "text": "def SetCursorPos(x: int, y: int) -> bool:\n    \"\"\"\n    SetCursorPos from Win32.\n    Set mouse cursor to point x, y.\n    x: int.\n    y: int.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    return bool(ctypes.windll.user32.SetCursorPos(x, y))", "title": ""}
{"_id": "d17584", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d17585", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d17586", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d17587", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d17588", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17589", "text": "def wipe_table(self, table: str) -> int:\n        \"\"\"Delete all records from a table. Use caution!\"\"\"\n        sql = \"DELETE FROM \" + self.delimit(table)\n        return self.db_exec(sql)", "title": ""}
{"_id": "d17590", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d17591", "text": "def _interface_exists(self, interface):\n        \"\"\"Check whether interface exists.\"\"\"\n        ios_cfg = self._get_running_config()\n        parse = HTParser(ios_cfg)\n        itfcs_raw = parse.find_lines(\"^interface \" + interface)\n        return len(itfcs_raw) > 0", "title": ""}
{"_id": "d17592", "text": "def templategetter(tmpl):\n    \"\"\"\n    This is a dirty little template function generator that turns single-brace\n    Mustache-style template strings into functions that interpolate dict keys:\n\n    >>> get_name = templategetter(\"{first} {last}\")\n    >>> get_name({'first': 'Shawn', 'last': 'Allen'})\n    'Shawn Allen'\n    \"\"\"\n    tmpl = tmpl.replace('{', '%(')\n    tmpl = tmpl.replace('}', ')s')\n    return lambda data: tmpl % data", "title": ""}
{"_id": "d17593", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d17594", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d17595", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d17596", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d17597", "text": "def get_window_dim():\n    \"\"\" gets the dimensions depending on python version and os\"\"\"\n    version = sys.version_info\n\n    if version >= (3, 3):\n        return _size_36()\n    if platform.system() == 'Windows':\n        return _size_windows()\n    return _size_27()", "title": ""}
{"_id": "d17598", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d17599", "text": "def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\"\n    Args:\n        x: iterable of strings\n\n    Yields:\n        each string in lower case\n    \"\"\"\n    for string in x:\n        yield string.lower()", "title": ""}
{"_id": "d17600", "text": "def calculate_fft(data, tbin):\n    \"\"\"\n    Function to calculate the Fourier transform of data.\n    \n    \n    Parameters\n    ----------\n    data : numpy.ndarray\n        1D or 2D array containing time series.\n    tbin : float\n        Bin size of time series (in ms).\n    \n    \n    Returns\n    -------\n    freqs : numpy.ndarray\n        Frequency axis of signal in Fourier space.         \n    fft : numpy.ndarray\n        Signal in Fourier space.\n        \n    \"\"\"\n    if len(np.shape(data)) > 1:\n        n = len(data[0])\n        return np.fft.fftfreq(n, tbin * 1e-3), np.fft.fft(data, axis=1)\n    else:\n        n = len(data)\n        return np.fft.fftfreq(n, tbin * 1e-3), np.fft.fft(data)", "title": ""}
{"_id": "d17601", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17602", "text": "def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:\n    \"\"\"return the higher parent which is not an AssignName, Tuple or List node\n    \"\"\"\n    while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)):\n        node = node.parent\n    return node", "title": ""}
{"_id": "d17603", "text": "def get_commits_modified_file(self, filepath: str) -> List[str]:\n        \"\"\"\n        Given a filepath, returns all the commits that modified this file\n        (following renames).\n\n        :param str filepath: path to the file\n        :return: the list of commits' hash\n        \"\"\"\n        path = str(Path(filepath))\n\n        commits = []\n        try:\n            commits = self.git.log(\"--follow\", \"--format=%H\", path).split('\\n')\n        except GitCommandError:\n            logger.debug(\"Could not find information of file %s\", path)\n\n        return commits", "title": ""}
{"_id": "d17604", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d17605", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d17606", "text": "def get_day_name(self) -> str:\n        \"\"\" Returns the day name \"\"\"\n        weekday = self.value.isoweekday() - 1\n        return calendar.day_name[weekday]", "title": ""}
{"_id": "d17607", "text": "def fib(n):\n    \"\"\"Fibonacci example function\n\n    Args:\n      n (int): integer\n\n    Returns:\n      int: n-th Fibonacci number\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", "title": ""}
{"_id": "d17608", "text": "def get_language():\n    \"\"\"\n    Wrapper around Django's `get_language` utility.\n    For Django >= 1.8, `get_language` returns None in case no translation is activate.\n    Here we patch this behavior e.g. for back-end functionality requiring access to translated fields\n    \"\"\"\n    from parler import appsettings\n    language = dj_get_language()\n    if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:\n        return appsettings.PARLER_DEFAULT_LANGUAGE_CODE\n    else:\n        return language", "title": ""}
{"_id": "d17609", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d17610", "text": "def __gt__(self, other):\n        \"\"\"Test for greater than.\"\"\"\n        if isinstance(other, Address):\n            return str(self) > str(other)\n        raise TypeError", "title": ""}
{"_id": "d17611", "text": "def similarity(word1: str, word2: str) -> float:\n    \"\"\"\n    Get cosine similarity between two words.\n    If a word is not in the vocabulary, KeyError will be raised.\n\n    :param string word1: first word\n    :param string word2: second word\n    :return: the cosine similarity between the two word vectors\n    \"\"\"\n    return _MODEL.similarity(word1, word2)", "title": ""}
{"_id": "d17612", "text": "def snake_case(a_string):\n    \"\"\"Returns a snake cased version of a string.\n\n    :param a_string: any :class:`str` object.\n\n    Usage:\n        >>> snake_case('FooBar')\n        \"foo_bar\"\n    \"\"\"\n\n    partial = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', a_string)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', partial).lower()", "title": ""}
{"_id": "d17613", "text": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n    \"\"\"\n    Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n    :param buckets: List of buckets.\n    :return: The largest bucket in the list.\n    \"\"\"\n    return max(buckets)", "title": ""}
{"_id": "d17614", "text": "def __remove_method(m: lmap.Map, key: T) -> lmap.Map:\n        \"\"\"Swap the methods atom to remove method with key.\"\"\"\n        return m.dissoc(key)", "title": ""}
{"_id": "d17615", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d17616", "text": "def __gt__(self, other):\n        \"\"\"Test for greater than.\"\"\"\n        if isinstance(other, Address):\n            return str(self) > str(other)\n        raise TypeError", "title": ""}
{"_id": "d17617", "text": "def file_or_stdin() -> Callable:\n    \"\"\"\n    Returns a file descriptor from stdin or opening a file from a given path.\n    \"\"\"\n\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\n    return parse", "title": ""}
{"_id": "d17618", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d17619", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d17620", "text": "def fetchvalue(self, sql: str, *args) -> Optional[Any]:\n        \"\"\"Executes SQL; returns the first value of the first row, or None.\"\"\"\n        row = self.fetchone(sql, *args)\n        if row is None:\n            return None\n        return row[0]", "title": ""}
{"_id": "d17621", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d17622", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d17623", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d17624", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d17625", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d17626", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d17627", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d17628", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17629", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17630", "text": "def running_containers(name_filter: str) -> List[str]:\n    \"\"\"\n    :raises docker.exceptions.APIError\n    \"\"\"\n    return [container.short_id for container in\n            docker_client.containers.list(filters={\"name\": name_filter})]", "title": ""}
{"_id": "d17631", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d17632", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d17633", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d17634", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d17635", "text": "def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:\n        \"\"\" Return a json array as a list\n\n        :param value: array\n        :return: array with JsonObj instances removed\n        \"\"\"\n        return [e._as_dict if isinstance(e, JsonObj) else e for e in value]", "title": ""}
{"_id": "d17636", "text": "def cookies(self) -> Dict[str, str]:\n        \"\"\"The parsed cookies attached to this request.\"\"\"\n        cookies = SimpleCookie()\n        cookies.load(self.headers.get('Cookie', ''))\n        return {key: cookie.value for key, cookie in cookies.items()}", "title": ""}
{"_id": "d17637", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d17638", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d17639", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d17640", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d17641", "text": "def de_duplicate(items):\n    \"\"\"Remove any duplicate item, preserving order\n\n    >>> de_duplicate([1, 2, 1, 2])\n    [1, 2]\n    \"\"\"\n    result = []\n    for item in items:\n        if item not in result:\n            result.append(item)\n    return result", "title": ""}
{"_id": "d17642", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17643", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d17644", "text": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n    \"\"\"\n    Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n    :param buckets: List of buckets.\n    :return: The largest bucket in the list.\n    \"\"\"\n    return max(buckets)", "title": ""}
{"_id": "d17645", "text": "def docker_environment(env):\n    \"\"\"\n    Transform dictionary of environment variables into Docker -e parameters.\n\n    >>> result = docker_environment({'param1': 'val1', 'param2': 'val2'})\n    >>> result in ['-e \"param1=val1\" -e \"param2=val2\"', '-e \"param2=val2\" -e \"param1=val1\"']\n    True\n    \"\"\"\n    return ' '.join(\n        [\"-e \\\"%s=%s\\\"\" % (key, value.replace(\"$\", \"\\\\$\").replace(\"\\\"\", \"\\\\\\\"\").replace(\"`\", \"\\\\`\"))\n         for key, value in env.items()])", "title": ""}
{"_id": "d17646", "text": "def call_api(self, resource_path, method,\n                 path_params=None, query_params=None, header_params=None,\n                 body=None, post_params=None, files=None,\n                 response_type=None, auth_settings=None, asynchronous=None,\n                 _return_http_data_only=None, collection_formats=None, _preload_content=True,\n                 _request_timeout=None):\n        \"\"\"\n        Makes the HTTP request (synchronous) and return the deserialized data.\n        To make an async request, set the asynchronous parameter.\n\n        :param resource_path: Path to method endpoint.\n        :param method: Method to call.\n        :param path_params: Path parameters in the url.\n        :param query_params: Query parameters in the url.\n        :param header_params: Header parameters to be\n            placed in the request header.\n        :param body: Request body.\n        :param post_params dict: Request post form parameters,\n            for `application/x-www-form-urlencoded`, `multipart/form-data`.\n        :param auth_settings list: Auth Settings names for the request.\n        :param response: Response data type.\n        :param files dict: key -> filename, value -> filepath,\n            for `multipart/form-data`.\n        :param asynchronous bool: execute request asynchronously\n        :param _return_http_data_only: response data without head status code and headers\n        :param collection_formats: dict of collection formats for path, query,\n            header, and post parameters.\n        :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without\n                                 reading/decoding response data. Default is True.\n        :param _request_timeout: timeout setting for this request. If one number provided, it will be total request\n                                 timeout. It can also be a pair (tuple) of (connection, read) timeouts.\n        :return:\n            If asynchronous parameter is True,\n            the request will be called asynchronously.\n            The method will return the request thread.\n            If parameter asynchronous is False or missing,\n            then the method will return the response directly.\n        \"\"\"\n        if not asynchronous:\n            return self.__call_api(resource_path, method,\n                                   path_params, query_params, header_params,\n                                   body, post_params, files,\n                                   response_type, auth_settings,\n                                   _return_http_data_only, collection_formats, _preload_content, _request_timeout)\n        else:\n            thread = self.pool.apply_async(self.__call_api, (resource_path, method,\n                                           path_params, query_params,\n                                           header_params, body,\n                                           post_params, files,\n                                           response_type, auth_settings,\n                                           _return_http_data_only,\n                                           collection_formats, _preload_content, _request_timeout))\n        return thread", "title": ""}
{"_id": "d17647", "text": "def snake_to_camel(value):\n    \"\"\"\n    Converts a snake_case_string to a camelCaseString.\n\n    >>> snake_to_camel(\"foo_bar_baz\")\n    'fooBarBaz'\n    \"\"\"\n    camel = \"\".join(word.title() for word in value.split(\"_\"))\n    return value[:1].lower() + camel[1:]", "title": ""}
{"_id": "d17648", "text": "def camelize(key):\n    \"\"\"Convert a python_style_variable_name to lowerCamelCase.\n\n    Examples\n    --------\n    >>> camelize('variable_name')\n    'variableName'\n    >>> camelize('variableName')\n    'variableName'\n    \"\"\"\n    return ''.join(x.capitalize() if i > 0 else x\n                   for i, x in enumerate(key.split('_')))", "title": ""}
{"_id": "d17649", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d17650", "text": "def parsehttpdate(string_):\n    \"\"\"\n    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)\n    \"\"\"\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])", "title": ""}
{"_id": "d17651", "text": "def count(self, elem):\n        \"\"\"\n        Return the number of elements equal to elem present in the queue\n\n        >>> pdeque([1, 2, 1]).count(1)\n        2\n        \"\"\"\n        return self._left_list.count(elem) + self._right_list.count(elem)", "title": ""}
{"_id": "d17652", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d17653", "text": "def find_duplicates(l: list) -> set:\n    \"\"\"\n    Return the duplicates in a list.\n\n    The function relies on\n    https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n    Parameters\n    ----------\n    l : list\n        Name\n\n    Returns\n    -------\n    set\n        Duplicated values\n\n    >>> find_duplicates([1,2,3])\n    set()\n    >>> find_duplicates([1,2,1])\n    {1}\n    \"\"\"\n    return set([x for x in l if l.count(x) > 1])", "title": ""}
{"_id": "d17654", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d17655", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17656", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d17657", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d17658", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d17659", "text": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n    \"\"\"\n    Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n    :param buckets: List of buckets.\n    :return: The largest bucket in the list.\n    \"\"\"\n    return max(buckets)", "title": ""}
{"_id": "d17660", "text": "def translate_dict(cls, val):\n        \"\"\"Translate dicts to scala Maps\"\"\"\n        escaped = ', '.join(\n            [\"{} -> {}\".format(cls.translate_str(k), cls.translate(v)) for k, v in val.items()]\n        )\n        return 'Map({})'.format(escaped)", "title": ""}
{"_id": "d17661", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d17662", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d17663", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d17664", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d17665", "text": "def datetime_iso_format(date):\n    \"\"\"\n    Return an ISO-8601 representation of a datetime object.\n    \"\"\"\n    return \"{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z\".format(\n        date.year, date.month, date.day, date.hour,\n        date.minute, date.second)", "title": ""}
{"_id": "d17666", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d17667", "text": "def get_bin_edges_from_axis(axis) -> np.ndarray:\n    \"\"\" Get bin edges from a ROOT hist axis.\n\n    Note:\n        Doesn't include over- or underflow bins!\n\n    Args:\n        axis (ROOT.TAxis): Axis from which the bin edges should be extracted.\n    Returns:\n        Array containing the bin edges.\n    \"\"\"\n    # Don't include over- or underflow bins\n    bins = range(1, axis.GetNbins() + 1)\n    # Bin edges\n    bin_edges = np.empty(len(bins) + 1)\n    bin_edges[:-1] = [axis.GetBinLowEdge(i) for i in bins]\n    bin_edges[-1] = axis.GetBinUpEdge(axis.GetNbins())\n\n    return bin_edges", "title": ""}
{"_id": "d17668", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d17669", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d17670", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d17671", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d17672", "text": "def lowercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the lowercase chars in the given string.\"\"\"\n        return ''.join([c if c.islower() else '' for c in str(string)])", "title": ""}
{"_id": "d17673", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d17674", "text": "def get_language(query: str) -> str:\n    \"\"\"Tries to work out the highlight.js language of a given file name or\n    shebang. Returns an empty string if none match.\n    \"\"\"\n    query = query.lower()\n    for language in LANGUAGES:\n        if query.endswith(language):\n            return language\n    return ''", "title": ""}
{"_id": "d17675", "text": "def get_datatype(self, table: str, column: str) -> str:\n        \"\"\"Returns database SQL datatype for a column: e.g. VARCHAR.\"\"\"\n        return self.flavour.get_datatype(self, table, column).upper()", "title": ""}
{"_id": "d17676", "text": "def lint(fmt='colorized'):\n    \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\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)", "title": ""}
{"_id": "d17677", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d17678", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d17679", "text": "def _strip_top_comments(lines: Sequence[str], line_separator: str) -> str:\n        \"\"\"Strips # comments that exist at the top of the given lines\"\"\"\n        lines = copy.copy(lines)\n        while lines and lines[0].startswith(\"#\"):\n            lines = lines[1:]\n        return line_separator.join(lines)", "title": ""}
{"_id": "d17680", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17681", "text": "def scope_logger(cls):\n    \"\"\"\n    Class decorator for adding a class local logger\n\n    Example:\n    >>> @scope_logger\n    >>> class Test:\n    >>>     def __init__(self):\n    >>>         self.log.info(\"class instantiated\")\n    >>> t = Test()\n    \n    \"\"\"\n    cls.log = logging.getLogger('{0}.{1}'.format(cls.__module__, cls.__name__))\n    return cls", "title": ""}
{"_id": "d17682", "text": "def is_quoted(arg: str) -> bool:\n    \"\"\"\n    Checks if a string is quoted\n    :param arg: the string being checked for quotes\n    :return: True if a string is quoted\n    \"\"\"\n    return len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES", "title": ""}
{"_id": "d17683", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d17684", "text": "def isfile_notempty(inputfile: str) -> bool:\n        \"\"\"Check if the input filename with path is a file and is not empty.\"\"\"\n        try:\n            return isfile(inputfile) and getsize(inputfile) > 0\n        except TypeError:\n            raise TypeError('inputfile is not a valid type')", "title": ""}
{"_id": "d17685", "text": "def read_flat(self):\n        \"\"\"\n        Read a PNG file and decode it into flat row flat pixel format.\n\n        Returns (*width*, *height*, *pixels*, *metadata*).\n\n        May use excessive memory.\n\n        `pixels` are returned in flat row flat pixel format.\n\n        See also the :meth:`read` method which returns pixels in the\n        more stream-friendly boxed row flat pixel format.\n        \"\"\"\n        x, y, pixel, meta = self.read()\n        arraycode = 'BH'[meta['bitdepth'] > 8]\n        pixel = array(arraycode, itertools.chain(*pixel))\n        return x, y, pixel, meta", "title": ""}
{"_id": "d17686", "text": "def SwitchToThisWindow(handle: int) -> None:\n    \"\"\"\n    SwitchToThisWindow from Win32.\n    handle: int, the handle of a native window.\n    \"\"\"\n    ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)", "title": ""}
{"_id": "d17687", "text": "def hex_color_to_tuple(hex):\n    \"\"\" convent hex color to tuple\n    \"#ffffff\"   ->  (255, 255, 255)\n    \"#ffff00ff\" ->  (255, 255, 0, 255)\n    \"\"\"\n    hex = hex[1:]\n    length = len(hex) // 2\n    return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))", "title": ""}
{"_id": "d17688", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17689", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d17690", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d17691", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d17692", "text": "def check64bit(current_system=\"python\"):\n    \"\"\"checks if you are on a 64 bit platform\"\"\"\n    if current_system == \"python\":\n        return sys.maxsize > 2147483647\n    elif current_system == \"os\":\n        import platform\n        pm = platform.machine()\n        if pm != \"..\" and pm.endswith('64'):  # recent Python (not Iron)\n            return True\n        else:\n            if 'PROCESSOR_ARCHITEW6432' in os.environ:\n                return True  # 32 bit program running on 64 bit Windows\n            try:\n                # 64 bit Windows 64 bit program\n                return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')\n            except IndexError:\n                pass  # not Windows\n            try:\n                # this often works in Linux\n                return '64' in platform.architecture()[0]\n            except Exception:\n                # is an older version of Python, assume also an older os@\n                # (best we can guess)\n                return False", "title": ""}
{"_id": "d17693", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d17694", "text": "def __rmatmul__(self, other):\n        \"\"\"\n        Matrix multiplication using binary `@` operator in Python>=3.5.\n        \"\"\"\n        return self.T.dot(np.transpose(other)).T", "title": ""}
{"_id": "d17695", "text": "def decodebytes(input):\n    \"\"\"Decode base64 string to byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _decodebytes_py3(input)\n    return _decodebytes_py2(input)", "title": ""}
{"_id": "d17696", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d17697", "text": "def parse_reading(val: str) -> Optional[float]:\n    \"\"\" Convert reading value to float (if possible) \"\"\"\n    try:\n        return float(val)\n    except ValueError:\n        logging.warning('Reading of \"%s\" is not a number', val)\n        return None", "title": ""}
{"_id": "d17698", "text": "def from_buffer(buffer, mime=False):\n    \"\"\"\n    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'\n    \"\"\"\n    m = _get_magic_type(mime)\n    return m.from_buffer(buffer)", "title": ""}
{"_id": "d17699", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17700", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d17701", "text": "def capitalize(string):\n    \"\"\"Capitalize a sentence.\n\n    Parameters\n    ----------\n    string : `str`\n        String to capitalize.\n\n    Returns\n    -------\n    `str`\n        Capitalized string.\n\n    Examples\n    --------\n    >>> capitalize('worD WORD WoRd')\n    'Word word word'\n    \"\"\"\n    if not string:\n        return string\n    if len(string) == 1:\n        return string.upper()\n    return string[0].upper() + string[1:].lower()", "title": ""}
{"_id": "d17702", "text": "def iterate_items(dictish):\n    \"\"\" Return a consistent (key, value) iterable on dict-like objects,\n    including lists of tuple pairs.\n\n    Example:\n\n        >>> list(iterate_items({'a': 1}))\n        [('a', 1)]\n        >>> list(iterate_items([('a', 1), ('b', 2)]))\n        [('a', 1), ('b', 2)]\n    \"\"\"\n    if hasattr(dictish, 'iteritems'):\n        return dictish.iteritems()\n    if hasattr(dictish, 'items'):\n        return dictish.items()\n    return dictish", "title": ""}
{"_id": "d17703", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d17704", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d17705", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d17706", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17707", "text": "def get_now_sql_datetime():\n    \"\"\"\n    *A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``*\n\n    **Return:**\n        - ``now`` -- current time and date in MySQL format\n\n    **Usage:**\n        .. code-block:: python \n\n            from fundamentals import times\n            now = times.get_now_sql_datetime()\n            print now\n\n            # OUT: 2016-03-18T11:08:23 \n    \"\"\"\n    ## > IMPORTS ##\n    from datetime import datetime, date, time\n    now = datetime.now()\n    now = now.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\n    return now", "title": ""}
{"_id": "d17708", "text": "def export_to_dot(self, filename: str = 'output') -> None:\n        \"\"\" Export the graph to the dot file \"filename.dot\". \"\"\"\n        with open(filename + '.dot', 'w') as output:\n            output.write(self.as_dot())", "title": ""}
{"_id": "d17709", "text": "def read_flat(self):\n        \"\"\"\n        Read a PNG file and decode it into flat row flat pixel format.\n\n        Returns (*width*, *height*, *pixels*, *metadata*).\n\n        May use excessive memory.\n\n        `pixels` are returned in flat row flat pixel format.\n\n        See also the :meth:`read` method which returns pixels in the\n        more stream-friendly boxed row flat pixel format.\n        \"\"\"\n        x, y, pixel, meta = self.read()\n        arraycode = 'BH'[meta['bitdepth'] > 8]\n        pixel = array(arraycode, itertools.chain(*pixel))\n        return x, y, pixel, meta", "title": ""}
{"_id": "d17710", "text": "def to_iso_string(self) -> str:\n        \"\"\" Returns full ISO string for the given date \"\"\"\n        assert isinstance(self.value, datetime)\n        return datetime.isoformat(self.value)", "title": ""}
{"_id": "d17711", "text": "def from_iso_time(timestring, use_dateutil=True):\n    \"\"\"Parse an ISO8601-formatted datetime string and return a datetime.time\n    object.\n    \"\"\"\n    if not _iso8601_time_re.match(timestring):\n        raise ValueError('Not a valid ISO8601-formatted time string')\n    if dateutil_available and use_dateutil:\n        return parser.parse(timestring).time()\n    else:\n        if len(timestring) > 8:  # has microseconds\n            fmt = '%H:%M:%S.%f'\n        else:\n            fmt = '%H:%M:%S'\n        return datetime.datetime.strptime(timestring, fmt).time()", "title": ""}
{"_id": "d17712", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d17713", "text": "def decodebytes(input):\n    \"\"\"Decode base64 string to byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _decodebytes_py3(input)\n    return _decodebytes_py2(input)", "title": ""}
{"_id": "d17714", "text": "def fix_title_capitalization(title):\n    \"\"\"Try to capitalize properly a title string.\"\"\"\n    if re.search(\"[A-Z]\", title) and re.search(\"[a-z]\", title):\n        return title\n    word_list = re.split(' +', title)\n    final = [word_list[0].capitalize()]\n    for word in word_list[1:]:\n        if word.upper() in COMMON_ACRONYMS:\n            final.append(word.upper())\n        elif len(word) > 3:\n            final.append(word.capitalize())\n        else:\n            final.append(word.lower())\n    return \" \".join(final)", "title": ""}
{"_id": "d17715", "text": "def argsort_k_smallest(x, k):\n    \"\"\" Return no more than ``k`` indices of smallest values. \"\"\"\n    if k == 0:\n        return np.array([], dtype=np.intp)\n    if k is None or k >= len(x):\n        return np.argsort(x)\n    indices = np.argpartition(x, k)[:k]\n    values = x[indices]\n    return indices[np.argsort(values)]", "title": ""}
{"_id": "d17716", "text": "def area (self):\n    \"\"\"area() -> number\n\n    Returns the area of this Polygon.\n    \"\"\"\n    area = 0.0\n    \n    for segment in self.segments():\n      area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2\n\n    return area", "title": ""}
{"_id": "d17717", "text": "def PrintIndented(self, file, ident, code):\n        \"\"\"Takes an array, add indentation to each entry and prints it.\"\"\"\n        for entry in code:\n            print >>file, '%s%s' % (ident, entry)", "title": ""}
{"_id": "d17718", "text": "def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:\n        \"\"\"Get elements in this document which matches condition.\"\"\"\n        return getElementsBy(self, cond)", "title": ""}
{"_id": "d17719", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d17720", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d17721", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d17722", "text": "def uuid2buid(value):\n    \"\"\"\n    Convert a UUID object to a 22-char BUID string\n\n    >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089')\n    >>> uuid2buid(u)\n    'MyA90vLvQi-usAWNb19wiQ'\n    \"\"\"\n    if six.PY3:  # pragma: no cover\n        return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=')\n    else:\n        return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))", "title": ""}
{"_id": "d17723", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d17724", "text": "def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\"\n    Args:\n        x: iterable of strings\n\n    Yields:\n        each string in lower case\n    \"\"\"\n    for string in x:\n        yield string.lower()", "title": ""}
{"_id": "d17725", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d17726", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d17727", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d17728", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d17729", "text": "def replace(s, old, new, maxreplace=-1):\n    \"\"\"replace (str, old, new[, maxreplace]) -> string\n\n    Return a copy of string str with all occurrences of substring\n    old replaced by new. If the optional argument maxreplace is\n    given, only the first maxreplace occurrences are replaced.\n\n    \"\"\"\n    return s.replace(old, new, maxreplace)", "title": ""}
{"_id": "d17730", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17731", "text": "def _prm_get_longest_stringsize(string_list):\n        \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n        maxlength = 1\n\n        for stringar in string_list:\n            if isinstance(stringar, np.ndarray):\n                if stringar.ndim > 0:\n                    for string in stringar.ravel():\n                        maxlength = max(len(string), maxlength)\n                else:\n                    maxlength = max(len(stringar.tolist()), maxlength)\n            else:\n                maxlength = max(len(stringar), maxlength)\n\n        # Make the string Col longer than needed in order to allow later on slightly larger strings\n        return int(maxlength * 1.5)", "title": ""}
{"_id": "d17732", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d17733", "text": "def list_depth(list_, func=max, _depth=0):\n    \"\"\"\n    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)\n\n    \"\"\"\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", "title": ""}
{"_id": "d17734", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d17735", "text": "def get_longest_line_length(text):\n    \"\"\"Get the length longest line in a paragraph\"\"\"\n    lines = text.split(\"\\n\")\n    length = 0\n\n    for i in range(len(lines)):\n        if len(lines[i]) > length:\n            length = len(lines[i])\n\n    return length", "title": ""}
{"_id": "d17736", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17737", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d17738", "text": "def constant(times: np.ndarray, amp: complex) -> np.ndarray:\n    \"\"\"Continuous constant pulse.\n\n    Args:\n        times: Times to output pulse for.\n        amp: Complex pulse amplitude.\n    \"\"\"\n    return np.full(len(times), amp, dtype=np.complex_)", "title": ""}
{"_id": "d17739", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d17740", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d17741", "text": "def sort_by_modified(files_or_folders: list) -> list:\n    \"\"\"\n    Sort files or folders by modified time\n\n    Args:\n        files_or_folders: list of files or folders\n\n    Returns:\n        list\n    \"\"\"\n    return sorted(files_or_folders, key=os.path.getmtime, reverse=True)", "title": ""}
{"_id": "d17742", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17743", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17744", "text": "def indices_to_labels(self, indices: Sequence[int]) -> List[str]:\n        \"\"\" Converts a sequence of indices into their corresponding labels.\"\"\"\n\n        return [(self.INDEX_TO_LABEL[index]) for index in indices]", "title": ""}
{"_id": "d17745", "text": "def strip_codes(s: Any) -> str:\n    \"\"\" Strip all color codes from a string.\n        Returns empty string for \"falsey\" inputs.\n    \"\"\"\n    return codepat.sub('', str(s) if (s or (s == 0)) else '')", "title": ""}
{"_id": "d17746", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d17747", "text": "def to_jupyter(graph: BELGraph, chart: Optional[str] = None) -> Javascript:\n    \"\"\"Render the graph as JavaScript in a Jupyter Notebook.\"\"\"\n    with open(os.path.join(HERE, 'render_with_javascript.js'), 'rt') as f:\n        js_template = Template(f.read())\n\n    return Javascript(js_template.render(**_get_context(graph, chart=chart)))", "title": ""}
{"_id": "d17748", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17749", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d17750", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d17751", "text": "def negate_mask(mask):\n    \"\"\"Returns the negated mask.\n\n    If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where\n    the original one has non-zero (0).\n\n    :param mask: Input mask\n    :type mask: np.array\n    :return: array of same shape and dtype=int8 as input array\n    :rtype: np.array\n    \"\"\"\n    res = np.ones(mask.shape, dtype=np.int8)\n    res[mask > 0] = 0\n\n    return res", "title": ""}
{"_id": "d17752", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d17753", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17754", "text": "def local_machine_uuid():\n    \"\"\"Return local machine unique identifier.\n\n    >>> uuid = local_machine_uuid()\n\n    \"\"\"\n\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\n    return uuid.UUID(hex=result)", "title": ""}
{"_id": "d17755", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d17756", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d17757", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d17758", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d17759", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d17760", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d17761", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d17762", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17763", "text": "def execute(cur, *args):\n    \"\"\"Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)\n    \"\"\"\n    stmt = args[0]\n    if len(args) > 1:\n        stmt = stmt.replace('%', '%%').replace('?', '%r')\n        print(stmt % (args[1]))\n    return cur.execute(*args)", "title": ""}
{"_id": "d17764", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d17765", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d17766", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17767", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d17768", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d17769", "text": "def normcdf(x, log=False):\n    \"\"\"Normal cumulative density function.\"\"\"\n    y = np.atleast_1d(x).copy()\n    flib.normcdf(y)\n    if log:\n        if (y>0).all():\n            return np.log(y)\n        return -np.inf\n    return y", "title": ""}
{"_id": "d17770", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17771", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17772", "text": "def is_orthogonal(\n        matrix: np.ndarray,\n        *,\n        rtol: float = 1e-5,\n        atol: float = 1e-8) -> bool:\n    \"\"\"Determines if a matrix is approximately orthogonal.\n\n    A matrix is orthogonal if it's square and real and its transpose is its\n    inverse.\n\n    Args:\n        matrix: The matrix to check.\n        rtol: The per-matrix-entry relative tolerance on equality.\n        atol: The per-matrix-entry absolute tolerance on equality.\n\n    Returns:\n        Whether the matrix is orthogonal within the given tolerance.\n    \"\"\"\n    return (matrix.shape[0] == matrix.shape[1] and\n            np.all(np.imag(matrix) == 0) and\n            np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]),\n                        rtol=rtol,\n                        atol=atol))", "title": ""}
{"_id": "d17773", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d17774", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d17775", "text": "def _brief_print_list(lst, limit=7):\n    \"\"\"Print at most `limit` elements of list.\"\"\"\n    lst = list(lst)\n    if len(lst) > limit:\n        return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n            _brief_print_list(lst[-limit//2:], limit)\n    return ', '.join([\"'%s'\"%str(i) for i in lst])", "title": ""}
{"_id": "d17776", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d17777", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d17778", "text": "def get_value(self) -> Decimal:\n        \"\"\" Returns the current value of stocks \"\"\"\n        quantity = self.get_quantity()\n        price = self.get_last_available_price()\n        if not price:\n            # raise ValueError(\"no price found for\", self.full_symbol)\n            return Decimal(0)\n\n        value = quantity * price.value\n        return value", "title": ""}
{"_id": "d17779", "text": "def setup_cache(app: Flask, cache_config) -> Optional[Cache]:\n    \"\"\"Setup the flask-cache on a flask app\"\"\"\n    if cache_config and cache_config.get('CACHE_TYPE') != 'null':\n        return Cache(app, config=cache_config)\n\n    return None", "title": ""}
{"_id": "d17780", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17781", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17782", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d17783", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d17784", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17785", "text": "def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool:\n    \"\"\"Return true if given node is inside lambda\"\"\"\n    parent = node.parent\n    while parent is not None:\n        if isinstance(parent, astroid.Lambda):\n            return True\n        parent = parent.parent\n    return False", "title": ""}
{"_id": "d17786", "text": "def stdout_encode(u, default='utf-8'):\n    \"\"\" Encodes a given string with the proper standard out encoding\n        If sys.stdout.encoding isn't specified, it this defaults to @default\n\n        @default: default encoding\n\n        -> #str with standard out encoding\n    \"\"\"\n    # from http://stackoverflow.com/questions/3627793/best-output-type-and-\n    #   encoding-practices-for-repr-functions\n    encoding = sys.stdout.encoding or default\n    return u.encode(encoding, \"replace\").decode(encoding, \"replace\")", "title": ""}
{"_id": "d17787", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d17788", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d17789", "text": "def _prm_get_longest_stringsize(string_list):\n        \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n        maxlength = 1\n\n        for stringar in string_list:\n            if isinstance(stringar, np.ndarray):\n                if stringar.ndim > 0:\n                    for string in stringar.ravel():\n                        maxlength = max(len(string), maxlength)\n                else:\n                    maxlength = max(len(stringar.tolist()), maxlength)\n            else:\n                maxlength = max(len(stringar), maxlength)\n\n        # Make the string Col longer than needed in order to allow later on slightly larger strings\n        return int(maxlength * 1.5)", "title": ""}
{"_id": "d17790", "text": "def multiple_replace(string, replacements):\n    # type: (str, Dict[str,str]) -> str\n    \"\"\"Simultaneously replace multiple strigns in a string\n\n    Args:\n        string (str): Input string\n        replacements (Dict[str,str]): Replacements dictionary\n\n    Returns:\n        str: String with replacements\n\n    \"\"\"\n    pattern = re.compile(\"|\".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL)\n    return pattern.sub(lambda x: replacements[x.group(0)], string)", "title": ""}
{"_id": "d17791", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d17792", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d17793", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d17794", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d17795", "text": "def remove_parenthesis_around_tz(cls, timestr):\n        \"\"\"get rid of parenthesis around timezone: (GMT) => GMT\n\n        :return: the new string if parenthesis were found, `None` otherwise\n        \"\"\"\n        parenthesis = cls.TIMEZONE_PARENTHESIS.match(timestr)\n        if parenthesis is not None:\n            return parenthesis.group(1)", "title": ""}
{"_id": "d17796", "text": "def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity.\"\"\"\n    a, b = set(x), set(y)\n    union = a | b\n\n    if not union:\n        return 0.0\n\n    return len(a & b) / len(union)", "title": ""}
{"_id": "d17797", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d17798", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d17799", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d17800", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d17801", "text": "def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:\n        \"\"\" Return a json array as a list\n\n        :param value: array\n        :return: array with JsonObj instances removed\n        \"\"\"\n        return [e._as_dict if isinstance(e, JsonObj) else e for e in value]", "title": ""}
{"_id": "d17802", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d17803", "text": "def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:\n    \"\"\"\n    Test if two objects are equal, based on a comparison of the specified\n    attributes ``attrs``.\n    \"\"\"\n    return all(getattr(one, a) == getattr(two, a) for a in attrs)", "title": ""}
{"_id": "d17804", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d17805", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d17806", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d17807", "text": "def __repr__(self) -> str:\n        \"\"\"Return the string representation of self.\"\"\"\n        return '{0}({1})'.format(type(self).__name__, repr(self.string))", "title": ""}
{"_id": "d17808", "text": "def _reshuffle(mat, shape):\n    \"\"\"Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].\"\"\"\n    return np.reshape(\n        np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),\n        (shape[3] * shape[1], shape[0] * shape[2]))", "title": ""}
{"_id": "d17809", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d17810", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d17811", "text": "def is_quoted(arg: str) -> bool:\n    \"\"\"\n    Checks if a string is quoted\n    :param arg: the string being checked for quotes\n    :return: True if a string is quoted\n    \"\"\"\n    return len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES", "title": ""}
{"_id": "d17812", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d17813", "text": "def quoted_or_list(items: List[str]) -> Optional[str]:\n    \"\"\"Given [A, B, C] return \"'A', 'B', or 'C'\".\n\n    Note: We use single quotes here, since these are also used by repr().\n    \"\"\"\n    return or_list([f\"'{item}'\" for item in items])", "title": ""}
{"_id": "d17814", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d17815", "text": "def first_digits(s, default=0):\n    \"\"\"Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-).\n    >>> first_digits('+123.456')\n    123\n    \"\"\"\n    s = re.split(r'[^0-9]+', str(s).strip().lstrip('+-' + charlist.whitespace))\n    if len(s) and len(s[0]):\n        return int(s[0])\n    return default", "title": ""}
{"_id": "d17816", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d17817", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17818", "text": "def run_time() -> timedelta:\n    \"\"\"\n\n    :return:\n    \"\"\"\n\n    delta = start_time if start_time else datetime.utcnow()\n    return datetime.utcnow() - delta", "title": ""}
{"_id": "d17819", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d17820", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d17821", "text": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "title": ""}
{"_id": "d17822", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d17823", "text": "def to_np(*args):\n    \"\"\" convert GPU arras to numpy and return them\"\"\"\n    if len(args) > 1:\n        return (cp.asnumpy(x) for x in args)\n    else:\n        return cp.asnumpy(args[0])", "title": ""}
{"_id": "d17824", "text": "def count(self, elem):\n        \"\"\"\n        Return the number of elements equal to elem present in the queue\n\n        >>> pdeque([1, 2, 1]).count(1)\n        2\n        \"\"\"\n        return self._left_list.count(elem) + self._right_list.count(elem)", "title": ""}
{"_id": "d17825", "text": "def _RetryRequest(self, timeout=None, **request_args):\n    \"\"\"Retry the request a few times before we determine it failed.\n\n    Sometimes the frontend becomes loaded and issues a 500 error to throttle the\n    clients. We wait Client.error_poll_min seconds between each attempt to back\n    off the frontend. Note that this does not affect any timing algorithm in the\n    client itself which is controlled by the Timer() class.\n\n    Args:\n      timeout: Timeout for retry.\n      **request_args: Args to the requests.request call.\n\n    Returns:\n      a tuple of duration, urllib.request.urlopen response.\n    \"\"\"\n    while True:\n      try:\n        now = time.time()\n        if not timeout:\n          timeout = config.CONFIG[\"Client.http_timeout\"]\n\n        result = requests.request(**request_args)\n        # By default requests doesn't raise on HTTP error codes.\n        result.raise_for_status()\n\n        # Requests does not always raise an exception when an incorrect response\n        # is received. This fixes that behaviour.\n        if not result.ok:\n          raise requests.RequestException(response=result)\n\n        return time.time() - now, result\n\n      # Catch any exceptions that dont have a code (e.g. socket.error).\n      except IOError as e:\n        self.consecutive_connection_errors += 1\n        # Request failed. If we connected successfully before we attempt a few\n        # connections before we determine that it really failed. This might\n        # happen if the front end is loaded and returns a few throttling 500\n        # messages.\n        if self.active_base_url is not None:\n          # Propagate 406 immediately without retrying, as 406 is a valid\n          # response that indicates a need for enrollment.\n          response = getattr(e, \"response\", None)\n          if getattr(response, \"status_code\", None) == 406:\n            raise\n\n          if self.consecutive_connection_errors >= self.retry_error_limit:\n            # We tried several times but this really did not work, just fail it.\n            logging.info(\n                \"Too many connection errors to %s, retrying another URL\",\n                self.active_base_url)\n            self.active_base_url = None\n            raise e\n\n          # Back off hard to allow the front end to recover.\n          logging.debug(\n              \"Unable to connect to frontend. Backing off %s seconds.\",\n              self.error_poll_min)\n          self.Wait(self.error_poll_min)\n\n        # We never previously connected, maybe the URL/proxy is wrong? Just fail\n        # right away to allow callers to try a different URL.\n        else:\n          raise e", "title": ""}
{"_id": "d17826", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d17827", "text": "def enum_mark_last(iterable, start=0):\n    \"\"\"\n    Returns a generator over iterable that tells whether the current item is the last one.\n    Usage:\n        >>> iterable = range(10)\n        >>> for index, is_last, item in enum_mark_last(iterable):\n        >>>     print(index, item, end='\\n' if is_last else ', ')\n    \"\"\"\n    it = iter(iterable)\n    count = start\n    try:\n        last = next(it)\n    except StopIteration:\n        return\n    for val in it:\n        yield count, False, last\n        last = val\n        count += 1\n    yield count, True, last", "title": ""}
{"_id": "d17828", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d17829", "text": "def memory_usage():\n    \"\"\"return memory usage of python process in MB\n\n    from\n    http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/\n    psutil is quicker\n\n    >>> isinstance(memory_usage(),float)\n    True\n\n    \"\"\"\n    try:\n        import psutil\n        import os\n    except ImportError:\n        return _memory_usage_ps()\n\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info()[0] / float(2 ** 20)\n    return mem", "title": ""}
{"_id": "d17830", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d17831", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d17832", "text": "def duration_expired(start_time, duration_seconds):\n    \"\"\"\n    Return True if ``duration_seconds`` have expired since ``start_time``\n    \"\"\"\n\n    if duration_seconds is not None:\n        delta_seconds = datetime_delta_to_seconds(dt.datetime.now() - start_time)\n\n        if delta_seconds >= duration_seconds:\n            return True\n\n    return False", "title": ""}
{"_id": "d17833", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17834", "text": "def get_valid_filename(s):\n    \"\"\"\n    Shamelessly taken from Django.\n    https://github.com/django/django/blob/master/django/utils/text.py\n\n    Return the given string converted to a string that can be used for a clean\n    filename. Remove leading and trailing spaces; convert other spaces to\n    underscores; and remove anything that is not an alphanumeric, dash,\n    underscore, or dot.\n    >>> get_valid_filename(\"john's portrait in 2004.jpg\")\n    'johns_portrait_in_2004.jpg'\n    \"\"\"\n    s = str(s).strip().replace(' ', '_')\n    return re.sub(r'(?u)[^-\\w.]', '', s)", "title": ""}
{"_id": "d17835", "text": "async def enter_captcha(self, url: str, sid: str) -> str:\n        \"\"\"\n        Override this method for processing captcha.\n\n        :param url: link to captcha image\n        :param sid: captcha id. I do not know why pass here but may be useful\n        :return captcha value\n        \"\"\"\n        raise VkCaptchaNeeded(url, sid)", "title": ""}
{"_id": "d17836", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d17837", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d17838", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d17839", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d17840", "text": "def wait_for_shutdown_signal(\n        self,\n        please_stop=False,  # ASSIGN SIGNAL TO STOP EARLY\n        allow_exit=False,  # ALLOW \"exit\" COMMAND ON CONSOLE TO ALSO STOP THE APP\n        wait_forever=True  # IGNORE CHILD THREADS, NEVER EXIT.  False => IF NO CHILD THREADS LEFT, THEN EXIT\n    ):\n        \"\"\"\n        FOR USE BY PROCESSES THAT NEVER DIE UNLESS EXTERNAL SHUTDOWN IS REQUESTED\n\n        CALLING THREAD WILL SLEEP UNTIL keyboard interrupt, OR please_stop, OR \"exit\"\n\n        :param please_stop:\n        :param allow_exit:\n        :param wait_forever:: Assume all needed threads have been launched. When done\n        :return:\n        \"\"\"\n        self_thread = Thread.current()\n        if self_thread != MAIN_THREAD or self_thread != self:\n            Log.error(\"Only the main thread can sleep forever (waiting for KeyboardInterrupt)\")\n\n        if isinstance(please_stop, Signal):\n            # MUTUAL SIGNALING MAKES THESE TWO EFFECTIVELY THE SAME SIGNAL\n            self.please_stop.on_go(please_stop.go)\n            please_stop.on_go(self.please_stop.go)\n        else:\n            please_stop = self.please_stop\n\n        if not wait_forever:\n            # TRIGGER SIGNAL WHEN ALL CHILDREN THEADS ARE DONE\n            with self_thread.child_lock:\n                pending = copy(self_thread.children)\n            children_done = AndSignals(please_stop, len(pending))\n            children_done.signal.on_go(self.please_stop.go)\n            for p in pending:\n                p.stopped.on_go(children_done.done)\n\n        try:\n            if allow_exit:\n                _wait_for_exit(please_stop)\n            else:\n                _wait_for_interrupt(please_stop)\n        except KeyboardInterrupt as _:\n            Log.alert(\"SIGINT Detected!  Stopping...\")\n        except SystemExit as _:\n            Log.alert(\"SIGTERM Detected!  Stopping...\")\n        finally:\n            self.stop()", "title": ""}
{"_id": "d17841", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d17842", "text": "def decode(self, bytes, raw=False):\n        \"\"\"decode(bytearray, raw=False) -> value\n\n        Decodes the given bytearray according to this PrimitiveType\n        definition.\n\n        NOTE: The parameter ``raw`` is present to adhere to the\n        ``decode()`` inteface, but has no effect for PrimitiveType\n        definitions.\n        \"\"\"\n        return struct.unpack(self.format, buffer(bytes))[0]", "title": ""}
{"_id": "d17843", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d17844", "text": "def non_increasing(values):\n    \"\"\"True if values are not increasing.\"\"\"\n    return all(x >= y for x, y in zip(values, values[1:]))", "title": ""}
{"_id": "d17845", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d17846", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d17847", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d17848", "text": "def strids2ids(tokens: Iterable[str]) -> List[int]:\n    \"\"\"\n    Returns sequence of integer ids given a sequence of string ids.\n\n    :param tokens: List of integer tokens.\n    :return: List of word ids.\n    \"\"\"\n    return list(map(int, tokens))", "title": ""}
{"_id": "d17849", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17850", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d17851", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d17852", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d17853", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17854", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d17855", "text": "def to_dict(self):\n        \"\"\"\n\n        Returns: the tree item as a dictionary\n\n        \"\"\"\n        if self.childCount() > 0:\n            value = {}\n            for index in range(self.childCount()):\n                value.update(self.child(index).to_dict())\n        else:\n            value = self.value\n\n        return {self.name: value}", "title": ""}
{"_id": "d17856", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17857", "text": "def same_network(atree, btree) -> bool:\n    \"\"\"True if given trees share the same structure of powernodes,\n    independently of (power)node names,\n    and same edge topology between (power)nodes.\n\n    \"\"\"\n    return same_hierarchy(atree, btree) and same_topology(atree, btree)", "title": ""}
{"_id": "d17858", "text": "def iterate_items(dictish):\n    \"\"\" Return a consistent (key, value) iterable on dict-like objects,\n    including lists of tuple pairs.\n\n    Example:\n\n        >>> list(iterate_items({'a': 1}))\n        [('a', 1)]\n        >>> list(iterate_items([('a', 1), ('b', 2)]))\n        [('a', 1), ('b', 2)]\n    \"\"\"\n    if hasattr(dictish, 'iteritems'):\n        return dictish.iteritems()\n    if hasattr(dictish, 'items'):\n        return dictish.items()\n    return dictish", "title": ""}
{"_id": "d17859", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d17860", "text": "def _create_empty_array(self, frames, always_2d, dtype):\n        \"\"\"Create an empty array with appropriate shape.\"\"\"\n        import numpy as np\n        if always_2d or self.channels > 1:\n            shape = frames, self.channels\n        else:\n            shape = frames,\n        return np.empty(shape, dtype, order='C')", "title": ""}
{"_id": "d17861", "text": "def python_utc_datetime_to_sqlite_strftime_string(\n        value: datetime.datetime) -> str:\n    \"\"\"\n    Converts a Python datetime to a string literal compatible with SQLite,\n    including the millisecond field.\n    \"\"\"\n    millisec_str = str(round(value.microsecond / 1000)).zfill(3)\n    return value.strftime(\"%Y-%m-%d %H:%M:%S\") + \".\" + millisec_str", "title": ""}
{"_id": "d17862", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d17863", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d17864", "text": "def drop_post(self):\n        \"\"\"Remove .postXXXX postfix from version\"\"\"\n        post_index = self.version.find('.post')\n        if post_index >= 0:\n            self.version = self.version[:post_index]", "title": ""}
{"_id": "d17865", "text": "def safe_pow(base, exp):\n    \"\"\"safe version of pow\"\"\"\n    if exp > MAX_EXPONENT:\n        raise RuntimeError(\"Invalid exponent, max exponent is {}\".format(MAX_EXPONENT))\n    return base ** exp", "title": ""}
{"_id": "d17866", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d17867", "text": "def callable_validator(v: Any) -> AnyCallable:\n    \"\"\"\n    Perform a simple check if the value is callable.\n\n    Note: complete matching of argument type hints and return types is not performed\n    \"\"\"\n    if callable(v):\n        return v\n\n    raise errors.CallableError(value=v)", "title": ""}
{"_id": "d17868", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d17869", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d17870", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d17871", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d17872", "text": "def mkdir(self, target_folder):\n        \"\"\"\n        Create a folder on S3.\n\n        Examples\n        --------\n            >>> s3utils.mkdir(\"path/to/my_folder\")\n            Making directory: path/to/my_folder\n        \"\"\"\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()", "title": ""}
{"_id": "d17873", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d17874", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d17875", "text": "def remove_prefix(text, prefix):\n\t\"\"\"\n\tRemove 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'\n\t\"\"\"\n\tnull, prefix, rest = text.rpartition(prefix)\n\treturn rest", "title": ""}
{"_id": "d17876", "text": "def local_machine_uuid():\n    \"\"\"Return local machine unique identifier.\n\n    >>> uuid = local_machine_uuid()\n\n    \"\"\"\n\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\n    return uuid.UUID(hex=result)", "title": ""}
{"_id": "d17877", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17878", "text": "def process_literal_param(self, value: Optional[List[int]],\n                              dialect: Dialect) -> str:\n        \"\"\"Convert things on the way from Python to the database.\"\"\"\n        retval = self._intlist_to_dbstr(value)\n        return retval", "title": ""}
{"_id": "d17879", "text": "def find_first(pattern: str, path: str) -> str:\n    \"\"\"\n    Finds first file in ``path`` whose filename matches ``pattern`` (via\n    :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`.\n    \"\"\"\n    try:\n        return find(pattern, path)[0]\n    except IndexError:\n        log.critical('''Couldn't find \"{}\" in \"{}\"''', pattern, path)\n        raise", "title": ""}
{"_id": "d17880", "text": "def is_any_type_set(sett: Set[Type]) -> bool:\n    \"\"\"\n    Helper method to check if a set of types is the {AnyObject} singleton\n\n    :param sett:\n    :return:\n    \"\"\"\n    return len(sett) == 1 and is_any_type(min(sett))", "title": ""}
{"_id": "d17881", "text": "def _short_repr(obj):\n  \"\"\"Helper function returns a truncated repr() of an object.\"\"\"\n  stringified = pprint.saferepr(obj)\n  if len(stringified) > 200:\n    return '%s... (%d bytes)' % (stringified[:200], len(stringified))\n  return stringified", "title": ""}
{"_id": "d17882", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d17883", "text": "def convert_bytes_to_ints(in_bytes, num):\n    \"\"\"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\"\"\"\n    dt = numpy.dtype('>i' + str(num))\n    return numpy.frombuffer(in_bytes, dt)", "title": ""}
{"_id": "d17884", "text": "def _create_empty_array(self, frames, always_2d, dtype):\n        \"\"\"Create an empty array with appropriate shape.\"\"\"\n        import numpy as np\n        if always_2d or self.channels > 1:\n            shape = frames, self.channels\n        else:\n            shape = frames,\n        return np.empty(shape, dtype, order='C')", "title": ""}
{"_id": "d17885", "text": "def union(cls, *sets):\n        \"\"\"\n        >>> from utool.util_set import *  # NOQA\n        \"\"\"\n        import utool as ut\n        lists_ = ut.flatten([list(s) for s in sets])\n        return cls(lists_)", "title": ""}
{"_id": "d17886", "text": "def _cleanup(path: str) -> None:\n    \"\"\"Cleanup temporary directory.\"\"\"\n    if os.path.isdir(path):\n        shutil.rmtree(path)", "title": ""}
{"_id": "d17887", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d17888", "text": "def __rmatmul__(self, other):\n        \"\"\"\n        Matrix multiplication using binary `@` operator in Python>=3.5.\n        \"\"\"\n        return self.T.dot(np.transpose(other)).T", "title": ""}
{"_id": "d17889", "text": "def running_containers(name_filter: str) -> List[str]:\n    \"\"\"\n    :raises docker.exceptions.APIError\n    \"\"\"\n    return [container.short_id for container in\n            docker_client.containers.list(filters={\"name\": name_filter})]", "title": ""}
{"_id": "d17890", "text": "def file_lines(bblfile:str) -> iter:\n    \"\"\"Yield lines found in given file\"\"\"\n    with open(bblfile) as fd:\n        yield from (line.rstrip() for line in fd if line.rstrip())", "title": ""}
{"_id": "d17891", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d17892", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d17893", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d17894", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d17895", "text": "def valid_substitution(strlen, index):\n    \"\"\"\n    skip performing substitutions that are outside the bounds of the string\n    \"\"\"\n    values = index[0]\n    return all([strlen > i for i in values])", "title": ""}
{"_id": "d17896", "text": "def recall_score(y_true, y_pred, average='micro', suffix=False):\n    \"\"\"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\n    \"\"\"\n    true_entities = set(get_entities(y_true, suffix))\n    pred_entities = set(get_entities(y_pred, suffix))\n\n    nb_correct = len(true_entities & pred_entities)\n    nb_true = len(true_entities)\n\n    score = nb_correct / nb_true if nb_true > 0 else 0\n\n    return score", "title": ""}
{"_id": "d17897", "text": "def default_parser() -> argparse.ArgumentParser:\n    \"\"\"Create a parser for CLI arguments and options.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=CONSOLE_SCRIPT,\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n    )\n    build_parser(parser)\n    return parser", "title": ""}
{"_id": "d17898", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d17899", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d17900", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d17901", "text": "def callable_validator(v: Any) -> AnyCallable:\n    \"\"\"\n    Perform a simple check if the value is callable.\n\n    Note: complete matching of argument type hints and return types is not performed\n    \"\"\"\n    if callable(v):\n        return v\n\n    raise errors.CallableError(value=v)", "title": ""}
{"_id": "d17902", "text": "def _find_conda():\n    \"\"\"Find the conda executable robustly across conda versions.\n\n    Returns\n    -------\n    conda : str\n        Path to the conda executable.\n\n    Raises\n    ------\n    IOError\n        If the executable cannot be found in either the CONDA_EXE environment\n        variable or in the PATH.\n\n    Notes\n    -----\n    In POSIX platforms in conda >= 4.4, conda can be set up as a bash function\n    rather than an executable. (This is to enable the syntax\n    ``conda activate env-name``.) In this case, the environment variable\n    ``CONDA_EXE`` contains the path to the conda executable. In other cases,\n    we use standard search for the appropriate name in the PATH.\n\n    See https://github.com/airspeed-velocity/asv/issues/645 for more details.\n    \"\"\"\n    if 'CONDA_EXE' in os.environ:\n        conda = os.environ['CONDA_EXE']\n    else:\n        conda = util.which('conda')\n    return conda", "title": ""}
{"_id": "d17903", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d17904", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d17905", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d17906", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d17907", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d17908", "text": "def cpu_count() -> int:\n    \"\"\"Returns the number of processors on this machine.\"\"\"\n    if multiprocessing is None:\n        return 1\n    try:\n        return multiprocessing.cpu_count()\n    except NotImplementedError:\n        pass\n    try:\n        return os.sysconf(\"SC_NPROCESSORS_CONF\")\n    except (AttributeError, ValueError):\n        pass\n    gen_log.error(\"Could not detect number of processors; assuming 1\")\n    return 1", "title": ""}
{"_id": "d17909", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17910", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d17911", "text": "def add_mark_at(string, index, mark):\n    \"\"\"\n    Add mark to the index-th character of the given string. Return the new string after applying change.\n    Notice: index > 0\n    \"\"\"\n    if index == -1:\n        return string\n    # Python can handle the case which index is out of range of given string\n    return string[:index] + add_mark_char(string[index], mark) + string[index+1:]", "title": ""}
{"_id": "d17912", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d17913", "text": "def is_up_to_date(outfile, basedatetime):\n        # type: (AnyStr, datetime) -> bool\n        \"\"\"Return true if outfile exists and is no older than base datetime.\"\"\"\n        if os.path.exists(outfile):\n            if os.path.getmtime(outfile) >= basedatetime:\n                return True\n        return False", "title": ""}
{"_id": "d17914", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d17915", "text": "def first_location_of_maximum(x):\n    \"\"\"\n    Returns the first location of the maximum 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\n    \"\"\"\n    if not isinstance(x, (np.ndarray, pd.Series)):\n        x = np.asarray(x)\n    return np.argmax(x) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d17916", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d17917", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d17918", "text": "def camel_to_snake_case(string):\n    \"\"\"Converts 'string' presented in camel case to snake case.\n\n    e.g.: CamelCase => snake_case\n    \"\"\"\n    s = _1.sub(r'\\1_\\2', string)\n    return _2.sub(r'\\1_\\2', s).lower()", "title": ""}
{"_id": "d17919", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d17920", "text": "def bulk_load_docs(es, docs):\n    \"\"\"Bulk load docs\n\n    Args:\n        es: elasticsearch handle\n        docs: Iterator of doc objects - includes index_name\n    \"\"\"\n\n    chunk_size = 200\n\n    try:\n        results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)\n        log.debug(f\"Elasticsearch documents loaded: {results[0]}\")\n\n        # elasticsearch.helpers.parallel_bulk(es, terms, chunk_size=chunk_size, thread_count=4)\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))", "title": ""}
{"_id": "d17921", "text": "def inject_nulls(data: Mapping, field_names) -> dict:\n    \"\"\"Insert None as value for missing fields.\"\"\"\n\n    record = dict()\n\n    for field in field_names:\n        record[field] = data.get(field, None)\n\n    return record", "title": ""}
{"_id": "d17922", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d17923", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d17924", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d17925", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d17926", "text": "def SGT(self, a, b):\n        \"\"\"Signed greater-than comparison\"\"\"\n        # http://gavwood.com/paper.pdf\n        s0, s1 = to_signed(a), to_signed(b)\n        return Operators.ITEBV(256, s0 > s1, 1, 0)", "title": ""}
{"_id": "d17927", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d17928", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d17929", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d17930", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d17931", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d17932", "text": "def after_third_friday(day=None):\n    \"\"\" check if day is after month's 3rd friday \"\"\"\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", "title": ""}
{"_id": "d17933", "text": "def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict:\n        \"\"\"HTTP request method of interface implementation.\"\"\"", "title": ""}
{"_id": "d17934", "text": "def _write_json(obj, path):  # type: (object, str) -> None\n    \"\"\"Writes a serializeable object as a JSON file\"\"\"\n    with open(path, 'w') as f:\n        json.dump(obj, f)", "title": ""}
{"_id": "d17935", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d17936", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d17937", "text": "def argmax(iterable, key=None, both=False):\n    \"\"\"\n    >>> argmax([4,2,-5])\n    0\n    >>> argmax([4,2,-5], key=abs)\n    2\n    >>> argmax([4,2,-5], key=abs, both=True)\n    (2, 5)\n    \"\"\"\n    if key is not None:\n        it = imap(key, iterable)\n    else:\n        it = iter(iterable)\n    score, argmax = reduce(max, izip(it, count()))\n    if both:\n        return argmax, score\n    return argmax", "title": ""}
{"_id": "d17938", "text": "def get_system_flags() -> FrozenSet[Flag]:\n    \"\"\"Return the set of implemented system flags.\"\"\"\n    return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})", "title": ""}
{"_id": "d17939", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d17940", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d17941", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d17942", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17943", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d17944", "text": "def hex_to_int(value):\n    \"\"\"\n    Convert hex string like \"\\x0A\\xE3\" to 2787.\n    \"\"\"\n    if version_info.major >= 3:\n        return int.from_bytes(value, \"big\")\n    return int(value.encode(\"hex\"), 16)", "title": ""}
{"_id": "d17945", "text": "def timestamp_with_tzinfo(dt):\n    \"\"\"\n    Serialize a date/time value into an ISO8601 text representation\n    adjusted (if needed) to UTC timezone.\n\n    For instance:\n    >>> serialize_date(datetime(2012, 4, 10, 22, 38, 20, 604391))\n    '2012-04-10T22:38:20.604391Z'\n    \"\"\"\n    utc = tzutc()\n\n    if dt.tzinfo:\n        dt = dt.astimezone(utc).replace(tzinfo=None)\n    return dt.isoformat() + 'Z'", "title": ""}
{"_id": "d17946", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d17947", "text": "async def fetchall(self) -> Iterable[sqlite3.Row]:\n        \"\"\"Fetch all remaining rows.\"\"\"\n        return await self._execute(self._cursor.fetchall)", "title": ""}
{"_id": "d17948", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d17949", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d17950", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d17951", "text": "def replace_variables(self, source: str, variables: dict) -> str:\n        \"\"\"Replace {{variable-name}} with stored value.\"\"\"\n        try:\n            replaced = re.sub(\n                \"{{(.*?)}}\", lambda m: variables.get(m.group(1), \"\"), source\n            )\n        except TypeError:\n            replaced = source\n        return replaced", "title": ""}
{"_id": "d17952", "text": "def is_empty_shape(sh: ShExJ.Shape) -> bool:\n        \"\"\" Determine whether sh has any value \"\"\"\n        return sh.closed is None and sh.expression is None and sh.extra is None and \\\n            sh.semActs is None", "title": ""}
{"_id": "d17953", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d17954", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d17955", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d17956", "text": "def duplicates(coll):\n    \"\"\"Return the duplicated items in the given collection\n\n    :param coll: a collection\n    :returns: a list of the duplicated items in the collection\n\n    >>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])\n    [1, 3]\n\n    \"\"\"\n    return list(set(x for x in coll if coll.count(x) > 1))", "title": ""}
{"_id": "d17957", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d17958", "text": "def _dfs_cycle_detect(graph, node, path, visited_nodes):\n    \"\"\"\n    search graph for cycle using DFS continuing from node\n    path contains the list of visited nodes currently on the stack\n    visited_nodes is the set of already visited nodes\n    :param graph:\n    :param node:\n    :param path:\n    :param visited_nodes:\n    :return:\n    \"\"\"\n    visited_nodes.add(node)\n    for target in graph[node]:\n        if target in path:\n            # cycle found => return current path\n            return path + [target]\n        else:\n            return _dfs_cycle_detect(graph, target, path + [target], visited_nodes)\n    return None", "title": ""}
{"_id": "d17959", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d17960", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d17961", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d17962", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d17963", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d17964", "text": "def collect_static() -> bool:\n    \"\"\"\n    Runs Django ``collectstatic`` command in silent mode.\n\n    :return: always ``True``\n    \"\"\"\n    from django.core.management import execute_from_command_line\n    # from django.conf import settings\n    # if not os.listdir(settings.STATIC_ROOT):\n    wf('Collecting static files... ', False)\n    execute_from_command_line(['./manage.py', 'collectstatic', '-c', '--noinput', '-v0'])\n    wf('[+]\\n')\n    return True", "title": ""}
{"_id": "d17965", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d17966", "text": "def safe_pow(base, exp):\n    \"\"\"safe version of pow\"\"\"\n    if exp > MAX_EXPONENT:\n        raise RuntimeError(\"Invalid exponent, max exponent is {}\".format(MAX_EXPONENT))\n    return base ** exp", "title": ""}
{"_id": "d17967", "text": "def lsr_pairwise_dense(comp_mat, alpha=0.0, initial_params=None):\n    \"\"\"Compute the LSR estimate of model parameters given dense data.\n\n    This function implements the Luce Spectral Ranking inference algorithm\n    [MG15]_ for 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.lsr_pairwise`, this function is particularly\n    efficient for dense pairwise-comparison datasets (i.e., containing many\n    comparisons for a large fraction of item pairs).\n\n    The argument ``initial_params`` can be used to iteratively refine an\n    existing parameter estimate (see the implementation of\n    :func:`~choix.ilsr_pairwise` for an idea on how this works). If it is set\n    to `None` (the default), the all-ones vector is used.\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 build the transition rates of the LSR Markov chain.\n\n    Returns\n    -------\n    params : np.array\n        An estimate of model parameters.\n    \"\"\"\n    n_items = comp_mat.shape[0]\n    ws, chain = _init_lsr(n_items, alpha, initial_params)\n    denom = np.tile(ws, (n_items, 1))\n    chain += comp_mat.T / (denom + denom.T)\n    chain -= np.diag(chain.sum(axis=1))\n    return log_transform(statdist(chain))", "title": ""}
{"_id": "d17968", "text": "def product(*args, **kwargs):\n    \"\"\" Yields all permutations with replacement:\n        list(product(\"cat\", repeat=2)) => \n        [(\"c\", \"c\"), \n         (\"c\", \"a\"), \n         (\"c\", \"t\"), \n         (\"a\", \"c\"), \n         (\"a\", \"a\"), \n         (\"a\", \"t\"), \n         (\"t\", \"c\"), \n         (\"t\", \"a\"), \n         (\"t\", \"t\")]\n    \"\"\"\n    p = [[]]\n    for iterable in map(tuple, args) * kwargs.get(\"repeat\", 1):\n        p = [x + [y] for x in p for y in iterable]\n    for p in p:\n        yield tuple(p)", "title": ""}
{"_id": "d17969", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d17970", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d17971", "text": "def _parse_date(string: str) -> datetime.date:\n    \"\"\"Parse an ISO format date (YYYY-mm-dd).\n\n    >>> _parse_date('1990-01-02')\n    datetime.date(1990, 1, 2)\n    \"\"\"\n    return datetime.datetime.strptime(string, '%Y-%m-%d').date()", "title": ""}
{"_id": "d17972", "text": "def read_flat(self):\n        \"\"\"\n        Read a PNG file and decode it into flat row flat pixel format.\n\n        Returns (*width*, *height*, *pixels*, *metadata*).\n\n        May use excessive memory.\n\n        `pixels` are returned in flat row flat pixel format.\n\n        See also the :meth:`read` method which returns pixels in the\n        more stream-friendly boxed row flat pixel format.\n        \"\"\"\n        x, y, pixel, meta = self.read()\n        arraycode = 'BH'[meta['bitdepth'] > 8]\n        pixel = array(arraycode, itertools.chain(*pixel))\n        return x, y, pixel, meta", "title": ""}
{"_id": "d17973", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d17974", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d17975", "text": "def import_by_path(path: str) -> Callable:\n    \"\"\"Import a class or function given it's absolute path.\n\n    Parameters\n    ----------\n    path:\n      Path to object to import\n    \"\"\"\n\n    module_path, _, class_name = path.rpartition('.')\n    return getattr(import_module(module_path), class_name)", "title": ""}
{"_id": "d17976", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d17977", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d17978", "text": "def sample_normal(mean, var, rng):\n    \"\"\"Sample from independent normal distributions\n\n    Each element is an independent normal distribution.\n\n    Parameters\n    ----------\n    mean : numpy.ndarray\n      Means of the normal distribution. Shape --> (batch_num, sample_dim)\n    var : numpy.ndarray\n      Variance of the normal distribution. Shape --> (batch_num, sample_dim)\n    rng : numpy.random.RandomState\n\n    Returns\n    -------\n    ret : numpy.ndarray\n       The sampling result. Shape --> (batch_num, sample_dim)\n    \"\"\"\n    ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean\n    return ret", "title": ""}
{"_id": "d17979", "text": "async def cursor(self) -> Cursor:\n        \"\"\"Create an aiosqlite cursor wrapping a sqlite3 cursor object.\"\"\"\n        return Cursor(self, await self._execute(self._conn.cursor))", "title": ""}
{"_id": "d17980", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d17981", "text": "def decodebytes(input):\n    \"\"\"Decode base64 string to byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _decodebytes_py3(input)\n    return _decodebytes_py2(input)", "title": ""}
{"_id": "d17982", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d17983", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d17984", "text": "def ensure_list(iterable: Iterable[A]) -> List[A]:\n    \"\"\"\n    An Iterable may be a list or a generator.\n    This ensures we get a list without making an unnecessary copy.\n    \"\"\"\n    if isinstance(iterable, list):\n        return iterable\n    else:\n        return list(iterable)", "title": ""}
{"_id": "d17985", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d17986", "text": "def lint(fmt='colorized'):\n    \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\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)", "title": ""}
{"_id": "d17987", "text": "def _protected_log(x1):\n    \"\"\"Closure of log for zero arguments.\"\"\"\n    with np.errstate(divide='ignore', invalid='ignore'):\n        return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)", "title": ""}
{"_id": "d17988", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d17989", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d17990", "text": "def url_concat(url, args):\n    \"\"\"Concatenate url and argument dictionary regardless of whether\n    url has existing query parameters.\n\n    >>> url_concat(\"http://example.com/foo?a=b\", dict(c=\"d\"))\n    'http://example.com/foo?a=b&c=d'\n    \"\"\"\n    if not args: return url\n    if url[-1] not in ('?', '&'):\n        url += '&' if ('?' in url) else '?'\n    return url + urllib.urlencode(args)", "title": ""}
{"_id": "d17991", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d17992", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d17993", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d17994", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d17995", "text": "def find_first(pattern: str, path: str) -> str:\n    \"\"\"\n    Finds first file in ``path`` whose filename matches ``pattern`` (via\n    :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`.\n    \"\"\"\n    try:\n        return find(pattern, path)[0]\n    except IndexError:\n        log.critical('''Couldn't find \"{}\" in \"{}\"''', pattern, path)\n        raise", "title": ""}
{"_id": "d17996", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d17997", "text": "def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]:\n    \"\"\"\n    Load and pre-process the images specified with absolute paths.\n\n    :param image_paths: List of images specified with paths.\n    :param image_size: Tuple to resize the image to (Channels, Height, Width)\n    :return: A list of loaded images (numpy arrays).\n    \"\"\"\n    image_size = image_size[1:]  # we do not need the number of channels\n    images = []\n    for image_path in image_paths:\n        images.append(load_preprocess_image(image_path, image_size))\n    return images", "title": ""}
{"_id": "d17998", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d17999", "text": "def bytes_hack(buf):\n    \"\"\"\n    Hacky workaround for old installs of the library on systems without python-future that were\n    keeping the 2to3 update from working after auto-update.\n    \"\"\"\n    ub = None\n    if sys.version_info > (3,):\n        ub = buf\n    else:\n        ub = bytes(buf)\n\n    return ub", "title": ""}
{"_id": "d18000", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d18001", "text": "def samefile(a: str, b: str) -> bool:\n    \"\"\"Check if two pathes represent the same file.\"\"\"\n    try:\n        return os.path.samefile(a, b)\n    except OSError:\n        return os.path.normpath(a) == os.path.normpath(b)", "title": ""}
{"_id": "d18002", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d18003", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d18004", "text": "def are_token_parallel(sequences: Sequence[Sized]) -> bool:\n    \"\"\"\n    Returns True if all sequences in the list have the same length.\n    \"\"\"\n    if not sequences or len(sequences) == 1:\n        return True\n    return all(len(s) == len(sequences[0]) for s in sequences)", "title": ""}
{"_id": "d18005", "text": "def local_machine_uuid():\n    \"\"\"Return local machine unique identifier.\n\n    >>> uuid = local_machine_uuid()\n\n    \"\"\"\n\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\n    return uuid.UUID(hex=result)", "title": ""}
{"_id": "d18006", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d18007", "text": "def _check_update_(self):\n        \"\"\"Check if the current version of the library is outdated.\"\"\"\n        try:\n            data = requests.get(\"https://pypi.python.org/pypi/jira/json\", timeout=2.001).json()\n\n            released_version = data['info']['version']\n            if parse_version(released_version) > parse_version(__version__):\n                warnings.warn(\n                    \"You are running an outdated version of JIRA Python %s. Current version is %s. Do not file any bugs against older versions.\" % (\n                        __version__, released_version))\n        except requests.RequestException:\n            pass\n        except Exception as e:\n            logging.warning(e)", "title": ""}
{"_id": "d18008", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d18009", "text": "def __gt__(self, other):\n        \"\"\"Test for greater than.\"\"\"\n        if isinstance(other, Address):\n            return str(self) > str(other)\n        raise TypeError", "title": ""}
{"_id": "d18010", "text": "def last(self):\n        \"\"\"Last time step available.\n\n        Example:\n            >>> sdat = StagyyData('path/to/run')\n            >>> assert(sdat.steps.last is sdat.steps[-1])\n        \"\"\"\n        if self._last is UNDETERMINED:\n            # not necessarily the last one...\n            self._last = self.sdat.tseries.index[-1]\n        return self[self._last]", "title": ""}
{"_id": "d18011", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d18012", "text": "def _get_or_default(mylist, i, default=None):\n    \"\"\"return list item number, or default if don't exist\"\"\"\n    if i >= len(mylist):\n        return default\n    else :\n        return mylist[i]", "title": ""}
{"_id": "d18013", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d18014", "text": "def right_replace(string, old, new, count=1):\n    \"\"\"\n    Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.\n    For example::\n\n        right_replace('one_two_two', 'two', 'three') -> 'one_two_three'\n    \"\"\"\n    if not string:\n        return string\n    return new.join(string.rsplit(old, count))", "title": ""}
{"_id": "d18015", "text": "def gcd_float(numbers, tol=1e-8):\n    \"\"\"\n    Returns the greatest common divisor for a sequence of numbers.\n    Uses a numerical tolerance, so can be used on floats\n\n    Args:\n        numbers: Sequence of numbers.\n        tol: Numerical tolerance\n\n    Returns:\n        (int) Greatest common divisor of numbers.\n    \"\"\"\n\n    def pair_gcd_tol(a, b):\n        \"\"\"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).\n        \"\"\"\n        while b > tol:\n            a, b = b, a % b\n        return a\n\n    n = numbers[0]\n    for i in numbers:\n        n = pair_gcd_tol(n, i)\n    return n", "title": ""}
{"_id": "d18016", "text": "def de_duplicate(items):\n    \"\"\"Remove any duplicate item, preserving order\n\n    >>> de_duplicate([1, 2, 1, 2])\n    [1, 2]\n    \"\"\"\n    result = []\n    for item in items:\n        if item not in result:\n            result.append(item)\n    return result", "title": ""}
{"_id": "d18017", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18018", "text": "def version():\n    \"\"\"Wrapper for opj_version library routine.\"\"\"\n    OPENJPEG.opj_version.restype = ctypes.c_char_p\n    library_version = OPENJPEG.opj_version()\n    if sys.hexversion >= 0x03000000:\n        return library_version.decode('utf-8')\n    else:\n        return library_version", "title": ""}
{"_id": "d18019", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d18020", "text": "def get_now_sql_datetime():\n    \"\"\"\n    *A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``*\n\n    **Return:**\n        - ``now`` -- current time and date in MySQL format\n\n    **Usage:**\n        .. code-block:: python \n\n            from fundamentals import times\n            now = times.get_now_sql_datetime()\n            print now\n\n            # OUT: 2016-03-18T11:08:23 \n    \"\"\"\n    ## > IMPORTS ##\n    from datetime import datetime, date, time\n    now = datetime.now()\n    now = now.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\n    return now", "title": ""}
{"_id": "d18021", "text": "def assert_equal(first, second, msg_fmt=\"{msg}\"):\n    \"\"\"Fail unless first equals second, as determined by the '==' operator.\n\n    >>> assert_equal(5, 5.0)\n    >>> assert_equal(\"Hello World!\", \"Goodbye!\")\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'Hello World!' != 'Goodbye!'\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\n    \"\"\"\n\n    if isinstance(first, dict) and isinstance(second, dict):\n        assert_dict_equal(first, second, msg_fmt)\n    elif not first == second:\n        msg = \"{!r} != {!r}\".format(first, second)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))", "title": ""}
{"_id": "d18022", "text": "def right_replace(string, old, new, count=1):\n    \"\"\"\n    Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.\n    For example::\n\n        right_replace('one_two_two', 'two', 'three') -> 'one_two_three'\n    \"\"\"\n    if not string:\n        return string\n    return new.join(string.rsplit(old, count))", "title": ""}
{"_id": "d18023", "text": "def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool:\n    \"\"\"Returns True if the given node is an object from the __builtin__ module.\"\"\"\n    return node and node.root().name == BUILTINS_NAME", "title": ""}
{"_id": "d18024", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d18025", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d18026", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d18027", "text": "def capitalize(string):\n    \"\"\"Capitalize a sentence.\n\n    Parameters\n    ----------\n    string : `str`\n        String to capitalize.\n\n    Returns\n    -------\n    `str`\n        Capitalized string.\n\n    Examples\n    --------\n    >>> capitalize('worD WORD WoRd')\n    'Word word word'\n    \"\"\"\n    if not string:\n        return string\n    if len(string) == 1:\n        return string.upper()\n    return string[0].upper() + string[1:].lower()", "title": ""}
{"_id": "d18028", "text": "def min(self):\n        \"\"\"\n        :returns the minimum of the column\n        \"\"\"\n        res = self._qexec(\"min(%s)\" % self._name)\n        if len(res) > 0:\n            self._min = res[0][0]\n        return self._min", "title": ""}
{"_id": "d18029", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d18030", "text": "def checksum(path):\n    \"\"\"Calculcate checksum for a file.\"\"\"\n    hasher = hashlib.sha1()\n    with open(path, 'rb') as stream:\n        buf = stream.read(BLOCKSIZE)\n        while len(buf) > 0:\n            hasher.update(buf)\n            buf = stream.read(BLOCKSIZE)\n    return hasher.hexdigest()", "title": ""}
{"_id": "d18031", "text": "def fib(n):\n    \"\"\"Fibonacci example function\n\n    Args:\n      n (int): integer\n\n    Returns:\n      int: n-th Fibonacci number\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", "title": ""}
{"_id": "d18032", "text": "def get_days_in_month(year: int, month: int) -> int:\n    \"\"\" Returns number of days in the given month.\n    1-based numbers as arguments. i.e. November = 11 \"\"\"\n    month_range = calendar.monthrange(year, month)\n    return month_range[1]", "title": ""}
{"_id": "d18033", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d18034", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d18035", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d18036", "text": "def pairwise(iterable):\n    \"\"\"From itertools cookbook. [a, b, c, ...] -> (a, b), (b, c), ...\"\"\"\n    first, second = tee(iterable)\n    next(second, None)\n    return zip(first, second)", "title": ""}
{"_id": "d18037", "text": "def to_graphviz(graph):\n    \"\"\"\n\n    :param graph:\n    :return:\n    \"\"\"\n    ret = ['digraph g {']\n    vertices = []\n\n    node_ids = dict([(name, 'node' + idx) for (idx, name) in enumerate(list(graph))])\n\n    for node in list(graph):\n        ret.append('  \"%s\" [label=\"%s\"];' % (node_ids[node], node))\n        for target in graph[node]:\n            vertices.append('  \"%s\" -> \"%s\";' % (node_ids[node], node_ids[target]))\n\n    ret += vertices\n    ret.append('}')\n    return '\\n'.join(ret)", "title": ""}
{"_id": "d18038", "text": "def file_or_stdin() -> Callable:\n    \"\"\"\n    Returns a file descriptor from stdin or opening a file from a given path.\n    \"\"\"\n\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\n    return parse", "title": ""}
{"_id": "d18039", "text": "def get_file_extension(filename):\n    \"\"\" Return the extension if the filename has it. None if not.\n\n    :param filename: The filename.\n    :return: Extension or None.\n    \"\"\"\n    filename_x = filename.split('.')\n    if len(filename_x) > 1:\n        if filename_x[-1].strip() is not '':\n            return filename_x[-1]\n    return None", "title": ""}
{"_id": "d18040", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d18041", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d18042", "text": "def normalize_column_names(df):\n    r\"\"\" Clean up whitespace in column names. See better version at `pugnlp.clean_columns`\n\n    >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here'])\n    >>> normalize_column_names(df)\n    ['hello_world', 'not_here']\n    \"\"\"\n    columns = df.columns if hasattr(df, 'columns') else df\n    columns = [c.lower().replace(' ', '_') for c in columns]\n    return columns", "title": ""}
{"_id": "d18043", "text": "def _width_is_big_enough(image, width):\n    \"\"\"Check that the image width is superior to `width`\"\"\"\n    if width > image.size[0]:\n        raise ImageSizeError(image.size[0], width)", "title": ""}
{"_id": "d18044", "text": "def bulk_load_docs(es, docs):\n    \"\"\"Bulk load docs\n\n    Args:\n        es: elasticsearch handle\n        docs: Iterator of doc objects - includes index_name\n    \"\"\"\n\n    chunk_size = 200\n\n    try:\n        results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)\n        log.debug(f\"Elasticsearch documents loaded: {results[0]}\")\n\n        # elasticsearch.helpers.parallel_bulk(es, terms, chunk_size=chunk_size, thread_count=4)\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))", "title": ""}
{"_id": "d18045", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18046", "text": "def detect_model_num(string):\n    \"\"\"Takes a string related to a model name and extract its model number.\n\n    For example:\n        '000000-bootstrap.index' => 0\n    \"\"\"\n    match = re.match(MODEL_NUM_REGEX, string)\n    if match:\n        return int(match.group())\n    return None", "title": ""}
{"_id": "d18047", "text": "def normcdf(x, log=False):\n    \"\"\"Normal cumulative density function.\"\"\"\n    y = np.atleast_1d(x).copy()\n    flib.normcdf(y)\n    if log:\n        if (y>0).all():\n            return np.log(y)\n        return -np.inf\n    return y", "title": ""}
{"_id": "d18048", "text": "def find_first(pattern: str, path: str) -> str:\n    \"\"\"\n    Finds first file in ``path`` whose filename matches ``pattern`` (via\n    :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`.\n    \"\"\"\n    try:\n        return find(pattern, path)[0]\n    except IndexError:\n        log.critical('''Couldn't find \"{}\" in \"{}\"''', pattern, path)\n        raise", "title": ""}
{"_id": "d18049", "text": "def _sum_cycles_from_tokens(self, tokens: List[str]) -> int:\n        \"\"\"Sum the total number of cycles over a list of tokens.\"\"\"\n        return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))", "title": ""}
{"_id": "d18050", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d18051", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d18052", "text": "def _prm_get_longest_stringsize(string_list):\n        \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n        maxlength = 1\n\n        for stringar in string_list:\n            if isinstance(stringar, np.ndarray):\n                if stringar.ndim > 0:\n                    for string in stringar.ravel():\n                        maxlength = max(len(string), maxlength)\n                else:\n                    maxlength = max(len(stringar.tolist()), maxlength)\n            else:\n                maxlength = max(len(stringar), maxlength)\n\n        # Make the string Col longer than needed in order to allow later on slightly larger strings\n        return int(maxlength * 1.5)", "title": ""}
{"_id": "d18053", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d18054", "text": "def de_duplicate(items):\n    \"\"\"Remove any duplicate item, preserving order\n\n    >>> de_duplicate([1, 2, 1, 2])\n    [1, 2]\n    \"\"\"\n    result = []\n    for item in items:\n        if item not in result:\n            result.append(item)\n    return result", "title": ""}
{"_id": "d18055", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d18056", "text": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n    \"\"\"\n    Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n    :param buckets: List of buckets.\n    :return: The largest bucket in the list.\n    \"\"\"\n    return max(buckets)", "title": ""}
{"_id": "d18057", "text": "def __next__(self):\n        \"\"\"\n        :return: int\n        \"\"\"\n        self.current += 1\n        if self.current > self.total:\n            raise StopIteration\n        else:\n            return self.iterable[self.current - 1]", "title": ""}
{"_id": "d18058", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d18059", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d18060", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d18061", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d18062", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d18063", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d18064", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d18065", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d18066", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d18067", "text": "def branches():\n    # type: () -> List[str]\n    \"\"\" Return a list of branches in the current repo.\n\n    Returns:\n        list[str]: A list of branches in the current repo.\n    \"\"\"\n    out = shell.run(\n        'git branch',\n        capture=True,\n        never_pretend=True\n    ).stdout.strip()\n    return [x.strip('* \\t\\n') for x in out.splitlines()]", "title": ""}
{"_id": "d18068", "text": "def cache_page(page_cache, page_hash, cache_size):\n    \"\"\"Add a page to the page cache.\"\"\"\n    page_cache.append(page_hash)\n    if len(page_cache) > cache_size:\n        page_cache.pop(0)", "title": ""}
{"_id": "d18069", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d18070", "text": "def _log_response(response):\n    \"\"\"Log out information about a ``Request`` object.\n\n    After calling ``requests.request`` or one of its convenience methods, the\n    object returned can be passed to this method. If done, information about\n    the object returned is logged.\n\n    :return: Nothing is returned.\n\n    \"\"\"\n    message = u'Received HTTP {0} response: {1}'.format(\n        response.status_code,\n        response.text\n    )\n    if response.status_code >= 400:  # pragma: no cover\n        logger.warning(message)\n    else:\n        logger.debug(message)", "title": ""}
{"_id": "d18071", "text": "def empty_wav(wav_path: Union[Path, str]) -> bool:\n    \"\"\"Check if a wav contains data\"\"\"\n    with wave.open(str(wav_path), 'rb') as wav_f:\n        return wav_f.getnframes() == 0", "title": ""}
{"_id": "d18072", "text": "def _in_qtconsole() -> bool:\n    \"\"\"\n    A small utility function which determines if we're running in QTConsole's context.\n    \"\"\"\n    try:\n        from IPython import get_ipython\n        try:\n            from ipykernel.zmqshell import ZMQInteractiveShell\n            shell_object = ZMQInteractiveShell\n        except ImportError:\n            from IPython.kernel.zmq import zmqshell\n            shell_object = zmqshell.ZMQInteractiveShell\n        return isinstance(get_ipython(), shell_object)\n    except Exception:\n        return False", "title": ""}
{"_id": "d18073", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d18074", "text": "def read(self, start_position: int, size: int) -> memoryview:\n        \"\"\"\n        Return a view into the memory\n        \"\"\"\n        return memoryview(self._bytes)[start_position:start_position + size]", "title": ""}
{"_id": "d18075", "text": "def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):\n        \"\"\"\n        If we're not on the first line (of a multiline input) go a line up,\n        otherwise go back in history. (If nothing is selected.)\n        \"\"\"\n        if self.complete_state:\n            self.complete_previous(count=count)\n        elif self.document.cursor_position_row > 0:\n            self.cursor_up(count=count)\n        elif not self.selection_state:\n            self.history_backward(count=count)\n\n            # Go to the start of the line?\n            if go_to_start_of_line_if_history_changes:\n                self.cursor_position += self.document.get_start_of_line_position()", "title": ""}
{"_id": "d18076", "text": "def set_cell_value(cell, value):\n    \"\"\"\n    Convenience method for setting the value of an openpyxl cell\n\n    This is necessary since the value property changed from internal_value\n    to value between version 1.* and 2.*.\n    \"\"\"\n    if OPENPYXL_MAJOR_VERSION > 1:\n        cell.value = value\n    else:\n        cell.internal_value = value", "title": ""}
{"_id": "d18077", "text": "def writable_stream(handle):\n    \"\"\"Test whether a stream can be written to.\n    \"\"\"\n    if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):\n        return handle.writable()\n    try:\n        handle.write(b'')\n    except (io.UnsupportedOperation, IOError):\n        return False\n    else:\n        return True", "title": ""}
{"_id": "d18078", "text": "def sorted(self):\n        \"\"\"Utility function for sort_file_tabs_alphabetically().\"\"\"\n        for i in range(0, self.tabs.tabBar().count() - 1):\n            if (self.tabs.tabBar().tabText(i) >\n                    self.tabs.tabBar().tabText(i + 1)):\n                return False\n        return True", "title": ""}
{"_id": "d18079", "text": "def ask_bool(question: str, default: bool = True) -> bool:\n    \"\"\"Asks a question yes no style\"\"\"\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\"", "title": ""}
{"_id": "d18080", "text": "def ensure_list(iterable: Iterable[A]) -> List[A]:\n    \"\"\"\n    An Iterable may be a list or a generator.\n    This ensures we get a list without making an unnecessary copy.\n    \"\"\"\n    if isinstance(iterable, list):\n        return iterable\n    else:\n        return list(iterable)", "title": ""}
{"_id": "d18081", "text": "def isfile_notempty(inputfile: str) -> bool:\n        \"\"\"Check if the input filename with path is a file and is not empty.\"\"\"\n        try:\n            return isfile(inputfile) and getsize(inputfile) > 0\n        except TypeError:\n            raise TypeError('inputfile is not a valid type')", "title": ""}
{"_id": "d18082", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d18083", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d18084", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d18085", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d18086", "text": "def parse_dim(features, check=True):\n    \"\"\"Return the features dimension, raise if error\n\n    Raise IOError if features have not all the same positive\n    dimension.  Return dim (int), the features dimension.\n\n    \"\"\"\n    # try:\n    dim = features[0].shape[1]\n    # except IndexError:\n    #     dim = 1\n\n    if check and not dim > 0:\n        raise IOError('features dimension must be strictly positive')\n    if check and not all([d == dim for d in [x.shape[1] for x in features]]):\n        raise IOError('all files must have the same feature dimension')\n    return dim", "title": ""}
{"_id": "d18087", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d18088", "text": "def camel_to_snake_case(string):\n    \"\"\"Converts 'string' presented in camel case to snake case.\n\n    e.g.: CamelCase => snake_case\n    \"\"\"\n    s = _1.sub(r'\\1_\\2', string)\n    return _2.sub(r'\\1_\\2', s).lower()", "title": ""}
{"_id": "d18089", "text": "def write_text(filename: str, text: str) -> None:\n    \"\"\"\n    Writes text to a file.\n    \"\"\"\n    with open(filename, 'w') as f:  # type: TextIO\n        print(text, file=f)", "title": ""}
{"_id": "d18090", "text": "def fmt_camel(name):\n    \"\"\"\n    Converts name to lower camel case. Words are identified by capitalization,\n    dashes, and underscores.\n    \"\"\"\n    words = split_words(name)\n    assert len(words) > 0\n    first = words.pop(0).lower()\n    return first + ''.join([word.capitalize() for word in words])", "title": ""}
{"_id": "d18091", "text": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n    \"\"\"\n    Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n    :param buckets: List of buckets.\n    :return: The largest bucket in the list.\n    \"\"\"\n    return max(buckets)", "title": ""}
{"_id": "d18092", "text": "def _brief_print_list(lst, limit=7):\n    \"\"\"Print at most `limit` elements of list.\"\"\"\n    lst = list(lst)\n    if len(lst) > limit:\n        return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n            _brief_print_list(lst[-limit//2:], limit)\n    return ', '.join([\"'%s'\"%str(i) for i in lst])", "title": ""}
{"_id": "d18093", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d18094", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d18095", "text": "def get_edge_relations(graph: BELGraph) -> Mapping[Tuple[BaseEntity, BaseEntity], Set[str]]:\n    \"\"\"Build a dictionary of {node pair: set of edge types}.\"\"\"\n    return group_dict_set(\n        ((u, v), d[RELATION])\n        for u, v, d in graph.edges(data=True)\n    )", "title": ""}
{"_id": "d18096", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d18097", "text": "def arcball_map_to_sphere(point, center, radius):\n    \"\"\"Return unit sphere coordinates from window coordinates.\"\"\"\n    v0 = (point[0] - center[0]) / radius\n    v1 = (center[1] - point[1]) / radius\n    n = v0*v0 + v1*v1\n    if n > 1.0:\n        # position outside of sphere\n        n = math.sqrt(n)\n        return numpy.array([v0/n, v1/n, 0.0])\n    else:\n        return numpy.array([v0, v1, math.sqrt(1.0 - n)])", "title": ""}
{"_id": "d18098", "text": "def file_exists(self) -> bool:\n        \"\"\" Check if the settings file exists or not \"\"\"\n        cfg_path = self.file_path\n        assert cfg_path\n\n        return path.isfile(cfg_path)", "title": ""}
{"_id": "d18099", "text": "def local_machine_uuid():\n    \"\"\"Return local machine unique identifier.\n\n    >>> uuid = local_machine_uuid()\n\n    \"\"\"\n\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\n    return uuid.UUID(hex=result)", "title": ""}
{"_id": "d18100", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d18101", "text": "def __setitem__(self, *args, **kwargs):\n        \"\"\" Cut if needed. \"\"\"\n        super(History, self).__setitem__(*args, **kwargs)\n        if len(self) > self.size:\n            self.popitem(False)", "title": ""}
{"_id": "d18102", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d18103", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d18104", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d18105", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d18106", "text": "def list_adb_devices_by_usb_id():\n    \"\"\"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.\n    \"\"\"\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", "title": ""}
{"_id": "d18107", "text": "def snake_case(a_string):\n    \"\"\"Returns a snake cased version of a string.\n\n    :param a_string: any :class:`str` object.\n\n    Usage:\n        >>> snake_case('FooBar')\n        \"foo_bar\"\n    \"\"\"\n\n    partial = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', a_string)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', partial).lower()", "title": ""}
{"_id": "d18108", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d18109", "text": "def decode(self, bytes, raw=False):\n        \"\"\"decode(bytearray, raw=False) -> value\n\n        Decodes the given bytearray according to this PrimitiveType\n        definition.\n\n        NOTE: The parameter ``raw`` is present to adhere to the\n        ``decode()`` inteface, but has no effect for PrimitiveType\n        definitions.\n        \"\"\"\n        return struct.unpack(self.format, buffer(bytes))[0]", "title": ""}
{"_id": "d18110", "text": "def returns(self) -> T.Optional[DocstringReturns]:\n        \"\"\"Return return information indicated in docstring.\"\"\"\n        try:\n            return next(\n                DocstringReturns.from_meta(meta)\n                for meta in self.meta\n                if meta.args[0] in {\"return\", \"returns\", \"yield\", \"yields\"}\n            )\n        except StopIteration:\n            return None", "title": ""}
{"_id": "d18111", "text": "def dict_of_sets_add(dictionary, key, value):\n    # type: (DictUpperBound, Any, Any) -> None\n    \"\"\"Add value to a set 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 set in dictionary\n\n    Returns:\n        None\n\n    \"\"\"\n    set_objs = dictionary.get(key, set())\n    set_objs.add(value)\n    dictionary[key] = set_objs", "title": ""}
{"_id": "d18112", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d18113", "text": "def running_containers(name_filter: str) -> List[str]:\n    \"\"\"\n    :raises docker.exceptions.APIError\n    \"\"\"\n    return [container.short_id for container in\n            docker_client.containers.list(filters={\"name\": name_filter})]", "title": ""}
{"_id": "d18114", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d18115", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d18116", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d18117", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d18118", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d18119", "text": "def constant(times: np.ndarray, amp: complex) -> np.ndarray:\n    \"\"\"Continuous constant pulse.\n\n    Args:\n        times: Times to output pulse for.\n        amp: Complex pulse amplitude.\n    \"\"\"\n    return np.full(len(times), amp, dtype=np.complex_)", "title": ""}
{"_id": "d18120", "text": "def normcdf(x, log=False):\n    \"\"\"Normal cumulative density function.\"\"\"\n    y = np.atleast_1d(x).copy()\n    flib.normcdf(y)\n    if log:\n        if (y>0).all():\n            return np.log(y)\n        return -np.inf\n    return y", "title": ""}
{"_id": "d18121", "text": "def replaceStrs(s, *args):\n    r\"\"\"Replace all ``(frm, to)`` tuples in `args` in string `s`.\n\n    >>> replaceStrs(\"nothing is better than warm beer\",\n    ...             ('nothing','warm beer'), ('warm beer','nothing'))\n    'warm beer is better than nothing'\n\n    \"\"\"\n    if args == (): return s\n    mapping = dict((frm, to) for frm, to in args)\n    return re.sub(\"|\".join(map(re.escape, mapping.keys())),\n                  lambda match:mapping[match.group(0)], s)", "title": ""}
{"_id": "d18122", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18123", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d18124", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d18125", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18126", "text": "def _protected_log(x1):\n    \"\"\"Closure of log for zero arguments.\"\"\"\n    with np.errstate(divide='ignore', invalid='ignore'):\n        return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)", "title": ""}
{"_id": "d18127", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18128", "text": "def check_max_filesize(chosen_file, max_size):\n    \"\"\"\n    Checks file sizes for host\n    \"\"\"\n    if os.path.getsize(chosen_file) > max_size:\n        return False\n    else:\n        return True", "title": ""}
{"_id": "d18129", "text": "def pretty_describe(object, nestedness=0, indent=2):\n    \"\"\"Maintain dict ordering - but make string version prettier\"\"\"\n    if not isinstance(object, dict):\n        return str(object)\n    sep = f'\\n{\" \" * nestedness * indent}'\n    out = sep.join((f'{k}: {pretty_describe(v, nestedness + 1)}' for k, v in object.items()))\n    if nestedness > 0 and out:\n        return f'{sep}{out}'\n    return out", "title": ""}
{"_id": "d18130", "text": "def indent(text: str, num: int = 2) -> str:\n    \"\"\"Indent a piece of text.\"\"\"\n    lines = text.splitlines()\n    return \"\\n\".join(indent_iterable(lines, num=num))", "title": ""}
{"_id": "d18131", "text": "def is_any_type_set(sett: Set[Type]) -> bool:\n    \"\"\"\n    Helper method to check if a set of types is the {AnyObject} singleton\n\n    :param sett:\n    :return:\n    \"\"\"\n    return len(sett) == 1 and is_any_type(min(sett))", "title": ""}
{"_id": "d18132", "text": "def extend(a: dict, b: dict) -> dict:\n    \"\"\"Merge two dicts and return a new dict. Much like subclassing works.\"\"\"\n    res = a.copy()\n    res.update(b)\n    return res", "title": ""}
{"_id": "d18133", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d18134", "text": "def _read_section(self):\n        \"\"\"Read and return an entire section\"\"\"\n        lines = [self._last[self._last.find(\":\")+1:]]\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            lines.append(self._last)\n            self._last = self._f.readline()\n        return lines", "title": ""}
{"_id": "d18135", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d18136", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d18137", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d18138", "text": "def decode(self, bytes, raw=False):\n        \"\"\"decode(bytearray, raw=False) -> value\n\n        Decodes the given bytearray according to this PrimitiveType\n        definition.\n\n        NOTE: The parameter ``raw`` is present to adhere to the\n        ``decode()`` inteface, but has no effect for PrimitiveType\n        definitions.\n        \"\"\"\n        return struct.unpack(self.format, buffer(bytes))[0]", "title": ""}
{"_id": "d18139", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d18140", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d18141", "text": "def decode_base64(data: str) -> bytes:\n    \"\"\"Decode base64, padding being optional.\n\n    :param data: Base64 data as an ASCII byte string\n    :returns: The decoded byte string.\n    \"\"\"\n    missing_padding = len(data) % 4\n    if missing_padding != 0:\n        data += \"=\" * (4 - missing_padding)\n    return base64.decodebytes(data.encode(\"utf-8\"))", "title": ""}
{"_id": "d18142", "text": "def lowercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the lowercase chars in the given string.\"\"\"\n        return ''.join([c if c.islower() else '' for c in str(string)])", "title": ""}
{"_id": "d18143", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18144", "text": "def get_view_selection(self):\n        \"\"\"Get actual tree selection object and all respective models of selected rows\"\"\"\n        if not self.MODEL_STORAGE_ID:\n            return None, None\n\n        # avoid selection requests on empty tree views -> case warnings in gtk3\n        if len(self.store) == 0:\n            paths = []\n        else:\n            model, paths = self._tree_selection.get_selected_rows()\n\n        # get all related models for selection from respective tree store field\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", "title": ""}
{"_id": "d18145", "text": "def public(self) -> 'PrettyDir':\n        \"\"\"Returns public attributes of the inspected object.\"\"\"\n        return PrettyDir(\n            self.obj, [pattr for pattr in self.pattrs if not pattr.name.startswith('_')]\n        )", "title": ""}
{"_id": "d18146", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d18147", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d18148", "text": "def output_dir(self, *args) -> str:\n        \"\"\" Directory where to store output \"\"\"\n        return os.path.join(self.project_dir, 'output', *args)", "title": ""}
{"_id": "d18149", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d18150", "text": "def get_pylint_options(config_dir='.'):\n    # type: (str) -> List[str]\n    \"\"\"Checks for local config overrides for `pylint`\n    and add them in the correct `pylint` `options` format.\n\n    :param config_dir:\n    :return: List [str]\n    \"\"\"\n    if PYLINT_CONFIG_NAME in os.listdir(config_dir):\n        pylint_config_path = PYLINT_CONFIG_NAME\n    else:\n        pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH\n\n    return ['--rcfile={}'.format(pylint_config_path)]", "title": ""}
{"_id": "d18151", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d18152", "text": "def _check_limit(self):\n        \"\"\"Intenal method: check if current cache size exceeds maximum cache\n           size and pop the oldest item in this case\"\"\"\n\n        # First compress\n        self._compress()\n\n        # Then check the max size\n        if len(self._store) >= self._max_size:\n            self._store.popitem(last=False)", "title": ""}
{"_id": "d18153", "text": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n    \"\"\"\n    Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n    :param buckets: List of buckets.\n    :return: The largest bucket in the list.\n    \"\"\"\n    return max(buckets)", "title": ""}
{"_id": "d18154", "text": "def codes_get_size(handle, key):\n    # type: (cffi.FFI.CData, str) -> int\n    \"\"\"\n    Get the number of coded value from a key.\n    If several keys of the same name are present, the total sum is returned.\n\n    :param bytes key: the keyword to get the size of\n\n    :rtype: int\n    \"\"\"\n    size = ffi.new('size_t *')\n    _codes_get_size(handle, key.encode(ENC), size)\n    return size[0]", "title": ""}
{"_id": "d18155", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d18156", "text": "def remove_namespaces(root):\n    \"\"\"Call this on an lxml.etree document to remove all namespaces\"\"\"\n    for elem in root.getiterator():\n        if not hasattr(elem.tag, 'find'):\n            continue\n\n        i = elem.tag.find('}')\n        if i >= 0:\n            elem.tag = elem.tag[i + 1:]\n\n    objectify.deannotate(root, cleanup_namespaces=True)", "title": ""}
{"_id": "d18157", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d18158", "text": "def _brief_print_list(lst, limit=7):\n    \"\"\"Print at most `limit` elements of list.\"\"\"\n    lst = list(lst)\n    if len(lst) > limit:\n        return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n            _brief_print_list(lst[-limit//2:], limit)\n    return ', '.join([\"'%s'\"%str(i) for i in lst])", "title": ""}
{"_id": "d18159", "text": "def update(self, iterable):\n        \"\"\"\n        Return a new PSet with elements in iterable added\n\n        >>> s1 = s(1, 2)\n        >>> s1.update([3, 4, 4])\n        pset([1, 2, 3, 4])\n        \"\"\"\n        e = self.evolver()\n        for element in iterable:\n            e.add(element)\n\n        return e.persistent()", "title": ""}
{"_id": "d18160", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d18161", "text": "def convert_bytes_to_ints(in_bytes, num):\n    \"\"\"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\"\"\"\n    dt = numpy.dtype('>i' + str(num))\n    return numpy.frombuffer(in_bytes, dt)", "title": ""}
{"_id": "d18162", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d18163", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d18164", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d18165", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d18166", "text": "def first_digits(s, default=0):\n    \"\"\"Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-).\n    >>> first_digits('+123.456')\n    123\n    \"\"\"\n    s = re.split(r'[^0-9]+', str(s).strip().lstrip('+-' + charlist.whitespace))\n    if len(s) and len(s[0]):\n        return int(s[0])\n    return default", "title": ""}
{"_id": "d18167", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d18168", "text": "def _exit(self, status_code):\n        \"\"\"Properly kill Python process including zombie threads.\"\"\"\n        # If there are active threads still running infinite loops, sys.exit\n        # won't kill them but os._exit will. os._exit skips calling cleanup\n        # handlers, flushing stdio buffers, etc.\n        exit_func = os._exit if threading.active_count() > 1 else sys.exit\n        exit_func(status_code)", "title": ""}
{"_id": "d18169", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18170", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d18171", "text": "def _relative_frequency(self, word):\n\t\t\"\"\"Computes the log relative frequency for a word form\"\"\"\n\n\t\tcount = self.type_counts.get(word, 0)\n\t\treturn math.log(count/len(self.type_counts)) if count > 0 else 0", "title": ""}
{"_id": "d18172", "text": "def replace_variables(self, source: str, variables: dict) -> str:\n        \"\"\"Replace {{variable-name}} with stored value.\"\"\"\n        try:\n            replaced = re.sub(\n                \"{{(.*?)}}\", lambda m: variables.get(m.group(1), \"\"), source\n            )\n        except TypeError:\n            replaced = source\n        return replaced", "title": ""}
{"_id": "d18173", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18174", "text": "def update_kwargs(kwargs, **keyvalues):\n    \"\"\"Update dict with keys and values if keys do not already exist.\n\n    >>> kwargs = {'one': 1, }\n    >>> update_kwargs(kwargs, one=None, two=2)\n    >>> kwargs == {'one': 1, 'two': 2}\n    True\n\n    \"\"\"\n    for key, value in keyvalues.items():\n        if key not in kwargs:\n            kwargs[key] = value", "title": ""}
{"_id": "d18175", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d18176", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d18177", "text": "def samefile(a: str, b: str) -> bool:\n    \"\"\"Check if two pathes represent the same file.\"\"\"\n    try:\n        return os.path.samefile(a, b)\n    except OSError:\n        return os.path.normpath(a) == os.path.normpath(b)", "title": ""}
{"_id": "d18178", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18179", "text": "async def parallel_results(future_map: Sequence[Tuple]) -> Dict:\n    \"\"\"\n    Run parallel execution of futures and return mapping of their results to the provided keys.\n    Just a neat shortcut around ``asyncio.gather()``\n\n    :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )\n    :return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'}\n    \"\"\"\n    ctx_methods = OrderedDict(future_map)\n    fs = list(ctx_methods.values())\n    results = await asyncio.gather(*fs)\n    results = {\n        key: results[idx] for idx, key in enumerate(ctx_methods.keys())\n    }\n    return results", "title": ""}
{"_id": "d18180", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d18181", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d18182", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d18183", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18184", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d18185", "text": "def head(self) -> Any:\n        \"\"\"Retrive first element in List.\"\"\"\n\n        lambda_list = self._get_value()\n        return lambda_list(lambda head, _: head)", "title": ""}
{"_id": "d18186", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d18187", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d18188", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d18189", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d18190", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d18191", "text": "def stop(self) -> None:\n        \"\"\"Stops the analysis as soon as possible.\"\"\"\n        if self._stop and not self._posted_kork:\n            self._stop()\n            self._stop = None", "title": ""}
{"_id": "d18192", "text": "def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):\n        \"\"\"\n        If we're not on the first line (of a multiline input) go a line up,\n        otherwise go back in history. (If nothing is selected.)\n        \"\"\"\n        if self.complete_state:\n            self.complete_previous(count=count)\n        elif self.document.cursor_position_row > 0:\n            self.cursor_up(count=count)\n        elif not self.selection_state:\n            self.history_backward(count=count)\n\n            # Go to the start of the line?\n            if go_to_start_of_line_if_history_changes:\n                self.cursor_position += self.document.get_start_of_line_position()", "title": ""}
{"_id": "d18193", "text": "def _reshuffle(mat, shape):\n    \"\"\"Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].\"\"\"\n    return np.reshape(\n        np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),\n        (shape[3] * shape[1], shape[0] * shape[2]))", "title": ""}
{"_id": "d18194", "text": "def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]:\n    \"\"\" Partition a list of integers into a list of partitions \"\"\"\n    for part in algorithm_u(range(size), nparts):\n        yield part", "title": ""}
{"_id": "d18195", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d18196", "text": "def filter_float(n: Node, query: str) -> float:\n    \"\"\"\n    Filter and ensure that the returned value is of type int.\n    \"\"\"\n    return _scalariter2item(n, query, float)", "title": ""}
{"_id": "d18197", "text": "def lcm(num1, num2):\n    \"\"\"\n    Find the lowest common multiple of 2 numbers\n\n    :type num1: number\n    :param num1: The first number to find the lcm for\n\n    :type num2: number\n    :param num2: The second number to find the lcm for\n    \"\"\"\n\n    if num1 > num2:\n        bigger = num1\n    else:\n        bigger = num2\n    while True:\n        if bigger % num1 == 0 and bigger % num2 == 0:\n            return bigger\n        bigger += 1", "title": ""}
{"_id": "d18198", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d18199", "text": "def is_up_to_date(outfile, basedatetime):\n        # type: (AnyStr, datetime) -> bool\n        \"\"\"Return true if outfile exists and is no older than base datetime.\"\"\"\n        if os.path.exists(outfile):\n            if os.path.getmtime(outfile) >= basedatetime:\n                return True\n        return False", "title": ""}
{"_id": "d18200", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d18201", "text": "def run_time() -> timedelta:\n    \"\"\"\n\n    :return:\n    \"\"\"\n\n    delta = start_time if start_time else datetime.utcnow()\n    return datetime.utcnow() - delta", "title": ""}
{"_id": "d18202", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d18203", "text": "def negate_mask(mask):\n    \"\"\"Returns the negated mask.\n\n    If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where\n    the original one has non-zero (0).\n\n    :param mask: Input mask\n    :type mask: np.array\n    :return: array of same shape and dtype=int8 as input array\n    :rtype: np.array\n    \"\"\"\n    res = np.ones(mask.shape, dtype=np.int8)\n    res[mask > 0] = 0\n\n    return res", "title": ""}
{"_id": "d18204", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d18205", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d18206", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d18207", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d18208", "text": "def memory_usage():\n    \"\"\"return memory usage of python process in MB\n\n    from\n    http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/\n    psutil is quicker\n\n    >>> isinstance(memory_usage(),float)\n    True\n\n    \"\"\"\n    try:\n        import psutil\n        import os\n    except ImportError:\n        return _memory_usage_ps()\n\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info()[0] / float(2 ** 20)\n    return mem", "title": ""}
{"_id": "d18209", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d18210", "text": "def was_into_check(self) -> bool:\n        \"\"\"\n        Checks if the king of the other side is attacked. Such a position is not\n        valid and could only be reached by an illegal move.\n        \"\"\"\n        king = self.king(not self.turn)\n        return king is not None and self.is_attacked_by(self.turn, king)", "title": ""}
{"_id": "d18211", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18212", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d18213", "text": "def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]:\n    \"\"\"\n    Load and pre-process the images specified with absolute paths.\n\n    :param image_paths: List of images specified with paths.\n    :param image_size: Tuple to resize the image to (Channels, Height, Width)\n    :return: A list of loaded images (numpy arrays).\n    \"\"\"\n    image_size = image_size[1:]  # we do not need the number of channels\n    images = []\n    for image_path in image_paths:\n        images.append(load_preprocess_image(image_path, image_size))\n    return images", "title": ""}
{"_id": "d18214", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d18215", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d18216", "text": "def find_unit_clause(clauses, model):\n    \"\"\"Find a forced assignment if possible from a clause with only 1\n    variable not bound in the model.\n    >>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True})\n    (B, False)\n    \"\"\"\n    for clause in clauses:\n        P, value = unit_clause_assign(clause, model)\n        if P: return P, value\n    return None, None", "title": ""}
{"_id": "d18217", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d18218", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18219", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d18220", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d18221", "text": "def listify(a):\n    \"\"\"\n    Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']\n    \"\"\"\n    if a is None:\n        return []\n    elif not isinstance(a, (tuple, list, np.ndarray)):\n        return [a]\n    return list(a)", "title": ""}
{"_id": "d18222", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d18223", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d18224", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d18225", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d18226", "text": "def get_now_utc_notz_datetime() -> datetime.datetime:\n    \"\"\"\n    Get the UTC time now, but with no timezone information,\n    in :class:`datetime.datetime` format.\n    \"\"\"\n    now = datetime.datetime.utcnow()\n    return now.replace(tzinfo=None)", "title": ""}
{"_id": "d18227", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18228", "text": "def make_dep_graph(depender):\n\t\"\"\"Returns a digraph string fragment based on the passed-in module\n\t\"\"\"\n\tshutit_global.shutit_global_object.yield_to_draw()\n\tdigraph = ''\n\tfor dependee_id in depender.depends_on:\n\t\tdigraph = (digraph + '\"' + depender.module_id + '\"->\"' + dependee_id + '\";\\n')\n\treturn digraph", "title": ""}
{"_id": "d18229", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d18230", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d18231", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d18232", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18233", "text": "def _find_conda():\n    \"\"\"Find the conda executable robustly across conda versions.\n\n    Returns\n    -------\n    conda : str\n        Path to the conda executable.\n\n    Raises\n    ------\n    IOError\n        If the executable cannot be found in either the CONDA_EXE environment\n        variable or in the PATH.\n\n    Notes\n    -----\n    In POSIX platforms in conda >= 4.4, conda can be set up as a bash function\n    rather than an executable. (This is to enable the syntax\n    ``conda activate env-name``.) In this case, the environment variable\n    ``CONDA_EXE`` contains the path to the conda executable. In other cases,\n    we use standard search for the appropriate name in the PATH.\n\n    See https://github.com/airspeed-velocity/asv/issues/645 for more details.\n    \"\"\"\n    if 'CONDA_EXE' in os.environ:\n        conda = os.environ['CONDA_EXE']\n    else:\n        conda = util.which('conda')\n    return conda", "title": ""}
{"_id": "d18234", "text": "def connect_to_database_odbc_access(self,\n                                        dsn: str,\n                                        autocommit: bool = True) -> None:\n        \"\"\"Connects to an Access database via ODBC, with the DSN\n        prespecified.\"\"\"\n        self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,\n                     dsn=dsn, autocommit=autocommit)", "title": ""}
{"_id": "d18235", "text": "def _find_conda():\n    \"\"\"Find the conda executable robustly across conda versions.\n\n    Returns\n    -------\n    conda : str\n        Path to the conda executable.\n\n    Raises\n    ------\n    IOError\n        If the executable cannot be found in either the CONDA_EXE environment\n        variable or in the PATH.\n\n    Notes\n    -----\n    In POSIX platforms in conda >= 4.4, conda can be set up as a bash function\n    rather than an executable. (This is to enable the syntax\n    ``conda activate env-name``.) In this case, the environment variable\n    ``CONDA_EXE`` contains the path to the conda executable. In other cases,\n    we use standard search for the appropriate name in the PATH.\n\n    See https://github.com/airspeed-velocity/asv/issues/645 for more details.\n    \"\"\"\n    if 'CONDA_EXE' in os.environ:\n        conda = os.environ['CONDA_EXE']\n    else:\n        conda = util.which('conda')\n    return conda", "title": ""}
{"_id": "d18236", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d18237", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d18238", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d18239", "text": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "title": ""}
{"_id": "d18240", "text": "def get_now_utc_notz_datetime() -> datetime.datetime:\n    \"\"\"\n    Get the UTC time now, but with no timezone information,\n    in :class:`datetime.datetime` format.\n    \"\"\"\n    now = datetime.datetime.utcnow()\n    return now.replace(tzinfo=None)", "title": ""}
{"_id": "d18241", "text": "def replace_in_list(stringlist: Iterable[str],\n                    replacedict: Dict[str, str]) -> List[str]:\n    \"\"\"\n    Returns a list produced by applying :func:`multiple_replace` to every\n    string in ``stringlist``.\n\n    Args:\n        stringlist: list of source strings\n        replacedict: dictionary mapping \"original\" to \"replacement\" strings\n\n    Returns:\n        list of final strings\n\n    \"\"\"\n    newlist = []\n    for fromstring in stringlist:\n        newlist.append(multiple_replace(fromstring, replacedict))\n    return newlist", "title": ""}
{"_id": "d18242", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18243", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d18244", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d18245", "text": "def set_range(self, min_val, max_val):\n        \"\"\"Set the range of the colormap to [*min_val*, *max_val*]\n        \"\"\"\n        if min_val > max_val:\n            max_val, min_val = min_val, max_val\n        self.values = (((self.values * 1.0 - self.values.min()) /\n                        (self.values.max() - self.values.min()))\n                       * (max_val - min_val) + min_val)", "title": ""}
{"_id": "d18246", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d18247", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d18248", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d18249", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d18250", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d18251", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d18252", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d18253", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d18254", "text": "def _create_empty_array(self, frames, always_2d, dtype):\n        \"\"\"Create an empty array with appropriate shape.\"\"\"\n        import numpy as np\n        if always_2d or self.channels > 1:\n            shape = frames, self.channels\n        else:\n            shape = frames,\n        return np.empty(shape, dtype, order='C')", "title": ""}
{"_id": "d18255", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d18256", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d18257", "text": "def dict_of_sets_add(dictionary, key, value):\n    # type: (DictUpperBound, Any, Any) -> None\n    \"\"\"Add value to a set 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 set in dictionary\n\n    Returns:\n        None\n\n    \"\"\"\n    set_objs = dictionary.get(key, set())\n    set_objs.add(value)\n    dictionary[key] = set_objs", "title": ""}
{"_id": "d18258", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d18259", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18260", "text": "def from_uuid(value: uuid.UUID) -> ulid.ULID:\n    \"\"\"\n    Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~uuid.UUID` value.\n\n    :param value: UUIDv4 value\n    :type value: :class:`~uuid.UUID`\n    :return: ULID from UUID value\n    :rtype: :class:`~ulid.ulid.ULID`\n    \"\"\"\n    return ulid.ULID(value.bytes)", "title": ""}
{"_id": "d18261", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d18262", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d18263", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d18264", "text": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "title": ""}
{"_id": "d18265", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d18266", "text": "def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:\n    \"\"\" Creates a mapping from indices to labels. \"\"\"\n\n    return {index: label for index, label in\n            enumerate([\"pad\"] + sorted(list(labels)))}", "title": ""}
{"_id": "d18267", "text": "def get_terminal_width():\n    \"\"\" -> #int width of the terminal window \"\"\"\n    # http://www.brandonrubin.me/2014/03/18/python-snippet-get-terminal-width/\n    command = ['tput', 'cols']\n    try:\n        width = int(subprocess.check_output(command))\n    except OSError as e:\n        print(\n            \"Invalid Command '{0}': exit status ({1})\".format(\n                command[0], e.errno))\n    except subprocess.CalledProcessError as e:\n        print(\n            \"'{0}' returned non-zero exit status: ({1})\".format(\n                command, e.returncode))\n    else:\n        return width", "title": ""}
{"_id": "d18268", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d18269", "text": "def flush(self):\n        \"\"\"\n        Ensure all logging output has been flushed\n        \"\"\"\n        if len(self._buffer) > 0:\n            self.logger.log(self.level, self._buffer)\n            self._buffer = str()", "title": ""}
{"_id": "d18270", "text": "def _brief_print_list(lst, limit=7):\n    \"\"\"Print at most `limit` elements of list.\"\"\"\n    lst = list(lst)\n    if len(lst) > limit:\n        return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n            _brief_print_list(lst[-limit//2:], limit)\n    return ', '.join([\"'%s'\"%str(i) for i in lst])", "title": ""}
{"_id": "d18271", "text": "def assert_or_raise(stmt: bool, exception: Exception,\n                    *exception_args, **exception_kwargs) -> None:\n  \"\"\"\n  If the statement is false, raise the given exception.\n  \"\"\"\n  if not stmt:\n    raise exception(*exception_args, **exception_kwargs)", "title": ""}
{"_id": "d18272", "text": "def strip_codes(s: Any) -> str:\n    \"\"\" Strip all color codes from a string.\n        Returns empty string for \"falsey\" inputs.\n    \"\"\"\n    return codepat.sub('', str(s) if (s or (s == 0)) else '')", "title": ""}
{"_id": "d18273", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d18274", "text": "def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:\n    \"\"\"return the higher parent which is not an AssignName, Tuple or List node\n    \"\"\"\n    while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)):\n        node = node.parent\n    return node", "title": ""}
{"_id": "d18275", "text": "def columns_equal(a: Column, b: Column) -> bool:\n    \"\"\"\n    Are two SQLAlchemy columns are equal? Checks based on:\n\n    - column ``name``\n    - column ``type`` (see :func:`column_types_equal`)\n    - ``nullable``\n    \"\"\"\n    return (\n        a.name == b.name and\n        column_types_equal(a.type, b.type) and\n        a.nullable == b.nullable\n    )", "title": ""}
{"_id": "d18276", "text": "def PrintIndented(self, file, ident, code):\n        \"\"\"Takes an array, add indentation to each entry and prints it.\"\"\"\n        for entry in code:\n            print >>file, '%s%s' % (ident, entry)", "title": ""}
{"_id": "d18277", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d18278", "text": "def sample_normal(mean, var, rng):\n    \"\"\"Sample from independent normal distributions\n\n    Each element is an independent normal distribution.\n\n    Parameters\n    ----------\n    mean : numpy.ndarray\n      Means of the normal distribution. Shape --> (batch_num, sample_dim)\n    var : numpy.ndarray\n      Variance of the normal distribution. Shape --> (batch_num, sample_dim)\n    rng : numpy.random.RandomState\n\n    Returns\n    -------\n    ret : numpy.ndarray\n       The sampling result. Shape --> (batch_num, sample_dim)\n    \"\"\"\n    ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean\n    return ret", "title": ""}
{"_id": "d18279", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18280", "text": "def hex_to_int(value):\n    \"\"\"\n    Convert hex string like \"\\x0A\\xE3\" to 2787.\n    \"\"\"\n    if version_info.major >= 3:\n        return int.from_bytes(value, \"big\")\n    return int(value.encode(\"hex\"), 16)", "title": ""}
{"_id": "d18281", "text": "def is_quoted(arg: str) -> bool:\n    \"\"\"\n    Checks if a string is quoted\n    :param arg: the string being checked for quotes\n    :return: True if a string is quoted\n    \"\"\"\n    return len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES", "title": ""}
{"_id": "d18282", "text": "def get_system_flags() -> FrozenSet[Flag]:\n    \"\"\"Return the set of implemented system flags.\"\"\"\n    return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})", "title": ""}
{"_id": "d18283", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d18284", "text": "def get_property_as_float(self, name: str) -> float:\n        \"\"\"Return the value of a float property.\n\n        :return: The property value (float).\n\n        Raises exception if property with name doesn't exist.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes\n        \"\"\"\n        return float(self.__instrument.get_property(name))", "title": ""}
{"_id": "d18285", "text": "def rollapply(data, window, fn):\n    \"\"\"\n    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\n    \"\"\"\n    res = data.copy()\n    res[:] = np.nan\n    n = len(data)\n\n    if window > n:\n        return res\n\n    for i in range(window - 1, n):\n        res.iloc[i] = fn(data.iloc[i - window + 1:i + 1])\n\n    return res", "title": ""}
{"_id": "d18286", "text": "def is_unitary(matrix: np.ndarray) -> bool:\n    \"\"\"\n    A helper function that checks if a matrix is unitary.\n\n    :param matrix: a matrix to test unitarity of\n    :return: true if and only if matrix is unitary\n    \"\"\"\n    rows, cols = matrix.shape\n    if rows != cols:\n        return False\n    return np.allclose(np.eye(rows), matrix.dot(matrix.T.conj()))", "title": ""}
{"_id": "d18287", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d18288", "text": "def get_table_names_from_metadata(metadata: MetaData) -> List[str]:\n    \"\"\"\n    Returns all database table names found in an SQLAlchemy :class:`MetaData`\n    object.\n    \"\"\"\n    return [table.name for table in metadata.tables.values()]", "title": ""}
{"_id": "d18289", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d18290", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d18291", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d18292", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d18293", "text": "def binary(length):\n    \"\"\"\n        returns a a random string that represent a binary representation\n\n    :param length: number of bits\n    \"\"\"\n    num = randint(1, 999999)\n    mask = '0' * length\n    return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]", "title": ""}
{"_id": "d18294", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d18295", "text": "def clear(self) -> None:\n        \"\"\"Resets all headers and content for this response.\"\"\"\n        self._headers = httputil.HTTPHeaders(\n            {\n                \"Server\": \"TornadoServer/%s\" % tornado.version,\n                \"Content-Type\": \"text/html; charset=UTF-8\",\n                \"Date\": httputil.format_timestamp(time.time()),\n            }\n        )\n        self.set_default_headers()\n        self._write_buffer = []  # type: List[bytes]\n        self._status_code = 200\n        self._reason = httputil.responses[200]", "title": ""}
{"_id": "d18296", "text": "def is_closing(self) -> bool:\n        \"\"\"Return ``True`` if this connection is closing.\n\n        The connection is considered closing if either side has\n        initiated its closing handshake or if the stream has been\n        shut down uncleanly.\n        \"\"\"\n        return self.stream.closed() or self.client_terminated or self.server_terminated", "title": ""}
{"_id": "d18297", "text": "def copy_session(session: requests.Session) -> requests.Session:\n    \"\"\"Duplicates a requests.Session.\"\"\"\n    new = requests.Session()\n    new.cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies))\n    new.headers = session.headers.copy()\n    return new", "title": ""}
{"_id": "d18298", "text": "def listify(a):\n    \"\"\"\n    Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']\n    \"\"\"\n    if a is None:\n        return []\n    elif not isinstance(a, (tuple, list, np.ndarray)):\n        return [a]\n    return list(a)", "title": ""}
{"_id": "d18299", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d18300", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d18301", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d18302", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d18303", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d18304", "text": "def check_consistent_length(*arrays):\n    \"\"\"Check that all arrays have consistent first dimensions.\n\n    Checks whether all objects in arrays have the same shape or length.\n\n    Parameters\n    ----------\n    arrays : list or tuple of input objects.\n        Objects that will be checked for consistent length.\n    \"\"\"\n\n    uniques = np.unique([_num_samples(X) for X in arrays if X is not None])\n    if len(uniques) > 1:\n        raise ValueError(\"Found arrays with inconsistent numbers of samples: %s\"\n                         % str(uniques))", "title": ""}
{"_id": "d18305", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d18306", "text": "def _cleanup(path: str) -> None:\n    \"\"\"Cleanup temporary directory.\"\"\"\n    if os.path.isdir(path):\n        shutil.rmtree(path)", "title": ""}
{"_id": "d18307", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d18308", "text": "def __getattr__(self, item: str) -> Callable:\n        \"\"\"Get a callable that sends the actual API request internally.\"\"\"\n        return functools.partial(self.call_action, item)", "title": ""}
{"_id": "d18309", "text": "def calculate_single_tanimoto_set_distances(target: Iterable[X], dict_of_sets: Mapping[Y, Set[X]]) -> Mapping[Y, float]:\n    \"\"\"Return a dictionary of distances keyed by the keys in the given dict.\n\n    Distances are calculated based on pairwise tanimoto similarity of the sets contained\n\n    :param set target: A set\n    :param dict_of_sets: A dict of {x: set of y}\n    :type dict_of_sets: dict\n    :return: A similarity dicationary based on the set overlap (tanimoto) score between the target set and the sets in\n            dos\n    :rtype: dict\n    \"\"\"\n    target_set = set(target)\n\n    return {\n        k: tanimoto_set_similarity(target_set, s)\n        for k, s in dict_of_sets.items()\n    }", "title": ""}
{"_id": "d18310", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d18311", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d18312", "text": "def quaternion_imag(quaternion):\n    \"\"\"Return imaginary part of quaternion.\n\n    >>> quaternion_imag([3, 0, 1, 2])\n    array([ 0.,  1.,  2.])\n\n    \"\"\"\n    return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)", "title": ""}
{"_id": "d18313", "text": "def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:\n    \"\"\"\n    Within the dictionary ``d``, find a key that matches (in case-insensitive\n    fashion) the key ``k``, and return it (or ``None`` if there isn't one).\n    \"\"\"\n    for key in d.keys():\n        if k.lower() == key.lower():\n            return key\n    return None", "title": ""}
{"_id": "d18314", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d18315", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d18316", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d18317", "text": "def snake_case(a_string):\n    \"\"\"Returns a snake cased version of a string.\n\n    :param a_string: any :class:`str` object.\n\n    Usage:\n        >>> snake_case('FooBar')\n        \"foo_bar\"\n    \"\"\"\n\n    partial = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', a_string)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', partial).lower()", "title": ""}
{"_id": "d18318", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d18319", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d18320", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d18321", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d18322", "text": "def warn_if_nans_exist(X):\n    \"\"\"Warn if nans exist in a numpy array.\"\"\"\n    null_count = count_rows_with_nans(X)\n    total = len(X)\n    percent = 100 * null_count / total\n\n    if null_count > 0:\n        warning_message = \\\n            'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n            'complete rows will be plotted.'.format(null_count, total, percent)\n        warnings.warn(warning_message, DataWarning)", "title": ""}
{"_id": "d18323", "text": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "title": ""}
{"_id": "d18324", "text": "def __next__(self):\n        \"\"\"\n        :return: int\n        \"\"\"\n        self.current += 1\n        if self.current > self.total:\n            raise StopIteration\n        else:\n            return self.iterable[self.current - 1]", "title": ""}
{"_id": "d18325", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d18326", "text": "def join_states(*states: State) -> State:\n    \"\"\"Join two state vectors into a larger qubit state\"\"\"\n    vectors = [ket.vec for ket in states]\n    vec = reduce(outer_product, vectors)\n    return State(vec.tensor, vec.qubits)", "title": ""}
{"_id": "d18327", "text": "def blk_coverage_1d(blk, size):\n    \"\"\"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)\n\n    \"\"\"\n    rem = size % blk\n    maxpix = size - rem\n    return maxpix, rem", "title": ""}
{"_id": "d18328", "text": "def cpu_count() -> int:\n    \"\"\"Returns the number of processors on this machine.\"\"\"\n    if multiprocessing is None:\n        return 1\n    try:\n        return multiprocessing.cpu_count()\n    except NotImplementedError:\n        pass\n    try:\n        return os.sysconf(\"SC_NPROCESSORS_CONF\")\n    except (AttributeError, ValueError):\n        pass\n    gen_log.error(\"Could not detect number of processors; assuming 1\")\n    return 1", "title": ""}
{"_id": "d18329", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d18330", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d18331", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d18332", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d18333", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d18334", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d18335", "text": "def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity.\"\"\"\n    a, b = set(x), set(y)\n    union = a | b\n\n    if not union:\n        return 0.0\n\n    return len(a & b) / len(union)", "title": ""}
{"_id": "d18336", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d18337", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d18338", "text": "def is_up_to_date(outfile, basedatetime):\n        # type: (AnyStr, datetime) -> bool\n        \"\"\"Return true if outfile exists and is no older than base datetime.\"\"\"\n        if os.path.exists(outfile):\n            if os.path.getmtime(outfile) >= basedatetime:\n                return True\n        return False", "title": ""}
{"_id": "d18339", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d18340", "text": "def _parse_date(string: str) -> datetime.date:\n    \"\"\"Parse an ISO format date (YYYY-mm-dd).\n\n    >>> _parse_date('1990-01-02')\n    datetime.date(1990, 1, 2)\n    \"\"\"\n    return datetime.datetime.strptime(string, '%Y-%m-%d').date()", "title": ""}
{"_id": "d18341", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d18342", "text": "def is_rate_limited(response):\n        \"\"\"\n        Checks if the response has been rate limited by CARTO APIs\n\n        :param response: The response rate limited by CARTO APIs\n        :type response: requests.models.Response class\n\n        :return: Boolean\n        \"\"\"\n        if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and\n                int(response.headers['Retry-After']) >= 0):\n            return True\n\n        return False", "title": ""}
{"_id": "d18343", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d18344", "text": "def has_changed (filename):\n    \"\"\"Check if filename has changed since the last check. If this\n    is the first check, assume the file is changed.\"\"\"\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]", "title": ""}
{"_id": "d18345", "text": "def shape(self) -> Tuple[int, ...]:\n        \"\"\"Shape of histogram's data.\n\n        Returns\n        -------\n        One-element tuple with the number of bins along each axis.\n        \"\"\"\n        return tuple(bins.bin_count for bins in self._binnings)", "title": ""}
{"_id": "d18346", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d18347", "text": "def header_status(header):\n    \"\"\"Parse HTTP status line, return status (int) and reason.\"\"\"\n    status_line = header[:header.find('\\r')]\n    # 'HTTP/1.1 200 OK' -> (200, 'OK')\n    fields = status_line.split(None, 2)\n    return int(fields[1]), fields[2]", "title": ""}
{"_id": "d18348", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d18349", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d18350", "text": "def array_to_npy(array_like):  # type: (np.array or Iterable or int or float) -> object\n    \"\"\"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.\n    \"\"\"\n    buffer = BytesIO()\n    np.save(buffer, array_like)\n    return buffer.getvalue()", "title": ""}
{"_id": "d18351", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d18352", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d18353", "text": "def indent(text: str, num: int = 2) -> str:\n    \"\"\"Indent a piece of text.\"\"\"\n    lines = text.splitlines()\n    return \"\\n\".join(indent_iterable(lines, num=num))", "title": ""}
{"_id": "d18354", "text": "def percent_of(percent, whole):\n    \"\"\"Calculates the value of a percent of a number\n    ie: 5% of 20 is what --> 1\n    \n    Args:\n        percent (float): The percent of a number\n        whole (float): The whole of the number\n        \n    Returns:\n        float: The value of a percent\n        \n    Example:\n    >>> percent_of(25, 100)\n    25.0\n    >>> percent_of(5, 20)\n    1.0\n    \n    \"\"\"\n    percent = float(percent)\n    whole = float(whole)\n    return (percent * whole) / 100", "title": ""}
{"_id": "d18355", "text": "def guess_mimetype(filename):\n    \"\"\"Guesses the mimetype of a file based on the given ``filename``.\n\n    .. code-block:: python\n\n        >>> guess_mimetype('example.txt')\n        'text/plain'\n        >>> guess_mimetype('/foo/bar/example')\n        'application/octet-stream'\n\n    Parameters\n    ----------\n    filename : str\n        The file name or path for which the mimetype is to be guessed\n    \"\"\"\n    fn = os.path.basename(filename)\n    return mimetypes.guess_type(fn)[0] or 'application/octet-stream'", "title": ""}
{"_id": "d18356", "text": "def enum_mark_last(iterable, start=0):\n    \"\"\"\n    Returns a generator over iterable that tells whether the current item is the last one.\n    Usage:\n        >>> iterable = range(10)\n        >>> for index, is_last, item in enum_mark_last(iterable):\n        >>>     print(index, item, end='\\n' if is_last else ', ')\n    \"\"\"\n    it = iter(iterable)\n    count = start\n    try:\n        last = next(it)\n    except StopIteration:\n        return\n    for val in it:\n        yield count, False, last\n        last = val\n        count += 1\n    yield count, True, last", "title": ""}
{"_id": "d18357", "text": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "title": ""}
{"_id": "d18358", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18359", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d18360", "text": "def get_tokens(line: str) -> Iterator[str]:\n    \"\"\"\n    Yields tokens from input string.\n\n    :param line: Input string.\n    :return: Iterator over tokens.\n    \"\"\"\n    for token in line.rstrip().split():\n        if len(token) > 0:\n            yield token", "title": ""}
{"_id": "d18361", "text": "def getElementByWdomId(id: str) -> Optional[WebEventTarget]:\n    \"\"\"Get element with ``wdom_id``.\"\"\"\n    if not id:\n        return None\n    elif id == 'document':\n        return get_document()\n    elif id == 'window':\n        return get_document().defaultView\n    elm = WdomElement._elements_with_wdom_id.get(id)\n    return elm", "title": ""}
{"_id": "d18362", "text": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "title": ""}
{"_id": "d18363", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d18364", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d18365", "text": "def viewport_to_screen_space(framebuffer_size: vec2, point: vec4) -> vec2:\n    \"\"\"Transform point in viewport space to screen space.\"\"\"\n    return (framebuffer_size * point.xy) / point.w", "title": ""}
{"_id": "d18366", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d18367", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d18368", "text": "def is_running(process_id: int) -> bool:\n    \"\"\"\n    Uses the Unix ``ps`` program to see if a process is running.\n    \"\"\"\n    pstr = str(process_id)\n    encoding = sys.getdefaultencoding()\n    s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE)\n    for line in s.stdout:\n        strline = line.decode(encoding)\n        if pstr in strline:\n            return True\n    return False", "title": ""}
{"_id": "d18369", "text": "def datetime_is_iso(date_str):\n    \"\"\"Attempts to parse a date formatted in ISO 8601 format\"\"\"\n    try:\n        if len(date_str) > 10:\n            dt = isodate.parse_datetime(date_str)\n        else:\n            dt = isodate.parse_date(date_str)\n        return True, []\n    except:  # Any error qualifies as not ISO format\n        return False, ['Datetime provided is not in a valid ISO 8601 format']", "title": ""}
{"_id": "d18370", "text": "def index_exists(self, table: str, indexname: str) -> bool:\n        \"\"\"Does an index exist? (Specific to MySQL.)\"\"\"\n        # MySQL:\n        sql = (\"SELECT COUNT(*) FROM information_schema.statistics\"\n               \" WHERE table_name=? AND index_name=?\")\n        row = self.fetchone(sql, table, indexname)\n        return True if row[0] >= 1 else False", "title": ""}
{"_id": "d18371", "text": "def moving_average(arr: np.ndarray, n: int = 3) -> np.ndarray:\n    \"\"\" Calculate the moving overage over an array.\n\n    Algorithm from: https://stackoverflow.com/a/14314054\n\n    Args:\n        arr (np.ndarray): Array over which to calculate the moving average.\n        n (int): Number of elements over which to calculate the moving average. Default: 3\n    Returns:\n        np.ndarray: Moving average calculated over n.\n    \"\"\"\n    ret = np.cumsum(arr, dtype=float)\n    ret[n:] = ret[n:] - ret[:-n]\n    return ret[n - 1:] / n", "title": ""}
{"_id": "d18372", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d18373", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d18374", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d18375", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d18376", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d18377", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d18378", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d18379", "text": "def right_replace(string, old, new, count=1):\n    \"\"\"\n    Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.\n    For example::\n\n        right_replace('one_two_two', 'two', 'three') -> 'one_two_three'\n    \"\"\"\n    if not string:\n        return string\n    return new.join(string.rsplit(old, count))", "title": ""}
{"_id": "d18380", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d18381", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d18382", "text": "def are_token_parallel(sequences: Sequence[Sized]) -> bool:\n    \"\"\"\n    Returns True if all sequences in the list have the same length.\n    \"\"\"\n    if not sequences or len(sequences) == 1:\n        return True\n    return all(len(s) == len(sequences[0]) for s in sequences)", "title": ""}
{"_id": "d18383", "text": "def exclude_from(l, containing = [], equal_to = []):\n    \"\"\"Exclude elements in list l containing any elements from list ex.\n    Example:\n        >>> l = ['bob', 'r', 'rob\\r', '\\r\\nrobert']\n        >>> containing = ['\\n', '\\r']\n        >>> equal_to = ['r']\n        >>> exclude_from(l, containing, equal_to)\n        ['bob']\n    \"\"\"\n      \n    cont = lambda li: any(c in li for c in containing)\n    eq = lambda li: any(e == li for e in equal_to)\n    return [li for li in l if not (cont(li) or eq(li))]", "title": ""}
{"_id": "d18384", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d18385", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d18386", "text": "def clean_all_buckets(self):\n        \"\"\"\n        Removes all buckets from all hashes and their content.\n        \"\"\"\n        bucket_keys = self.redis_object.keys(pattern='nearpy_*')\n        if len(bucket_keys) > 0:\n            self.redis_object.delete(*bucket_keys)", "title": ""}
{"_id": "d18387", "text": "async def cursor(self) -> Cursor:\n        \"\"\"Create an aiosqlite cursor wrapping a sqlite3 cursor object.\"\"\"\n        return Cursor(self, await self._execute(self._conn.cursor))", "title": ""}
{"_id": "d18388", "text": "def rl_get_point() -> int:  # pragma: no cover\n    \"\"\"\n    Returns the offset of the current cursor position in rl_line_buffer\n    \"\"\"\n    if rl_type == RlType.GNU:\n        return ctypes.c_int.in_dll(readline_lib, \"rl_point\").value\n\n    elif rl_type == RlType.PYREADLINE:\n        return readline.rl.mode.l_buffer.point\n\n    else:\n        return 0", "title": ""}
{"_id": "d18389", "text": "def to_dict(cls):\n        \"\"\"Make dictionary version of enumerated class.\n\n        Dictionary created this way can be used with def_num.\n\n        Returns:\n          A dict (name) -> number\n        \"\"\"\n        return dict((item.name, item.number) for item in iter(cls))", "title": ""}
{"_id": "d18390", "text": "def is_valid(cls, arg):\n        \"\"\"Return True if arg is valid value for the class.  If the string\n        value is wrong for the enumeration, the encoding will fail.\n        \"\"\"\n        return (isinstance(arg, (int, long)) and (arg >= 0)) or \\\n            isinstance(arg, basestring)", "title": ""}
{"_id": "d18391", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d18392", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d18393", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d18394", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d18395", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18396", "text": "def replaceStrs(s, *args):\n    r\"\"\"Replace all ``(frm, to)`` tuples in `args` in string `s`.\n\n    >>> replaceStrs(\"nothing is better than warm beer\",\n    ...             ('nothing','warm beer'), ('warm beer','nothing'))\n    'warm beer is better than nothing'\n\n    \"\"\"\n    if args == (): return s\n    mapping = dict((frm, to) for frm, to in args)\n    return re.sub(\"|\".join(map(re.escape, mapping.keys())),\n                  lambda match:mapping[match.group(0)], s)", "title": ""}
{"_id": "d18397", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d18398", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18399", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d18400", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18401", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d18402", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d18403", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d18404", "text": "def remove_links(text):\n    \"\"\"\n    Helper function to remove the links from the input text\n\n    Args:\n        text (str): A string\n\n    Returns:\n        str: the same text, but with any substring that matches the regex\n        for a link removed and replaced with a space\n\n    Example:\n        >>> from tweet_parser.getter_methods.tweet_text import remove_links\n        >>> text = \"lorem ipsum dolor https://twitter.com/RobotPrincessFi\"\n        >>> remove_links(text)\n        'lorem ipsum dolor  '\n    \"\"\"\n    tco_link_regex = re.compile(\"https?://t.co/[A-z0-9].*\")\n    generic_link_regex = re.compile(\"(https?://)?(\\w*[.]\\w+)+([/?=&]+\\w+)*\")\n    remove_tco = re.sub(tco_link_regex, \" \", text)\n    remove_generic = re.sub(generic_link_regex, \" \", remove_tco)\n    return remove_generic", "title": ""}
{"_id": "d18405", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d18406", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d18407", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d18408", "text": "def looks_like_url(url):\n    \"\"\" 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\n    \"\"\"\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", "title": ""}
{"_id": "d18409", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d18410", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d18411", "text": "def process_literal_param(self, value: Optional[List[int]],\n                              dialect: Dialect) -> str:\n        \"\"\"Convert things on the way from Python to the database.\"\"\"\n        retval = self._intlist_to_dbstr(value)\n        return retval", "title": ""}
{"_id": "d18412", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d18413", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d18414", "text": "def validate_django_compatible_with_python():\n    \"\"\"\n    Verify Django 1.11 is present if Python 2.7 is active\n\n    Installation of pinax-cli requires the correct version of Django for\n    the active Python version. If the developer subsequently changes\n    the Python version the installed Django may no longer be compatible.\n    \"\"\"\n    python_version = sys.version[:5]\n    django_version = django.get_version()\n    if sys.version_info == (2, 7) and django_version >= \"2\":\n        click.BadArgumentUsage(\"Please install Django v1.11 for Python {}, or switch to Python >= v3.4\".format(python_version))", "title": ""}
{"_id": "d18415", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d18416", "text": "def SwitchToThisWindow(handle: int) -> None:\n    \"\"\"\n    SwitchToThisWindow from Win32.\n    handle: int, the handle of a native window.\n    \"\"\"\n    ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)", "title": ""}
{"_id": "d18417", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d18418", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18419", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d18420", "text": "def dict_of_sets_add(dictionary, key, value):\n    # type: (DictUpperBound, Any, Any) -> None\n    \"\"\"Add value to a set 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 set in dictionary\n\n    Returns:\n        None\n\n    \"\"\"\n    set_objs = dictionary.get(key, set())\n    set_objs.add(value)\n    dictionary[key] = set_objs", "title": ""}
{"_id": "d18421", "text": "def attrname_to_colname_dict(cls) -> Dict[str, str]:\n    \"\"\"\n    Asks an SQLAlchemy class how its attribute names correspond to database\n    column names.\n\n    Args:\n        cls: SQLAlchemy ORM class\n\n    Returns:\n        a dictionary mapping attribute names to database column names\n    \"\"\"\n    attr_col = {}  # type: Dict[str, str]\n    for attrname, column in gen_columns(cls):\n        attr_col[attrname] = column.name\n    return attr_col", "title": ""}
{"_id": "d18422", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d18423", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d18424", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d18425", "text": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "title": ""}
{"_id": "d18426", "text": "def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:\n        \"\"\" Return a json array as a list\n\n        :param value: array\n        :return: array with JsonObj instances removed\n        \"\"\"\n        return [e._as_dict if isinstance(e, JsonObj) else e for e in value]", "title": ""}
{"_id": "d18427", "text": "def strip_codes(s: Any) -> str:\n    \"\"\" Strip all color codes from a string.\n        Returns empty string for \"falsey\" inputs.\n    \"\"\"\n    return codepat.sub('', str(s) if (s or (s == 0)) else '')", "title": ""}
{"_id": "d18428", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d18429", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d18430", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d18431", "text": "def trade_day(dt, cal='US'):\n    \"\"\"\n    Latest trading day w.r.t given dt\n\n    Args:\n        dt: date of reference\n        cal: trading calendar\n\n    Returns:\n        pd.Timestamp: last trading day\n\n    Examples:\n        >>> trade_day('2018-12-25').strftime('%Y-%m-%d')\n        '2018-12-24'\n    \"\"\"\n    from xone import calendar\n\n    dt = pd.Timestamp(dt).date()\n    return calendar.trading_dates(start=dt - pd.Timedelta('10D'), end=dt, calendar=cal)[-1]", "title": ""}
{"_id": "d18432", "text": "def get_now_utc_notz_datetime() -> datetime.datetime:\n    \"\"\"\n    Get the UTC time now, but with no timezone information,\n    in :class:`datetime.datetime` format.\n    \"\"\"\n    now = datetime.datetime.utcnow()\n    return now.replace(tzinfo=None)", "title": ""}
{"_id": "d18433", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18434", "text": "def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]:\n    \"\"\" Write a numpy array to YAML.\n\n    It registers the array under the tag ``!numpy_array``.\n\n    Use with:\n\n    .. code-block:: python\n\n        >>> yaml = ruamel.yaml.YAML()\n        >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml)\n\n    Note:\n        We cannot use ``yaml.register_class`` because it won't register the proper type.\n        (It would register the type of the class, rather than of `numpy.ndarray`). Instead,\n        we use the above approach to register this method explicitly with the representer.\n    \"\"\"\n    return representer.represent_sequence(\n        \"!numpy_array\",\n        data.tolist()\n    )", "title": ""}
{"_id": "d18435", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d18436", "text": "def looks_like_url(url):\n    \"\"\" 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\n    \"\"\"\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", "title": ""}
{"_id": "d18437", "text": "def clean_all_buckets(self):\n        \"\"\"\n        Removes all buckets from all hashes and their content.\n        \"\"\"\n        bucket_keys = self.redis_object.keys(pattern='nearpy_*')\n        if len(bucket_keys) > 0:\n            self.redis_object.delete(*bucket_keys)", "title": ""}
{"_id": "d18438", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d18439", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d18440", "text": "def get_now_sql_datetime():\n    \"\"\"\n    *A datetime stamp in MySQL format: ``YYYY-MM-DDTHH:MM:SS``*\n\n    **Return:**\n        - ``now`` -- current time and date in MySQL format\n\n    **Usage:**\n        .. code-block:: python \n\n            from fundamentals import times\n            now = times.get_now_sql_datetime()\n            print now\n\n            # OUT: 2016-03-18T11:08:23 \n    \"\"\"\n    ## > IMPORTS ##\n    from datetime import datetime, date, time\n    now = datetime.now()\n    now = now.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\n    return now", "title": ""}
{"_id": "d18441", "text": "def is_end_of_month(self) -> bool:\n        \"\"\" Checks if the date is at the end of the month \"\"\"\n        end_of_month = Datum()\n        # get_end_of_month(value)\n        end_of_month.end_of_month()\n        return self.value == end_of_month.value", "title": ""}
{"_id": "d18442", "text": "def uuid2buid(value):\n    \"\"\"\n    Convert a UUID object to a 22-char BUID string\n\n    >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089')\n    >>> uuid2buid(u)\n    'MyA90vLvQi-usAWNb19wiQ'\n    \"\"\"\n    if six.PY3:  # pragma: no cover\n        return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=')\n    else:\n        return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))", "title": ""}
{"_id": "d18443", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18444", "text": "def suppress_stdout():\n    \"\"\"\n    Context manager that suppresses stdout.\n\n    Examples:\n        >>> with suppress_stdout():\n        ...     print('Test print')\n\n        >>> print('test')\n        test\n\n    \"\"\"\n    save_stdout = sys.stdout\n    sys.stdout = DevNull()\n    yield\n    sys.stdout = save_stdout", "title": ""}
{"_id": "d18445", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d18446", "text": "def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\"\n    Args:\n        x: iterable of strings\n\n    Yields:\n        each string in lower case\n    \"\"\"\n    for string in x:\n        yield string.lower()", "title": ""}
{"_id": "d18447", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d18448", "text": "def remove_links(text):\n    \"\"\"\n    Helper function to remove the links from the input text\n\n    Args:\n        text (str): A string\n\n    Returns:\n        str: the same text, but with any substring that matches the regex\n        for a link removed and replaced with a space\n\n    Example:\n        >>> from tweet_parser.getter_methods.tweet_text import remove_links\n        >>> text = \"lorem ipsum dolor https://twitter.com/RobotPrincessFi\"\n        >>> remove_links(text)\n        'lorem ipsum dolor  '\n    \"\"\"\n    tco_link_regex = re.compile(\"https?://t.co/[A-z0-9].*\")\n    generic_link_regex = re.compile(\"(https?://)?(\\w*[.]\\w+)+([/?=&]+\\w+)*\")\n    remove_tco = re.sub(tco_link_regex, \" \", text)\n    remove_generic = re.sub(generic_link_regex, \" \", remove_tco)\n    return remove_generic", "title": ""}
{"_id": "d18449", "text": "def decode_value(stream):\n    \"\"\"Decode the contents of a value from a serialized stream.\n\n    :param stream: Source data stream\n    :type stream: io.BytesIO\n    :returns: Decoded value\n    :rtype: bytes\n    \"\"\"\n    length = decode_length(stream)\n    (value,) = unpack_value(\">{:d}s\".format(length), stream)\n    return value", "title": ""}
{"_id": "d18450", "text": "def fcast(value: float) -> TensorLike:\n    \"\"\"Cast to float tensor\"\"\"\n    newvalue = tf.cast(value, FTYPE)\n    if DEVICE == 'gpu':\n        newvalue = newvalue.gpu()  # Why is this needed?  # pragma: no cover\n    return newvalue", "title": ""}
{"_id": "d18451", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d18452", "text": "def check_valid(number, input_base=10):\n    \"\"\"\n    Checks if there is an invalid digit in the input number.\n\n    Args:\n        number: An number in the following form:\n            (int, int, int, ... , '.' , int, int, int)\n            (iterable container) containing positive integers of the input base\n        input_base(int): The base of the input number.\n\n    Returns:\n        bool, True if all digits valid, else False.\n\n    Examples:\n        >>> check_valid((1,9,6,'.',5,1,6), 12)\n        True\n        >>> check_valid((8,1,15,9), 15)\n        False\n    \"\"\"\n    for n in number:\n        if n in (\".\", \"[\", \"]\"):\n            continue\n        elif n >= input_base:\n            if n == 1 and input_base == 1:\n                continue\n            else:\n                return False\n    return True", "title": ""}
{"_id": "d18453", "text": "def ResetConsoleColor() -> bool:\n    \"\"\"\n    Reset to the default text color on console window.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    if sys.stdout:\n        sys.stdout.flush()\n    bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))", "title": ""}
{"_id": "d18454", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d18455", "text": "def upsert_multi(db, collection, object, match_params=None):\n        \"\"\"\n        Wrapper for pymongo.insert_many() and update_many()\n        :param db: db connection\n        :param collection: collection to update\n        :param object: the modifications to apply\n        :param match_params: a query that matches the documents to update\n        :return: ids of inserted/updated document\n        \"\"\"\n        if isinstance(object, list) and len(object) > 0:\n            return str(db[collection].insert_many(object).inserted_ids)\n        elif isinstance(object, dict):\n            return str(db[collection].update_many(match_params, {\"$set\": object}, upsert=False).upserted_id)", "title": ""}
{"_id": "d18456", "text": "def get_language():\n    \"\"\"\n    Wrapper around Django's `get_language` utility.\n    For Django >= 1.8, `get_language` returns None in case no translation is activate.\n    Here we patch this behavior e.g. for back-end functionality requiring access to translated fields\n    \"\"\"\n    from parler import appsettings\n    language = dj_get_language()\n    if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:\n        return appsettings.PARLER_DEFAULT_LANGUAGE_CODE\n    else:\n        return language", "title": ""}
{"_id": "d18457", "text": "def url_concat(url, args):\n    \"\"\"Concatenate url and argument dictionary regardless of whether\n    url has existing query parameters.\n\n    >>> url_concat(\"http://example.com/foo?a=b\", dict(c=\"d\"))\n    'http://example.com/foo?a=b&c=d'\n    \"\"\"\n    if not args: return url\n    if url[-1] not in ('?', '&'):\n        url += '&' if ('?' in url) else '?'\n    return url + urllib.urlencode(args)", "title": ""}
{"_id": "d18458", "text": "def get_system_flags() -> FrozenSet[Flag]:\n    \"\"\"Return the set of implemented system flags.\"\"\"\n    return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})", "title": ""}
{"_id": "d18459", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d18460", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d18461", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d18462", "text": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "title": ""}
{"_id": "d18463", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d18464", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d18465", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d18466", "text": "def process_literal_param(self, value: Optional[List[int]],\n                              dialect: Dialect) -> str:\n        \"\"\"Convert things on the way from Python to the database.\"\"\"\n        retval = self._intlist_to_dbstr(value)\n        return retval", "title": ""}
{"_id": "d18467", "text": "def __rmatmul__(self, other):\n        \"\"\"\n        Matrix multiplication using binary `@` operator in Python>=3.5.\n        \"\"\"\n        return self.T.dot(np.transpose(other)).T", "title": ""}
{"_id": "d18468", "text": "def non_increasing(values):\n    \"\"\"True if values are not increasing.\"\"\"\n    return all(x >= y for x, y in zip(values, values[1:]))", "title": ""}
{"_id": "d18469", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18470", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18471", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d18472", "text": "def codes_get_size(handle, key):\n    # type: (cffi.FFI.CData, str) -> int\n    \"\"\"\n    Get the number of coded value from a key.\n    If several keys of the same name are present, the total sum is returned.\n\n    :param bytes key: the keyword to get the size of\n\n    :rtype: int\n    \"\"\"\n    size = ffi.new('size_t *')\n    _codes_get_size(handle, key.encode(ENC), size)\n    return size[0]", "title": ""}
{"_id": "d18473", "text": "def setup_cache(app: Flask, cache_config) -> Optional[Cache]:\n    \"\"\"Setup the flask-cache on a flask app\"\"\"\n    if cache_config and cache_config.get('CACHE_TYPE') != 'null':\n        return Cache(app, config=cache_config)\n\n    return None", "title": ""}
{"_id": "d18474", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d18475", "text": "def call_fset(self, obj, value) -> None:\n        \"\"\"Store the given custom value and call the setter function.\"\"\"\n        vars(obj)[self.name] = self.fset(obj, value)", "title": ""}
{"_id": "d18476", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d18477", "text": "def src2ast(src: str) -> Expression:\n    \"\"\"Return ast.Expression created from source code given in `src`.\"\"\"\n    try:\n        return ast.parse(src, mode='eval')\n    except SyntaxError:\n        raise ValueError(\"Not a valid expression.\") from None", "title": ""}
{"_id": "d18478", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d18479", "text": "def listify(a):\n    \"\"\"\n    Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']\n    \"\"\"\n    if a is None:\n        return []\n    elif not isinstance(a, (tuple, list, np.ndarray)):\n        return [a]\n    return list(a)", "title": ""}
{"_id": "d18480", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d18481", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d18482", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d18483", "text": "def get_table_names_from_metadata(metadata: MetaData) -> List[str]:\n    \"\"\"\n    Returns all database table names found in an SQLAlchemy :class:`MetaData`\n    object.\n    \"\"\"\n    return [table.name for table in metadata.tables.values()]", "title": ""}
{"_id": "d18484", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d18485", "text": "def signed_distance(mesh, points):\n    \"\"\"\n    Find the signed distance from a mesh to a list of points.\n\n    * Points OUTSIDE the mesh will have NEGATIVE distance\n    * Points within tol.merge of the surface will have POSITIVE distance\n    * Points INSIDE the mesh will have POSITIVE distance\n\n    Parameters\n    -----------\n    mesh   : Trimesh object\n    points : (n,3) float, list of points in space\n\n    Returns\n    ----------\n    signed_distance : (n,3) float, signed distance from point to mesh\n    \"\"\"\n    # make sure we have a numpy array\n    points = np.asanyarray(points, dtype=np.float64)\n\n    # find the closest point on the mesh to the queried points\n    closest, distance, triangle_id = closest_point(mesh, points)\n\n    # we only care about nonzero distances\n    nonzero = distance > tol.merge\n\n    if not nonzero.any():\n        return distance\n\n    inside = mesh.ray.contains_points(points[nonzero])\n    sign = (inside.astype(int) * 2) - 1\n\n    # apply sign to previously computed distance\n    distance[nonzero] *= sign\n\n    return distance", "title": ""}
{"_id": "d18486", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d18487", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d18488", "text": "def replace_in_list(stringlist: Iterable[str],\n                    replacedict: Dict[str, str]) -> List[str]:\n    \"\"\"\n    Returns a list produced by applying :func:`multiple_replace` to every\n    string in ``stringlist``.\n\n    Args:\n        stringlist: list of source strings\n        replacedict: dictionary mapping \"original\" to \"replacement\" strings\n\n    Returns:\n        list of final strings\n\n    \"\"\"\n    newlist = []\n    for fromstring in stringlist:\n        newlist.append(multiple_replace(fromstring, replacedict))\n    return newlist", "title": ""}
{"_id": "d18489", "text": "def get_creation_date(\n            self,\n            bucket: str,\n            key: str,\n    ) -> datetime.datetime:\n        \"\"\"\n        Retrieves the creation date for a given key in a given bucket.\n        :param bucket: the bucket the object resides in.\n        :param key: the key of the object for which the creation date is being retrieved.\n        :return: the creation date\n        \"\"\"\n        blob_obj = self._get_blob_obj(bucket, key)\n        return blob_obj.time_created", "title": ""}
{"_id": "d18490", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18491", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d18492", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18493", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d18494", "text": "def safe_pow(base, exp):\n    \"\"\"safe version of pow\"\"\"\n    if exp > MAX_EXPONENT:\n        raise RuntimeError(\"Invalid exponent, max exponent is {}\".format(MAX_EXPONENT))\n    return base ** exp", "title": ""}
{"_id": "d18495", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d18496", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d18497", "text": "def is_empty_shape(sh: ShExJ.Shape) -> bool:\n        \"\"\" Determine whether sh has any value \"\"\"\n        return sh.closed is None and sh.expression is None and sh.extra is None and \\\n            sh.semActs is None", "title": ""}
{"_id": "d18498", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d18499", "text": "def get_day_name(self) -> str:\n        \"\"\" Returns the day name \"\"\"\n        weekday = self.value.isoweekday() - 1\n        return calendar.day_name[weekday]", "title": ""}
{"_id": "d18500", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d18501", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d18502", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d18503", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d18504", "text": "def MoveWindow(handle: int, x: int, y: int, width: int, height: int, repaint: int = 1) -> bool:\n    \"\"\"\n    MoveWindow from Win32.\n    handle: int, the handle of a native window.\n    x: int.\n    y: int.\n    width: int.\n    height: int.\n    repaint: int, use 1 or 0.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    return bool(ctypes.windll.user32.MoveWindow(ctypes.c_void_p(handle), x, y, width, height, repaint))", "title": ""}
{"_id": "d18505", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d18506", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d18507", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d18508", "text": "def to_0d_array(value: Any) -> np.ndarray:\n    \"\"\"Given a value, wrap it in a 0-D numpy.ndarray.\n    \"\"\"\n    if np.isscalar(value) or (isinstance(value, np.ndarray) and\n                              value.ndim == 0):\n        return np.array(value)\n    else:\n        return to_0d_object_array(value)", "title": ""}
{"_id": "d18509", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d18510", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d18511", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d18512", "text": "def clip_to_seconds(m: Union[int, pd.Series]) -> Union[int, pd.Series]:\n        \"\"\"Clips UTC datetime in nanoseconds to seconds.\"\"\"\n        return m // pd.Timedelta(1, unit='s').value", "title": ""}
{"_id": "d18513", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d18514", "text": "def setlocale(name):\n    \"\"\"\n    Context manager with threading lock for set locale on enter, and set it\n    back to original state on exit.\n\n    ::\n\n        >>> with setlocale(\"C\"):\n        ...     ...\n    \"\"\"\n    with LOCALE_LOCK:\n        old_locale = locale.setlocale(locale.LC_ALL)\n        try:\n            yield locale.setlocale(locale.LC_ALL, name)\n        finally:\n            locale.setlocale(locale.LC_ALL, old_locale)", "title": ""}
{"_id": "d18515", "text": "def to_javascript_(self, table_name: str=\"data\") -> str:\n        \"\"\"Convert the main dataframe to javascript code\n\n        :param table_name: javascript variable name, defaults to \"data\"\n        :param table_name: str, optional\n        :return: a javascript constant with the data\n        :rtype: str\n\n        :example: ``ds.to_javastript_(\"myconst\")``\n        \"\"\"\n        try:\n            renderer = pytablewriter.JavaScriptTableWriter\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 javascript code\")", "title": ""}
{"_id": "d18516", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18517", "text": "def write_text(filename: str, text: str) -> None:\n    \"\"\"\n    Writes text to a file.\n    \"\"\"\n    with open(filename, 'w') as f:  # type: TextIO\n        print(text, file=f)", "title": ""}
{"_id": "d18518", "text": "def isfile_notempty(inputfile: str) -> bool:\n        \"\"\"Check if the input filename with path is a file and is not empty.\"\"\"\n        try:\n            return isfile(inputfile) and getsize(inputfile) > 0\n        except TypeError:\n            raise TypeError('inputfile is not a valid type')", "title": ""}
{"_id": "d18519", "text": "def availability_pdf() -> bool:\n    \"\"\"\n    Is a PDF-to-text tool available?\n    \"\"\"\n    pdftotext = tools['pdftotext']\n    if pdftotext:\n        return True\n    elif pdfminer:\n        log.warning(\"PDF conversion: pdftotext missing; \"\n                    \"using pdfminer (less efficient)\")\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18520", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18521", "text": "def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:\n        \"\"\"Executes SQL; returns list of first values of each row.\"\"\"\n        rows = self.fetchall(sql, *args)\n        return [row[0] for row in rows]", "title": ""}
{"_id": "d18522", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d18523", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d18524", "text": "def name_is_valid(name):\n    \"\"\"Return True if the dataset name is valid.\n\n    The name can only be 80 characters long.\n    Valid characters: Alpha numeric characters [0-9a-zA-Z]\n    Valid special characters: - _ .\n    \"\"\"\n    # The name can only be 80 characters long.\n    if len(name) > MAX_NAME_LENGTH:\n        return False\n    return bool(NAME_VALID_CHARS_REGEX.match(name))", "title": ""}
{"_id": "d18525", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d18526", "text": "def safe_pow(base, exp):\n    \"\"\"safe version of pow\"\"\"\n    if exp > MAX_EXPONENT:\n        raise RuntimeError(\"Invalid exponent, max exponent is {}\".format(MAX_EXPONENT))\n    return base ** exp", "title": ""}
{"_id": "d18527", "text": "def text_coords(string, position):\n    r\"\"\"\n    Transform a simple index into a human-readable position in a string.\n\n    This function accepts a string and an index, and will return a triple of\n    `(lineno, columnno, line)` representing the position through the text. It's\n    useful for displaying a string index in a human-readable way::\n\n        >>> s = \"abcdef\\nghijkl\\nmnopqr\\nstuvwx\\nyz\"\n        >>> text_coords(s, 0)\n        (0, 0, 'abcdef')\n        >>> text_coords(s, 4)\n        (0, 4, 'abcdef')\n        >>> text_coords(s, 6)\n        (0, 6, 'abcdef')\n        >>> text_coords(s, 7)\n        (1, 0, 'ghijkl')\n        >>> text_coords(s, 11)\n        (1, 4, 'ghijkl')\n        >>> text_coords(s, 15)\n        (2, 1, 'mnopqr')\n    \"\"\"\n    line_start = string.rfind('\\n', 0, position) + 1\n    line_end = string.find('\\n', position)\n    lineno = string.count('\\n', 0, position)\n    columnno = position - line_start\n    line = string[line_start:line_end]\n    return (lineno, columnno, line)", "title": ""}
{"_id": "d18528", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d18529", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d18530", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d18531", "text": "def build(ctx):\n    \"\"\"Build documentation as HTML.\n\n    The build HTML site is located in the ``doc/_build/html`` directory\n    of the package.\n    \"\"\"\n    return_code = run_sphinx(ctx.obj['root_dir'])\n    if return_code > 0:\n        sys.exit(return_code)", "title": ""}
{"_id": "d18532", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d18533", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d18534", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d18535", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d18536", "text": "def find_duplicates(l: list) -> set:\n    \"\"\"\n    Return the duplicates in a list.\n\n    The function relies on\n    https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n    Parameters\n    ----------\n    l : list\n        Name\n\n    Returns\n    -------\n    set\n        Duplicated values\n\n    >>> find_duplicates([1,2,3])\n    set()\n    >>> find_duplicates([1,2,1])\n    {1}\n    \"\"\"\n    return set([x for x in l if l.count(x) > 1])", "title": ""}
{"_id": "d18537", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d18538", "text": "def __getattr__(self, item: str) -> Callable:\n        \"\"\"Get a callable that sends the actual API request internally.\"\"\"\n        return functools.partial(self.call_action, item)", "title": ""}
{"_id": "d18539", "text": "def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:\n        \"\"\"Executes SQL; returns list of first values of each row.\"\"\"\n        rows = self.fetchall(sql, *args)\n        return [row[0] for row in rows]", "title": ""}
{"_id": "d18540", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d18541", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d18542", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d18543", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d18544", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d18545", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d18546", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d18547", "text": "def method_caller(method_name, *args, **kwargs):\n\t\"\"\"\n\tReturn a function that will call a named method on the\n\ttarget object with optional positional and keyword\n\targuments.\n\n\t>>> lower = method_caller('lower')\n\t>>> lower('MyString')\n\t'mystring'\n\t\"\"\"\n\tdef call_method(target):\n\t\tfunc = getattr(target, method_name)\n\t\treturn func(*args, **kwargs)\n\treturn call_method", "title": ""}
{"_id": "d18548", "text": "def psutil_phymem_usage():\n    \"\"\"\n    Return physical memory usage (float)\n    Requires the cross-platform psutil (>=v0.3) library\n    (https://github.com/giampaolo/psutil)\n    \"\"\"\n    import psutil\n    # This is needed to avoid a deprecation warning error with\n    # newer psutil versions\n    try:\n        percent = psutil.virtual_memory().percent\n    except:\n        percent = psutil.phymem_usage().percent\n    return percent", "title": ""}
{"_id": "d18549", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d18550", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d18551", "text": "def block_diag(*blocks: np.ndarray) -> np.ndarray:\n    \"\"\"Concatenates blocks into a block diagonal matrix.\n\n    Args:\n        *blocks: Square matrices to place along the diagonal of the result.\n\n    Returns:\n        A block diagonal matrix with the given blocks along its diagonal.\n\n    Raises:\n        ValueError: A block isn't square.\n    \"\"\"\n    for b in blocks:\n        if b.shape[0] != b.shape[1]:\n            raise ValueError('Blocks must be square.')\n\n    if not blocks:\n        return np.zeros((0, 0), dtype=np.complex128)\n\n    n = sum(b.shape[0] for b in blocks)\n    dtype = functools.reduce(_merge_dtypes, (b.dtype for b in blocks))\n\n    result = np.zeros(shape=(n, n), dtype=dtype)\n    i = 0\n    for b in blocks:\n        j = i + b.shape[0]\n        result[i:j, i:j] = b\n        i = j\n\n    return result", "title": ""}
{"_id": "d18552", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d18553", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d18554", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d18555", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d18556", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d18557", "text": "def average_arrays(arrays: List[mx.nd.NDArray]) -> mx.nd.NDArray:\n    \"\"\"\n    Take a list of arrays of the same shape and take the element wise average.\n\n    :param arrays: A list of NDArrays with the same shape that will be averaged.\n    :return: The average of the NDArrays in the same context as arrays[0].\n    \"\"\"\n    if not arrays:\n        raise ValueError(\"arrays is empty.\")\n    if len(arrays) == 1:\n        return arrays[0]\n    check_condition(all(arrays[0].shape == a.shape for a in arrays), \"nd array shapes do not match\")\n    return mx.nd.add_n(*arrays) / len(arrays)", "title": ""}
{"_id": "d18558", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18559", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18560", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d18561", "text": "def write_text(filename: str, text: str) -> None:\n    \"\"\"\n    Writes text to a file.\n    \"\"\"\n    with open(filename, 'w') as f:  # type: TextIO\n        print(text, file=f)", "title": ""}
{"_id": "d18562", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d18563", "text": "def after_third_friday(day=None):\n    \"\"\" check if day is after month's 3rd friday \"\"\"\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", "title": ""}
{"_id": "d18564", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d18565", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d18566", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d18567", "text": "def get_account_id_by_fullname(self, fullname: str) -> str:\n        \"\"\" Locates the account by fullname \"\"\"\n        account = self.get_by_fullname(fullname)\n        return account.guid", "title": ""}
{"_id": "d18568", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d18569", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d18570", "text": "def _reshuffle(mat, shape):\n    \"\"\"Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].\"\"\"\n    return np.reshape(\n        np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),\n        (shape[3] * shape[1], shape[0] * shape[2]))", "title": ""}
{"_id": "d18571", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d18572", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18573", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d18574", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18575", "text": "def isFull(self):\n        \"\"\"\n        Returns True if the response buffer is full, and False otherwise.\n        The buffer is full if either (1) the number of items in the value\n        list is >= pageSize or (2) the total length of the serialised\n        elements in the page is >= maxBufferSize.\n\n        If page_size or max_response_length were not set in the request\n        then they're not checked.\n        \"\"\"\n        return (\n            (self._pageSize > 0 and self._numElements >= self._pageSize) or\n            (self._bufferSize >= self._maxBufferSize)\n        )", "title": ""}
{"_id": "d18576", "text": "def after_third_friday(day=None):\n    \"\"\" check if day is after month's 3rd friday \"\"\"\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", "title": ""}
{"_id": "d18577", "text": "def callable_validator(v: Any) -> AnyCallable:\n    \"\"\"\n    Perform a simple check if the value is callable.\n\n    Note: complete matching of argument type hints and return types is not performed\n    \"\"\"\n    if callable(v):\n        return v\n\n    raise errors.CallableError(value=v)", "title": ""}
{"_id": "d18578", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d18579", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d18580", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d18581", "text": "def camel_to_snake_case(string):\n    \"\"\"Converts 'string' presented in camel case to snake case.\n\n    e.g.: CamelCase => snake_case\n    \"\"\"\n    s = _1.sub(r'\\1_\\2', string)\n    return _2.sub(r'\\1_\\2', s).lower()", "title": ""}
{"_id": "d18582", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d18583", "text": "def lower_camel_case_from_underscores(string):\n    \"\"\"generate a lower-cased camelCase string from an underscore_string.\n    For example: my_variable_name -> myVariableName\"\"\"\n    components = string.split('_')\n    string = components[0]\n    for component in components[1:]:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d18584", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d18585", "text": "def _brief_print_list(lst, limit=7):\n    \"\"\"Print at most `limit` elements of list.\"\"\"\n    lst = list(lst)\n    if len(lst) > limit:\n        return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n            _brief_print_list(lst[-limit//2:], limit)\n    return ', '.join([\"'%s'\"%str(i) for i in lst])", "title": ""}
{"_id": "d18586", "text": "def has_table(self, name):\n        \"\"\"Return ``True`` if the table *name* exists in the database.\"\"\"\n        return len(self.sql(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\",\n                            parameters=(name,), asrecarray=False, cache=False)) > 0", "title": ""}
{"_id": "d18587", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d18588", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d18589", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d18590", "text": "def suppress_stdout():\n    \"\"\"\n    Context manager that suppresses stdout.\n\n    Examples:\n        >>> with suppress_stdout():\n        ...     print('Test print')\n\n        >>> print('test')\n        test\n\n    \"\"\"\n    save_stdout = sys.stdout\n    sys.stdout = DevNull()\n    yield\n    sys.stdout = save_stdout", "title": ""}
{"_id": "d18591", "text": "def command(self, cmd, *args):\n        \"\"\"\n        Sends a command and an (optional) sequence of arguments through to the\n        delegated serial interface. Note that the arguments are passed through\n        as data.\n        \"\"\"\n        self._serial_interface.command(cmd)\n        if len(args) > 0:\n            self._serial_interface.data(list(args))", "title": ""}
{"_id": "d18592", "text": "def timeit (func, log, limit):\n    \"\"\"Print execution time of the function. For quick'n'dirty profiling.\"\"\"\n\n    def newfunc (*args, **kwargs):\n        \"\"\"Execute function and print execution time.\"\"\"\n        t = time.time()\n        res = func(*args, **kwargs)\n        duration = time.time() - t\n        if duration > limit:\n            print(func.__name__, \"took %0.2f seconds\" % duration, file=log)\n            print(args, file=log)\n            print(kwargs, file=log)\n        return res\n    return update_func_meta(newfunc, func)", "title": ""}
{"_id": "d18593", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d18594", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d18595", "text": "def date_to_datetime(d):\n    \"\"\"\n    >>> date_to_datetime(date(2000, 1, 2))\n    datetime.datetime(2000, 1, 2, 0, 0)\n    >>> date_to_datetime(datetime(2000, 1, 2, 3, 4, 5))\n    datetime.datetime(2000, 1, 2, 3, 4, 5)\n    \"\"\"\n    if not isinstance(d, datetime):\n        d = datetime.combine(d, datetime.min.time())\n    return d", "title": ""}
{"_id": "d18596", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d18597", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d18598", "text": "def find_duplicates(l: list) -> set:\n    \"\"\"\n    Return the duplicates in a list.\n\n    The function relies on\n    https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n    Parameters\n    ----------\n    l : list\n        Name\n\n    Returns\n    -------\n    set\n        Duplicated values\n\n    >>> find_duplicates([1,2,3])\n    set()\n    >>> find_duplicates([1,2,1])\n    {1}\n    \"\"\"\n    return set([x for x in l if l.count(x) > 1])", "title": ""}
{"_id": "d18599", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d18600", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d18601", "text": "def quaternion_imag(quaternion):\n    \"\"\"Return imaginary part of quaternion.\n\n    >>> quaternion_imag([3, 0, 1, 2])\n    array([0., 1., 2.])\n\n    \"\"\"\n    return np.array(quaternion[1:4], dtype=np.float64, copy=True)", "title": ""}
{"_id": "d18602", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d18603", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d18604", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d18605", "text": "def wipe_table(self, table: str) -> int:\n        \"\"\"Delete all records from a table. Use caution!\"\"\"\n        sql = \"DELETE FROM \" + self.delimit(table)\n        return self.db_exec(sql)", "title": ""}
{"_id": "d18606", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d18607", "text": "def zip_with_index(rdd):\n    \"\"\"\n    Alternate version of Spark's zipWithIndex that eagerly returns count.\n    \"\"\"\n    starts = [0]\n    if rdd.getNumPartitions() > 1:\n        nums = rdd.mapPartitions(lambda it: [sum(1 for _ in it)]).collect()\n        count = sum(nums)\n        for i in range(len(nums) - 1):\n            starts.append(starts[-1] + nums[i])\n    else:\n        count = rdd.count()\n\n    def func(k, it):\n        for i, v in enumerate(it, starts[k]):\n            yield v, i\n\n    return count, rdd.mapPartitionsWithIndex(func)", "title": ""}
{"_id": "d18608", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d18609", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18610", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d18611", "text": "def isfinite(data: mx.nd.NDArray) -> mx.nd.NDArray:\n    \"\"\"Performs an element-wise check to determine if the NDArray contains an infinite element or not.\n       TODO: remove this funciton after upgrade to MXNet 1.4.* in favor of mx.ndarray.contrib.isfinite()\n    \"\"\"\n    is_data_not_nan = data == data\n    is_data_not_infinite = data.abs() != np.inf\n    return mx.nd.logical_and(is_data_not_infinite, is_data_not_nan)", "title": ""}
{"_id": "d18612", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d18613", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d18614", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d18615", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d18616", "text": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n    \"\"\"\n    Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n    :param buckets: List of buckets.\n    :return: The largest bucket in the list.\n    \"\"\"\n    return max(buckets)", "title": ""}
{"_id": "d18617", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d18618", "text": "def console_get_background_flag(con: tcod.console.Console) -> int:\n    \"\"\"Return this consoles current blend mode.\n\n    Args:\n        con (Console): Any Console instance.\n\n    .. deprecated:: 8.5\n        Check :any:`Console.default_bg_blend` instead.\n    \"\"\"\n    return int(lib.TCOD_console_get_background_flag(_console(con)))", "title": ""}
{"_id": "d18619", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d18620", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d18621", "text": "def get_valid_filename(s):\n    \"\"\"\n    Shamelessly taken from Django.\n    https://github.com/django/django/blob/master/django/utils/text.py\n\n    Return the given string converted to a string that can be used for a clean\n    filename. Remove leading and trailing spaces; convert other spaces to\n    underscores; and remove anything that is not an alphanumeric, dash,\n    underscore, or dot.\n    >>> get_valid_filename(\"john's portrait in 2004.jpg\")\n    'johns_portrait_in_2004.jpg'\n    \"\"\"\n    s = str(s).strip().replace(' ', '_')\n    return re.sub(r'(?u)[^-\\w.]', '', s)", "title": ""}
{"_id": "d18622", "text": "def load_yaml(file):\n    \"\"\"If pyyaml > 5.1 use full_load to avoid warning\"\"\"\n    if hasattr(yaml, \"full_load\"):\n        return yaml.full_load(file)\n    else:\n        return yaml.load(file)", "title": ""}
{"_id": "d18623", "text": "def warn_if_nans_exist(X):\n    \"\"\"Warn if nans exist in a numpy array.\"\"\"\n    null_count = count_rows_with_nans(X)\n    total = len(X)\n    percent = 100 * null_count / total\n\n    if null_count > 0:\n        warning_message = \\\n            'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n            'complete rows will be plotted.'.format(null_count, total, percent)\n        warnings.warn(warning_message, DataWarning)", "title": ""}
{"_id": "d18624", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d18625", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d18626", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d18627", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d18628", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d18629", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18630", "text": "def iter_fields(self, schema: Schema) -> Iterable[Tuple[str, Field]]:\n        \"\"\"\n        Iterate through marshmallow schema fields.\n\n        Generates: name, field pairs\n\n        \"\"\"\n        for name in sorted(schema.fields.keys()):\n            field = schema.fields[name]\n            yield field.dump_to or name, field", "title": ""}
{"_id": "d18631", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d18632", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d18633", "text": "def numeric_part(s):\n    \"\"\"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\n    \"\"\"\n\n    m = re_numeric_part.match(s)\n    if m:\n        return int(m.group(1))\n    return None", "title": ""}
{"_id": "d18634", "text": "def random_name_gen(size=6):\n    \"\"\"Generate a random python attribute name.\"\"\"\n\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 ''", "title": ""}
{"_id": "d18635", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d18636", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d18637", "text": "def looks_like_url(url):\n    \"\"\" 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\n    \"\"\"\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", "title": ""}
{"_id": "d18638", "text": "def check64bit(current_system=\"python\"):\n    \"\"\"checks if you are on a 64 bit platform\"\"\"\n    if current_system == \"python\":\n        return sys.maxsize > 2147483647\n    elif current_system == \"os\":\n        import platform\n        pm = platform.machine()\n        if pm != \"..\" and pm.endswith('64'):  # recent Python (not Iron)\n            return True\n        else:\n            if 'PROCESSOR_ARCHITEW6432' in os.environ:\n                return True  # 32 bit program running on 64 bit Windows\n            try:\n                # 64 bit Windows 64 bit program\n                return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')\n            except IndexError:\n                pass  # not Windows\n            try:\n                # this often works in Linux\n                return '64' in platform.architecture()[0]\n            except Exception:\n                # is an older version of Python, assume also an older os@\n                # (best we can guess)\n                return False", "title": ""}
{"_id": "d18639", "text": "def quoted_or_list(items: List[str]) -> Optional[str]:\n    \"\"\"Given [A, B, C] return \"'A', 'B', or 'C'\".\n\n    Note: We use single quotes here, since these are also used by repr().\n    \"\"\"\n    return or_list([f\"'{item}'\" for item in items])", "title": ""}
{"_id": "d18640", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d18641", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d18642", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d18643", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d18644", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18645", "text": "def urljoin(*args):\n    \"\"\"\n    Joins given arguments into a url, removing duplicate slashes\n    Thanks http://stackoverflow.com/a/11326230/1267398\n\n    >>> urljoin('/lol', '///lol', '/lol//')\n    '/lol/lol/lol'\n    \"\"\"\n    value = \"/\".join(map(lambda x: str(x).strip('/'), args))\n    return \"/{}\".format(value)", "title": ""}
{"_id": "d18646", "text": "def clean_int(x) -> int:\n    \"\"\"\n    Returns its parameter as an integer, or raises\n    ``django.forms.ValidationError``.\n    \"\"\"\n    try:\n        return int(x)\n    except ValueError:\n        raise forms.ValidationError(\n            \"Cannot convert to integer: {}\".format(repr(x)))", "title": ""}
{"_id": "d18647", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d18648", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d18649", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d18650", "text": "def stdev(self):\n        \"\"\" -> #float :func:numpy.std of the timing intervals \"\"\"\n        return round(np.std(self.array), self.precision)\\\n            if len(self.array) else None", "title": ""}
{"_id": "d18651", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d18652", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18653", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d18654", "text": "def space_list(line: str) -> List[int]:\n    \"\"\"\n    Given a string, return a list of index positions where a blank space occurs.\n\n    :param line:\n    :return:\n\n    >>> space_list(\"    abc \")\n    [0, 1, 2, 3, 7]\n    \"\"\"\n    spaces = []\n    for idx, car in enumerate(list(line)):\n        if car == \" \":\n            spaces.append(idx)\n    return spaces", "title": ""}
{"_id": "d18655", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18656", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d18657", "text": "def get_property(self, name):\n        # type: (str) -> object\n        \"\"\"\n        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\n        \"\"\"\n        with self.__properties_lock:\n            return self.__properties.get(name, os.getenv(name))", "title": ""}
{"_id": "d18658", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d18659", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d18660", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d18661", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d18662", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d18663", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d18664", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d18665", "text": "def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool:\n    \"\"\"Returns True if the given node is an object from the __builtin__ module.\"\"\"\n    return node and node.root().name == BUILTINS_NAME", "title": ""}
{"_id": "d18666", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d18667", "text": "def __del__(self):\n        \"\"\"Frees all resources.\n        \"\"\"\n        if hasattr(self, '_Api'):\n            self._Api.close()\n\n        self._Logger.info('object destroyed')", "title": ""}
{"_id": "d18668", "text": "def assert_equal(first, second, msg_fmt=\"{msg}\"):\n    \"\"\"Fail unless first equals second, as determined by the '==' operator.\n\n    >>> assert_equal(5, 5.0)\n    >>> assert_equal(\"Hello World!\", \"Goodbye!\")\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'Hello World!' != 'Goodbye!'\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\n    \"\"\"\n\n    if isinstance(first, dict) and isinstance(second, dict):\n        assert_dict_equal(first, second, msg_fmt)\n    elif not first == second:\n        msg = \"{!r} != {!r}\".format(first, second)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))", "title": ""}
{"_id": "d18669", "text": "def get_language(query: str) -> str:\n    \"\"\"Tries to work out the highlight.js language of a given file name or\n    shebang. Returns an empty string if none match.\n    \"\"\"\n    query = query.lower()\n    for language in LANGUAGES:\n        if query.endswith(language):\n            return language\n    return ''", "title": ""}
{"_id": "d18670", "text": "def prin(*args, **kwargs):\n    r\"\"\"Like ``print``, but a function. I.e. prints out all arguments as\n    ``print`` would do. Specify output stream like this::\n\n      print('ERROR', `out=\"sys.stderr\"``).\n\n    \"\"\"\n    print >> kwargs.get('out',None), \" \".join([str(arg) for arg in args])", "title": ""}
{"_id": "d18671", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d18672", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d18673", "text": "def to_bool(value):\n    # type: (Any) -> bool\n    \"\"\"\n    Convert a value into a bool but handle \"truthy\" strings eg, yes, true, ok, y\n    \"\"\"\n    if isinstance(value, _compat.string_types):\n        return value.upper() in ('Y', 'YES', 'T', 'TRUE', '1', 'OK')\n    return bool(value)", "title": ""}
{"_id": "d18674", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d18675", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d18676", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d18677", "text": "def version():\n    \"\"\"Wrapper for opj_version library routine.\"\"\"\n    OPENJPEG.opj_version.restype = ctypes.c_char_p\n    library_version = OPENJPEG.opj_version()\n    if sys.hexversion >= 0x03000000:\n        return library_version.decode('utf-8')\n    else:\n        return library_version", "title": ""}
{"_id": "d18678", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d18679", "text": "def full(self):\n        \"\"\"Return ``True`` if the queue is full, ``False``\n        otherwise (not reliable!).\n\n        Only applicable if :attr:`maxsize` is set.\n\n        \"\"\"\n        return self.maxsize and len(self.list) >= self.maxsize or False", "title": ""}
{"_id": "d18680", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d18681", "text": "def tail(filename, number_of_bytes):\n    \"\"\"Returns the last number_of_bytes of filename\"\"\"\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()", "title": ""}
{"_id": "d18682", "text": "def find_editor() -> str:\n    \"\"\"Find a reasonable editor to use by default for the system that the cmd2 application is running on.\"\"\"\n    editor = os.environ.get('EDITOR')\n    if not editor:\n        if sys.platform[:3] == 'win':\n            editor = 'notepad'\n        else:\n            # Favor command-line editors first so we don't leave the terminal to edit\n            for editor in ['vim', 'vi', 'emacs', 'nano', 'pico', 'gedit', 'kate', 'subl', 'geany', 'atom']:\n                if which(editor):\n                    break\n    return editor", "title": ""}
{"_id": "d18683", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d18684", "text": "def assert_equal(first, second, msg_fmt=\"{msg}\"):\n    \"\"\"Fail unless first equals second, as determined by the '==' operator.\n\n    >>> assert_equal(5, 5.0)\n    >>> assert_equal(\"Hello World!\", \"Goodbye!\")\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'Hello World!' != 'Goodbye!'\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\n    \"\"\"\n\n    if isinstance(first, dict) and isinstance(second, dict):\n        assert_dict_equal(first, second, msg_fmt)\n    elif not first == second:\n        msg = \"{!r} != {!r}\".format(first, second)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))", "title": ""}
{"_id": "d18685", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18686", "text": "def get_pixel(framebuf, x, y):\n        \"\"\"Get the color of a given pixel\"\"\"\n        index = (y >> 3) * framebuf.stride + x\n        offset = y & 0x07\n        return (framebuf.buf[index] >> offset) & 0x01", "title": ""}
{"_id": "d18687", "text": "def replaceStrs(s, *args):\n    r\"\"\"Replace all ``(frm, to)`` tuples in `args` in string `s`.\n\n    >>> replaceStrs(\"nothing is better than warm beer\",\n    ...             ('nothing','warm beer'), ('warm beer','nothing'))\n    'warm beer is better than nothing'\n\n    \"\"\"\n    if args == (): return s\n    mapping = dict((frm, to) for frm, to in args)\n    return re.sub(\"|\".join(map(re.escape, mapping.keys())),\n                  lambda match:mapping[match.group(0)], s)", "title": ""}
{"_id": "d18688", "text": "def is_sqlatype_text_over_one_char(\n        coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type that's more than one character\n    long?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return is_sqlatype_text_of_length_at_least(coltype, 2)", "title": ""}
{"_id": "d18689", "text": "def uconcatenate(arrs, axis=0):\n    \"\"\"Concatenate a sequence of arrays.\n\n    This wrapper around numpy.concatenate preserves units. All input arrays\n    must have the same units.  See the documentation of numpy.concatenate for\n    full details.\n\n    Examples\n    --------\n    >>> from unyt import cm\n    >>> A = [1, 2, 3]*cm\n    >>> B = [2, 3, 4]*cm\n    >>> uconcatenate((A, B))\n    unyt_array([1, 2, 3, 2, 3, 4], 'cm')\n\n    \"\"\"\n    v = np.concatenate(arrs, axis=axis)\n    v = _validate_numpy_wrapper_units(v, arrs)\n    return v", "title": ""}
{"_id": "d18690", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d18691", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d18692", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d18693", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d18694", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d18695", "text": "def get_view_selection(self):\n        \"\"\"Get actual tree selection object and all respective models of selected rows\"\"\"\n        if not self.MODEL_STORAGE_ID:\n            return None, None\n\n        # avoid selection requests on empty tree views -> case warnings in gtk3\n        if len(self.store) == 0:\n            paths = []\n        else:\n            model, paths = self._tree_selection.get_selected_rows()\n\n        # get all related models for selection from respective tree store field\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", "title": ""}
{"_id": "d18696", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d18697", "text": "def _gauss(mean: int, sigma: int) -> int:\n        \"\"\"\n        Creates a variation from a base value\n\n        Args:\n            mean: base value\n            sigma: gaussian sigma\n\n        Returns: random value\n\n        \"\"\"\n        return int(random.gauss(mean, sigma))", "title": ""}
{"_id": "d18698", "text": "def cpu_count() -> int:\n    \"\"\"Returns the number of processors on this machine.\"\"\"\n    if multiprocessing is None:\n        return 1\n    try:\n        return multiprocessing.cpu_count()\n    except NotImplementedError:\n        pass\n    try:\n        return os.sysconf(\"SC_NPROCESSORS_CONF\")\n    except (AttributeError, ValueError):\n        pass\n    gen_log.error(\"Could not detect number of processors; assuming 1\")\n    return 1", "title": ""}
{"_id": "d18699", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d18700", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18701", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18702", "text": "def _protected_log(x1):\n    \"\"\"Closure of log for zero arguments.\"\"\"\n    with np.errstate(divide='ignore', invalid='ignore'):\n        return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)", "title": ""}
{"_id": "d18703", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d18704", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d18705", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d18706", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d18707", "text": "def expired(self):\n        \"\"\"Boolean property if this action has expired\n        \"\"\"\n        if self.timeout is None:\n            return False\n\n        return monotonic() - self.start_time > self.timeout", "title": ""}
{"_id": "d18708", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d18709", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d18710", "text": "def _extension(modpath: str) -> setuptools.Extension:\n    \"\"\"Make setuptools.Extension.\"\"\"\n    return setuptools.Extension(modpath, [modpath.replace(\".\", \"/\") + \".py\"])", "title": ""}
{"_id": "d18711", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d18712", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18713", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d18714", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d18715", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d18716", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d18717", "text": "def last(self):\n        \"\"\"Last time step available.\n\n        Example:\n            >>> sdat = StagyyData('path/to/run')\n            >>> assert(sdat.steps.last is sdat.steps[-1])\n        \"\"\"\n        if self._last is UNDETERMINED:\n            # not necessarily the last one...\n            self._last = self.sdat.tseries.index[-1]\n        return self[self._last]", "title": ""}
{"_id": "d18718", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d18719", "text": "def fib(n):\n    \"\"\"Fibonacci example function\n\n    Args:\n      n (int): integer\n\n    Returns:\n      int: n-th Fibonacci number\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", "title": ""}
{"_id": "d18720", "text": "def suppress_stdout():\n    \"\"\"\n    Context manager that suppresses stdout.\n\n    Examples:\n        >>> with suppress_stdout():\n        ...     print('Test print')\n\n        >>> print('test')\n        test\n\n    \"\"\"\n    save_stdout = sys.stdout\n    sys.stdout = DevNull()\n    yield\n    sys.stdout = save_stdout", "title": ""}
{"_id": "d18721", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d18722", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d18723", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d18724", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d18725", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d18726", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d18727", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d18728", "text": "def get_property_as_float(self, name: str) -> float:\n        \"\"\"Return the value of a float property.\n\n        :return: The property value (float).\n\n        Raises exception if property with name doesn't exist.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes\n        \"\"\"\n        return float(self.__instrument.get_property(name))", "title": ""}
{"_id": "d18729", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d18730", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d18731", "text": "def _exit(self, status_code):\n        \"\"\"Properly kill Python process including zombie threads.\"\"\"\n        # If there are active threads still running infinite loops, sys.exit\n        # won't kill them but os._exit will. os._exit skips calling cleanup\n        # handlers, flushing stdio buffers, etc.\n        exit_func = os._exit if threading.active_count() > 1 else sys.exit\n        exit_func(status_code)", "title": ""}
{"_id": "d18732", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18733", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d18734", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d18735", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d18736", "text": "def rl_get_point() -> int:  # pragma: no cover\n    \"\"\"\n    Returns the offset of the current cursor position in rl_line_buffer\n    \"\"\"\n    if rl_type == RlType.GNU:\n        return ctypes.c_int.in_dll(readline_lib, \"rl_point\").value\n\n    elif rl_type == RlType.PYREADLINE:\n        return readline.rl.mode.l_buffer.point\n\n    else:\n        return 0", "title": ""}
{"_id": "d18737", "text": "def get_pylint_options(config_dir='.'):\n    # type: (str) -> List[str]\n    \"\"\"Checks for local config overrides for `pylint`\n    and add them in the correct `pylint` `options` format.\n\n    :param config_dir:\n    :return: List [str]\n    \"\"\"\n    if PYLINT_CONFIG_NAME in os.listdir(config_dir):\n        pylint_config_path = PYLINT_CONFIG_NAME\n    else:\n        pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH\n\n    return ['--rcfile={}'.format(pylint_config_path)]", "title": ""}
{"_id": "d18738", "text": "def _skip(self, cnt):\n        \"\"\"Read and discard data\"\"\"\n        while cnt > 0:\n            if cnt > 8192:\n                buf = self.read(8192)\n            else:\n                buf = self.read(cnt)\n            if not buf:\n                break\n            cnt -= len(buf)", "title": ""}
{"_id": "d18739", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d18740", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d18741", "text": "def argmax(iterable, key=None, both=False):\n    \"\"\"\n    >>> argmax([4,2,-5])\n    0\n    >>> argmax([4,2,-5], key=abs)\n    2\n    >>> argmax([4,2,-5], key=abs, both=True)\n    (2, 5)\n    \"\"\"\n    if key is not None:\n        it = imap(key, iterable)\n    else:\n        it = iter(iterable)\n    score, argmax = reduce(max, izip(it, count()))\n    if both:\n        return argmax, score\n    return argmax", "title": ""}
{"_id": "d18742", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d18743", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d18744", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d18745", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d18746", "text": "def _get_or_default(mylist, i, default=None):\n    \"\"\"return list item number, or default if don't exist\"\"\"\n    if i >= len(mylist):\n        return default\n    else :\n        return mylist[i]", "title": ""}
{"_id": "d18747", "text": "def hex_to_int(value):\n    \"\"\"\n    Convert hex string like \"\\x0A\\xE3\" to 2787.\n    \"\"\"\n    if version_info.major >= 3:\n        return int.from_bytes(value, \"big\")\n    return int(value.encode(\"hex\"), 16)", "title": ""}
{"_id": "d18748", "text": "def remove_links(text):\n    \"\"\"\n    Helper function to remove the links from the input text\n\n    Args:\n        text (str): A string\n\n    Returns:\n        str: the same text, but with any substring that matches the regex\n        for a link removed and replaced with a space\n\n    Example:\n        >>> from tweet_parser.getter_methods.tweet_text import remove_links\n        >>> text = \"lorem ipsum dolor https://twitter.com/RobotPrincessFi\"\n        >>> remove_links(text)\n        'lorem ipsum dolor  '\n    \"\"\"\n    tco_link_regex = re.compile(\"https?://t.co/[A-z0-9].*\")\n    generic_link_regex = re.compile(\"(https?://)?(\\w*[.]\\w+)+([/?=&]+\\w+)*\")\n    remove_tco = re.sub(tco_link_regex, \" \", text)\n    remove_generic = re.sub(generic_link_regex, \" \", remove_tco)\n    return remove_generic", "title": ""}
{"_id": "d18749", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d18750", "text": "def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:\n    \"\"\"\n    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\n    \"\"\"\n    jsonschema_validate(request, schema)\n    return request", "title": ""}
{"_id": "d18751", "text": "def load_yaml(file):\n    \"\"\"If pyyaml > 5.1 use full_load to avoid warning\"\"\"\n    if hasattr(yaml, \"full_load\"):\n        return yaml.full_load(file)\n    else:\n        return yaml.load(file)", "title": ""}
{"_id": "d18752", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d18753", "text": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "title": ""}
{"_id": "d18754", "text": "def format_exp_floats(decimals):\n    \"\"\"\n    sometimes the exp. column can be too large\n    \"\"\"\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    )", "title": ""}
{"_id": "d18755", "text": "def login(self, user: str, passwd: str) -> None:\n        \"\"\"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`.\"\"\"\n        self.context.login(user, passwd)", "title": ""}
{"_id": "d18756", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18757", "text": "def quaternion_imag(quaternion):\n    \"\"\"Return imaginary part of quaternion.\n\n    >>> quaternion_imag([3, 0, 1, 2])\n    array([0., 1., 2.])\n\n    \"\"\"\n    return np.array(quaternion[1:4], dtype=np.float64, copy=True)", "title": ""}
{"_id": "d18758", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d18759", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d18760", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d18761", "text": "def remove_leading_zeros(num: str) -> str:\n    \"\"\"\n    Strips zeros while handling -, M, and empty strings\n    \"\"\"\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", "title": ""}
{"_id": "d18762", "text": "def _create_empty_array(self, frames, always_2d, dtype):\n        \"\"\"Create an empty array with appropriate shape.\"\"\"\n        import numpy as np\n        if always_2d or self.channels > 1:\n            shape = frames, self.channels\n        else:\n            shape = frames,\n        return np.empty(shape, dtype, order='C')", "title": ""}
{"_id": "d18763", "text": "def increment_frame(self):\n        \"\"\"Increment a frame of the animation.\"\"\"\n        self.current_frame += 1\n\n        if self.current_frame >= self.end_frame:\n            # Wrap back to the beginning of the animation.\n            self.current_frame = 0", "title": ""}
{"_id": "d18764", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d18765", "text": "def samefile(a: str, b: str) -> bool:\n    \"\"\"Check if two pathes represent the same file.\"\"\"\n    try:\n        return os.path.samefile(a, b)\n    except OSError:\n        return os.path.normpath(a) == os.path.normpath(b)", "title": ""}
{"_id": "d18766", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d18767", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d18768", "text": "async def fetchall(self) -> Iterable[sqlite3.Row]:\n        \"\"\"Fetch all remaining rows.\"\"\"\n        return await self._execute(self._cursor.fetchall)", "title": ""}
{"_id": "d18769", "text": "def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):\n        \"\"\"\n        If we're not on the first line (of a multiline input) go a line up,\n        otherwise go back in history. (If nothing is selected.)\n        \"\"\"\n        if self.complete_state:\n            self.complete_previous(count=count)\n        elif self.document.cursor_position_row > 0:\n            self.cursor_up(count=count)\n        elif not self.selection_state:\n            self.history_backward(count=count)\n\n            # Go to the start of the line?\n            if go_to_start_of_line_if_history_changes:\n                self.cursor_position += self.document.get_start_of_line_position()", "title": ""}
{"_id": "d18770", "text": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n    \"\"\"Rate limit a function.\"\"\"\n    return util.rate_limited(max_per_hour, *args)", "title": ""}
{"_id": "d18771", "text": "def hex_to_int(value):\n    \"\"\"\n    Convert hex string like \"\\x0A\\xE3\" to 2787.\n    \"\"\"\n    if version_info.major >= 3:\n        return int.from_bytes(value, \"big\")\n    return int(value.encode(\"hex\"), 16)", "title": ""}
{"_id": "d18772", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d18773", "text": "def de_duplicate(items):\n    \"\"\"Remove any duplicate item, preserving order\n\n    >>> de_duplicate([1, 2, 1, 2])\n    [1, 2]\n    \"\"\"\n    result = []\n    for item in items:\n        if item not in result:\n            result.append(item)\n    return result", "title": ""}
{"_id": "d18774", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d18775", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d18776", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18777", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d18778", "text": "def closest_values(L):\n    \"\"\"Closest values\n\n    :param L: list of values\n    :returns: two values from L with minimal distance\n    :modifies: the order of L\n    :complexity: O(n log n), for n=len(L)\n    \"\"\"\n    assert len(L) >= 2\n    L.sort()\n    valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L)))\n    return L[argmin - 1], L[argmin]", "title": ""}
{"_id": "d18779", "text": "def singularize(word):\n    \"\"\"\n    Return the singular form of a word, the reverse of :func:`pluralize`.\n\n    Examples::\n\n        >>> singularize(\"posts\")\n        \"post\"\n        >>> singularize(\"octopi\")\n        \"octopus\"\n        >>> singularize(\"sheep\")\n        \"sheep\"\n        >>> singularize(\"word\")\n        \"word\"\n        >>> singularize(\"CamelOctopi\")\n        \"CamelOctopus\"\n\n    \"\"\"\n    for inflection in UNCOUNTABLES:\n        if re.search(r'(?i)\\b(%s)\\Z' % inflection, word):\n            return word\n\n    for rule, replacement in SINGULARS:\n        if re.search(rule, word):\n            return re.sub(rule, replacement, word)\n    return word", "title": ""}
{"_id": "d18780", "text": "def factors(n):\n    \"\"\"\n    Computes all the integer factors of the number `n`\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> import utool as ut\n        >>> result = sorted(ut.factors(10))\n        >>> print(result)\n        [1, 2, 5, 10]\n\n    References:\n        http://stackoverflow.com/questions/6800193/finding-all-the-factors\n    \"\"\"\n    return set(reduce(list.__add__,\n                      ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))", "title": ""}
{"_id": "d18781", "text": "def get_environment_info() -> dict:\n    \"\"\"\n    Information about Cauldron and its Python interpreter.\n\n    :return:\n        A dictionary containing information about the Cauldron and its\n        Python environment. This information is useful when providing feedback\n        and bug reports.\n    \"\"\"\n    data = _environ.systems.get_system_data()\n    data['cauldron'] = _environ.package_settings.copy()\n    return data", "title": ""}
{"_id": "d18782", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d18783", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d18784", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d18785", "text": "def detect_model_num(string):\n    \"\"\"Takes a string related to a model name and extract its model number.\n\n    For example:\n        '000000-bootstrap.index' => 0\n    \"\"\"\n    match = re.match(MODEL_NUM_REGEX, string)\n    if match:\n        return int(match.group())\n    return None", "title": ""}
{"_id": "d18786", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d18787", "text": "def uniqued(iterable):\n    \"\"\"Return unique list of ``iterable`` items preserving order.\n\n    >>> uniqued('spameggs')\n    ['s', 'p', 'a', 'm', 'e', 'g']\n    \"\"\"\n    seen = set()\n    return [item for item in iterable if item not in seen and not seen.add(item)]", "title": ""}
{"_id": "d18788", "text": "def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):\n        \"\"\"\n        If we're not on the first line (of a multiline input) go a line up,\n        otherwise go back in history. (If nothing is selected.)\n        \"\"\"\n        if self.complete_state:\n            self.complete_previous(count=count)\n        elif self.document.cursor_position_row > 0:\n            self.cursor_up(count=count)\n        elif not self.selection_state:\n            self.history_backward(count=count)\n\n            # Go to the start of the line?\n            if go_to_start_of_line_if_history_changes:\n                self.cursor_position += self.document.get_start_of_line_position()", "title": ""}
{"_id": "d18789", "text": "def pruning(self, X, y, cost_mat):\n        \"\"\" Function that prune the decision tree.\n\n        Parameters\n        ----------\n\n        X : array-like of shape = [n_samples, n_features]\n            The input samples.\n\n        y_true : array indicator matrix\n            Ground truth (correct) labels.\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        \"\"\"\n        self.tree_.tree_pruned = copy.deepcopy(self.tree_.tree)\n        if self.tree_.n_nodes > 0:\n            self._pruning(X, y, cost_mat)\n            nodes_pruned = self._nodes(self.tree_.tree_pruned)\n            self.tree_.n_nodes_pruned = len(nodes_pruned)", "title": ""}
{"_id": "d18790", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d18791", "text": "def branches():\n    # type: () -> List[str]\n    \"\"\" Return a list of branches in the current repo.\n\n    Returns:\n        list[str]: A list of branches in the current repo.\n    \"\"\"\n    out = shell.run(\n        'git branch',\n        capture=True,\n        never_pretend=True\n    ).stdout.strip()\n    return [x.strip('* \\t\\n') for x in out.splitlines()]", "title": ""}
{"_id": "d18792", "text": "def content_type(self) -> ContentType:\n        \"\"\"Return receiver's content type.\"\"\"\n        return self._ctype if self._ctype else self.parent.content_type()", "title": ""}
{"_id": "d18793", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d18794", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d18795", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d18796", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d18797", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d18798", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d18799", "text": "def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:\n        \"\"\"Executes SQL; returns list of first values of each row.\"\"\"\n        rows = self.fetchall(sql, *args)\n        return [row[0] for row in rows]", "title": ""}
{"_id": "d18800", "text": "def url_concat(url, args):\n    \"\"\"Concatenate url and argument dictionary regardless of whether\n    url has existing query parameters.\n\n    >>> url_concat(\"http://example.com/foo?a=b\", dict(c=\"d\"))\n    'http://example.com/foo?a=b&c=d'\n    \"\"\"\n    if not args: return url\n    if url[-1] not in ('?', '&'):\n        url += '&' if ('?' in url) else '?'\n    return url + urllib.urlencode(args)", "title": ""}
{"_id": "d18801", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d18802", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d18803", "text": "def _prm_get_longest_stringsize(string_list):\n        \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n        maxlength = 1\n\n        for stringar in string_list:\n            if isinstance(stringar, np.ndarray):\n                if stringar.ndim > 0:\n                    for string in stringar.ravel():\n                        maxlength = max(len(string), maxlength)\n                else:\n                    maxlength = max(len(stringar.tolist()), maxlength)\n            else:\n                maxlength = max(len(stringar), maxlength)\n\n        # Make the string Col longer than needed in order to allow later on slightly larger strings\n        return int(maxlength * 1.5)", "title": ""}
{"_id": "d18804", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d18805", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d18806", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d18807", "text": "def replace_in_list(stringlist: Iterable[str],\n                    replacedict: Dict[str, str]) -> List[str]:\n    \"\"\"\n    Returns a list produced by applying :func:`multiple_replace` to every\n    string in ``stringlist``.\n\n    Args:\n        stringlist: list of source strings\n        replacedict: dictionary mapping \"original\" to \"replacement\" strings\n\n    Returns:\n        list of final strings\n\n    \"\"\"\n    newlist = []\n    for fromstring in stringlist:\n        newlist.append(multiple_replace(fromstring, replacedict))\n    return newlist", "title": ""}
{"_id": "d18808", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d18809", "text": "def _hash_the_file(hasher, filename):\n    \"\"\"Helper function for creating hash functions.\n\n    See implementation of :func:`dtoolcore.filehasher.shasum`\n    for more usage details.\n    \"\"\"\n    BUF_SIZE = 65536\n    with open(filename, 'rb') as f:\n        buf = f.read(BUF_SIZE)\n        while len(buf) > 0:\n            hasher.update(buf)\n            buf = f.read(BUF_SIZE)\n    return hasher", "title": ""}
{"_id": "d18810", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d18811", "text": "def fix_missing(df, col, name, na_dict):\n    \"\"\" Fill missing data in a column of df with the median, and add a {name}_na column\n    which specifies if the data was missing.\n    Parameters:\n    -----------\n    df: The data frame that will be changed.\n    col: The column of data to fix by filling in missing data.\n    name: The name of the new filled column in df.\n    na_dict: A dictionary of values to create na's of and the value to insert. If\n        name is not a key of na_dict the median will fill any missing data. Also\n        if name is not a key of na_dict and there is no missing data in col, then\n        no {name}_na column is not created.\n    Examples:\n    ---------\n    >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]})\n    >>> df\n       col1 col2\n    0     1    5\n    1   nan    2\n    2     3    2\n    >>> fix_missing(df, df['col1'], 'col1', {})\n    >>> df\n       col1 col2 col1_na\n    0     1    5   False\n    1     2    2    True\n    2     3    2   False\n    >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]})\n    >>> df\n       col1 col2\n    0     1    5\n    1   nan    2\n    2     3    2\n    >>> fix_missing(df, df['col2'], 'col2', {})\n    >>> df\n       col1 col2\n    0     1    5\n    1   nan    2\n    2     3    2\n    >>> df = pd.DataFrame({'col1' : [1, np.NaN, 3], 'col2' : [5, 2, 2]})\n    >>> df\n       col1 col2\n    0     1    5\n    1   nan    2\n    2     3    2\n    >>> fix_missing(df, df['col1'], 'col1', {'col1' : 500})\n    >>> df\n       col1 col2 col1_na\n    0     1    5   False\n    1   500    2    True\n    2     3    2   False\n    \"\"\"\n    if is_numeric_dtype(col):\n        if pd.isnull(col).sum() or (name in na_dict):\n            df[name+'_na'] = pd.isnull(col)\n            filler = na_dict[name] if name in na_dict else col.median()\n            df[name] = col.fillna(filler)\n            na_dict[name] = filler\n    return na_dict", "title": ""}
{"_id": "d18812", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d18813", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d18814", "text": "def listify(a):\n    \"\"\"\n    Convert a scalar ``a`` to a list and all iterables to list as well.\n\n    Examples\n    --------\n    >>> listify(0)\n    [0]\n\n    >>> listify([1,2,3])\n    [1, 2, 3]\n\n    >>> listify('a')\n    ['a']\n\n    >>> listify(np.array([1,2,3]))\n    [1, 2, 3]\n\n    >>> listify('string')\n    ['string']\n    \"\"\"\n    if a is None:\n        return []\n    elif not isinstance(a, (tuple, list, np.ndarray)):\n        return [a]\n    return list(a)", "title": ""}
{"_id": "d18815", "text": "def same(*values):\n    \"\"\"\n    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\n    \"\"\"\n    if not values:\n        return True\n    first, rest = values[0], values[1:]\n    return all(value == first for value in rest)", "title": ""}
{"_id": "d18816", "text": "def is_string_dtype(arr_or_dtype):\n    \"\"\"\n    Check whether the provided array or dtype is of the string 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 the string dtype.\n\n    Examples\n    --------\n    >>> is_string_dtype(str)\n    True\n    >>> is_string_dtype(object)\n    True\n    >>> is_string_dtype(int)\n    False\n    >>>\n    >>> is_string_dtype(np.array(['a', 'b']))\n    True\n    >>> is_string_dtype(pd.Series([1, 2]))\n    False\n    \"\"\"\n\n    # TODO: gh-15585: consider making the checks stricter.\n    def condition(dtype):\n        return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype)\n    return _is_dtype(arr_or_dtype, condition)", "title": ""}
{"_id": "d18817", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d18818", "text": "def trunc(obj, max, left=0):\n    \"\"\"\n    Convert `obj` to string, eliminate newlines and truncate the string to `max`\n    characters. If there are more characters in the string add ``...`` to the\n    string. With `left=True`, the string can be truncated at the beginning.\n\n    @note: Does not catch exceptions when converting `obj` to string with `str`.\n\n    >>> trunc('This is a long text.', 8)\n    This ...\n    >>> trunc('This is a long text.', 8, left)\n    ...text.\n    \"\"\"\n    s = str(obj)\n    s = s.replace('\\n', '|')\n    if len(s) > max:\n        if left:\n            return '...'+s[len(s)-max+3:]\n        else:\n            return s[:(max-3)]+'...'\n    else:\n        return s", "title": ""}
{"_id": "d18819", "text": "def decodebytes(input):\n    \"\"\"Decode base64 string to byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _decodebytes_py3(input)\n    return _decodebytes_py2(input)", "title": ""}
{"_id": "d18820", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d18821", "text": "def uconcatenate(arrs, axis=0):\n    \"\"\"Concatenate a sequence of arrays.\n\n    This wrapper around numpy.concatenate preserves units. All input arrays\n    must have the same units.  See the documentation of numpy.concatenate for\n    full details.\n\n    Examples\n    --------\n    >>> from unyt import cm\n    >>> A = [1, 2, 3]*cm\n    >>> B = [2, 3, 4]*cm\n    >>> uconcatenate((A, B))\n    unyt_array([1, 2, 3, 2, 3, 4], 'cm')\n\n    \"\"\"\n    v = np.concatenate(arrs, axis=axis)\n    v = _validate_numpy_wrapper_units(v, arrs)\n    return v", "title": ""}
{"_id": "d18822", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d18823", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d18824", "text": "def count(self, elem):\n        \"\"\"\n        Return the number of elements equal to elem present in the queue\n\n        >>> pdeque([1, 2, 1]).count(1)\n        2\n        \"\"\"\n        return self._left_list.count(elem) + self._right_list.count(elem)", "title": ""}
{"_id": "d18825", "text": "def _close(self):\n        \"\"\"\n        Release the USB interface again.\n        \"\"\"\n        self._usb_handle.releaseInterface()\n        try:\n            # If we're using PyUSB >= 1.0 we can re-attach the kernel driver here.\n            self._usb_handle.dev.attach_kernel_driver(0)\n        except:\n            pass\n        self._usb_int = None\n        self._usb_handle = None\n        return True", "title": ""}
{"_id": "d18826", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d18827", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d18828", "text": "def get_versions(reporev=True):\n    \"\"\"Get version information for components used by Spyder\"\"\"\n    import sys\n    import platform\n\n    import qtpy\n    import qtpy.QtCore\n\n    revision = None\n    if reporev:\n        from spyder.utils import vcs\n        revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n    if not sys.platform == 'darwin':  # To avoid a crash with our Mac app\n        system = platform.system()\n    else:\n        system = 'Darwin'\n\n    return {\n        'spyder': __version__,\n        'python': platform.python_version(),  # \"2.7.3\"\n        'bitness': 64 if sys.maxsize > 2**32 else 32,\n        'qt': qtpy.QtCore.__version__,\n        'qt_api': qtpy.API_NAME,      # PyQt5\n        'qt_api_ver': qtpy.PYQT_VERSION,\n        'system': system,   # Linux, Windows, ...\n        'release': platform.release(),  # XP, 10.6, 2.2.0, etc.\n        'revision': revision,  # '9fdf926eccce'\n    }", "title": ""}
{"_id": "d18829", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d18830", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d18831", "text": "def to_np(*args):\n    \"\"\" convert GPU arras to numpy and return them\"\"\"\n    if len(args) > 1:\n        return (cp.asnumpy(x) for x in args)\n    else:\n        return cp.asnumpy(args[0])", "title": ""}
{"_id": "d18832", "text": "def remove_blank_spaces(syllables: List[str]) -> List[str]:\n    \"\"\"\n    Given a list of letters, remove any blank spaces or empty strings.\n\n    :param syllables:\n    :return:\n\n    >>> remove_blank_spaces(['', 'a', ' ', 'b', ' ', 'c', ''])\n    ['a', 'b', 'c']\n    \"\"\"\n    cleaned = []\n    for syl in syllables:\n        if syl == \" \" or syl == '':\n            pass\n        else:\n            cleaned.append(syl)\n    return cleaned", "title": ""}
{"_id": "d18833", "text": "def dict_to_ddb(item):\n    # type: (Dict[str, Any]) -> Dict[str, Any]\n    # TODO: narrow these types down\n    \"\"\"Converts a native Python dictionary to a raw DynamoDB item.\n\n    :param dict item: Native item\n    :returns: DynamoDB item\n    :rtype: dict\n    \"\"\"\n    serializer = TypeSerializer()\n    return {key: serializer.serialize(value) for key, value in item.items()}", "title": ""}
{"_id": "d18834", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d18835", "text": "def non_increasing(values):\n    \"\"\"True if values are not increasing.\"\"\"\n    return all(x >= y for x, y in zip(values, values[1:]))", "title": ""}
{"_id": "d18836", "text": "def input(prompt=\"\"):\n\t\"\"\"input([prompt]) -> value\n\nEquivalent to eval(raw_input(prompt)).\"\"\"\n\t\n\tstring = stdin_decode(raw_input(prompt))\n\t\n\tcaller_frame = sys._getframe(1)\n\tglobals = caller_frame.f_globals\n\tlocals = caller_frame.f_locals\n\t\n\treturn eval(string, globals, locals)", "title": ""}
{"_id": "d18837", "text": "def suppress_stdout():\n    \"\"\"\n    Context manager that suppresses stdout.\n\n    Examples:\n        >>> with suppress_stdout():\n        ...     print('Test print')\n\n        >>> print('test')\n        test\n\n    \"\"\"\n    save_stdout = sys.stdout\n    sys.stdout = DevNull()\n    yield\n    sys.stdout = save_stdout", "title": ""}
{"_id": "d18838", "text": "def convert_to_int(x: Any, default: int = None) -> int:\n    \"\"\"\n    Transforms its input into an integer, or returns ``default``.\n    \"\"\"\n    try:\n        return int(x)\n    except (TypeError, ValueError):\n        return default", "title": ""}
{"_id": "d18839", "text": "def filter_bool(n: Node, query: str) -> bool:\n    \"\"\"\n    Filter and ensure that the returned value is of type bool.\n    \"\"\"\n    return _scalariter2item(n, query, bool)", "title": ""}
{"_id": "d18840", "text": "def ask_bool(question: str, default: bool = True) -> bool:\n    \"\"\"Asks a question yes no style\"\"\"\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\"", "title": ""}
{"_id": "d18841", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d18842", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d18843", "text": "def to_bool(value: Any) -> bool:\n    \"\"\"Convert string or other Python object to boolean.\n\n    **Rationalle**\n\n    Passing flags is one of the most common cases of using environment vars and\n    as values are strings we need to have an easy way to convert them to\n    boolean Python value.\n\n    Without this function int or float string values can be converted as false\n    positives, e.g. ``bool('0') => True``, but using this function ensure that\n    digit flag be properly converted to boolean value.\n\n    :param value: String or other value.\n    \"\"\"\n    return bool(strtobool(value) if isinstance(value, str) else value)", "title": ""}
{"_id": "d18844", "text": "def remove_prefix(text, prefix):\n\t\"\"\"\n\tRemove 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'\n\t\"\"\"\n\tnull, prefix, rest = text.rpartition(prefix)\n\treturn rest", "title": ""}
{"_id": "d18845", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d18846", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d18847", "text": "def cpu_count() -> int:\n    \"\"\"Returns the number of processors on this machine.\"\"\"\n    if multiprocessing is None:\n        return 1\n    try:\n        return multiprocessing.cpu_count()\n    except NotImplementedError:\n        pass\n    try:\n        return os.sysconf(\"SC_NPROCESSORS_CONF\")\n    except (AttributeError, ValueError):\n        pass\n    gen_log.error(\"Could not detect number of processors; assuming 1\")\n    return 1", "title": ""}
{"_id": "d18848", "text": "def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict:\n        \"\"\"HTTP request method of interface implementation.\"\"\"", "title": ""}
{"_id": "d18849", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d18850", "text": "def from_buffer(buffer, mime=False):\n    \"\"\"\n    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'\n    \"\"\"\n    m = _get_magic_type(mime)\n    return m.from_buffer(buffer)", "title": ""}
{"_id": "d18851", "text": "def url_concat(url, args):\n    \"\"\"Concatenate url and argument dictionary regardless of whether\n    url has existing query parameters.\n\n    >>> url_concat(\"http://example.com/foo?a=b\", dict(c=\"d\"))\n    'http://example.com/foo?a=b&c=d'\n    \"\"\"\n    if not args: return url\n    if url[-1] not in ('?', '&'):\n        url += '&' if ('?' in url) else '?'\n    return url + urllib.urlencode(args)", "title": ""}
{"_id": "d18852", "text": "def getVectorFromType(self, dtype) -> Union[bool, None, Tuple[int, int]]:\n        \"\"\"\n        :see: doc of method on parent class\n        \"\"\"\n        if dtype == BIT:\n            return False\n        elif isinstance(dtype, Bits):\n            return [evalParam(dtype.width) - 1, hInt(0)]", "title": ""}
{"_id": "d18853", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d18854", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d18855", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d18856", "text": "def get_day_name(self) -> str:\n        \"\"\" Returns the day name \"\"\"\n        weekday = self.value.isoweekday() - 1\n        return calendar.day_name[weekday]", "title": ""}
{"_id": "d18857", "text": "def convert_camel_case_string(name: str) -> str:\n    \"\"\"Convert camel case string to snake case\"\"\"\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()", "title": ""}
{"_id": "d18858", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d18859", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d18860", "text": "def distinct_permutations(iterable):\n    \"\"\"Yield successive distinct permutations of the elements in *iterable*.\n\n        >>> sorted(distinct_permutations([1, 0, 1]))\n        [(0, 1, 1), (1, 0, 1), (1, 1, 0)]\n\n    Equivalent to ``set(permutations(iterable))``, except duplicates are not\n    generated and thrown away. For larger input sequences this is much more\n    efficient.\n\n    Duplicate permutations arise when there are duplicated elements in the\n    input iterable. The number of items returned is\n    `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of\n    items input, and each `x_i` is the count of a distinct item in the input\n    sequence.\n\n    \"\"\"\n    def make_new_permutations(permutations, e):\n        \"\"\"Internal helper function.\n        The output permutations are built up by adding element *e* to the\n        current *permutations* at every possible position.\n        The key idea is to keep repeated elements (reverse) ordered:\n        if e1 == e2 and e1 is before e2 in the iterable, then all permutations\n        with e1 before e2 are ignored.\n\n        \"\"\"\n        for permutation in permutations:\n            for j in range(len(permutation)):\n                yield permutation[:j] + [e] + permutation[j:]\n                if permutation[j] == e:\n                    break\n            else:\n                yield permutation + [e]\n\n    permutations = [[]]\n    for e in iterable:\n        permutations = make_new_permutations(permutations, e)\n\n    return (tuple(t) for t in permutations)", "title": ""}
{"_id": "d18861", "text": "def text_alignment(x, y):\n    \"\"\"\n    Align text labels based on the x- and y-axis coordinate values.\n\n    This function is used for computing the appropriate alignment of the text\n    label.\n\n    For example, if the text is on the \"right\" side of the plot, we want it to\n    be left-aligned. If the text is on the \"top\" side of the plot, we want it\n    to be bottom-aligned.\n\n    :param x, y: (`int` or `float`) x- and y-axis coordinate respectively.\n    :returns: A 2-tuple of strings, the horizontal and vertical alignments\n        respectively.\n    \"\"\"\n    if x == 0:\n        ha = \"center\"\n    elif x > 0:\n        ha = \"left\"\n    else:\n        ha = \"right\"\n    if y == 0:\n        va = \"center\"\n    elif y > 0:\n        va = \"bottom\"\n    else:\n        va = \"top\"\n\n    return ha, va", "title": ""}
{"_id": "d18862", "text": "def _validate_image_rank(self, img_array):\n        \"\"\"\n        Images must be either 2D or 3D.\n        \"\"\"\n        if img_array.ndim == 1 or img_array.ndim > 3:\n            msg = \"{0}D imagery is not allowed.\".format(img_array.ndim)\n            raise IOError(msg)", "title": ""}
{"_id": "d18863", "text": "def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict:\n        \"\"\"HTTP request method of interface implementation.\"\"\"", "title": ""}
{"_id": "d18864", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d18865", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d18866", "text": "def lint(fmt='colorized'):\n    \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\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)", "title": ""}
{"_id": "d18867", "text": "def _hash_the_file(hasher, filename):\n    \"\"\"Helper function for creating hash functions.\n\n    See implementation of :func:`dtoolcore.filehasher.shasum`\n    for more usage details.\n    \"\"\"\n    BUF_SIZE = 65536\n    with open(filename, 'rb') as f:\n        buf = f.read(BUF_SIZE)\n        while len(buf) > 0:\n            hasher.update(buf)\n            buf = f.read(BUF_SIZE)\n    return hasher", "title": ""}
{"_id": "d18868", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d18869", "text": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "title": ""}
{"_id": "d18870", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d18871", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d18872", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d18873", "text": "def camel_to_snake(s: str) -> str:\n    \"\"\"Convert string from camel case to snake case.\"\"\"\n\n    return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()", "title": ""}
{"_id": "d18874", "text": "def get_window_dim():\n    \"\"\" gets the dimensions depending on python version and os\"\"\"\n    version = sys.version_info\n\n    if version >= (3, 3):\n        return _size_36()\n    if platform.system() == 'Windows':\n        return _size_windows()\n    return _size_27()", "title": ""}
{"_id": "d18875", "text": "def _prm_get_longest_stringsize(string_list):\n        \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n        maxlength = 1\n\n        for stringar in string_list:\n            if isinstance(stringar, np.ndarray):\n                if stringar.ndim > 0:\n                    for string in stringar.ravel():\n                        maxlength = max(len(string), maxlength)\n                else:\n                    maxlength = max(len(stringar.tolist()), maxlength)\n            else:\n                maxlength = max(len(stringar), maxlength)\n\n        # Make the string Col longer than needed in order to allow later on slightly larger strings\n        return int(maxlength * 1.5)", "title": ""}
{"_id": "d18876", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d18877", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d18878", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d18879", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d18880", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d18881", "text": "def timeit (func, log, limit):\n    \"\"\"Print execution time of the function. For quick'n'dirty profiling.\"\"\"\n\n    def newfunc (*args, **kwargs):\n        \"\"\"Execute function and print execution time.\"\"\"\n        t = time.time()\n        res = func(*args, **kwargs)\n        duration = time.time() - t\n        if duration > limit:\n            print(func.__name__, \"took %0.2f seconds\" % duration, file=log)\n            print(args, file=log)\n            print(kwargs, file=log)\n        return res\n    return update_func_meta(newfunc, func)", "title": ""}
{"_id": "d18882", "text": "def find_duplicates(l: list) -> set:\n    \"\"\"\n    Return the duplicates in a list.\n\n    The function relies on\n    https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n    Parameters\n    ----------\n    l : list\n        Name\n\n    Returns\n    -------\n    set\n        Duplicated values\n\n    >>> find_duplicates([1,2,3])\n    set()\n    >>> find_duplicates([1,2,1])\n    {1}\n    \"\"\"\n    return set([x for x in l if l.count(x) > 1])", "title": ""}
{"_id": "d18883", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d18884", "text": "def execute(cur, *args):\n    \"\"\"Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)\n    \"\"\"\n    stmt = args[0]\n    if len(args) > 1:\n        stmt = stmt.replace('%', '%%').replace('?', '%r')\n        print(stmt % (args[1]))\n    return cur.execute(*args)", "title": ""}
{"_id": "d18885", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18886", "text": "def get_versions(reporev=True):\n    \"\"\"Get version information for components used by Spyder\"\"\"\n    import sys\n    import platform\n\n    import qtpy\n    import qtpy.QtCore\n\n    revision = None\n    if reporev:\n        from spyder.utils import vcs\n        revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))\n\n    if not sys.platform == 'darwin':  # To avoid a crash with our Mac app\n        system = platform.system()\n    else:\n        system = 'Darwin'\n\n    return {\n        'spyder': __version__,\n        'python': platform.python_version(),  # \"2.7.3\"\n        'bitness': 64 if sys.maxsize > 2**32 else 32,\n        'qt': qtpy.QtCore.__version__,\n        'qt_api': qtpy.API_NAME,      # PyQt5\n        'qt_api_ver': qtpy.PYQT_VERSION,\n        'system': system,   # Linux, Windows, ...\n        'release': platform.release(),  # XP, 10.6, 2.2.0, etc.\n        'revision': revision,  # '9fdf926eccce'\n    }", "title": ""}
{"_id": "d18887", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d18888", "text": "def _isbool(string):\n    \"\"\"\n    >>> _isbool(True)\n    True\n    >>> _isbool(\"False\")\n    True\n    >>> _isbool(1)\n    False\n    \"\"\"\n    return isinstance(string, _bool_type) or\\\n        (isinstance(string, (_binary_type, _text_type))\n         and\n         string in (\"True\", \"False\"))", "title": ""}
{"_id": "d18889", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d18890", "text": "def callable_validator(v: Any) -> AnyCallable:\n    \"\"\"\n    Perform a simple check if the value is callable.\n\n    Note: complete matching of argument type hints and return types is not performed\n    \"\"\"\n    if callable(v):\n        return v\n\n    raise errors.CallableError(value=v)", "title": ""}
{"_id": "d18891", "text": "def setup_cache(app: Flask, cache_config) -> Optional[Cache]:\n    \"\"\"Setup the flask-cache on a flask app\"\"\"\n    if cache_config and cache_config.get('CACHE_TYPE') != 'null':\n        return Cache(app, config=cache_config)\n\n    return None", "title": ""}
{"_id": "d18892", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18893", "text": "def __gt__(self, other):\n    \"\"\"Greater than ordering.\"\"\"\n    if not isinstance(other, Key):\n      return NotImplemented\n    return self.__tuple() > other.__tuple()", "title": ""}
{"_id": "d18894", "text": "def strictly_positive_int_or_none(val):\n    \"\"\"Parse `val` into either `None` or a strictly positive integer.\"\"\"\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))", "title": ""}
{"_id": "d18895", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d18896", "text": "def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]:\n    \"\"\" Write a numpy array to YAML.\n\n    It registers the array under the tag ``!numpy_array``.\n\n    Use with:\n\n    .. code-block:: python\n\n        >>> yaml = ruamel.yaml.YAML()\n        >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml)\n\n    Note:\n        We cannot use ``yaml.register_class`` because it won't register the proper type.\n        (It would register the type of the class, rather than of `numpy.ndarray`). Instead,\n        we use the above approach to register this method explicitly with the representer.\n    \"\"\"\n    return representer.represent_sequence(\n        \"!numpy_array\",\n        data.tolist()\n    )", "title": ""}
{"_id": "d18897", "text": "def sections(self) -> list:\n        \"\"\"List of sections.\"\"\"\n        self.config.read(self.filepath)\n        return self.config.sections()", "title": ""}
{"_id": "d18898", "text": "def obj_in_list_always(target_list, obj):\n    \"\"\"\n    >>> l = [1,1,1]\n    >>> obj_in_list_always(l, 1)\n    True\n    >>> l.append(2)\n    >>> obj_in_list_always(l, 1)\n    False\n    \"\"\"\n    for item in set(target_list):\n        if item is not obj:\n            return False\n    return True", "title": ""}
{"_id": "d18899", "text": "def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]:\n    \"\"\" Partition a list of integers into a list of partitions \"\"\"\n    for part in algorithm_u(range(size), nparts):\n        yield part", "title": ""}
{"_id": "d18900", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d18901", "text": "def assert_raises(ex_type, func, *args, **kwargs):\n    r\"\"\"\n    Checks that a function raises an error when given specific arguments.\n\n    Args:\n        ex_type (Exception): exception type\n        func (callable): live python function\n\n    CommandLine:\n        python -m utool.util_assert assert_raises --show\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_assert import *  # NOQA\n        >>> import utool as ut\n        >>> ex_type = AssertionError\n        >>> func = len\n        >>> # Check that this raises an error when something else does not\n        >>> assert_raises(ex_type, assert_raises, ex_type, func, [])\n        >>> # Check this does not raise an error when something else does\n        >>> assert_raises(ValueError, [].index, 0)\n    \"\"\"\n    try:\n        func(*args, **kwargs)\n    except Exception as ex:\n        assert isinstance(ex, ex_type), (\n            'Raised %r but type should have been %r' % (ex, ex_type))\n        return True\n    else:\n        raise AssertionError('No error was raised')", "title": ""}
{"_id": "d18902", "text": "def uuid2buid(value):\n    \"\"\"\n    Convert a UUID object to a 22-char BUID string\n\n    >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089')\n    >>> uuid2buid(u)\n    'MyA90vLvQi-usAWNb19wiQ'\n    \"\"\"\n    if six.PY3:  # pragma: no cover\n        return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=')\n    else:\n        return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))", "title": ""}
{"_id": "d18903", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d18904", "text": "def get_window_dim():\n    \"\"\" gets the dimensions depending on python version and os\"\"\"\n    version = sys.version_info\n\n    if version >= (3, 3):\n        return _size_36()\n    if platform.system() == 'Windows':\n        return _size_windows()\n    return _size_27()", "title": ""}
{"_id": "d18905", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d18906", "text": "def truncate_string(value, max_width=None):\n    \"\"\"Truncate string values.\"\"\"\n    if isinstance(value, text_type) and max_width is not None and len(value) > max_width:\n        return value[:max_width]\n    return value", "title": ""}
{"_id": "d18907", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d18908", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d18909", "text": "def _numbers_units(N):\n    \"\"\"\n    >>> _numbers_units(45)\n    '123456789012345678901234567890123456789012345'\n    \"\"\"\n    lst = range(1, N + 1)\n    return \"\".join(list(map(lambda i: str(i % 10), lst)))", "title": ""}
{"_id": "d18910", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18911", "text": "def put(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP PUT operation to API endpoint.\"\"\"\n\n        return self._request('PUT', endpoint, **kwargs)", "title": ""}
{"_id": "d18912", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d18913", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d18914", "text": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "title": ""}
{"_id": "d18915", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d18916", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18917", "text": "def insert_ordered(value, array):\n    \"\"\"\n    This will insert the value into the array, keeping it sorted, and returning the\n    index where it was inserted\n    \"\"\"\n\n    index = 0\n\n    # search for the last array item that value is larger than\n    for n in range(0,len(array)):\n        if value >= array[n]: index = n+1\n\n    array.insert(index, value)\n    return index", "title": ""}
{"_id": "d18918", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d18919", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d18920", "text": "def check_python_version():\n    \"\"\"Check if the currently running Python version is new enough.\"\"\"\n    # Required due to multiple with statements on one line\n    req_version = (2, 7)\n    cur_version = sys.version_info\n    if cur_version >= req_version:\n        print(\"Python version... %sOK%s (found %s, requires %s)\" %\n              (Bcolors.OKGREEN, Bcolors.ENDC, str(platform.python_version()),\n               str(req_version[0]) + \".\" + str(req_version[1])))\n    else:\n        print(\"Python version... %sFAIL%s (found %s, requires %s)\" %\n              (Bcolors.FAIL, Bcolors.ENDC, str(cur_version),\n               str(req_version)))", "title": ""}
{"_id": "d18921", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d18922", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d18923", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d18924", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d18925", "text": "def quaternion_imag(quaternion):\n    \"\"\"Return imaginary part of quaternion.\n\n    >>> quaternion_imag([3, 0, 1, 2])\n    array([ 0.,  1.,  2.])\n\n    \"\"\"\n    return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)", "title": ""}
{"_id": "d18926", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d18927", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d18928", "text": "def url_concat(url, args):\n    \"\"\"Concatenate url and argument dictionary regardless of whether\n    url has existing query parameters.\n\n    >>> url_concat(\"http://example.com/foo?a=b\", dict(c=\"d\"))\n    'http://example.com/foo?a=b&c=d'\n    \"\"\"\n    if not args: return url\n    if url[-1] not in ('?', '&'):\n        url += '&' if ('?' in url) else '?'\n    return url + urllib.urlencode(args)", "title": ""}
{"_id": "d18929", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18930", "text": "def percentile(sorted_list, percent, key=lambda x: x):\n    \"\"\"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\n    \"\"\"\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])", "title": ""}
{"_id": "d18931", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d18932", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d18933", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d18934", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d18935", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d18936", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d18937", "text": "def get_caller_module():\n    \"\"\"\n    Returns the name of the caller's module as a string.\n\n    >>> get_caller_module()\n    '__main__'\n    \"\"\"\n    stack = inspect.stack()\n    assert len(stack) > 1\n    caller = stack[2][0]\n    return caller.f_globals['__name__']", "title": ""}
{"_id": "d18938", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d18939", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d18940", "text": "def shape(self) -> Tuple[int, ...]:\n        \"\"\"Shape of histogram's data.\n\n        Returns\n        -------\n        One-element tuple with the number of bins along each axis.\n        \"\"\"\n        return tuple(bins.bin_count for bins in self._binnings)", "title": ""}
{"_id": "d18941", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d18942", "text": "def negate_mask(mask):\n    \"\"\"Returns the negated mask.\n\n    If elements of input mask have 0 and non-zero values, then the returned matrix will have all elements 0 (1) where\n    the original one has non-zero (0).\n\n    :param mask: Input mask\n    :type mask: np.array\n    :return: array of same shape and dtype=int8 as input array\n    :rtype: np.array\n    \"\"\"\n    res = np.ones(mask.shape, dtype=np.int8)\n    res[mask > 0] = 0\n\n    return res", "title": ""}
{"_id": "d18943", "text": "def to_iso_string(self) -> str:\n        \"\"\" Returns full ISO string for the given date \"\"\"\n        assert isinstance(self.value, datetime)\n        return datetime.isoformat(self.value)", "title": ""}
{"_id": "d18944", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d18945", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d18946", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d18947", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d18948", "text": "def closest_values(L):\n    \"\"\"Closest values\n\n    :param L: list of values\n    :returns: two values from L with minimal distance\n    :modifies: the order of L\n    :complexity: O(n log n), for n=len(L)\n    \"\"\"\n    assert len(L) >= 2\n    L.sort()\n    valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L)))\n    return L[argmin - 1], L[argmin]", "title": ""}
{"_id": "d18949", "text": "def is_running(process_id: int) -> bool:\n    \"\"\"\n    Uses the Unix ``ps`` program to see if a process is running.\n    \"\"\"\n    pstr = str(process_id)\n    encoding = sys.getdefaultencoding()\n    s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE)\n    for line in s.stdout:\n        strline = line.decode(encoding)\n        if pstr in strline:\n            return True\n    return False", "title": ""}
{"_id": "d18950", "text": "def uconcatenate(arrs, axis=0):\n    \"\"\"Concatenate a sequence of arrays.\n\n    This wrapper around numpy.concatenate preserves units. All input arrays\n    must have the same units.  See the documentation of numpy.concatenate for\n    full details.\n\n    Examples\n    --------\n    >>> from unyt import cm\n    >>> A = [1, 2, 3]*cm\n    >>> B = [2, 3, 4]*cm\n    >>> uconcatenate((A, B))\n    unyt_array([1, 2, 3, 2, 3, 4], 'cm')\n\n    \"\"\"\n    v = np.concatenate(arrs, axis=axis)\n    v = _validate_numpy_wrapper_units(v, arrs)\n    return v", "title": ""}
{"_id": "d18951", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d18952", "text": "def find_duplicates(l: list) -> set:\n    \"\"\"\n    Return the duplicates in a list.\n\n    The function relies on\n    https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n    Parameters\n    ----------\n    l : list\n        Name\n\n    Returns\n    -------\n    set\n        Duplicated values\n\n    >>> find_duplicates([1,2,3])\n    set()\n    >>> find_duplicates([1,2,1])\n    {1}\n    \"\"\"\n    return set([x for x in l if l.count(x) > 1])", "title": ""}
{"_id": "d18953", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d18954", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d18955", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d18956", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d18957", "text": "def shape(self) -> Tuple[int, ...]:\n        \"\"\"Shape of histogram's data.\n\n        Returns\n        -------\n        One-element tuple with the number of bins along each axis.\n        \"\"\"\n        return tuple(bins.bin_count for bins in self._binnings)", "title": ""}
{"_id": "d18958", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d18959", "text": "def list_depth(list_, func=max, _depth=0):\n    \"\"\"\n    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)\n\n    \"\"\"\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", "title": ""}
{"_id": "d18960", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d18961", "text": "def is_any_type_set(sett: Set[Type]) -> bool:\n    \"\"\"\n    Helper method to check if a set of types is the {AnyObject} singleton\n\n    :param sett:\n    :return:\n    \"\"\"\n    return len(sett) == 1 and is_any_type(min(sett))", "title": ""}
{"_id": "d18962", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d18963", "text": "def stop(self) -> None:\n        \"\"\"Stops the analysis as soon as possible.\"\"\"\n        if self._stop and not self._posted_kork:\n            self._stop()\n            self._stop = None", "title": ""}
{"_id": "d18964", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d18965", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d18966", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d18967", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d18968", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d18969", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d18970", "text": "def pluralize(word):\n    \"\"\"\n    Return the plural form of a word.\n\n    Examples::\n\n        >>> pluralize(\"post\")\n        \"posts\"\n        >>> pluralize(\"octopus\")\n        \"octopi\"\n        >>> pluralize(\"sheep\")\n        \"sheep\"\n        >>> pluralize(\"CamelOctopus\")\n        \"CamelOctopi\"\n\n    \"\"\"\n    if not word or word.lower() in UNCOUNTABLES:\n        return word\n    else:\n        for rule, replacement in PLURALS:\n            if re.search(rule, word):\n                return re.sub(rule, replacement, word)\n        return word", "title": ""}
{"_id": "d18971", "text": "def method_caller(method_name, *args, **kwargs):\n\t\"\"\"\n\tReturn a function that will call a named method on the\n\ttarget object with optional positional and keyword\n\targuments.\n\n\t>>> lower = method_caller('lower')\n\t>>> lower('MyString')\n\t'mystring'\n\t\"\"\"\n\tdef call_method(target):\n\t\tfunc = getattr(target, method_name)\n\t\treturn func(*args, **kwargs)\n\treturn call_method", "title": ""}
{"_id": "d18972", "text": "async def parallel_results(future_map: Sequence[Tuple]) -> Dict:\n    \"\"\"\n    Run parallel execution of futures and return mapping of their results to the provided keys.\n    Just a neat shortcut around ``asyncio.gather()``\n\n    :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )\n    :return: Dict with futures results mapped to keys {'nav': {1:2}, 'content': 'xyz'}\n    \"\"\"\n    ctx_methods = OrderedDict(future_map)\n    fs = list(ctx_methods.values())\n    results = await asyncio.gather(*fs)\n    results = {\n        key: results[idx] for idx, key in enumerate(ctx_methods.keys())\n    }\n    return results", "title": ""}
{"_id": "d18973", "text": "def positive_int(val):\n    \"\"\"Parse `val` into a positive integer.\"\"\"\n    if isinstance(val, float):\n        raise ValueError('\"{}\" must not be a float'.format(val))\n    val = int(val)\n    if val >= 0:\n        return val\n    raise ValueError('\"{}\" must be positive'.format(val))", "title": ""}
{"_id": "d18974", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d18975", "text": "def branches():\n    # type: () -> List[str]\n    \"\"\" Return a list of branches in the current repo.\n\n    Returns:\n        list[str]: A list of branches in the current repo.\n    \"\"\"\n    out = shell.run(\n        'git branch',\n        capture=True,\n        never_pretend=True\n    ).stdout.strip()\n    return [x.strip('* \\t\\n') for x in out.splitlines()]", "title": ""}
{"_id": "d18976", "text": "def execute(cur, *args):\n    \"\"\"Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)\n    \"\"\"\n    stmt = args[0]\n    if len(args) > 1:\n        stmt = stmt.replace('%', '%%').replace('?', '%r')\n        print(stmt % (args[1]))\n    return cur.execute(*args)", "title": ""}
{"_id": "d18977", "text": "def signed_area(coords):\n    \"\"\"Return the signed area enclosed by a ring using the linear time\n    algorithm. A value >= 0 indicates a counter-clockwise oriented ring.\n    \"\"\"\n    xs, ys = map(list, zip(*coords))\n    xs.append(xs[1])\n    ys.append(ys[1])\n    return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, len(coords)))/2.0", "title": ""}
{"_id": "d18978", "text": "def classify_fit(fqdn, result, *argl, **argd):\n    \"\"\"Analyzes the result of a classification algorithm's fitting. See also\n    :func:`fit` for explanation of arguments.\n    \"\"\"\n    if len(argl) > 2:\n        #Usually fit is called with fit(machine, Xtrain, ytrain).\n        yP = argl[2]\n    out = _generic_fit(fqdn, result, classify_predict, yP, *argl, **argd)\n    return out", "title": ""}
{"_id": "d18979", "text": "def thai_to_eng(text: str) -> str:\n    \"\"\"\n    Correct text in one language that is incorrectly-typed with a keyboard layout in another language. (type Thai with English keyboard)\n\n    :param str text: Incorrect input (type English with Thai keyboard)\n    :return: English text\n    \"\"\"\n    return \"\".join(\n        [TH_EN_KEYB_PAIRS[ch] if (ch in TH_EN_KEYB_PAIRS) else ch for ch in text]\n    )", "title": ""}
{"_id": "d18980", "text": "def file_or_stdin() -> Callable:\n    \"\"\"\n    Returns a file descriptor from stdin or opening a file from a given path.\n    \"\"\"\n\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\n    return parse", "title": ""}
{"_id": "d18981", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d18982", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d18983", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d18984", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d18985", "text": "def arcball_map_to_sphere(point, center, radius):\n    \"\"\"Return unit sphere coordinates from window coordinates.\"\"\"\n    v0 = (point[0] - center[0]) / radius\n    v1 = (center[1] - point[1]) / radius\n    n = v0*v0 + v1*v1\n    if n > 1.0:\n        # position outside of sphere\n        n = math.sqrt(n)\n        return numpy.array([v0/n, v1/n, 0.0])\n    else:\n        return numpy.array([v0, v1, math.sqrt(1.0 - n)])", "title": ""}
{"_id": "d18986", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d18987", "text": "def __gt__(self, other):\n        \"\"\"Test for greater than.\"\"\"\n        if isinstance(other, Address):\n            return str(self) > str(other)\n        raise TypeError", "title": ""}
{"_id": "d18988", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d18989", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d18990", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d18991", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d18992", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d18993", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d18994", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d18995", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d18996", "text": "def impose_legend_limit(limit=30, axes=\"gca\", **kwargs):\n    \"\"\"\n    This will erase all but, say, 30 of the legend entries and remake the legend.\n    You'll probably have to move it back into your favorite position at this point.\n    \"\"\"\n    if axes==\"gca\": axes = _pylab.gca()\n\n    # make these axes current\n    _pylab.axes(axes)\n\n    # loop over all the lines_pylab.\n    for n in range(0,len(axes.lines)):\n        if n >  limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label(\"_nolegend_\")\n        if n == limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label(\"...\")\n\n    _pylab.legend(**kwargs)", "title": ""}
{"_id": "d18997", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d18998", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d18999", "text": "def header_status(header):\n    \"\"\"Parse HTTP status line, return status (int) and reason.\"\"\"\n    status_line = header[:header.find('\\r')]\n    # 'HTTP/1.1 200 OK' -> (200, 'OK')\n    fields = status_line.split(None, 2)\n    return int(fields[1]), fields[2]", "title": ""}
{"_id": "d19000", "text": "def mmap(func, iterable):\n    \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n    if sys.version_info[0] > 2:\n        return [i for i in map(func, iterable)]\n    else:\n        return map(func, iterable)", "title": ""}
{"_id": "d19001", "text": "def lower_camel_case_from_underscores(string):\n    \"\"\"generate a lower-cased camelCase string from an underscore_string.\n    For example: my_variable_name -> myVariableName\"\"\"\n    components = string.split('_')\n    string = components[0]\n    for component in components[1:]:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d19002", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d19003", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d19004", "text": "def months_ago(date, nb_months=1):\n    \"\"\"\n    Return the given `date` with `nb_months` substracted from it.\n    \"\"\"\n    nb_years = nb_months // 12\n    nb_months = nb_months % 12\n\n    month_diff = date.month - nb_months\n\n    if month_diff > 0:\n        new_month = month_diff\n    else:\n        new_month = 12 + month_diff\n        nb_years += 1\n\n    return date.replace(day=1, month=new_month, year=date.year - nb_years)", "title": ""}
{"_id": "d19005", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d19006", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d19007", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d19008", "text": "def guess_mimetype(filename):\n    \"\"\"Guesses the mimetype of a file based on the given ``filename``.\n\n    .. code-block:: python\n\n        >>> guess_mimetype('example.txt')\n        'text/plain'\n        >>> guess_mimetype('/foo/bar/example')\n        'application/octet-stream'\n\n    Parameters\n    ----------\n    filename : str\n        The file name or path for which the mimetype is to be guessed\n    \"\"\"\n    fn = os.path.basename(filename)\n    return mimetypes.guess_type(fn)[0] or 'application/octet-stream'", "title": ""}
{"_id": "d19009", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d19010", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d19011", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d19012", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d19013", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d19014", "text": "def exists(self):\n        \"\"\"\n        Determine if any rows exist for the current query.\n\n        :return: Whether the rows exist or not\n        :rtype: bool\n        \"\"\"\n        limit = self.limit_\n\n        result = self.limit(1).count() > 0\n\n        self.limit(limit)\n\n        return result", "title": ""}
{"_id": "d19015", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d19016", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d19017", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d19018", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d19019", "text": "def normalize_pattern(pattern):\n    \"\"\"Converts backslashes in path patterns to forward slashes.\n\n    Doesn't normalize regular expressions - they may contain escapes.\n    \"\"\"\n    if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):\n        pattern = _slashes.sub('/', pattern)\n    if len(pattern) > 1:\n        pattern = pattern.rstrip('/')\n    return pattern", "title": ""}
{"_id": "d19020", "text": "def uniqued(iterable):\n    \"\"\"Return unique list of ``iterable`` items preserving order.\n\n    >>> uniqued('spameggs')\n    ['s', 'p', 'a', 'm', 'e', 'g']\n    \"\"\"\n    seen = set()\n    return [item for item in iterable if item not in seen and not seen.add(item)]", "title": ""}
{"_id": "d19021", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d19022", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d19023", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d19024", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d19025", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d19026", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d19027", "text": "def _collection_literal_to_py_ast(\n    ctx: GeneratorContext, form: Iterable[LispForm]\n) -> Iterable[GeneratedPyAST]:\n    \"\"\"Turn a quoted collection literal of Lisp forms into Python AST nodes.\n\n    This function can only handle constant values. It does not call back into\n    the generic AST generators, so only constant values will be generated down\n    this path.\"\"\"\n    yield from map(partial(_const_val_to_py_ast, ctx), form)", "title": ""}
{"_id": "d19028", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d19029", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d19030", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d19031", "text": "def segment_intersection(start0, end0, start1, end1):\n    r\"\"\"Determine the intersection of two line segments.\n\n    Assumes each line is parametric\n\n    .. math::\n\n       \\begin{alignat*}{2}\n        L_0(s) &= S_0 (1 - s) + E_0 s &&= S_0 + s \\Delta_0 \\\\\n        L_1(t) &= S_1 (1 - t) + E_1 t &&= S_1 + t \\Delta_1.\n       \\end{alignat*}\n\n    To solve :math:`S_0 + s \\Delta_0 = S_1 + t \\Delta_1`, we use the\n    cross product:\n\n    .. math::\n\n       \\left(S_0 + s \\Delta_0\\right) \\times \\Delta_1 =\n           \\left(S_1 + t \\Delta_1\\right) \\times \\Delta_1 \\Longrightarrow\n       s \\left(\\Delta_0 \\times \\Delta_1\\right) =\n           \\left(S_1 - S_0\\right) \\times \\Delta_1.\n\n    Similarly\n\n    .. math::\n\n       \\Delta_0 \\times \\left(S_0 + s \\Delta_0\\right) =\n           \\Delta_0 \\times \\left(S_1 + t \\Delta_1\\right) \\Longrightarrow\n       \\left(S_1 - S_0\\right) \\times \\Delta_0 =\n           \\Delta_0 \\times \\left(S_0 - S_1\\right) =\n           t \\left(\\Delta_0 \\times \\Delta_1\\right).\n\n    .. note::\n\n       Since our points are in :math:`\\mathbf{R}^2`, the \"traditional\"\n       cross product in :math:`\\mathbf{R}^3` will always point in the\n       :math:`z` direction, so in the above we mean the :math:`z`\n       component of the cross product, rather than the entire vector.\n\n    For example, the diagonal lines\n\n    .. math::\n\n       \\begin{align*}\n        L_0(s) &= \\left[\\begin{array}{c} 0 \\\\ 0 \\end{array}\\right] (1 - s) +\n                  \\left[\\begin{array}{c} 2 \\\\ 2 \\end{array}\\right] s \\\\\n        L_1(t) &= \\left[\\begin{array}{c} -1 \\\\ 2 \\end{array}\\right] (1 - t) +\n                  \\left[\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right] t\n       \\end{align*}\n\n    intersect at :math:`L_0\\left(\\frac{1}{4}\\right) =\n    L_1\\left(\\frac{3}{4}\\right) =\n    \\frac{1}{2} \\left[\\begin{array}{c} 1 \\\\ 1 \\end{array}\\right]`.\n\n    .. image:: ../images/segment_intersection1.png\n       :align: center\n\n    .. testsetup:: segment-intersection1, segment-intersection2\n\n       import numpy as np\n       from bezier._geometric_intersection import segment_intersection\n\n    .. doctest:: segment-intersection1\n       :options: +NORMALIZE_WHITESPACE\n\n       >>> start0 = np.asfortranarray([0.0, 0.0])\n       >>> end0 = np.asfortranarray([2.0, 2.0])\n       >>> start1 = np.asfortranarray([-1.0, 2.0])\n       >>> end1 = np.asfortranarray([1.0, 0.0])\n       >>> s, t, _ = segment_intersection(start0, end0, start1, end1)\n       >>> s\n       0.25\n       >>> t\n       0.75\n\n    .. testcleanup:: segment-intersection1\n\n       import make_images\n       make_images.segment_intersection1(start0, end0, start1, end1, s)\n\n    Taking the parallel (but different) lines\n\n    .. math::\n\n       \\begin{align*}\n        L_0(s) &= \\left[\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right] (1 - s) +\n                  \\left[\\begin{array}{c} 0 \\\\ 1 \\end{array}\\right] s \\\\\n        L_1(t) &= \\left[\\begin{array}{c} -1 \\\\ 3 \\end{array}\\right] (1 - t) +\n                  \\left[\\begin{array}{c} 3 \\\\ -1 \\end{array}\\right] t\n       \\end{align*}\n\n    we should be able to determine that the lines don't intersect, but\n    this function is not meant for that check:\n\n    .. image:: ../images/segment_intersection2.png\n       :align: center\n\n    .. doctest:: segment-intersection2\n       :options: +NORMALIZE_WHITESPACE\n\n       >>> start0 = np.asfortranarray([1.0, 0.0])\n       >>> end0 = np.asfortranarray([0.0, 1.0])\n       >>> start1 = np.asfortranarray([-1.0, 3.0])\n       >>> end1 = np.asfortranarray([3.0, -1.0])\n       >>> _, _, success = segment_intersection(start0, end0, start1, end1)\n       >>> success\n       False\n\n    .. testcleanup:: segment-intersection2\n\n       import make_images\n       make_images.segment_intersection2(start0, end0, start1, end1)\n\n    Instead, we use :func:`parallel_lines_parameters`:\n\n    .. testsetup:: segment-intersection2-continued\n\n       import numpy as np\n       from bezier._geometric_intersection import parallel_lines_parameters\n\n       start0 = np.asfortranarray([1.0, 0.0])\n       end0 = np.asfortranarray([0.0, 1.0])\n       start1 = np.asfortranarray([-1.0, 3.0])\n       end1 = np.asfortranarray([3.0, -1.0])\n\n    .. doctest:: segment-intersection2-continued\n\n       >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1)\n       >>> disjoint\n       True\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        start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start\n            vector :math:`S_0` of the parametric line :math:`L_0(s)`.\n        end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end\n            vector :math:`E_0` of the parametric line :math:`L_0(s)`.\n        start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start\n            vector :math:`S_1` of the parametric line :math:`L_1(s)`.\n        end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end\n            vector :math:`E_1` of the parametric line :math:`L_1(s)`.\n\n    Returns:\n        Tuple[float, float, bool]: Pair of :math:`s_{\\ast}` and\n        :math:`t_{\\ast}` such that the lines intersect:\n        :math:`L_0\\left(s_{\\ast}\\right) = L_1\\left(t_{\\ast}\\right)` and then\n        a boolean indicating if an intersection was found (i.e. if the lines\n        aren't parallel).\n    \"\"\"\n    delta0 = end0 - start0\n    delta1 = end1 - start1\n    cross_d0_d1 = _helpers.cross_product(delta0, delta1)\n    if cross_d0_d1 == 0.0:\n        return None, None, False\n\n    else:\n        start_delta = start1 - start0\n        s = _helpers.cross_product(start_delta, delta1) / cross_d0_d1\n        t = _helpers.cross_product(start_delta, delta0) / cross_d0_d1\n        return s, t, True", "title": ""}
{"_id": "d19032", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d19033", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d19034", "text": "def kernel(self, spread=1):\n        \"\"\" This will return whatever kind of kernel we want to use.\n            Must have signature (ndarray size NxM, ndarray size 1xM) -> ndarray size Nx1\n        \"\"\"\n        # TODO: use self.kernel_type to choose function\n\n        def gaussian(data, pixel):\n            return mvn.pdf(data, mean=pixel, cov=spread)\n\n        return gaussian", "title": ""}
{"_id": "d19035", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d19036", "text": "def decode_value(stream):\n    \"\"\"Decode the contents of a value from a serialized stream.\n\n    :param stream: Source data stream\n    :type stream: io.BytesIO\n    :returns: Decoded value\n    :rtype: bytes\n    \"\"\"\n    length = decode_length(stream)\n    (value,) = unpack_value(\">{:d}s\".format(length), stream)\n    return value", "title": ""}
{"_id": "d19037", "text": "def is_intersection(g, n):\n    \"\"\"\n    Determine if a node is an intersection\n\n    graph: 1 -->-- 2 -->-- 3\n\n    >>> is_intersection(g, 2)\n    False\n\n    graph:\n     1 -- 2 -- 3\n          |\n          4\n\n    >>> is_intersection(g, 2)\n    True\n\n    Parameters\n    ----------\n    g : networkx DiGraph\n    n : node id\n\n    Returns\n    -------\n    bool\n\n    \"\"\"\n    return len(set(g.predecessors(n) + g.successors(n))) > 2", "title": ""}
{"_id": "d19038", "text": "def warn_if_nans_exist(X):\n    \"\"\"Warn if nans exist in a numpy array.\"\"\"\n    null_count = count_rows_with_nans(X)\n    total = len(X)\n    percent = 100 * null_count / total\n\n    if null_count > 0:\n        warning_message = \\\n            'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n            'complete rows will be plotted.'.format(null_count, total, percent)\n        warnings.warn(warning_message, DataWarning)", "title": ""}
{"_id": "d19039", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d19040", "text": "def has_synset(word: str) -> list:\n    \"\"\"\" Returns a list of synsets of a word after lemmatization. \"\"\"\n\n    return wn.synsets(lemmatize(word, neverstem=True))", "title": ""}
{"_id": "d19041", "text": "def lint(fmt='colorized'):\n    \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\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)", "title": ""}
{"_id": "d19042", "text": "def getPiLambert(n):\n    \"\"\"Returns a list containing first n digits of Pi\n    \"\"\"\n    mypi = piGenLambert()\n    result = []\n    if n > 0:\n        result += [next(mypi) for i in range(n)]\n    mypi.close()\n    return result", "title": ""}
{"_id": "d19043", "text": "def after_third_friday(day=None):\n    \"\"\" check if day is after month's 3rd friday \"\"\"\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", "title": ""}
{"_id": "d19044", "text": "def _get_latest_version():\n    \"\"\"Gets latest Dusty binary version using the GitHub api\"\"\"\n    url = 'https://api.github.com/repos/{}/releases/latest'.format(constants.DUSTY_GITHUB_PATH)\n    conn = urllib.urlopen(url)\n    if conn.getcode() >= 300:\n        raise RuntimeError('GitHub api returned code {}; can\\'t determine latest version.  Aborting'.format(conn.getcode()))\n    json_data = conn.read()\n    return json.loads(json_data)['tag_name']", "title": ""}
{"_id": "d19045", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d19046", "text": "def inverted_dict_of_lists(d):\n    \"\"\"Return a dict where the keys are all the values listed in the values of the original dict\n\n    >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1}\n    True\n    \"\"\"\n    new_dict = {}\n    for (old_key, old_value_list) in viewitems(dict(d)):\n        for new_key in listify(old_value_list):\n            new_dict[new_key] = old_key\n    return new_dict", "title": ""}
{"_id": "d19047", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d19048", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d19049", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d19050", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d19051", "text": "def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:\n    \"\"\"\n    Test if two objects are equal, based on a comparison of the specified\n    attributes ``attrs``.\n    \"\"\"\n    return all(getattr(one, a) == getattr(two, a) for a in attrs)", "title": ""}
{"_id": "d19052", "text": "def decode_value(stream):\n    \"\"\"Decode the contents of a value from a serialized stream.\n\n    :param stream: Source data stream\n    :type stream: io.BytesIO\n    :returns: Decoded value\n    :rtype: bytes\n    \"\"\"\n    length = decode_length(stream)\n    (value,) = unpack_value(\">{:d}s\".format(length), stream)\n    return value", "title": ""}
{"_id": "d19053", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d19054", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d19055", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d19056", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d19057", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d19058", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d19059", "text": "def to_iso_string(self) -> str:\n        \"\"\" Returns full ISO string for the given date \"\"\"\n        assert isinstance(self.value, datetime)\n        return datetime.isoformat(self.value)", "title": ""}
{"_id": "d19060", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d19061", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d19062", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d19063", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d19064", "text": "def shift(self, m: Union[float, pd.Series]) -> Union[int, pd.Series]:\n        \"\"\"Shifts floats so that the first 10 decimal digits are significant.\"\"\"\n        out = m % 1 * self.TEN_DIGIT_MODULUS // 1\n        if isinstance(out, pd.Series):\n            return out.astype(int)\n        return int(out)", "title": ""}
{"_id": "d19065", "text": "def is_empty_shape(sh: ShExJ.Shape) -> bool:\n        \"\"\" Determine whether sh has any value \"\"\"\n        return sh.closed is None and sh.expression is None and sh.extra is None and \\\n            sh.semActs is None", "title": ""}
{"_id": "d19066", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d19067", "text": "def get_window_dim():\n    \"\"\" gets the dimensions depending on python version and os\"\"\"\n    version = sys.version_info\n\n    if version >= (3, 3):\n        return _size_36()\n    if platform.system() == 'Windows':\n        return _size_windows()\n    return _size_27()", "title": ""}
{"_id": "d19068", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d19069", "text": "def sort_by_modified(files_or_folders: list) -> list:\n    \"\"\"\n    Sort files or folders by modified time\n\n    Args:\n        files_or_folders: list of files or folders\n\n    Returns:\n        list\n    \"\"\"\n    return sorted(files_or_folders, key=os.path.getmtime, reverse=True)", "title": ""}
{"_id": "d19070", "text": "def execute(cur, *args):\n    \"\"\"Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)\n    \"\"\"\n    stmt = args[0]\n    if len(args) > 1:\n        stmt = stmt.replace('%', '%%').replace('?', '%r')\n        print(stmt % (args[1]))\n    return cur.execute(*args)", "title": ""}
{"_id": "d19071", "text": "def kdot(x, y, K=2):\n    \"\"\"Algorithm 5.10. Dot product algorithm in K-fold working precision,\n    K >= 3.\n    \"\"\"\n    xx = x.reshape(-1, x.shape[-1])\n    yy = y.reshape(y.shape[0], -1)\n\n    xx = numpy.ascontiguousarray(xx)\n    yy = numpy.ascontiguousarray(yy)\n\n    r = _accupy.kdot_helper(xx, yy).reshape((-1,) + x.shape[:-1] + y.shape[1:])\n    return ksum(r, K - 1)", "title": ""}
{"_id": "d19072", "text": "def uniqued(iterable):\n    \"\"\"Return unique list of ``iterable`` items preserving order.\n\n    >>> uniqued('spameggs')\n    ['s', 'p', 'a', 'm', 'e', 'g']\n    \"\"\"\n    seen = set()\n    return [item for item in iterable if item not in seen and not seen.add(item)]", "title": ""}
{"_id": "d19073", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d19074", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d19075", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d19076", "text": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "title": ""}
{"_id": "d19077", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d19078", "text": "def lowercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the lowercase chars in the given string.\"\"\"\n        return ''.join([c if c.islower() else '' for c in str(string)])", "title": ""}
{"_id": "d19079", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d19080", "text": "def pad(a, desiredlength):\n    \"\"\"\n    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\n    \"\"\"\n\n    if len(a) >= desiredlength:\n        return a\n\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\n    padded = np.concatenate([a, np.zeros(shape, dtype=a.dtype)])\n    return padded.tolist() if islist else padded", "title": ""}
{"_id": "d19081", "text": "def clean_int(x) -> int:\n    \"\"\"\n    Returns its parameter as an integer, or raises\n    ``django.forms.ValidationError``.\n    \"\"\"\n    try:\n        return int(x)\n    except ValueError:\n        raise forms.ValidationError(\n            \"Cannot convert to integer: {}\".format(repr(x)))", "title": ""}
{"_id": "d19082", "text": "def get_language():\n    \"\"\"\n    Wrapper around Django's `get_language` utility.\n    For Django >= 1.8, `get_language` returns None in case no translation is activate.\n    Here we patch this behavior e.g. for back-end functionality requiring access to translated fields\n    \"\"\"\n    from parler import appsettings\n    language = dj_get_language()\n    if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:\n        return appsettings.PARLER_DEFAULT_LANGUAGE_CODE\n    else:\n        return language", "title": ""}
{"_id": "d19083", "text": "def _darwin_current_arch(self):\n        \"\"\"Add Mac OS X support.\"\"\"\n        if sys.platform == \"darwin\":\n            if sys.maxsize > 2 ** 32: # 64bits.\n                return platform.mac_ver()[2] # Both Darwin and Python are 64bits.\n            else: # Python 32 bits\n                return platform.processor()", "title": ""}
{"_id": "d19084", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d19085", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d19086", "text": "def usetz_now():\n    \"\"\"Determine current time depending on USE_TZ setting.\n\n    Affects Django 1.4 and above only. if `USE_TZ = True`, then returns\n    current time according to timezone, else returns current UTC time.\n\n    \"\"\"\n    USE_TZ = getattr(settings, 'USE_TZ', False)\n    if USE_TZ and DJANGO_VERSION >= '1.4':\n        return now()\n    else:\n        return datetime.utcnow()", "title": ""}
{"_id": "d19087", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d19088", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d19089", "text": "def _parse_date(string: str) -> datetime.date:\n    \"\"\"Parse an ISO format date (YYYY-mm-dd).\n\n    >>> _parse_date('1990-01-02')\n    datetime.date(1990, 1, 2)\n    \"\"\"\n    return datetime.datetime.strptime(string, '%Y-%m-%d').date()", "title": ""}
{"_id": "d19090", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d19091", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d19092", "text": "def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, convert\n    (in place) ``d[key]`` to a float. If that fails, convert it to ``None``.\n    \"\"\"\n    for d in dict_list:\n        try:\n            d[key] = float(d[key])\n        except ValueError:\n            d[key] = None", "title": ""}
{"_id": "d19093", "text": "def infer_format(filename:str) -> str:\n    \"\"\"Return extension identifying format of given filename\"\"\"\n    _, ext = os.path.splitext(filename)\n    return ext", "title": ""}
{"_id": "d19094", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d19095", "text": "def lowercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the lowercase chars in the given string.\"\"\"\n        return ''.join([c if c.islower() else '' for c in str(string)])", "title": ""}
{"_id": "d19096", "text": "def normalize_column_names(df):\n    r\"\"\" Clean up whitespace in column names. See better version at `pugnlp.clean_columns`\n\n    >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here'])\n    >>> normalize_column_names(df)\n    ['hello_world', 'not_here']\n    \"\"\"\n    columns = df.columns if hasattr(df, 'columns') else df\n    columns = [c.lower().replace(' ', '_') for c in columns]\n    return columns", "title": ""}
{"_id": "d19097", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d19098", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d19099", "text": "def command(self, cmd, *args):\n        \"\"\"\n        Sends a command and an (optional) sequence of arguments through to the\n        delegated serial interface. Note that the arguments are passed through\n        as data.\n        \"\"\"\n        self._serial_interface.command(cmd)\n        if len(args) > 0:\n            self._serial_interface.data(list(args))", "title": ""}
{"_id": "d19100", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d19101", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d19102", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d19103", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d19104", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d19105", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d19106", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d19107", "text": "def bulk_load_docs(es, docs):\n    \"\"\"Bulk load docs\n\n    Args:\n        es: elasticsearch handle\n        docs: Iterator of doc objects - includes index_name\n    \"\"\"\n\n    chunk_size = 200\n\n    try:\n        results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)\n        log.debug(f\"Elasticsearch documents loaded: {results[0]}\")\n\n        # elasticsearch.helpers.parallel_bulk(es, terms, chunk_size=chunk_size, thread_count=4)\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))", "title": ""}
{"_id": "d19108", "text": "def _parse_date(string: str) -> datetime.date:\n    \"\"\"Parse an ISO format date (YYYY-mm-dd).\n\n    >>> _parse_date('1990-01-02')\n    datetime.date(1990, 1, 2)\n    \"\"\"\n    return datetime.datetime.strptime(string, '%Y-%m-%d').date()", "title": ""}
{"_id": "d19109", "text": "def get_codes(s: Union[str, 'ChainedBase']) -> List[str]:\n    \"\"\" Grab all escape codes from a string.\n        Returns a list of all escape codes.\n    \"\"\"\n    return codegrabpat.findall(str(s))", "title": ""}
{"_id": "d19110", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d19111", "text": "def hex_color_to_tuple(hex):\n    \"\"\" convent hex color to tuple\n    \"#ffffff\"   ->  (255, 255, 255)\n    \"#ffff00ff\" ->  (255, 255, 0, 255)\n    \"\"\"\n    hex = hex[1:]\n    length = len(hex) // 2\n    return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))", "title": ""}
{"_id": "d19112", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d19113", "text": "def is_valid(cls, arg):\n        \"\"\"Return True if arg is valid value for the class.  If the string\n        value is wrong for the enumeration, the encoding will fail.\n        \"\"\"\n        return (isinstance(arg, (int, long)) and (arg >= 0)) or \\\n            isinstance(arg, basestring)", "title": ""}
{"_id": "d19114", "text": "def setdefault(self, name: str, default: Any=None) -> Any:\n        \"\"\"Set an attribute with a default value.\"\"\"\n        return self.__dict__.setdefault(name, default)", "title": ""}
{"_id": "d19115", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d19116", "text": "def decode(string, base):\n    \"\"\"\n    Given a string (string) and a numeric base (base),\n    decode the string into an integer.\n\n    Returns the integer\n    \"\"\"\n\n    base = int(base)\n    code_string = get_code_string(base)\n    result = 0\n    if base == 16:\n        string = string.lower()\n    while len(string) > 0:\n        result *= base\n        result += code_string.find(string[0])\n        string = string[1:]\n    return result", "title": ""}
{"_id": "d19117", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d19118", "text": "def enrich_complexes(graph: BELGraph) -> None:\n    \"\"\"Add all of the members of the complex abundances to the graph.\"\"\"\n    nodes = list(get_nodes_by_function(graph, COMPLEX))\n    for u in nodes:\n        for v in u.members:\n            graph.add_has_component(u, v)", "title": ""}
{"_id": "d19119", "text": "def get_datatype(self, table: str, column: str) -> str:\n        \"\"\"Returns database SQL datatype for a column: e.g. VARCHAR.\"\"\"\n        return self.flavour.get_datatype(self, table, column).upper()", "title": ""}
{"_id": "d19120", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d19121", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d19122", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d19123", "text": "def is_orthogonal(\n        matrix: np.ndarray,\n        *,\n        rtol: float = 1e-5,\n        atol: float = 1e-8) -> bool:\n    \"\"\"Determines if a matrix is approximately orthogonal.\n\n    A matrix is orthogonal if it's square and real and its transpose is its\n    inverse.\n\n    Args:\n        matrix: The matrix to check.\n        rtol: The per-matrix-entry relative tolerance on equality.\n        atol: The per-matrix-entry absolute tolerance on equality.\n\n    Returns:\n        Whether the matrix is orthogonal within the given tolerance.\n    \"\"\"\n    return (matrix.shape[0] == matrix.shape[1] and\n            np.all(np.imag(matrix) == 0) and\n            np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]),\n                        rtol=rtol,\n                        atol=atol))", "title": ""}
{"_id": "d19124", "text": "def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray:\n        \"\"\"Create an identical 2d array where the second row is filled with value\"\"\"\n        b = np.full((2, len(sample)), value, dtype=float)\n        b[0] = sample\n        return b", "title": ""}
{"_id": "d19125", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d19126", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d19127", "text": "def input_validate_str(string, name, max_len=None, exact_len=None):\n    \"\"\" Input validation for strings. \"\"\"\n    if type(string) is not str:\n        raise pyhsm.exception.YHSM_WrongInputType(name, str, type(string))\n    if max_len != None and len(string) > max_len:\n        raise pyhsm.exception.YHSM_InputTooLong(name, max_len, len(string))\n    if exact_len != None and len(string) != exact_len:\n        raise pyhsm.exception.YHSM_WrongInputSize(name, exact_len, len(string))\n    return string", "title": ""}
{"_id": "d19128", "text": "def issuperset(self, items):\n        \"\"\"Return whether this collection contains all items.\n\n        >>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])\n        True\n        \"\"\"\n        return all(_compat.map(self._seen.__contains__, items))", "title": ""}
{"_id": "d19129", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d19130", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d19131", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d19132", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d19133", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d19134", "text": "def has_changed (filename):\n    \"\"\"Check if filename has changed since the last check. If this\n    is the first check, assume the file is changed.\"\"\"\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]", "title": ""}
{"_id": "d19135", "text": "def connect_to_database_odbc_access(self,\n                                        dsn: str,\n                                        autocommit: bool = True) -> None:\n        \"\"\"Connects to an Access database via ODBC, with the DSN\n        prespecified.\"\"\"\n        self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,\n                     dsn=dsn, autocommit=autocommit)", "title": ""}
{"_id": "d19136", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d19137", "text": "def _get_tuple(self, fields):\n    \"\"\"\n    :param fields: a list which contains either 0,1,or 2 values\n    :return: a tuple with default values of '';\n    \"\"\"\n    v1 = ''\n    v2 = ''\n    if len(fields) > 0:\n      v1 = fields[0]\n    if len(fields) > 1:\n      v2 = fields[1]\n    return v1, v2", "title": ""}
{"_id": "d19138", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d19139", "text": "def autoreload(self, parameter_s=''):\n        r\"\"\"%autoreload => Reload modules automatically\n\n        %autoreload\n        Reload all modules (except those excluded by %aimport) automatically\n        now.\n\n        %autoreload 0\n        Disable automatic reloading.\n\n        %autoreload 1\n        Reload all modules imported with %aimport every time before executing\n        the Python code typed.\n\n        %autoreload 2\n        Reload all modules (except those excluded by %aimport) every time\n        before executing the Python code typed.\n\n        Reloading Python modules in a reliable way is in general\n        difficult, and unexpected things may occur. %autoreload tries to\n        work around common pitfalls by replacing function code objects and\n        parts of classes previously in the module with new versions. This\n        makes the following things to work:\n\n        - Functions and classes imported via 'from xxx import foo' are upgraded\n          to new versions when 'xxx' is reloaded.\n\n        - Methods and properties of classes are upgraded on reload, so that\n          calling 'c.foo()' on an object 'c' created before the reload causes\n          the new code for 'foo' to be executed.\n\n        Some of the known remaining caveats are:\n\n        - Replacing code objects does not always succeed: changing a @property\n          in a class to an ordinary method or a method to a member variable\n          can cause problems (but in old objects only).\n\n        - Functions that are removed (eg. via monkey-patching) from a module\n          before it is reloaded are not upgraded.\n\n        - C extension modules cannot be reloaded, and so cannot be\n          autoreloaded.\n\n        \"\"\"\n        if parameter_s == '':\n            self._reloader.check(True)\n        elif parameter_s == '0':\n            self._reloader.enabled = False\n        elif parameter_s == '1':\n            self._reloader.check_all = False\n            self._reloader.enabled = True\n        elif parameter_s == '2':\n            self._reloader.check_all = True\n            self._reloader.enabled = True", "title": ""}
{"_id": "d19140", "text": "def _centroids(n_clusters: int, points: List[List[float]]) -> List[List[float]]:\n    \"\"\" Return n_clusters centroids of points\n    \"\"\"\n\n    k_means = KMeans(n_clusters=n_clusters)\n    k_means.fit(points)\n\n    closest, _ = pairwise_distances_argmin_min(k_means.cluster_centers_, points)\n\n    return list(map(list, np.array(points)[closest.tolist()]))", "title": ""}
{"_id": "d19141", "text": "def product(*args, **kwargs):\n    \"\"\" Yields all permutations with replacement:\n        list(product(\"cat\", repeat=2)) => \n        [(\"c\", \"c\"), \n         (\"c\", \"a\"), \n         (\"c\", \"t\"), \n         (\"a\", \"c\"), \n         (\"a\", \"a\"), \n         (\"a\", \"t\"), \n         (\"t\", \"c\"), \n         (\"t\", \"a\"), \n         (\"t\", \"t\")]\n    \"\"\"\n    p = [[]]\n    for iterable in map(tuple, args) * kwargs.get(\"repeat\", 1):\n        p = [x + [y] for x in p for y in iterable]\n    for p in p:\n        yield tuple(p)", "title": ""}
{"_id": "d19142", "text": "def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:\n    \"\"\"Return the inner product between two tensors\"\"\"\n    # Note: Relying on fact that vdot flattens arrays\n    return np.vdot(tensor0, tensor1)", "title": ""}
{"_id": "d19143", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d19144", "text": "def _sum_cycles_from_tokens(self, tokens: List[str]) -> int:\n        \"\"\"Sum the total number of cycles over a list of tokens.\"\"\"\n        return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))", "title": ""}
{"_id": "d19145", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d19146", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d19147", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d19148", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d19149", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d19150", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d19151", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d19152", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d19153", "text": "def chars(string: any) -> str:\n        \"\"\"Return all (and only) the chars in the given string.\"\"\"\n        return ''.join([c if c.isalpha() else '' for c in str(string)])", "title": ""}
{"_id": "d19154", "text": "def rms(x):\n    \"\"\"\"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\n    \"\"\"\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", "title": ""}
{"_id": "d19155", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d19156", "text": "def get_unique_links(self):\n        \"\"\" Get all unique links in the html of the page source.\n            Page links include those obtained from:\n            \"a\"->\"href\", \"img\"->\"src\", \"link\"->\"href\", and \"script\"->\"src\". \"\"\"\n        page_url = self.get_current_url()\n        soup = self.get_beautiful_soup(self.get_page_source())\n        links = page_utils._get_unique_links(page_url, soup)\n        return links", "title": ""}
{"_id": "d19157", "text": "def is_prime(n):\n    \"\"\"\n    Check if n is a prime number\n    \"\"\"\n    if n % 2 == 0 and n > 2:\n        return False\n    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "title": ""}
{"_id": "d19158", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d19159", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d19160", "text": "def datetime_from_isoformat(value: str):\n    \"\"\"Return a datetime object from an isoformat string.\n\n    Args:\n        value (str): Datetime string in isoformat.\n\n    \"\"\"\n    if sys.version_info >= (3, 7):\n        return datetime.fromisoformat(value)\n\n    return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')", "title": ""}
{"_id": "d19161", "text": "def samefile(a: str, b: str) -> bool:\n    \"\"\"Check if two pathes represent the same file.\"\"\"\n    try:\n        return os.path.samefile(a, b)\n    except OSError:\n        return os.path.normpath(a) == os.path.normpath(b)", "title": ""}
{"_id": "d19162", "text": "def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None:\n    \"\"\"mouse_event from Win32.\"\"\"\n    ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)", "title": ""}
{"_id": "d19163", "text": "def setup_cache(app: Flask, cache_config) -> Optional[Cache]:\n    \"\"\"Setup the flask-cache on a flask app\"\"\"\n    if cache_config and cache_config.get('CACHE_TYPE') != 'null':\n        return Cache(app, config=cache_config)\n\n    return None", "title": ""}
{"_id": "d19164", "text": "def _find_conda():\n    \"\"\"Find the conda executable robustly across conda versions.\n\n    Returns\n    -------\n    conda : str\n        Path to the conda executable.\n\n    Raises\n    ------\n    IOError\n        If the executable cannot be found in either the CONDA_EXE environment\n        variable or in the PATH.\n\n    Notes\n    -----\n    In POSIX platforms in conda >= 4.4, conda can be set up as a bash function\n    rather than an executable. (This is to enable the syntax\n    ``conda activate env-name``.) In this case, the environment variable\n    ``CONDA_EXE`` contains the path to the conda executable. In other cases,\n    we use standard search for the appropriate name in the PATH.\n\n    See https://github.com/airspeed-velocity/asv/issues/645 for more details.\n    \"\"\"\n    if 'CONDA_EXE' in os.environ:\n        conda = os.environ['CONDA_EXE']\n    else:\n        conda = util.which('conda')\n    return conda", "title": ""}
{"_id": "d19165", "text": "def multi_split(s, split):\n    # type: (S, Iterable[S]) -> List[S]\n    \"\"\"Splits on multiple given separators.\"\"\"\n    for r in split:\n        s = s.replace(r, \"|\")\n    return [i for i in s.split(\"|\") if len(i) > 0]", "title": ""}
{"_id": "d19166", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d19167", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d19168", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d19169", "text": "def clean_int(x) -> int:\n    \"\"\"\n    Returns its parameter as an integer, or raises\n    ``django.forms.ValidationError``.\n    \"\"\"\n    try:\n        return int(x)\n    except ValueError:\n        raise forms.ValidationError(\n            \"Cannot convert to integer: {}\".format(repr(x)))", "title": ""}
{"_id": "d19170", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d19171", "text": "def list_depth(list_, func=max, _depth=0):\n    \"\"\"\n    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)\n\n    \"\"\"\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", "title": ""}
{"_id": "d19172", "text": "def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool:\n    \"\"\"Return true if given node is inside lambda\"\"\"\n    parent = node.parent\n    while parent is not None:\n        if isinstance(parent, astroid.Lambda):\n            return True\n        parent = parent.parent\n    return False", "title": ""}
{"_id": "d19173", "text": "def get_unique_links(self):\n        \"\"\" Get all unique links in the html of the page source.\n            Page links include those obtained from:\n            \"a\"->\"href\", \"img\"->\"src\", \"link\"->\"href\", and \"script\"->\"src\". \"\"\"\n        page_url = self.get_current_url()\n        soup = self.get_beautiful_soup(self.get_page_source())\n        links = page_utils._get_unique_links(page_url, soup)\n        return links", "title": ""}
{"_id": "d19174", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d19175", "text": "def identify_request(request: RequestType) -> bool:\n    \"\"\"\n    Try to identify whether this is an ActivityPub request.\n    \"\"\"\n    # noinspection PyBroadException\n    try:\n        data = json.loads(decode_if_bytes(request.body))\n        if \"@context\" in data:\n            return True\n    except Exception:\n        pass\n    return False", "title": ""}
{"_id": "d19176", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d19177", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d19178", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d19179", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d19180", "text": "def enum_mark_last(iterable, start=0):\n    \"\"\"\n    Returns a generator over iterable that tells whether the current item is the last one.\n    Usage:\n        >>> iterable = range(10)\n        >>> for index, is_last, item in enum_mark_last(iterable):\n        >>>     print(index, item, end='\\n' if is_last else ', ')\n    \"\"\"\n    it = iter(iterable)\n    count = start\n    try:\n        last = next(it)\n    except StopIteration:\n        return\n    for val in it:\n        yield count, False, last\n        last = val\n        count += 1\n    yield count, True, last", "title": ""}
{"_id": "d19181", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d19182", "text": "def get_all_args(fn) -> list:\n    \"\"\"\n    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']\n    \"\"\"\n    sig = inspect.signature(fn)\n    return list(sig.parameters)", "title": ""}
{"_id": "d19183", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d19184", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d19185", "text": "def copy_session(session: requests.Session) -> requests.Session:\n    \"\"\"Duplicates a requests.Session.\"\"\"\n    new = requests.Session()\n    new.cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies))\n    new.headers = session.headers.copy()\n    return new", "title": ""}
{"_id": "d19186", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d19187", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d19188", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d19189", "text": "def enumerate_chunks (phrase, spacy_nlp):\n    \"\"\"\n    iterate through the noun phrases\n    \"\"\"\n    if (len(phrase) > 1):\n        found = False\n        text = \" \".join([rl.text for rl in phrase])\n        doc = spacy_nlp(text.strip(), parse=True)\n\n        for np in doc.noun_chunks:\n            if np.text != text:\n                found = True\n                yield np.text, find_chunk(phrase, np.text.split(\" \"))\n\n        if not found and all([rl.pos[0] != \"v\" for rl in phrase]):\n            yield text, phrase", "title": ""}
{"_id": "d19190", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d19191", "text": "def convert_column(self, values):\n        \"\"\"Normalize values.\"\"\"\n        assert all(values >= 0), 'Cannot normalize a column with negatives'\n        total = sum(values)\n        if total > 0:\n            return values / total\n        else:\n            return values", "title": ""}
{"_id": "d19192", "text": "def __next__(self):\n        \"\"\"\n        :return: int\n        \"\"\"\n        self.current += 1\n        if self.current > self.total:\n            raise StopIteration\n        else:\n            return self.iterable[self.current - 1]", "title": ""}
{"_id": "d19193", "text": "def uniqued(iterable):\n    \"\"\"Return unique list of items preserving order.\n\n    >>> uniqued([3, 2, 1, 3, 2, 1, 0])\n    [3, 2, 1, 0]\n    \"\"\"\n    seen = set()\n    add = seen.add\n    return [i for i in iterable if i not in seen and not add(i)]", "title": ""}
{"_id": "d19194", "text": "def run_web(self, flask, host='127.0.0.1', port=5000, **options):\n        # type: (Zsl, str, int, **Any)->None\n        \"\"\"Alias for Flask.run\"\"\"\n        return flask.run(\n            host=flask.config.get('FLASK_HOST', host),\n            port=flask.config.get('FLASK_PORT', port),\n            debug=flask.config.get('DEBUG', False),\n            **options\n        )", "title": ""}
{"_id": "d19195", "text": "def wipe_table(self, table: str) -> int:\n        \"\"\"Delete all records from a table. Use caution!\"\"\"\n        sql = \"DELETE FROM \" + self.delimit(table)\n        return self.db_exec(sql)", "title": ""}
{"_id": "d19196", "text": "def write_text(filename: str, text: str) -> None:\n    \"\"\"\n    Writes text to a file.\n    \"\"\"\n    with open(filename, 'w') as f:  # type: TextIO\n        print(text, file=f)", "title": ""}
{"_id": "d19197", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d19198", "text": "def fast_median(a):\n    \"\"\"Fast median operation for masked array using 50th-percentile\n    \"\"\"\n    a = checkma(a)\n    #return scoreatpercentile(a.compressed(), 50)\n    if a.count() > 0:\n        out = np.percentile(a.compressed(), 50)\n    else:\n        out = np.ma.masked\n    return out", "title": ""}
{"_id": "d19199", "text": "def _is_video(filepath) -> bool:\n    \"\"\"Check filename extension to see if it's a video file.\"\"\"\n    if os.path.exists(filepath):  # Could be broken symlink\n        extension = os.path.splitext(filepath)[1]\n        return extension in ('.mkv', '.mp4', '.avi')\n    else:\n        return False", "title": ""}
{"_id": "d19200", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d19201", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d19202", "text": "def shape(self) -> Tuple[int, ...]:\n        \"\"\"Shape of histogram's data.\n\n        Returns\n        -------\n        One-element tuple with the number of bins along each axis.\n        \"\"\"\n        return tuple(bins.bin_count for bins in self._binnings)", "title": ""}
{"_id": "d19203", "text": "def str_upper(x):\n    \"\"\"Converts all strings in a column to uppercase.\n\n    :returns: an expression containing the converted strings.\n\n    Example:\n\n    >>> import vaex\n    >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']\n    >>> df = vaex.from_arrays(text=text)\n    >>> df\n      #  text\n      0  Something\n      1  very pretty\n      2  is coming\n      3  our\n      4  way.\n\n\n    >>> df.text.str.upper()\n    Expression = str_upper(text)\n    Length: 5 dtype: str (expression)\n    ---------------------------------\n    0    SOMETHING\n    1  VERY PRETTY\n    2    IS COMING\n    3          OUR\n    4         WAY.\n\n    \"\"\"\n    sl = _to_string_sequence(x).upper()\n    return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)", "title": ""}
{"_id": "d19204", "text": "def combine_pdf_as_bytes(pdfs: List[BytesIO]) -> bytes:\n    \"\"\"Combine PDFs and return a byte-string with the result.\n\n    Arguments\n    ---------\n    pdfs\n        A list of BytesIO representations of PDFs\n\n    \"\"\"\n    writer = PdfWriter()\n    for pdf in pdfs:\n        writer.addpages(PdfReader(pdf).pages)\n    bio = BytesIO()\n    writer.write(bio)\n    bio.seek(0)\n    output = bio.read()\n    bio.close()\n    return output", "title": ""}
{"_id": "d19205", "text": "def cpu_count() -> int:\n    \"\"\"Returns the number of processors on this machine.\"\"\"\n    if multiprocessing is None:\n        return 1\n    try:\n        return multiprocessing.cpu_count()\n    except NotImplementedError:\n        pass\n    try:\n        return os.sysconf(\"SC_NPROCESSORS_CONF\")\n    except (AttributeError, ValueError):\n        pass\n    gen_log.error(\"Could not detect number of processors; assuming 1\")\n    return 1", "title": ""}
{"_id": "d19206", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d19207", "text": "def to_np(*args):\n    \"\"\" convert GPU arras to numpy and return them\"\"\"\n    if len(args) > 1:\n        return (cp.asnumpy(x) for x in args)\n    else:\n        return cp.asnumpy(args[0])", "title": ""}
{"_id": "d19208", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d19209", "text": "def psutil_phymem_usage():\n    \"\"\"\n    Return physical memory usage (float)\n    Requires the cross-platform psutil (>=v0.3) library\n    (https://github.com/giampaolo/psutil)\n    \"\"\"\n    import psutil\n    # This is needed to avoid a deprecation warning error with\n    # newer psutil versions\n    try:\n        percent = psutil.virtual_memory().percent\n    except:\n        percent = psutil.phymem_usage().percent\n    return percent", "title": ""}
{"_id": "d19210", "text": "def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]:\n    \"\"\" Partition a list of integers into a list of partitions \"\"\"\n    for part in algorithm_u(range(size), nparts):\n        yield part", "title": ""}
{"_id": "d19211", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d19212", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d19213", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d19214", "text": "def session_expired(self):\n        \"\"\"\n        Returns True if login_time not set or seconds since\n        login time is greater than 200 mins.\n        \"\"\"\n        if not self._login_time or (datetime.datetime.now()-self._login_time).total_seconds() > 12000:\n            return True", "title": ""}
{"_id": "d19215", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d19216", "text": "def random_name_gen(size=6):\n    \"\"\"Generate a random python attribute name.\"\"\"\n\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 ''", "title": ""}
{"_id": "d19217", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d19218", "text": "def repl_complete(text: str, state: int) -> Optional[str]:\n    \"\"\"Completer function for Python's readline/libedit implementation.\"\"\"\n    # Can't complete Keywords, Numerals\n    if __NOT_COMPLETEABLE.match(text):\n        return None\n    elif text.startswith(\":\"):\n        completions = kw.complete(text)\n    else:\n        ns = get_current_ns()\n        completions = ns.complete(text)\n\n    return list(completions)[state] if completions is not None else None", "title": ""}
{"_id": "d19219", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d19220", "text": "def _brief_print_list(lst, limit=7):\n    \"\"\"Print at most `limit` elements of list.\"\"\"\n    lst = list(lst)\n    if len(lst) > limit:\n        return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \\\n            _brief_print_list(lst[-limit//2:], limit)\n    return ', '.join([\"'%s'\"%str(i) for i in lst])", "title": ""}
{"_id": "d19221", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d19222", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d19223", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d19224", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d19225", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d19226", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d19227", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d19228", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d19229", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d19230", "text": "def ranges_to_set(lst):\n    \"\"\"\n    Convert a list of ranges to a set of numbers::\n\n    >>> ranges = [(1,3), (5,6)]\n    >>> sorted(list(ranges_to_set(ranges)))\n    [1, 2, 3, 5, 6]\n\n    \"\"\"\n    return set(itertools.chain(*(range(x[0], x[1]+1) for x in lst)))", "title": ""}
{"_id": "d19231", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d19232", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d19233", "text": "def make_dep_graph(depender):\n\t\"\"\"Returns a digraph string fragment based on the passed-in module\n\t\"\"\"\n\tshutit_global.shutit_global_object.yield_to_draw()\n\tdigraph = ''\n\tfor dependee_id in depender.depends_on:\n\t\tdigraph = (digraph + '\"' + depender.module_id + '\"->\"' + dependee_id + '\";\\n')\n\treturn digraph", "title": ""}
{"_id": "d19234", "text": "def quaternion_imag(quaternion):\n    \"\"\"Return imaginary part of quaternion.\n\n    >>> quaternion_imag([3, 0, 1, 2])\n    array([ 0.,  1.,  2.])\n\n    \"\"\"\n    return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)", "title": ""}
{"_id": "d19235", "text": "def multiple_replace(string, replacements):\n    # type: (str, Dict[str,str]) -> str\n    \"\"\"Simultaneously replace multiple strigns in a string\n\n    Args:\n        string (str): Input string\n        replacements (Dict[str,str]): Replacements dictionary\n\n    Returns:\n        str: String with replacements\n\n    \"\"\"\n    pattern = re.compile(\"|\".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL)\n    return pattern.sub(lambda x: replacements[x.group(0)], string)", "title": ""}
{"_id": "d19236", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d19237", "text": "def _read_section(self):\n        \"\"\"Read and return an entire section\"\"\"\n        lines = [self._last[self._last.find(\":\")+1:]]\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            lines.append(self._last)\n            self._last = self._f.readline()\n        return lines", "title": ""}
{"_id": "d19238", "text": "def get_tokens(line: str) -> Iterator[str]:\n    \"\"\"\n    Yields tokens from input string.\n\n    :param line: Input string.\n    :return: Iterator over tokens.\n    \"\"\"\n    for token in line.rstrip().split():\n        if len(token) > 0:\n            yield token", "title": ""}
{"_id": "d19239", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d19240", "text": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "title": ""}
{"_id": "d19241", "text": "def _prm_get_longest_stringsize(string_list):\n        \"\"\" Returns the longest string size for a string entry across data.\"\"\"\n        maxlength = 1\n\n        for stringar in string_list:\n            if isinstance(stringar, np.ndarray):\n                if stringar.ndim > 0:\n                    for string in stringar.ravel():\n                        maxlength = max(len(string), maxlength)\n                else:\n                    maxlength = max(len(stringar.tolist()), maxlength)\n            else:\n                maxlength = max(len(stringar), maxlength)\n\n        # Make the string Col longer than needed in order to allow later on slightly larger strings\n        return int(maxlength * 1.5)", "title": ""}
{"_id": "d19242", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d19243", "text": "def fib(n):\n    \"\"\"Fibonacci example function\n\n    Args:\n      n (int): integer\n\n    Returns:\n      int: n-th Fibonacci number\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", "title": ""}
{"_id": "d19244", "text": "def enum_mark_last(iterable, start=0):\n    \"\"\"\n    Returns a generator over iterable that tells whether the current item is the last one.\n    Usage:\n        >>> iterable = range(10)\n        >>> for index, is_last, item in enum_mark_last(iterable):\n        >>>     print(index, item, end='\\n' if is_last else ', ')\n    \"\"\"\n    it = iter(iterable)\n    count = start\n    try:\n        last = next(it)\n    except StopIteration:\n        return\n    for val in it:\n        yield count, False, last\n        last = val\n        count += 1\n    yield count, True, last", "title": ""}
{"_id": "d19245", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d19246", "text": "def command(self, cmd, *args):\n        \"\"\"\n        Sends a command and an (optional) sequence of arguments through to the\n        delegated serial interface. Note that the arguments are passed through\n        as data.\n        \"\"\"\n        self._serial_interface.command(cmd)\n        if len(args) > 0:\n            self._serial_interface.data(list(args))", "title": ""}
{"_id": "d19247", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d19248", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d19249", "text": "def non_increasing(values):\n    \"\"\"True if values are not increasing.\"\"\"\n    return all(x >= y for x, y in zip(values, values[1:]))", "title": ""}
{"_id": "d19250", "text": "def get_window_dim():\n    \"\"\" gets the dimensions depending on python version and os\"\"\"\n    version = sys.version_info\n\n    if version >= (3, 3):\n        return _size_36()\n    if platform.system() == 'Windows':\n        return _size_windows()\n    return _size_27()", "title": ""}
{"_id": "d19251", "text": "def sort_by_modified(files_or_folders: list) -> list:\n    \"\"\"\n    Sort files or folders by modified time\n\n    Args:\n        files_or_folders: list of files or folders\n\n    Returns:\n        list\n    \"\"\"\n    return sorted(files_or_folders, key=os.path.getmtime, reverse=True)", "title": ""}
{"_id": "d19252", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d19253", "text": "def supports_py3(project_name):\n    \"\"\"Check with PyPI if a project supports Python 3.\"\"\"\n    log = logging.getLogger(\"ciu\")\n    log.info(\"Checking {} ...\".format(project_name))\n    request = requests.get(\"https://pypi.org/pypi/{}/json\".format(project_name))\n    if request.status_code >= 400:\n        log = logging.getLogger(\"ciu\")\n        log.warning(\"problem fetching {}, assuming ported ({})\".format(\n                        project_name, request.status_code))\n        return True\n    response = request.json()\n    return any(c.startswith(\"Programming Language :: Python :: 3\")\n               for c in response[\"info\"][\"classifiers\"])", "title": ""}
{"_id": "d19254", "text": "def to_0d_array(value: Any) -> np.ndarray:\n    \"\"\"Given a value, wrap it in a 0-D numpy.ndarray.\n    \"\"\"\n    if np.isscalar(value) or (isinstance(value, np.ndarray) and\n                              value.ndim == 0):\n        return np.array(value)\n    else:\n        return to_0d_object_array(value)", "title": ""}
{"_id": "d19255", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d19256", "text": "def repl_complete(text: str, state: int) -> Optional[str]:\n    \"\"\"Completer function for Python's readline/libedit implementation.\"\"\"\n    # Can't complete Keywords, Numerals\n    if __NOT_COMPLETEABLE.match(text):\n        return None\n    elif text.startswith(\":\"):\n        completions = kw.complete(text)\n    else:\n        ns = get_current_ns()\n        completions = ns.complete(text)\n\n    return list(completions)[state] if completions is not None else None", "title": ""}
{"_id": "d19257", "text": "def fprint(expr, print_ascii=False):\n    r\"\"\"This function chooses whether to use ascii characters to represent\n    a symbolic expression in the notebook or to use sympy's pprint.\n\n    >>> from sympy import cos\n    >>> omega=Symbol(\"omega\")\n    >>> fprint(cos(omega),print_ascii=True)\n    cos(omega)\n\n\n    \"\"\"\n    if print_ascii:\n        pprint(expr, use_unicode=False, num_columns=120)\n    else:\n        return expr", "title": ""}
{"_id": "d19258", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d19259", "text": "def get_property_as_float(self, name: str) -> float:\n        \"\"\"Return the value of a float property.\n\n        :return: The property value (float).\n\n        Raises exception if property with name doesn't exist.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes\n        \"\"\"\n        return float(self.__instrument.get_property(name))", "title": ""}
{"_id": "d19260", "text": "def get_triangles(graph: DiGraph) -> SetOfNodeTriples:\n    \"\"\"Get a set of triples representing the 3-cycles from a directional graph.\n\n    Each 3-cycle is returned once, with nodes in sorted order.\n    \"\"\"\n    return {\n        tuple(sorted([a, b, c], key=str))\n        for a, b in graph.edges()\n        for c in graph.successors(b)\n        if graph.has_edge(c, a)\n    }", "title": ""}
{"_id": "d19261", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d19262", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d19263", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d19264", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d19265", "text": "def after_third_friday(day=None):\n    \"\"\" check if day is after month's 3rd friday \"\"\"\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", "title": ""}
{"_id": "d19266", "text": "def timeit (func, log, limit):\n    \"\"\"Print execution time of the function. For quick'n'dirty profiling.\"\"\"\n\n    def newfunc (*args, **kwargs):\n        \"\"\"Execute function and print execution time.\"\"\"\n        t = time.time()\n        res = func(*args, **kwargs)\n        duration = time.time() - t\n        if duration > limit:\n            print(func.__name__, \"took %0.2f seconds\" % duration, file=log)\n            print(args, file=log)\n            print(kwargs, file=log)\n        return res\n    return update_func_meta(newfunc, func)", "title": ""}
{"_id": "d19267", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d19268", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d19269", "text": "def assert_in(first, second, msg_fmt=\"{msg}\"):\n    \"\"\"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\n    \"\"\"\n\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))", "title": ""}
{"_id": "d19270", "text": "def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:\n    \"\"\"\n    Within the dictionary ``d``, find a key that matches (in case-insensitive\n    fashion) the key ``k``, and return it (or ``None`` if there isn't one).\n    \"\"\"\n    for key in d.keys():\n        if k.lower() == key.lower():\n            return key\n    return None", "title": ""}
{"_id": "d19271", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d19272", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d19273", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d19274", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d19275", "text": "def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]:\n    \"\"\"\n    Return all rows from a cursor as a list of :class:`OrderedDict` objects.\n\n    Args:\n        cursor: the cursor\n\n    Returns:\n        a list (one item per row) of :class:`OrderedDict` objects whose key are\n        column names and whose values are the row values\n    \"\"\"\n    columns = get_fieldnames_from_cursor(cursor)\n    return [\n        OrderedDict(zip(columns, row))\n        for row in cursor.fetchall()\n    ]", "title": ""}
{"_id": "d19276", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d19277", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d19278", "text": "def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict:\n        \"\"\"HTTP request method of interface implementation.\"\"\"", "title": ""}
{"_id": "d19279", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d19280", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d19281", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d19282", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d19283", "text": "def backspace(self):\n        \"\"\"\n        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.\n        \"\"\"\n        if self._cx + self._cw >= 0:\n            self.erase()\n            self._cx -= self._cw\n\n        self.flush()", "title": ""}
{"_id": "d19284", "text": "def get_valid_filename(s):\n    \"\"\"\n    Shamelessly taken from Django.\n    https://github.com/django/django/blob/master/django/utils/text.py\n\n    Return the given string converted to a string that can be used for a clean\n    filename. Remove leading and trailing spaces; convert other spaces to\n    underscores; and remove anything that is not an alphanumeric, dash,\n    underscore, or dot.\n    >>> get_valid_filename(\"john's portrait in 2004.jpg\")\n    'johns_portrait_in_2004.jpg'\n    \"\"\"\n    s = str(s).strip().replace(' ', '_')\n    return re.sub(r'(?u)[^-\\w.]', '', s)", "title": ""}
{"_id": "d19285", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d19286", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d19287", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d19288", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d19289", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d19290", "text": "def lowercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the lowercase chars in the given string.\"\"\"\n        return ''.join([c if c.islower() else '' for c in str(string)])", "title": ""}
{"_id": "d19291", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d19292", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d19293", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d19294", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d19295", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d19296", "text": "def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:\n        \"\"\"Executes SQL; returns list of first values of each row.\"\"\"\n        rows = self.fetchall(sql, *args)\n        return [row[0] for row in rows]", "title": ""}
{"_id": "d19297", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d19298", "text": "def to_json(self) -> Mapping:\n        \"\"\"Return the properties of this :class:`Sample` as JSON serializable.\n\n        \"\"\"\n        return {str(x): str(y) for x, y in self.items()}", "title": ""}
{"_id": "d19299", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d19300", "text": "def fib(n):\n    \"\"\"Fibonacci example function\n\n    Args:\n      n (int): integer\n\n    Returns:\n      int: n-th Fibonacci number\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", "title": ""}
{"_id": "d19301", "text": "def read(self, start_position: int, size: int) -> memoryview:\n        \"\"\"\n        Return a view into the memory\n        \"\"\"\n        return memoryview(self._bytes)[start_position:start_position + size]", "title": ""}
{"_id": "d19302", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d19303", "text": "def remove_leading(needle, haystack):\n    \"\"\"Remove leading needle string (if exists).\n\n    >>> remove_leading('Test', 'TestThisAndThat')\n    'ThisAndThat'\n    >>> remove_leading('Test', 'ArbitraryName')\n    'ArbitraryName'\n    \"\"\"\n    if haystack[:len(needle)] == needle:\n        return haystack[len(needle):]\n    return haystack", "title": ""}
{"_id": "d19304", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d19305", "text": "def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:\n    \"\"\"Return the inner product between two tensors\"\"\"\n    # Note: Relying on fact that vdot flattens arrays\n    return np.vdot(tensor0, tensor1)", "title": ""}
{"_id": "d19306", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d19307", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d19308", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d19309", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d19310", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d19311", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d19312", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d19313", "text": "async def async_run(self) -> None:\n        \"\"\"\n        Asynchronously run the worker, does not close connections. Useful when testing.\n        \"\"\"\n        self.main_task = self.loop.create_task(self.main())\n        await self.main_task", "title": ""}
{"_id": "d19314", "text": "async def async_run(self) -> None:\n        \"\"\"\n        Asynchronously run the worker, does not close connections. Useful when testing.\n        \"\"\"\n        self.main_task = self.loop.create_task(self.main())\n        await self.main_task", "title": ""}
{"_id": "d19315", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d19316", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d19317", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d19318", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d19319", "text": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n    \"\"\"\n    Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n    :param buckets: List of buckets.\n    :return: The largest bucket in the list.\n    \"\"\"\n    return max(buckets)", "title": ""}
{"_id": "d19320", "text": "def bfx(value, msb, lsb):\n    \"\"\"! @brief Extract a value from a bitfield.\"\"\"\n    mask = bitmask((msb, lsb))\n    return (value & mask) >> lsb", "title": ""}
{"_id": "d19321", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d19322", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d19323", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d19324", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d19325", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d19326", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d19327", "text": "def availability_pdf() -> bool:\n    \"\"\"\n    Is a PDF-to-text tool available?\n    \"\"\"\n    pdftotext = tools['pdftotext']\n    if pdftotext:\n        return True\n    elif pdfminer:\n        log.warning(\"PDF conversion: pdftotext missing; \"\n                    \"using pdfminer (less efficient)\")\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d19328", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d19329", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d19330", "text": "def samefile(a: str, b: str) -> bool:\n    \"\"\"Check if two pathes represent the same file.\"\"\"\n    try:\n        return os.path.samefile(a, b)\n    except OSError:\n        return os.path.normpath(a) == os.path.normpath(b)", "title": ""}
{"_id": "d19331", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d19332", "text": "def CheckDisjointCalendars(self):\n    \"\"\"Check whether any old service periods intersect with any new ones.\n\n    This is a rather coarse check based on\n    transitfeed.SevicePeriod.GetDateRange.\n\n    Returns:\n      True if the calendars are disjoint or False if not.\n    \"\"\"\n    # TODO: Do an exact check here.\n\n    a_service_periods = self.feed_merger.a_schedule.GetServicePeriodList()\n    b_service_periods = self.feed_merger.b_schedule.GetServicePeriodList()\n\n    for a_service_period in a_service_periods:\n      a_start, a_end = a_service_period.GetDateRange()\n      for b_service_period in b_service_periods:\n        b_start, b_end = b_service_period.GetDateRange()\n        overlap_start = max(a_start, b_start)\n        overlap_end = min(a_end, b_end)\n        if overlap_end >= overlap_start:\n          return False\n    return True", "title": ""}
{"_id": "d19333", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d19334", "text": "def __gt__(self, other):\n        \"\"\"Test for greater than.\"\"\"\n        if isinstance(other, Address):\n            return str(self) > str(other)\n        raise TypeError", "title": ""}
{"_id": "d19335", "text": "def inject_nulls(data: Mapping, field_names) -> dict:\n    \"\"\"Insert None as value for missing fields.\"\"\"\n\n    record = dict()\n\n    for field in field_names:\n        record[field] = data.get(field, None)\n\n    return record", "title": ""}
{"_id": "d19336", "text": "def connect_to_database_odbc_access(self,\n                                        dsn: str,\n                                        autocommit: bool = True) -> None:\n        \"\"\"Connects to an Access database via ODBC, with the DSN\n        prespecified.\"\"\"\n        self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,\n                     dsn=dsn, autocommit=autocommit)", "title": ""}
{"_id": "d19337", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d19338", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d19339", "text": "def PrintIndented(self, file, ident, code):\n        \"\"\"Takes an array, add indentation to each entry and prints it.\"\"\"\n        for entry in code:\n            print >>file, '%s%s' % (ident, entry)", "title": ""}
{"_id": "d19340", "text": "def pack_bits( longbits ):\n    \"\"\"Crunch a 64-bit int (8 bool bytes) into a bitfield.\"\"\"\n    byte = longbits & (0x0101010101010101)\n    byte = (byte | (byte>>7)) & (0x0003000300030003)\n    byte = (byte | (byte>>14)) & (0x0000000f0000000f)\n    byte = (byte | (byte>>28)) & (0x00000000000000ff)\n    return byte", "title": ""}
{"_id": "d19341", "text": "def full(self):\n        \"\"\"Return ``True`` if the queue is full, ``False``\n        otherwise (not reliable!).\n\n        Only applicable if :attr:`maxsize` is set.\n\n        \"\"\"\n        return self.maxsize and len(self.list) >= self.maxsize or False", "title": ""}
{"_id": "d19342", "text": "def kernel(self, spread=1):\n        \"\"\" This will return whatever kind of kernel we want to use.\n            Must have signature (ndarray size NxM, ndarray size 1xM) -> ndarray size Nx1\n        \"\"\"\n        # TODO: use self.kernel_type to choose function\n\n        def gaussian(data, pixel):\n            return mvn.pdf(data, mean=pixel, cov=spread)\n\n        return gaussian", "title": ""}
{"_id": "d19343", "text": "def _reshuffle(mat, shape):\n    \"\"\"Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].\"\"\"\n    return np.reshape(\n        np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),\n        (shape[3] * shape[1], shape[0] * shape[2]))", "title": ""}
{"_id": "d19344", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d19345", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d19346", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d19347", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d19348", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d19349", "text": "def ResetConsoleColor() -> bool:\n    \"\"\"\n    Reset to the default text color on console window.\n    Return bool, True if succeed otherwise False.\n    \"\"\"\n    if sys.stdout:\n        sys.stdout.flush()\n    bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))", "title": ""}
{"_id": "d19350", "text": "def pairwise(iterable):\n    \"\"\"From itertools cookbook. [a, b, c, ...] -> (a, b), (b, c), ...\"\"\"\n    first, second = tee(iterable)\n    next(second, None)\n    return zip(first, second)", "title": ""}
{"_id": "d19351", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d19352", "text": "def memory_usage():\n    \"\"\"return memory usage of python process in MB\n\n    from\n    http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/\n    psutil is quicker\n\n    >>> isinstance(memory_usage(),float)\n    True\n\n    \"\"\"\n    try:\n        import psutil\n        import os\n    except ImportError:\n        return _memory_usage_ps()\n\n    process = psutil.Process(os.getpid())\n    mem = process.memory_info()[0] / float(2 ** 20)\n    return mem", "title": ""}
{"_id": "d19353", "text": "def de_duplicate(items):\n    \"\"\"Remove any duplicate item, preserving order\n\n    >>> de_duplicate([1, 2, 1, 2])\n    [1, 2]\n    \"\"\"\n    result = []\n    for item in items:\n        if item not in result:\n            result.append(item)\n    return result", "title": ""}
{"_id": "d19354", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d19355", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d19356", "text": "def almost_hermitian(gate: Gate) -> bool:\n    \"\"\"Return true if gate tensor is (almost) Hermitian\"\"\"\n    return np.allclose(asarray(gate.asoperator()),\n                       asarray(gate.H.asoperator()))", "title": ""}
{"_id": "d19357", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d19358", "text": "def is_any_type_set(sett: Set[Type]) -> bool:\n    \"\"\"\n    Helper method to check if a set of types is the {AnyObject} singleton\n\n    :param sett:\n    :return:\n    \"\"\"\n    return len(sett) == 1 and is_any_type(min(sett))", "title": ""}
{"_id": "d19359", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d19360", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d19361", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d19362", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d19363", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d19364", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d19365", "text": "def full(self):\n        \"\"\"Return ``True`` if the queue is full, ``False``\n        otherwise (not reliable!).\n\n        Only applicable if :attr:`maxsize` is set.\n\n        \"\"\"\n        return self.maxsize and len(self.list) >= self.maxsize or False", "title": ""}
{"_id": "d19366", "text": "def toHdlConversion(self, top, topName: str, saveTo: str) -> List[str]:\n        \"\"\"\n        :param top: object which is represenation of design\n        :param topName: name which should be used for ipcore\n        :param saveTo: path of directory where generated files should be stored\n\n        :return: list of file namens in correct compile order\n        \"\"\"\n        raise NotImplementedError(\n            \"Implement this function for your type of your top module\")", "title": ""}
{"_id": "d19367", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d19368", "text": "def default_parser() -> argparse.ArgumentParser:\n    \"\"\"Create a parser for CLI arguments and options.\"\"\"\n    parser = argparse.ArgumentParser(\n        prog=CONSOLE_SCRIPT,\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n    )\n    build_parser(parser)\n    return parser", "title": ""}
{"_id": "d19369", "text": "def titleize(text):\n    \"\"\"Capitalizes all the words and replaces some characters in the string \n    to create a nicer looking title.\n    \"\"\"\n    if len(text) == 0: # if empty string, return it\n        return text\n    else:\n        text = text.lower() # lower all char\n        # delete redundant empty space \n        chunks = [chunk[0].upper() + chunk[1:] for chunk in text.split(\" \") if len(chunk) >= 1]\n        return \" \".join(chunks)", "title": ""}
{"_id": "d19370", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d19371", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d19372", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d19373", "text": "def set_int(bytearray_, byte_index, _int):\n    \"\"\"\n    Set value in bytearray to int\n    \"\"\"\n    # make sure were dealing with an int\n    _int = int(_int)\n    _bytes = struct.unpack('2B', struct.pack('>h', _int))\n    bytearray_[byte_index:byte_index + 2] = _bytes\n    return bytearray_", "title": ""}
{"_id": "d19374", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d19375", "text": "def multi_split(s, split):\n    # type: (S, Iterable[S]) -> List[S]\n    \"\"\"Splits on multiple given separators.\"\"\"\n    for r in split:\n        s = s.replace(r, \"|\")\n    return [i for i in s.split(\"|\") if len(i) > 0]", "title": ""}
{"_id": "d19376", "text": "def get_period_last_3_months() -> str:\n    \"\"\" Returns the last week as a period string \"\"\"\n    today = Datum()\n    today.today()\n\n    # start_date = today - timedelta(weeks=13)\n    start_date = today.clone()\n    start_date.subtract_months(3)\n\n    period = get_period(start_date.date, today.date)\n    return period", "title": ""}
{"_id": "d19377", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d19378", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d19379", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d19380", "text": "def infer_format(filename:str) -> str:\n    \"\"\"Return extension identifying format of given filename\"\"\"\n    _, ext = os.path.splitext(filename)\n    return ext", "title": ""}
{"_id": "d19381", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d19382", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d19383", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d19384", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d19385", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d19386", "text": "async def cursor(self) -> Cursor:\n        \"\"\"Create an aiosqlite cursor wrapping a sqlite3 cursor object.\"\"\"\n        return Cursor(self, await self._execute(self._conn.cursor))", "title": ""}
{"_id": "d19387", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d19388", "text": "def infer_format(filename:str) -> str:\n    \"\"\"Return extension identifying format of given filename\"\"\"\n    _, ext = os.path.splitext(filename)\n    return ext", "title": ""}
{"_id": "d19389", "text": "def decodebytes(input):\n    \"\"\"Decode base64 string to byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _decodebytes_py3(input)\n    return _decodebytes_py2(input)", "title": ""}
{"_id": "d19390", "text": "def fetchvalue(self, sql: str, *args) -> Optional[Any]:\n        \"\"\"Executes SQL; returns the first value of the first row, or None.\"\"\"\n        row = self.fetchone(sql, *args)\n        if row is None:\n            return None\n        return row[0]", "title": ""}
{"_id": "d19391", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d19392", "text": "def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type an integer type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Integer)", "title": ""}
{"_id": "d19393", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d19394", "text": "def warn_if_nans_exist(X):\n    \"\"\"Warn if nans exist in a numpy array.\"\"\"\n    null_count = count_rows_with_nans(X)\n    total = len(X)\n    percent = 100 * null_count / total\n\n    if null_count > 0:\n        warning_message = \\\n            'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n            'complete rows will be plotted.'.format(null_count, total, percent)\n        warnings.warn(warning_message, DataWarning)", "title": ""}
{"_id": "d19395", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d19396", "text": "def dfromdm(dm):\n    \"\"\"Returns distance given distance modulus.\n    \"\"\"\n    if np.size(dm)>1:\n        dm = np.atleast_1d(dm)\n    return 10**(1+dm/5)", "title": ""}
{"_id": "d19397", "text": "def get_window_dim():\n    \"\"\" gets the dimensions depending on python version and os\"\"\"\n    version = sys.version_info\n\n    if version >= (3, 3):\n        return _size_36()\n    if platform.system() == 'Windows':\n        return _size_windows()\n    return _size_27()", "title": ""}
{"_id": "d19398", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d19399", "text": "def get_window_dim():\n    \"\"\" gets the dimensions depending on python version and os\"\"\"\n    version = sys.version_info\n\n    if version >= (3, 3):\n        return _size_36()\n    if platform.system() == 'Windows':\n        return _size_windows()\n    return _size_27()", "title": ""}
{"_id": "d19400", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d19401", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d19402", "text": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "title": ""}
{"_id": "d19403", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d19404", "text": "def long_substr(data):\n    \"\"\"Return the longest common substring in a list of strings.\n    \n    Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n    \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n                    substr = data[0][i:i+j]\n    elif len(data) == 1:\n        substr = data[0]\n    return substr", "title": ""}
{"_id": "d19405", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d19406", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d19407", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d19408", "text": "def add_colons(s):\n    \"\"\"Add colons after every second digit.\n\n    This function is used in functions to prettify serials.\n\n    >>> add_colons('teststring')\n    'te:st:st:ri:ng'\n    \"\"\"\n    return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)])", "title": ""}
{"_id": "d19409", "text": "def lint(fmt='colorized'):\n    \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\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)", "title": ""}
{"_id": "d19410", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d19411", "text": "def strtobytes(input, encoding):\n    \"\"\"Take a str and transform it into a byte array.\"\"\"\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)", "title": ""}
{"_id": "d19412", "text": "def spanning_tree_count(graph: nx.Graph) -> int:\n    \"\"\"Return the number of unique spanning trees of a graph, using\n    Kirchhoff's matrix tree theorem.\n    \"\"\"\n    laplacian = nx.laplacian_matrix(graph).toarray()\n    comatrix = laplacian[:-1, :-1]\n    det = np.linalg.det(comatrix)\n    count = int(round(det))\n    return count", "title": ""}
{"_id": "d19413", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d19414", "text": "def maybe_infer_dtype_type(element):\n    \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n    Uses `element.dtype` if that's available.\n    Objects implementing the iterator protocol are cast to a NumPy array,\n    and from there the array's type is used.\n\n    Parameters\n    ----------\n    element : object\n        Possibly has a `.dtype` attribute, and possibly the iterator\n        protocol.\n\n    Returns\n    -------\n    tipo : type\n\n    Examples\n    --------\n    >>> from collections import namedtuple\n    >>> Foo = namedtuple(\"Foo\", \"dtype\")\n    >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n    numpy.int64\n    \"\"\"\n    tipo = None\n    if hasattr(element, 'dtype'):\n        tipo = element.dtype\n    elif is_list_like(element):\n        element = np.asarray(element)\n        tipo = element.dtype\n    return tipo", "title": ""}
{"_id": "d19415", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d19416", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d19417", "text": "def dict_of_sets_add(dictionary, key, value):\n    # type: (DictUpperBound, Any, Any) -> None\n    \"\"\"Add value to a set 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 set in dictionary\n\n    Returns:\n        None\n\n    \"\"\"\n    set_objs = dictionary.get(key, set())\n    set_objs.add(value)\n    dictionary[key] = set_objs", "title": ""}
{"_id": "d19418", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d19419", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d19420", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d19421", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d19422", "text": "def define_struct(defn):\n    \"\"\"\n    Register a struct definition globally\n\n    >>> define_struct('struct abcd {int x; int y;}')\n    \"\"\"\n    struct = parse_type(defn)\n    ALL_TYPES[struct.name] = struct\n    return struct", "title": ""}
{"_id": "d19423", "text": "def lint(fmt='colorized'):\n    \"\"\"Run verbose PyLint on source. Optionally specify fmt=html for HTML output.\"\"\"\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)", "title": ""}
{"_id": "d19424", "text": "def get_current_item(self):\n        \"\"\"Returns (first) selected item or None\"\"\"\n        l = self.selectedIndexes()\n        if len(l) > 0:\n            return self.model().get_item(l[0])", "title": ""}
{"_id": "d19425", "text": "def median(data):\n    \"\"\"\n    Return the median of numeric data, unsing the \"mean of middle two\" method.\n    If ``data`` is empty, ``0`` is returned.\n\n    Examples\n    --------\n\n    >>> median([1, 3, 5])\n    3.0\n\n    When the number of data points is even, the median is interpolated:\n    >>> median([1, 3, 5, 7])\n    4.0\n    \"\"\"\n\n    if len(data) == 0:\n        return None\n\n    data = sorted(data)\n    return float((data[len(data) // 2] + data[(len(data) - 1) // 2]) / 2.)", "title": ""}
{"_id": "d19426", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d19427", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d19428", "text": "def lower_camel_case_from_underscores(string):\n    \"\"\"generate a lower-cased camelCase string from an underscore_string.\n    For example: my_variable_name -> myVariableName\"\"\"\n    components = string.split('_')\n    string = components[0]\n    for component in components[1:]:\n        string += component[0].upper() + component[1:]\n    return string", "title": ""}
{"_id": "d19429", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d19430", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d19431", "text": "def isarray(array, test, dim=2):\n    \"\"\"Returns True if test is True for all array elements.\n    Otherwise, returns False.\n    \"\"\"\n    if dim > 1:\n        return all(isarray(array[i], test, dim - 1)\n                   for i in range(len(array)))\n    return all(test(i) for i in array)", "title": ""}
{"_id": "d19432", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d19433", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d19434", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d19435", "text": "def get_datatype(self, table: str, column: str) -> str:\n        \"\"\"Returns database SQL datatype for a column: e.g. VARCHAR.\"\"\"\n        return self.flavour.get_datatype(self, table, column).upper()", "title": ""}
{"_id": "d19436", "text": "def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:\n    \"\"\"\n    Convert a list of strings to a list of integers.\n\n    :param strings: a list of string\n    :return: a list of converted integers\n\n    .. doctest::\n\n        >>> strings_to_integers(['1', '1.0', '-0.2'])\n        [1, 1, 0]\n    \"\"\"\n    return strings_to_(strings, lambda x: int(float(x)))", "title": ""}
{"_id": "d19437", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d19438", "text": "def get_input_nodes(G: nx.DiGraph) -> List[str]:\n    \"\"\" Get all input nodes from a network. \"\"\"\n    return [n for n, d in G.in_degree() if d == 0]", "title": ""}
{"_id": "d19439", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d19440", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d19441", "text": "def attr_names(cls) -> List[str]:\n        \"\"\"\n        Returns annotated attribute names\n        :return: List[str]\n        \"\"\"\n        return [k for k, v in cls.attr_types().items()]", "title": ""}
{"_id": "d19442", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d19443", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d19444", "text": "def __rmatmul__(self, other):\n        \"\"\"\n        Matrix multiplication using binary `@` operator in Python>=3.5.\n        \"\"\"\n        return self.T.dot(np.transpose(other)).T", "title": ""}
{"_id": "d19445", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d19446", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d19447", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d19448", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d19449", "text": "def is_blankspace(self, char):\n        \"\"\"\n        Test if a character is a blankspace.\n\n        Parameters\n        ----------\n        char : str\n            The character to test.\n\n        Returns\n        -------\n        ret : bool\n            True if character is a blankspace, False otherwise.\n\n        \"\"\"\n        if len(char) > 1:\n            raise TypeError(\"Expected a char.\")\n        if char in self.blankspaces:\n            return True\n        return False", "title": ""}
{"_id": "d19450", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d19451", "text": "def stretch(iterable, n=2):\n    r\"\"\"Repeat each item in `iterable` `n` times.\n\n    Example:\n\n    >>> list(stretch(range(3), 2))\n    [0, 0, 1, 1, 2, 2]\n    \"\"\"\n    times = range(n)\n    for item in iterable:\n        for i in times: yield item", "title": ""}
{"_id": "d19452", "text": "def consistent_shuffle(*lists):\n    \"\"\"\n    Shuffle lists consistently.\n\n    Parameters\n    ----------\n    *lists\n        Variable length number of lists\n\n    Returns\n    -------\n    shuffled_lists : tuple of lists\n        All of the lists are shuffled consistently\n\n    Examples\n    --------\n    >>> import mpu, random; random.seed(8)\n    >>> mpu.consistent_shuffle([1,2,3], ['a', 'b', 'c'], ['A', 'B', 'C'])\n    ([3, 2, 1], ['c', 'b', 'a'], ['C', 'B', 'A'])\n    \"\"\"\n    perm = list(range(len(lists[0])))\n    random.shuffle(perm)\n    lists = tuple([sublist[index] for index in perm]\n                  for sublist in lists)\n    return lists", "title": ""}
{"_id": "d19453", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d19454", "text": "def execute(cur, *args):\n    \"\"\"Utility function to print sqlite queries before executing.\n\n    Use instead of cur.execute().  First argument is cursor.\n\n    cur.execute(stmt)\n    becomes\n    util.execute(cur, stmt)\n    \"\"\"\n    stmt = args[0]\n    if len(args) > 1:\n        stmt = stmt.replace('%', '%%').replace('?', '%r')\n        print(stmt % (args[1]))\n    return cur.execute(*args)", "title": ""}
{"_id": "d19455", "text": "def file_exists(fname):\n    \"\"\"Check if a file exists and is non-empty.\n    \"\"\"\n    try:\n        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0\n    except OSError:\n        return False", "title": ""}
{"_id": "d19456", "text": "def uconcatenate(arrs, axis=0):\n    \"\"\"Concatenate a sequence of arrays.\n\n    This wrapper around numpy.concatenate preserves units. All input arrays\n    must have the same units.  See the documentation of numpy.concatenate for\n    full details.\n\n    Examples\n    --------\n    >>> from unyt import cm\n    >>> A = [1, 2, 3]*cm\n    >>> B = [2, 3, 4]*cm\n    >>> uconcatenate((A, B))\n    unyt_array([1, 2, 3, 2, 3, 4], 'cm')\n\n    \"\"\"\n    v = np.concatenate(arrs, axis=axis)\n    v = _validate_numpy_wrapper_units(v, arrs)\n    return v", "title": ""}
{"_id": "d19457", "text": "def full(self):\n        \"\"\"Return ``True`` if the queue is full, ``False``\n        otherwise (not reliable!).\n\n        Only applicable if :attr:`maxsize` is set.\n\n        \"\"\"\n        return self.maxsize and len(self.list) >= self.maxsize or False", "title": ""}
{"_id": "d19458", "text": "def is_quoted(arg: str) -> bool:\n    \"\"\"\n    Checks if a string is quoted\n    :param arg: the string being checked for quotes\n    :return: True if a string is quoted\n    \"\"\"\n    return len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES", "title": ""}
{"_id": "d19459", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d19460", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d19461", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d19462", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d19463", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d19464", "text": "def cpu_count() -> int:\n    \"\"\"Returns the number of processors on this machine.\"\"\"\n    if multiprocessing is None:\n        return 1\n    try:\n        return multiprocessing.cpu_count()\n    except NotImplementedError:\n        pass\n    try:\n        return os.sysconf(\"SC_NPROCESSORS_CONF\")\n    except (AttributeError, ValueError):\n        pass\n    gen_log.error(\"Could not detect number of processors; assuming 1\")\n    return 1", "title": ""}
{"_id": "d19465", "text": "async def async_run(self) -> None:\n        \"\"\"\n        Asynchronously run the worker, does not close connections. Useful when testing.\n        \"\"\"\n        self.main_task = self.loop.create_task(self.main())\n        await self.main_task", "title": ""}
{"_id": "d19466", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d19467", "text": "def _rindex(mylist: Sequence[T], x: T) -> int:\n    \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n    return len(mylist) - mylist[::-1].index(x) - 1", "title": ""}
{"_id": "d19468", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d19469", "text": "def head(self) -> Any:\n        \"\"\"Retrive first element in List.\"\"\"\n\n        lambda_list = self._get_value()\n        return lambda_list(lambda head, _: head)", "title": ""}
{"_id": "d19470", "text": "def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, convert\n    (in place) ``d[key]`` to a float. If that fails, convert it to ``None``.\n    \"\"\"\n    for d in dict_list:\n        try:\n            d[key] = float(d[key])\n        except ValueError:\n            d[key] = None", "title": ""}
{"_id": "d19471", "text": "def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\" Helper for iterating only nonempty lines without line breaks\"\"\"\n    for line in file_like:\n        line = line.rstrip('\\r\\n')\n        if line:\n            yield line", "title": ""}
{"_id": "d19472", "text": "def compatible_staticpath(path):\n    \"\"\"\n    Try to return a path to static the static files compatible all\n    the way back to Django 1.2. If anyone has a cleaner or better\n    way to do this let me know!\n    \"\"\"\n\n    if VERSION >= (1, 10):\n        # Since Django 1.10, forms.Media automatically invoke static\n        # lazily on the path if it is relative.\n        return path\n    try:\n        # >= 1.4\n        from django.templatetags.static import static\n        return static(path)\n    except ImportError:\n        pass\n    try:\n        # >= 1.3\n        return '%s/%s' % (settings.STATIC_URL.rstrip('/'), path)\n    except AttributeError:\n        pass\n    try:\n        return '%s/%s' % (settings.PAGEDOWN_URL.rstrip('/'), path)\n    except AttributeError:\n        pass\n    return '%s/%s' % (settings.MEDIA_URL.rstrip('/'), path)", "title": ""}
{"_id": "d19473", "text": "def ranges_to_set(lst):\n    \"\"\"\n    Convert a list of ranges to a set of numbers::\n\n    >>> ranges = [(1,3), (5,6)]\n    >>> sorted(list(ranges_to_set(ranges)))\n    [1, 2, 3, 5, 6]\n\n    \"\"\"\n    return set(itertools.chain(*(range(x[0], x[1]+1) for x in lst)))", "title": ""}
{"_id": "d19474", "text": "def mkdir(self, target_folder):\n        \"\"\"\n        Create a folder on S3.\n\n        Examples\n        --------\n            >>> s3utils.mkdir(\"path/to/my_folder\")\n            Making directory: path/to/my_folder\n        \"\"\"\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()", "title": ""}
{"_id": "d19475", "text": "def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:\n        \"\"\"Executes SQL; returns list of first values of each row.\"\"\"\n        rows = self.fetchall(sql, *args)\n        return [row[0] for row in rows]", "title": ""}
{"_id": "d19476", "text": "def grep(pattern, filename):\n    \"\"\"Very simple grep that returns the first matching line in a file.\n    String matching only, does not do REs as currently implemented.\n    \"\"\"\n    try:\n        # for line in file\n        # if line matches pattern:\n        #    return line\n        return next((L for L in open(filename) if L.find(pattern) >= 0))\n    except StopIteration:\n        return ''", "title": ""}
{"_id": "d19477", "text": "def _sum_cycles_from_tokens(self, tokens: List[str]) -> int:\n        \"\"\"Sum the total number of cycles over a list of tokens.\"\"\"\n        return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))", "title": ""}
{"_id": "d19478", "text": "def __rmatmul__(self, other):\n        \"\"\"\n        Matrix multiplication using binary `@` operator in Python>=3.5.\n        \"\"\"\n        return self.T.dot(np.transpose(other)).T", "title": ""}
{"_id": "d19479", "text": "def uniqued(iterable):\n    \"\"\"Return unique list of items preserving order.\n\n    >>> uniqued([3, 2, 1, 3, 2, 1, 0])\n    [3, 2, 1, 0]\n    \"\"\"\n    seen = set()\n    add = seen.add\n    return [i for i in iterable if i not in seen and not add(i)]", "title": ""}
{"_id": "d19480", "text": "def extend(a: dict, b: dict) -> dict:\n    \"\"\"Merge two dicts and return a new dict. Much like subclassing works.\"\"\"\n    res = a.copy()\n    res.update(b)\n    return res", "title": ""}
{"_id": "d19481", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d19482", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d19483", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d19484", "text": "def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:\n    \"\"\"\n    Finds the index of an item in list, which satisfies predicate\n    :param predicateFn: predicate function to run on items of list\n    :param items: list of tuples\n    :return: first index for which predicate function returns True\n    \"\"\"\n    try:\n        return next(i for i, v in enumerate(items) if predicateFn(v))\n    except StopIteration:\n        return -1", "title": ""}
{"_id": "d19485", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d19486", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d19487", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d19488", "text": "def proper_round(n):\n    \"\"\"\n    rounds float to closest int\n    :rtype: int\n    :param n: float\n    \"\"\"\n    return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0", "title": ""}
{"_id": "d19489", "text": "def isfile_notempty(inputfile: str) -> bool:\n        \"\"\"Check if the input filename with path is a file and is not empty.\"\"\"\n        try:\n            return isfile(inputfile) and getsize(inputfile) > 0\n        except TypeError:\n            raise TypeError('inputfile is not a valid type')", "title": ""}
{"_id": "d19490", "text": "def fcast(value: float) -> TensorLike:\n    \"\"\"Cast to float tensor\"\"\"\n    newvalue = tf.cast(value, FTYPE)\n    if DEVICE == 'gpu':\n        newvalue = newvalue.gpu()  # Why is this needed?  # pragma: no cover\n    return newvalue", "title": ""}
{"_id": "d19491", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d19492", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d19493", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d19494", "text": "def excel_datetime(timestamp, epoch=None):\n    \"\"\"Return datetime object from timestamp in Excel serial format.\n\n    Convert LSM time stamps.\n\n    >>> excel_datetime(40237.029999999795)\n    datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)\n\n    \"\"\"\n    if epoch is None:\n        epoch = datetime.datetime.fromordinal(693594)\n    return epoch + datetime.timedelta(timestamp)", "title": ""}
{"_id": "d19495", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d19496", "text": "def simple_moving_average(x, n=10):\n    \"\"\"\n    Calculate simple moving average\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 1 x n numpy array instance\n    \"\"\"\n    if x.ndim > 1 and len(x[0]) > 1:\n        x = np.average(x, axis=1)\n    a = np.ones(n) / float(n)\n    return np.convolve(x, a, 'valid')", "title": ""}
{"_id": "d19497", "text": "def de_duplicate(items):\n    \"\"\"Remove any duplicate item, preserving order\n\n    >>> de_duplicate([1, 2, 1, 2])\n    [1, 2]\n    \"\"\"\n    result = []\n    for item in items:\n        if item not in result:\n            result.append(item)\n    return result", "title": ""}
{"_id": "d19498", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d19499", "text": "def argmax(iterable, key=None, both=False):\n    \"\"\"\n    >>> argmax([4,2,-5])\n    0\n    >>> argmax([4,2,-5], key=abs)\n    2\n    >>> argmax([4,2,-5], key=abs, both=True)\n    (2, 5)\n    \"\"\"\n    if key is not None:\n        it = imap(key, iterable)\n    else:\n        it = iter(iterable)\n    score, argmax = reduce(max, izip(it, count()))\n    if both:\n        return argmax, score\n    return argmax", "title": ""}
{"_id": "d19500", "text": "def _protected_log(x1):\n    \"\"\"Closure of log for zero arguments.\"\"\"\n    with np.errstate(divide='ignore', invalid='ignore'):\n        return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)", "title": ""}
{"_id": "d19501", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d19502", "text": "def mostLikely(self, pred):\n    \"\"\" Helper function to return a scalar value representing the most\n        likely outcome given a probability distribution\n    \"\"\"\n    if len(pred) == 1:\n      return pred.keys()[0]\n\n    mostLikelyOutcome = None\n    maxProbability = 0\n\n    for prediction, probability in pred.items():\n      if probability > maxProbability:\n        mostLikelyOutcome = prediction\n        maxProbability = probability\n\n    return mostLikelyOutcome", "title": ""}
{"_id": "d19503", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d19504", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d19505", "text": "def moving_average(arr: np.ndarray, n: int = 3) -> np.ndarray:\n    \"\"\" Calculate the moving overage over an array.\n\n    Algorithm from: https://stackoverflow.com/a/14314054\n\n    Args:\n        arr (np.ndarray): Array over which to calculate the moving average.\n        n (int): Number of elements over which to calculate the moving average. Default: 3\n    Returns:\n        np.ndarray: Moving average calculated over n.\n    \"\"\"\n    ret = np.cumsum(arr, dtype=float)\n    ret[n:] = ret[n:] - ret[:-n]\n    return ret[n - 1:] / n", "title": ""}
{"_id": "d19506", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d19507", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d19508", "text": "def singularize(word):\n    \"\"\"\n    Return the singular form of a word, the reverse of :func:`pluralize`.\n\n    Examples::\n\n        >>> singularize(\"posts\")\n        \"post\"\n        >>> singularize(\"octopi\")\n        \"octopus\"\n        >>> singularize(\"sheep\")\n        \"sheep\"\n        >>> singularize(\"word\")\n        \"word\"\n        >>> singularize(\"CamelOctopi\")\n        \"CamelOctopus\"\n\n    \"\"\"\n    for inflection in UNCOUNTABLES:\n        if re.search(r'(?i)\\b(%s)\\Z' % inflection, word):\n            return word\n\n    for rule, replacement in SINGULARS:\n        if re.search(rule, word):\n            return re.sub(rule, replacement, word)\n    return word", "title": ""}
{"_id": "d19509", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d19510", "text": "def hsv2rgb_spectrum(hsv):\n    \"\"\"Generates RGB values from HSV values in line with a typical light\n    spectrum.\"\"\"\n    h, s, v = hsv\n    return hsv2rgb_raw(((h * 192) >> 8, s, v))", "title": ""}
{"_id": "d19511", "text": "def strictly_positive_int_or_none(val):\n    \"\"\"Parse `val` into either `None` or a strictly positive integer.\"\"\"\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))", "title": ""}
{"_id": "d19512", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d19513", "text": "def clean(ctx, text):\n    \"\"\"\n    Removes all non-printable characters from a text string\n    \"\"\"\n    text = conversions.to_string(text, ctx)\n    return ''.join([c for c in text if ord(c) >= 32])", "title": ""}
{"_id": "d19514", "text": "def extend(a: dict, b: dict) -> dict:\n    \"\"\"Merge two dicts and return a new dict. Much like subclassing works.\"\"\"\n    res = a.copy()\n    res.update(b)\n    return res", "title": ""}
{"_id": "d19515", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d19516", "text": "def snake_to_camel(s: str) -> str:\n    \"\"\"Convert string from snake case to camel case.\"\"\"\n\n    fragments = s.split('_')\n\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])", "title": ""}
{"_id": "d19517", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d19518", "text": "def is_running(process_id: int) -> bool:\n    \"\"\"\n    Uses the Unix ``ps`` program to see if a process is running.\n    \"\"\"\n    pstr = str(process_id)\n    encoding = sys.getdefaultencoding()\n    s = subprocess.Popen([\"ps\", \"-p\", pstr], stdout=subprocess.PIPE)\n    for line in s.stdout:\n        strline = line.decode(encoding)\n        if pstr in strline:\n            return True\n    return False", "title": ""}
{"_id": "d19519", "text": "def _protected_log(x1):\n    \"\"\"Closure of log for zero arguments.\"\"\"\n    with np.errstate(divide='ignore', invalid='ignore'):\n        return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.)", "title": ""}
{"_id": "d19520", "text": "def _my_hash(arg_list):\n    # type: (List[Any]) -> int\n    \"\"\"Simple helper hash function\"\"\"\n    res = 0\n    for arg in arg_list:\n        res = res * 31 + hash(arg)\n    return res", "title": ""}
{"_id": "d19521", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d19522", "text": "def has_obstory_metadata(self, status_id):\n        \"\"\"\n        Check for the presence of the given metadata item\n\n        :param string status_id:\n            The metadata item ID\n        :return:\n            True if we have a metadata item with this ID, False otherwise\n        \"\"\"\n        self.con.execute('SELECT 1 FROM archive_metadata WHERE publicId=%s;', (status_id,))\n        return len(self.con.fetchall()) > 0", "title": ""}
{"_id": "d19523", "text": "def has_key(cls, *args):\n        \"\"\"\n        Check whether flyweight object with specified key has already been created.\n\n        Returns:\n            bool: True if already created, False if not\n        \"\"\"\n        key = args if len(args) > 1 else args[0]\n        return key in cls._instances", "title": ""}
{"_id": "d19524", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d19525", "text": "def require(executable: str, explanation: str = \"\") -> None:\n    \"\"\"\n    Ensures that the external tool is available.\n    Asserts upon failure.\n    \"\"\"\n    assert shutil.which(executable), \"Need {!r} on the PATH.{}\".format(\n        executable, \"\\n\" + explanation if explanation else \"\")", "title": ""}
{"_id": "d19526", "text": "def rank(tensor: BKTensor) -> int:\n    \"\"\"Return the number of dimensions of a tensor\"\"\"\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n\n    return len(tensor[0].size())", "title": ""}
{"_id": "d19527", "text": "def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:\n    \"\"\" Creates a mapping from indices to labels. \"\"\"\n\n    return {index: label for index, label in\n            enumerate([\"pad\"] + sorted(list(labels)))}", "title": ""}
{"_id": "d19528", "text": "def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)", "title": ""}
{"_id": "d19529", "text": "def without(seq1, seq2):\n    r\"\"\"Return a list with all elements in `seq2` removed from `seq1`, order\n    preserved.\n\n    Examples:\n\n    >>> without([1,2,3,1,2], [1])\n    [2, 3, 2]\n    \"\"\"\n    if isSet(seq2): d2 = seq2\n    else: d2 = set(seq2)\n    return [elt for elt in seq1 if elt not in d2]", "title": ""}
{"_id": "d19530", "text": "def read32(bytestream):\n  \"\"\"Read 4 bytes from bytestream as an unsigned 32-bit integer.\"\"\"\n  dt = np.dtype(np.uint32).newbyteorder('>')\n  return np.frombuffer(bytestream.read(4), dtype=dt)[0]", "title": ""}
{"_id": "d19531", "text": "def _check_stream_timeout(started, timeout):\n    \"\"\"Check if the timeout has been reached and raise a `StopIteration` if so.\n    \"\"\"\n    if timeout:\n        elapsed = datetime.datetime.utcnow() - started\n        if elapsed.seconds > timeout:\n            raise StopIteration", "title": ""}
{"_id": "d19532", "text": "def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:\n    \"\"\"Calculate the tanimoto set similarity.\"\"\"\n    a, b = set(x), set(y)\n    union = a | b\n\n    if not union:\n        return 0.0\n\n    return len(a & b) / len(union)", "title": ""}
{"_id": "d19533", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d19534", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d19535", "text": "def do_quit(self, _: argparse.Namespace) -> bool:\n        \"\"\"Exit this application\"\"\"\n        self._should_quit = True\n        return self._STOP_AND_EXIT", "title": ""}
{"_id": "d19536", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d19537", "text": "def rmglob(pattern: str) -> None:\n    \"\"\"\n    Deletes all files whose filename matches the glob ``pattern`` (via\n    :func:`glob.glob`).\n    \"\"\"\n    for f in glob.glob(pattern):\n        os.remove(f)", "title": ""}
{"_id": "d19538", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d19539", "text": "def position(self) -> Position:\n        \"\"\"The current position of the cursor.\"\"\"\n        return Position(self._index, self._lineno, self._col_offset)", "title": ""}
{"_id": "d19540", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d19541", "text": "def _duplicates(list_):\n    \"\"\"Return dict mapping item -> indices.\"\"\"\n    item_indices = {}\n    for i, item in enumerate(list_):\n        try:\n            item_indices[item].append(i)\n        except KeyError:  # First time seen\n            item_indices[item] = [i]\n    return item_indices", "title": ""}
{"_id": "d19542", "text": "def trim_decimals(s, precision=-3):\n        \"\"\"\n        Convert from scientific notation using precision\n        \"\"\"\n        encoded = s.encode('ascii', 'ignore')\n        str_val = \"\"\n        if six.PY3:\n            str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]\n        else:\n            # If precision is 0, this must be handled seperately\n            if precision == 0:\n                str_val = str(encoded)\n            else:\n                str_val = str(encoded)[:precision]\n        if len(str_val) > 0:\n            return float(str_val)\n        else:\n            return 0", "title": ""}
{"_id": "d19543", "text": "def arcball_map_to_sphere(point, center, radius):\n    \"\"\"Return unit sphere coordinates from window coordinates.\"\"\"\n    v0 = (point[0] - center[0]) / radius\n    v1 = (center[1] - point[1]) / radius\n    n = v0*v0 + v1*v1\n    if n > 1.0:\n        # position outside of sphere\n        n = math.sqrt(n)\n        return numpy.array([v0/n, v1/n, 0.0])\n    else:\n        return numpy.array([v0, v1, math.sqrt(1.0 - n)])", "title": ""}
{"_id": "d19544", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d19545", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d19546", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d19547", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d19548", "text": "def normcdf(x, log=False):\n    \"\"\"Normal cumulative density function.\"\"\"\n    y = np.atleast_1d(x).copy()\n    flib.normcdf(y)\n    if log:\n        if (y>0).all():\n            return np.log(y)\n        return -np.inf\n    return y", "title": ""}
{"_id": "d19549", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d19550", "text": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "title": ""}
{"_id": "d19551", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d19552", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d19553", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d19554", "text": "def test_string(self, string: str) -> bool:\n        \"\"\"If `string` comes next, return ``True`` and advance offset.\n\n        Args:\n            string: string to test\n        \"\"\"\n        if self.input.startswith(string, self.offset):\n            self.offset += len(string)\n            return True\n        return False", "title": ""}
{"_id": "d19555", "text": "def Exit(msg, code=1):\n    \"\"\"Exit execution with return code and message\n    :param msg: Message displayed prior to exit\n    :param code: code returned upon exiting\n    \"\"\"\n    print >> sys.stderr, msg\n    sys.exit(code)", "title": ""}
{"_id": "d19556", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d19557", "text": "def capture_stdout():\n    \"\"\"Intercept standard output in a with-context\n    :return: cStringIO instance\n\n    >>> with capture_stdout() as stdout:\n            ...\n        print stdout.getvalue()\n    \"\"\"\n    stdout = sys.stdout\n    sys.stdout = six.moves.cStringIO()\n    try:\n        yield sys.stdout\n    finally:\n        sys.stdout = stdout", "title": ""}
{"_id": "d19558", "text": "def list_to_str(lst):\n    \"\"\"\n    Turn a list into a comma- and/or and-separated string.\n\n    Parameters\n    ----------\n    lst : :obj:`list`\n        A list of strings to join into a single string.\n\n    Returns\n    -------\n    str_ : :obj:`str`\n        A string with commas and/or ands separating th elements from ``lst``.\n\n    \"\"\"\n    if len(lst) == 1:\n        str_ = lst[0]\n    elif len(lst) == 2:\n        str_ = ' and '.join(lst)\n    elif len(lst) > 2:\n        str_ = ', '.join(lst[:-1])\n        str_ += ', and {0}'.format(lst[-1])\n    else:\n        raise ValueError('List of length 0 provided.')\n    return str_", "title": ""}
{"_id": "d19559", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d19560", "text": "def memory_read(self, start_position: int, size: int) -> memoryview:\n        \"\"\"\n        Read and return a view of ``size`` bytes from memory starting at ``start_position``.\n        \"\"\"\n        return self._memory.read(start_position, size)", "title": ""}
{"_id": "d19561", "text": "def spanning_tree_count(graph: nx.Graph) -> int:\n    \"\"\"Return the number of unique spanning trees of a graph, using\n    Kirchhoff's matrix tree theorem.\n    \"\"\"\n    laplacian = nx.laplacian_matrix(graph).toarray()\n    comatrix = laplacian[:-1, :-1]\n    det = np.linalg.det(comatrix)\n    count = int(round(det))\n    return count", "title": ""}
{"_id": "d19562", "text": "def get_valid_filename(s):\n    \"\"\"\n    Returns the given string converted to a string that can be used for a clean\n    filename. Specifically, leading and trailing spaces are removed; other\n    spaces are converted to underscores; and anything that is not a unicode\n    alphanumeric, dash, underscore, or dot, is removed.\n    >>> get_valid_filename(\"john's portrait in 2004.jpg\")\n    'johns_portrait_in_2004.jpg'\n    \"\"\"\n    s = s.strip().replace(\" \", \"_\")\n    return re.sub(r\"(?u)[^-\\w.]\", \"\", s)", "title": ""}
{"_id": "d19563", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d19564", "text": "def find_duplicates(l: list) -> set:\n    \"\"\"\n    Return the duplicates in a list.\n\n    The function relies on\n    https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n    Parameters\n    ----------\n    l : list\n        Name\n\n    Returns\n    -------\n    set\n        Duplicated values\n\n    >>> find_duplicates([1,2,3])\n    set()\n    >>> find_duplicates([1,2,1])\n    {1}\n    \"\"\"\n    return set([x for x in l if l.count(x) > 1])", "title": ""}
{"_id": "d19565", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d19566", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d19567", "text": "def most_frequent(lst):\n    \"\"\"\n    Returns the item that appears most frequently in the given list.\n    \"\"\"\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n            \n    return most_freq", "title": ""}
{"_id": "d19568", "text": "def _is_numeric(self, values):\n        \"\"\"Check to be sure values are numbers before doing numerical operations.\"\"\"\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", "title": ""}
{"_id": "d19569", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d19570", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d19571", "text": "def get_margin(length):\n    \"\"\"Add enough tabs to align in two columns\"\"\"\n    if length > 23:\n        margin_left = \"\\t\"\n        chars = 1\n    elif length > 15:\n        margin_left = \"\\t\\t\"\n        chars = 2\n    elif length > 7:\n        margin_left = \"\\t\\t\\t\"\n        chars = 3\n    else:\n        margin_left = \"\\t\\t\\t\\t\"\n        chars = 4\n    return margin_left", "title": ""}
{"_id": "d19572", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d19573", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d19574", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d19575", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d19576", "text": "def get_keys_of_max_n(dict_obj, n):\n    \"\"\"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']\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    ])", "title": ""}
{"_id": "d19577", "text": "def nTimes(n, f, *args, **kwargs):\n    r\"\"\"Call `f` `n` times with `args` and `kwargs`.\n    Useful e.g. for simplistic timing.\n\n    Examples:\n\n    >>> nTimes(3, sys.stdout.write, 'hallo\\n')\n    hallo\n    hallo\n    hallo\n\n    \"\"\"\n    for i in xrange(n): f(*args, **kwargs)", "title": ""}
{"_id": "d19578", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d19579", "text": "def _width_is_big_enough(image, width):\n    \"\"\"Check that the image width is superior to `width`\"\"\"\n    if width > image.size[0]:\n        raise ImageSizeError(image.size[0], width)", "title": ""}
{"_id": "d19580", "text": "def assert_equal(first, second, msg_fmt=\"{msg}\"):\n    \"\"\"Fail unless first equals second, as determined by the '==' operator.\n\n    >>> assert_equal(5, 5.0)\n    >>> assert_equal(\"Hello World!\", \"Goodbye!\")\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'Hello World!' != 'Goodbye!'\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\n    \"\"\"\n\n    if isinstance(first, dict) and isinstance(second, dict):\n        assert_dict_equal(first, second, msg_fmt)\n    elif not first == second:\n        msg = \"{!r} != {!r}\".format(first, second)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))", "title": ""}
{"_id": "d19581", "text": "def add_colons(s):\n    \"\"\"Add colons after every second digit.\n\n    This function is used in functions to prettify serials.\n\n    >>> add_colons('teststring')\n    'te:st:st:ri:ng'\n    \"\"\"\n    return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)])", "title": ""}
{"_id": "d19582", "text": "def label_from_bin(buf):\n    \"\"\"\n    Converts binary representation label to integer.\n\n    :param buf: Binary representation of label.\n    :return: MPLS Label and BoS bit.\n    \"\"\"\n\n    mpls_label = type_desc.Int3.to_user(six.binary_type(buf))\n    return mpls_label >> 4, mpls_label & 1", "title": ""}
{"_id": "d19583", "text": "def zfill(x, width):\n    \"\"\"zfill(x, width) -> string\n\n    Pad a numeric string x with zeros on the left, to fill a field\n    of the specified width.  The string x is never truncated.\n\n    \"\"\"\n    if not isinstance(x, basestring):\n        x = repr(x)\n    return x.zfill(width)", "title": ""}
{"_id": "d19584", "text": "def valid_file(path: str) -> bool:\n    \"\"\"\n    Verifies that a string path actually exists and is a file\n\n    :param path: The path to verify\n    :return: **True** if path exist and is a file\n    \"\"\"\n    path = Path(path).expanduser()\n    log.debug(\"checking if %s is a valid file\", path)\n    return path.exists() and path.is_file()", "title": ""}
{"_id": "d19585", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d19586", "text": "def copen(filepath, flag='r', encoding=None):\n\n    \"\"\"\n    FIXME: How to test this ?\n\n    >>> c = copen(__file__)\n    >>> c is not None\n    True\n    \"\"\"\n    if encoding is None:\n        encoding = locale.getdefaultlocale()[1]\n\n    return codecs.open(filepath, flag, encoding)", "title": ""}
{"_id": "d19587", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d19588", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d19589", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d19590", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d19591", "text": "def convert_bytes_to_ints(in_bytes, num):\n    \"\"\"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\"\"\"\n    dt = numpy.dtype('>i' + str(num))\n    return numpy.frombuffer(in_bytes, dt)", "title": ""}
{"_id": "d19592", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d19593", "text": "def camel_to_snake(s: str) -> str:\n    \"\"\"Convert string from camel case to snake case.\"\"\"\n\n    return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()", "title": ""}
{"_id": "d19594", "text": "def isfile_notempty(inputfile: str) -> bool:\n        \"\"\"Check if the input filename with path is a file and is not empty.\"\"\"\n        try:\n            return isfile(inputfile) and getsize(inputfile) > 0\n        except TypeError:\n            raise TypeError('inputfile is not a valid type')", "title": ""}
{"_id": "d19595", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d19596", "text": "def post(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP POST operation to API endpoint.\"\"\"\n\n        return self._request('POST', endpoint, **kwargs)", "title": ""}
{"_id": "d19597", "text": "def create_opengl_object(gl_gen_function, n=1):\n    \"\"\"Returns int pointing to an OpenGL texture\"\"\"\n    handle = gl.GLuint(1)\n    gl_gen_function(n, byref(handle))  # Create n Empty Objects\n    if n > 1:\n        return [handle.value + el for el in range(n)]  # Return list of handle values\n    else:\n        return handle.value", "title": ""}
{"_id": "d19598", "text": "def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]:\n        \"\"\" Return a json array as a list\n\n        :param value: array\n        :return: array with JsonObj instances removed\n        \"\"\"\n        return [e._as_dict if isinstance(e, JsonObj) else e for e in value]", "title": ""}
{"_id": "d19599", "text": "def text_to_bool(value: str) -> bool:\n    \"\"\"\n    Tries to convert a text value to a bool. If unsuccessful returns if value is None or not\n\n    :param value: Value to check\n    \"\"\"\n    try:\n        return bool(strtobool(value))\n    except (ValueError, AttributeError):\n        return value is not None", "title": ""}
{"_id": "d19600", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d19601", "text": "def is_any_type_set(sett: Set[Type]) -> bool:\n    \"\"\"\n    Helper method to check if a set of types is the {AnyObject} singleton\n\n    :param sett:\n    :return:\n    \"\"\"\n    return len(sett) == 1 and is_any_type(min(sett))", "title": ""}
{"_id": "d19602", "text": "def _check_env_var(envvar: str) -> bool:\n    \"\"\"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\n    \"\"\"\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):  # test if env var is empty\n        raise KeyError(\n            \"Required ENVVAR: {0} is empty\".format(envvar))\n    return True", "title": ""}
{"_id": "d19603", "text": "def warn_if_nans_exist(X):\n    \"\"\"Warn if nans exist in a numpy array.\"\"\"\n    null_count = count_rows_with_nans(X)\n    total = len(X)\n    percent = 100 * null_count / total\n\n    if null_count > 0:\n        warning_message = \\\n            'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n            'complete rows will be plotted.'.format(null_count, total, percent)\n        warnings.warn(warning_message, DataWarning)", "title": ""}
{"_id": "d19604", "text": "async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:\n        \"\"\"Execute the given multiquery.\"\"\"\n        await self._execute(self._cursor.executemany, sql, parameters)", "title": ""}
{"_id": "d19605", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d19606", "text": "def make_file_readable (filename):\n    \"\"\"Make file user readable if it is not a link.\"\"\"\n    if not os.path.islink(filename):\n        util.set_mode(filename, stat.S_IRUSR)", "title": ""}
{"_id": "d19607", "text": "def apply(filter):\n    \"\"\"Manufacture decorator that filters return value with given function.\n\n    ``filter``:\n      Callable that takes a single parameter.\n    \"\"\"\n    def decorator(callable):\n        return lambda *args, **kwargs: filter(callable(*args, **kwargs))\n    return decorator", "title": ""}
{"_id": "d19608", "text": "def ensure_newline(self):\n        \"\"\"\n        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\n        \"\"\"\n        DECTCEM_SHOW = '\\033[?25h'  # show cursor\n        AT_END = DECTCEM_SHOW + '\\n'\n        if not self._cursor_at_newline:\n            self.write(AT_END)\n            self._cursor_at_newline = True", "title": ""}
{"_id": "d19609", "text": "def variance(arr):\n  \"\"\"variance of the values, must have 2 or more entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: variance\n  :rtype: float\n\n  \"\"\"\n  avg = average(arr)\n  return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "title": ""}
{"_id": "d19610", "text": "def is_bool_matrix(l):\n    r\"\"\"Checks if l is a 2D numpy array of bools\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 2 and (l.dtype == bool):\n            return True\n    return False", "title": ""}
{"_id": "d19611", "text": "def is_integer_array(val):\n    \"\"\"\n    Checks whether a variable is a numpy integer array.\n\n    Parameters\n    ----------\n    val\n        The variable to check.\n\n    Returns\n    -------\n    bool\n        True if the variable is a numpy integer array. Otherwise False.\n\n    \"\"\"\n    return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "title": ""}
{"_id": "d19612", "text": "def rrmdir(directory):\n    \"\"\"\n    Recursivly delete a directory\n\n    :param directory: directory to remove\n    \"\"\"\n    for root, dirs, files in os.walk(directory, topdown=False):\n        for name in files:\n            os.remove(os.path.join(root, name))\n        for name in dirs:\n            os.rmdir(os.path.join(root, name))\n    os.rmdir(directory)", "title": ""}
{"_id": "d19613", "text": "def values(self):\n        \"\"\"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\n        \"\"\"\n        lower = float(self.lowerSpnbx.value())\n        upper = float(self.upperSpnbx.value())\n        return (lower, upper)", "title": ""}
{"_id": "d19614", "text": "def list_formatter(handler, item, value):\n    \"\"\"Format list.\"\"\"\n    return u', '.join(str(v) for v in value)", "title": ""}
{"_id": "d19615", "text": "def distinct(xs):\n    \"\"\"Get the list of distinct values with preserving order.\"\"\"\n    # don't use collections.OrderedDict because we do support Python 2.6\n    seen = set()\n    return [x for x in xs if x not in seen and not seen.add(x)]", "title": ""}
{"_id": "d19616", "text": "def graph_from_dot_file(path):\n    \"\"\"Load graph as defined by a DOT file.\n    \n    The file is assumed to be in DOT format. It will\n    be loaded, parsed and a Dot class will be returned, \n    representing the graph.\n    \"\"\"\n    \n    fd = file(path, 'rb')\n    data = fd.read()\n    fd.close()\n    \n    return graph_from_dot_data(data)", "title": ""}
{"_id": "d19617", "text": "def butlast(iterable):\n    \"\"\"Yield all items from ``iterable`` except the last one.\n\n    >>> list(butlast(['spam', 'eggs', 'ham']))\n    ['spam', 'eggs']\n\n    >>> list(butlast(['spam']))\n    []\n\n    >>> list(butlast([]))\n    []\n    \"\"\"\n    iterable = iter(iterable)\n    try:\n        first = next(iterable)\n    except StopIteration:\n        return\n    for second in iterable:\n        yield first\n        first = second", "title": ""}
{"_id": "d19618", "text": "def _read_stream_for_size(stream, buf_size=65536):\n    \"\"\"Reads a stream discarding the data read and returns its size.\"\"\"\n    size = 0\n    while True:\n        buf = stream.read(buf_size)\n        size += len(buf)\n        if not buf:\n            break\n    return size", "title": ""}
{"_id": "d19619", "text": "def s3_get(url: str, temp_file: IO) -> None:\n    \"\"\"Pull a file directly from S3.\"\"\"\n    s3_resource = boto3.resource(\"s3\")\n    bucket_name, s3_path = split_s3_path(url)\n    s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "title": ""}
{"_id": "d19620", "text": "def Proxy(f):\n  \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n\n  return Wrapped", "title": ""}
{"_id": "d19621", "text": "def is_float(value):\n    \"\"\"must be a float\"\"\"\n    return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "title": ""}
{"_id": "d19622", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d19623", "text": "def cli_run():\n    \"\"\"docstring for argparse\"\"\"\n    parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n    parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n    parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n    args = parser.parse_args()\n    main(args)", "title": ""}
{"_id": "d19624", "text": "def setdefault(obj, field, default):\n    \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n    setattr(obj, field, getattr(obj, field, default))", "title": ""}
{"_id": "d19625", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d19626", "text": "def clean_int(x) -> int:\n    \"\"\"\n    Returns its parameter as an integer, or raises\n    ``django.forms.ValidationError``.\n    \"\"\"\n    try:\n        return int(x)\n    except ValueError:\n        raise forms.ValidationError(\n            \"Cannot convert to integer: {}\".format(repr(x)))", "title": ""}
{"_id": "d19627", "text": "def contains_empty(features):\n    \"\"\"Check features data are not empty\n\n    :param features: The features data to check.\n    :type features: list of numpy arrays.\n\n    :return: True if one of the array is empty, False else.\n\n    \"\"\"\n    if not features:\n        return True\n    for feature in features:\n        if feature.shape[0] == 0:\n            return True\n    return False", "title": ""}
{"_id": "d19628", "text": "def _go_to_line(editor, line):\n    \"\"\"\n    Move cursor to this line in the current buffer.\n    \"\"\"\n    b = editor.application.current_buffer\n    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "title": ""}
{"_id": "d19629", "text": "def test_value(self, value):\n        \"\"\"Test if value is an instance of int.\"\"\"\n        if not isinstance(value, int):\n            raise ValueError('expected int value: ' + str(type(value)))", "title": ""}
{"_id": "d19630", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d19631", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d19632", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d19633", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d19634", "text": "def getpackagepath():\n    \"\"\"\n     *Get the root path for this python package - used in unit testing code*\n    \"\"\"\n    moduleDirectory = os.path.dirname(__file__)\n    packagePath = os.path.dirname(__file__) + \"/../\"\n\n    return packagePath", "title": ""}
{"_id": "d19635", "text": "def to_bin(data, width):\n    \"\"\"\n    Convert an unsigned integer to a numpy binary array with the first\n    element the MSB and the last element the LSB.\n    \"\"\"\n    data_str = bin(data & (2**width-1))[2:].zfill(width)\n    return [int(x) for x in tuple(data_str)]", "title": ""}
{"_id": "d19636", "text": "def __remove_trailing_zeros(self, collection):\n        \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n\n        return collection[:index + 1]", "title": ""}
{"_id": "d19637", "text": "def fix(h, i):\n    \"\"\"Rearrange the heap after the item at position i got updated.\"\"\"\n    down(h, i, h.size())\n    up(h, i)", "title": ""}
{"_id": "d19638", "text": "def crop_box(im, box=False, **kwargs):\n    \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n    if box:\n        im = im.crop(box)\n    return im", "title": ""}
{"_id": "d19639", "text": "def _linear_interpolation(x, X, Y):\n    \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n    \"\"\"\n    return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "title": ""}
{"_id": "d19640", "text": "def is_numeric_dtype(dtype):\n    \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n    dtype = np.dtype(dtype)\n    return np.issubsctype(getattr(dtype, 'base', None), np.number)", "title": ""}
{"_id": "d19641", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d19642", "text": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "title": ""}
{"_id": "d19643", "text": "def is_valid(number):\n    \"\"\"determines whether the card number is valid.\"\"\"\n    n = str(number)\n    if not n.isdigit():\n        return False\n    return int(n[-1]) == get_check_digit(n[:-1])", "title": ""}
{"_id": "d19644", "text": "def isbinary(*args):\n    \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n    return all(map(lambda c: isnumber(c) or isbool(c), args))", "title": ""}
{"_id": "d19645", "text": "def rm_empty_indices(*args):\n    \"\"\"\n    Remove unwanted list indices. First argument is the list\n    of indices to remove. Other elements are the lists\n    to trim.\n    \"\"\"\n    rm_inds = args[0]\n\n    if not rm_inds:\n        return args[1:]\n\n    keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n    return [[a[i] for i in keep_inds] for a in args[1:]]", "title": ""}
{"_id": "d19646", "text": "def clear_instance(cls):\n        \"\"\"unset _instance for this class and singleton parents.\n        \"\"\"\n        if not cls.initialized():\n            return\n        for subclass in cls._walk_mro():\n            if isinstance(subclass._instance, cls):\n                # only clear instances that are instances\n                # of the calling class\n                subclass._instance = None", "title": ""}
{"_id": "d19647", "text": "def stderr(a):\n    \"\"\"\n    Calculate the standard error of a.\n    \"\"\"\n    return np.nanstd(a) / np.sqrt(sum(np.isfinite(a)))", "title": ""}
{"_id": "d19648", "text": "def __init__(self, capacity=10):\n        \"\"\"\n        Initialize python List with capacity of 10 or user given input.\n        Python List type is a dynamic array, so we have to restrict its\n        dynamic nature to make it work like a static array.\n        \"\"\"\n        super().__init__()\n        self._array = [None] * capacity\n        self._front = 0\n        self._rear = 0", "title": ""}
{"_id": "d19649", "text": "def login(self, user: str, passwd: str) -> None:\n        \"\"\"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`.\"\"\"\n        self.context.login(user, passwd)", "title": ""}
{"_id": "d19650", "text": "def get_shape(img):\n    \"\"\"Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple\n    \"\"\"\n    if hasattr(img, 'shape'):\n        shape = img.shape\n    else:\n        shape = img.get_data().shape\n    return shape", "title": ""}
{"_id": "d19651", "text": "def rotateImage(image, angle):\n    \"\"\"\n        rotates a 2d array to a multiple of 90 deg.\n        0 = default\n        1 = 90 deg. cw\n        2 = 180 deg.\n        3 = 90 deg. ccw\n    \"\"\"\n    image = [list(row) for row in image]\n\n    for n in range(angle % 4):\n        image = list(zip(*image[::-1]))\n\n    return image", "title": ""}
{"_id": "d19652", "text": "def staticdir():\n    \"\"\"Return the location of the static data directory.\"\"\"\n    root = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(root, \"static\")", "title": ""}
{"_id": "d19653", "text": "def add_chart(self, chart, row, col):\n        \"\"\"\n        Adds a chart to the worksheet at (row, col).\n\n        :param xltable.Chart Chart: chart to add to the workbook.\n        :param int row: Row to add the chart at.\n        \"\"\"\n        self.__charts.append((chart, (row, col)))", "title": ""}
{"_id": "d19654", "text": "def from_series(cls, series):\n        \"\"\"Convert a pandas.Series into an xarray.DataArray.\n\n        If the series's index is a MultiIndex, it will be expanded into a\n        tensor product of one-dimensional coordinates (filling in missing\n        values with NaN). Thus this operation should be the inverse of the\n        `to_series` method.\n        \"\"\"\n        # TODO: add a 'name' parameter\n        name = series.name\n        df = pd.DataFrame({name: series})\n        ds = Dataset.from_dataframe(df)\n        return ds[name]", "title": ""}
{"_id": "d19655", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d19656", "text": "def contains(self, token: str) -> bool:\n        \"\"\"Return if the token is in the list or not.\"\"\"\n        self._validate_token(token)\n        return token in self", "title": ""}
{"_id": "d19657", "text": "def sem(inlist):\n    \"\"\"\nReturns the estimated standard error of the mean (sx-bar) of the\nvalues in the passed list.  sem = stdev / sqrt(n)\n\nUsage:   lsem(inlist)\n\"\"\"\n    sd = stdev(inlist)\n    n = len(inlist)\n    return sd / math.sqrt(n)", "title": ""}
{"_id": "d19658", "text": "def get(key, default=None):\n    \"\"\" return the key from the request\n    \"\"\"\n    data = get_form() or get_query_string()\n    return data.get(key, default)", "title": ""}
{"_id": "d19659", "text": "def use_kwargs(self, *args, **kwargs) -> typing.Callable:\n        \"\"\"Decorator that injects parsed arguments into a view function or method.\n\n        Receives the same arguments as `webargs.core.Parser.use_kwargs`.\n\n        \"\"\"\n        return super().use_kwargs(*args, **kwargs)", "title": ""}
{"_id": "d19660", "text": "def _check_whitespace(string):\n    \"\"\"\n    Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected\n    \"\"\"\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "title": ""}
{"_id": "d19661", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d19662", "text": "def clear_globals_reload_modules(self):\n        \"\"\"Clears globals and reloads modules\"\"\"\n\n        self.code_array.clear_globals()\n        self.code_array.reload_modules()\n\n        # Clear result cache\n        self.code_array.result_cache.clear()", "title": ""}
{"_id": "d19663", "text": "def raw_connection_from(engine_or_conn):\n    \"\"\"Extract a raw_connection and determine if it should be automatically closed.\n\n    Only connections opened by this package will be closed automatically.\n    \"\"\"\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", "title": ""}
{"_id": "d19664", "text": "def selectnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is `None`.\"\"\"\n\n    return select(table, field, lambda v: v is None, complement=complement)", "title": ""}
{"_id": "d19665", "text": "def axes_off(ax):\n    \"\"\"Get rid of all axis ticks, lines, etc.\n    \"\"\"\n    ax.set_frame_on(False)\n    ax.axes.get_yaxis().set_visible(False)\n    ax.axes.get_xaxis().set_visible(False)", "title": ""}
{"_id": "d19666", "text": "def is_defined(self, objtxt, force_import=False):\n        \"\"\"Return True if object is defined\"\"\"\n        return self.interpreter.is_defined(objtxt, force_import)", "title": ""}
{"_id": "d19667", "text": "def filter_query_string(query):\n    \"\"\"\n        Return a version of the query string with the _e, _k and _s values\n        removed.\n    \"\"\"\n    return '&'.join([q for q in query.split('&')\n        if not (q.startswith('_k=') or q.startswith('_e=') or q.startswith('_s'))])", "title": ""}
{"_id": "d19668", "text": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n    \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n    dt = get_datetime_now().astimezone()\n    tzstr = dt.strftime(\"%z\")\n    tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n    return dt.tzinfo, tzstr", "title": ""}
{"_id": "d19669", "text": "def normalise_string(string):\n    \"\"\" Strips trailing whitespace from string, lowercases it and replaces\n        spaces with underscores\n    \"\"\"\n    string = (string.strip()).lower()\n    return re.sub(r'\\W+', '_', string)", "title": ""}
{"_id": "d19670", "text": "def transpose(table):\n    \"\"\"\n    transpose matrix\n    \"\"\"\n    t = []\n    for i in range(0, len(table[0])):\n        t.append([row[i] for row in table])\n    return t", "title": ""}
{"_id": "d19671", "text": "def is_same_shape(self, other_im, check_channels=False):\n        \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n        Parameters\n        ----------\n        other_im : :obj:`Image`\n            image to compare\n        check_channels : bool\n            whether or not to check equality of the channels\n\n        Returns\n        -------\n        bool\n            True if the images are the same shape, False otherwise\n        \"\"\"\n        if self.height == other_im.height and self.width == other_im.width:\n            if check_channels and self.channels != other_im.channels:\n                return False\n            return True\n        return False", "title": ""}
{"_id": "d19672", "text": "def is_identifier(string):\n    \"\"\"Check if string could be a valid python identifier\n\n    :param string: string to be tested\n    :returns: True if string can be a python identifier, False otherwise\n    :rtype: bool\n    \"\"\"\n    matched = PYTHON_IDENTIFIER_RE.match(string)\n    return bool(matched) and not keyword.iskeyword(string)", "title": ""}
{"_id": "d19673", "text": "def remove_hop_by_hop_headers(headers):\n    \"\"\"Remove all HTTP/1.1 \"Hop-by-Hop\" headers from a list or\n    :class:`Headers` object.  This operation works in-place.\n\n    .. versionadded:: 0.5\n\n    :param headers: a list or :class:`Headers` object.\n    \"\"\"\n    headers[:] = [\n        (key, value) for key, value in headers if not is_hop_by_hop_header(key)\n    ]", "title": ""}
{"_id": "d19674", "text": "def coerce(self, value):\n        \"\"\"Convert from whatever is given to a list of scalars for the lookup_field.\"\"\"\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]", "title": ""}
{"_id": "d19675", "text": "def rlognormal(mu, tau, size=None):\n    \"\"\"\n    Return random lognormal variates.\n    \"\"\"\n\n    return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "title": ""}
{"_id": "d19676", "text": "def on_train_end(self, logs):\n        \"\"\" Print training time at end of training \"\"\"\n        duration = timeit.default_timer() - self.train_start\n        print('done, took {:.3f} seconds'.format(duration))", "title": ""}
{"_id": "d19677", "text": "def guess_title(basename):\n    \"\"\" Attempt to guess the title from the filename \"\"\"\n\n    base, _ = os.path.splitext(basename)\n    return re.sub(r'[ _-]+', r' ', base).title()", "title": ""}
{"_id": "d19678", "text": "def log_no_newline(self, msg):\n      \"\"\" print the message to the predefined log file without newline \"\"\"\n      self.print2file(self.logfile, False, False, msg)", "title": ""}
{"_id": "d19679", "text": "def read_text_from_file(path: str) -> str:\n    \"\"\" Reads text file contents \"\"\"\n    with open(path) as text_file:\n        content = text_file.read()\n\n    return content", "title": ""}
{"_id": "d19680", "text": "def remove_duplicates(lst):\n    \"\"\"\n    Emulate what a Python ``set()`` does, but keeping the element's order.\n    \"\"\"\n    dset = set()\n    return [l for l in lst if l not in dset and not dset.add(l)]", "title": ""}
{"_id": "d19681", "text": "def computeDelaunayTriangulation(points):\n    \"\"\" Takes a list of point objects (which must have x and y fields).\n        Returns a list of 3-tuples: the indices of the points that form a\n        Delaunay triangle.\n    \"\"\"\n    siteList = SiteList(points)\n    context  = Context()\n    context.triangulate = True\n    voronoi(siteList,context)\n    return context.triangles", "title": ""}
{"_id": "d19682", "text": "def is_string_dtype(arr_or_dtype):\n    \"\"\"\n    Check whether the provided array or dtype is of the string 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 the string dtype.\n\n    Examples\n    --------\n    >>> is_string_dtype(str)\n    True\n    >>> is_string_dtype(object)\n    True\n    >>> is_string_dtype(int)\n    False\n    >>>\n    >>> is_string_dtype(np.array(['a', 'b']))\n    True\n    >>> is_string_dtype(pd.Series([1, 2]))\n    False\n    \"\"\"\n\n    # TODO: gh-15585: consider making the checks stricter.\n    def condition(dtype):\n        return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype)\n    return _is_dtype(arr_or_dtype, condition)", "title": ""}
{"_id": "d19683", "text": "def to_str(obj):\n    \"\"\"Attempts to convert given object to a string object\n    \"\"\"\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)", "title": ""}
{"_id": "d19684", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d19685", "text": "def smooth_array(array, amount=1):\n    \"\"\"\n\n    Returns the nearest-neighbor (+/- amount) smoothed array.\n    This does not modify the array or slice off the funny end points.\n\n    \"\"\"\n    if amount==0: return array\n\n    # we have to store the old values in a temp array to keep the\n    # smoothing from affecting the smoothing\n    new_array = _n.array(array)\n\n    for n in range(len(array)):\n        new_array[n] = smooth(array, n, amount)\n\n    return new_array", "title": ""}
{"_id": "d19686", "text": "def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:\n    \"\"\"\n    Within the dictionary ``d``, find a key that matches (in case-insensitive\n    fashion) the key ``k``, and return it (or ``None`` if there isn't one).\n    \"\"\"\n    for key in d.keys():\n        if k.lower() == key.lower():\n            return key\n    return None", "title": ""}
{"_id": "d19687", "text": "def sort_func(self, key):\n        \"\"\"Sorting logic for `Quantity` objects.\"\"\"\n        if key == self._KEYS.VALUE:\n            return 'aaa'\n        if key == self._KEYS.SOURCE:\n            return 'zzz'\n        return key", "title": ""}
{"_id": "d19688", "text": "def _index_ordering(redshift_list):\n        \"\"\"\n\n        :param redshift_list: list of redshifts\n        :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n        \"\"\"\n        redshift_list = np.array(redshift_list)\n        sort_index = np.argsort(redshift_list)\n        return sort_index", "title": ""}
{"_id": "d19689", "text": "def cprint(string, fg=None, bg=None, end='\\n', target=sys.stdout):\n    \"\"\"Print a colored string to the target handle.\n\n    fg and bg specify foreground- and background colors, respectively. The\n    remaining keyword arguments are the same as for Python's built-in print\n    function. Colors are returned to their defaults before the function\n    returns.\n\n    \"\"\"\n    _color_manager.set_color(fg, bg)\n    target.write(string + end)\n    target.flush()  # Needed for Python 3.x\n    _color_manager.set_defaults()", "title": ""}
{"_id": "d19690", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d19691", "text": "def is_readable(filename):\n    \"\"\"Check if file is a regular file and is readable.\"\"\"\n    return os.path.isfile(filename) and os.access(filename, os.R_OK)", "title": ""}
{"_id": "d19692", "text": "def ln_norm(x, mu, sigma=1.0):\n    \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n    return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "title": ""}
{"_id": "d19693", "text": "def ensure_dir(f):\n    \"\"\" Ensure a a file exists and if not make the relevant path \"\"\"\n    d = os.path.dirname(f)\n    if not os.path.exists(d):\n        os.makedirs(d)", "title": ""}
{"_id": "d19694", "text": "def redirect_output(fileobj):\n    \"\"\"Redirect standard out to file.\"\"\"\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old", "title": ""}
{"_id": "d19695", "text": "def close_database_session(session):\n    \"\"\"Close connection with the database\"\"\"\n\n    try:\n        session.close()\n    except OperationalError as e:\n        raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])", "title": ""}
{"_id": "d19696", "text": "def parse_cookies(self, req, name, field):\n        \"\"\"Pull the value from the cookiejar.\"\"\"\n        return core.get_value(req.COOKIES, name, field)", "title": ""}
{"_id": "d19697", "text": "def unique(seq):\n    \"\"\"Return the unique elements of a collection even if those elements are\n       unhashable and unsortable, like dicts and sets\"\"\"\n    cleaned = []\n    for each in seq:\n        if each not in cleaned:\n            cleaned.append(each)\n    return cleaned", "title": ""}
{"_id": "d19698", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d19699", "text": "def redirect_stdout(new_stdout):\n    \"\"\"Redirect the stdout\n\n    Args:\n        new_stdout (io.StringIO): New stdout to use instead\n    \"\"\"\n    old_stdout, sys.stdout = sys.stdout, new_stdout\n    try:\n        yield None\n    finally:\n        sys.stdout = old_stdout", "title": ""}
{"_id": "d19700", "text": "def command_py2to3(args):\n    \"\"\"\n    Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n    \"\"\"\n    from lib2to3.main import main\n    sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "title": ""}
{"_id": "d19701", "text": "def _skip_section(self):\n        \"\"\"Skip a section\"\"\"\n        self._last = self._f.readline()\n        while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n            self._last = self._f.readline()", "title": ""}
{"_id": "d19702", "text": "def get_git_branch(git_path='git'):\n    \"\"\"Returns the name of the current git branch\n    \"\"\"\n    branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD'))\n    if branch_match == \"HEAD\":\n        return None\n    else:\n        return os.path.basename(branch_match)", "title": ""}
{"_id": "d19703", "text": "def check_auth(email, password):\n    \"\"\"Check if a username/password combination is valid.\n    \"\"\"\n    try:\n        user = User.get(User.email == email)\n    except User.DoesNotExist:\n        return False\n    return password == user.password", "title": ""}
{"_id": "d19704", "text": "def _read_date_from_string(str1):\n    \"\"\"\n    Reads the date from a string in the format YYYY/MM/DD and returns\n    :class: datetime.date\n    \"\"\"\n    full_date = [int(x) for x in str1.split('/')]\n    return datetime.date(full_date[0], full_date[1], full_date[2])", "title": ""}
{"_id": "d19705", "text": "def find_le(a, x):\n    \"\"\"Find rightmost value less than or equal to x.\"\"\"\n    i = bs.bisect_right(a, x)\n    if i: return i - 1\n    raise ValueError", "title": ""}
{"_id": "d19706", "text": "def write_line(self, line, count=1):\n        \"\"\"writes the line and count newlines after the line\"\"\"\n        self.write(line)\n        self.write_newlines(count)", "title": ""}
{"_id": "d19707", "text": "def is_int(value):\n    \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n    if isinstance(value, bool):\n        return False\n    try:\n        int(value)\n        return True\n    except (ValueError, TypeError):\n        return False", "title": ""}
{"_id": "d19708", "text": "def ma(self):\n        \"\"\"Represent data as a masked array.\n\n        The array is returned with column-first indexing, i.e. for a data file with\n        columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n        inf and nan are filtered via :func:`numpy.isfinite`.\n        \"\"\"\n        a = self.array\n        return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))", "title": ""}
{"_id": "d19709", "text": "def isetdiff_flags(list1, list2):\n    \"\"\"\n    move to util_iter\n    \"\"\"\n    set2 = set(list2)\n    return (item not in set2 for item in list1)", "title": ""}
{"_id": "d19710", "text": "def text(value, encoding=\"utf-8\", errors=\"strict\"):\n    \"\"\"Convert a value to str on Python 3 and unicode on Python 2.\"\"\"\n    if isinstance(value, text_type):\n        return value\n    elif isinstance(value, bytes):\n        return text_type(value, encoding, errors)\n    else:\n        return text_type(value)", "title": ""}
{"_id": "d19711", "text": "def filter_dict(d, keys):\n    \"\"\"\n    Creates a new dict from an existing dict that only has the given keys\n    \"\"\"\n    return {k: v for k, v in d.items() if k in keys}", "title": ""}
{"_id": "d19712", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d19713", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d19714", "text": "def web(host, port):\n    \"\"\"Start web application\"\"\"\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)", "title": ""}
{"_id": "d19715", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d19716", "text": "def datetime_delta_to_ms(delta):\n    \"\"\"\n    Given a datetime.timedelta object, return the delta in milliseconds\n    \"\"\"\n    delta_ms = delta.days * 24 * 60 * 60 * 1000\n    delta_ms += delta.seconds * 1000\n    delta_ms += delta.microseconds / 1000\n    delta_ms = int(delta_ms)\n    return delta_ms", "title": ""}
{"_id": "d19717", "text": "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)", "title": ""}
{"_id": "d19718", "text": "def median_high(data):\n    \"\"\"Return the high median of data.\n\n    When the number of data points is odd, the middle value is returned.\n    When it is even, the larger of the two middle values is returned.\n\n    \"\"\"\n    data = sorted(data)\n    n = len(data)\n    if n == 0:\n        raise StatisticsError(\"no median for empty data\")\n    return data[n // 2]", "title": ""}
{"_id": "d19719", "text": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "title": ""}
{"_id": "d19720", "text": "def is_same_file (filename1, filename2):\n    \"\"\"Check if filename1 and filename2 point to the same file object.\n    There can be false negatives, ie. the result is False, but it is\n    the same file anyway. Reason is that network filesystems can create\n    different paths to the same physical file.\n    \"\"\"\n    if filename1 == filename2:\n        return True\n    if os.name == 'posix':\n        return os.path.samefile(filename1, filename2)\n    return is_same_filename(filename1, filename2)", "title": ""}
{"_id": "d19721", "text": "def writeCSV(data, headers, csvFile):\n  \"\"\"Write data with column headers to a CSV.\"\"\"\n  with open(csvFile, \"wb\") as f:\n    writer = csv.writer(f, delimiter=\",\")\n    writer.writerow(headers)\n    writer.writerows(data)", "title": ""}
{"_id": "d19722", "text": "def DeleteLog() -> None:\n        \"\"\"Delete log file.\"\"\"\n        if os.path.exists(Logger.FileName):\n            os.remove(Logger.FileName)", "title": ""}
{"_id": "d19723", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d19724", "text": "def join(mapping, bind, values):\n    \"\"\" Merge all the strings. Put space between them. \"\"\"\n    return [' '.join([six.text_type(v) for v in values if v is not None])]", "title": ""}
{"_id": "d19725", "text": "def clean(some_string, uppercase=False):\n    \"\"\"\n    helper to clean up an input string\n    \"\"\"\n    if uppercase:\n        return some_string.strip().upper()\n    else:\n        return some_string.strip().lower()", "title": ""}
{"_id": "d19726", "text": "def _count_leading_whitespace(text):\n  \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n  idx = 0\n  for idx, char in enumerate(text):\n    if not char.isspace():\n      return idx\n  return idx + 1", "title": ""}
{"_id": "d19727", "text": "def cos_sin_deg(deg):\n    \"\"\"Return the cosine and sin for the given angle\n    in degrees, with special-case handling of multiples\n    of 90 for perfect right angles\n    \"\"\"\n    deg = deg % 360.0\n    if deg == 90.0:\n        return 0.0, 1.0\n    elif deg == 180.0:\n        return -1.0, 0\n    elif deg == 270.0:\n        return 0, -1.0\n    rad = math.radians(deg)\n    return math.cos(rad), math.sin(rad)", "title": ""}
{"_id": "d19728", "text": "def __add__(self, other):\n        \"\"\"Handle the `+` operator.\"\"\"\n        return self._handle_type(other)(self.value + other.value)", "title": ""}
{"_id": "d19729", "text": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    \"\"\"\n    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)\n    \"\"\"\n\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\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\n    return env_dir, env_name", "title": ""}
{"_id": "d19730", "text": "def is_same_shape(self, other_im, check_channels=False):\n        \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n        Parameters\n        ----------\n        other_im : :obj:`Image`\n            image to compare\n        check_channels : bool\n            whether or not to check equality of the channels\n\n        Returns\n        -------\n        bool\n            True if the images are the same shape, False otherwise\n        \"\"\"\n        if self.height == other_im.height and self.width == other_im.width:\n            if check_channels and self.channels != other_im.channels:\n                return False\n            return True\n        return False", "title": ""}
{"_id": "d19731", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d19732", "text": "def _npiter(arr):\n    \"\"\"Wrapper for iterating numpy array\"\"\"\n    for a in np.nditer(arr, flags=[\"refs_ok\"]):\n        c = a.item()\n        if c is not None:\n            yield c", "title": ""}
{"_id": "d19733", "text": "def get_value(key, obj, default=missing):\n    \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n    if isinstance(key, int):\n        return _get_value_for_key(key, obj, default)\n    return _get_value_for_keys(key.split('.'), obj, default)", "title": ""}
{"_id": "d19734", "text": "def itervalues(d, **kw):\n    \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n    if not PY2:\n        return iter(d.values(**kw))\n    return d.itervalues(**kw)", "title": ""}
{"_id": "d19735", "text": "def load_feature(fname, language):\n    \"\"\" Load and parse a feature file. \"\"\"\n\n    fname = os.path.abspath(fname)\n    feat = parse_file(fname, language)\n    return feat", "title": ""}
{"_id": "d19736", "text": "def split(text: str) -> List[str]:\n    \"\"\"Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens\n    \"\"\"\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "title": ""}
{"_id": "d19737", "text": "def normal_noise(points):\n    \"\"\"Init a noise variable.\"\"\"\n    return np.random.rand(1) * np.random.randn(points, 1) \\\n        + random.sample([2, -2], 1)", "title": ""}
{"_id": "d19738", "text": "def connect(host, port, username, password):\n        \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n        # Instantiate ftplib client\n        session = ftplib.FTP()\n\n        # Connect to host without auth\n        session.connect(host, port)\n\n        # Authenticate connection\n        session.login(username, password)\n        return session", "title": ""}
{"_id": "d19739", "text": "def numchannels(samples:np.ndarray) -> int:\n    \"\"\"\n    return the number of channels present in samples\n\n    samples: a numpy array as returned by sndread\n\n    for multichannel audio, samples is always interleaved,\n    meaning that samples[n] returns always a frame, which\n    is either a single scalar for mono audio, or an array\n    for multichannel audio.\n    \"\"\"\n    if len(samples.shape) == 1:\n        return 1\n    else:\n        return samples.shape[1]", "title": ""}
{"_id": "d19740", "text": "def sort_key(x):\n    \"\"\"\n    >>> sort_key(('name', ('ROUTE', 'URL')))\n    -3\n    \"\"\"\n    name, (r, u) = x\n    return - len(u) + u.count('}') * 100", "title": ""}
{"_id": "d19741", "text": "def _mid(pt1, pt2):\n    \"\"\"\n    (Point, Point) -> Point\n    Return the point that lies in between the two input points.\n    \"\"\"\n    (x0, y0), (x1, y1) = pt1, pt2\n    return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "title": ""}
{"_id": "d19742", "text": "def convert_ajax_data(self, field_data):\n        \"\"\"\n        Due to the way Angular organizes it model, when this Form data is sent using Ajax,\n        then for this kind of widget, the sent data has to be converted into a format suitable\n        for Django's Form validation.\n        \"\"\"\n        data = [key for key, val in field_data.items() if val]\n        return data", "title": ""}
{"_id": "d19743", "text": "def count_string_diff(a,b):\n    \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n    shortest = min(len(a), len(b))\n    return sum(a[i] != b[i] for i in range(shortest))", "title": ""}
{"_id": "d19744", "text": "def MessageToDict(message,\n                  including_default_value_fields=False,\n                  preserving_proto_field_name=False):\n  \"\"\"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.\n  \"\"\"\n  printer = _Printer(including_default_value_fields,\n                     preserving_proto_field_name)\n  # pylint: disable=protected-access\n  return printer._MessageToJsonObject(message)", "title": ""}
{"_id": "d19745", "text": "def argsort_indices(a, axis=-1):\n    \"\"\"Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional\n    \"\"\"\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)", "title": ""}
{"_id": "d19746", "text": "def register_modele(self, modele: Modele):\n        \"\"\" Register a modele onto the lemmatizer\n\n        :param modele: Modele to register\n        \"\"\"\n        self.lemmatiseur._modeles[modele.gr()] = modele", "title": ""}
{"_id": "d19747", "text": "def shape(self) -> Tuple[int, ...]:\n        \"\"\"Shape of histogram's data.\n\n        Returns\n        -------\n        One-element tuple with the number of bins along each axis.\n        \"\"\"\n        return tuple(bins.bin_count for bins in self._binnings)", "title": ""}
{"_id": "d19748", "text": "def is_int_vector(l):\n    r\"\"\"Checks if l is a numpy array of integers\n\n    \"\"\"\n    if isinstance(l, np.ndarray):\n        if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n            return True\n    return False", "title": ""}
{"_id": "d19749", "text": "def get_key_by_value(dictionary, search_value):\n    \"\"\"\n    searchs a value in a dicionary and returns the key of the first occurrence\n\n    :param dictionary: dictionary to search in\n    :param search_value: value to search for\n    \"\"\"\n    for key, value in dictionary.iteritems():\n        if value == search_value:\n            return ugettext(key)", "title": ""}
{"_id": "d19750", "text": "def _DateToEpoch(date):\n  \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n  tz_zero = datetime.datetime.utcfromtimestamp(0)\n  diff_sec = int((date - tz_zero).total_seconds())\n  return diff_sec * 1000000", "title": ""}
{"_id": "d19751", "text": "def _GetProxies(self):\n    \"\"\"Gather a list of proxies to use.\"\"\"\n    # Detect proxies from the OS environment.\n    result = client_utils.FindProxies()\n\n    # Also try to connect directly if all proxies fail.\n    result.append(\"\")\n\n    # Also try all proxies configured in the config system.\n    result.extend(config.CONFIG[\"Client.proxy_servers\"])\n\n    return result", "title": ""}
{"_id": "d19752", "text": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        \"\"\"\n        Utility method to run commands synchronously for testing.\n        \"\"\"\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n\n        self.loop.run_until_complete(self.quit())\n\n        return result", "title": ""}
{"_id": "d19753", "text": "def check_cv(self, y):\n        \"\"\"Resolve which cross validation strategy is used.\"\"\"\n        y_arr = None\n        if self.stratified:\n            # Try to convert y to numpy for sklearn's check_cv; if conversion\n            # doesn't work, still try.\n            try:\n                y_arr = to_numpy(y)\n            except (AttributeError, TypeError):\n                y_arr = y\n\n        if self._is_float(self.cv):\n            return self._check_cv_float()\n        return self._check_cv_non_float(y_arr)", "title": ""}
{"_id": "d19754", "text": "def _remove_blank(l):\n        \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n        ret = []\n        for i, _ in enumerate(l):\n            if l[i] == 0:\n                break\n            ret.append(l[i])\n        return ret", "title": ""}
{"_id": "d19755", "text": "def split_every(iterable, n):  # TODO: Remove this, or make it return a generator.\n    \"\"\"\n    A generator of n-length chunks of an input iterable\n    \"\"\"\n    i = iter(iterable)\n    piece = list(islice(i, n))\n    while piece:\n        yield piece\n        piece = list(islice(i, n))", "title": ""}
{"_id": "d19756", "text": "def dot_v3(v, w):\n    \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n    return sum([x * y for x, y in zip(v, w)])", "title": ""}
{"_id": "d19757", "text": "def detach_all(self):\n        \"\"\"\n        Detach from all tracked classes and objects.\n        Restore the original constructors and cleanse the tracking lists.\n        \"\"\"\n        self.detach_all_classes()\n        self.objects.clear()\n        self.index.clear()\n        self._keepalive[:] = []", "title": ""}
{"_id": "d19758", "text": "def is_valid_row(cls, row):\n        \"\"\"Indicates whether or not the given row contains valid data.\"\"\"\n        for k in row.keys():\n            if row[k] is None:\n                return False\n        return True", "title": ""}
{"_id": "d19759", "text": "def border(self):\n        \"\"\"Region formed by taking border elements.\n\n        :returns: :class:`jicimagelib.region.Region`\n        \"\"\"\n\n        border_array = self.bitmap - self.inner.bitmap\n        return Region(border_array)", "title": ""}
{"_id": "d19760", "text": "def substitute(dict_, source):\n    \"\"\" Perform re.sub with the patterns in the given dict\n    Args:\n      dict_: {pattern: repl}\n      source: str\n    \"\"\"\n    d_esc = (re.escape(k) for k in dict_.keys())\n    pattern = re.compile('|'.join(d_esc))\n    return pattern.sub(lambda x: dict_[x.group()], source)", "title": ""}
{"_id": "d19761", "text": "def change_dir(directory):\n  \"\"\"\n  Wraps a function to run in a given directory.\n\n  \"\"\"\n  def cd_decorator(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n      org_path = os.getcwd()\n      os.chdir(directory)\n      func(*args, **kwargs)\n      os.chdir(org_path)\n    return wrapper\n  return cd_decorator", "title": ""}
{"_id": "d19762", "text": "def register_service(self, service):\n        \"\"\"\n            Register service into the system. Called by Services.\n        \"\"\"\n        if service not in self.services:\n            self.services.append(service)", "title": ""}
{"_id": "d19763", "text": "def to_camel(s):\n    \"\"\"\n    :param string s: under_scored string to be CamelCased\n    :return: CamelCase version of input\n    :rtype: str\n    \"\"\"\n    # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n    return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "title": ""}
{"_id": "d19764", "text": "def Slice(a, begin, size):\n    \"\"\"\n    Slicing op.\n    \"\"\"\n    return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],", "title": ""}
{"_id": "d19765", "text": "def compose(*funcs):\n    \"\"\"compose a list of functions\"\"\"\n    return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)", "title": ""}
{"_id": "d19766", "text": "def calculate_size(name, replace_existing_values):\n    \"\"\" Calculates the request payload size\"\"\"\n    data_size = 0\n    data_size += calculate_size_str(name)\n    data_size += BOOLEAN_SIZE_IN_BYTES\n    return data_size", "title": ""}
{"_id": "d19767", "text": "def reset(self):\n        \"\"\"Reset analyzer state\n        \"\"\"\n        self.prevframe = None\n        self.wasmoving = False\n        self.t0 = 0\n        self.ismoving = False", "title": ""}
{"_id": "d19768", "text": "def _not(condition=None, **kwargs):\n    \"\"\"\n    Return the opposite of input condition.\n\n    :param condition: condition to process.\n\n    :result: not condition.\n    :rtype: bool\n    \"\"\"\n\n    result = True\n\n    if condition is not None:\n        result = not run(condition, **kwargs)\n\n    return result", "title": ""}
{"_id": "d19769", "text": "def _validate_key(self, key):\n        \"\"\"Returns a boolean indicating if the attribute name is valid or not\"\"\"\n        return not any([key.startswith(i) for i in self.EXCEPTIONS])", "title": ""}
{"_id": "d19770", "text": "def get_creation_datetime(filepath):\n    \"\"\"\n    Get the date that a file was created.\n\n    Parameters\n    ----------\n    filepath : str\n\n    Returns\n    -------\n    creation_datetime : datetime.datetime or None\n    \"\"\"\n    if platform.system() == 'Windows':\n        return datetime.fromtimestamp(os.path.getctime(filepath))\n    else:\n        stat = os.stat(filepath)\n        try:\n            return datetime.fromtimestamp(stat.st_birthtime)\n        except AttributeError:\n            # We're probably on Linux. No easy way to get creation dates here,\n            # so we'll settle for when its content was last modified.\n            return None", "title": ""}
{"_id": "d19771", "text": "def vectorize(values):\n    \"\"\"\n    Takes a value or list of values and returns a single result, joined by \",\"\n    if necessary.\n    \"\"\"\n    if isinstance(values, list):\n        return ','.join(str(v) for v in values)\n    return values", "title": ""}
{"_id": "d19772", "text": "def memory_full():\n    \"\"\"Check if the memory is too full for further caching.\"\"\"\n    current_process = psutil.Process(os.getpid())\n    return (current_process.memory_percent() >\n            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "title": ""}
{"_id": "d19773", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d19774", "text": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n    \"\"\"\n    Return ``True`` if the given DataFrame has a column of the given\n    name (string), and there exists at least one non-NaN value in that\n    column; return ``False`` otherwise.\n    \"\"\"\n    if (\n        isinstance(df, pd.DataFrame)\n        and col_name in df.columns\n        and df[col_name].notnull().any()\n    ):\n        return True\n    else:\n        return False", "title": ""}
{"_id": "d19775", "text": "def from_pydatetime(cls, pydatetime):\n        \"\"\"\n        Creates sql datetime2 object from Python datetime object\n        ignoring timezone\n        @param pydatetime: Python datetime object\n        @return: sql datetime2 object\n        \"\"\"\n        return cls(date=Date.from_pydate(pydatetime.date),\n                   time=Time.from_pytime(pydatetime.time))", "title": ""}
{"_id": "d19776", "text": "def prettyprint(d):\n        \"\"\"Print dicttree in Json-like format. keys are sorted\n        \"\"\"\n        print(json.dumps(d, sort_keys=True, \n                         indent=4, separators=(\",\" , \": \")))", "title": ""}
{"_id": "d19777", "text": "def set_xlimits(self, row, column, min=None, max=None):\n        \"\"\"Set x-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_xlimits(min, max)", "title": ""}
{"_id": "d19778", "text": "def l2_norm(params):\n    \"\"\"Computes l2 norm of params by flattening them into a vector.\"\"\"\n    flattened, _ = flatten(params)\n    return np.dot(flattened, flattened)", "title": ""}
{"_id": "d19779", "text": "def info(self, text):\n\t\t\"\"\" Ajout d'un message de log de type INFO \"\"\"\n\t\tself.logger.info(\"{}{}\".format(self.message_prefix, text))", "title": ""}
{"_id": "d19780", "text": "def __remove_method(m: lmap.Map, key: T) -> lmap.Map:\n        \"\"\"Swap the methods atom to remove method with key.\"\"\"\n        return m.dissoc(key)", "title": ""}
{"_id": "d19781", "text": "def struct2dict(struct):\n    \"\"\"convert a ctypes structure to a dictionary\"\"\"\n    return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}", "title": ""}
{"_id": "d19782", "text": "def plot3d_init(fignum):\n    \"\"\"\n    initializes 3D plot\n    \"\"\"\n    from mpl_toolkits.mplot3d import Axes3D\n    fig = plt.figure(fignum)\n    ax = fig.add_subplot(111, projection='3d')\n    return ax", "title": ""}
{"_id": "d19783", "text": "def get_month_start_end_day():\n    \"\"\"\n    Get the month start date a nd end date\n    \"\"\"\n    t = date.today()\n    n = mdays[t.month]\n    return (date(t.year, t.month, 1), date(t.year, t.month, n))", "title": ""}
{"_id": "d19784", "text": "def delete_duplicates(seq):\n    \"\"\"\n    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.\n\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]", "title": ""}
{"_id": "d19785", "text": "def parse_form(self, req, name, field):\n        \"\"\"Pull a form value from the request.\"\"\"\n        return get_value(req.body_arguments, name, field)", "title": ""}
{"_id": "d19786", "text": "def _accumulate(sequence, func):\n    \"\"\"\n    Python2 accumulate implementation taken from\n    https://docs.python.org/3/library/itertools.html#itertools.accumulate\n    \"\"\"\n    iterator = iter(sequence)\n    total = next(iterator)\n    yield total\n    for element in iterator:\n        total = func(total, element)\n        yield total", "title": ""}
{"_id": "d19787", "text": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "title": ""}
{"_id": "d19788", "text": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "title": ""}
{"_id": "d19789", "text": "def getfirstline(file, default):\n    \"\"\"\n    Returns the first line of a file.\n    \"\"\"\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\n    return default", "title": ""}
{"_id": "d19790", "text": "def batch(items, size):\n    \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n    batch size.\"\"\"\n    return [items[x:x + size] for x in xrange(0, len(items), size)]", "title": ""}
{"_id": "d19791", "text": "def all_versions(req):\n    \"\"\"Get all versions of req from PyPI.\"\"\"\n    import requests\n    url = \"https://pypi.python.org/pypi/\" + req + \"/json\"\n    return tuple(requests.get(url).json()[\"releases\"].keys())", "title": ""}
{"_id": "d19792", "text": "def natural_sort(list, key=lambda s:s):\n    \"\"\"\n    Sort the list into natural alphanumeric order.\n    \"\"\"\n    def get_alphanum_key_func(key):\n        convert = lambda text: int(text) if text.isdigit() else text\n        return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))]\n    sort_key = get_alphanum_key_func(key)\n    list.sort(key=sort_key)", "title": ""}
{"_id": "d19793", "text": "def _pip_exists(self):\n        \"\"\"Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed.\"\"\"\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "title": ""}
{"_id": "d19794", "text": "def hasattrs(object, *names):\n    \"\"\"\n    Takes in an object and a variable length amount of named attributes,\n    and checks to see if the object has each property. If any of the\n    attributes are missing, this returns false.\n\n    :param object: an object that may or may not contain the listed attributes\n    :param names: a variable amount of attribute names to check for\n    :return: True if the object contains each named attribute, false otherwise\n    \"\"\"\n    for name in names:\n        if not hasattr(object, name):\n            return False\n    return True", "title": ""}
{"_id": "d19795", "text": "def list_to_str(list, separator=','):\n    \"\"\"\n    >>> list = [0, 0, 7]\n    >>> list_to_str(list)\n    '0,0,7'\n    \"\"\"\n    list = [str(x) for x in list]\n    return separator.join(list)", "title": ""}
{"_id": "d19796", "text": "def needs_check(self):\n        \"\"\"\n        Check if enough time has elapsed to perform a check().\n\n        If this time has elapsed, a state change check through\n        has_state_changed() should be performed and eventually a sync().\n\n        :rtype: boolean\n        \"\"\"\n        if self.lastcheck is None:\n            return True\n        return time.time() - self.lastcheck >= self.ipchangedetection_sleep", "title": ""}
{"_id": "d19797", "text": "def execute(self, cmd, *args, **kwargs):\n        \"\"\" Execute the SQL command and return the data rows as tuples\n        \"\"\"\n        self.cursor.execute(cmd, *args, **kwargs)", "title": ""}
{"_id": "d19798", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d19799", "text": "def parse(self, s):\n        \"\"\"\n        Parses a date string formatted like ``YYYY-MM-DD``.\n        \"\"\"\n        return datetime.datetime.strptime(s, self.date_format).date()", "title": ""}
{"_id": "d19800", "text": "def is_integer(obj):\n    \"\"\"Is this an integer.\n\n    :param object obj:\n    :return:\n    \"\"\"\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))", "title": ""}
{"_id": "d19801", "text": "def bisect_index(a, x):\n    \"\"\" Find the leftmost index of an element in a list using binary search.\n\n    Parameters\n    ----------\n    a: list\n        A sorted list.\n    x: arbitrary\n        The element.\n\n    Returns\n    -------\n    int\n        The index.\n\n    \"\"\"\n    i = bisect.bisect_left(a, x)\n    if i != len(a) and a[i] == x:\n        return i\n    raise ValueError", "title": ""}
{"_id": "d19802", "text": "def find_one(cls, *args, **kw):\n\t\t\"\"\"Get a single document from the collection this class is bound to.\n\t\t\n\t\tAdditional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional\n\t\tparameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword\n\t\targuments passed along with minor transformation.\n\t\t\n\t\tAutomatically calls `to_mongo` with the retrieved data.\n\t\t\n\t\thttps://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one\n\t\t\"\"\"\n\t\t\n\t\tif len(args) == 1 and not isinstance(args[0], Filter):\n\t\t\targs = (getattr(cls, cls.__pk__) == args[0], )\n\t\t\n\t\tDoc, collection, query, options = cls._prepare_find(*args, **kw)\n\t\tresult = Doc.from_mongo(collection.find_one(query, **options))\n\t\t\n\t\treturn result", "title": ""}
{"_id": "d19803", "text": "def parse(text, showToc=True):\n\t\"\"\"Returns HTML from MediaWiki markup\"\"\"\n\tp = Parser(show_toc=showToc)\n\treturn p.parse(text)", "title": ""}
{"_id": "d19804", "text": "def update_screen(self):\n        \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n        self.clock.tick(self.FPS)\n        pygame.display.update()", "title": ""}
{"_id": "d19805", "text": "def setDictDefaults (d, defaults):\n  \"\"\"Sets all defaults for the given dictionary to those contained in a\n  second defaults dictionary.  This convenience method calls:\n\n    d.setdefault(key, value)\n\n  for each key and value in the given defaults dictionary.\n  \"\"\"\n  for key, val in defaults.items():\n    d.setdefault(key, val)\n\n  return d", "title": ""}
{"_id": "d19806", "text": "def region_from_segment(image, segment):\n    \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n    x, y, w, h = segment\n    return image[y:y + h, x:x + w]", "title": ""}
{"_id": "d19807", "text": "def _clean_dict(target_dict, whitelist=None):\n    \"\"\" Convenience function that removes a dicts keys that have falsy values\n    \"\"\"\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    }", "title": ""}
{"_id": "d19808", "text": "def timed_rotating_file_handler(name, logname, filename, when='h',\n                                interval=1, backupCount=0,\n                                encoding=None, delay=False, utc=False):\n    \"\"\"\n    A Bark logging handler logging output to a named file.  At\n    intervals specified by the 'when', the file will be rotated, under\n    control of 'backupCount'.\n\n    Similar to logging.handlers.TimedRotatingFileHandler.\n    \"\"\"\n\n    return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n        filename, when=when, interval=interval, backupCount=backupCount,\n        encoding=encoding, delay=delay, utc=utc))", "title": ""}
{"_id": "d19809", "text": "def _get_column_types(self, data):\n        \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n        columns = list(zip_longest(*data))\n        return [self._get_column_type(column) for column in columns]", "title": ""}
{"_id": "d19810", "text": "def delete_index(self):\n        \"\"\"\n        Delete the index, if it exists.\n        \"\"\"\n        es = self._init_connection()\n        if es.indices.exists(index=self.index):\n            es.indices.delete(index=self.index)", "title": ""}
{"_id": "d19811", "text": "def _linear_seaborn_(self, label=None, style=None, opts=None):\n        \"\"\"\n        Returns a Seaborn linear regression plot\n        \"\"\"\n        xticks, yticks = self._get_ticks(opts)\n        try:\n            fig = sns.lmplot(self.x, self.y, data=self.df)\n            fig = self._set_with_height(fig, opts)\n            return fig\n        except Exception as e:\n            self.err(e, self.linear_,\n                     \"Can not draw linear regression chart\")", "title": ""}
{"_id": "d19812", "text": "def load_streams(chunks):\n    \"\"\"\n    Given a gzipped stream of data, yield streams of decompressed data.\n    \"\"\"\n    chunks = peekable(chunks)\n    while chunks:\n        if six.PY3:\n            dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)\n        else:\n            dc = zlib.decompressobj(zlib.MAX_WBITS | 16)\n        yield load_stream(dc, chunks)\n        if dc.unused_data:\n            chunks = peekable(itertools.chain((dc.unused_data,), chunks))", "title": ""}
{"_id": "d19813", "text": "def split_len(s, length):\n    \"\"\"split string *s* into list of strings no longer than *length*\"\"\"\n    return [s[i:i+length] for i in range(0, len(s), length)]", "title": ""}
{"_id": "d19814", "text": "def json(body, charset='utf-8', **kwargs):\n    \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n    return json_converter.loads(text(body, charset=charset))", "title": ""}
{"_id": "d19815", "text": "def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to be padded.\n\n        Returns:\n            PIL Image: Padded image.\n        \"\"\"\n        return F.pad(img, self.padding, self.fill, self.padding_mode)", "title": ""}
{"_id": "d19816", "text": "def remove_series(self, series):\n        \"\"\"Removes a :py:class:`.Series` from the chart.\n\n        :param Series series: The :py:class:`.Series` to remove.\n        :raises ValueError: if you try to remove the last\\\n        :py:class:`.Series`.\"\"\"\n\n        if len(self.all_series()) == 1:\n            raise ValueError(\"Cannot remove last series from %s\" % str(self))\n        self._all_series.remove(series)\n        series._chart = None", "title": ""}
{"_id": "d19817", "text": "def is_valid_ipv6(ip_str):\n    \"\"\"\n    Check the validity of an IPv6 address\n    \"\"\"\n    try:\n        socket.inet_pton(socket.AF_INET6, ip_str)\n    except socket.error:\n        return False\n    return True", "title": ""}
{"_id": "d19818", "text": "def multi_replace(instr, search_list=[], repl_list=None):\n    \"\"\"\n    Does a string replace with a list of search and replacements\n\n    TODO: rename\n    \"\"\"\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", "title": ""}
{"_id": "d19819", "text": "def format(self, record, *args, **kwargs):\n        \"\"\"\n        Format a message in the log\n\n        Act like the normal format, but indent anything that is a\n        newline within the message.\n\n        \"\"\"\n        return logging.Formatter.format(\n            self, record, *args, **kwargs).replace('\\n', '\\n' + ' ' * 8)", "title": ""}
{"_id": "d19820", "text": "def get_stripped_file_lines(filename):\n    \"\"\"\n    Return lines of a file with whitespace removed\n    \"\"\"\n    try:\n        lines = open(filename).readlines()\n    except FileNotFoundError:\n        fatal(\"Could not open file: {!r}\".format(filename))\n\n    return [line.strip() for line in lines]", "title": ""}
{"_id": "d19821", "text": "def find_geom(geom, geoms):\n    \"\"\"\n    Returns the index of a geometry in a list of geometries avoiding\n    expensive equality checks of `in` operator.\n    \"\"\"\n    for i, g in enumerate(geoms):\n        if g is geom:\n            return i", "title": ""}
{"_id": "d19822", "text": "def dedupe_list(seq):\n    \"\"\"\n    Utility function to remove duplicates from a list\n    :param seq: The sequence (list) to deduplicate\n    :return: A list with original duplicates removed\n    \"\"\"\n    seen = set()\n    return [x for x in seq if not (x in seen or seen.add(x))]", "title": ""}
{"_id": "d19823", "text": "def inverted_dict(d):\n    \"\"\"Return a dict with swapped keys and values\n\n    >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n    True\n    \"\"\"\n    return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "title": ""}
{"_id": "d19824", "text": "def disable_stdout_buffering():\n    \"\"\"This turns off stdout buffering so that outputs are immediately\n    materialized and log messages show up before the program exits\"\"\"\n    stdout_orig = sys.stdout\n    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n    # NOTE(brandyn): This removes the original stdout\n    return stdout_orig", "title": ""}
{"_id": "d19825", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d19826", "text": "def write(self, text):\n        \"\"\"Write text. An additional attribute terminator with a value of\n           None is added to the logging record to indicate that StreamHandler\n           should not add a newline.\"\"\"\n        self.logger.log(self.loglevel, text, extra={'terminator': None})", "title": ""}
{"_id": "d19827", "text": "def required_header(header):\n    \"\"\"Function that verify if the header parameter is a essential header\n\n    :param header:  A string represented a header\n    :returns:       A boolean value that represent if the header is required\n    \"\"\"\n    if header in IGNORE_HEADERS:\n        return False\n\n    if header.startswith('HTTP_') or header == 'CONTENT_TYPE':\n        return True\n\n    return False", "title": ""}
{"_id": "d19828", "text": "def compare(dicts):\n    \"\"\"Compare by iteration\"\"\"\n\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\n    return common_members", "title": ""}
{"_id": "d19829", "text": "def endless_permutations(N, random_state=None):\n    \"\"\"\n    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)\n    \"\"\"\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", "title": ""}
{"_id": "d19830", "text": "def dedupe_list(l):\n    \"\"\"Remove duplicates from a list preserving the order.\n\n    We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n    the order, which hinders testability and does not work for lists with\n    unhashable elements.\n    \"\"\"\n    result = []\n\n    for el in l:\n        if el not in result:\n            result.append(el)\n\n    return result", "title": ""}
{"_id": "d19831", "text": "def getvariable(name):\n    \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n    import inspect\n    fr = inspect.currentframe()\n    try:\n        while fr:\n            fr = fr.f_back\n            vars = fr.f_locals\n            if name in vars:\n                return vars[name]\n    except:\n        pass\n    return None", "title": ""}
{"_id": "d19832", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d19833", "text": "def set_verbosity(verbosity):\n        \"\"\"Banana banana\n        \"\"\"\n        Logger._verbosity = min(max(0, WARNING - verbosity), 2)\n        debug(\"Verbosity set to %d\" % (WARNING - Logger._verbosity), 'logging')", "title": ""}
{"_id": "d19834", "text": "def setPixel(self, x, y, color):\n        \"\"\"Set the pixel at (x,y) to the integers in sequence 'color'.\"\"\"\n        return _fitz.Pixmap_setPixel(self, x, y, color)", "title": ""}
{"_id": "d19835", "text": "def _get_compiled_ext():\n    \"\"\"Official way to get the extension of compiled files (.pyc or .pyo)\"\"\"\n    for ext, mode, typ in imp.get_suffixes():\n        if typ == imp.PY_COMPILED:\n            return ext", "title": ""}
{"_id": "d19836", "text": "def hline(self, x, y, width, color):\n        \"\"\"Draw a horizontal line up to a given length.\"\"\"\n        self.rect(x, y, width, 1, color, fill=True)", "title": ""}
{"_id": "d19837", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d19838", "text": "def detokenize(s):\n    \"\"\" Detokenize a string by removing spaces before punctuation.\"\"\"\n    print(s)\n    s = re.sub(\"\\s+([;:,\\.\\?!])\", \"\\\\1\", s)\n    s = re.sub(\"\\s+(n't)\", \"\\\\1\", s)\n    return s", "title": ""}
{"_id": "d19839", "text": "def commajoin_as_strings(iterable):\n    \"\"\" Join the given iterable with ',' \"\"\"\n    return _(u',').join((six.text_type(i) for i in iterable))", "title": ""}
{"_id": "d19840", "text": "def install_postgres(user=None, dbname=None, password=None):\n    \"\"\"Install Postgres on remote\"\"\"\n    execute(pydiploy.django.install_postgres_server,\n            user=user, dbname=dbname, password=password)", "title": ""}
{"_id": "d19841", "text": "def filter_greys_using_image(image, target):\n    \"\"\"Filter out any values in target not in image\n\n    :param image: image containing values to appear in filtered image\n    :param target: the image to filter\n    :rtype: 2d  :class:`numpy.ndarray` containing only value in image\n        and with the same dimensions as target\n\n    \"\"\"\n    maskbase = numpy.array(range(256), dtype=numpy.uint8)\n    mask = numpy.where(numpy.in1d(maskbase, numpy.unique(image)), maskbase, 0)\n    return mask[target]", "title": ""}
{"_id": "d19842", "text": "def longest_run_1d(arr):\n    \"\"\"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.\n    \"\"\"\n    v, rl = rle_1d(arr)[:2]\n    return np.where(v, rl, 0).max()", "title": ""}
{"_id": "d19843", "text": "def load_yaml(yaml_file: str) -> Any:\n    \"\"\"\n    Load YAML from file.\n\n    :param yaml_file: path to YAML file\n    :return: content of the YAML as dict/list\n    \"\"\"\n    with open(yaml_file, 'r') as file:\n        return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader)", "title": ""}
{"_id": "d19844", "text": "def get_methods(*objs):\n    \"\"\" Return the names of all callable attributes of an object\"\"\"\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    )", "title": ""}
{"_id": "d19845", "text": "def comma_converter(float_string):\n    \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n    trans_table = maketrans(b',', b'.')\n    return float(float_string.translate(trans_table))", "title": ""}
{"_id": "d19846", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d19847", "text": "def __rmatmul__(self, other):\n        \"\"\"\n        Matrix multiplication using binary `@` operator in Python>=3.5.\n        \"\"\"\n        return self.T.dot(np.transpose(other)).T", "title": ""}
{"_id": "d19848", "text": "def product(*args, **kwargs):\n    \"\"\" Yields all permutations with replacement:\n        list(product(\"cat\", repeat=2)) => \n        [(\"c\", \"c\"), \n         (\"c\", \"a\"), \n         (\"c\", \"t\"), \n         (\"a\", \"c\"), \n         (\"a\", \"a\"), \n         (\"a\", \"t\"), \n         (\"t\", \"c\"), \n         (\"t\", \"a\"), \n         (\"t\", \"t\")]\n    \"\"\"\n    p = [[]]\n    for iterable in map(tuple, args) * kwargs.get(\"repeat\", 1):\n        p = [x + [y] for x in p for y in iterable]\n    for p in p:\n        yield tuple(p)", "title": ""}
{"_id": "d19849", "text": "def validate_string(option, value):\n    \"\"\"Validates that 'value' is an instance of `basestring` for Python 2\n    or `str` for Python 3.\n    \"\"\"\n    if isinstance(value, string_type):\n        return value\n    raise TypeError(\"Wrong type for %s, value must be \"\n                    \"an instance of %s\" % (option, string_type.__name__))", "title": ""}
{"_id": "d19850", "text": "def _show(self, message, indent=0, enable_verbose=True):  # pragma: no cover\n        \"\"\"Message printer.\n        \"\"\"\n        if enable_verbose:\n            print(\"    \" * indent + message)", "title": ""}
{"_id": "d19851", "text": "def cmd_dot(conf: Config):\n    \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n    Use graphviz to render the dot file, e.g.:\n\n    > ybt dot :foo :bar | dot -Tpng -o graph.png\n    \"\"\"\n    build_context = BuildContext(conf)\n    populate_targets_graph(build_context, conf)\n    if conf.output_dot_file is None:\n        write_dot(build_context, conf, sys.stdout)\n    else:\n        with open(conf.output_dot_file, 'w') as out_file:\n            write_dot(build_context, conf, out_file)", "title": ""}
{"_id": "d19852", "text": "def BROADCAST_FILTER_NOT(func):\n        \"\"\"\n        Composes the passed filters into an and-joined filter.\n        \"\"\"\n        return lambda u, command, *args, **kwargs: not func(u, command, *args, **kwargs)", "title": ""}
{"_id": "d19853", "text": "def ensure_index(self, key, unique=False):\n        \"\"\"Wrapper for pymongo.Collection.ensure_index\n        \"\"\"\n        return self.collection.ensure_index(key, unique=unique)", "title": ""}
{"_id": "d19854", "text": "def get(url):\n    \"\"\"Recieving the JSON file from uulm\"\"\"\n    response = urllib.request.urlopen(url)\n    data = response.read()\n    data = data.decode(\"utf-8\")\n    data = json.loads(data)\n    return data", "title": ""}
{"_id": "d19855", "text": "def column_exists(cr, table, column):\n    \"\"\" Check whether a certain column exists \"\"\"\n    cr.execute(\n        'SELECT count(attname) FROM pg_attribute '\n        'WHERE attrelid = '\n        '( SELECT oid FROM pg_class WHERE relname = %s ) '\n        'AND attname = %s',\n        (table, column))\n    return cr.fetchone()[0] == 1", "title": ""}
{"_id": "d19856", "text": "def clear_matplotlib_ticks(self, axis=\"both\"):\n        \"\"\"Clears the default matplotlib ticks.\"\"\"\n        ax = self.get_axes()\n        plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "title": ""}
{"_id": "d19857", "text": "def build_parser():\n    \"\"\"Build argument parsers.\"\"\"\n\n    parser = argparse.ArgumentParser(\"Release packages to pypi\")\n    parser.add_argument('--check', '-c', action=\"store_true\", help=\"Do a dry run without uploading\")\n    parser.add_argument('component', help=\"The component to release as component-version\")\n    return parser", "title": ""}
{"_id": "d19858", "text": "def get_anchor_href(markup):\n    \"\"\"\n    Given HTML markup, return a list of hrefs for each anchor tag.\n    \"\"\"\n    soup = BeautifulSoup(markup, 'lxml')\n    return ['%s' % link.get('href') for link in soup.find_all('a')]", "title": ""}
{"_id": "d19859", "text": "def toBase64(s):\n    \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n    if isinstance(s, str):\n        s = s.encode(\"utf-8\")\n    return binascii.b2a_base64(s)[:-1]", "title": ""}
{"_id": "d19860", "text": "def command_py2to3(args):\n    \"\"\"\n    Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n    \"\"\"\n    from lib2to3.main import main\n    sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "title": ""}
{"_id": "d19861", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d19862", "text": "def get_count(self, query):\n        \"\"\"\n        Returns a number of query results. This is faster than .count() on the query\n        \"\"\"\n        count_q = query.statement.with_only_columns(\n            [func.count()]).order_by(None)\n        count = query.session.execute(count_q).scalar()\n        return count", "title": ""}
{"_id": "d19863", "text": "def safe_int(val, default=None):\n    \"\"\"\n    Returns int() of val if val is not convertable to int use default\n    instead\n\n    :param val:\n    :param default:\n    \"\"\"\n\n    try:\n        val = int(val)\n    except (ValueError, TypeError):\n        val = default\n\n    return val", "title": ""}
{"_id": "d19864", "text": "def head(filename, n=10):\n    \"\"\" prints the top `n` lines of a file \"\"\"\n    with freader(filename) as fr:\n        for _ in range(n):\n            print(fr.readline().strip())", "title": ""}
{"_id": "d19865", "text": "def erase_lines(n=1):\n    \"\"\" Erases n lines from the screen and moves the cursor up to follow\n    \"\"\"\n    for _ in range(n):\n        print(codes.cursor[\"up\"], end=\"\")\n        print(codes.cursor[\"eol\"], end=\"\")", "title": ""}
{"_id": "d19866", "text": "def conv1x1(in_planes, out_planes, stride=1):\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "title": ""}
{"_id": "d19867", "text": "def inpaint(self):\n        \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n        import inpaint\n        filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n        self.raster_data = np.ma.masked_invalid(filled)", "title": ""}
{"_id": "d19868", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d19869", "text": "def required_header(header):\n    \"\"\"Function that verify if the header parameter is a essential header\n\n    :param header:  A string represented a header\n    :returns:       A boolean value that represent if the header is required\n    \"\"\"\n    if header in IGNORE_HEADERS:\n        return False\n\n    if header.startswith('HTTP_') or header == 'CONTENT_TYPE':\n        return True\n\n    return False", "title": ""}
{"_id": "d19870", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d19871", "text": "def shot_noise(x, severity=1):\n  \"\"\"Shot noise corruption to 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]. Added shot noise.\n  \"\"\"\n  c = [60, 25, 12, 5, 3][severity - 1]\n  x = np.array(x) / 255.\n  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n  return around_and_astype(x_clip)", "title": ""}
{"_id": "d19872", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d19873", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d19874", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d19875", "text": "def dumped(text, level, indent=2):\n    \"\"\"Put curly brackets round an indented text\"\"\"\n    return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "title": ""}
{"_id": "d19876", "text": "def basic_word_sim(word1, word2):\n    \"\"\"\n    Simple measure of similarity: Number of letters in common / max length\n    \"\"\"\n    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "title": ""}
{"_id": "d19877", "text": "def json_iter (path):\n    \"\"\"\n    iterator for JSON-per-line in a file pattern\n    \"\"\"\n    with open(path, 'r') as f:\n        for line in f.readlines():\n            yield json.loads(line)", "title": ""}
{"_id": "d19878", "text": "def show_xticklabels(self, row, column):\n        \"\"\"Show the x-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_xticklabels()", "title": ""}
{"_id": "d19879", "text": "def load_image(fname):\n    \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n    with open(fname, \"rb\") as f:\n        i = Image.open(fname)\n        #i.load()\n        return i", "title": ""}
{"_id": "d19880", "text": "def set_subparsers_args(self, *args, **kwargs):\n        \"\"\"\n        Sets args and kwargs that are passed when creating a subparsers group\n        in an argparse.ArgumentParser i.e. when calling\n        argparser.ArgumentParser.add_subparsers\n        \"\"\"\n        self.subparsers_args = args\n        self.subparsers_kwargs = kwargs", "title": ""}
{"_id": "d19881", "text": "def strip_spaces(s):\n    \"\"\" Strip excess spaces from a string \"\"\"\n    return u\" \".join([c for c in s.split(u' ') if c])", "title": ""}
{"_id": "d19882", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d19883", "text": "def has_changed (filename):\n    \"\"\"Check if filename has changed since the last check. If this\n    is the first check, assume the file is changed.\"\"\"\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]", "title": ""}
{"_id": "d19884", "text": "def _short_repr(obj):\n  \"\"\"Helper function returns a truncated repr() of an object.\"\"\"\n  stringified = pprint.saferepr(obj)\n  if len(stringified) > 200:\n    return '%s... (%d bytes)' % (stringified[:200], len(stringified))\n  return stringified", "title": ""}
{"_id": "d19885", "text": "def closing_plugin(self, cancelable=False):\n        \"\"\"Perform actions before parent main window is closed\"\"\"\n        self.dialog_manager.close_all()\n        self.shell.exit_interpreter()\n        return True", "title": ""}
{"_id": "d19886", "text": "def open_json(file_name):\n    \"\"\"\n    returns json contents as string\n    \"\"\"\n    with open(file_name, \"r\") as json_data:\n        data = json.load(json_data)\n        return data", "title": ""}
{"_id": "d19887", "text": "def _get_sql(filename):\n    \"\"\"Returns the contents of the sql file from the given ``filename``.\"\"\"\n    with open(os.path.join(SQL_DIR, filename), 'r') as f:\n        return f.read()", "title": ""}
{"_id": "d19888", "text": "def directory_files(path):\n    \"\"\"Yield directory file names.\"\"\"\n\n    for entry in os.scandir(path):\n        if not entry.name.startswith('.') and entry.is_file():\n            yield entry.name", "title": ""}
{"_id": "d19889", "text": "def sort_data(data, cols):\n    \"\"\"Sort `data` rows and order columns\"\"\"\n    return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "title": ""}
{"_id": "d19890", "text": "def scale_min(im, targ, interpolation=cv2.INTER_AREA):\n    \"\"\" Scale the image so that the smallest axis is of size targ.\n\n    Arguments:\n        im (array): image\n        targ (int): target size\n    \"\"\"\n    r,c,*_ = im.shape\n    ratio = targ/min(r,c)\n    sz = (scale_to(c, ratio, targ), scale_to(r, ratio, targ))\n    return cv2.resize(im, sz, interpolation=interpolation)", "title": ""}
{"_id": "d19891", "text": "def build_output(self, fout):\n        \"\"\"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.\n        \"\"\"\n        fout.write('\\n'.join([s for s in self.out]))", "title": ""}
{"_id": "d19892", "text": "def get_file_size(filename):\n    \"\"\"\n    Get the file size of a given file\n\n    :param filename: string: pathname of a file\n    :return: human readable filesize\n    \"\"\"\n    if os.path.isfile(filename):\n        return convert_size(os.path.getsize(filename))\n    return None", "title": ""}
{"_id": "d19893", "text": "def timestamp_to_datetime(timestamp):\n    \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n    from datetime import datetime, timedelta\n    obj = datetime.fromtimestamp(timestamp[0])\n    return obj + timedelta(microseconds=int(timestamp[1]))", "title": ""}
{"_id": "d19894", "text": "def _updateItemComboBoxIndex(self, item, column, num):\n        \"\"\"Callback for comboboxes: notifies us that a combobox for the given item and column has changed\"\"\"\n        item._combobox_current_index[column] = num\n        item._combobox_current_value[column] = item._combobox_option_list[column][num][0]", "title": ""}
{"_id": "d19895", "text": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n    \"\"\"\n    Converts an ``dict`` to a ``Enum``.\n    \"\"\"\n    return enum_class[d['name']]", "title": ""}
{"_id": "d19896", "text": "def _is_override(meta, method):\n        \"\"\"Checks whether given class or instance method has been marked\n        with the ``@override`` decorator.\n        \"\"\"\n        from taipan.objective.modifiers import _OverriddenMethod\n        return isinstance(method, _OverriddenMethod)", "title": ""}
{"_id": "d19897", "text": "def _unordered_iterator(self):\n        \"\"\"\n        Return the value of each QuerySet, but also add the '#' property to each\n        return item.\n        \"\"\"\n        for i, qs in zip(self._queryset_idxs, self._querysets):\n            for item in qs:\n                setattr(item, '#', i)\n                yield item", "title": ""}
{"_id": "d19898", "text": "def cfloat64_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\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')", "title": ""}
{"_id": "d19899", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d19900", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d19901", "text": "def mouse_get_pos():\n    \"\"\"\n\n    :return:\n    \"\"\"\n    p = POINT()\n    AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))\n    return p.x, p.y", "title": ""}
{"_id": "d19902", "text": "def delete_all_eggs(self):\n        \"\"\" delete all the eggs in the directory specified \"\"\"\n        path_to_delete = os.path.join(self.egg_directory, \"lib\", \"python\")\n        if os.path.exists(path_to_delete):\n            shutil.rmtree(path_to_delete)", "title": ""}
{"_id": "d19903", "text": "def split_every(n, iterable):\n    \"\"\"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.\"\"\"\n    items = iter(iterable)\n    return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))", "title": ""}
{"_id": "d19904", "text": "def FindMethodByName(self, name):\n    \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n    for method in self.methods:\n      if name == method.name:\n        return method\n    return None", "title": ""}
{"_id": "d19905", "text": "def split_multiline(value):\n    \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n    return [element for element in (line.strip() for line in value.split('\\n'))\n            if element]", "title": ""}
{"_id": "d19906", "text": "def _get_col_index(name):\n    \"\"\"Convert column name to index.\"\"\"\n\n    index = string.ascii_uppercase.index\n    col = 0\n    for c in name.upper():\n        col = col * 26 + index(c) + 1\n    return col", "title": ""}
{"_id": "d19907", "text": "def memory_read(self, start_position: int, size: int) -> memoryview:\n        \"\"\"\n        Read and return a view of ``size`` bytes from memory starting at ``start_position``.\n        \"\"\"\n        return self._memory.read(start_position, size)", "title": ""}
{"_id": "d19908", "text": "def purge_cache(self, object_type):\n        \"\"\" Purge the named cache of all values. If no cache exists for object_type, nothing is done \"\"\"\n        if object_type in self.mapping:\n            cache = self.mapping[object_type]\n            log.debug(\"Purging [{}] cache of {} values.\".format(object_type, len(cache)))\n            cache.purge()", "title": ""}
{"_id": "d19909", "text": "def _is_leap_year(year):\n    \"\"\"Determine if a year is leap year.\n\n    Parameters\n    ----------\n    year : numeric\n\n    Returns\n    -------\n    isleap : array of bools\n    \"\"\"\n    isleap = ((np.mod(year, 4) == 0) &\n              ((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0)))\n    return isleap", "title": ""}
{"_id": "d19910", "text": "def get_login_credentials(args):\n  \"\"\"\n    Gets the login credentials from the user, if not specified while invoking\n    the script.\n    @param args: arguments provided to the script.\n    \"\"\"\n  if not args.username:\n    args.username = raw_input(\"Enter Username: \")\n  if not args.password:\n    args.password = getpass.getpass(\"Enter Password: \")", "title": ""}
{"_id": "d19911", "text": "def isin(elems, line):\n    \"\"\"Check if an element from a list is in a string.\n\n    :type elems: list\n    :type line: str\n\n    \"\"\"\n    found = False\n    for e in elems:\n        if e in line.lower():\n            found = True\n            break\n    return found", "title": ""}
{"_id": "d19912", "text": "def __rmatmul__(self, other):\n        \"\"\"\n        Matrix multiplication using binary `@` operator in Python>=3.5.\n        \"\"\"\n        return self.T.dot(np.transpose(other)).T", "title": ""}
{"_id": "d19913", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d19914", "text": "def get_adjacent_matrix(self):\n        \"\"\"Get adjacency matrix.\n\n        Returns:\n            :param adj: adjacency matrix\n            :type adj: np.ndarray\n        \"\"\"\n        edges = self.edges\n        num_edges = len(edges) + 1\n        adj = np.zeros([num_edges, num_edges])\n\n        for k in range(num_edges - 1):\n            adj[edges[k].L, edges[k].R] = 1\n            adj[edges[k].R, edges[k].L] = 1\n\n        return adj", "title": ""}
{"_id": "d19915", "text": "def _gcd_array(X):\n    \"\"\"\n    Return the largest real value h such that all elements in x are integer\n    multiples of h.\n    \"\"\"\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n    return greatest_common_divisor", "title": ""}
{"_id": "d19916", "text": "def move_up(lines=1, file=sys.stdout):\n    \"\"\" Move the cursor up a number of lines.\n\n        Esc[ValueA:\n        Moves the cursor up by the specified number of lines without changing\n        columns. If the cursor is already on the top line, ANSI.SYS ignores\n        this sequence.\n    \"\"\"\n    move.up(lines).write(file=file)", "title": ""}
{"_id": "d19917", "text": "def py(self, output):\n        \"\"\"Output data as a nicely-formatted python data structure\"\"\"\n        import pprint\n        pprint.pprint(output, stream=self.outfile)", "title": ""}
{"_id": "d19918", "text": "def to_json(value, **kwargs):\n        \"\"\"Return a copy of the tuple as a list\n\n        If the tuple contains HasProperties instances, they are serialized.\n        \"\"\"\n        serial_list = [\n            val.serialize(**kwargs) if isinstance(val, HasProperties)\n            else val for val in value\n        ]\n        return serial_list", "title": ""}
{"_id": "d19919", "text": "def get_latex_table(self, parameters=None, transpose=False, caption=None,\n                        label=\"tab:model_params\", hlines=True, blank_fill=\"--\"):  # pragma: no cover\n        \"\"\" Generates a LaTeX table from parameter summaries.\n\n        Parameters\n        ----------\n        parameters : list[str], optional\n            A list of what parameters to include in the table. By default, includes all parameters\n        transpose : bool, optional\n            Defaults to False, which gives each column as a parameter, each chain (framework)\n            as a row. You can swap it so that you have a parameter each row and a framework\n            each column by setting this to True\n        caption : str, optional\n            If you want to generate a caption for the table through Python, use this.\n            Defaults to an empty string\n        label : str, optional\n            If you want to generate a label for the table through Python, use this.\n            Defaults to an empty string\n        hlines : bool, optional\n            Inserts ``\\\\hline`` before and after the header, and at the end of table.\n        blank_fill : str, optional\n            If a framework does not have a particular parameter, will fill that cell of\n            the table with this string.\n\n        Returns\n        -------\n        str\n            the LaTeX table.\n        \"\"\"\n        if parameters is None:\n            parameters = self.parent._all_parameters\n        for p in parameters:\n            assert isinstance(p, str), \\\n                \"Generating a LaTeX table requires all parameters have labels\"\n        num_parameters = len(parameters)\n        num_chains = len(self.parent.chains)\n        fit_values = self.get_summary(squeeze=False)\n        if label is None:\n            label = \"\"\n        if caption is None:\n            caption = \"\"\n\n        end_text = \" \\\\\\\\ \\n\"\n        if transpose:\n            column_text = \"c\" * (num_chains + 1)\n        else:\n            column_text = \"c\" * (num_parameters + 1)\n\n        center_text = \"\"\n        hline_text = \"\\\\hline\\n\"\n        if hlines:\n            center_text += hline_text + \"\\t\\t\"\n        if transpose:\n            center_text += \" & \".join([\"Parameter\"] + [c.name for c in self.parent.chains]) + end_text\n            if hlines:\n                center_text += \"\\t\\t\" + hline_text\n            for p in parameters:\n                arr = [\"\\t\\t\" + p]\n                for chain_res in fit_values:\n                    if p in chain_res:\n                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n                    else:\n                        arr.append(blank_fill)\n                center_text += \" & \".join(arr) + end_text\n        else:\n            center_text += \" & \".join([\"Model\"] + parameters) + end_text\n            if hlines:\n                center_text += \"\\t\\t\" + hline_text\n            for name, chain_res in zip([c.name for c in self.parent.chains], fit_values):\n                arr = [\"\\t\\t\" + name]\n                for p in parameters:\n                    if p in chain_res:\n                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n                    else:\n                        arr.append(blank_fill)\n                center_text += \" & \".join(arr) + end_text\n        if hlines:\n            center_text += \"\\t\\t\" + hline_text\n        final_text = get_latex_table_frame(caption, label) % (column_text, center_text)\n\n        return final_text", "title": ""}
{"_id": "d19920", "text": "def _help():\n    \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n    statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n    print statement.strip()", "title": ""}
{"_id": "d19921", "text": "def heappush_max(heap, item):\n    \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n    heap.append(item)\n    _siftdown_max(heap, 0, len(heap) - 1)", "title": ""}
{"_id": "d19922", "text": "def first_unique_char(s):\n    \"\"\"\n    :type s: str\n    :rtype: int\n    \"\"\"\n    if (len(s) == 1):\n        return 0\n    ban = []\n    for i in range(len(s)):\n        if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:\n            return i\n        else:\n            ban.append(s[i])\n    return -1", "title": ""}
{"_id": "d19923", "text": "def pick_unused_port(self):\n    \"\"\" Pick an unused port. There is a slight chance that this wont work. \"\"\"\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.bind(('127.0.0.1', 0))\n    _, port = s.getsockname()\n    s.close()\n    return port", "title": ""}
{"_id": "d19924", "text": "def validate(self):\n        \"\"\"Validate the configuration file.\"\"\"\n        validator = Draft4Validator(self.SCHEMA)\n        if not validator.is_valid(self.config):\n            for err in validator.iter_errors(self.config):\n                LOGGER.error(str(err.message))\n            validator.validate(self.config)", "title": ""}
{"_id": "d19925", "text": "def count_rows(self, table, cols='*'):\n        \"\"\"Get the number of rows in a particular table.\"\"\"\n        query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table))\n        result = self.fetch(query)\n        return result if result is not None else 0", "title": ""}
{"_id": "d19926", "text": "def to_index(self, index_type, index_name, includes=None):\n        \"\"\" Create an index field from this field \"\"\"\n        return IndexField(self.name, self.data_type, index_type, index_name, includes)", "title": ""}
{"_id": "d19927", "text": "def _parse_tuple_string(argument):\n        \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n        if isinstance(argument, str):\n            return tuple(int(p.strip()) for p in argument.split(','))\n        return argument", "title": ""}
{"_id": "d19928", "text": "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig", "title": ""}
{"_id": "d19929", "text": "def url_syntax_check(url):  # pragma: no cover\n    \"\"\"\n    Check the syntax of the given URL.\n\n    :param url: The URL to check the syntax for.\n    :type url: str\n\n    :return: The syntax validity.\n    :rtype: bool\n\n    .. warning::\n        If an empty or a non-string :code:`url` is given, we return :code:`None`.\n    \"\"\"\n\n    if url and isinstance(url, str):\n        # The given URL is not empty nor None.\n        # and\n        # * The given URL is a string.\n\n        # We silently load the configuration.\n        load_config(True)\n\n        return Check(url).is_url_valid()\n\n    # We return None, there is nothing to check.\n    return None", "title": ""}
{"_id": "d19930", "text": "def _check_for_int(x):\n    \"\"\"\n    This is a compatibility function that takes a C{float} and converts it to an\n    C{int} if the values are equal.\n    \"\"\"\n    try:\n        y = int(x)\n    except (OverflowError, ValueError):\n        pass\n    else:\n        # There is no way in AMF0 to distinguish between integers and floats\n        if x == x and y == x:\n            return y\n\n    return x", "title": ""}
{"_id": "d19931", "text": "def set_trace():\n    \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n    # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n    pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "title": ""}
{"_id": "d19932", "text": "def _power(ctx, number, power):\n    \"\"\"\n    Returns the result of a number raised to a power\n    \"\"\"\n    return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx))", "title": ""}
{"_id": "d19933", "text": "def _change_height(self, ax, new_value):\n        \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n        for patch in ax.patches:\n            current_height = patch.get_height()\n            diff = current_height - new_value\n\n            # we change the bar height\n            patch.set_height(new_value)\n\n            # we recenter the bar\n            patch.set_y(patch.get_y() + diff * .5)", "title": ""}
{"_id": "d19934", "text": "def add_to_js(self, name, var):\n        \"\"\"Add an object to Javascript.\"\"\"\n        frame = self.page().mainFrame()\n        frame.addToJavaScriptWindowObject(name, var)", "title": ""}
{"_id": "d19935", "text": "def dot_v2(vec1, vec2):\n    \"\"\"Return the dot product of two vectors\"\"\"\n\n    return vec1.x * vec2.x + vec1.y * vec2.y", "title": ""}
{"_id": "d19936", "text": "def parsed_args():\n    parser = argparse.ArgumentParser(description=\"\"\"python runtime functions\"\"\", epilog=\"\")\n    parser.add_argument('command',nargs='*',\n        help=\"Name of the function to run with arguments\")\n    args = parser.parse_args()\n    return (args, parser)", "title": ""}
{"_id": "d19937", "text": "def vline(self, x, y, height, color):\n        \"\"\"Draw a vertical line up to a given length.\"\"\"\n        self.rect(x, y, 1, height, color, fill=True)", "title": ""}
{"_id": "d19938", "text": "def load_yaml(filepath):\n    \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n    with open(filepath) as f:\n        txt = f.read()\n    return yaml.load(txt)", "title": ""}
{"_id": "d19939", "text": "def is_symlink(self):\n        \"\"\"\n        Whether this path is a symbolic link.\n        \"\"\"\n        try:\n            return S_ISLNK(self.lstat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            # Path doesn't exist\n            return False", "title": ""}
{"_id": "d19940", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d19941", "text": "def drop_column(self, tablename: str, fieldname: str) -> int:\n        \"\"\"Drops (deletes) a column from an existing table.\"\"\"\n        sql = \"ALTER TABLE {} DROP COLUMN {}\".format(tablename, fieldname)\n        log.info(sql)\n        return self.db_exec_literal(sql)", "title": ""}
{"_id": "d19942", "text": "def center_eigenvalue_diff(mat):\n    \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n    N = len(mat)\n    evals = np.sort(la.eigvals(mat))\n    diff = np.abs(evals[N/2] - evals[N/2-1])\n    return diff", "title": ""}
{"_id": "d19943", "text": "def list_adb_devices_by_usb_id():\n    \"\"\"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.\n    \"\"\"\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", "title": ""}
{"_id": "d19944", "text": "def to_capitalized_camel_case(snake_case_string):\n    \"\"\"\n    Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n    would become \"SomeVar\".\n\n    :param snake_case_string: Snake-cased string to convert to camel case.\n    :returns: Camel-cased version of snake_case_string.\n    \"\"\"\n    parts = snake_case_string.split('_')\n    return ''.join([i.title() for i in parts])", "title": ""}
{"_id": "d19945", "text": "def get_number(s, cast=int):\n    \"\"\"\n    Try to get a number out of a string, and cast it.\n    \"\"\"\n    import string\n    d = \"\".join(x for x in str(s) if x in string.digits)\n    return cast(d)", "title": ""}
{"_id": "d19946", "text": "def _import(module, cls):\n    \"\"\"\n    A messy way to import library-specific classes.\n    TODO: I should really make a factory class or something, but I'm lazy.\n    Plus, factories remind me a lot of java...\n    \"\"\"\n    global Scanner\n\n    try:\n        cls = str(cls)\n        mod = __import__(str(module), globals(), locals(), [cls], 1)\n        Scanner = getattr(mod, cls)\n    except ImportError:\n        pass", "title": ""}
{"_id": "d19947", "text": "def recClearTag(element):\n    \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n    recursively to all child elements.\n\n    :param element: an :instance:`xml.etree.Element`\n    \"\"\"\n    children = element.getchildren()\n    if len(children) > 0:\n        for child in children:\n            recClearTag(child)\n    element.tag = clearTag(element.tag)", "title": ""}
{"_id": "d19948", "text": "def save_session(self, sid, session, namespace=None):\n        \"\"\"Store the user session for a client.\n\n        The only difference with the :func:`socketio.Server.save_session`\n        method is that when the ``namespace`` argument is not given the\n        namespace associated with the class is used.\n        \"\"\"\n        return self.server.save_session(\n            sid, session, namespace=namespace or self.namespace)", "title": ""}
{"_id": "d19949", "text": "def library(func):\n    \"\"\"\n    A decorator for providing a unittest with a library and have it called only\n    once.\n    \"\"\"\n    @wraps(func)\n    def wrapped(*args, **kwargs):\n        \"\"\"Transparent wrapper.\"\"\"\n        return func(*args, **kwargs)\n    SINGLES.append(wrapped)\n    return wrapped", "title": ""}
{"_id": "d19950", "text": "def delimited(items, character='|'):\n    \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n    return '|'.join(items) if type(items) in (list, tuple, set) else items", "title": ""}
{"_id": "d19951", "text": "def vars_(self):\n        \"\"\" Returns symbol instances corresponding to variables\n        of the current scope.\n        \"\"\"\n        return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]", "title": ""}
{"_id": "d19952", "text": "def stop(self):\n        \"\"\"Stop stream.\"\"\"\n        if self.stream and self.stream.session.state != STATE_STOPPED:\n            self.stream.stop()", "title": ""}
{"_id": "d19953", "text": "def send_file(self, local_path, remote_path, user='root', unix_mode=None):\n        \"\"\"Upload a local file on the remote host.\n        \"\"\"\n        self.enable_user(user)\n        return self.ssh_pool.send_file(user, local_path, remote_path, unix_mode=unix_mode)", "title": ""}
{"_id": "d19954", "text": "def reduce_fn(x):\n    \"\"\"\n    Aggregation function to get the first non-zero value.\n    \"\"\"\n    values = x.values if pd and isinstance(x, pd.Series) else x\n    for v in values:\n        if not is_nan(v):\n            return v\n    return np.NaN", "title": ""}
{"_id": "d19955", "text": "def _get_var_from_string(item):\n    \"\"\" Get resource variable. \"\"\"\n    modname, varname = _split_mod_var_names(item)\n    if modname:\n        mod = __import__(modname, globals(), locals(), [varname], -1)\n        return getattr(mod, varname)\n    else:\n        return globals()[varname]", "title": ""}
{"_id": "d19956", "text": "def setwinsize(self, rows, cols):\n        \"\"\"Set the terminal window size of the child tty.\n        \"\"\"\n        self._winsize = (rows, cols)\n        self.pty.set_size(cols, rows)", "title": ""}
{"_id": "d19957", "text": "def dict_to_numpy_array(d):\n    \"\"\"\n    Convert a dict of 1d array to a numpy recarray\n    \"\"\"\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "title": ""}
{"_id": "d19958", "text": "def default_diff(latest_config, current_config):\n    \"\"\"Determine if two revisions have actually changed.\"\"\"\n    # Pop off the fields we don't care about:\n    pop_no_diff_fields(latest_config, current_config)\n\n    diff = DeepDiff(\n        latest_config,\n        current_config,\n        ignore_order=True\n    )\n    return diff", "title": ""}
{"_id": "d19959", "text": "def get_width():\n    \"\"\"Get terminal width\"\"\"\n    # Get terminal size\n    ws = struct.pack(\"HHHH\", 0, 0, 0, 0)\n    ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)\n    lines, columns, x, y = struct.unpack(\"HHHH\", ws)\n    width = min(columns * 39 // 40, columns - 2)\n    return width", "title": ""}
{"_id": "d19960", "text": "def top(self, topn=10):\n        \"\"\"\n        Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n        >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n        >>> myFeature.top(1)\n        [('trapezoid', 5)]\n\n        Parameters\n        ----------\n        topn : int\n\n        Returns\n        -------\n        list\n        \"\"\"\n        return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "title": ""}
{"_id": "d19961", "text": "def get_file_md5sum(path):\n    \"\"\"Calculate the MD5 hash for a file.\"\"\"\n    with open(path, 'rb') as fh:\n        h = str(hashlib.md5(fh.read()).hexdigest())\n    return h", "title": ""}
{"_id": "d19962", "text": "def mkdir(dir, enter):\n    \"\"\"Create directory with template for topic of the current environment\n\n    \"\"\"\n\n    if not os.path.exists(dir):\n        os.makedirs(dir)", "title": ""}
{"_id": "d19963", "text": "def check_lengths(*arrays):\n    \"\"\"\n    tool to ensure input and output data have the same number of samples\n\n    Parameters\n    ----------\n    *arrays : iterable of arrays to be checked\n\n    Returns\n    -------\n    None\n    \"\"\"\n    lengths = [len(array) for array in arrays]\n    if len(np.unique(lengths)) > 1:\n        raise ValueError('Inconsistent data lengths: {}'.format(lengths))", "title": ""}
{"_id": "d19964", "text": "def generate_chunks(string, num_chars):\n    \"\"\"Yield num_chars-character chunks from string.\"\"\"\n    for start in range(0, len(string), num_chars):\n        yield string[start:start+num_chars]", "title": ""}
{"_id": "d19965", "text": "def _validate_pos(df):\n    \"\"\"Validates the returned positional object\n    \"\"\"\n    assert isinstance(df, pd.DataFrame)\n    assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n    assert df.position.dtype == np.dtype(\"int64\")\n    assert df.strand.dtype == np.dtype(\"O\")\n    assert df.seqname.dtype == np.dtype(\"O\")\n    return df", "title": ""}
{"_id": "d19966", "text": "def findfirst(f, coll):\n    \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n    result = list(dropwhile(f, coll))\n    return result[0] if result else None", "title": ""}
{"_id": "d19967", "text": "def get_numbers(s):\n    \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n    result = map(int, re.findall(r'[0-9]+', unicode(s)))\n    return result + [1] * (2 - len(result))", "title": ""}
{"_id": "d19968", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d19969", "text": "def start(self, test_connection=True):\n        \"\"\"Starts connection to server if not existent.\n\n        NO-OP if connection is already established.\n        Makes ping-pong test as well if desired.\n\n        \"\"\"\n        if self._context is None:\n            self._logger.debug('Starting Client')\n            self._context = zmq.Context()\n            self._poll = zmq.Poller()\n            self._start_socket()\n            if test_connection:\n                self.test_ping()", "title": ""}
{"_id": "d19970", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d19971", "text": "def flatten_list(l: List[list]) -> list:\n    \"\"\" takes a list of lists, l and returns a flat list\n    \"\"\"\n    return [v for inner_l in l for v in inner_l]", "title": ""}
{"_id": "d19972", "text": "def get_labels(labels):\n    \"\"\"Create unique labels.\"\"\"\n    label_u = unique_labels(labels)\n    label_u_line = [i + \"_line\" for i in label_u]\n    return label_u, label_u_line", "title": ""}
{"_id": "d19973", "text": "def set_mlimits(self, row, column, min=None, max=None):\n        \"\"\"Set limits for the point meta (colormap).\n\n        Point meta values outside this range will be clipped.\n\n        :param min: value for start of the colormap.\n        :param max: value for end of the colormap.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_mlimits(min, max)", "title": ""}
{"_id": "d19974", "text": "def iprotate(l, steps=1):\n    r\"\"\"Like rotate, but modifies `l` in-place.\n\n    >>> l = [1,2,3]\n    >>> iprotate(l) is l\n    True\n    >>> l\n    [2, 3, 1]\n    >>> iprotate(iprotate(l, 2), -3)\n    [1, 2, 3]\n\n    \"\"\"\n    if len(l):\n        steps %= len(l)\n        if steps:\n            firstPart = l[:steps]\n            del l[:steps]\n            l.extend(firstPart)\n    return l", "title": ""}
{"_id": "d19975", "text": "def _remove_from_index(index, obj):\n    \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n    try:\n        index.value_map[indexed_value(index, obj)].remove(obj.id)\n    except KeyError:\n        pass", "title": ""}
{"_id": "d19976", "text": "def wordify(text):\n    \"\"\"Generate a list of words given text, removing punctuation.\n\n    Parameters\n    ----------\n    text : unicode\n        A piece of english text.\n\n    Returns\n    -------\n    words : list\n        List of words.\n    \"\"\"\n    stopset = set(nltk.corpus.stopwords.words('english'))\n    tokens = nltk.WordPunctTokenizer().tokenize(text)\n    return [w for w in tokens if w not in stopset]", "title": ""}
{"_id": "d19977", "text": "def strip_columns(tab):\n    \"\"\"Strip whitespace from string columns.\"\"\"\n    for colname in tab.colnames:\n        if tab[colname].dtype.kind in ['S', 'U']:\n            tab[colname] = np.core.defchararray.strip(tab[colname])", "title": ""}
{"_id": "d19978", "text": "def get_last_day_of_month(t: datetime) -> int:\n    \"\"\"\n    Returns day number of the last day of the month\n    :param t: datetime\n    :return: int\n    \"\"\"\n    tn = t + timedelta(days=32)\n    tn = datetime(year=tn.year, month=tn.month, day=1)\n    tt = tn - timedelta(hours=1)\n    return tt.day", "title": ""}
{"_id": "d19979", "text": "def assert_is_not(expected, actual, message=None, extra=None):\n    \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )", "title": ""}
{"_id": "d19980", "text": "def angle_between_vectors(x, y):\n    \"\"\" Compute the angle between vector x and y \"\"\"\n    dp = dot_product(x, y)\n    if dp == 0:\n        return 0\n    xm = magnitude(x)\n    ym = magnitude(y)\n    return math.acos(dp / (xm*ym)) * (180. / math.pi)", "title": ""}
{"_id": "d19981", "text": "def ibatch(iterable, size):\n    \"\"\"Yield a series of batches from iterable, each size elements long.\"\"\"\n    source = iter(iterable)\n    while True:\n        batch = itertools.islice(source, size)\n        yield itertools.chain([next(batch)], batch)", "title": ""}
{"_id": "d19982", "text": "def disassemble_file(filename, outstream=None):\n    \"\"\"\n    disassemble Python byte-code file (.pyc)\n\n    If given a Python source file (\".py\") file, we'll\n    try to find the corresponding compiled object.\n    \"\"\"\n    filename = check_object_path(filename)\n    (version, timestamp, magic_int, co, is_pypy,\n     source_size) = load_module(filename)\n    if type(co) == list:\n        for con in co:\n            disco(version, con, outstream)\n    else:\n        disco(version, co, outstream, is_pypy=is_pypy)\n    co = None", "title": ""}
{"_id": "d19983", "text": "def _finish(self):\n        \"\"\"\n        Closes and waits for subprocess to exit.\n        \"\"\"\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", "title": ""}
{"_id": "d19984", "text": "def _delete_keys(dct, keys):\n    \"\"\"Returns a copy of dct without `keys` keys\n    \"\"\"\n    c = deepcopy(dct)\n    assert isinstance(keys, list)\n    for k in keys:\n        c.pop(k)\n    return c", "title": ""}
{"_id": "d19985", "text": "def process_instance(self, instance):\n        self.log.debug(\"e = mc^2\")\n        self.log.info(\"About to fail..\")\n        self.log.warning(\"Failing.. soooon..\")\n        self.log.critical(\"Ok, you're done.\")\n        assert False, \"\"\"ValidateFailureMock was destined to fail..\n\nHere's some extended information about what went wrong.\n\nIt has quite the long string associated with it, including\na few newlines and a list.\n\n- Item 1\n- Item 2\n\n\"\"\"", "title": ""}
{"_id": "d19986", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d19987", "text": "def _sub_patterns(patterns, text):\n    \"\"\"\n    Apply re.sub to bunch of (pattern, repl)\n    \"\"\"\n    for pattern, repl in patterns:\n        text = re.sub(pattern, repl, text)\n    return text", "title": ""}
{"_id": "d19988", "text": "def validate_multiindex(self, obj):\n        \"\"\"validate that we can store the multi-index; reset and return the\n        new object\n        \"\"\"\n        levels = [l if l is not None else \"level_{0}\".format(i)\n                  for i, l in enumerate(obj.index.names)]\n        try:\n            return obj.reset_index(), levels\n        except ValueError:\n            raise ValueError(\"duplicate names/columns in the multi-index when \"\n                             \"storing as a table\")", "title": ""}
{"_id": "d19989", "text": "def __or__(self, other):\n        \"\"\"Return the union of two RangeSets as a new RangeSet.\n\n        (I.e. all elements that are in either set.)\n        \"\"\"\n        if not isinstance(other, set):\n            return NotImplemented\n        return self.union(other)", "title": ""}
{"_id": "d19990", "text": "def _decode(self, obj, context):\n        \"\"\"\n        Get the python representation of the obj\n        \"\"\"\n        return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode(\"utf8\")", "title": ""}
{"_id": "d19991", "text": "def roundClosestValid(val, res, decimals=None):\n        \"\"\" round to closest resolution \"\"\"\n        if decimals is None and \".\" in str(res):\n            decimals = len(str(res).split('.')[1])\n\n        return round(round(val / res) * res, decimals)", "title": ""}
{"_id": "d19992", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d19993", "text": "def generate_id(self, obj):\n        \"\"\"Generate unique document id for ElasticSearch.\"\"\"\n        object_type = type(obj).__name__.lower()\n        return '{}_{}'.format(object_type, self.get_object_id(obj))", "title": ""}
{"_id": "d19994", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d19995", "text": "def _writable_dir(path):\n    \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n    return os.path.isdir(path) and os.access(path, os.W_OK)", "title": ""}
{"_id": "d19996", "text": "def _to_corrected_pandas_type(dt):\n    \"\"\"\n    When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n    This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n    \"\"\"\n    import numpy as np\n    if type(dt) == ByteType:\n        return np.int8\n    elif type(dt) == ShortType:\n        return np.int16\n    elif type(dt) == IntegerType:\n        return np.int32\n    elif type(dt) == FloatType:\n        return np.float32\n    else:\n        return None", "title": ""}
{"_id": "d19997", "text": "def save(self, fname):\n        \"\"\" Saves the dictionary in json format\n        :param fname: file to save to\n        \"\"\"\n        with open(fname, 'wb') as f:\n            json.dump(self, f)", "title": ""}
{"_id": "d19998", "text": "def setRect(self, rect):\n\t\t\"\"\"\n\t\tSets the window bounds from a tuple of (x,y,w,h)\n\t\t\"\"\"\n\t\tself.x, self.y, self.w, self.h = rect", "title": ""}
{"_id": "d19999", "text": "def adapter(data, headers, **kwargs):\n    \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n    keys = ('sep_title', 'sep_character', 'sep_length')\n    return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "title": ""}
{"_id": "d20000", "text": "def select_from_array(cls, array, identifier):\n        \"\"\"Return a region from a numpy array.\n        \n        :param array: :class:`numpy.ndarray`\n        :param identifier: value representing the region to select in the array\n        :returns: :class:`jicimagelib.region.Region`\n        \"\"\"\n\n        base_array = np.zeros(array.shape)\n        array_coords = np.where(array == identifier)\n        base_array[array_coords] = 1\n\n        return cls(base_array)", "title": ""}
{"_id": "d20001", "text": "def less_strict_bool(x):\n    \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n    if x is None:\n        return False\n    elif x is True or x is False:\n        return x\n    else:\n        return strict_bool(x)", "title": ""}
{"_id": "d20002", "text": "def is_writable_by_others(filename):\n    \"\"\"Check if file or directory is world writable.\"\"\"\n    mode = os.stat(filename)[stat.ST_MODE]\n    return mode & stat.S_IWOTH", "title": ""}
{"_id": "d20003", "text": "def show(self):\n        \"\"\" Ensure the widget is shown.\n        Calling this method will also set the widget visibility to True.\n        \"\"\"\n        self.visible = True\n        if self.proxy_is_active:\n            self.proxy.ensure_visible()", "title": ""}
{"_id": "d20004", "text": "def click_estimate_slope():\n    \"\"\"\n    Takes two clicks and returns the slope.\n\n    Right-click aborts.\n    \"\"\"\n\n    c1 = _pylab.ginput()\n    if len(c1)==0:\n        return None\n\n    c2 = _pylab.ginput()\n    if len(c2)==0:\n        return None\n\n    return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])", "title": ""}
{"_id": "d20005", "text": "def checkbox_uncheck(self, force_check=False):\n        \"\"\"\n        Wrapper to uncheck a checkbox\n        \"\"\"\n        if self.get_attribute('checked'):\n            self.click(force_click=force_check)", "title": ""}
{"_id": "d20006", "text": "def deserialize_ndarray_npy(d):\n    \"\"\"\n    Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's\n    :obj:`save` function.\n\n    Args:\n        d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created\n            using :obj:`numpy.save`.\n\n    Returns:\n        An :obj:`ndarray` object.\n    \"\"\"\n    with io.BytesIO() as f:\n        f.write(json.loads(d['npy']).encode('latin-1'))\n        f.seek(0)\n        return np.load(f)", "title": ""}
{"_id": "d20007", "text": "def clean(some_string, uppercase=False):\n    \"\"\"\n    helper to clean up an input string\n    \"\"\"\n    if uppercase:\n        return some_string.strip().upper()\n    else:\n        return some_string.strip().lower()", "title": ""}
{"_id": "d20008", "text": "def tag_to_dict(html):\n    \"\"\"Extract tag's attributes into a `dict`.\"\"\"\n\n    element = document_fromstring(html).xpath(\"//html/body/child::*\")[0]\n    attributes = dict(element.attrib)\n    attributes[\"text\"] = element.text_content()\n    return attributes", "title": ""}
{"_id": "d20009", "text": "def slugify(s, delimiter='-'):\n    \"\"\"\n    Normalize `s` into ASCII and replace non-word characters with `delimiter`.\n    \"\"\"\n    s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')\n    return RE_SLUG.sub(delimiter, s).strip(delimiter).lower()", "title": ""}
{"_id": "d20010", "text": "def OnUpdateFigurePanel(self, event):\n        \"\"\"Redraw event handler for the figure panel\"\"\"\n\n        if self.updating:\n            return\n\n        self.updating = True\n        self.figure_panel.update(self.get_figure(self.code))\n        self.updating = False", "title": ""}
{"_id": "d20011", "text": "def _hash_the_file(hasher, filename):\n    \"\"\"Helper function for creating hash functions.\n\n    See implementation of :func:`dtoolcore.filehasher.shasum`\n    for more usage details.\n    \"\"\"\n    BUF_SIZE = 65536\n    with open(filename, 'rb') as f:\n        buf = f.read(BUF_SIZE)\n        while len(buf) > 0:\n            hasher.update(buf)\n            buf = f.read(BUF_SIZE)\n    return hasher", "title": ""}
{"_id": "d20012", "text": "def get_power(self):\n        \"\"\"Check if the device is on.\"\"\"\n        power = (yield from self.handle_int(self.API.get('power')))\n        return bool(power)", "title": ""}
{"_id": "d20013", "text": "def get_hash(self, handle):\n        \"\"\"Return the hash.\"\"\"\n        fpath = self._fpath_from_handle(handle)\n        return DiskStorageBroker.hasher(fpath)", "title": ""}
{"_id": "d20014", "text": "def cpu_count() -> int:\n    \"\"\"Returns the number of processors on this machine.\"\"\"\n    if multiprocessing is None:\n        return 1\n    try:\n        return multiprocessing.cpu_count()\n    except NotImplementedError:\n        pass\n    try:\n        return os.sysconf(\"SC_NPROCESSORS_CONF\")\n    except (AttributeError, ValueError):\n        pass\n    gen_log.error(\"Could not detect number of processors; assuming 1\")\n    return 1", "title": ""}
{"_id": "d20015", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d20016", "text": "def getAllTriples(self):\n        \"\"\"Returns:\n\n        list of tuples : Each tuple holds a subject, predicate, object triple\n\n        \"\"\"\n        return [(str(s), str(p), str(o)) for s, p, o in self]", "title": ""}
{"_id": "d20017", "text": "def iter_finds(regex_obj, s):\n    \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\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()", "title": ""}
{"_id": "d20018", "text": "def strip_comments(string, comment_symbols=frozenset(('#', '//'))):\n    \"\"\"Strip comments from json string.\n\n    :param string: A string containing json with comments started by comment_symbols.\n    :param comment_symbols: Iterable of symbols that start a line comment (default # or //).\n    :return: The string with the comments removed.\n    \"\"\"\n    lines = string.splitlines()\n    for k in range(len(lines)):\n        for symbol in comment_symbols:\n            lines[k] = strip_comment_line_with_symbol(lines[k], start=symbol)\n    return '\\n'.join(lines)", "title": ""}
{"_id": "d20019", "text": "def is_line_in_file(filename: str, line: str) -> bool:\n    \"\"\"\n    Detects whether a line is present within a file.\n\n    Args:\n        filename: file to check\n        line: line to search for (as an exact match)\n    \"\"\"\n    assert \"\\n\" not in line\n    with open(filename, \"r\") as file:\n        for fileline in file:\n            if fileline == line:\n                return True\n        return False", "title": ""}
{"_id": "d20020", "text": "async def async_run(self) -> None:\n        \"\"\"\n        Asynchronously run the worker, does not close connections. Useful when testing.\n        \"\"\"\n        self.main_task = self.loop.create_task(self.main())\n        await self.main_task", "title": ""}
{"_id": "d20021", "text": "def _not_none(items):\n    \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n    if not isinstance(items, (tuple, list)):\n        items = (items,)\n    return all(item is not _none for item in items)", "title": ""}
{"_id": "d20022", "text": "def has_attribute(module_name, attribute_name):\n    \"\"\"Is this attribute present?\"\"\"\n    init_file = '%s/__init__.py' % module_name\n    return any(\n        [attribute_name in init_line for init_line in open(init_file).readlines()]\n    )", "title": ""}
{"_id": "d20023", "text": "def drop_bad_characters(text):\n    \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n    also any whitespace characters that aren't space.\n\n    :arg str text: the text to fix\n\n    :returns: text with all bad characters dropped\n\n    \"\"\"\n    # Strip all non-ascii and non-printable characters\n    text = ''.join([c for c in text if c in ALLOWED_CHARS])\n    return text", "title": ""}
{"_id": "d20024", "text": "def imapchain(*a, **kwa):\n    \"\"\" Like map but also chains the results. \"\"\"\n\n    imap_results = map( *a, **kwa )\n    return itertools.chain( *imap_results )", "title": ""}
{"_id": "d20025", "text": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n    \"\"\"Clean a pandas dataframe by:\n        1. Filling empty values with Nan\n        2. Dropping columns with all empty values\n\n    Args:\n        df: Pandas DataFrame\n        fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n        drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n    Returns:\n        DataFrame: cleaned DataFrame\n\n    \"\"\"\n    if fill_nan:\n        df = df.fillna(value=np.nan)\n    if drop_empty_columns:\n        df = df.dropna(axis=1, how='all')\n    return df.sort_index()", "title": ""}
{"_id": "d20026", "text": "def eof(fd):\n    \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n    b = fd.read(1)\n    end = len(b) == 0\n    if not end:\n        curpos = fd.tell()\n        fd.seek(curpos - 1)\n    return end", "title": ""}
{"_id": "d20027", "text": "def table_width(self):\n        \"\"\"Return the width of the table including padding and borders.\"\"\"\n        outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]\n        outer_border = 2 if self.outer_border else 0\n        inner_border = 1 if self.inner_column_border else 0\n        return table_width(outer_widths, outer_border, inner_border)", "title": ""}
{"_id": "d20028", "text": "def json(body, charset='utf-8', **kwargs):\n    \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n    return json_converter.loads(text(body, charset=charset))", "title": ""}
{"_id": "d20029", "text": "def llen(self, name):\n        \"\"\"\n        Returns the length of the list.\n\n        :param name: str     the name of the redis key\n        :return: Future()\n        \"\"\"\n        with self.pipe as pipe:\n            return pipe.llen(self.redis_key(name))", "title": ""}
{"_id": "d20030", "text": "def _prepare_proxy(self, conn):\n        \"\"\"\n        Establish tunnel connection early, because otherwise httplib\n        would improperly set Host: header to proxy's IP:port.\n        \"\"\"\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n        conn.connect()", "title": ""}
{"_id": "d20031", "text": "def is_value_type_valid_for_exact_conditions(self, value):\n    \"\"\" Method to validate if the value is valid for exact match type evaluation.\n\n    Args:\n      value: Value to validate.\n\n    Returns:\n      Boolean: True if value is a string, boolean, or number. Otherwise False.\n    \"\"\"\n    # No need to check for bool since bool is a subclass of int\n    if isinstance(value, string_types) or isinstance(value, (numbers.Integral, float)):\n      return True\n\n    return False", "title": ""}
{"_id": "d20032", "text": "def filter_none(list_of_points):\n    \"\"\"\n    \n    :param list_of_points: \n    :return: list_of_points with None's removed\n    \"\"\"\n    remove_elementnone = filter(lambda p: p is not None, list_of_points)\n    remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n    return list(remove_sublistnone)", "title": ""}
{"_id": "d20033", "text": "def caller_locals():\n    \"\"\"Get the local variables in the caller's frame.\"\"\"\n    import inspect\n    frame = inspect.currentframe()\n    try:\n        return frame.f_back.f_back.f_locals\n    finally:\n        del frame", "title": ""}
{"_id": "d20034", "text": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n    \"\"\"\n    http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n    \"\"\"\n    fft = np.fft.fft(data)\n    # n = len(data)\n    # timestep = 1.0 / fs\n    # freq = np.fft.fftfreq(n, d=timestep)\n    bp = fft.copy()\n\n    # Zero out fft coefficients\n    # bp[10:-10] = 0\n\n    # Normalise\n    # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n    bp *= fft.dot(fft) / bp.dot(bp)\n\n    # must multipy by 2 to get the correct amplitude\n    ibp = 12 * np.fft.ifft(bp)\n    return ibp", "title": ""}
{"_id": "d20035", "text": "def _reshuffle(mat, shape):\n    \"\"\"Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].\"\"\"\n    return np.reshape(\n        np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),\n        (shape[3] * shape[1], shape[0] * shape[2]))", "title": ""}
{"_id": "d20036", "text": "def distinct(l):\n    \"\"\"\n    Return a list where the duplicates have been removed.\n\n    Args:\n        l (list): the list to filter.\n\n    Returns:\n        list: the same list without duplicates.\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    return (_ for _ in l if not (_ in seen or seen_add(_)))", "title": ""}
{"_id": "d20037", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d20038", "text": "def datetime_local_to_utc(local):\n    \"\"\"\n    Simple function to convert naive :std:`datetime.datetime` object containing\n    local time to a naive :std:`datetime.datetime` object with UTC time.\n    \"\"\"\n    timestamp = time.mktime(local.timetuple())\n    return datetime.datetime.utcfromtimestamp(timestamp)", "title": ""}
{"_id": "d20039", "text": "def file_empty(fp):\n    \"\"\"Determine if a file is empty or not.\"\"\"\n    # for python 2 we need to use a homemade peek()\n    if six.PY2:\n        contents = fp.read()\n        fp.seek(0)\n        return not bool(contents)\n\n    else:\n        return not fp.peek()", "title": ""}
{"_id": "d20040", "text": "def get_tri_area(pts):\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d20041", "text": "def copy(obj):\n    def copy(self):\n        \"\"\"\n        Copy self to a new object.\n        \"\"\"\n        from copy import deepcopy\n\n        return deepcopy(self)\n    obj.copy = copy\n    return obj", "title": ""}
{"_id": "d20042", "text": "def _heapify_max(x):\n    \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n    n = len(x)\n    for i in reversed(range(n//2)):\n        _siftup_max(x, i)", "title": ""}
{"_id": "d20043", "text": "def information(filename):\n    \"\"\"Returns the file exif\"\"\"\n    check_if_this_file_exist(filename)\n    filename = os.path.abspath(filename)\n    result = get_json(filename)\n    result = result[0]\n    return result", "title": ""}
{"_id": "d20044", "text": "def is_readable(filename):\n    \"\"\"Check if file is a regular file and is readable.\"\"\"\n    return os.path.isfile(filename) and os.access(filename, os.R_OK)", "title": ""}
{"_id": "d20045", "text": "def get_last_weekday_in_month(year, month, weekday):\n        \"\"\"Get the last weekday in a given month. e.g:\n\n        >>> # the last monday in Jan 2013\n        >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n        datetime.date(2013, 1, 28)\n        \"\"\"\n        day = date(year, month, monthrange(year, month)[1])\n        while True:\n            if day.weekday() == weekday:\n                break\n            day = day - timedelta(days=1)\n        return day", "title": ""}
{"_id": "d20046", "text": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n        \"\"\"\n        Takes a list of rows and a column name and returns a list containing a single row (dict from\n        columns to cells) that has the maximum numerical value in the given column. We return a list\n        instead of a single dict to be consistent with the return type of ``select`` and\n        ``all_rows``.\n        \"\"\"\n        if not rows:\n            return []\n        value_row_pairs = [(row.values[column.name], row) for row in rows]\n        if not value_row_pairs:\n            return []\n        # Returns a list containing the row with the max cell value.\n        return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "title": ""}
{"_id": "d20047", "text": "def negate(self):\n        \"\"\"Reverse the range\"\"\"\n        self.from_value, self.to_value = self.to_value, self.from_value\n        self.include_lower, self.include_upper = self.include_upper, self.include_lower", "title": ""}
{"_id": "d20048", "text": "def quote(s, unsafe='/'):\n    \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n    encoded value as the value.\"\"\"\n    res = s.replace('%', '%25')\n    for c in unsafe:\n        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n    return res", "title": ""}
{"_id": "d20049", "text": "def plot_kde(data, ax, title=None, color='r', fill_bt=True):\n    \"\"\"\n    Plot a smoothed (by kernel density estimate) histogram.\n    :type data: numpy array\n    :param data: An array containing the data to be plotted\n\n    :type ax: matplotlib.Axes\n    :param ax: The Axes object to draw to\n\n    :type title: str\n    :param title: The plot title\n\n    :type color: str\n    :param color: The color of the histogram line and fill. Note that the fill\n                  will be plotted with an alpha of 0.35.\n\n    :type fill_bt: bool\n    :param fill_bt: Specify whether to fill the area beneath the histogram line\n    \"\"\"\n    if isinstance(data, list):\n        data = np.asarray(data)\n    e = kde.KDEUnivariate(data.astype(np.float))\n    e.fit()\n    ax.plot(e.support, e.density, color=color, alpha=0.9, linewidth=2.25)\n    if fill_bt:\n        ax.fill_between(e.support, e.density, alpha=.35, zorder=1,\n                        antialiased=True, color=color)\n    if title is not None:\n        t = ax.set_title(title)\n        t.set_y(1.05)", "title": ""}
{"_id": "d20050", "text": "def normalize(numbers):\n    \"\"\"Multiply each number by a constant such that the sum is 1.0\n    >>> normalize([1,2,1])\n    [0.25, 0.5, 0.25]\n    \"\"\"\n    total = float(sum(numbers))\n    return [n / total for n in numbers]", "title": ""}
{"_id": "d20051", "text": "def _linearInterpolationTransformMatrix(matrix1, matrix2, value):\n    \"\"\" Linear, 'oldstyle' interpolation of the transform matrix.\"\"\"\n    return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))", "title": ""}
{"_id": "d20052", "text": "def get_public_members(obj):\n    \"\"\"\n    Retrieves a list of member-like objects (members or properties) that are\n    publically exposed.\n\n    :param obj: The object to probe.\n    :return:    A list of strings.\n    \"\"\"\n    return {attr: getattr(obj, attr) for attr in dir(obj)\n            if not attr.startswith(\"_\")\n            and not hasattr(getattr(obj, attr), '__call__')}", "title": ""}
{"_id": "d20053", "text": "def check_player_collision(self):\n        \"\"\"Check to see if we are colliding with the player.\"\"\"\n        player_tiles = r.TileMapManager.active_map.grab_collisions(self.char.coords)\n        enemy_tiles = r.TileMapManager.active_map.grab_collisions(self.coords)\n\n        #Check to see if any of the tiles are the same. If so, there is a collision.\n        for ptile in player_tiles:\n            for etile in enemy_tiles:\n                if r.TileMapManager.active_map.pixels_to_tiles(ptile.coords) == r.TileMapManager.active_map.pixels_to_tiles(etile.coords):\n                    return True\n\n        return False", "title": ""}
{"_id": "d20054", "text": "def get_object_or_child_by_type(self, *types):\n        \"\"\" Get object if child already been read or get child.\n\n        Use this method for fast access to objects in case of static configurations.\n\n        :param types: requested object types.\n        :return: all children of the specified types.\n        \"\"\"\n\n        objects = self.get_objects_or_children_by_type(*types)\n        return objects[0] if any(objects) else None", "title": ""}
{"_id": "d20055", "text": "def _tofloat(obj):\n    \"\"\"Convert to float if object is a float string.\"\"\"\n    if \"inf\" in obj.lower().strip():\n        return obj\n    try:\n        return int(obj)\n    except ValueError:\n        try:\n            return float(obj)\n        except ValueError:\n            return obj", "title": ""}
{"_id": "d20056", "text": "def exit(self):\n        \"\"\"\n        Closes the connection\n        \"\"\"\n        self.pubsub.unsubscribe()\n        self.client.connection_pool.disconnect()\n\n        logger.info(\"Connection to Redis closed\")", "title": ""}
{"_id": "d20057", "text": "def ask_folder(message='Select folder.', default='', title=''):\n    \"\"\"\n    A dialog to get a directory name.\n    Returns the name of a directory, or None if user chose to cancel.\n    If the \"default\" argument specifies a directory name, and that\n    directory exists, then the dialog box will start with that directory.\n\n    :param message: message to be displayed.\n    :param title: window title\n    :param default: default folder path\n    :rtype: None or string\n    \"\"\"\n    return backend_api.opendialog(\"ask_folder\", dict(message=message, default=default, title=title))", "title": ""}
{"_id": "d20058", "text": "def debug_src(src, pm=False, globs=None):\n    \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n    testsrc = script_from_examples(src)\n    debug_script(testsrc, pm, globs)", "title": ""}
{"_id": "d20059", "text": "def v_normalize(v):\n    \"\"\"\n    Normalizes the given vector.\n    \n    The vector given may have any number of dimensions.\n    \"\"\"\n    vmag = v_magnitude(v)\n    return [ v[i]/vmag  for i in range(len(v)) ]", "title": ""}
{"_id": "d20060", "text": "def def_linear(fun):\n    \"\"\"Flags that a function is linear wrt all args\"\"\"\n    defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:\n                  fun(*subval(args, argnum, g), **kwargs))", "title": ""}
{"_id": "d20061", "text": "def __next__(self):\n        \"\"\"\n\n        :return: a pair (1-based line number in the input, row)\n        \"\"\"\n        # Retrieve the row, thereby incrementing the line number:\n        row = super(UnicodeReaderWithLineNumber, self).__next__()\n        return self.lineno + 1, row", "title": ""}
{"_id": "d20062", "text": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n    \"\"\"\n    Get all the database column names for the specified table.\n    \"\"\"\n    return [info.name for info in gen_columns_info(engine, tablename)]", "title": ""}
{"_id": "d20063", "text": "def build_columns(self, X, verbose=False):\n        \"\"\"construct the model matrix columns for the term\n\n        Parameters\n        ----------\n        X : array-like\n            Input dataset with n rows\n\n        verbose : bool\n            whether to show warnings\n\n        Returns\n        -------\n        scipy sparse array with n rows\n        \"\"\"\n        return sp.sparse.csc_matrix(X[:, self.feature][:, np.newaxis])", "title": ""}
{"_id": "d20064", "text": "def __get__(self, obj, objtype):\n        \"\"\" Support instance methods \"\"\"\n        import functools\n        return functools.partial(self.__call__, obj)", "title": ""}
{"_id": "d20065", "text": "def async_update(self, event):\n        \"\"\"New event for light.\n\n        Check that state is part of event.\n        Signal that light has updated state.\n        \"\"\"\n        self.update_attr(event.get('state', {}))\n        super().async_update(event)", "title": ""}
{"_id": "d20066", "text": "def is_float(value):\n    \"\"\"must be a float\"\"\"\n    return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "title": ""}
{"_id": "d20067", "text": "def maxlevel(lst):\n    \"\"\"Return maximum nesting depth\"\"\"\n    maxlev = 0\n    def f(lst, level):\n        nonlocal maxlev\n        if isinstance(lst, list):\n            level += 1\n            maxlev = max(level, maxlev)\n            for item in lst:\n                f(item, level)\n    f(lst, 0)\n    return maxlev", "title": ""}
{"_id": "d20068", "text": "def inside_softimage():\n    \"\"\"Returns a boolean indicating if the code is executed 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", "title": ""}
{"_id": "d20069", "text": "def _multiline_width(multiline_s, line_width_fn=len):\n    \"\"\"Visible width of a potentially multiline content.\"\"\"\n    return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "title": ""}
{"_id": "d20070", "text": "def _async_requests(urls):\n    \"\"\"\n    Sends multiple non-blocking requests. Returns\n    a list of responses.\n\n    :param urls:\n        List of urls\n    \"\"\"\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 ]", "title": ""}
{"_id": "d20071", "text": "def LinSpace(start, stop, num):\n    \"\"\"\n    Linspace op.\n    \"\"\"\n    return np.linspace(start, stop, num=num, dtype=np.float32),", "title": ""}
{"_id": "d20072", "text": "def last(self):\n        \"\"\"Get the last object in file.\"\"\"\n        # End of file\n        self.__file.seek(0, 2)\n\n        # Get the last struct\n        data = self.get(self.length - 1)\n\n        return data", "title": ""}
{"_id": "d20073", "text": "def logout(self):\n        \"\"\"\n            Logout from the remote server.\n        \"\"\"\n        self.client.write('exit\\r\\n')\n        self.client.read_all()\n        self.client.close()", "title": ""}
{"_id": "d20074", "text": "def list_get(l, idx, default=None):\n    \"\"\"\n    Get from a list with an optional default value.\n    \"\"\"\n    try:\n        if l[idx]:\n            return l[idx]\n        else:\n            return default\n    except IndexError:\n        return default", "title": ""}
{"_id": "d20075", "text": "def sometimesish(fn):\n    \"\"\"\n    Has a 50/50 chance of calling a function\n    \"\"\"\n    def wrapped(*args, **kwargs):\n        if random.randint(1, 2) == 1:\n            return fn(*args, **kwargs)\n\n    return wrapped", "title": ""}
{"_id": "d20076", "text": "def get_connection(self, host, port, db):\n        \"\"\"\n        Returns a ``StrictRedis`` connection instance.\n        \"\"\"\n        return redis.StrictRedis(\n            host=host,\n            port=port,\n            db=db,\n            decode_responses=True\n        )", "title": ""}
{"_id": "d20077", "text": "def stringify_dict_contents(dct):\n    \"\"\"Turn dict keys and values into native strings.\"\"\"\n    return {\n        str_if_nested_or_str(k): str_if_nested_or_str(v)\n        for k, v in dct.items()\n    }", "title": ""}
{"_id": "d20078", "text": "def minify(path):\n    \"\"\"\n    Load a javascript file and minify.\n\n    Parameters\n    ------------\n    path: str, path of resource\n    \"\"\"\n\n    if 'http' in path:\n        data = requests.get(path).content.decode(\n            'ascii', errors='ignore')\n    else:\n        with open(path, 'rb') as f:\n            # some of these assholes use unicode spaces -_-\n            data = f.read().decode('ascii',\n                                   errors='ignore')\n    # don't re- minify\n    if '.min.' in path:\n        return data\n\n    try:\n        return jsmin.jsmin(data)\n    except BaseException:\n        return data", "title": ""}
{"_id": "d20079", "text": "def earth_orientation(date):\n    \"\"\"Earth orientation as a rotating matrix\n    \"\"\"\n\n    x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date))\n    return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p)", "title": ""}
{"_id": "d20080", "text": "def calc_volume(self, sample: np.ndarray):\n        \"\"\"Find the RMS of the audio\"\"\"\n        return sqrt(np.mean(np.square(sample)))", "title": ""}
{"_id": "d20081", "text": "def tokenize_list(self, text):\n        \"\"\"\n        Split a text into separate words.\n        \"\"\"\n        return [self.get_record_token(record) for record in self.analyze(text)]", "title": ""}
{"_id": "d20082", "text": "def is_float(value):\n    \"\"\"must be a float\"\"\"\n    return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "title": ""}
{"_id": "d20083", "text": "def _write_color_colorama (fp, text, color):\n    \"\"\"Colorize text with given color.\"\"\"\n    foreground, background, style = get_win_color(color)\n    colorama.set_console(foreground=foreground, background=background,\n      style=style)\n    fp.write(text)\n    colorama.reset_console()", "title": ""}
{"_id": "d20084", "text": "def values(self):\n        \"\"\"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\n        \"\"\"\n        lower = float(self.lowerSpnbx.value())\n        upper = float(self.upperSpnbx.value())\n        return (lower, upper)", "title": ""}
{"_id": "d20085", "text": "def contains_extractor(document):\n    \"\"\"A basic document feature extractor that returns a dict of words that the\n    document contains.\"\"\"\n    tokens = _get_document_tokens(document)\n    features = dict((u'contains({0})'.format(w), True) for w in tokens)\n    return features", "title": ""}
{"_id": "d20086", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d20087", "text": "def get_list_index(lst, index_or_name):\n    \"\"\"\n    Return the index of an element in the list.\n\n    Args:\n        lst (list): The 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 element in the list.\n    \"\"\"\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n\n    return lst.index(index_or_name)", "title": ""}
{"_id": "d20088", "text": "def l2_norm(arr):\n    \"\"\"\n    The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n    dot product of the vector.\n    \"\"\"\n    arr = np.asarray(arr)\n    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "title": ""}
{"_id": "d20089", "text": "def register(linter):\n    \"\"\"Register the reporter classes with the linter.\"\"\"\n    linter.register_reporter(TextReporter)\n    linter.register_reporter(ParseableTextReporter)\n    linter.register_reporter(VSTextReporter)\n    linter.register_reporter(ColorizedTextReporter)", "title": ""}
{"_id": "d20090", "text": "def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type one that inherits from :class:`Numeric`,\n    such as :class:`Float`, :class:`Decimal`?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.Numeric)", "title": ""}
{"_id": "d20091", "text": "def isInteractive():\n    \"\"\"\n    A basic check of if the program is running in interactive mode\n    \"\"\"\n    if sys.stdout.isatty() and os.name != 'nt':\n        #Hopefully everything but ms supports '\\r'\n        try:\n            import threading\n        except ImportError:\n            return False\n        else:\n            return True\n    else:\n        return False", "title": ""}
{"_id": "d20092", "text": "def start_of_month(val):\n    \"\"\"\n    Return a new datetime.datetime object with values that represent\n    a start of a month.\n    :param val: Date to ...\n    :type val: datetime.datetime | datetime.date\n    :rtype: datetime.datetime\n    \"\"\"\n    if type(val) == date:\n        val = datetime.fromordinal(val.toordinal())\n    return start_of_day(val).replace(day=1)", "title": ""}
{"_id": "d20093", "text": "def cor(y_true, y_pred):\n    \"\"\"Compute Pearson correlation coefficient.\n    \"\"\"\n    y_true, y_pred = _mask_nan(y_true, y_pred)\n    return np.corrcoef(y_true, y_pred)[0, 1]", "title": ""}
{"_id": "d20094", "text": "def hidden_cursor(self):\n        \"\"\"Return a context manager that hides the cursor while inside it and\n        makes it visible on leaving.\"\"\"\n        self.stream.write(self.hide_cursor)\n        try:\n            yield\n        finally:\n            self.stream.write(self.normal_cursor)", "title": ""}
{"_id": "d20095", "text": "def token_list_len(tokenlist):\n    \"\"\"\n    Return the amount of characters in this token list.\n\n    :param tokenlist: List of (token, text) or (token, text, mouse_handler)\n                      tuples.\n    \"\"\"\n    ZeroWidthEscape = Token.ZeroWidthEscape\n    return sum(len(item[1]) for item in tokenlist if item[0] != ZeroWidthEscape)", "title": ""}
{"_id": "d20096", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d20097", "text": "def main(argv, version=DEFAULT_VERSION):\n    \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n    tarball = download_setuptools()\n    _install(tarball, _build_install_args(argv))", "title": ""}
{"_id": "d20098", "text": "def _windowsLdmodTargets(target, source, env, for_signature):\n    \"\"\"Get targets for loadable modules.\"\"\"\n    return _dllTargets(target, source, env, for_signature, 'LDMODULE')", "title": ""}
{"_id": "d20099", "text": "def encode_list(key, list_):\n    # type: (str, Iterable) -> Dict[str, str]\n    \"\"\"\n    Converts a list into a space-separated string and puts it in a dictionary\n\n    :param key: Dictionary key to store the list\n    :param list_: A list of objects\n    :return: A dictionary key->string or an empty dictionary\n    \"\"\"\n    if not list_:\n        return {}\n    return {key: \" \".join(str(i) for i in list_)}", "title": ""}
{"_id": "d20100", "text": "def resize_by_area(img, size):\n  \"\"\"image resize function used by quite a few image problems.\"\"\"\n  return tf.to_int64(\n      tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))", "title": ""}
{"_id": "d20101", "text": "def fillna(series_or_arr, missing_value=0.0):\n    \"\"\"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.\n    \"\"\"\n\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\n    return series_or_arr", "title": ""}
{"_id": "d20102", "text": "def get_size(objects):\n    \"\"\"Compute the total size of all elements in objects.\"\"\"\n    res = 0\n    for o in objects:\n        try:\n            res += _getsizeof(o)\n        except AttributeError:\n            print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n    return res", "title": ""}
{"_id": "d20103", "text": "def do_help(self, arg):\n        \"\"\"\n        Show help on all commands.\n        \"\"\"\n        print(self.response_prompt, file=self.stdout)\n        return cmd.Cmd.do_help(self, arg)", "title": ""}
{"_id": "d20104", "text": "def C_dict2array(C):\n    \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n    return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "title": ""}
{"_id": "d20105", "text": "def _process_and_sort(s, force_ascii, full_process=True):\n    \"\"\"Return a cleaned string with token sorted.\"\"\"\n    # pull tokens\n    ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s\n    tokens = ts.split()\n\n    # sort tokens and join\n    sorted_string = u\" \".join(sorted(tokens))\n    return sorted_string.strip()", "title": ""}
{"_id": "d20106", "text": "def is_readable(filename):\n    \"\"\"Check if file is a regular file and is readable.\"\"\"\n    return os.path.isfile(filename) and os.access(filename, os.R_OK)", "title": ""}
{"_id": "d20107", "text": "def empty(self, name, **kwargs):\n        \"\"\"Create an array. Keyword arguments as per\n        :func:`zarr.creation.empty`.\"\"\"\n        return self._write_op(self._empty_nosync, name, **kwargs)", "title": ""}
{"_id": "d20108", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d20109", "text": "def print_runs(query):\n    \"\"\" Print all rows in this result query. \"\"\"\n\n    if query is None:\n        return\n\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)))", "title": ""}
{"_id": "d20110", "text": "def write_fits(self, fitsfile):\n        \"\"\"Write the ROI model to a FITS file.\"\"\"\n\n        tab = self.create_table()\n        hdu_data = fits.table_to_hdu(tab)\n        hdus = [fits.PrimaryHDU(), hdu_data]\n        fits_utils.write_hdus(hdus, fitsfile)", "title": ""}
{"_id": "d20111", "text": "def page_align_content_length(length):\n    # type: (int) -> int\n    \"\"\"Compute page boundary alignment\n    :param int length: content length\n    :rtype: int\n    :return: aligned byte boundary\n    \"\"\"\n    mod = length % _PAGEBLOB_BOUNDARY\n    if mod != 0:\n        return length + (_PAGEBLOB_BOUNDARY - mod)\n    return length", "title": ""}
{"_id": "d20112", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d20113", "text": "def __replace_all(repls: dict, input: str) -> str:\n    \"\"\" Replaces from a string **input** all the occurrences of some\n    symbols according to mapping **repls**.\n\n    :param dict repls: where #key is the old character and\n    #value is the one to substitute with;\n    :param str input: original string where to apply the\n    replacements;\n    :return: *(str)* the string with the desired characters replaced\n    \"\"\"\n    return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n                  lambda k: repls[k.group(0)], input)", "title": ""}
{"_id": "d20114", "text": "def is_iterable_of_int(l):\n    r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n    if not is_iterable(l):\n        return False\n\n    return all(is_int(value) for value in l)", "title": ""}
{"_id": "d20115", "text": "def save(variable, filename):\n    \"\"\"Save variable on given path using Pickle\n    \n    Args:\n        variable: what to save\n        path (str): path of the output\n    \"\"\"\n    fileObj = open(filename, 'wb')\n    pickle.dump(variable, fileObj)\n    fileObj.close()", "title": ""}
{"_id": "d20116", "text": "def stop_at(iterable, idx):\n    \"\"\"Stops iterating before yielding the specified idx.\"\"\"\n    for i, item in enumerate(iterable):\n        if i == idx: return\n        yield item", "title": ""}
{"_id": "d20117", "text": "def token(name):\n    \"\"\"Marker for a token\n\n    :param str name: Name of tokenizer\n    \"\"\"\n\n    def wrap(f):\n        tokenizers.append((name, f))\n        return f\n\n    return wrap", "title": ""}
{"_id": "d20118", "text": "def assert_or_raise(stmt: bool, exception: Exception,\n                    *exception_args, **exception_kwargs) -> None:\n  \"\"\"\n  If the statement is false, raise the given exception.\n  \"\"\"\n  if not stmt:\n    raise exception(*exception_args, **exception_kwargs)", "title": ""}
{"_id": "d20119", "text": "def _return_comma_list(self, l):\n        \"\"\" get a list and return a string with comma separated list values\n        Examples ['to', 'ta'] will return 'to,ta'.\n        \"\"\"\n        if isinstance(l, (text_type, int)):\n            return l\n\n        if not isinstance(l, list):\n            raise TypeError(l, ' should be a list of integers, \\\nnot {0}'.format(type(l)))\n\n        str_ids = ','.join(str(i) for i in l)\n\n        return str_ids", "title": ""}
{"_id": "d20120", "text": "def asynchronous(function, event):\n    \"\"\"\n    Runs the function asynchronously taking care of exceptions.\n    \"\"\"\n    thread = Thread(target=synchronous, args=(function, event))\n    thread.daemon = True\n    thread.start()", "title": ""}
{"_id": "d20121", "text": "def time2seconds(t):\n    \"\"\"Returns seconds since 0h00.\"\"\"\n    return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6", "title": ""}
{"_id": "d20122", "text": "def _to_numeric(val):\n    \"\"\"\n    Helper function for conversion of various data types into numeric representation.\n    \"\"\"\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)", "title": ""}
{"_id": "d20123", "text": "def datetime_to_ms(dt):\n    \"\"\"\n    Converts a datetime to a millisecond accuracy timestamp\n    \"\"\"\n    seconds = calendar.timegm(dt.utctimetuple())\n    return seconds * 1000 + int(dt.microsecond / 1000)", "title": ""}
{"_id": "d20124", "text": "def get_readline_tail(self, n=10):\n        \"\"\"Get the last n items in readline history.\"\"\"\n        end = self.shell.readline.get_current_history_length() + 1\n        start = max(end-n, 1)\n        ghi = self.shell.readline.get_history_item\n        return [ghi(x) for x in range(start, end)]", "title": ""}
{"_id": "d20125", "text": "def get_table_columns(dbconn, tablename):\n    \"\"\"\n    Return a list of tuples specifying the column name and type\n    \"\"\"\n    cur = dbconn.cursor()\n    cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n    info = cur.fetchall()\n    cols = [(i[1], i[2]) for i in info]\n    return cols", "title": ""}
{"_id": "d20126", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d20127", "text": "def flatten_multidict(multidict):\n    \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n    return dict([(key, value if len(value) > 1 else value[0])\n                 for (key, value) in multidict.iterlists()])", "title": ""}
{"_id": "d20128", "text": "def _session_set(self, key, value):\n        \"\"\"\n        Saves a value to session.\n        \"\"\"\n\n        self.session[self._session_key(key)] = value", "title": ""}
{"_id": "d20129", "text": "def to_dotfile(G: nx.DiGraph, filename: str):\n    \"\"\" Output a networkx graph to a DOT file. \"\"\"\n    A = to_agraph(G)\n    A.write(filename)", "title": ""}
{"_id": "d20130", "text": "def rmfile(path):\n    \"\"\"Ensure file deleted also on *Windows* where read-only files need special treatment.\"\"\"\n    if osp.isfile(path):\n        if is_win:\n            os.chmod(path, 0o777)\n        os.remove(path)", "title": ""}
{"_id": "d20131", "text": "def add_suffix(fullname, suffix):\n    \"\"\" Add suffix to a full file name\"\"\"\n    name, ext = os.path.splitext(fullname)\n    return name + '_' + suffix + ext", "title": ""}
{"_id": "d20132", "text": "def is_iterable_but_not_string(obj):\n    \"\"\"\n    Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n    \"\"\"\n    return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "title": ""}
{"_id": "d20133", "text": "def askopenfilename(**kwargs):\n    \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n    try:\n        from Tkinter import Tk\n        import tkFileDialog as filedialog\n    except ImportError:\n        from tkinter import Tk, filedialog\n    root = Tk()\n    root.withdraw()\n    root.update()\n    filenames = filedialog.askopenfilename(**kwargs)\n    root.destroy()\n    return filenames", "title": ""}
{"_id": "d20134", "text": "def _pad(self):\n    \"\"\"Pads the output with an amount of indentation appropriate for the number of open element.\n\n    This method does nothing if the indent value passed to the constructor is falsy.\n    \"\"\"\n    if self._indent:\n      self.whitespace(self._indent * len(self._open_elements))", "title": ""}
{"_id": "d20135", "text": "def compute_centroid(points):\n    \"\"\" Computes the centroid of set of points\n\n    Args:\n        points (:obj:`list` of :obj:`Point`)\n    Returns:\n        :obj:`Point`\n    \"\"\"\n    lats = [p[1] for p in points]\n    lons = [p[0] for p in points]\n    return Point(np.mean(lats), np.mean(lons), None)", "title": ""}
{"_id": "d20136", "text": "def cfloat32_array_to_numpy(cptr, length):\n    \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n        return np.fromiter(cptr, dtype=np.float32, count=length)\n    else:\n        raise RuntimeError('Expected float pointer')", "title": ""}
{"_id": "d20137", "text": "def paragraph(separator='\\n\\n', wrap_start='', wrap_end='',\n              html=False, sentences_quantity=3):\n    \"\"\"Return a random paragraph.\"\"\"\n    return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start,\n                      wrap_end=wrap_end, html=html,\n                      sentences_quantity=sentences_quantity)", "title": ""}
{"_id": "d20138", "text": "def delete(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP DELETE operation to API endpoint.\"\"\"\n\n        return self._request('DELETE', endpoint, **kwargs)", "title": ""}
{"_id": "d20139", "text": "def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):\n    \"\"\"Replace month strings occurrences with month number.\"\"\"\n    num, abbr = get_month_from_date_str(date_str, lang)\n    return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE)", "title": ""}
{"_id": "d20140", "text": "def is_integer(obj):\n    \"\"\"Is this an integer.\n\n    :param object obj:\n    :return:\n    \"\"\"\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))", "title": ""}
{"_id": "d20141", "text": "def _validate(data, schema, ac_schema_safe=True, **options):\n    \"\"\"\n    See the descritpion of :func:`validate` for more details of parameters and\n    return value.\n\n    Validate target object 'data' with given schema object.\n    \"\"\"\n    try:\n        jsonschema.validate(data, schema, **options)\n\n    except (jsonschema.ValidationError, jsonschema.SchemaError,\n            Exception) as exc:\n        if ac_schema_safe:\n            return (False, str(exc))  # Validation was failed.\n        raise\n\n    return (True, '')", "title": ""}
{"_id": "d20142", "text": "def access_token(self):\n        \"\"\" WeChat access token \"\"\"\n        access_token = self.session.get(self.access_token_key)\n        if access_token:\n            if not self.expires_at:\n                # user provided access_token, just return it\n                return access_token\n\n            timestamp = time.time()\n            if self.expires_at - timestamp > 60:\n                return access_token\n\n        self.fetch_access_token()\n        return self.session.get(self.access_token_key)", "title": ""}
{"_id": "d20143", "text": "def str2int(num, radix=10, alphabet=BASE85):\n    \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n    return NumConv(radix, alphabet).str2int(num)", "title": ""}
{"_id": "d20144", "text": "def drag_and_drop(self, droppable):\n        \"\"\"\n        Performs drag a element to another elmenet.\n\n        Currently works only on Chrome driver.\n        \"\"\"\n        self.scroll_to()\n        ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()", "title": ""}
{"_id": "d20145", "text": "def unique_list(lst):\n    \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n    uniq = []\n    for item in lst:\n        if item not in uniq:\n            uniq.append(item)\n    return uniq", "title": ""}
{"_id": "d20146", "text": "def check_git():\n    \"\"\"Check if git command is available.\"\"\"\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.\")", "title": ""}
{"_id": "d20147", "text": "def prt_nts(data_nts, prtfmt=None, prt=sys.stdout, nt_fields=None, **kws):\n    \"\"\"Print list of namedtuples into a table using prtfmt.\"\"\"\n    prt_txt(prt, data_nts, prtfmt, nt_fields, **kws)", "title": ""}
{"_id": "d20148", "text": "def task_property_present_predicate(service, task, prop):\n    \"\"\" True if the json_element passed is present for the task specified.\n    \"\"\"\n    try:\n        response = get_service_task(service, task)\n    except Exception as e:\n        pass\n\n    return (response is not None) and (prop in response)", "title": ""}
{"_id": "d20149", "text": "def count_list(the_list):\n    \"\"\"\n    Generates a count of the number of times each unique item appears in a list\n    \"\"\"\n    count = the_list.count\n    result = [(item, count(item)) for item in set(the_list)]\n    result.sort()\n    return result", "title": ""}
{"_id": "d20150", "text": "def get_randomized_guid_sample(self, item_count):\n        \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n        dataset = self.get_whitelist()\n        random.shuffle(dataset)\n        return dataset[:item_count]", "title": ""}
{"_id": "d20151", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d20152", "text": "def set_scrollregion(self, event=None):\n        \"\"\" Set the scroll region on the canvas\"\"\"\n        self.canvas.configure(scrollregion=self.canvas.bbox('all'))", "title": ""}
{"_id": "d20153", "text": "def print_fatal_results(results, level=0):\n    \"\"\"Print fatal errors that occurred during validation runs.\n    \"\"\"\n    print_level(logger.critical, _RED + \"[X] Fatal Error: %s\", level, results.error)", "title": ""}
{"_id": "d20154", "text": "def safe_format(s, **kwargs):\n  \"\"\"\n  :type s str\n  \"\"\"\n  return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))", "title": ""}
{"_id": "d20155", "text": "def url_host(url: str) -> str:\n    \"\"\"\n    Parses hostname from URL.\n    :param url: URL\n    :return: hostname\n    \"\"\"\n    from urllib.parse import urlparse\n    res = urlparse(url)\n    return res.netloc.split(':')[0] if res.netloc else ''", "title": ""}
{"_id": "d20156", "text": "def asMaskedArray(self):\n        \"\"\" Creates converts to a masked array\n        \"\"\"\n        return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)", "title": ""}
{"_id": "d20157", "text": "def closeEvent(self, e):\n        \"\"\"Qt slot when the window is closed.\"\"\"\n        self.emit('close_widget')\n        super(DockWidget, self).closeEvent(e)", "title": ""}
{"_id": "d20158", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d20159", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d20160", "text": "def loads(s, model=None, parser=None):\n    \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n    with StringIO(s) as f:\n        return load(f, model=model, parser=parser)", "title": ""}
{"_id": "d20161", "text": "def get_groups(self, username):\n        \"\"\"Get all groups of a user\"\"\"\n        username = ldap.filter.escape_filter_chars(self._byte_p2(username))\n        userdn = self._get_user(username, NO_ATTR)\n\n        searchfilter = self.group_filter_tmpl % {\n            'userdn': userdn,\n            'username': username\n        }\n\n        groups = self._search(searchfilter, NO_ATTR, self.groupdn)\n        ret = []\n        for entry in groups:\n            ret.append(self._uni(entry[0]))\n        return ret", "title": ""}
{"_id": "d20162", "text": "def is_unicode(string):\n    \"\"\"Validates that the object itself is some kinda string\"\"\"\n    str_type = str(type(string))\n\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n\n    return False", "title": ""}
{"_id": "d20163", "text": "def caller_locals():\n    \"\"\"Get the local variables in the caller's frame.\"\"\"\n    import inspect\n    frame = inspect.currentframe()\n    try:\n        return frame.f_back.f_back.f_locals\n    finally:\n        del frame", "title": ""}
{"_id": "d20164", "text": "def _get_loggers():\n    \"\"\"Return list of Logger classes.\"\"\"\n    from .. import loader\n    modules = loader.get_package_modules('logger')\n    return list(loader.get_plugins(modules, [_Logger]))", "title": ""}
{"_id": "d20165", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d20166", "text": "def EvalGaussianPdf(x, mu, sigma):\n    \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n    x: value\n    mu: mean\n    sigma: standard deviation\n    \n    returns: float probability density\n    \"\"\"\n    return scipy.stats.norm.pdf(x, mu, sigma)", "title": ""}
{"_id": "d20167", "text": "def GetAllPixelColors(self) -> ctypes.Array:\n        \"\"\"\n        Return `ctypes.Array`, an iterable array of int values in argb.\n        \"\"\"\n        return self.GetPixelColorsOfRect(0, 0, self.Width, self.Height)", "title": ""}
{"_id": "d20168", "text": "def _rescale_array(self, array, scale, zero):\n        \"\"\"\n        Scale the input array\n        \"\"\"\n        if scale != 1.0:\n            sval = numpy.array(scale, dtype=array.dtype)\n            array *= sval\n        if zero != 0.0:\n            zval = numpy.array(zero, dtype=array.dtype)\n            array += zval", "title": ""}
{"_id": "d20169", "text": "def upcaseTokens(s,l,t):\n    \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n    return [ tt.upper() for tt in map(_ustr,t) ]", "title": ""}
{"_id": "d20170", "text": "def build(self, **kwargs):\n        \"\"\"Build the lexer.\"\"\"\n        self.lexer = ply.lex.lex(object=self, **kwargs)", "title": ""}
{"_id": "d20171", "text": "def _get_file_sha1(file):\n    \"\"\"Return the SHA1 hash of the given a file-like object as ``file``.\n    This will seek the file back to 0 when it's finished.\n\n    \"\"\"\n    bits = file.read()\n    file.seek(0)\n    h = hashlib.new('sha1', bits).hexdigest()\n    return h", "title": ""}
{"_id": "d20172", "text": "def set_trace():\n    \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n    # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n    pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "title": ""}
{"_id": "d20173", "text": "def factorial(n, mod=None):\n    \"\"\"Calculates factorial iteratively.\n    If mod is not None, then return (n! % mod)\n    Time Complexity - O(n)\"\"\"\n    if not (isinstance(n, int) and n >= 0):\n        raise ValueError(\"'n' must be a non-negative integer.\")\n    if mod is not None and not (isinstance(mod, int) and mod > 0):\n        raise ValueError(\"'mod' must be a positive integer\")\n    result = 1\n    if n == 0:\n        return 1\n    for i in range(2, n+1):\n        result *= i\n        if mod:\n            result %= mod\n    return result", "title": ""}
{"_id": "d20174", "text": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n    \"\"\"\n    Returns the last `n` rows in the table\n    \"\"\"\n    return fetch(dbconn, tablename, n, uuid, end=True)", "title": ""}
{"_id": "d20175", "text": "def lower_ext(abspath):\n    \"\"\"Convert file extension to lowercase.\n    \"\"\"\n    fname, ext = os.path.splitext(abspath)\n    return fname + ext.lower()", "title": ""}
{"_id": "d20176", "text": "def machine_info():\n    \"\"\"Retrieve core and memory information for the current machine.\n    \"\"\"\n    import psutil\n    BYTES_IN_GIG = 1073741824.0\n    free_bytes = psutil.virtual_memory().total\n    return [{\"memory\": float(\"%.1f\" % (free_bytes / BYTES_IN_GIG)), \"cores\": multiprocessing.cpu_count(),\n             \"name\": socket.gethostname()}]", "title": ""}
{"_id": "d20177", "text": "def indexes_equal(a: Index, b: Index) -> bool:\n    \"\"\"\n    Are two indexes equal? Checks by comparing ``str()`` versions of them.\n    (AM UNSURE IF THIS IS ENOUGH.)\n    \"\"\"\n    return str(a) == str(b)", "title": ""}
{"_id": "d20178", "text": "def create_db(app, appbuilder):\n    \"\"\"\n        Create all your database objects (SQLAlchemy specific).\n    \"\"\"\n    from flask_appbuilder.models.sqla import Base\n\n    _appbuilder = import_application(app, appbuilder)\n    engine = _appbuilder.get_session.get_bind(mapper=None, clause=None)\n    Base.metadata.create_all(engine)\n    click.echo(click.style(\"DB objects created\", fg=\"green\"))", "title": ""}
{"_id": "d20179", "text": "def cleanup():\n    \"\"\"Cleanup the output directory\"\"\"\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)", "title": ""}
{"_id": "d20180", "text": "def debugTreePrint(node,pfx=\"->\"):\n  \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n  print pfx,node.item\n  for c in node.children:\n    debugTreePrint(c,\"  \"+pfx)", "title": ""}
{"_id": "d20181", "text": "def urlencoded(body, charset='ascii', **kwargs):\n    \"\"\"Converts query strings into native Python objects\"\"\"\n    return parse_query_string(text(body, charset=charset), False)", "title": ""}
{"_id": "d20182", "text": "def each_img(dir_path):\n    \"\"\"\n    Iterates through each image in the given directory. (not recursive)\n    :param dir_path: Directory path where images files are present\n    :return: Iterator to iterate through image files\n    \"\"\"\n    for fname in os.listdir(dir_path):\n        if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'):\n            yield fname", "title": ""}
{"_id": "d20183", "text": "def valid_date(x: str) -> bool:\n    \"\"\"\n    Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n    otherwise return ``False``.\n    \"\"\"\n    try:\n        if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n            raise ValueError\n        return True\n    except ValueError:\n        return False", "title": ""}
{"_id": "d20184", "text": "def sbessely(x, N):\n    \"\"\"Returns a vector of spherical bessel functions yn:\n\n        x:   The argument.\n        N:   values of n will run from 0 to N-1.\n\n    \"\"\"\n\n    out = np.zeros(N, dtype=np.float64)\n\n    out[0] = -np.cos(x) / x\n    out[1] = -np.cos(x) / (x ** 2) - np.sin(x) / x\n\n    for n in xrange(2, N):\n        out[n] = ((2.0 * n - 1.0) / x) * out[n - 1] - out[n - 2]\n\n    return out", "title": ""}
{"_id": "d20185", "text": "def _cnx_is_empty(in_file):\n    \"\"\"Check if cnr or cns files are empty (only have a header)\n    \"\"\"\n    with open(in_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 0:\n                return False\n    return True", "title": ""}
{"_id": "d20186", "text": "def stop(self, timeout=None):\n        \"\"\" Initiates a graceful stop of the processes \"\"\"\n\n        self.stopping = True\n\n        for process in list(self.processes):\n            self.stop_process(process, timeout=timeout)", "title": ""}
{"_id": "d20187", "text": "def sanitize_word(s):\n    \"\"\"Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores.\n    \"\"\"\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')", "title": ""}
{"_id": "d20188", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d20189", "text": "def __init__(self):\n        \"\"\"Initialize the state of the object\"\"\"\n        self.state = self.STATE_INITIALIZING\n        self.state_start = time.time()", "title": ""}
{"_id": "d20190", "text": "def scan(client, query=None, scroll='5m', raise_on_error=True,\n         preserve_order=False, size=1000, **kwargs):\n    \"\"\"\n    Simple abstraction on top of the\n    :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that\n    yields all hits as returned by underlining scroll requests.\n    By default scan does not return results in any pre-determined order. To\n    have a standard order in the returned documents (either by score or\n    explicit sort definition) when scrolling, use ``preserve_order=True``. This\n    may be an expensive operation and will negate the performance benefits of\n    using ``scan``.\n    :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n    :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api\n    :arg scroll: Specify how long a consistent view of the index should be\n        maintained for scrolled search\n    :arg raise_on_error: raises an exception (``ScanError``) if an error is\n        encountered (some shards fail to execute). By default we raise.\n    :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will\n        cause the scroll to paginate with preserving the order. Note that this\n        can be an extremely expensive operation and can easily lead to\n        unpredictable results, use with caution.\n    :arg size: size (per shard) of the batch send at each iteration.\n    Any additional keyword arguments will be passed to the initial\n    :meth:`~elasticsearch.Elasticsearch.search` call::\n        scan(es,\n            query={\"query\": {\"match\": {\"title\": \"python\"}}},\n            index=\"orders-*\",\n            doc_type=\"books\"\n        )\n    \"\"\"\n    if not preserve_order:\n        kwargs['search_type'] = 'scan'\n    # initial search\n    resp = client.search(body=query, scroll=scroll, size=size, **kwargs)\n\n    scroll_id = resp.get('_scroll_id')\n    if scroll_id is None:\n        return\n\n    first_run = True\n    while True:\n        # if we didn't set search_type to scan initial search contains data\n        if preserve_order and first_run:\n            first_run = False\n        else:\n            resp = client.scroll(scroll_id, scroll=scroll)\n\n        for hit in resp['hits']['hits']:\n            yield hit\n\n        # check if we have any errrors\n        if resp[\"_shards\"][\"failed\"]:\n            logger.warning(\n                'Scroll request has failed on %d shards out of %d.',\n                resp['_shards']['failed'], resp['_shards']['total']\n            )\n            if raise_on_error:\n                raise ScanError(\n                    'Scroll request has failed on %d shards out of %d.' %\n                    (resp['_shards']['failed'], resp['_shards']['total'])\n                )\n\n        scroll_id = resp.get('_scroll_id')\n        # end of scroll\n        if scroll_id is None or not resp['hits']['hits']:\n            break", "title": ""}
{"_id": "d20191", "text": "def __exit__(self, type, value, traceback):\n        \"\"\"When the `with` statement ends.\"\"\"\n\n        if not self.asarfile:\n            return\n\n        self.asarfile.close()\n        self.asarfile = None", "title": ""}
{"_id": "d20192", "text": "def attr_cache_clear(self):\n        node = extract_node(\"\"\"def cache_clear(self): pass\"\"\")\n        return BoundMethod(proxy=node, bound=self._instance.parent.scope())", "title": ""}
{"_id": "d20193", "text": "def stop_at(iterable, idx):\n    \"\"\"Stops iterating before yielding the specified idx.\"\"\"\n    for i, item in enumerate(iterable):\n        if i == idx: return\n        yield item", "title": ""}
{"_id": "d20194", "text": "def date_to_datetime(x):\n    \"\"\"Convert a date into a datetime\"\"\"\n    if not isinstance(x, datetime) and isinstance(x, date):\n        return datetime.combine(x, time())\n    return x", "title": ""}
{"_id": "d20195", "text": "def accel_next(self, *args):\n        \"\"\"Callback to go to the next tab. Called by the accel key.\n        \"\"\"\n        if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n            self.get_notebook().set_current_page(0)\n        else:\n            self.get_notebook().next_page()\n        return True", "title": ""}
{"_id": "d20196", "text": "def clean_dataframe(df):\n    \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n    df = df.fillna(method='ffill')\n    df = df.fillna(0.0)\n    return df", "title": ""}
{"_id": "d20197", "text": "def check_output(args, env=None, sp=subprocess):\n    \"\"\"Call an external binary and return its stdout.\"\"\"\n    log.debug('calling %s with env %s', args, env)\n    output = sp.check_output(args=args, env=env)\n    log.debug('output: %r', output)\n    return output", "title": ""}
{"_id": "d20198", "text": "def cpp_prog_builder(build_context, target):\n    \"\"\"Build a C++ binary executable\"\"\"\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)", "title": ""}
{"_id": "d20199", "text": "def to_bytes(self):\n\t\t\"\"\"Convert the entire image to bytes.\n\t\t\n\t\t:rtype: bytes\n\t\t\"\"\"\n\t\tchunks = [PNG_SIGN]\n\t\tchunks.extend(c[1] for c in self.chunks)\n\t\treturn b\"\".join(chunks)", "title": ""}
{"_id": "d20200", "text": "def fetch_token(self, **kwargs):\n        \"\"\"Exchange a code (and 'state' token) for a bearer token\"\"\"\n        return super(AsanaOAuth2Session, self).fetch_token(self.token_url, client_secret=self.client_secret, **kwargs)", "title": ""}
{"_id": "d20201", "text": "def advance_one_line(self):\n    \"\"\"Advances to next line.\"\"\"\n\n    current_line = self._current_token.line_number\n    while current_line == self._current_token.line_number:\n      self._current_token = ConfigParser.Token(*next(self._token_generator))", "title": ""}
{"_id": "d20202", "text": "def round_to_int(number, precision):\n    \"\"\"Round a number to a precision\"\"\"\n    precision = int(precision)\n    rounded = (int(number) + precision / 2) // precision * precision\n    return rounded", "title": ""}
{"_id": "d20203", "text": "def roll_dice():\n    \"\"\"\n    Roll a die.\n\n    :return: None\n    \"\"\"\n    sums = 0  # will return the sum of the roll calls.\n    while True:\n        roll = random.randint(1, 6)\n        sums += roll\n        if(input(\"Enter y or n to continue: \").upper()) == 'N':\n            print(sums)  # prints the sum of the roll calls\n            break", "title": ""}
{"_id": "d20204", "text": "def __add_namespaceinfo(self, ni):\n        \"\"\"Internal method to directly add a _NamespaceInfo object to this\n        set.  No sanity checks are done (e.g. checking for prefix conflicts),\n        so be sure to do it yourself before calling this.\"\"\"\n        self.__ns_uri_map[ni.uri] = ni\n        for prefix in ni.prefixes:\n            self.__prefix_map[prefix] = ni", "title": ""}
{"_id": "d20205", "text": "def generate_seed(seed):\n    \"\"\"Generate seed for random number generator\"\"\"\n    if seed is None:\n        random.seed()\n        seed = random.randint(0, sys.maxsize)\n    random.seed(a=seed)\n\n    return seed", "title": ""}
{"_id": "d20206", "text": "def arg_default(*args, **kwargs):\n    \"\"\"Return default argument value as given by argparse's add_argument().\n\n    The argument is passed through a mocked-up argument parser. This way, we\n    get default parameters even if the feature is called directly and not\n    through the CLI.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(*args, **kwargs)\n    args = vars(parser.parse_args([]))\n    _, default = args.popitem()\n    return default", "title": ""}
{"_id": "d20207", "text": "def to_int64(a):\n    \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n    # build new dtype and replace i4 --> i8\n    def promote_i4(typestr):\n        if typestr[1:] == 'i4':\n            typestr = typestr[0]+'i8'\n        return typestr\n\n    dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n    return a.astype(dtype)", "title": ""}
{"_id": "d20208", "text": "def close(self):\n    \"\"\"Send a close message to the external process and join it.\"\"\"\n    try:\n      self._conn.send((self._CLOSE, None))\n      self._conn.close()\n    except IOError:\n      # The connection was already closed.\n      pass\n    self._process.join()", "title": ""}
{"_id": "d20209", "text": "def reduce_fn(x):\n    \"\"\"\n    Aggregation function to get the first non-zero value.\n    \"\"\"\n    values = x.values if pd and isinstance(x, pd.Series) else x\n    for v in values:\n        if not is_nan(v):\n            return v\n    return np.NaN", "title": ""}
{"_id": "d20210", "text": "def _increment(arr, indices):\n    \"\"\"Increment some indices in a 1D vector of non-negative integers.\n    Repeated indices are taken into account.\"\"\"\n    arr = _as_array(arr)\n    indices = _as_array(indices)\n    bbins = np.bincount(indices)\n    arr[:len(bbins)] += bbins\n    return arr", "title": ""}
{"_id": "d20211", "text": "def coverage(ctx, opts=\"\"):\n    \"\"\"\n    Execute all tests (normal and slow) with coverage enabled.\n    \"\"\"\n    return test(ctx, coverage=True, include_slow=True, opts=opts)", "title": ""}
{"_id": "d20212", "text": "def glob_by_extensions(directory, extensions):\n    \"\"\" Returns files matched by all extensions in the extensions list \"\"\"\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", "title": ""}
{"_id": "d20213", "text": "def is_builtin_type(tp):\n    \"\"\"Checks if the given type is a builtin one.\n    \"\"\"\n    return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "title": ""}
{"_id": "d20214", "text": "def calc_list_average(l):\n    \"\"\"\n    Calculates the average value of a list of numbers\n    Returns a float\n    \"\"\"\n    total = 0.0\n    for value in l:\n        total += value\n    return total / len(l)", "title": ""}
{"_id": "d20215", "text": "def numpy_aware_eq(a, b):\n    \"\"\"Return whether two objects are equal via recursion, using\n    :func:`numpy.array_equal` for comparing numpy arays.\n    \"\"\"\n    if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n        return np.array_equal(a, b)\n    if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n            not isinstance(a, str) and not isinstance(b, str)):\n        if len(a) != len(b):\n            return False\n        return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n    return a == b", "title": ""}
{"_id": "d20216", "text": "def round_array(array_in):\n    \"\"\"\n    arr_out = round_array(array_in)\n\n    Rounds an array and recasts it to int. Also works on scalars.\n    \"\"\"\n    if isinstance(array_in, ndarray):\n        return np.round(array_in).astype(int)\n    else:\n        return int(np.round(array_in))", "title": ""}
{"_id": "d20217", "text": "def win32_refresh_window(cls):\n        \"\"\"\n        Call win32 API to refresh the whole Window.\n\n        This is sometimes necessary when the application paints background\n        for completion menus. When the menu disappears, it leaves traces due\n        to a bug in the Windows Console. Sending a repaint request solves it.\n        \"\"\"\n        # Get console handle\n        handle = windll.kernel32.GetConsoleWindow()\n\n        RDW_INVALIDATE = 0x0001\n        windll.user32.RedrawWindow(handle, None, None, c_uint(RDW_INVALIDATE))", "title": ""}
{"_id": "d20218", "text": "def _latest_date(self, query, datetime_field_name):\n        \"\"\"Given a QuerySet and the name of field containing datetimes, return the\n        latest (most recent) date.\n\n        Return None if QuerySet is empty.\n\n        \"\"\"\n        return list(\n            query.aggregate(django.db.models.Max(datetime_field_name)).values()\n        )[0]", "title": ""}
{"_id": "d20219", "text": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "title": ""}
{"_id": "d20220", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d20221", "text": "def us2mc(string):\n    \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)", "title": ""}
{"_id": "d20222", "text": "def convert_tstamp(response):\n\t\"\"\"\n\tConvert a Stripe API timestamp response (unix epoch) to a native datetime.\n\n\t:rtype: datetime\n\t\"\"\"\n\tif response is None:\n\t\t# Allow passing None to convert_tstamp()\n\t\treturn response\n\n\t# Overrides the set timezone to UTC - I think...\n\ttz = timezone.utc if settings.USE_TZ else None\n\n\treturn datetime.datetime.fromtimestamp(response, tz)", "title": ""}
{"_id": "d20223", "text": "def generate_id(self, obj):\n        \"\"\"Generate unique document id for ElasticSearch.\"\"\"\n        object_type = type(obj).__name__.lower()\n        return '{}_{}'.format(object_type, self.get_object_id(obj))", "title": ""}
{"_id": "d20224", "text": "def assert_called(_mock_self):\n        \"\"\"assert that the mock was called at least once\n        \"\"\"\n        self = _mock_self\n        if self.call_count == 0:\n            msg = (\"Expected '%s' to have been called.\" %\n                   self._mock_name or 'mock')\n            raise AssertionError(msg)", "title": ""}
{"_id": "d20225", "text": "def get_current_desktop(self):\n        \"\"\"\n        Get the current desktop.\n        Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec.\n        \"\"\"\n        desktop = ctypes.c_long(0)\n        _libxdo.xdo_get_current_desktop(self._xdo, ctypes.byref(desktop))\n        return desktop.value", "title": ""}
{"_id": "d20226", "text": "def __connect():\n    \"\"\"\n    Connect to a redis instance.\n    \"\"\"\n    global redis_instance\n    if use_tcp_socket:\n        redis_instance = redis.StrictRedis(host=hostname, port=port)\n    else:\n        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "title": ""}
{"_id": "d20227", "text": "def show_yticklabels(self, row, column):\n        \"\"\"Show the y-axis tick labels for a subplot.\n\n        :param row,column: specify the subplot.\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.show_yticklabels()", "title": ""}
{"_id": "d20228", "text": "def find_first_in_list(txt: str, str_list: [str]) -> int:  # type: ignore\n    \"\"\"\n    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\n    \"\"\"\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", "title": ""}
{"_id": "d20229", "text": "def imflip(img, direction='horizontal'):\n    \"\"\"Flip an image horizontally or vertically.\n\n    Args:\n        img (ndarray): Image to be flipped.\n        direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n    Returns:\n        ndarray: The flipped image.\n    \"\"\"\n    assert direction in ['horizontal', 'vertical']\n    if direction == 'horizontal':\n        return np.flip(img, axis=1)\n    else:\n        return np.flip(img, axis=0)", "title": ""}
{"_id": "d20230", "text": "def _fullname(o):\n    \"\"\"Return the fully-qualified name of a function.\"\"\"\n    return o.__module__ + \".\" + o.__name__ if o.__module__ else o.__name__", "title": ""}
{"_id": "d20231", "text": "def is_integer(value: Any) -> bool:\n    \"\"\"Return true if a value is an integer number.\"\"\"\n    return (isinstance(value, int) and not isinstance(value, bool)) or (\n        isinstance(value, float) and isfinite(value) and int(value) == value\n    )", "title": ""}
{"_id": "d20232", "text": "def to_array(self):\n        \"\"\"Convert the table to a structured NumPy array.\"\"\"\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", "title": ""}
{"_id": "d20233", "text": "def join_cols(cols):\n    \"\"\"Join list of columns into a string for a SQL query\"\"\"\n    return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols", "title": ""}
{"_id": "d20234", "text": "def lines(input):\n    \"\"\"Remove comments and empty lines\"\"\"\n    for raw_line in input:\n        line = raw_line.strip()\n        if line and not line.startswith('#'):\n            yield strip_comments(line)", "title": ""}
{"_id": "d20235", "text": "def qsize(self):\n        \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n        self.mutex.acquire()\n        n = self._qsize()\n        self.mutex.release()\n        return n", "title": ""}
{"_id": "d20236", "text": "def get_substring_idxs(substr, string):\n    \"\"\"\n    Return a list of indexes of substr. If substr not found, list is\n    empty.\n\n    Arguments:\n        substr (str): Substring to match.\n        string (str): String to match in.\n\n    Returns:\n        list of int: Start indices of substr.\n    \"\"\"\n    return [match.start() for match in re.finditer(substr, string)]", "title": ""}
{"_id": "d20237", "text": "def is_natural(x):\n    \"\"\"A non-negative integer.\"\"\"\n    try:\n        is_integer = int(x) == x\n    except (TypeError, ValueError):\n        return False\n    return is_integer and x >= 0", "title": ""}
{"_id": "d20238", "text": "def toJson(protoObject, indent=None):\n    \"\"\"\n    Serialises a protobuf object as json\n    \"\"\"\n    # Using the internal method because this way we can reformat the JSON\n    js = json_format.MessageToDict(protoObject, False)\n    return json.dumps(js, indent=indent)", "title": ""}
{"_id": "d20239", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d20240", "text": "def dotproduct(X, Y):\n    \"\"\"Return the sum of the element-wise product of vectors x and y.\n    >>> dotproduct([1, 2, 3], [1000, 100, 10])\n    1230\n    \"\"\"\n    return sum([x * y for x, y in zip(X, Y)])", "title": ""}
{"_id": "d20241", "text": "def dates_in_range(start_date, end_date):\n    \"\"\"Returns all dates between two dates.\n\n    Inclusive of the start date but not the end date.\n\n    Args:\n        start_date (datetime.date)\n        end_date (datetime.date)\n\n    Returns:\n        (list) of datetime.date objects\n    \"\"\"\n    return [\n        start_date + timedelta(n)\n        for n in range(int((end_date - start_date).days))\n    ]", "title": ""}
{"_id": "d20242", "text": "def get_remote_content(filepath):\n        \"\"\" A handy wrapper to get a remote file content \"\"\"\n        with hide('running'):\n            temp = BytesIO()\n            get(filepath, temp)\n            content = temp.getvalue().decode('utf-8')\n        return content.strip()", "title": ""}
{"_id": "d20243", "text": "def get_dates_link(url):\n    \"\"\" download the dates file from the internet and parse it as a dates file\"\"\"\n    urllib.request.urlretrieve(url, \"temp.txt\")\n    dates = get_dates_file(\"temp.txt\")\n    os.remove(\"temp.txt\")\n    return dates", "title": ""}
{"_id": "d20244", "text": "def _removeStopwords(text_list):\n    \"\"\"\n    Removes stopwords contained in a list of words.\n\n    :param text_string: A list of strings.\n    :type text_string: list.\n\n    :returns: The input ``text_list`` with stopwords removed.\n    :rtype: list\n    \"\"\"\n\n    output_list = []\n\n    for word in text_list:\n        if word.lower() not in _stopwords:\n            output_list.append(word)\n\n    return output_list", "title": ""}
{"_id": "d20245", "text": "def _increase_file_handle_limit():\n    \"\"\"Raise the open file handles permitted by the Dusty daemon process\n    and its child processes. The number we choose here needs to be within\n    the OS X default kernel hard limit, which is 10240.\"\"\"\n    logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT))\n    resource.setrlimit(resource.RLIMIT_NOFILE,\n                       (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))", "title": ""}
{"_id": "d20246", "text": "def get_longest_orf(orfs):\n    \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n    sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n    return sorted_orf", "title": ""}
{"_id": "d20247", "text": "def pprint_for_ordereddict():\n    \"\"\"\n    Context manager that causes pprint() to print OrderedDict objects as nicely\n    as standard Python dictionary objects.\n    \"\"\"\n    od_saved = OrderedDict.__repr__\n    try:\n        OrderedDict.__repr__ = dict.__repr__\n        yield\n    finally:\n        OrderedDict.__repr__ = od_saved", "title": ""}
{"_id": "d20248", "text": "def strip_xml_namespace(root):\n    \"\"\"Strip out namespace data from an ElementTree.\n\n    This function is recursive and will traverse all\n    subnodes to the root element\n\n    @param root: the root element\n\n    @return: the same root element, minus namespace\n    \"\"\"\n    try:\n        root.tag = root.tag.split('}')[1]\n    except IndexError:\n        pass\n\n    for element in root.getchildren():\n        strip_xml_namespace(element)", "title": ""}
{"_id": "d20249", "text": "def clean_dataframe(df):\n    \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n    df = df.fillna(method='ffill')\n    df = df.fillna(0.0)\n    return df", "title": ""}
{"_id": "d20250", "text": "async def async_input(prompt):\n    \"\"\"\n    Python's ``input()`` is blocking, which means the event loop we set\n    above can't be running while we're blocking there. This method will\n    let the loop run while we wait for input.\n    \"\"\"\n    print(prompt, end='', flush=True)\n    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "title": ""}
{"_id": "d20251", "text": "def find_geom(geom, geoms):\n    \"\"\"\n    Returns the index of a geometry in a list of geometries avoiding\n    expensive equality checks of `in` operator.\n    \"\"\"\n    for i, g in enumerate(geoms):\n        if g is geom:\n            return i", "title": ""}
{"_id": "d20252", "text": "def _get_pretty_string(obj):\n    \"\"\"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\n    \"\"\"\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()", "title": ""}
{"_id": "d20253", "text": "def newest_file(file_iterable):\n  \"\"\"\n  Returns the name of the newest file given an iterable of file names.\n\n  \"\"\"\n  return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "title": ""}
{"_id": "d20254", "text": "def truncate_table(self, tablename):\n        \"\"\"\n        SQLite3 doesn't support direct truncate, so we just use delete here\n        \"\"\"\n        self.get(tablename).remove()\n        self.db.commit()", "title": ""}
{"_id": "d20255", "text": "def find_all(self, string, callback):\n\t\t\"\"\"\n\t\tWrapper on iter method, callback gets an iterator result\n\t\t\"\"\"\n\t\tfor index, output in self.iter(string):\n\t\t\tcallback(index, output)", "title": ""}
{"_id": "d20256", "text": "def __next__(self, reward, ask_id, lbl):\n        \"\"\"For Python3 compatibility of generator.\"\"\"\n        return self.next(reward, ask_id, lbl)", "title": ""}
{"_id": "d20257", "text": "def var_dump(*obs):\n\t\"\"\"\n\t  shows structured information of a object, list, tuple etc\n\t\"\"\"\n\ti = 0\n\tfor x in obs:\n\t\t\n\t\tstr = var_dump_output(x, 0, '  ', '\\n', True)\n\t\tprint (str.strip())\n\t\t\n\t\t#dump(x, 0, i, '', object)\n\t\ti += 1", "title": ""}
{"_id": "d20258", "text": "def _infer_interval_breaks(coord):\n    \"\"\"\n    >>> _infer_interval_breaks(np.arange(5))\n    array([-0.5,  0.5,  1.5,  2.5,  3.5,  4.5])\n\n    Taken from xarray.plotting.plot module\n    \"\"\"\n    coord = np.asarray(coord)\n    deltas = 0.5 * (coord[1:] - coord[:-1])\n    first = coord[0] - deltas[0]\n    last = coord[-1] + deltas[-1]\n    return np.r_[[first], coord[:-1] + deltas, [last]]", "title": ""}
{"_id": "d20259", "text": "def array2string(arr: numpy.ndarray) -> str:\n        \"\"\"Format numpy array as a string.\"\"\"\n        shape = str(arr.shape)[1:-1]\n        if shape.endswith(\",\"):\n            shape = shape[:-1]\n        return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "title": ""}
{"_id": "d20260", "text": "def _assert_is_type(name, value, value_type):\n    \"\"\"Assert that a value must be a given 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__))", "title": ""}
{"_id": "d20261", "text": "def imapchain(*a, **kwa):\n    \"\"\" Like map but also chains the results. \"\"\"\n\n    imap_results = map( *a, **kwa )\n    return itertools.chain( *imap_results )", "title": ""}
{"_id": "d20262", "text": "def add_suffix(fullname, suffix):\n    \"\"\" Add suffix to a full file name\"\"\"\n    name, ext = os.path.splitext(fullname)\n    return name + '_' + suffix + ext", "title": ""}
{"_id": "d20263", "text": "def paginate(self, request, offset=0, limit=None):\n        \"\"\"Paginate queryset.\"\"\"\n        return self.collection.offset(offset).limit(limit), self.collection.count()", "title": ""}
{"_id": "d20264", "text": "def factors(n):\n    \"\"\"\n    Computes all the integer factors of the number `n`\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> import utool as ut\n        >>> result = sorted(ut.factors(10))\n        >>> print(result)\n        [1, 2, 5, 10]\n\n    References:\n        http://stackoverflow.com/questions/6800193/finding-all-the-factors\n    \"\"\"\n    return set(reduce(list.__add__,\n                      ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))", "title": ""}
{"_id": "d20265", "text": "def xmltreefromfile(filename):\n    \"\"\"Internal function to read an XML file\"\"\"\n    try:\n        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n    except TypeError:\n        return ElementTree.parse(filename, ElementTree.XMLParser())", "title": ""}
{"_id": "d20266", "text": "def generate_yaml_file(filename, contents):\n    \"\"\"Creates a yaml file with the given content.\"\"\"\n    with open(filename, 'w') as file:\n        file.write(yaml.dump(contents, default_flow_style=False))", "title": ""}
{"_id": "d20267", "text": "def _go_to_line(editor, line):\n    \"\"\"\n    Move cursor to this line in the current buffer.\n    \"\"\"\n    b = editor.application.current_buffer\n    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "title": ""}
{"_id": "d20268", "text": "def strids2ids(tokens: Iterable[str]) -> List[int]:\n    \"\"\"\n    Returns sequence of integer ids given a sequence of string ids.\n\n    :param tokens: List of integer tokens.\n    :return: List of word ids.\n    \"\"\"\n    return list(map(int, tokens))", "title": ""}
{"_id": "d20269", "text": "def get_domain(url):\n    \"\"\"\n    Get domain part of an url.\n\n    For example: https://www.python.org/doc/ -> https://www.python.org\n    \"\"\"\n    parse_result = urlparse(url)\n    domain = \"{schema}://{netloc}\".format(\n        schema=parse_result.scheme, netloc=parse_result.netloc)\n    return domain", "title": ""}
{"_id": "d20270", "text": "def get_number(s, cast=int):\n    \"\"\"\n    Try to get a number out of a string, and cast it.\n    \"\"\"\n    import string\n    d = \"\".join(x for x in str(s) if x in string.digits)\n    return cast(d)", "title": ""}
{"_id": "d20271", "text": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n    \"\"\"\n    Is the SQLAlchemy column type a string type?\n    \"\"\"\n    coltype = _coltype_to_typeengine(coltype)\n    return isinstance(coltype, sqltypes.String)", "title": ""}
{"_id": "d20272", "text": "def val_to_bin(edges, x):\n    \"\"\"Convert axis coordinate to bin index.\"\"\"\n    ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n    return ibin", "title": ""}
{"_id": "d20273", "text": "def remove_file_from_s3(awsclient, bucket, key):\n    \"\"\"Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:\n    \"\"\"\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)", "title": ""}
{"_id": "d20274", "text": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "title": ""}
{"_id": "d20275", "text": "def _removeTags(tags, objects):\n    \"\"\" Removes tags from objects \"\"\"\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n\n    return True", "title": ""}
{"_id": "d20276", "text": "def RoundToSeconds(cls, timestamp):\n    \"\"\"Takes a timestamp value and rounds it to a second precision.\"\"\"\n    leftovers = timestamp % definitions.MICROSECONDS_PER_SECOND\n    scrubbed = timestamp - leftovers\n    rounded = round(float(leftovers) / definitions.MICROSECONDS_PER_SECOND)\n\n    return int(scrubbed + rounded * definitions.MICROSECONDS_PER_SECOND)", "title": ""}
{"_id": "d20277", "text": "def read_json(location):\n    \"\"\"Open and load JSON from file.\n\n    location (Path): Path to JSON file.\n    RETURNS (dict): Loaded JSON content.\n    \"\"\"\n    location = ensure_path(location)\n    with location.open('r', encoding='utf8') as f:\n        return ujson.load(f)", "title": ""}
{"_id": "d20278", "text": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "title": ""}
{"_id": "d20279", "text": "def __init__(self, function):\n\t\t\"\"\"function: to be called with each stream element as its\n\t\tonly argument\n\t\t\"\"\"\n\t\tsuper(filter, self).__init__()\n\t\tself.function = function", "title": ""}
{"_id": "d20280", "text": "def listlike(obj):\n    \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n    \n    return hasattr(obj, \"__iter__\") \\\n    and not issubclass(type(obj), str)\\\n    and not issubclass(type(obj), unicode)", "title": ""}
{"_id": "d20281", "text": "def _set_scroll_v(self, *args):\n        \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n        self._canvas_categories.yview(*args)\n        self._canvas_scroll.yview(*args)", "title": ""}
{"_id": "d20282", "text": "def to_topojson(self):\n        \"\"\"Adds points and converts to topojson string.\"\"\"\n        topojson = self.topojson\n        topojson[\"objects\"][\"points\"] = {\n            \"type\": \"GeometryCollection\",\n            \"geometries\": [point.to_topojson() for point in self.points.all()],\n        }\n        return json.dumps(topojson)", "title": ""}
{"_id": "d20283", "text": "def getDimensionForImage(filename, maxsize):\n    \"\"\"Return scaled image size in (width, height) format.\n    The scaling preserves the aspect ratio.\n    If PIL is not found returns None.\"\"\"\n    try:\n        from PIL import Image\n    except ImportError:\n        return None\n    img = Image.open(filename)\n    width, height = img.size\n    if width > maxsize[0] or height > maxsize[1]:\n        img.thumbnail(maxsize)\n        out.info(\"Downscaled display size from %s to %s\" % ((width, height), img.size))\n    return img.size", "title": ""}
{"_id": "d20284", "text": "def handleFlaskPostRequest(flaskRequest, endpoint):\n    \"\"\"\n    Handles the specified flask request for one of the POST URLS\n    Invokes the specified endpoint to generate a response.\n    \"\"\"\n    if flaskRequest.method == \"POST\":\n        return handleHttpPost(flaskRequest, endpoint)\n    elif flaskRequest.method == \"OPTIONS\":\n        return handleHttpOptions()\n    else:\n        raise exceptions.MethodNotAllowedException()", "title": ""}
{"_id": "d20285", "text": "def year(date):\n    \"\"\" Returns the year.\n\n    :param date:\n        The string date with this format %m/%d/%Y\n    :type date:\n        String\n\n    :returns:\n        int\n\n    :example:\n        >>> year('05/1/2015')\n        2015\n    \"\"\"\n    try:\n        fmt = '%m/%d/%Y'\n        return datetime.strptime(date, fmt).timetuple().tm_year\n    except ValueError:\n        return 0", "title": ""}
{"_id": "d20286", "text": "def __iter__(self):\n        \"\"\"\n        Returns the list of modes.\n\n        :return:\n        \"\"\"\n        return iter([v for k, v in sorted(self._modes.items())])", "title": ""}
{"_id": "d20287", "text": "def binary(length):\n    \"\"\"\n        returns a a random string that represent a binary representation\n\n    :param length: number of bits\n    \"\"\"\n    num = randint(1, 999999)\n    mask = '0' * length\n    return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]", "title": ""}
{"_id": "d20288", "text": "def smartread(path):\n    \"\"\"Read text from file, automatically detect encoding. ``chardet`` required.\n    \"\"\"\n    with open(path, \"rb\") as f:\n        content = f.read()\n        result = chardet.detect(content)\n        return content.decode(result[\"encoding\"])", "title": ""}
{"_id": "d20289", "text": "def connect_rds(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):\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.rds.RDSConnection`\n    :return: A connection to RDS\n    \"\"\"\n    from boto.rds import RDSConnection\n    return RDSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)", "title": ""}
{"_id": "d20290", "text": "def is_empty(self):\n        \"\"\"Checks for an empty image.\n        \"\"\"\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)", "title": ""}
{"_id": "d20291", "text": "def hide(self):\n        \"\"\"Hides the main window of the terminal and sets the visible\n        flag to False.\n        \"\"\"\n        if not HidePrevention(self.window).may_hide():\n            return\n        self.hidden = True\n        self.get_widget('window-root').unstick()\n        self.window.hide()", "title": ""}
{"_id": "d20292", "text": "def validate(schema, data, owner=None):\n    \"\"\"Validate input data with input schema.\n\n    :param Schema schema: schema able to validate input data.\n    :param data: data to validate.\n    :param Schema owner: input schema parent schema.\n    :raises: Exception if the data is not validated.\n    \"\"\"\n    schema._validate(data=data, owner=owner)", "title": ""}
{"_id": "d20293", "text": "def stringify_col(df, col_name):\n    \"\"\"\n    Take a dataframe and string-i-fy a column of values.\n    Turn nan/None into \"\" and all other values into strings.\n\n    Parameters\n    ----------\n    df : dataframe\n    col_name : string\n    \"\"\"\n    df = df.copy()\n    df[col_name] = df[col_name].fillna(\"\")\n    df[col_name] = df[col_name].astype(str)\n    return df", "title": ""}
{"_id": "d20294", "text": "def split_strings_in_list_retain_spaces(orig_list):\n    \"\"\"\n    Function to split every line in a list, and retain spaces for a rejoin\n    :param orig_list: Original list\n    :return:\n        A List with split lines\n\n    \"\"\"\n    temp_list = list()\n    for line in orig_list:\n        line_split = __re.split(r'(\\s+)', line)\n        temp_list.append(line_split)\n\n    return temp_list", "title": ""}
{"_id": "d20295", "text": "def safe_int(val, default=None):\n    \"\"\"\n    Returns int() of val if val is not convertable to int use default\n    instead\n\n    :param val:\n    :param default:\n    \"\"\"\n\n    try:\n        val = int(val)\n    except (ValueError, TypeError):\n        val = default\n\n    return val", "title": ""}
{"_id": "d20296", "text": "def keys_to_snake_case(camel_case_dict):\n    \"\"\"\n    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.\n    \"\"\"\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "title": ""}
{"_id": "d20297", "text": "def equal(list1, list2):\n    \"\"\" takes flags returns indexes of True values \"\"\"\n    return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]", "title": ""}
{"_id": "d20298", "text": "def process_request(self, request, response):\n        \"\"\"Logs the basic endpoint requested\"\"\"\n        self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))", "title": ""}
{"_id": "d20299", "text": "def glr_path_static():\n    \"\"\"Returns path to packaged static files\"\"\"\n    return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))", "title": ""}
{"_id": "d20300", "text": "def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:\n    \"\"\"\n    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\n    \"\"\"\n    jsonschema_validate(request, schema)\n    return request", "title": ""}
{"_id": "d20301", "text": "def good(txt):\n    \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n    print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n    sys.stdout.flush()", "title": ""}
{"_id": "d20302", "text": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n    \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "title": ""}
{"_id": "d20303", "text": "def im2mat(I):\n    \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n    return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "title": ""}
{"_id": "d20304", "text": "def sometimesish(fn):\n    \"\"\"\n    Has a 50/50 chance of calling a function\n    \"\"\"\n    def wrapped(*args, **kwargs):\n        if random.randint(1, 2) == 1:\n            return fn(*args, **kwargs)\n\n    return wrapped", "title": ""}
{"_id": "d20305", "text": "def wait(self, timeout=None):\n    \"\"\"\n    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.\n    \"\"\"\n\n    if not self.__running:\n      raise RuntimeError(\"ThreadPool ain't running\")\n    self.__queue.wait(timeout)", "title": ""}
{"_id": "d20306", "text": "def seconds(num):\n    \"\"\"\n    Pause for this many seconds\n    \"\"\"\n    now = pytime.time()\n    end = now + num\n    until(end)", "title": ""}
{"_id": "d20307", "text": "def str_to_time(time_str: str) -> datetime.datetime:\n    \"\"\"\n    Convert human readable string to datetime.datetime.\n    \"\"\"\n    pieces: Any = [int(piece) for piece in time_str.split('-')]\n    return datetime.datetime(*pieces)", "title": ""}
{"_id": "d20308", "text": "def is_executable(path):\n  \"\"\"Returns whether a path names an existing executable file.\"\"\"\n  return os.path.isfile(path) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d20309", "text": "def full(self):\n        \"\"\"Return ``True`` if the queue is full, ``False``\n        otherwise (not reliable!).\n\n        Only applicable if :attr:`maxsize` is set.\n\n        \"\"\"\n        return self.maxsize and len(self.list) >= self.maxsize or False", "title": ""}
{"_id": "d20310", "text": "def search(self, filterstr, attrlist):\n        \"\"\"Query the configured LDAP server.\"\"\"\n        return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr,\n                                        attrlist=attrlist, page_size=self.settings.PAGE_SIZE)", "title": ""}
{"_id": "d20311", "text": "def fill_document(doc):\n    \"\"\"Add a section, a subsection and some text to the document.\n\n    :param doc: the document\n    :type doc: :class:`pylatex.document.Document` instance\n    \"\"\"\n    with doc.create(Section('A section')):\n        doc.append('Some regular text and some ')\n        doc.append(italic('italic text. '))\n\n        with doc.create(Subsection('A subsection')):\n            doc.append('Also some crazy characters: $&#{}')", "title": ""}
{"_id": "d20312", "text": "def _serialize_json(obj, fp):\n    \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n    json.dump(obj, fp, indent=4, default=serialize)", "title": ""}
{"_id": "d20313", "text": "def last_location_of_minimum(x):\n    \"\"\"\n    Returns the last 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\n    \"\"\"\n    x = np.asarray(x)\n    return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "title": ""}
{"_id": "d20314", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d20315", "text": "def expect_all(a, b):\n    \"\"\"\\\n    Asserts that two iterables contain the same values.\n    \"\"\"\n    assert all(_a == _b for _a, _b in zip_longest(a, b))", "title": ""}
{"_id": "d20316", "text": "def load(self):\n        \"\"\"Load proxy list from configured proxy source\"\"\"\n        self._list = self._source.load()\n        self._list_iter = itertools.cycle(self._list)", "title": ""}
{"_id": "d20317", "text": "def lognorm(x, mu, sigma=1.0):\n    \"\"\" Log-normal function from scipy \"\"\"\n    return stats.lognorm(sigma, scale=mu).pdf(x)", "title": ""}
{"_id": "d20318", "text": "def gcd_float(numbers, tol=1e-8):\n    \"\"\"\n    Returns the greatest common divisor for a sequence of numbers.\n    Uses a numerical tolerance, so can be used on floats\n\n    Args:\n        numbers: Sequence of numbers.\n        tol: Numerical tolerance\n\n    Returns:\n        (int) Greatest common divisor of numbers.\n    \"\"\"\n\n    def pair_gcd_tol(a, b):\n        \"\"\"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).\n        \"\"\"\n        while b > tol:\n            a, b = b, a % b\n        return a\n\n    n = numbers[0]\n    for i in numbers:\n        n = pair_gcd_tol(n, i)\n    return n", "title": ""}
{"_id": "d20319", "text": "def Flush(self):\n    \"\"\"Flush all items from cache.\"\"\"\n    while self._age:\n      node = self._age.PopLeft()\n      self.KillObject(node.data)\n\n    self._hash = dict()", "title": ""}
{"_id": "d20320", "text": "def vector_distance(a, b):\n    \"\"\"The Euclidean distance between two vectors.\"\"\"\n    a = np.array(a)\n    b = np.array(b)\n    return np.linalg.norm(a - b)", "title": ""}
{"_id": "d20321", "text": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "title": ""}
{"_id": "d20322", "text": "def from_years_range(start_year, end_year):\n        \"\"\"Transform a range of years (two ints) to a DateRange object.\"\"\"\n        start = datetime.date(start_year, 1 , 1)\n        end = datetime.date(end_year, 12 , 31)\n        return DateRange(start, end)", "title": ""}
{"_id": "d20323", "text": "def safe_dump(data, stream=None, **kwds):\n    \"\"\"implementation of safe dumper using Ordered Dict Yaml Dumper\"\"\"\n    return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)", "title": ""}
{"_id": "d20324", "text": "def is_array(type_):\n    \"\"\"returns True, if type represents C++ array type, False otherwise\"\"\"\n    nake_type = remove_alias(type_)\n    nake_type = remove_reference(nake_type)\n    nake_type = remove_cv(nake_type)\n    return isinstance(nake_type, cpptypes.array_t)", "title": ""}
{"_id": "d20325", "text": "def apply(self, func, args=(), kwds=dict()):\n        \"\"\"Equivalent of the apply() builtin function. It blocks till\n        the result is ready.\"\"\"\n        return self.apply_async(func, args, kwds).get()", "title": ""}
{"_id": "d20326", "text": "def reload(self, save_config=True):\n        \"\"\"Reload the device.\n\n        !!!WARNING! there is unsaved configuration!!!\n        This command will reboot the system. (y/n)?  [n]\n        \"\"\"\n        if save_config:\n            self.device.send(\"copy running-config startup-config\")\n        self.device(\"reload\", wait_for_string=\"This command will reboot the system\")\n        self.device.ctrl.sendline(\"y\")", "title": ""}
{"_id": "d20327", "text": "def _split_str(s, n):\n    \"\"\"\n    split string into list of strings by specified number.\n    \"\"\"\n    length = len(s)\n    return [s[i:i + n] for i in range(0, length, n)]", "title": ""}
{"_id": "d20328", "text": "def conv_dict(self):\n        \"\"\"dictionary of conversion\"\"\"\n        return dict(integer=self.integer, real=self.real, no_type=self.no_type)", "title": ""}
{"_id": "d20329", "text": "def to_0d_array(value: Any) -> np.ndarray:\n    \"\"\"Given a value, wrap it in a 0-D numpy.ndarray.\n    \"\"\"\n    if np.isscalar(value) or (isinstance(value, np.ndarray) and\n                              value.ndim == 0):\n        return np.array(value)\n    else:\n        return to_0d_object_array(value)", "title": ""}
{"_id": "d20330", "text": "def get_tokens(line: str) -> Iterator[str]:\n    \"\"\"\n    Yields tokens from input string.\n\n    :param line: Input string.\n    :return: Iterator over tokens.\n    \"\"\"\n    for token in line.rstrip().split():\n        if len(token) > 0:\n            yield token", "title": ""}
{"_id": "d20331", "text": "def write_fits(self, fitsfile):\n        \"\"\"Write the ROI model to a FITS file.\"\"\"\n\n        tab = self.create_table()\n        hdu_data = fits.table_to_hdu(tab)\n        hdus = [fits.PrimaryHDU(), hdu_data]\n        fits_utils.write_hdus(hdus, fitsfile)", "title": ""}
{"_id": "d20332", "text": "def ansi(color, text):\n    \"\"\"Wrap text in an ansi escape sequence\"\"\"\n    code = COLOR_CODES[color]\n    return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)", "title": ""}
{"_id": "d20333", "text": "def has_value(cls, value: int) -> bool:\n        \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n        return any(value == item.value for item in cls)", "title": ""}
{"_id": "d20334", "text": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "title": ""}
{"_id": "d20335", "text": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n    \"\"\"\n    Return a new copied dictionary without the keys with ``None`` values from\n    the given Mapping object.\n    \"\"\"\n    return {k: v for k, v in obj.items() if v is not None}", "title": ""}
{"_id": "d20336", "text": "def parse_query_string(query):\n    \"\"\"\n    parse_query_string:\n    very simplistic. won't do the right thing with list values\n    \"\"\"\n    result = {}\n    qparts = query.split('&')\n    for item in qparts:\n        key, value = item.split('=')\n        key = key.strip()\n        value = value.strip()\n        result[key] = unquote_plus(value)\n    return result", "title": ""}
{"_id": "d20337", "text": "def isolate_element(self, x):\n        \"\"\"Isolates `x` from its equivalence class.\"\"\"\n        members = list(self.members(x))\n        self.delete_set(x)\n        self.union(*(v for v in members if v != x))", "title": ""}
{"_id": "d20338", "text": "def _manhattan_distance(vec_a, vec_b):\n    \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n    if len(vec_a) != len(vec_b):\n        raise ValueError('len(vec_a) must equal len(vec_b)')\n    return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "title": ""}
{"_id": "d20339", "text": "def get_list_from_file(file_name):\n    \"\"\"read the lines from a file into a list\"\"\"\n    with open(file_name, mode='r', encoding='utf-8') as f1:\n        lst = f1.readlines()\n    return lst", "title": ""}
{"_id": "d20340", "text": "def update(self, params):\n        \"\"\"Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device.\n        \"\"\"\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "title": ""}
{"_id": "d20341", "text": "def right_replace(string, old, new, count=1):\n    \"\"\"\n    Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.\n    For example::\n\n        right_replace('one_two_two', 'two', 'three') -> 'one_two_three'\n    \"\"\"\n    if not string:\n        return string\n    return new.join(string.rsplit(old, count))", "title": ""}
{"_id": "d20342", "text": "def _writable_dir(path):\n    \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n    return os.path.isdir(path) and os.access(path, os.W_OK)", "title": ""}
{"_id": "d20343", "text": "def get_attribute_name_id(attr):\n    \"\"\"\n    Return the attribute name identifier\n    \"\"\"\n    return attr.value.id if isinstance(attr.value, ast.Name) else None", "title": ""}
{"_id": "d20344", "text": "def object_as_dict(obj):\n    \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n    Based on https://stackoverflow.com/a/37350445/1579058\n    \"\"\"\n    return {c.key: getattr(obj, c.key)\n            for c in inspect(obj).mapper.column_attrs}", "title": ""}
{"_id": "d20345", "text": "def fetchvalue(self, sql: str, *args) -> Optional[Any]:\n        \"\"\"Executes SQL; returns the first value of the first row, or None.\"\"\"\n        row = self.fetchone(sql, *args)\n        if row is None:\n            return None\n        return row[0]", "title": ""}
{"_id": "d20346", "text": "def add_url_rule(self, route, endpoint, handler):\n        \"\"\"Add a new url route.\n\n        Args:\n            See flask.Flask.add_url_route().\n        \"\"\"\n        self.app.add_url_rule(route, endpoint, handler)", "title": ""}
{"_id": "d20347", "text": "def get_default_args(func):\n    \"\"\"\n    returns a dictionary of arg_name:default_values for the input function\n    \"\"\"\n    args, varargs, keywords, defaults = getargspec_no_self(func)\n    return dict(zip(args[-len(defaults):], defaults))", "title": ""}
{"_id": "d20348", "text": "def get_shape(img):\n    \"\"\"Return the shape of img.\n\n    Paramerers\n    -----------\n    img:\n\n    Returns\n    -------\n    shape: tuple\n    \"\"\"\n    if hasattr(img, 'shape'):\n        shape = img.shape\n    else:\n        shape = img.get_data().shape\n    return shape", "title": ""}
{"_id": "d20349", "text": "def _fill(self):\n    \"\"\"Advance the iterator without returning the old head.\"\"\"\n    try:\n      self._head = self._iterable.next()\n    except StopIteration:\n      self._head = None", "title": ""}
{"_id": "d20350", "text": "def drop_bad_characters(text):\n    \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n    also any whitespace characters that aren't space.\n\n    :arg str text: the text to fix\n\n    :returns: text with all bad characters dropped\n\n    \"\"\"\n    # Strip all non-ascii and non-printable characters\n    text = ''.join([c for c in text if c in ALLOWED_CHARS])\n    return text", "title": ""}
{"_id": "d20351", "text": "def getBitmap(self):\n        \"\"\" Captures screen area of this region, at least the part that is on the screen\n\n        Returns image as numpy array\n        \"\"\"\n        return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h)", "title": ""}
{"_id": "d20352", "text": "def setup_environment():\n    \"\"\"Set up neccessary environment variables\n\n    This appends all path of sys.path to the python path\n    so mayapy will find all installed modules.\n    We have to make sure, that we use maya libs instead of\n    libs of the virtual env. So we insert all the libs for mayapy\n    first.\n\n    :returns: None\n    :rtype: None\n    :raises: None\n    \"\"\"\n    osinter = ostool.get_interface()\n    pypath = osinter.get_maya_envpath()\n    for p in sys.path:\n        pypath = os.pathsep.join((pypath, p))\n    os.environ['PYTHONPATH'] = pypath", "title": ""}
{"_id": "d20353", "text": "def uppercase_chars(string: any) -> str:\n        \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n        return ''.join([c if c.isupper() else '' for c in str(string)])", "title": ""}
{"_id": "d20354", "text": "def remove_once(gset, elem):\n    \"\"\"Remove the element from a set, lists or dict.\n    \n        >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n        >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n        >>> print L, S, D\n        [] set([]) {}\n\n    Returns the element if it was removed. Raises one of the exceptions in \n    :obj:`RemoveError` otherwise.\n    \"\"\"\n    remove = getattr(gset, 'remove', None)\n    if remove is not None: remove(elem)\n    else: del gset[elem]\n    return elem", "title": ""}
{"_id": "d20355", "text": "def get_last_commit(git_path=None):\n    \"\"\"\n    Get the HEAD commit SHA1 of repository in current dir.\n    \"\"\"\n    if git_path is None: git_path = GIT_PATH\n    line = get_last_commit_line(git_path)\n    revision_id = line.split()[1]\n    return revision_id", "title": ""}
{"_id": "d20356", "text": "def do_restart(self, line):\n        \"\"\"Request that the Outstation perform a cold restart. Command syntax is: restart\"\"\"\n        self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)", "title": ""}
{"_id": "d20357", "text": "def __run(self):\n    \"\"\"Hacked run function, which installs the trace.\"\"\"\n    sys.settrace(self.globaltrace)\n    self.__run_backup()\n    self.run = self.__run_backup", "title": ""}
{"_id": "d20358", "text": "def clean(dry_run='n'):\n    \"\"\"Wipes compiled and cached python files. To simulate: pynt clean[dry_run=y]\"\"\"\n    file_patterns = ['*.pyc', '*.pyo', '*~']\n    dir_patterns = ['__pycache__']\n    recursive_pattern_delete(project_paths.root, file_patterns, dir_patterns, dry_run=bool(dry_run.lower() == 'y'))", "title": ""}
{"_id": "d20359", "text": "def test3():\n    \"\"\"Test the multiprocess\n    \"\"\"\n    import time\n    \n    p = MVisionProcess()\n    p.start()\n    time.sleep(5)\n    p.stop()", "title": ""}
{"_id": "d20360", "text": "def walk_tree(root):\n    \"\"\"Pre-order depth-first\"\"\"\n    yield root\n\n    for child in root.children:\n        for el in walk_tree(child):\n            yield el", "title": ""}
{"_id": "d20361", "text": "def timeit(func, *args, **kwargs):\n    \"\"\"\n    Time execution of function. Returns (res, seconds).\n\n    >>> res, timing = timeit(time.sleep, 1)\n    \"\"\"\n    start_time = time.time()\n    res = func(*args, **kwargs)\n    timing = time.time() - start_time\n    return res, timing", "title": ""}
{"_id": "d20362", "text": "def stop(self):\n        \"\"\"Stops playback\"\"\"\n        if self.isPlaying is True:\n            self._execute(\"stop\")\n            self._changePlayingState(False)", "title": ""}
{"_id": "d20363", "text": "def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, change\n    (in place) ``d[key]`` to ``value``.\n    \"\"\"\n    for d in dict_list:\n        d[key] = value", "title": ""}
{"_id": "d20364", "text": "def do(self):\n        \"\"\"\n        Set a restore point (copy the object), then call the method.\n        :return: obj.do_method(*args)\n        \"\"\"\n        self.restore_point = self.obj.copy()\n        return self.do_method(self.obj, *self.args)", "title": ""}
{"_id": "d20365", "text": "def read_raw(data_path):\n    \"\"\"\n    Parameters\n    ----------\n    data_path : str\n    \"\"\"\n    with open(data_path, 'rb') as f:\n        data = pickle.load(f)\n    return data", "title": ""}
{"_id": "d20366", "text": "def cross_join(df1, df2):\n    \"\"\"\n    Return a dataframe that is a cross between dataframes\n    df1 and df2\n\n    ref: https://github.com/pydata/pandas/issues/5401\n    \"\"\"\n    if len(df1) == 0:\n        return df2\n\n    if len(df2) == 0:\n        return df1\n\n    # Add as lists so that the new index keeps the items in\n    # the order that they are added together\n    all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n    df1['key'] = 1\n    df2['key'] = 1\n    return pd.merge(df1, df2, on='key').loc[:, all_columns]", "title": ""}
{"_id": "d20367", "text": "def flatten(nested):\n    \"\"\" Return a flatten version of the nested argument \"\"\"\n    flat_return = list()\n\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\n    __inner_flat(nested,flat_return)\n\n    return flat_return", "title": ""}
{"_id": "d20368", "text": "def indented_show(text, howmany=1):\n        \"\"\"Print a formatted indented text.\n        \"\"\"\n        print(StrTemplate.pad_indent(text=text, howmany=howmany))", "title": ""}
{"_id": "d20369", "text": "def list_get(l, idx, default=None):\n    \"\"\"\n    Get from a list with an optional default value.\n    \"\"\"\n    try:\n        if l[idx]:\n            return l[idx]\n        else:\n            return default\n    except IndexError:\n        return default", "title": ""}
{"_id": "d20370", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d20371", "text": "def A(*a):\n    \"\"\"convert iterable object into numpy array\"\"\"\n    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "title": ""}
{"_id": "d20372", "text": "def read_set_from_file(filename: str) -> Set[str]:\n    \"\"\"\n    Extract a de-duped collection (set) of text from a file.\n    Expected file format is one item per line.\n    \"\"\"\n    collection = set()\n    with open(filename, 'r') as file_:\n        for line in file_:\n            collection.add(line.rstrip())\n    return collection", "title": ""}
{"_id": "d20373", "text": "def intround(value):\n    \"\"\"Given a float returns a rounded int. Should give the same result on\n    both Py2/3\n    \"\"\"\n\n    return int(decimal.Decimal.from_float(\n        value).to_integral_value(decimal.ROUND_HALF_EVEN))", "title": ""}
{"_id": "d20374", "text": "def __init__(self):\n        \"\"\"__init__: Performs basic initialisations\"\"\"\n        # Root parser\n        self.parser = argparse.ArgumentParser()\n        # Subparsers\n        self.subparsers = self.parser.add_subparsers()\n        # Parser dictionary, to avoir overwriting existing parsers\n        self.parsers = {}", "title": ""}
{"_id": "d20375", "text": "def nonull_dict(self):\n        \"\"\"Like dict, but does not hold any null values.\n\n        :return:\n\n        \"\"\"\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "title": ""}
{"_id": "d20376", "text": "def get_stripped_file_lines(filename):\n    \"\"\"\n    Return lines of a file with whitespace removed\n    \"\"\"\n    try:\n        lines = open(filename).readlines()\n    except FileNotFoundError:\n        fatal(\"Could not open file: {!r}\".format(filename))\n\n    return [line.strip() for line in lines]", "title": ""}
{"_id": "d20377", "text": "def generate_hash(filepath):\n    \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n    fr = FileReader(filepath)\n    data = fr.read_bin()\n    return _calculate_sha256(data)", "title": ""}
{"_id": "d20378", "text": "def parse_func_kwarg_keys(func, with_vals=False):\n    \"\"\" hacky inference of kwargs keys\n\n    SeeAlso:\n        argparse_funckw\n        recursive_parse_kwargs\n        parse_kwarg_keys\n        parse_func_kwarg_keys\n        get_func_kwargs\n\n    \"\"\"\n    sourcecode = get_func_sourcecode(func, strip_docstr=True,\n                                     strip_comments=True)\n    kwkeys = parse_kwarg_keys(sourcecode, with_vals=with_vals)\n    #ut.get_func_kwargs  TODO\n    return kwkeys", "title": ""}
{"_id": "d20379", "text": "def extract_words(lines):\n    \"\"\"\n    Extract from the given iterable of lines the list of words.\n\n    :param lines: an iterable of lines;\n    :return: a generator of words of lines.\n    \"\"\"\n    for line in lines:\n        for word in re.findall(r\"\\w+\", line):\n            yield word", "title": ""}
{"_id": "d20380", "text": "def put(self, endpoint: str, **kwargs) -> dict:\n        \"\"\"HTTP PUT operation to API endpoint.\"\"\"\n\n        return self._request('PUT', endpoint, **kwargs)", "title": ""}
{"_id": "d20381", "text": "def threadid(self):\n        \"\"\"\n        Current thread ident. If current thread is main thread then it returns ``None``.\n\n        :type: int or None\n        \"\"\"\n        current = self.thread.ident\n        main = get_main_thread()\n        if main is None:\n            return current\n        else:\n            return current if current != main.ident else None", "title": ""}
{"_id": "d20382", "text": "def filtany(entities, **kw):\n  \"\"\"Filter a set of entities based on method return. Use keyword arguments.\n  \n  Example:\n    filtmeth(entities, id='123')\n    filtmeth(entities, name='bart')\n\n  Multiple filters are 'OR'.\n  \"\"\"\n  ret = set()\n  for k,v in kw.items():\n    for entity in entities:\n      if getattr(entity, k)() == v:\n        ret.add(entity)\n  return ret", "title": ""}
{"_id": "d20383", "text": "def flatten_list(x: List[Any]) -> List[Any]:\n    \"\"\"\n    Converts a list of lists into a flat list.\n    \n    Args:\n        x: list of lists \n\n    Returns:\n        flat list\n        \n    As per\n    http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n    \"\"\"  # noqa\n    return [item for sublist in x for item in sublist]", "title": ""}
{"_id": "d20384", "text": "def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]:\n    \"\"\" Write a numpy array to YAML.\n\n    It registers the array under the tag ``!numpy_array``.\n\n    Use with:\n\n    .. code-block:: python\n\n        >>> yaml = ruamel.yaml.YAML()\n        >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml)\n\n    Note:\n        We cannot use ``yaml.register_class`` because it won't register the proper type.\n        (It would register the type of the class, rather than of `numpy.ndarray`). Instead,\n        we use the above approach to register this method explicitly with the representer.\n    \"\"\"\n    return representer.represent_sequence(\n        \"!numpy_array\",\n        data.tolist()\n    )", "title": ""}
{"_id": "d20385", "text": "def get_user_by_id(self, id):\n        \"\"\"Retrieve a User object by ID.\"\"\"\n        return self.db_adapter.get_object(self.UserClass, id=id)", "title": ""}
{"_id": "d20386", "text": "def count(args):\n    \"\"\" count occurences in a list of lists\n    >>> count([['a','b'],['a']])\n    defaultdict(int, {'a' : 2, 'b' : 1})\n    \"\"\"\n    counts = defaultdict(int)\n    for arg in args:\n        for item in arg:\n            counts[item] = counts[item] + 1\n    return counts", "title": ""}
{"_id": "d20387", "text": "def qsize(self):\n        \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n        self.mutex.acquire()\n        n = self._qsize()\n        self.mutex.release()\n        return n", "title": ""}
{"_id": "d20388", "text": "def impute_data(self,x):\n        \"\"\"Imputes data set containing Nan values\"\"\"\n        imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n        return imp.fit_transform(x)", "title": ""}
{"_id": "d20389", "text": "def revrank_dict(dict, key=lambda t: t[1], as_tuple=False):\n    \"\"\" Reverse sorts a #dict by a given key, optionally returning it as a\n        #tuple. By default, the @dict is sorted by it's value.\n\n        @dict: the #dict you wish to sorts\n        @key: the #sorted key to use\n        @as_tuple: returns result as a #tuple ((k, v),...)\n\n        -> :class:OrderedDict or #tuple\n    \"\"\"\n    sorted_list = sorted(dict.items(), key=key, reverse=True)\n    return OrderedDict(sorted_list) if not as_tuple else tuple(sorted_list)", "title": ""}
{"_id": "d20390", "text": "def generate_unique_host_id():\n    \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n    instances running at the same time.\"\"\"\n    host = \".\".join(reversed(socket.gethostname().split(\".\")))\n    pid = os.getpid()\n    return \"%s.%d\" % (host, pid)", "title": ""}
{"_id": "d20391", "text": "def MatrixInverse(a, adj):\n    \"\"\"\n    Matrix inversion op.\n    \"\"\"\n    return np.linalg.inv(a if not adj else _adjoint(a)),", "title": ""}
{"_id": "d20392", "text": "def norm_slash(name):\n    \"\"\"Normalize path slashes.\"\"\"\n\n    if isinstance(name, str):\n        return name.replace('/', \"\\\\\") if not is_case_sensitive() else name\n    else:\n        return name.replace(b'/', b\"\\\\\") if not is_case_sensitive() else name", "title": ""}
{"_id": "d20393", "text": "def compose(func_list):\n    \"\"\"\n    composion of preprocessing functions\n    \"\"\"\n\n    def f(G, bim):\n        for func in func_list:\n            G, bim = func(G, bim)\n        return G, bim\n\n    return f", "title": ""}
{"_id": "d20394", "text": "def _kbhit_unix() -> bool:\n    \"\"\"\n    Under UNIX: is a keystroke available?\n    \"\"\"\n    dr, dw, de = select.select([sys.stdin], [], [], 0)\n    return dr != []", "title": ""}
{"_id": "d20395", "text": "def getRandomBinaryTreeLeafNode(binaryTree):\n    \"\"\"Get random binary tree node.\n    \"\"\"\n    if binaryTree.internal == True:\n        if random.random() > 0.5:\n            return getRandomBinaryTreeLeafNode(binaryTree.left)\n        else:\n            return getRandomBinaryTreeLeafNode(binaryTree.right)\n    else:\n        return binaryTree", "title": ""}
{"_id": "d20396", "text": "def _dt_to_epoch(dt):\n        \"\"\"Convert datetime to epoch seconds.\"\"\"\n        try:\n            epoch = dt.timestamp()\n        except AttributeError:  # py2\n            epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n        return epoch", "title": ""}
{"_id": "d20397", "text": "def get_user_name():\n    \"\"\"Get user name provide by operating system\n    \"\"\"\n\n    if sys.platform == 'win32':\n        #user = os.getenv('USERPROFILE')\n        user = os.getenv('USERNAME')\n    else:\n        user = os.getenv('LOGNAME')\n\n    return user", "title": ""}
{"_id": "d20398", "text": "def __next__(self):\n    \"\"\"Pop the head off the iterator and return it.\"\"\"\n    res = self._head\n    self._fill()\n    if res is None:\n      raise StopIteration()\n    return res", "title": ""}
{"_id": "d20399", "text": "def check_create_folder(filename):\n    \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n    os.makedirs(os.path.dirname(filename), exist_ok=True)", "title": ""}
{"_id": "d20400", "text": "def is_relative_url(url):\n    \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n    if url.startswith(\"#\"):\n        return None\n    if url.find(\"://\") > 0 or url.startswith(\"//\"):\n        # either 'http(s)://...' or '//cdn...' and therefore absolute\n        return False\n    return True", "title": ""}
{"_id": "d20401", "text": "def to_snake_case(text):\n    \"\"\"Convert to snake case.\n\n    :param str text:\n    :rtype: str\n    :return:\n    \"\"\"\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "title": ""}
{"_id": "d20402", "text": "def println(msg):\n    \"\"\"\n    Convenience function to print messages on a single line in the terminal\n    \"\"\"\n    sys.stdout.write(msg)\n    sys.stdout.flush()\n    sys.stdout.write('\\x08' * len(msg))\n    sys.stdout.flush()", "title": ""}
{"_id": "d20403", "text": "def force_iterable(f):\n    \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n    def wrapper(*args, **kwargs):\n        r = f(*args, **kwargs)\n        if hasattr(r, '__iter__'):\n            return r\n        else:\n            return [r]\n    return wrapper", "title": ""}
{"_id": "d20404", "text": "def _float_feature(value):\n  \"\"\"Wrapper for inserting float features into Example proto.\"\"\"\n  if not isinstance(value, list):\n    value = [value]\n  return tf.train.Feature(float_list=tf.train.FloatList(value=value))", "title": ""}
{"_id": "d20405", "text": "def _interval_to_bound_points(array):\n    \"\"\"\n    Helper function which returns an array\n    with the Intervals' boundaries.\n    \"\"\"\n\n    array_boundaries = np.array([x.left for x in array])\n    array_boundaries = np.concatenate(\n        (array_boundaries, np.array([array[-1].right])))\n\n    return array_boundaries", "title": ""}
{"_id": "d20406", "text": "def commajoin_as_strings(iterable):\n    \"\"\" Join the given iterable with ',' \"\"\"\n    return _(u',').join((six.text_type(i) for i in iterable))", "title": ""}
{"_id": "d20407", "text": "def checkbox_uncheck(self, force_check=False):\n        \"\"\"\n        Wrapper to uncheck a checkbox\n        \"\"\"\n        if self.get_attribute('checked'):\n            self.click(force_click=force_check)", "title": ""}
{"_id": "d20408", "text": "def _requiredSize(shape, dtype):\n\t\"\"\"\n\tDetermines the number of bytes required to store a NumPy array with\n\tthe specified shape and datatype.\n\t\"\"\"\n\treturn math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)", "title": ""}
{"_id": "d20409", "text": "def csv_to_numpy(string_like, dtype=None):  # type: (str) -> np.array\n    \"\"\"Convert a CSV object to a numpy array.\n\n    Args:\n        string_like (str): CSV string.\n        dtype (dtype, optional):  Data type of the resulting array. If None, the dtypes will be determined by the\n                                        contents of each column, individually. This argument can only be used to\n                                        'upcast' the array.  For downcasting, use the .astype(t) method.\n    Returns:\n        (np.array): numpy array\n    \"\"\"\n    stream = StringIO(string_like)\n    return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "title": ""}
{"_id": "d20410", "text": "def remove_elements(target, indices):\n    \"\"\"Remove multiple elements from a list and return result.\n    This implementation is faster than the alternative below.\n    Also note the creation of a new list to avoid altering the\n    original. We don't have any current use for the original\n    intact list, but may in the future...\"\"\"\n\n    copied = list(target)\n\n    for index in reversed(indices):\n        del copied[index]\n    return copied", "title": ""}
{"_id": "d20411", "text": "def get_propety_by_name(pif, name):\n    \"\"\"Get a property by name\"\"\"\n    warn(\"This method has been deprecated in favor of get_property_by_name\")\n    return next((x for x in pif.properties if x.name == name), None)", "title": ""}
{"_id": "d20412", "text": "def is_in(self, search_list, pair):\n        \"\"\"\n        If pair is in search_list, return the index. Otherwise return -1\n        \"\"\"\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index", "title": ""}
{"_id": "d20413", "text": "def _is_iterable(item):\n    \"\"\" Checks if an item is iterable (list, tuple, generator), but not string \"\"\"\n    return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)", "title": ""}
{"_id": "d20414", "text": "def get_from_gnucash26_date(date_str: str) -> date:\n    \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n    date_format = \"%Y%m%d\"\n    result = datetime.strptime(date_str, date_format).date()\n    return result", "title": ""}
{"_id": "d20415", "text": "def prepend_line(filepath, line):\n    \"\"\"Rewrite a file adding a line to its beginning.\n    \"\"\"\n    with open(filepath) as f:\n        lines = f.readlines()\n\n    lines.insert(0, line)\n\n    with open(filepath, 'w') as f:\n        f.writelines(lines)", "title": ""}
{"_id": "d20416", "text": "def _split(string, splitters):\n    \"\"\"Splits a string into parts at multiple characters\"\"\"\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", "title": ""}
{"_id": "d20417", "text": "def index(self, item):\n        \"\"\" Not recommended for use on large lists due to time\n            complexity, but it works\n\n            -> #int list index of @item\n        \"\"\"\n        for i, x in enumerate(self.iter()):\n            if x == item:\n                return i\n        return None", "title": ""}
{"_id": "d20418", "text": "def _dotify(cls, data):\n    \"\"\"Add dots.\"\"\"\n    return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "title": ""}
{"_id": "d20419", "text": "def pop(h):\n    \"\"\"Pop the heap value from the heap.\"\"\"\n    n = h.size() - 1\n    h.swap(0, n)\n    down(h, 0, n)\n    return h.pop()", "title": ""}
{"_id": "d20420", "text": "def cprint(string, fg=None, bg=None, end='\\n', target=sys.stdout):\n    \"\"\"Print a colored string to the target handle.\n\n    fg and bg specify foreground- and background colors, respectively. The\n    remaining keyword arguments are the same as for Python's built-in print\n    function. Colors are returned to their defaults before the function\n    returns.\n\n    \"\"\"\n    _color_manager.set_color(fg, bg)\n    target.write(string + end)\n    target.flush()  # Needed for Python 3.x\n    _color_manager.set_defaults()", "title": ""}
{"_id": "d20421", "text": "def visit_BinOp(self, node):\n        \"\"\" Return type depend from both operand of the binary operation. \"\"\"\n        args = [self.visit(arg) for arg in (node.left, node.right)]\n        return list({frozenset.union(*x) for x in itertools.product(*args)})", "title": ""}
{"_id": "d20422", "text": "def sort_filenames(filenames):\n    \"\"\"\n    sort a list of files by filename only, ignoring the directory names\n    \"\"\"\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]", "title": ""}
{"_id": "d20423", "text": "def set_xlimits(self, row, column, min=None, max=None):\n        \"\"\"Set x-axis limits of a subplot.\n\n        :param row,column: specify the subplot.\n        :param min: minimal axis value\n        :param max: maximum axis value\n\n        \"\"\"\n        subplot = self.get_subplot_at(row, column)\n        subplot.set_xlimits(min, max)", "title": ""}
{"_id": "d20424", "text": "def world_to_view(v):\n    \"\"\"world coords to view coords; v an eu.Vector2, returns (float, float)\"\"\"\n    return v.x * config.scale_x, v.y * config.scale_y", "title": ""}
{"_id": "d20425", "text": "def sort_data(x, y):\n    \"\"\"Sort the data.\"\"\"\n    xy = sorted(zip(x, y))\n    x, y = zip(*xy)\n    return x, y", "title": ""}
{"_id": "d20426", "text": "def bisect_index(a, x):\n    \"\"\" Find the leftmost index of an element in a list using binary search.\n\n    Parameters\n    ----------\n    a: list\n        A sorted list.\n    x: arbitrary\n        The element.\n\n    Returns\n    -------\n    int\n        The index.\n\n    \"\"\"\n    i = bisect.bisect_left(a, x)\n    if i != len(a) and a[i] == x:\n        return i\n    raise ValueError", "title": ""}
{"_id": "d20427", "text": "def save_notebook(work_notebook, write_file):\n    \"\"\"Saves the Jupyter work_notebook to write_file\"\"\"\n    with open(write_file, 'w') as out_nb:\n        json.dump(work_notebook, out_nb, indent=2)", "title": ""}
{"_id": "d20428", "text": "def _remove_dict_keys_with_value(dict_, val):\n  \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n  return {k: v for k, v in dict_.items() if v is not val}", "title": ""}
{"_id": "d20429", "text": "def clean_out_dir(directory):\n    \"\"\"\n    Delete all the files and subdirectories in a directory.\n    \"\"\"\n    if not isinstance(directory, path):\n        directory = path(directory)\n    for file_path in directory.files():\n        file_path.remove()\n    for dir_path in directory.dirs():\n        dir_path.rmtree()", "title": ""}
{"_id": "d20430", "text": "def push(h, x):\n    \"\"\"Push a new value into heap.\"\"\"\n    h.push(x)\n    up(h, h.size()-1)", "title": ""}
{"_id": "d20431", "text": "def chmod_add_excute(filename):\n        \"\"\"\n        Adds execute permission to file.\n        :param filename:\n        :return:\n        \"\"\"\n        st = os.stat(filename)\n        os.chmod(filename, st.st_mode | stat.S_IEXEC)", "title": ""}
{"_id": "d20432", "text": "def fetch_event(urls):\n    \"\"\"\n    This parallel fetcher uses gevent one uses gevent\n    \"\"\"\n    rs = (grequests.get(u) for u in urls)\n    return [content.json() for content in grequests.map(rs)]", "title": ""}
{"_id": "d20433", "text": "def copy(obj):\n    def copy(self):\n        \"\"\"\n        Copy self to a new object.\n        \"\"\"\n        from copy import deepcopy\n\n        return deepcopy(self)\n    obj.copy = copy\n    return obj", "title": ""}
{"_id": "d20434", "text": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "title": ""}
{"_id": "d20435", "text": "def get_python(self):\n        \"\"\"Only return cursor instance if configured for multiselect\"\"\"\n        if self.multiselect:\n            return super(MultiSelectField, self).get_python()\n\n        return self._get()", "title": ""}
{"_id": "d20436", "text": "def _index_ordering(redshift_list):\n        \"\"\"\n\n        :param redshift_list: list of redshifts\n        :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n        \"\"\"\n        redshift_list = np.array(redshift_list)\n        sort_index = np.argsort(redshift_list)\n        return sort_index", "title": ""}
{"_id": "d20437", "text": "def go_to_new_line(self):\n        \"\"\"Go to the end of the current line and create a new line\"\"\"\n        self.stdkey_end(False, False)\n        self.insert_text(self.get_line_separator())", "title": ""}
{"_id": "d20438", "text": "def rgba_bytes_tuple(self, x):\n        \"\"\"Provides the color corresponding to value `x` in the\n        form of a tuple (R,G,B,A) with int values between 0 and 255.\n        \"\"\"\n        return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))", "title": ""}
{"_id": "d20439", "text": "def date_to_datetime(x):\n    \"\"\"Convert a date into a datetime\"\"\"\n    if not isinstance(x, datetime) and isinstance(x, date):\n        return datetime.combine(x, time())\n    return x", "title": ""}
{"_id": "d20440", "text": "def purge_dict(idict):\n    \"\"\"Remove null items from a dictionary \"\"\"\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict", "title": ""}
{"_id": "d20441", "text": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n    \"\"\"\n    Like `pretty` but print to stdout.\n    \"\"\"\n    printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n    printer.pretty(obj)\n    printer.flush()\n    sys.stdout.write(newline)\n    sys.stdout.flush()", "title": ""}
{"_id": "d20442", "text": "def determine_interactive(self):\n\t\t\"\"\"Determine whether we're in an interactive shell.\n\t\tSets interactivity off if appropriate.\n\t\tcf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):\n\t\t\t\tself.interactive = 0\n\t\t\t\treturn False\n\t\texcept Exception:\n\t\t\tself.interactive = 0\n\t\t\treturn False\n\t\tif self.interactive == 0:\n\t\t\treturn False\n\t\treturn True", "title": ""}
{"_id": "d20443", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d20444", "text": "def insert_one(self, mongo_collection, doc, mongo_db=None, **kwargs):\n        \"\"\"\n        Inserts a single document into a mongo collection\n        https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one\n        \"\"\"\n        collection = self.get_collection(mongo_collection, mongo_db=mongo_db)\n\n        return collection.insert_one(doc, **kwargs)", "title": ""}
{"_id": "d20445", "text": "def _read_json_file(self, json_file):\n        \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n        self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n        with open(json_file, 'r') as f:\n            return json.load(f, object_pairs_hook=OrderedDict)", "title": ""}
{"_id": "d20446", "text": "async def join(self, ctx, *, channel: discord.VoiceChannel):\n        \"\"\"Joins a voice channel\"\"\"\n\n        if ctx.voice_client is not None:\n            return await ctx.voice_client.move_to(channel)\n\n        await channel.connect()", "title": ""}
{"_id": "d20447", "text": "def test():\n    \"\"\"Run the unit tests.\"\"\"\n    import unittest\n    tests = unittest.TestLoader().discover('tests')\n    unittest.TextTestRunner(verbosity=2).run(tests)", "title": ""}
{"_id": "d20448", "text": "async def _send_plain_text(self, request: Request, stack: Stack):\n        \"\"\"\n        Sends plain text using `_send_text()`.\n        \"\"\"\n\n        await self._send_text(request, stack, None)", "title": ""}
{"_id": "d20449", "text": "def get_numbers(s):\n    \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n    result = map(int, re.findall(r'[0-9]+', unicode(s)))\n    return result + [1] * (2 - len(result))", "title": ""}
{"_id": "d20450", "text": "def _format_title_string(self, title_string):\n        \"\"\" format mpv's title \"\"\"\n        return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix))", "title": ""}
{"_id": "d20451", "text": "def downsample(array, k):\n    \"\"\"Choose k random elements of array.\"\"\"\n    length = array.shape[0]\n    indices = random.sample(xrange(length), k)\n    return array[indices]", "title": ""}
{"_id": "d20452", "text": "def get_file_string(filepath):\n    \"\"\"Get string from file.\"\"\"\n    with open(os.path.abspath(filepath)) as f:\n        return f.read()", "title": ""}
{"_id": "d20453", "text": "def distance(vec1, vec2):\n        \"\"\"Calculate the distance between two Vectors\"\"\"\n        if isinstance(vec1, Vector2) \\\n                and isinstance(vec2, Vector2):\n            dist_vec = vec2 - vec1\n            return dist_vec.length()\n        else:\n            raise TypeError(\"vec1 and vec2 must be Vector2's\")", "title": ""}
{"_id": "d20454", "text": "def get_dimension_array(array):\n    \"\"\"\n    Get dimension of an array getting the number of rows and the max num of\n    columns.\n    \"\"\"\n    if all(isinstance(el, list) for el in array):\n        result = [len(array), len(max([x for x in array], key=len,))]\n\n    # elif array and isinstance(array, list):\n    else:\n        result = [len(array), 1]\n\n    return result", "title": ""}
{"_id": "d20455", "text": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n    \"\"\"\n    http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n    \"\"\"\n    fft = np.fft.fft(data)\n    # n = len(data)\n    # timestep = 1.0 / fs\n    # freq = np.fft.fftfreq(n, d=timestep)\n    bp = fft.copy()\n\n    # Zero out fft coefficients\n    # bp[10:-10] = 0\n\n    # Normalise\n    # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n    bp *= fft.dot(fft) / bp.dot(bp)\n\n    # must multipy by 2 to get the correct amplitude\n    ibp = 12 * np.fft.ifft(bp)\n    return ibp", "title": ""}
{"_id": "d20456", "text": "def comma_delimited_to_list(list_param):\n    \"\"\"Convert comma-delimited list / string into a list of strings\n\n    :param list_param: Comma-delimited string\n    :type list_param: str | unicode\n    :return: A list of strings\n    :rtype: list\n    \"\"\"\n    if isinstance(list_param, list):\n        return list_param\n    if isinstance(list_param, str):\n        return list_param.split(',')\n    else:\n        return []", "title": ""}
{"_id": "d20457", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d20458", "text": "def set_value(self, value):\n        \"\"\"Set value of the checkbox.\n\n        Parameters\n        ----------\n        value : bool\n            value for the checkbox\n\n        \"\"\"\n        if value:\n            self.setChecked(Qt.Checked)\n        else:\n            self.setChecked(Qt.Unchecked)", "title": ""}
{"_id": "d20459", "text": "def Softsign(a):\n    \"\"\"\n    Softsign op.\n    \"\"\"\n    return np.divide(a, np.add(np.abs(a), 1)),", "title": ""}
{"_id": "d20460", "text": "def rlognormal(mu, tau, size=None):\n    \"\"\"\n    Return random lognormal variates.\n    \"\"\"\n\n    return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "title": ""}
{"_id": "d20461", "text": "def __len__(self):\n\t\t\"\"\"Get a list of the public data attributes.\"\"\"\n\t\treturn len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])", "title": ""}
{"_id": "d20462", "text": "def read(self):\n        \"\"\"https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image\"\"\"\n        stream = BytesIO()\n        self.cam.capture(stream, format='png')\n        # \"Rewind\" the stream to the beginning so we can read its content\n        stream.seek(0)\n        return Image.open(stream)", "title": ""}
{"_id": "d20463", "text": "def logout(cache):\n    \"\"\"\n    Logs out the current session by removing it from the cache. This is\n    expected to only occur when a session has\n    \"\"\"\n    cache.set(flask.session['auth0_key'], None)\n    flask.session.clear()\n    return True", "title": ""}
{"_id": "d20464", "text": "def save(self):\n        \"\"\"Saves the updated model to the current entity db.\n        \"\"\"\n        self.session.add(self)\n        self.session.flush()\n        return self", "title": ""}
{"_id": "d20465", "text": "def do_next(self, args):\n        \"\"\"Step over the next statement\n        \"\"\"\n        self._do_print_from_last_cmd = True\n        self._interp.step_over()\n        return True", "title": ""}
{"_id": "d20466", "text": "def is_string(obj):\n    \"\"\"Is this a string.\n\n    :param object obj:\n    :rtype: bool\n    \"\"\"\n    if PYTHON3:\n        str_type = (bytes, str)\n    else:\n        str_type = (bytes, str, unicode)\n    return isinstance(obj, str_type)", "title": ""}
{"_id": "d20467", "text": "def log_loss(preds, labels):\n    \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n    log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n    return -log_likelihood", "title": ""}
{"_id": "d20468", "text": "def __init__(self, master=None, compound=tk.RIGHT, autohidescrollbar=True, **kwargs):\n        \"\"\"\n        Create a Listbox with a vertical scrollbar.\n\n        :param master: master widget\n        :type master: widget\n        :param compound: side for the Scrollbar to be on (:obj:`tk.LEFT` or :obj:`tk.RIGHT`)\n        :type compound: str\n        :param autohidescrollbar: whether to use an :class:`~ttkwidgets.AutoHideScrollbar` or a :class:`ttk.Scrollbar`\n        :type autohidescrollbar: bool\n        :param kwargs: keyword arguments passed on to the :class:`tk.Listbox` initializer\n        \"\"\"\n        ttk.Frame.__init__(self, master)\n        self.columnconfigure(1, weight=1)\n        self.rowconfigure(0, weight=1)\n        self.listbox = tk.Listbox(self, **kwargs)\n        if autohidescrollbar:\n            self.scrollbar = AutoHideScrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n        else:\n            self.scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n        self.config_listbox(yscrollcommand=self.scrollbar.set)\n        if compound is not tk.LEFT and compound is not tk.RIGHT:\n            raise ValueError(\"Invalid compound value passed: {0}\".format(compound))\n        self.__compound = compound\n        self._grid_widgets()", "title": ""}
{"_id": "d20469", "text": "def most_significant_bit(lst: np.ndarray) -> int:\n    \"\"\"\n    A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n    i.e. the first position where a 1 appears, reading left to right.\n\n    :param lst: a 1d array of 0s and 1s with at least one 1\n    :return: the first position in lst that a 1 appears\n    \"\"\"\n    return np.argwhere(np.asarray(lst) == 1)[0][0]", "title": ""}
{"_id": "d20470", "text": "def _tab(content):\n    \"\"\"\n    Helper funcation that converts text-based get response\n    to tab separated values for additional manipulation.\n    \"\"\"\n    response = _data_frame(content).to_csv(index=False,sep='\\t')\n    return response", "title": ""}
{"_id": "d20471", "text": "def normalize(data):\n    \"\"\"Normalize the data to be in the [0, 1] range.\n\n    :param data:\n    :return: normalized data\n    \"\"\"\n    out_data = data.copy()\n\n    for i, sample in enumerate(out_data):\n        out_data[i] /= sum(out_data[i])\n\n    return out_data", "title": ""}
{"_id": "d20472", "text": "def is_finite(value: Any) -> bool:\n    \"\"\"Return true if a value is a finite number.\"\"\"\n    return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "title": ""}
{"_id": "d20473", "text": "def remove_blank_lines(string):\n    \"\"\" Removes all blank lines in @string\n\n        -> #str without blank lines\n    \"\"\"\n    return \"\\n\".join(line\n                     for line in string.split(\"\\n\")\n                     if len(line.strip()))", "title": ""}
{"_id": "d20474", "text": "def _repr(obj):\n    \"\"\"Show the received object as precise as possible.\"\"\"\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", "title": ""}
{"_id": "d20475", "text": "def find_duplicates(l: list) -> set:\n    \"\"\"\n    Return the duplicates in a list.\n\n    The function relies on\n    https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n    Parameters\n    ----------\n    l : list\n        Name\n\n    Returns\n    -------\n    set\n        Duplicated values\n\n    >>> find_duplicates([1,2,3])\n    set()\n    >>> find_duplicates([1,2,1])\n    {1}\n    \"\"\"\n    return set([x for x in l if l.count(x) > 1])", "title": ""}
{"_id": "d20476", "text": "def label_saves(name):\n    \"\"\"Labels plots and saves file\"\"\"\n    plt.legend(loc=0)\n    plt.ylim([0, 1.025])\n    plt.xlabel('$U/D$', fontsize=20)\n    plt.ylabel('$Z$', fontsize=20)\n    plt.savefig(name, dpi=300, format='png',\n            transparent=False, bbox_inches='tight', pad_inches=0.05)", "title": ""}
{"_id": "d20477", "text": "def dag_longest_path(graph, source, target):\n    \"\"\"\n    Finds the longest path in a dag between two nodes\n    \"\"\"\n    if source == target:\n        return [source]\n    allpaths = nx.all_simple_paths(graph, source, target)\n    longest_path = []\n    for l in allpaths:\n        if len(l) > len(longest_path):\n            longest_path = l\n    return longest_path", "title": ""}
{"_id": "d20478", "text": "def itemlist(item, sep, suppress_trailing=True):\n    \"\"\"Create a list of items seperated by seps.\"\"\"\n    return condense(item + ZeroOrMore(addspace(sep + item)) + Optional(sep.suppress() if suppress_trailing else sep))", "title": ""}
{"_id": "d20479", "text": "def to_list(self):\n        \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n        return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n                [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "title": ""}
{"_id": "d20480", "text": "def cross_v2(vec1, vec2):\n    \"\"\"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.\n    \"\"\"\n\n    return vec1.y * vec2.x - vec1.x * vec2.y", "title": ""}
{"_id": "d20481", "text": "def Fsphere(q, R):\n    \"\"\"Scattering form-factor amplitude of a sphere normalized to F(q=0)=V\n\n    Inputs:\n    -------\n        ``q``: independent variable\n        ``R``: sphere radius\n\n    Formula:\n    --------\n        ``4*pi/q^3 * (sin(qR) - qR*cos(qR))``\n    \"\"\"\n    return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R * np.cos(q * R))", "title": ""}
{"_id": "d20482", "text": "def is_readable_dir(path):\n  \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n  return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)", "title": ""}
{"_id": "d20483", "text": "def assert_exactly_one_true(bool_list):\n    \"\"\"This method asserts that only one value of the provided list is True.\n\n    :param bool_list: List of booleans to check\n    :return: True if only one value is True, False otherwise\n    \"\"\"\n    assert isinstance(bool_list, list)\n    counter = 0\n    for item in bool_list:\n        if item:\n            counter += 1\n    return counter == 1", "title": ""}
{"_id": "d20484", "text": "def EnumValueName(self, enum, value):\n    \"\"\"Returns the string name of an enum value.\n\n    This is just a small helper method to simplify a common operation.\n\n    Args:\n      enum: string name of the Enum.\n      value: int, value of the enum.\n\n    Returns:\n      string name of the enum value.\n\n    Raises:\n      KeyError if either the Enum doesn't exist or the value is not a valid\n        value for the enum.\n    \"\"\"\n    return self.enum_types_by_name[enum].values_by_number[value].name", "title": ""}
{"_id": "d20485", "text": "def POINTER(obj):\n    \"\"\"\n    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.\n\n    \"\"\"\n\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\n    return p", "title": ""}
{"_id": "d20486", "text": "def md5_string(s):\n    \"\"\"\n    Shortcut to create md5 hash\n    :param s:\n    :return:\n    \"\"\"\n    m = hashlib.md5()\n    m.update(s)\n    return str(m.hexdigest())", "title": ""}
{"_id": "d20487", "text": "def intersect(d1, d2):\n    \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n    return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "title": ""}
{"_id": "d20488", "text": "def remove_elements(target, indices):\n    \"\"\"Remove multiple elements from a list and return result.\n    This implementation is faster than the alternative below.\n    Also note the creation of a new list to avoid altering the\n    original. We don't have any current use for the original\n    intact list, but may in the future...\"\"\"\n\n    copied = list(target)\n\n    for index in reversed(indices):\n        del copied[index]\n    return copied", "title": ""}
{"_id": "d20489", "text": "def convertToBool():\n    \"\"\" Convert a byte value to boolean (0 or 1) if\n    the global flag strictBool is True\n    \"\"\"\n    if not OPTIONS.strictBool.value:\n        return []\n\n    REQUIRES.add('strictbool.asm')\n\n    result = []\n    result.append('pop af')\n    result.append('call __NORMALIZE_BOOLEAN')\n    result.append('push af')\n\n    return result", "title": ""}
{"_id": "d20490", "text": "def append_query_parameter(url, parameters, ignore_if_exists=True):\n    \"\"\" quick and dirty appending of query parameters to a url \"\"\"\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", "title": ""}
{"_id": "d20491", "text": "def pid_exists(pid):\n    \"\"\" Determines if a system process identifer exists in process table.\n        \"\"\"\n    try:\n        os.kill(pid, 0)\n    except OSError as exc:\n        return exc.errno == errno.EPERM\n    else:\n        return True", "title": ""}
{"_id": "d20492", "text": "def is_static(*p):\n    \"\"\" A static value (does not change at runtime)\n    which is known at compile time\n    \"\"\"\n    return all(is_CONST(x) or\n               is_number(x) or\n               is_const(x)\n               for x in p)", "title": ""}
{"_id": "d20493", "text": "def getvariable(name):\n    \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n    import inspect\n    fr = inspect.currentframe()\n    try:\n        while fr:\n            fr = fr.f_back\n            vars = fr.f_locals\n            if name in vars:\n                return vars[name]\n    except:\n        pass\n    return None", "title": ""}
{"_id": "d20494", "text": "def _(f, x):\n    \"\"\"\n    filter for dict, note `f` should have signature: `f::key->value->bool`\n    \"\"\"\n    return {k: v for k, v in x.items() if f(k, v)}", "title": ""}
{"_id": "d20495", "text": "def from_file(file_path) -> dict:\n        \"\"\" Load JSON file \"\"\"\n        with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n            return Json.parse(json_stream, True)", "title": ""}
{"_id": "d20496", "text": "def shape_list(l,shape,dtype):\n    \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n    return np.array(l, dtype=dtype).reshape(shape)", "title": ""}
{"_id": "d20497", "text": "def dtypes(self):\n        \"\"\"Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]\n        \"\"\"\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "title": ""}
{"_id": "d20498", "text": "def random_str(size=10):\n    \"\"\"\n    create random string of selected size\n\n    :param size: int, length of the string\n    :return: the string\n    \"\"\"\n    return ''.join(random.choice(string.ascii_lowercase) for _ in range(size))", "title": ""}
{"_id": "d20499", "text": "def try_cast_int(s):\n    \"\"\"(str) -> int\n    All the digits in a given string are concatenated and converted into a single number.\n    \"\"\"\n    try:\n        temp = re.findall('\\d', str(s))\n        temp = ''.join(temp)\n        return int(temp)\n    except:\n        return s", "title": ""}
{"_id": "d20500", "text": "def column_names(self, table):\n      \"\"\"An iterable of column names, for a particular table or\n      view.\"\"\"\n\n      table_info = self.execute(\n        u'PRAGMA table_info(%s)' % quote(table))\n      return (column['name'] for column in table_info)", "title": ""}
{"_id": "d20501", "text": "def get_files(dir_name):\n    \"\"\"Simple directory walker\"\"\"\n    return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]", "title": ""}
{"_id": "d20502", "text": "def _get_str_columns(sf):\n    \"\"\"\n    Returns a list of names of columns that are string type.\n    \"\"\"\n    return [name for name in sf.column_names() if sf[name].dtype == str]", "title": ""}
{"_id": "d20503", "text": "def as_dict(self):\n        \"\"\"Return all child objects in nested dict.\"\"\"\n        dicts = [x.as_dict for x in self.children]\n        return {'{0} {1}'.format(self.name, self.value): dicts}", "title": ""}
{"_id": "d20504", "text": "def numpy(self):\n        \"\"\" Grabs image data and converts it to a numpy array \"\"\"\n        # load GDCM's image reading functionality\n        image_reader = gdcm.ImageReader()\n        image_reader.SetFileName(self.fname)\n        if not image_reader.Read():\n            raise IOError(\"Could not read DICOM image\")\n        pixel_array = self._gdcm_to_numpy(image_reader.GetImage())\n        return pixel_array", "title": ""}
{"_id": "d20505", "text": "def to_camel(s):\n    \"\"\"\n    :param string s: under_scored string to be CamelCased\n    :return: CamelCase version of input\n    :rtype: str\n    \"\"\"\n    # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n    return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "title": ""}
{"_id": "d20506", "text": "def define_macro(self, name, themacro):\n        \"\"\"Define a new macro\n\n        Parameters\n        ----------\n        name : str\n            The name of the macro.\n        themacro : str or Macro\n            The action to do upon invoking the macro.  If a string, a new\n            Macro object is created by passing the string to it.\n        \"\"\"\n\n        from IPython.core import macro\n\n        if isinstance(themacro, basestring):\n            themacro = macro.Macro(themacro)\n        if not isinstance(themacro, macro.Macro):\n            raise ValueError('A macro must be a string or a Macro instance.')\n        self.user_ns[name] = themacro", "title": ""}
{"_id": "d20507", "text": "def _finish(self):\n        \"\"\"\n        Closes and waits for subprocess to exit.\n        \"\"\"\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", "title": ""}
{"_id": "d20508", "text": "def _accumulate(sequence, func):\n    \"\"\"\n    Python2 accumulate implementation taken from\n    https://docs.python.org/3/library/itertools.html#itertools.accumulate\n    \"\"\"\n    iterator = iter(sequence)\n    total = next(iterator)\n    yield total\n    for element in iterator:\n        total = func(total, element)\n        yield total", "title": ""}
{"_id": "d20509", "text": "def timedelta_seconds(timedelta):\n    \"\"\"Returns the total timedelta duration in seconds.\"\"\"\n    return (timedelta.total_seconds() if hasattr(timedelta, \"total_seconds\")\n            else timedelta.days * 24 * 3600 + timedelta.seconds +\n                 timedelta.microseconds / 1000000.)", "title": ""}
{"_id": "d20510", "text": "def string(value) -> str:\n        \"\"\" string dict/object/value to JSON \"\"\"\n        return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "title": ""}
{"_id": "d20511", "text": "def get_trace_id_from_flask():\n    \"\"\"Get trace_id from flask request headers.\n\n    :rtype: str\n    :returns: TraceID in HTTP request headers.\n    \"\"\"\n    if flask is None or not flask.request:\n        return None\n\n    header = flask.request.headers.get(_FLASK_TRACE_HEADER)\n\n    if header is None:\n        return None\n\n    trace_id = header.split(\"/\", 1)[0]\n\n    return trace_id", "title": ""}
{"_id": "d20512", "text": "def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:\n    \"\"\"\n    Args:\n        x: iterable of strings\n\n    Yields:\n        each string in lower case\n    \"\"\"\n    for string in x:\n        yield string.lower()", "title": ""}
{"_id": "d20513", "text": "def insort_no_dup(lst, item):\n    \"\"\"\n    If item is not in lst, add item to list at its sorted position\n    \"\"\"\n    import bisect\n    ix = bisect.bisect_left(lst, item)\n    if lst[ix] != item: \n        lst[ix:ix] = [item]", "title": ""}
{"_id": "d20514", "text": "def normalize_column_names(df):\n    r\"\"\" Clean up whitespace in column names. See better version at `pugnlp.clean_columns`\n\n    >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here'])\n    >>> normalize_column_names(df)\n    ['hello_world', 'not_here']\n    \"\"\"\n    columns = df.columns if hasattr(df, 'columns') else df\n    columns = [c.lower().replace(' ', '_') for c in columns]\n    return columns", "title": ""}
{"_id": "d20515", "text": "def mean(inlist):\n    \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage:   lmean(inlist)\n\"\"\"\n    sum = 0\n    for item in inlist:\n        sum = sum + item\n    return sum / float(len(inlist))", "title": ""}
{"_id": "d20516", "text": "def mkhead(repo, path):\n    \"\"\":return: New branch/head instance\"\"\"\n    return git.Head(repo, git.Head.to_full_path(path))", "title": ""}
{"_id": "d20517", "text": "def make_lambda(call):\n    \"\"\"Wrap an AST Call node to lambda expression node.\n    call: ast.Call node\n    \"\"\"\n    empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n    return ast.Lambda(args=empty_args, body=call)", "title": ""}
{"_id": "d20518", "text": "def is_punctuation(text):\n    \"\"\"Check if given string is a punctuation\"\"\"\n    return not (text.lower() in config.AVRO_VOWELS or\n                text.lower() in config.AVRO_CONSONANTS)", "title": ""}
{"_id": "d20519", "text": "def parse(self, data, mimetype):\n        \"\"\"\n        Parses a byte array containing a JSON document and returns a Python object.\n        :param data: The byte array containing a JSON document.\n        :param MimeType mimetype: The mimetype chose to parse the data.\n        :return: A Python object.\n        \"\"\"\n        encoding = mimetype.params.get('charset') or 'utf-8'\n\n        return json.loads(data.decode(encoding))", "title": ""}
{"_id": "d20520", "text": "def _str_to_list(value, separator):\n    \"\"\"Convert a string to a list with sanitization.\"\"\"\n    value_list = [item.strip() for item in value.split(separator)]\n    value_list_sanitized = builtins.list(filter(None, value_list))\n    if len(value_list_sanitized) > 0:\n        return value_list_sanitized\n    else:\n        raise ValueError('Invalid list variable.')", "title": ""}
{"_id": "d20521", "text": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n    \"\"\"Remove empty utterances from a list of utterances\n    Args:\n        utterances: The list of utterance we are processing\n    \"\"\"\n    return [utter for utter in utterances if utter.text.strip() != \"\"]", "title": ""}
{"_id": "d20522", "text": "def get_data(self):\n        \"\"\"\n        Fetch the data field if it does not exist.\n        \"\"\"\n        try:\n            return DocumentDataDict(self.__dict__['data'])\n        except KeyError:\n            self._lazy_load()\n            return DocumentDataDict(self.__dict__['data'])", "title": ""}
{"_id": "d20523", "text": "def synthesize(self, duration):\n        \"\"\"\n        Synthesize white noise\n\n        Args:\n            duration (numpy.timedelta64): The duration of the synthesized sound\n        \"\"\"\n        sr = self.samplerate.samples_per_second\n        seconds = duration / Seconds(1)\n        samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n        return AudioSamples(samples, self.samplerate)", "title": ""}
{"_id": "d20524", "text": "def seq_to_str(obj, sep=\",\"):\n    \"\"\"\n    Given a sequence convert it to a comma separated string.\n    If, however, the argument is a single object, return its string\n    representation.\n    \"\"\"\n    if isinstance(obj, string_classes):\n        return obj\n    elif isinstance(obj, (list, tuple)):\n        return sep.join([str(x) for x in obj])\n    else:\n        return str(obj)", "title": ""}
{"_id": "d20525", "text": "def set_xlimits(self, min=None, max=None):\n        \"\"\"Set limits for the x-axis.\n\n        :param min: minimum value to be displayed.  If None, it will be\n            calculated.\n        :param max: maximum value to be displayed.  If None, it will be\n            calculated.\n\n        \"\"\"\n        self.limits['xmin'] = min\n        self.limits['xmax'] = max", "title": ""}
{"_id": "d20526", "text": "def enable_ssl(self, *args, **kwargs):\n        \"\"\"\n        Transforms the regular socket.socket to an ssl.SSLSocket for secure\n        connections. Any arguments are passed to ssl.wrap_socket:\n        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n        \"\"\"\n        if self.handshake_sent:\n            raise SSLError('can only enable SSL before handshake')\n\n        self.secure = True\n        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "title": ""}
{"_id": "d20527", "text": "def to_bytes(value):\n    \"\"\" str to bytes (py3k) \"\"\"\n    vtype = type(value)\n\n    if vtype == bytes or vtype == type(None):\n        return value\n\n    try:\n        return vtype.encode(value)\n    except UnicodeEncodeError:\n        pass\n    return value", "title": ""}
{"_id": "d20528", "text": "def from_file(cls, file_path, validate=True):\n        \"\"\" Creates a Python object from a XML file\n\n        :param file_path: Path to the XML file\n        :param validate: XML should be validated against the embedded XSD definition\n        :type validate: Boolean\n        :returns: the Python object\n        \"\"\"\n        return xmlmap.load_xmlobject_from_file(file_path, xmlclass=cls, validate=validate)", "title": ""}
{"_id": "d20529", "text": "def expandpath(path):\n    \"\"\"\n    Expand a filesystem path that may or may not contain user/env vars.\n\n    :param str path: path to expand\n    :return str: expanded version of input path\n    \"\"\"\n    return os.path.expandvars(os.path.expanduser(path)).replace(\"//\", \"/\")", "title": ""}
{"_id": "d20530", "text": "def index():\n    \"\"\" Display productpage with normal user and test user buttons\"\"\"\n    global productpage\n\n    table = json2html.convert(json = json.dumps(productpage),\n                              table_attributes=\"class=\\\"table table-condensed table-bordered table-hover\\\"\")\n\n    return render_template('index.html', serviceTable=table)", "title": ""}
{"_id": "d20531", "text": "def is_defined(self, objtxt, force_import=False):\n        \"\"\"Return True if object is defined\"\"\"\n        return self.interpreter.is_defined(objtxt, force_import)", "title": ""}
{"_id": "d20532", "text": "def s3(ctx, bucket_name, data_file, region):\n    \"\"\"Use the S3 SWAG backend.\"\"\"\n    if not ctx.data_file:\n        ctx.data_file = data_file\n\n    if not ctx.bucket_name:\n        ctx.bucket_name = bucket_name\n\n    if not ctx.region:\n        ctx.region = region\n\n    ctx.type = 's3'", "title": ""}
{"_id": "d20533", "text": "def list(self):\n        \"\"\"position in 3d space\"\"\"\n        return [self._pos3d.x, self._pos3d.y, self._pos3d.z]", "title": ""}
{"_id": "d20534", "text": "def _num_cpus_darwin():\n    \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n    p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n    return p.stdout.read()", "title": ""}
{"_id": "d20535", "text": "def set_trace():\n    \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n    # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n    pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "title": ""}
{"_id": "d20536", "text": "def get_dict_to_encoded_url(data):\n    \"\"\"\n    Converts a dict to an encoded URL.\n    Example: given  data = {'a': 1, 'b': 2}, it returns 'a=1&b=2'\n    \"\"\"\n    unicode_data = dict([(k, smart_str(v)) for k, v in data.items()])\n    encoded = urllib.urlencode(unicode_data)\n    return encoded", "title": ""}
{"_id": "d20537", "text": "def _isint(string):\n    \"\"\"\n    >>> _isint(\"123\")\n    True\n    >>> _isint(\"123.45\")\n    False\n    \"\"\"\n    return type(string) is int or \\\n           (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n           _isconvertible(int, string)", "title": ""}
{"_id": "d20538", "text": "def add_exec_permission_to(target_file):\n    \"\"\"Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed\n    \"\"\"\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)", "title": ""}
{"_id": "d20539", "text": "def smooth_gaussian(image, sigma=1):\n    \"\"\"Returns Gaussian smoothed image.\n\n    :param image: numpy array or :class:`jicimagelib.image.Image`\n    :param sigma: standard deviation\n    :returns: :class:`jicimagelib.image.Image`\n    \"\"\"\n    return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode=\"nearest\")", "title": ""}
{"_id": "d20540", "text": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n    \"\"\"Truncates a value to a number of decimals places\"\"\"\n    return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "title": ""}
{"_id": "d20541", "text": "def replace_list(items, match, replacement):\n    \"\"\"Replaces occurrences of a match string in a given list of strings and returns\n    a list of new strings. The match string can be a regex expression.\n\n    Args:\n        items (list):       the list of strings to modify.\n        match (str):        the search expression.\n        replacement (str):  the string to replace with.\n    \"\"\"\n    return [replace(item, match, replacement) for item in items]", "title": ""}
{"_id": "d20542", "text": "def as_float_array(a):\n    \"\"\"View the quaternion array as an array of floats\n\n    This function is fast (of order 1 microsecond) because no data is\n    copied; the returned quantity is just a \"view\" of the original.\n\n    The output view has one more dimension (of size 4) than the input\n    array, but is otherwise the same shape.\n\n    \"\"\"\n    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "title": ""}
{"_id": "d20543", "text": "def ranks(self, key, value):\n    \"\"\"Populate the ``ranks`` key.\"\"\"\n    return [normalize_rank(el) for el in force_list(value.get('a'))]", "title": ""}
{"_id": "d20544", "text": "def is_valid_file(parser, arg):\n    \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n    arg = os.path.abspath(arg)\n    if not os.path.exists(arg):\n        parser.error(\"The file %s does not exist!\" % arg)\n    else:\n        return arg", "title": ""}
{"_id": "d20545", "text": "def get_parent_dir(name):\n    \"\"\"Get the parent directory of a filename.\"\"\"\n    parent_dir = os.path.dirname(os.path.dirname(name))\n    if parent_dir:\n        return parent_dir\n    return os.path.abspath('.')", "title": ""}
{"_id": "d20546", "text": "def resize(self, size):\n        \"\"\"Return a new Image instance with the given size.\"\"\"\n        return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))", "title": ""}
{"_id": "d20547", "text": "def compute_boxplot(self, series):\n        \"\"\"\n        Compute boxplot for given pandas Series.\n        \"\"\"\n        from matplotlib.cbook import boxplot_stats\n        series = series[series.notnull()]\n        if len(series.values) == 0:\n            return {}\n        elif not is_numeric_dtype(series):\n            return self.non_numeric_stats(series)\n        stats = boxplot_stats(list(series.values))[0]\n        stats['count'] = len(series.values)\n        stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n        return stats", "title": ""}
{"_id": "d20548", "text": "def glpk_read_cplex(path):\n    \"\"\"Reads cplex file and returns glpk problem.\n\n    Returns\n    -------\n    glp_prob\n        A glpk problems (same type as returned by glp_create_prob)\n    \"\"\"\n    from swiglpk import glp_create_prob, glp_read_lp\n\n    problem = glp_create_prob()\n    glp_read_lp(problem, None, path)\n    return problem", "title": ""}
{"_id": "d20549", "text": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "title": ""}
{"_id": "d20550", "text": "def one_hot2string(arr, vocab):\n    \"\"\"Convert a one-hot encoded array back to string\n    \"\"\"\n    tokens = one_hot2token(arr)\n    indexToLetter = _get_index_dict(vocab)\n\n    return [''.join([indexToLetter[x] for x in row]) for row in tokens]", "title": ""}
{"_id": "d20551", "text": "def to_bytes(data: Any) -> bytearray:\n    \"\"\"\n    Convert anything to a ``bytearray``.\n    \n    See\n    \n    - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n    - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n    \"\"\"  # noqa\n    if isinstance(data, int):\n        return bytearray([data])\n    return bytearray(data, encoding='latin-1')", "title": ""}
{"_id": "d20552", "text": "def json(body, charset='utf-8', **kwargs):\n    \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n    return json_converter.loads(text(body, charset=charset))", "title": ""}
{"_id": "d20553", "text": "def add_blank_row(self, label):\n        \"\"\"\n        Add a blank row with only an index value to self.df.\n        This is done inplace.\n        \"\"\"\n        col_labels = self.df.columns\n        blank_item = pd.Series({}, index=col_labels, name=label)\n        # use .loc to add in place (append won't do that)\n        self.df.loc[blank_item.name] = blank_item\n        return self.df", "title": ""}
{"_id": "d20554", "text": "def clean(s):\n  \"\"\"Removes trailing whitespace on each line.\"\"\"\n  lines = [l.rstrip() for l in s.split('\\n')]\n  return '\\n'.join(lines)", "title": ""}
{"_id": "d20555", "text": "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)", "title": ""}
{"_id": "d20556", "text": "def string_input(prompt=''):\n    \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n    v = sys.version[0]\n    if v == '3':\n        return input(prompt)\n    else:\n        return raw_input(prompt)", "title": ""}
{"_id": "d20557", "text": "def parse(self):\n        \"\"\"\n        Parse file specified by constructor.\n        \"\"\"\n        f = open(self.parse_log_path, \"r\")\n        self.parse2(f)\n        f.close()", "title": ""}
{"_id": "d20558", "text": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n    \"\"\"\n    Process an iterable of dictionaries. For each dictionary ``d``, delete\n    ``d[key]`` if it exists.\n    \"\"\"\n    for d in dict_list:\n        d.pop(key, None)", "title": ""}
{"_id": "d20559", "text": "def write_line(self, line, count=1):\n        \"\"\"writes the line and count newlines after the line\"\"\"\n        self.write(line)\n        self.write_newlines(count)", "title": ""}
{"_id": "d20560", "text": "def format(x, format):\n    \"\"\"Uses http://www.cplusplus.com/reference/string/to_string/ for formatting\"\"\"\n    # don't change the dtype, otherwise for each block the dtype may be different (string length)\n    sl = vaex.strings.format(x, format)\n    return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)", "title": ""}
{"_id": "d20561", "text": "def selectnotnone(table, field, complement=False):\n    \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)", "title": ""}
{"_id": "d20562", "text": "def is_symbol(string):\n    \"\"\"\n    Return true if the string is a mathematical symbol.\n    \"\"\"\n    return (\n        is_int(string) or is_float(string) or\n        is_constant(string) or is_unary(string) or\n        is_binary(string) or\n        (string == '(') or (string == ')')\n    )", "title": ""}
{"_id": "d20563", "text": "def ensure_hbounds(self):\n        \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "title": ""}
{"_id": "d20564", "text": "def create_ellipse(width,height,angle):\n    \"\"\"Create parametric ellipse from 200 points.\"\"\"\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\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", "title": ""}
{"_id": "d20565", "text": "def _sim_fill(r1, r2, imsize):\n    \"\"\"\n        calculate the fill similarity over the image\n    \"\"\"\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", "title": ""}
{"_id": "d20566", "text": "def pass_from_pipe(cls):\n        \"\"\"Return password from pipe if not on TTY, else False.\n        \"\"\"\n        is_pipe = not sys.stdin.isatty()\n        return is_pipe and cls.strip_last_newline(sys.stdin.read())", "title": ""}
{"_id": "d20567", "text": "def __next__(self):\n        \"\"\"\n\n        :return: a pair (1-based line number in the input, row)\n        \"\"\"\n        # Retrieve the row, thereby incrementing the line number:\n        row = super(UnicodeReaderWithLineNumber, self).__next__()\n        return self.lineno + 1, row", "title": ""}
{"_id": "d20568", "text": "def list_move_to_front(l,value='other'):\n    \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n    l=list(l)\n    if value in l:\n        l.remove(value)\n        l.insert(0,value)\n    return l", "title": ""}
{"_id": "d20569", "text": "def _wrap(text, columns=80):\n    \"\"\"\n    Own \"dumb\" reimplementation of textwrap.wrap().\n\n    This is because calling .wrap() on bigger strings can take a LOT of\n    processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of\n    text without spaces.\n\n    Args:\n        text (str): Text to wrap.\n        columns (int): Wrap after `columns` characters.\n\n    Returns:\n        str: Wrapped text.\n    \"\"\"\n    out = []\n    for cnt, char in enumerate(text):\n        out.append(char)\n\n        if (cnt + 1) % columns == 0:\n            out.append(\"\\n\")\n\n    return \"\".join(out)", "title": ""}
{"_id": "d20570", "text": "def warn_if_nans_exist(X):\n    \"\"\"Warn if nans exist in a numpy array.\"\"\"\n    null_count = count_rows_with_nans(X)\n    total = len(X)\n    percent = 100 * null_count / total\n\n    if null_count > 0:\n        warning_message = \\\n            'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n            'complete rows will be plotted.'.format(null_count, total, percent)\n        warnings.warn(warning_message, DataWarning)", "title": ""}
{"_id": "d20571", "text": "def val_to_bin(edges, x):\n    \"\"\"Convert axis coordinate to bin index.\"\"\"\n    ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n    return ibin", "title": ""}
{"_id": "d20572", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d20573", "text": "def disable_insecure_request_warning():\n    \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "title": ""}
{"_id": "d20574", "text": "def pdf(x, mu, std):\n    \"\"\"Probability density function (normal distribution)\"\"\"\n    return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))", "title": ""}
{"_id": "d20575", "text": "def is_orthogonal(\n        matrix: np.ndarray,\n        *,\n        rtol: float = 1e-5,\n        atol: float = 1e-8) -> bool:\n    \"\"\"Determines if a matrix is approximately orthogonal.\n\n    A matrix is orthogonal if it's square and real and its transpose is its\n    inverse.\n\n    Args:\n        matrix: The matrix to check.\n        rtol: The per-matrix-entry relative tolerance on equality.\n        atol: The per-matrix-entry absolute tolerance on equality.\n\n    Returns:\n        Whether the matrix is orthogonal within the given tolerance.\n    \"\"\"\n    return (matrix.shape[0] == matrix.shape[1] and\n            np.all(np.imag(matrix) == 0) and\n            np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]),\n                        rtol=rtol,\n                        atol=atol))", "title": ""}
{"_id": "d20576", "text": "def do_striptags(value):\n    \"\"\"Strip SGML/XML tags and replace adjacent whitespace by one space.\n    \"\"\"\n    if hasattr(value, '__html__'):\n        value = value.__html__()\n    return Markup(unicode(value)).striptags()", "title": ""}
{"_id": "d20577", "text": "def center_text(text, width=80):\n    \"\"\"Center all lines of the text.\n\n    It is assumed that all lines width is smaller then B{width}, because the\n    line width will not be checked.\n\n    Args:\n        text (str): Text to wrap.\n        width (int): Maximum number of characters per line.\n\n    Returns:\n        str: Centered text.\n    \"\"\"\n    centered = []\n    for line in text.splitlines():\n        centered.append(line.center(width))\n    return \"\\n\".join(centered)", "title": ""}
{"_id": "d20578", "text": "def get_keys_from_class(cc):\n    \"\"\"Return list of the key property names for a class \"\"\"\n    return [prop.name for prop in cc.properties.values() \\\n            if 'key' in prop.qualifiers]", "title": ""}
{"_id": "d20579", "text": "def reduce_fn(x):\n    \"\"\"\n    Aggregation function to get the first non-zero value.\n    \"\"\"\n    values = x.values if pd and isinstance(x, pd.Series) else x\n    for v in values:\n        if not is_nan(v):\n            return v\n    return np.NaN", "title": ""}
{"_id": "d20580", "text": "def parse_cookies(self, req, name, field):\n        \"\"\"Pull the value from the cookiejar.\"\"\"\n        return core.get_value(req.COOKIES, name, field)", "title": ""}
{"_id": "d20581", "text": "def is_listish(obj):\n    \"\"\"Check if something quacks like a list.\"\"\"\n    if isinstance(obj, (list, tuple, set)):\n        return True\n    return is_sequence(obj)", "title": ""}
{"_id": "d20582", "text": "def is_image(filename):\n    \"\"\"Determine if given filename is an image.\"\"\"\n    # note: isfile() also accepts symlinks\n    return os.path.isfile(filename) and filename.lower().endswith(ImageExts)", "title": ""}
{"_id": "d20583", "text": "def _preprocess(df):\n    \"\"\"\n    given a DataFrame where records are stored row-wise, rearrange it\n    such that records are stored column-wise.\n    \"\"\"\n\n    df = df.stack()\n\n    df.index.rename([\"id\", \"time\"], inplace=True)  # .reset_index()\n    df.name = \"value\"\n    df = df.reset_index()\n\n    return df", "title": ""}
{"_id": "d20584", "text": "def getfirstline(file, default):\n    \"\"\"\n    Returns the first line of a file.\n    \"\"\"\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\n    return default", "title": ""}
{"_id": "d20585", "text": "def sub(name, func,**kwarg):\n    \"\"\" Add subparser\n\n    \"\"\"\n    sp = subparsers.add_parser(name, **kwarg)\n    sp.set_defaults(func=func)\n    sp.arg = sp.add_argument\n    return sp", "title": ""}
{"_id": "d20586", "text": "def print_err(*args, end='\\n'):\n    \"\"\"Similar to print, but prints to stderr.\n    \"\"\"\n    print(*args, end=end, file=sys.stderr)\n    sys.stderr.flush()", "title": ""}
{"_id": "d20587", "text": "def unit_key_from_name(name):\n  \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n  result = name\n\n  for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n    result = result.replace(old, new)\n\n  # Collapse redundant underscores and convert to uppercase.\n  result = re.sub(r'_+', '_', result.upper())\n\n  return result", "title": ""}
{"_id": "d20588", "text": "def mouse_move_event(self, event):\n        \"\"\"\n        Forward mouse cursor position events to the example\n        \"\"\"\n        self.example.mouse_position_event(event.x(), event.y())", "title": ""}
{"_id": "d20589", "text": "def service_available(service_name):\n    \"\"\"Determine whether a system service is available\"\"\"\n    try:\n        subprocess.check_output(\n            ['service', service_name, 'status'],\n            stderr=subprocess.STDOUT).decode('UTF-8')\n    except subprocess.CalledProcessError as e:\n        return b'unrecognized service' not in e.output\n    else:\n        return True", "title": ""}
{"_id": "d20590", "text": "def issuperset(self, items):\n        \"\"\"Return whether this collection contains all items.\n\n        >>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])\n        True\n        \"\"\"\n        return all(_compat.map(self._seen.__contains__, items))", "title": ""}
{"_id": "d20591", "text": "def decode(self, bytes, raw=False):\n        \"\"\"decode(bytearray, raw=False) -> value\n\n        Decodes the given bytearray according to this PrimitiveType\n        definition.\n\n        NOTE: The parameter ``raw`` is present to adhere to the\n        ``decode()`` inteface, but has no effect for PrimitiveType\n        definitions.\n        \"\"\"\n        return struct.unpack(self.format, buffer(bytes))[0]", "title": ""}
{"_id": "d20592", "text": "def _writable_dir(path):\n    \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n    return os.path.isdir(path) and os.access(path, os.W_OK)", "title": ""}
{"_id": "d20593", "text": "def as_list(self):\n        \"\"\"Return all child objects in nested lists of strings.\"\"\"\n        return [self.name, self.value, [x.as_list for x in self.children]]", "title": ""}
{"_id": "d20594", "text": "def _replace_nan(a, val):\n    \"\"\"\n    replace nan in a by val, and returns the replaced array and the nan\n    position\n    \"\"\"\n    mask = isnull(a)\n    return where_method(val, mask, a), mask", "title": ""}
{"_id": "d20595", "text": "def check_key(self, key: str) -> bool:\n        \"\"\"\n        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\n        \"\"\"\n        keys = self.get_keys()\n        return key in keys", "title": ""}
{"_id": "d20596", "text": "def point8_to_box(points):\n    \"\"\"\n    Args:\n        points: (nx4)x2\n    Returns:\n        nx4 boxes (x1y1x2y2)\n    \"\"\"\n    p = points.reshape((-1, 4, 2))\n    minxy = p.min(axis=1)   # nx2\n    maxxy = p.max(axis=1)   # nx2\n    return np.concatenate((minxy, maxxy), axis=1)", "title": ""}
{"_id": "d20597", "text": "def get_enum_from_name(self, enum_name):\n        \"\"\"\n            Return an enum from a name\n        Args:\n            enum_name (str): name of the enum\n        Returns:\n            Enum\n        \"\"\"\n        return next((e for e in self.enums if e.name == enum_name), None)", "title": ""}
{"_id": "d20598", "text": "def add_arrow(self, x1, y1, x2, y2, **kws):\n        \"\"\"add arrow to plot\"\"\"\n        self.panel.add_arrow(x1, y1, x2, y2, **kws)", "title": ""}
{"_id": "d20599", "text": "def get_default_args(func):\n    \"\"\"\n    returns a dictionary of arg_name:default_values for the input function\n    \"\"\"\n    args, varargs, keywords, defaults = getargspec_no_self(func)\n    return dict(zip(args[-len(defaults):], defaults))", "title": ""}
{"_id": "d20600", "text": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n        -> Generator[Any, None, None]:\n    \"\"\"\n    Generate the first value in each row.\n\n    Args:\n        cursor: the cursor\n        arraysize: split fetches into chunks of this many records\n\n    Yields:\n        the first value of each row\n    \"\"\"\n    return (row[0] for row in genrows(cursor, arraysize))", "title": ""}
{"_id": "d20601", "text": "def clean_column_names(df: DataFrame) -> DataFrame:\n    \"\"\"\n    Strip the whitespace from all column names in the given DataFrame\n    and return the result.\n    \"\"\"\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f", "title": ""}
{"_id": "d20602", "text": "def astensor(array: TensorLike) -> BKTensor:\n    \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor", "title": ""}
{"_id": "d20603", "text": "def list_to_csv(value):\n    \"\"\"\n    Converts list to string with comma separated values. For string is no-op.\n    \"\"\"\n    if isinstance(value, (list, tuple, set)):\n        value = \",\".join(value)\n    return value", "title": ""}
{"_id": "d20604", "text": "def _unzip_handle(handle):\n    \"\"\"Transparently unzip the file handle\"\"\"\n    if isinstance(handle, basestring):\n        handle = _gzip_open_filename(handle)\n    else:\n        handle = _gzip_open_handle(handle)\n    return handle", "title": ""}
