content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_template_names(info):
"""
Generates template names with specific template order. For template 404:
404.html
40x.html
4xx.html
error.html
"""
return [
f'{info["value"]}.html',
f'{info["value"][:2]}x.html',
f'{info["value"][:1]}xx.html',
f'error.html',
] | 4b424d9281ba53583b31d10b38ca681323bef2c1 | 582,740 |
def compare_range(a, astart, aend, b, bstart, bend):
"""Compare a[astart:aend] == b[bstart:bend], without slicing.
"""
if (aend-astart) != (bend-bstart):
return False
for ia, ib in zip(range(astart, aend), range(bstart, bend)):
if a[ia] != b[ib]:
return False
else:
... | 0cbb92a073d4b3156b11c295374e2fdc81995f03 | 582,742 |
def databaseSettingsDict(db_dict):
"""
Function for transfroming the database setting dict into a one that psycopg2 accepts.
:param dict db_dict: Dict of from the database configuration file
:returns: dict fitted for psycopg2.connect function
"""
newdict = dict(db_dict)
del newdict['locatio... | d5f1a9d33c801001607b12d48ff34ad124603f2b | 582,743 |
def ip_for_request(request):
"""
Returns ip address for request - first checks ``HTTP_X_FORWARDED_FOR``
header, since app will generally be behind a public web server.
"""
meta = request.META
return meta.get("HTTP_X_FORWARDED_FOR", meta["REMOTE_ADDR"]) | fb8c39052cd22d2c736f36c9dd74f0eb8777db48 | 582,744 |
def _bits32(i):
"""Truncates an integer to 32 bits."""
return i&4294967295 | 2e03a7732542309e3f71ee3c6651971c79e3bfe0 | 582,746 |
def scale4(a,c):
""" 4 vector ``a`` times scalar ``c``"""
return [a[0]*c,a[1]*c,a[2]*c,a[3]*c] | abb1fe533f3e8ad2b919ec91b1554a5a51315451 | 582,747 |
def percentage(value):
"""Returns the number as percentage with two-digit precision"""
try:
value = float(value)
except (ValueError, TypeError, UnicodeEncodeError):
return ''
return '{0:.2%}'.format(value) | dddae997bcb18f4718f902b289372996305df432 | 582,749 |
async def create(hub, ctx, name: str, image: str, wait=False):
"""
Create a new container.
CLI Example:
.. code-block:: bash
idem exec lxd.containers.create container01 centos7
idem exec lxd.containers.create container01 centos7 wait=True
"""
if await hub.tool.lxd.api.request(... | 776d8eb1ce9a2189ab7abea376ad8eabbda5c1f5 | 582,751 |
def bounds_from_notchcount(count):
"""Returns the boundaries between a desired number of power notch levels.
The power range between 0 to 255 can be subdivided into a desired number
of notch levels (up to 8 levels). For example, 2 notch levels would
return a list with one bound of 128. 4 levels would... | 91a0baab0994a44550b9a7392d545c791d5cf17c | 582,753 |
import re
def labelCommands(commands, labelRules, defaultLabel = None):
"""Labels the commands according to the label rules.
Label rules are of the form (cmd pattern, arg pattern). Rules can
be combined such as
(cmd pattern, arg pattern)&(cmd patter, arg pattern)
When rules are combined, they re... | 45a908c1f68b05a7674bcc5a3fc7d7d0ff794011 | 582,761 |
import time
def delta(t, desc):
"""Helper function to print a time delta with a message."""
delta = time.time() - t
print("[{:.8f}s] {}".format(delta, desc))
return time.time() | c9e9e80c39e0511b3597608c608b3fcf97c7f5d2 | 582,770 |
def normalize(next_grams_counter):
"""
For a given n-gram, divide the frequency of each next gram with
the sum of the frequencies of all the possible next grams.
:param next_grams_counter: A collections.Counter object about an n-gram
:return: A list of (gram, probability) tuples.
"""
s = flo... | b16316c6d53de02baa72340781b239c88a03d715 | 582,772 |
def add_two(one, two):
"""Adds two values together and returns it."""
return one + two | 754b4d8de6449504a73dcacb52088c2f898eab41 | 582,773 |
import torch
def pad(data_tensor, pad_size, dim, pad_at_end=True):
"""
Pads a Tensor with zeros along a dimension.
:param data_tensor: Tensor to pad.
:param pad_size: How many zeros to append.
:param dim: The dimension to pad.
:param pad_at_end: Whether to pad at the end.
:return: Padded ... | 8eaf22c50f9b363d6843af8005e69957827567a4 | 582,777 |
def get_text(analysis):
"""
Gets the resultant text of the image supplied
Arguments:
analysis {JSON} -- JSON form of the final response
that contains the text detected
Returns:
[list] -- Returns the polygon data, and the text detected
"""
if('recognitionResu... | 45a787dfc6989198717d13400a3d6c6f696def68 | 582,780 |
from pathlib import Path
from typing import List
from typing import Dict
def define_expected_envrc_variables(
folder: Path,
exclude_folders: List[str],
exclude_root_folders: List[str],
exclude_sub_folders_in_parent_folders: List[str],
) -> Dict[str, Path]:
"""Get the expected export directory vari... | acb8f96d20b1ecf433e0c64a4da80f3ec2394443 | 582,783 |
import io
def is_sh(executable):
"""Determine if the specified executable is a .sh (contains a #! line)"""
try:
with io.open(executable, encoding='latin-1') as fp:
magic = fp.read(2)
except (OSError, IOError):
return executable
return magic == '#!' | 93e6c5204fc54b13d5b58bce7e8e8e9889f173ae | 582,787 |
def log_str(obj, func, msg):
"""Compose a log message with an object's class name and (optional) function name."""
if func is None:
return "{0}: {1}".format(obj.__class__.__name__, msg)
else:
return "{0}.{1}(): {2}".format(obj.__class__.__name__, func, msg) | f3169016db1f0bcfa7642055711a99d7ae008d23 | 582,788 |
import requests
def get_request(uri):
"""
Make an HTTP GET request to the (EDR) Server at `uri`.
"""
response = None
status_code = None
errors = None
print(uri)
try:
r = requests.get(uri)
except Exception as e:
errors = e.__class__.__name__
else:
respon... | b0edb661749ae102818b007084fa9a2e15de2ac0 | 582,789 |
from typing import Union
from pathlib import Path
def is_binary_file(filename: Union[str, Path]) -> bool:
"""
Check if file is a binary file.
Args:
filename (`str` or `Path`):
The filename to check.
Returns:
`bool`: `True` if the file passed is a binary file, `False` othe... | 5292802082f0b93096ea3e044305c0219a7e1a01 | 582,791 |
def wsgi_key_of_header_name(header_name: str) -> str:
"""
>>> wsgi_key_of_header_name('Accept-Language')
'HTTP_ACCEPT_LANGUAGE'
>>> wsgi_key_of_header_name('Authorization')
'HTTP_AUTHORIZATION'
"""
return 'HTTP_' + header_name.replace('-', '_').upper() | 1e147e9004d849b247d4e10bc2d6711918088af9 | 582,793 |
def vcolor(data, pattern):
""" Color a graph line by line
:param data: the data
:type data: list of tuples (info, value)
:param pattern: list of colors, this list defines
the pattern to color each line of the graph.
:type pattern: list of 'colors' (str)
:return: the colored graph
:rty... | b468402fa116cd6843fe5d904531d43b607ba83d | 582,796 |
def regularize_truncation(truncation):
""" regularize_truncation( (code, cutoff) ) -> (N1b,N2b)
Converts a mnemonic description ("ob",N1b) or ("tb",N2b) to the
appropriate (N1b,N2b) pair for a two-body interaction file.
"""
(code, N) = truncation
if (code == "ob"):
return (N,2*N)
e... | 10569fc565109a8d5e4da02b12ea63aa68274568 | 582,800 |
def convert_old_time(time: str, revert_12hour=False, truncate_minute=False) -> str:
"""
Convert previous float-formatted times to 24-hour, full format
Parameters
----------
time:
a time from the previous CourseTable format
revert_12hour:
whether or not to convert back to 12-hour... | cf77f7dca1e2ea728781dd5db7b255d7b5becec4 | 582,804 |
def parse_hibp_page(page_str):
"""
>>> parse_hibp_page('A8C4A624898B4221FC963986F9DC19CF42E:1\r\nAA18199A6DB91A7A4BB1C4B2A89068DAAFC:1\r\n')
{'A8C4A624898B4221FC963986F9DC19CF42E': 1, 'AA18199A6DB91A7A4BB1C4B2A89068DAAFC': 1}
"""
return dict(
(hash_suffix, int(frequency))
for (hash_... | 65890e99e76ea2f89f1d74de266ed18498dce8f1 | 582,806 |
import string
import zipfile
def create_proxyauth_extension(proxy_host, proxy_port,
proxy_username, proxy_password,
scheme='http', plugin_path=None):
"""
Proxy Auth Extension
args:
proxy_host (str): domain or ip address, ie proxy.domain... | 0d47faa57ff25b10007b2fe037e61c518f1fad0e | 582,807 |
def identify(tech: str, ctx: str):
"""Adds two attributes to a class: (1) the class technology (mqtt, sqlite,
etc...) and (2) the class context (database, interface or sender).
Params
------
tech: str -- the technology associated with the class
ctx: str -- the context where the class is inserted
Returns
-----... | 4b6c3b3cafa210e2eb3c29e72c2e094d564a2584 | 582,812 |
def as_dict(traited_instance):
"""Returns a dictionary from the traited class, with keys
equal to trait names and values the corresponding values."""
return {attr: getattr(traited_instance, attr)
for attr in traited_instance.trait_names()} | 5ee0b90b6361bcdb501119fd2870475ee2b383ae | 582,817 |
def _get_destination_folder(json_spec, folder_name=None):
"""
Returns destination project in which the workflow should be created.
It can be set in the json specification or by --destination option supplied
with `dx build`.
The order of precedence is:
1. --destination, -d option,
2. 'folder'... | dc7b99fc3b2f40d4629a04f40aeeb65d3fc30c4a | 582,819 |
def clean(token):
"""
Remove blank characters.
"""
return token.strip() if token else None | 91bad9205adaa0c16ae0247bdeec63f96acecbe8 | 582,820 |
def __format_command(command):
"""
Formats the command taken by run_command/run_pipe.
Examples:
> __format_command("sort")
'sort'
> __format_command(["sort", "-u"])
'sort -u'
> __format_command([["sort"], ["unique", "-n"]])
'sort | unique -n'
"""
if i... | 86a6d342c414433f70a54c03feefc4adb5f7f3f5 | 582,822 |
def _is_a_namedtuple(field_type: type) -> bool:
"""Determine whether or not a field type is a NamedTuple class."""
return hasattr(field_type, '_fields') | 914791a96f5943a3391b80666dbb4becccadbe18 | 582,824 |
from typing import List
from functools import reduce
def names_to_vs(names: List[str]) -> str:
"""
Return a string made by names joined by "vs".
"""
return reduce(lambda x, y: x + ' vs ' + y, names) if len(names) > 1 else names[0] | 62a123d603164a5e3ca134d30e55e1b2bf8bd6c7 | 582,830 |
def marathon_app_id_to_mesos_dns_subdomain(app_id):
"""Return app_id's subdomain as it would appear in a Mesos DNS A record.
>>> marathon_app_id_to_mesos_dns_subdomain('/app-1')
'app-1'
>>> marathon_app_id_to_mesos_dns_subdomain('app-1')
'app-1'
>>> marathon_app_id_to_mesos_dns_subdomain('/grou... | a0e9e755aa4987fa0e35dfc238f8018c2ee89e71 | 582,831 |
def remove_substrings(text, to_replace, replace_with=""):
"""
Remove (or replace) substrings from a text.
Args:
text (str): raw text to preprocess
to_replace (iterable or str): substrings to remove/replace
replace_with (str): defaults to an empty string but
you replace su... | 765247ffd7ee4caa33a3afffbca7e47799bc0b16 | 582,832 |
def render_entities_html(passage, m_starts, m_ends):
"""Add <b> tags to mark entities in string passage."""
sorted_i = sorted(enumerate(m_ends), key=lambda x: x[1], reverse=True)
for ii in sorted_i:
passage = passage[:m_ends[ii[0]]] + "</b>" + passage[m_ends[ii[0]]:]
passage = passage[:m_starts[ii[0]]] + ... | b44454b476c75e369cf343f6bd256816855474f5 | 582,834 |
def _ispath(string):
"""Check if a string is a directory."""
if string.startswith('$') or string.startswith('/'):
return True
else:
return False | 920c94961d788884bc1ee7c03846903c8ae33629 | 582,835 |
from typing import List
def sort_values(values_dict: dict) -> List[tuple]:
"""Returns a list of tuples that is sorted by the values of a given dict."""
return sorted(((value, key) for key, value in values_dict.items()),
reverse=True) | e341a26646a965ce433db93542776b818e659813 | 582,837 |
from pathlib import Path
from typing import List
from typing import Tuple
from typing import IO
def compute_chunks(file_path: Path, nb_chunks: int) -> List[Tuple[int, int]]:
"""Take a `file_descriptor` to a (non padded) text file, the file size and a
number of chunks. Outputs a list of tuple.
For each tup... | c2e471f5965529784c929366c1acbd61c12d4c1e | 582,838 |
def normalize_go_id(identifier: str) -> str:
"""If a GO term does not start with the ``GO:`` prefix, add it."""
if not identifier.startswith('GO:'):
return f'GO:{identifier}'
return identifier | 01cac614f0a8833edc5ffedfcb9008b21dba2d6e | 582,839 |
def clean_cat(catalog, pdict, fill_mask=None):
"""
Convert table column names intrinsic to the slurped
catalog with the FRB survey desired values
Args:
catalog (astropy.table.Table): Catalog generated by astroquery
pdict (dict): Defines the original key and desired key
fill_mas... | 5bc59c046f3d259a1653de036e0a8727487caeb7 | 582,840 |
def help(inp, *, command, elemental):
"""Give a link to the help page."""
if elemental:
return
url = 'http://scp-stats.wikidot.com/jarvis'
return url if not command else url + '#' + command.replace(' ', '-') | fe8e926b6cdd8dd3389abe00fe969f0e6eac6257 | 582,848 |
import collections
def to_vector(signal, channels=None):
"""Convert a signal to a vector"""
if channels is None:
# we need consistent ordering
assert isinstance(signal, collections.OrderedDict)
return tuple(signal.values())
else:
return tuple(signal[c.name] for c in channel... | 9cea95f274ca505ef1616459d576809707df76c5 | 582,849 |
import typing
def get_allowed_kinds() -> typing.List[str]:
""" Get list of implemented charts
Returns:
typing.List[str]: List of implemented chart types
"""
return ["race", "line", "scatter","pie","bar"] | 620c7b2de052d6f5b61c8d4e894d60c61726efc9 | 582,853 |
def nested_contains(list_: list, value: object) -> bool:
"""
Return whether list_, or any nested sub-list of list_ contains value.
>>> list_ = ["how", "now", "brown", 1]
>>> nested_contains(list_, "now")
True
>>> nested_contains(list_, 1)
True
>>> nested_contains(list_, 3)
False
... | 5b8d641aeb8f61cf6e9e40d7f3223fbeec0c221b | 582,858 |
import requests
def get_page(url):
"""
Use request to get an URL page
:params:
url str: the URL to parse
:returns:
requests object text
"""
page = requests.get(url)
return page.text | f899cb953ad0bbd383a78a1ae77f7c1cc41f778f | 582,859 |
def filter_nuc_variants(nuc_variants):
"""
Transforms nucleotide variants of type SUB longer than 1 in multiple variants of length 1.
Ignore insertions or substitutions of alternative sequence 'n'.
Removes duplicated variant impacts.
"""
new_nuc_variants = []
for n in nuc_variants:
s... | 4bdc507de783ba4d536352fc8144dc3b7ffc2737 | 582,860 |
def IsLocalId(model_id):
"""Returns true if the given id is a local id, false otherwise."""
try:
int(model_id)
except ValueError:
return False
return True | 7435cabc3c0e576a0774538ce1b56c5bfecb8abd | 582,861 |
def sortkey(item):
""" Sorting key function that is robust to different types
Both strings and tuples are common key types in dask graphs.
However In Python 3 one can not compare strings with tuples directly.
This function maps many types to a form where they can be compared
Examples
--------
... | 6d7dd40b75d5684e0de14f6a255daa103d6d2838 | 582,862 |
def error_check(elem):
"""Check if the response sent by Authorize.net contains an error.
Errors can be a failure to try the transaction (in that case, the transasctionResponse
is empty, and the meaningful error message will be in message/code) or a failure to process
the transaction (in that case, the ... | b3be4eadf2e621f1ae878e6fce33e2a89b1dca67 | 582,864 |
import math
def absolute_value(vector):
"""Returns the absolute value of a vector.
It is calculated by the
euclidean norm ``abs(a) = Sqrt( pow(a1) + pow(a2) + pow(a3) )``
:param vector: vector.abstractvector.DocumentVector
:type vector: the vector whose absolute value will be calculated
:ret... | ad29087601f706113dcadb1dd77e780c22045a80 | 582,866 |
def make_parameter(name, values, **kwargs):
""" define a new parameter that will be added to a store.
Primarily takes a name and an array of potential values.
May also be given a default value from inside the array.
May also be given a typechoice to help the UI which is required to be
one of 'list',... | a77eb681f9c055c3407b4f5ed88180f90569e44a | 582,870 |
def calc_corr(ser1, ser2, window):
"""
Calculates correlation between two series.
"""
ret1 = ser1.pct_change()
ret2 = ser2.pct_change()
corr = ret1.rolling(window).corr(ret2)
return corr | 260254d41358e79a1970d3e945934eab9c0e17f3 | 582,872 |
def more_synonyms(data):
"""Expand list of possible synonyms from ["foo bar"] to ["foo-bar"]"""
def moar(s):
yield s
if " " in s:
yield s.replace(" ", "-")
for ds in data:
for cf in ds["exchanges"]:
cf["synonyms"] = [s for item in cf["synonyms"] for s in moa... | eae03e72486f298fc8245ef9edff1546394419ae | 582,874 |
import ctypes
def depth_cb_string_factory(func):
"""Converts the raw depth data into a python string for your function
Args:
func: A function that takes (dev, data, timestamp), corresponding to C function
except that data is a python string corresponding to the data.
"""
def dept... | 3f99468b8b4676c2f0a35a0f2192a556c4603819 | 582,878 |
def hz2fft(fb, fs, nfft):
"""
Convert Bark frequencies to fft bins.
Args:
fb (np.array): frequencies in Bark [Bark].
fs (int): sample rate/ sampling frequency of the signal.
nfft (int): the FFT size.
Returns:
(np.array) : fft bin numbers.
"""
return (n... | 23bbcac0778b34595f57ec840aa684063170d4af | 582,879 |
from pathlib import Path
def get_dataset_golden_types_path(dataset_name: str) -> str:
"""Returns the path to the golden types file for the given dataset."""
return str(Path(__file__).resolve().parent / "golden" / f"{dataset_name}.types.json") | 8d6a005f1263beed33b7acbcbe084854e44fdd22 | 582,885 |
def fun(t, z, omega):
"""
Right hand side of the differential equations
dx/dt = -omega * y
dy/dt = omega * x
"""
x, y = z
f = [-omega*y, omega*x]
return f | 7eff6fd1327d3f2e39a0f8bdec1642063baab03c | 582,886 |
def writeVector(q):
"""Writes a vector to text 'n v1 ... vn'"""
return str(len(q))+'\t'+' '.join(str(v) for v in q) | 7edb9535e97beec0d889b09a7640979acb1649c2 | 582,889 |
import torch
def mse_loss(pre, gt):
""" MSE loss
"""
return torch.nn.functional.mse_loss(pre, gt) | e9bb34096960d3ac3586d5154d330dc4a614108c | 582,890 |
def PrettifyList(items):
"""Returns a string representation of a list.
It adds comma in between the elements and removes the brackets.
Args:
items: A list to prettify.
Returns:
A string representation of the list.
"""
return ', '.join(map(str, items)) | b241e2432ddef170c11ba670a7e367c4e1a153d5 | 582,891 |
import requests
def gcs_post_request(url):
""" Performs a POST request to the given url.
Args:
url: A str, the URL to POST to.
Raises:
HTTPError if the resource cannot be reached.
"""
return requests.request('POST', url, verify=False) | 8e8ad9f62ff23178c5365f0daab03264df4e400f | 582,892 |
def member( x, set ):
"""test for set membership"""
try:
set.index( x )
return True
except ValueError:
return False | 9a61de3c34b2e401e4cc3fc6d3b5be30edb36390 | 582,893 |
def IsCustomMetadataHeader(header):
"""Returns true if header (which must be lowercase) is a custom header."""
return header.startswith('x-goog-meta-') or header.startswith('x-amz-meta-') | 2875ee1c49ee26ab971dd026d09951d9d1556894 | 582,904 |
import re
def find_certs(txt):
"""Split text with multiple certificates into a list of certificates.
Args:
txt (:obj:`str`):
the text to find certificates in.
Returns:
(:obj:`list` of :obj:`str`)
"""
pattern = r"-----BEGIN.*?-----.*?-----END.*?-----"
pattern = re... | 77324e76ed6a5f5a616ea20bf6a8299779c6c53a | 582,906 |
import requests
def api_get(url):
"""
Use requests package to perform GET
"""
resp = requests.get(url)
if resp.status_code != 200:
raise NotImplementedError
return resp.json() | 19fc614374515054d3335e3e426cd4790ff001b3 | 582,908 |
def sample(field, inds=None, slicer=None, flat=True):
"""
Take a sample from a field given flat indices or a shaped slice
Parameters
-----------
inds : list of indices
One dimensional (raveled) indices to return from the field
slicer : slice object
A shaped (3D) slicer that ret... | 7ff4fc8e68cfc277a66261530b869313f6572aaf | 582,909 |
def _find_flavor(client, name):
""" Return the first flavor which matches the given name """
for flavor in client.flavors.list():
if flavor.name == name:
return flavor | 22c8c224baaf5694135f0830de46a3dc89560c45 | 582,910 |
def expand(node, x=0, y=0, clip=None, level=0):
"""Turn a quadtree a list of (x,y,gray) triples
in the rectangle (x,y) -> (clip[0], clip[1]) (if clip is not-None).
If `level` is given, quadtree elements at the given level are given
as a grayscale level 0.0->1.0, "zooming out" the display.
"""... | d8abd574bba6be24c762410089ad917f5fa24388 | 582,913 |
def is_school_holidays(school_holidays_dt, day_dt):
"""
:param school_holidays_dt: List of tuple(start_date, end_date) which represents the school holidays period,
format of the dates is datetime
:param day_dt: Day with format datetime to analyze
:return: Boolean, True if day ... | ec84316e3b6207afe680f160a4a722c7288235f6 | 582,920 |
import torch
def exponential_transition(perturbations, norm, epsilon=0.3, gamma=1):
"""
Exponential transition rule.
:param perturbations: perturbations
:type perturbations: torch.autograd.Variable
:param norm: norm
:type norm: attacks.norms.Norm
:param epsilon: epsilon
:type epsilon:... | fe18820cdf9543d0c4928543d8174107de224694 | 582,921 |
def year_range(df, yr_column_name):
"""
Return the oldest and most recent year (yr) that a game was released
Parameters
----------
df : pandas object
dataFrame from which to pull the values
yr_column_name : string
name of the column containing the "Year" values
Retu... | 11ddea1edb768f6249b54ebcfdf899a55455b9fc | 582,924 |
def ask(question, default=None):
"""
Asks the user the question until he answers it with *yes* or *no*.
Returns true if the user answered with yes.
Returns *default* if the user only hit enter.
"""
if default is None:
prompt = question + " (yes|no) "
elif default:
prompt = q... | c1ea2b9276b022c99f497b6c5682a78ae4aceee8 | 582,925 |
def admin_actions(context):
"""
Track the number of times the action field has been rendered on the page,
so we know which value to use.
"""
context['action_index'] = context.get('action_index', -1) + 1
return context | 98c9cefe5fe76552ff106d478a0877fcaa2df411 | 582,927 |
def normalize(operation, expr):
"""
Transform a expression into its normal form in the given operation.
Returns a tuple of arguments that will satisfy the condition
operation(*args) == expr (here mathematical equality is meant) and
the operation doesn't occur in any arg. Also NOT is only appearing
... | 01adfb6b6a3da438a54701bbb877ec619c01f7ca | 582,930 |
def MostPopularKey(d, default):
"""Given a dict, return the key corresponding to the largest
value. Returns 'default' if the dict is empty."""
x = [(v, k) for (k, v) in d.iteritems()]
if not x:
return default
x.sort()
return x[-1][1] | 2808c93f6aec9b881d5d7423339c5953a72315af | 582,931 |
import types
def is_method_of_class(mthd, cls):
"""
Returns True if function 'mthd' is a method of class 'cls'
:type mthd: function
:type cls: class
:return: True if 'mthd' is a method of class 'cls', and False otherwise.
:rtype: bool
"""
try:
class_method = getattr(cls, mthd.... | 91a1e78b70d6607390f153f3f268ad9613118dd6 | 582,932 |
async def async_setup_entry(hass, entry):
"""Set up Ambiclimate from a config entry."""
hass.async_create_task(hass.config_entries.async_forward_entry_setup(
entry, 'climate'))
return True | 0bd8e2e6d26cea5022a4ec877c52cee3583bc7e3 | 582,933 |
def with_decimal_places(number, decimal_count):
"""
Trims a float to a given number of decimal places
"""
# n is a placeholder for the number of decimals to keep
return "{:.nf}" \
.replace("n", str(decimal_count)) \
.format(number) | 4a93c6a72e1446a33e7402283328a0e9e94851a6 | 582,936 |
def boostedScore(mep, country, factor=100):
""" Multiply and return a candidate's score by a factor if its country matches the requested one """
rc = mep['score']
if mep['country_short'] == country:
rc *= factor
return rc | 2000388c1ba7cbe485c508928da53e5709ba50f8 | 582,943 |
def weight(alpha, beta, x):
"""The weight function of the jacobi polynomials for a given alpha, beta value."""
one_minus_x = 1 - x
return (one_minus_x ** alpha) * (one_minus_x ** beta) | 66d5395e1fc5639c2417519c22d4ab318e2dd3b8 | 582,944 |
import random
def shuffle_two_list(a, b):
"""
shuffle两个列表
"""
c = list(zip(a, b))
random.shuffle(c)
a, b = zip(*c)
return a, b | 978e5b8cf3e962caf521e0c5214edf42e229c7ac | 582,945 |
import torch
def activation(x):
"""
Sigmoid activation function
Arguments
---------
x: torch.Tensor
"""
return 1/(1 + torch.exp(-x)) | c948b0790ef8733588cc63cadb2a97a512c2b589 | 582,948 |
def getOrganismCountsFromFile(orgCountFile):
"""
Parse the given file into dictionary from organism name to count of hits
"""
orgCounts = {}
with open(orgCountFile) as f:
for line in f:
(organism, counts) = line.split(None, 1)
orgCounts[organism] = int(counts)
ret... | 69e489bc85b387b39a092cc7682038a6e100d950 | 582,950 |
def inverse_dict(dic):
"""Accepts dictionary, returns dictionary where keys become values,
and values become keys"""
new_dict = {}
for k, v in dic.items():
new_dict[v] = k
return new_dict | cb44b34a70aaaa159912e65f96e36daa64be5471 | 582,951 |
def sanitize_text(text: str) -> str:
"""Sanitizes and removes all useless characters from the text, returns sanitized text string"""
alphanum_text = ""
for letter in list(text):
if letter.isalnum() or letter == " " or letter in "!?.,:;\'\"&()$%#@~":
alphanum_text += letter
return al... | 0e22dedaa729fcfe593644782f129e94af767a9f | 582,953 |
import re
def _convert_dtmi_to_path(dtmi):
"""Converts a DTMI into a DTMI path
E.g:
dtmi:com:example:Thermostat;1 -> dtmi/com/example/thermostat-1.json
"""
pattern = re.compile("^dtmi:[A-Za-z](?:[A-Za-z0-9_]*[A-Za-z0-9])?(?::[A-Za-z](?:[A-Za-z0-9_]*[A-Za-z0-9])?)*;[1-9][0-9]{0,8}$")
if not pa... | 63b099685e48c7f17fedf66942c93627be2d2cf0 | 582,958 |
def findLocations(data, single=False):
"""Extract the path from a location tag
Args:
data (xml.etree.ElementTree.Element): xml from PMS as Element
single (bool, optional): Only return one
Returns:
filepath string if single is True else list of filepaths
"""
locations = []
... | 75ff9d2c1bd3b8815d8111d7404584ac29574718 | 582,959 |
def webstring(value):
""" Convert a Python dictionary to a web string where the values are in the
format of 'foo=bar&up=down'. This is necessary when processing needs to be done
on a dictionary but the values need to be passed to urllib2 as POST data. """
data = ""
for key in value:
new... | fbc12b8978b4ab7338d00ab24a986750f517da08 | 582,961 |
import csv
def _decode_csv(input_str):
""" Decodes CSVs into a list of strings. """
reader = csv.reader([input_str], quotechar='"', delimiter=',', escapechar="\\",
doublequote=False, quoting=csv.QUOTE_ALL, skipinitialspace=True);
result = []
for row in reader:
result += row
return ... | 6ab4e99ea17e502d498c5a79b23bbc37094e4743 | 582,965 |
from typing import Callable
def safe_split(source: str, delimiter=',', converter: Callable = lambda x: x):
"""
Splits a string via the delimiter, throws out any empties and strips the whitespace from each item
:param source: str
:param delimiter: str
:param converter: Callable
:return: list
... | f6d836a4ef21c6325c4fc031960f838cd431b5d3 | 582,973 |
def clamp(val, min_=0.0, max_=1.0):
""" Clamp a value between an upper and lower bound. """
return min_ if val < min_ else max_ if val > max_ else val | 82f033cf36955e3f868964f7eaa19843e0fd6e71 | 582,977 |
def parse_metrics(metrics: tuple) -> dict:
"""
Parse and convert the metrics captured by get_metrics() into a dictionary.
The main role of this is to parse the enormous dict returned by docker.container.stats and just
retrieve the memory usage as a list. NOTE: memory_usage_mb is total usage in megabyte... | 0dd726c39662c680f6c5d3e18585bce20391d2a6 | 582,984 |
def load_pdb_ids(pdb_ids_file: str) -> list:
"""
Load the list of PDB IDs from a file.
Automatically detect the separator used in the file, which is the 5th character.
Then check that last character of the file is the same character.
:param pdb_ids_file: path to the file containing the list of PDB... | e5e35fc8645045db72f0ff27d5eba6a49a2a786a | 582,985 |
import json
def get_scan_fields(series,fieldnames):
"""
For applying to each row of a dataframe.
The field is extracted from the json and added to the
sub_sess tsv.
"""
json_path = series.json_path
with json_path.open() as j:
data = json.load(j)
for f i... | dc77e8037408bdbed61fb64107db6f7474c44b48 | 582,996 |
def GetGuestPolicyRelativePath(parent, guest_policy):
"""Return the relative path of an osconfig guest policy."""
return '/'.join([parent, 'guestPolicies', guest_policy]) | 20a3ce383921230b276d70fc44021496ab7fa959 | 582,997 |
def get_user_expense(items, user):
"""Returns expense per user
Args:
items (List[List[str, float, dict]]): Constains the parsed expense
user (str): User name
Returns:
Total expense for the user.
"""
total_user_expense = 0.0
for item in items:
distribution = ... | b538c0c68d41317174914ddad76bf390abfb9ec4 | 582,998 |
import ntpath
def path_leaf(path):
"""
Get just the filename from the full path.
http://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format
"""
head, tail = ntpath.split(path)
return tail or ntpath.basename(head) | 7b2b4215e80b06b411c1ea549cfb9e3c64303473 | 583,000 |
def no_of_elements(mesh):
"""
Calculate the number of elements contained in the given mesh.
Parameters
----------
mesh : dict
mesh dict containing
at least the following keyword
elements : dict of ndarrays
Contains array of nodes for elements sorted by el... | 256fcc8823acc192830945963b3ec6b5a505c3a3 | 583,002 |
def any_tagged_cell(nb, tag):
"""Whether the notebook contains at least one cell tagged ``tag``?
Parameters
----------
nb : nbformat.NotebookNode
The notebook to introspect
tag : str
The tag to look for
Returns
-------
bool
Whether the notebook contains a cell t... | a5645aae183de4dda5bc4610091dbee5e890d0b0 | 583,006 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.