content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def fold_change(c, RK, KdA=0.017, KdI=0.002, Kswitch=5.8):
""" Function computes the theoretical fold change in repression."""
# Compute fold change
fold_change = (1 + RK*((1+c/KdA))**2/((1+c/KdA)**2 + Kswitch*(1+c/KdI)**2))**(-1)
# Return concentration array and fold change array
return fold_change | 2fbc0eee45667443ba33a08f34bae7f7d80073cd | 313,145 |
def denpify(f):
"""
Transforms a function over a tuple into a function over arguments.
Suppose that
`g` = ``denpify(f)``,
then
`g(a_1, a_2, ..., a_n) = f((a_1, a_2, ..., a_n))`.
Examples
--------
>>> flip((0, 1))
(1, 0)
>>> f = denpify(flip)
>>> f(0, 1) # note the the argument is *not* a tuple
(1, 0)
"""
return lambda *t: f(t) | 57ee3aa381352eab2823da0a30e6252d0377bdfe | 662,007 |
def lol_tuples(head, ind, values, dummies):
"""List of list of tuple keys
Parameters
----------
head : tuple
The known tuple so far
ind : Iterable
An iterable of indices not yet covered
values : dict
Known values for non-dummy indices
dummies : dict
Ranges of values for dummy indices
Examples
--------
>>> lol_tuples(('x',), 'ij', {'i': 1, 'j': 0}, {})
('x', 1, 0)
>>> lol_tuples(('x',), 'ij', {'i': 1}, {'j': range(3)})
[('x', 1, 0), ('x', 1, 1), ('x', 1, 2)]
>>> lol_tuples(('x',), 'ijk', {'i': 1}, {'j': [0, 1, 2], 'k': [0, 1]}) # doctest: +NORMALIZE_WHITESPACE
[[('x', 1, 0, 0), ('x', 1, 0, 1)],
[('x', 1, 1, 0), ('x', 1, 1, 1)],
[('x', 1, 2, 0), ('x', 1, 2, 1)]]
"""
if not ind:
return head
if ind[0] not in dummies:
return lol_tuples(head + (values[ind[0]],), ind[1:], values, dummies)
else:
return [
lol_tuples(head + (v,), ind[1:], values, dummies) for v in dummies[ind[0]]
] | 68ab4c1e8bf159f3fb0828a9e2a7812c1623ee6a | 479,196 |
import asyncio
async def service_failed(unit_name):
"""
Return true if service with given name is in a failed state.
"""
proc = await asyncio.create_subprocess_exec(
'systemctl',
'is-failed',
unit_name,
# hide stdout, but don't capture stderr at all
stdout=asyncio.subprocess.DEVNULL
)
ret = await proc.wait()
return ret == 0 | 6af31bd1ddbdd6f8c67fabb527f8b571e7c8d90c | 529,859 |
import hashlib
import json
def check_hash(hash: str, content: dict) -> bool:
"""Check that the stored hash from the metadata file matches the pyproject.toml file."""
# OG source: https://github.com/python-poetry/poetry/blob/fe59f689f255ea7f3290daf635aefb0060add056/poetry/packages/locker.py#L44 # noqa: E501
# This code is as verbatim as possible, with a few changes to be non-object-oriented.
_relevant_keys = ["dependencies", "dev-dependencies", "source", "extras"]
def get_hash(content: dict) -> str:
"""Returns the sha256 hash of the sorted content of the pyproject file."""
content = content["tool"]["poetry"]
relevant_content = {}
for key in _relevant_keys:
relevant_content[key] = content.get(key)
content_hash = hashlib.sha256(json.dumps(relevant_content, sort_keys=True).encode()).hexdigest()
return content_hash
return hash == get_hash(content) | 5b4d9407c95eb2239c42dd13c5052ce011f4fa5a | 36,694 |
def _normalize(df, col, start_values, target_values):
"""Normalize the values in **col** relative to the total possible improvement.
We normalize the values of **col** by calculating the share of the distance between
the start and target values that is still missing.
Note: This is correct whether we have a minimization or a maximization problem
because in the case of a maximization both the sign of the numerator and denominator
in the line where normalized is defined would be switched, i.e. that cancels out.
(In the case of a maximization the total improvement would be target - start values
and the currently still missing improvement would be target - current values)
Args:
df (pandas.DataFrame): contains the columns **col** and "problem".
col (str): name of the column to normalize
start_values (pandas.Series): index are problems, values are start values
target_values (pandas.Series): index are problems, values are target values.
Returns:
pandas.Series: index is the same as that of sr. The lower the value the closer
the current value is to the target value. 0 means the target value has been
reached. 1 means the current value is as far from the target value as the
start value.
"""
# expand start and target values to the length of the full DataFrame
start_values = df["problem"].map(start_values)
target_values = df["problem"].map(target_values)
normalized = (df[col] - target_values) / (start_values - target_values)
return normalized | a57705ec4591a51bb2a7b4f1db3a81474c387892 | 139,796 |
def get_title(file_path: str) -> str:
"""
Get the title of the file based on its position in the file.
If there is a title, it will be the first line followed by two blank lines.
"""
with open(file_path, 'r', encoding='utf-8') as f:
MAX_BLANK_LINES = 2
blank_lines = 0
lines = f.read().splitlines()
for line in lines[:MAX_BLANK_LINES + 1]:
if line.strip() == '':
blank_lines += 1
if (blank_lines == MAX_BLANK_LINES):
return lines[0]
return '' | ad9136958f63a91a47e8488a94f896164b833353 | 396,704 |
def toggle_bits(S, *positions):
"""
Returns a new set from set `S` with bits toggled (flip the status of) in the given `positions`.
Examples
========
Toggle the 2-nd item and then 3-rd item of the set
>>> S = int('0b101000', base=2)
>>> S = toggle_bits(S, 2, 3)
>>> bin(S)
'0b100100'
"""
for j in positions:
S = S ^ (1 << j)
return S | dd933090595273832b42e8e68de5d4e3be472ff8 | 353,442 |
import re
def remove_vowels(txt):
"""Remove every vowel from string txt."""
return re.sub(r'[a|e|i|o|u|A|E|I|O|U]', '', txt) | 7f187e8e07211c23fb94dbf28b9a081f666f1ac8 | 564,306 |
def check_port(port):
""" Check if a port is valid. Return an error message indicating what is invalid if something isn't valid. """
if isinstance(port, int):
if port not in range(0, 65535):
return 'Source port must in range from 0 to 65535'
else:
return 'Source port must be an integer'
return None | 6aa6d4113613daf6520251f142dcd8f94cd1b213 | 552,278 |
def build_event_info(info, time):
"""Adds created_at time to event info dict."""
return {**info, 'created_at': time} | a7faa2d3798d2692310af16e84099d7b86fa84f0 | 49,192 |
def _str_to_hex(s: str) -> str:
"""
Convert given string to hex string.
given string can be one of hex format, int, or a float between 0 and 1.
>>> _str_to_hex('0xFf')
'Ff'
>>> _str_to_hex('200')
'c8'
>>> _str_to_hex('0.52')
'84'
"""
if s.startswith('0x'):
return s[2:].zfill(2)
if s.isdigit():
return hex(int(s))[2:].zfill(2)
return hex(int(float(s) * 255))[2:].zfill(2) | a7def289214f593c287938591b0e0523ba1f2994 | 539,207 |
def number_factor(PD, SC=30.0, OD=0.32153):
"""
PD - Planet density
OD - Optimal density
SC - a number used to scale how bad it is to differ from the
optimal density. Lower number means less bad
Returns a number between 0.0 and 1.0 indicating how good the
density of planets is compared to the optimal density
"""
diff_from_opt = OD - PD
exponent = -SC * diff_from_opt * diff_from_opt
return pow(2.718281828, exponent) | be28fd46ca29552acd0f099c1843a00a75ccaa34 | 255,204 |
from typing import Counter
def same(word_1: str, word_2: str) -> bool:
"""
a simple helper function for checking if words match
:param word_1: a word
:param word_2: a word
:return: boolean, do words consist of exactly same letters?
"""
return Counter(list(word_1)) == Counter(list(word_2)) | 5fbe06e9699c84bdbdedae1e265dc773e82cb4ab | 513,214 |
import math
def poids_attirance(p, dist):
"""
Calcule le poids d'attraction d'une neurone vers une ville.
"""
d = p[0] * p[0] + p[1] * p[1]
d = math.sqrt(d)
d = dist / (d + dist)
return d | 4a997566d19dc7e436a3a1704be7b5ac74424266 | 12,688 |
def contains(main_str: str, sub_str: str) -> bool:
"""
>>> "a" in "abc"
True
>>> "bc" in "abc"
True
>>> "ac" in "abc"
False
>>> "" in "abc"
True
>>> "" in ""
True
"""
return sub_str in main_str | 7d949e1dcc6d5dfad020bf6debe34fd1a13cf40c | 124,084 |
def reduceColours(image, mode="optimised"):
"""Reduces the number of colours in an image. Modes "logo", "optimised"
Args:
image (PIL.Image.Image): Input image
mode (str, optional): Mode "logo" or "optimised". Defaults to
"optimised".
Returns:
PIL.Image.Image: A PIL Image
"""
modes = {"logo": 16, "optimised": 256}
return image.quantize(colors=modes[mode.lower()], method=2, kmeans=1, dither=None) | 5f655ed6f0cb16f049a62a95558b203a0ea23059 | 237,437 |
def is_route(tag):
""" Checks if an HTML tag is a bus route.
:param tag A BeautifulSoup tag
:return True if the tag has a "data-routes" attribute, False otherwise"""
return tag.has_attr("data-routes") | a568a7cd610095e233eed7f04caf04983572e4d7 | 615,840 |
def upsert_resource(apiroot, settings):
"""
Convenience function to create or update a resource
Args:
apiroot (obj): API endpoint root eg `api.cnxn.pipes`
settings (dict): resource settings
Returns:
response (obj): server response
data (dict): json returned by server
"""
try:
r, d = apiroot._(settings['name']).patch(request_body=settings)
except Exception as e:
if 'Not found' in str(e):
return apiroot.post(request_body=settings)
else:
raise e
return apiroot._(settings['name']).get() | 949326354ab41b2cc291dc7536d27755926856b2 | 585,179 |
def find_if(pred, iterable, default=None):
"""
Returns a reference to the first element in the ``iterable`` range for
which ``pred`` returns ``True``. If no such element is found, the
function returns ``default``.
>>> find_if(lambda x: x == 3, [1, 2, 3, 4])
3
:param pred: a predicate function to check a value from the iterable range
:param iterable: an iterable range to check in
:param default: a value that will be returned if no elements were found
:returns: a reference to the first found element or default
"""
return next((i for i in iterable if pred(i)), default) | 90515e2652cd9da0b446591b801593b02ad39d3d | 544,123 |
import itertools
def subsets(S):
"""
Return an iterator with all possible subsets of the set S.
Parameters
----------
S: set
a given set
Returns
-------
subsets: iterable
an iterable over the subsets of S, in increasing size
"""
subsets = []
for r in range(len(S) + 1):
subsets += [set(ss) for ss in itertools.combinations(S, r)]
return subsets | d757b03fdf541a89d803da19aa370382418c7f7b | 535,331 |
def output(the_bytes, as_squirrel=True):
"""
Format the output string.
Args:
the_bytes (list): The individual integer byte values.
as_squirrel (bool): Should we output as Squirrel code? Default: True
Returns:
str: The formatted output.
"""
out_str = "local unicodeString=\""
end_str = "\";"
if as_squirrel is False:
out_str = ""
end_str = ""
for a_byte in the_bytes:
out_str += (("\\x" if as_squirrel is True else "") + "{0:02X}".format(a_byte))
return out_str + end_str | 4042aaa1b44f2c52f81082a0f382bd11fa9613d0 | 432,715 |
def get_lomb_trend(lomb_model):
"""Get the linear trend of a fitted Lomb-Scargle model."""
return lomb_model['trend'] | 10334d850c8c6559169b4653912dd0bffc03f1fa | 319,245 |
def create_dataset(connection, body):
"""Create a single-table dataset from external data uploaded to the
MicroStrategy Intelligence Server.
Args:
connection (object): MicroStrategy connection object returned by
`connection.Connection()`.
body (str): JSON-formatted definition of the dataset. Generated by
`utils.formjson()`.
Returns:
HTTP response object returned by the MicroStrategy REST server.
"""
connection._validate_project_selected()
return connection.post(
url=f'{connection.base_url}/api/datasets',
json=body
) | 094d9eef49663b6606a40d73c6684f7f90f382f8 | 235,055 |
async def id_exists(collection, id_: str) -> bool:
"""
Check if the document id exists in the collection.
:param collection: the Mongo collection to check the _id against
:param id_: the _id to check for
:return: does the id exist
"""
return bool(await collection.count_documents({"_id": id_})) | 2c3355227b7d24133dc1383e47a26c03c468e2a4 | 578,243 |
def strToListFloat(s):
""" Convert a string to a list of float
"""
return map(float,s.split()) | 94317f2a6e802986d268ced16f09e2e0d3f5c507 | 560,020 |
def set_bit(number, site, N, bit):
"""
Change the bit value of number at a single site.
:param number: the number to be changed
:param site: the index of the site starting from left
:param bit: the bit value to be changed
:returns: the changed number
"""
if bit:
return number | (1 << (N-site))
else:
return number & ~(1 << (N-site)) | 01225923c410f0dbb76b5aa94854e8a2f961eb68 | 619,654 |
def id_is_int(patient_id):
""" Check if patient id is integer
Check if the patient's id is a integer
Args:
patient_id (int): id number of the patient
Returns:
True or str: indicate if the input patient id is an integer
"""
try:
int(patient_id)
return True
except ValueError:
return "Please use an integer or a numeric string containing " \
"an ID number but without any letter" | 21400915bf15cbdd01f594fc6d7e01ff045d528d | 127,196 |
def clean_code(code: str) -> str:
"""Replaces certain parts of the code, which cannot be enforced via the generator"""
# Mapping used for replacement
replace_map = [
("...", "default_factory=list"),
("type_class", "typeClass"),
("type_name", "typeName"),
("from core", "from easyDataverse.core"),
]
for replacement in replace_map:
code = code.replace(*replacement)
return code | f09eee589c74c4211afa778515c6186ea0c79496 | 119,683 |
from typing import List
from typing import Union
def findFirstVar(results : List[Union[None, int]]) -> Union[None, int]:
"""Finds the first index in a list of none's
Args:
results (List[Union[None, int]]): A list of none's and integers
Returns(either):
int: The first item's value(index)
None: If there were no indexes in the list, return none
"""
if len(results) == 0:
return None
if results[0] is not None:
return results[0]
return findFirstVar(results[1:]) | cb092688119a580707b98d810469ea832a5fd9a6 | 230,421 |
def drop_unneeded_cols(df_adverse_ev):
""" Drop the columns that will not be used as features """
drop_cols = ['companynumb','duplicate', 'occurcountry',
'patient',
'primarysourcecountry', 'receiptdateformat',
'receiver', 'receivedate', 'receivedateformat', 'reportduplicate',
'reporttype','safetyreportid',
'safetyreportversion', 'sender',
'transmissiondate','transmissiondateformat']
df_adverse_ev = df_adverse_ev.drop(drop_cols, axis=1)
return df_adverse_ev | 1d50de5e5bacf772fe128e491d5b1a872054d883 | 175,710 |
from typing import List
def ok(lines: List[str], join_on_newline: bool = True) -> bytes:
"""Send the given lines to stdout, preceded by a 20 (success) \
response.
:param lines: List of lines to send to stdout.
:param join_on_newline: Whether to join `lines` on newlines, or an \
empty string. Should be False if each line in `lines` \
already has a newline at the end.
:return: Bytes to be sent to the client.
"""
if join_on_newline:
content = '\n'.join(lines)
else:
content = ''.join(lines)
return f'20 text/gemini\r\n{content}\n'.encode() | bbd6df9bc18425f8ad144992a4f048670dc8ae8b | 319,069 |
def round_family(family, num_digits=3):
"""Round the matrix coefficients of a family to specified significant digits.
Parameters
-----------
family: iterable of Model objects that represents
a family.
num_digits: integer
Number if significant digits to which the matrix coefficients are rounded.
Returns
----------
A list of Model objects representing the family, with
the matrix coefficients rounded to num_digits significant digits.
"""
return [member.around(num_digits) for member in family] | 35e8f6bac7824d8b35d04820b40ce649609f885e | 499,502 |
import inspect
def _source(obj):
"""
Returns the source code of the Python object `obj` as a list of
lines. This tries to extract the source from the special
`__wrapped__` attribute if it exists. Otherwise, it falls back
to `inspect.getsourcelines`.
If neither works, then the empty list is returned.
"""
try:
return inspect.getsourcelines(obj.__wrapped__)[0]
except:
pass
try:
return inspect.getsourcelines(obj)[0]
except:
return [] | 0faf18c32fa03ef3ac39b8e163b8e2ea028e1191 | 674,432 |
def line_format(data, length=75, indent=0):
"""Format the input to a max row length
Parameters
----------
data: list
list och items that is beeing formated
length: int
how long is the max row length
indent: int
how many whitespaces should each line start with
Returns
------
str
"""
returnstring = ""
row = "" + (" " * indent)
for i in data:
if len(row + i) > length or len(i) >= length:
returnstring += row + i + "\n"
row = "" + (" " * indent)
else:
row += i + " "
returnstring += row + "\n"
return returnstring.rstrip() | 67dd9438ff96868bac5f9e3c4e7827bc718a8a36 | 78,049 |
import random
import torch
def get_example_inputs(multichannel: bool = False):
"""
returns a list of possible input tensors for an AudacityModel.
Possible inputs are audio tensors with shape (n_channels, n_samples).
If multichannel == False, n_channels will always be 1.
"""
max_channels = 2 if multichannel else 1
num_inputs = 10
channels = [random.randint(1, max_channels) for _ in range(num_inputs)]
sizes = [random.randint(2048, 396000) for _ in range(num_inputs)]
return [
torch.randn((c, s)) for c, s in zip(channels, sizes)
] | a0abd8c700375bb97425ef11072319168a682c39 | 494,035 |
def get_twin(ax):
"""
Retrieves a twin Y axis for a given matplotlib axis. This is useful when we have two axes one placed at each side
of the plot.
@param ax: the known matplotlib axis.
@return: the twin axis.
"""
for other_ax in ax.figure.axes:
if other_ax is ax:
continue
if other_ax.bbox.bounds == ax.bbox.bounds:
return other_ax
return None | c60fb151d72d28242ba9aef12a1ae688f1725d0c | 459,372 |
import requests
import json
def westBengalStateID(state):
"""
Function to get state id from state name derived by reverse engineering
pincode
Parameters
----------
state : String
State name.
Returns
-------
state_id : String
ID associated with that state name
"""
state_id = ''
url = "https://cdn-api.co-vin.in/api/v2/admin/location/states"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' }
try:
response = requests.get(url,headers=headers)
parsed_response = json.loads(response.text)
state_length = len(parsed_response['states'])
for idx in range(state_length):
if((parsed_response['states'][idx]['state_name']).lower().replace(" ", "") == state.lower().replace(" ", "")):
state_id = parsed_response['states'][idx]['state_id']
return(state_id)
except Exception as e:
print(e) | 4ddef75ea2206ac2ef92d6d84975f5b2a4b2af77 | 270,516 |
def makeBundlesDictFromList(bundleList):
"""Utility to convert a list of MetricBundles into a dictionary, keyed by the fileRoot names.
Raises an exception if the fileroot duplicates another metricBundle.
(Note this should alert to potential cases of filename duplication).
Parameters
----------
bundleList : list of MetricBundles
"""
bDict = {}
for b in bundleList:
if b.fileRoot in bDict:
raise NameError('More than one metricBundle is using the same fileroot, %s' % (b.fileRoot))
bDict[b.fileRoot] = b
return bDict | ae121beaa69f0f69e8d544dea7b8e208e7b609ca | 118,961 |
def align(s, offset):
"""Adds 'offset' times whitespaces end of the string 's'"""
return s + (' ' * offset) | d9f6d58387f044566e1a9aedb52f8542acb753a0 | 138,553 |
def strip_numbers(s):
"""
Return a string removing words made only of numbers. If there is an
exception or s is not a string, return s as-is.
"""
if s:
s = u' '.join([x for x in s.split(' ') if not x.isdigit()])
return s | 64c55a6777bd43e8cbc5a5c872c1c2f3302e0545 | 139,818 |
import re
def simplify_string(string):
""" Removes punctuation and capitalization from given string
Args:
string(string): string to be simplified
Returns:
string: a string without punctuation or capitalization
"""
return re.sub(r'[^a-zA-Z0-9]', '', string).lower() | b324763092f5410e9d8382158310a728725fa030 | 236,749 |
def example_netcdf_path(request):
"""Return a string path to `sample_tile.nc` in the test data dir"""
return str(request.fspath.dirpath('data/sample_tile.nc')) | 5fb5bf102c3ea8b21d6c847f8d5fc88c2d6e0615 | 143,974 |
def create_generic_templating_dict(dashboard_info):
"""
Generic templating dictionary: name just maps to value
:param dashboard_info: Grafana dashboard API response
:return: dict of {"name": "value"}
"""
templates = {}
templating_info = dashboard_info['dashboard']['templating']
for template in filter(lambda template: template.get('current'), templating_info['list']):
value = template['current']['value']
name = template['name']
if isinstance(value, list):
value = ', '.join(value)
elif value == '$__auto_interval':
value = 'auto'
templates[name] = value
return templates | 6cd6f7ad56c2a8e5dd7d32d23fb76ff644835b03 | 157,312 |
import inspect
def _is_model_class(obj):
"""Return whether or not the given object is a Model class."""
if not inspect.isclass(obj):
return False
if obj.__name__ == 'Model':
# Base model class, don't include.
return False
return 'Model' in [o.__name__ for o in inspect.getmro(obj)] | 7e1f2eba38c709f1c6017ff1a147290c16ff0b38 | 152,314 |
import re
def convert_to_platform_safe(dir_file_name):
"""
:param dir_file_name: a string to be processed
:return: a string with all the reserved characters replaced
"""
return re.sub('[\?|<>=:*,;+&"@]', '_', dir_file_name) | 8fd0495b78aa9628dc6de79612f8fba945b1f871 | 538,655 |
def fill_world_template(world_temp, model_info):
"""
Write relevant information into the world file template.
"""
# Replace template values
world_content = world_temp
world_content = world_content.replace("$FILENAME$", model_info.name)
return world_content | 1f81ef2e95d3eecffc4a3f5d1d66f5d10f39675a | 173,428 |
import string
def ignore_whitespace(a):
"""
Compare two base strings, disregarding whitespace
Adapted from https://github.com/dsindex/blog/wiki/%5Bpython%5D-string-compare-disregarding-white-space
"""
WHITE_MAP = dict.fromkeys(ord(c) for c in string.whitespace)
return a.translate(WHITE_MAP) | 9f90e0cd10744fe337f9469913654d0dd951f2a5 | 38,416 |
import math
from typing import Counter
def entropy(data, unit='natural'):
"""
Compute and return the entropy of a stream of data.
:param bytearray data: Stream to compute entropy on.
:param str,optional unit: Passed to math.log calculation.
Default is natural.
:return: Entropy calculation
:rtype: float
"""
base = {
'shannon': 2.,
'natural': math.exp(1),
'hartley': 10.
}
if len(data) <= 1:
return 0
counts = Counter()
for d in data:
counts[d] += 1
probs = [float(c) / len(data) for c in list(counts.values())]
probs = [p for p in probs if p > 0.]
ent = 0
for p in probs:
if p > 0.:
ent -= p * math.log(p, base[unit])
return ent | 68120db58a921c83945e52b1d36fd8c458bac461 | 294,215 |
def print_exam_schedule(exam_schedule):
"""
Prints the exam schedule in a prettier format.
Parameters:
-----------
exam_schedule (2D list): Departments for each exam block
returns (NoneType): None
"""
for i in range(len(exam_schedule)):
print("Block " + str(i+1) + ": [" + ', '.join(exam_schedule[i]) + "]")
return None | dbb8a7813c6e76d33a5874c88f0a7eb123b1b881 | 481,580 |
def orthogonal_vector(vector):
""" Given a vector, returns a orthogonal/perpendicular vector of equal length.
Returns
------
(float, float): A vector that points in the direction orthogonal to vector.
"""
return -1 * vector[1], vector[0] | 760ec2adf8994d4b2871d57b054a660a1d03411f | 357,027 |
def concatenate_url(endpoint, url):
""" concatenate endpoint & url
:param endpoint: the base url for example http://localhost:port/v1
:param url: the target url for example "/dashboard"
:return: concatenated url for example http://localhost:port/v1/dashboard
"""
return "%s/%s" % (endpoint.rstrip("/"), url.rstrip("/")) | 2c4eb63fcad9cdf99bbc16e53452601b79f17b4f | 250,416 |
def _read_first_line(file_path):
"""
Returns the first line of a file.
"""
with open(file_path, 'r') as file_:
first_line = file_.readline().strip()
return first_line | 035f22e1e35aa2f945d6ee6d8435d44fee17cc01 | 33,197 |
def data_from_response(response: dict) -> dict:
"""If the response is OK, return its payload.
- response: A dict like::
{
"status": 200, # <int>
"timestamp": "....", # ISO format string of the current date time
"payload": { ... } # dict with the returned data
}
- Returns a dictionary like::
{"data": { .. } }
- Raises:
- ValueError if the HTTP status is != 200
"""
if response["status"] != 200:
raise ValueError
return {"data": response["payload"]} | 368b099264168b935f146f787d3999a2494e4446 | 326,965 |
def region_filters(DF, lon_min, lon_max, lat_min, lat_max, shapefile=False):
"""Takes a Dataframe with the all the rivers information and filters the data
from the rivers in an especific region.
Parameters
----------
DF: Dataframe
is the River_sources dataframe.
lat_min, lat_max, lon_min, lon_max: float, float, float float
domain limits.
shapefile: bool, optional
True when dealing with a geopandas Dataframe.
Returns
-------
new_DF: Dataframe
a pandas Dataframe rivers in the especific region.
"""
if shapefile:
X = DF.geometry.x
Y = DF.geometry.y
else:
X = DF['X']
Y = DF['Y']
mask = (X <= lon_max) & (X > lon_min) & (Y <= lat_max) & (Y > lat_min)
new_DF = DF[mask]
return new_DF | 73be07602873444ab22e2febe7aea8c421e92321 | 127,079 |
def image_type(file):
"""Returns str of file type. 'jpeg', 'png', 'gif'.
Returns None if unable to identify file type"""
if isinstance(file, str):
f = open(file, 'rb')
binary_string = f.read(32)
else:
binary_string = file.read(32)
if binary_string[6:10] in (b'JFIF', b'Exif'):
return 'jpeg'
elif binary_string.startswith(b'\211PNG\r\n\032\n'):
return 'png'
elif binary_string[:6] in (b'GIF87a', b'GIF89a'):
return 'gif'
else:
return None | b19e53dc86bc92c7bb4bff1810678fee5b0fb44b | 530,724 |
def get_parameter(model, name):
"""
Finds the named parameter within the given model.
"""
for n, p in model.named_parameters():
if n == name:
return p
raise LookupError(name) | ba35b743d9189c94da0dcce27630bba311ea8a46 | 5,964 |
from typing import List
def calc_share(total: int, no: int, yes: int, maybe: int, bad: int) -> List[float]:
"""Calculate the share of each category on the total count."""
no_share = no / total
yes_share = yes / total
maybe_share = maybe / total
bad_share = bad / total
return [no_share, yes_share, maybe_share, bad_share] | b9b18124f9c82fede43032a1776e57bc16a403fb | 605,862 |
def _select_mapping(items, keep=(), drop=()):
"""Helper function for `select`.
Parameters
----------
items: Mapping
Dict (or similar mapping) to select/drop from.
keep: Iterable[str]
Sequence of keys to keep.
drop: Iterable[str]
Sequence of keys to drop. You should specify either `keep` or `drop`,
not both.
Returns
-------
Dict
"""
if keep:
return {k: items[k] for k in keep}
return {k: v for k, v in items.items() if k not in set(drop)} | 2fd34956b79fc222b423d50eb94d1b646f1b86ac | 362,460 |
def str2bool(s):
"""
Convert a string to a boolean value. The supported conversions are:
- `"false"` -> `False`
- `"true"` -> `True`
- `"f"` -> `False`
- `"t"` -> `True`
- `"0"` -> `False`
- `"1"` -> `True`
- `"n"` -> `False`
- `"y"` -> `True`
- `"no"` -> `False`
- `"yes"` -> `True`
- `"off"` -> `False`
- `"on"` -> `True`
Strings are compared in a case-blind fashion.
**Note**: This function is not currently localizable.
**Parameters**
`s` (`str`): The string to convert to boolean
**Returns**
the corresponding boolean value
**Raises**
`ValueError`: unrecognized boolean string
"""
try:
return {'false' : False,
'true' : True,
'f' : False,
't' : True,
'0' : False,
'1' : True,
'no' : False,
'yes' : True,
'y' : False,
'n' : True,
'off' : False,
'on' : True}[s.lower()]
except KeyError:
raise ValueError('Unrecognized boolean string: "{0}"'.format(s)) | e9305e3d377333d1d51756a7ac6c227b2e37a2dd | 248,224 |
def file_size_formatter(size):
"""
File size with units formatting
:param size: File size to be formatted
:type size: String, float or integer
:returns: File size with units
:rtype: String
Examples:
>>> file_size_formatter('60')
'60.0B'
>>> file_size_formatter('600000')
'585.94K'
>>> file_size_formatter('600000000')
'572.2M'
>>> file_size_formatter('600000000000')
'558.79G'
>>> file_size_formatter('600000000000000')
'545.7T'
"""
size=float(size)
suffixes = [('B',2**10), ('K',2**20), ('M',2**30), ('G',2**40), ('T',2**50)]
for suffix, limit in suffixes:
if size > limit:
continue
else:
return round(size/float(limit/2**10),2).__str__()+suffix | 4c0af463afea0166ac58f393426a40caead9305c | 380,447 |
from typing import Dict
def table(services: Dict[str, str]) -> str:
"""
Collect all services and their current otp as a table.
:param services: Dictionary of service name to otp
:return: the table representation of d as a string
"""
# the longest service name or 10
left_column = max([10, *map(len, services)])
right_column = 8 # max number of digits specified by RFC
header = f'{"service":<{left_column}} | {"otp":<{right_column}}'
divider = "-" * len(header)
body = [
f"{service:<{left_column}} | {otp:{right_column}}"
for service, otp in services.items()
]
return "\n".join([header, divider, *body]) | 608f4749cab6b09ca75e3e2ad1eb810625008262 | 151,680 |
def splitBinNum(binNum):
"""Split an alternate block number into latitude and longitude parts.
Args:
binNum (int): Alternative block number
Returns:
:tuple Tuple:
1. (int) Latitude portion of the alternate block number.
Example: ``614123`` => ``614``
2. (int) Longitude portion of the alternate block number.
Example: ``614123`` => ``123``
"""
latBin = int(binNum / 1000)
longBin = binNum - (latBin * 1000)
return (latBin, longBin) | da9b9cc67d592e73da842f4b686c0d16985f3457 | 706,514 |
def linear(x):
"""
Linear activation function
"""
return x | 57395e300e2c4186662c7c96c5938ff92bee2a0a | 157,526 |
def create_look_up_table(vocab_list):
"""Create tables for encoding and decoding texts."""
vocab2int = {word: i for i, word in enumerate(vocab_list)}
int2vocab = vocab_list
return vocab2int, int2vocab | d9f0591d50e92cb518c3b6fda3a5240d3beacfbb | 279,028 |
def __evaluate_model(valid_world, batchsize, datatype, display_examples, max_exs=-1):
"""Evaluate on validation/test data.
- valid_world created before calling this function
- batchsize obtained from opt['batchsize']
- datatype is the datatype to use, such as "valid" or "test"
- display_examples is bool
- max_exs limits the number of examples if max_exs > 0
"""
print('[ running eval: ' + datatype + ' ]')
valid_world.reset()
cnt = 0
for _ in valid_world:
valid_world.parley()
if cnt == 0 and display_examples:
print(valid_world.display() + '\n~~')
print(valid_world.report())
cnt += batchsize
if valid_world.epoch_done() or (max_exs > 0 and cnt >= max_exs):
# note this max_exs is approximate--some batches won't always be
# full depending on the structure of the data
break
valid_report = valid_world.report()
print(datatype + ':' + str(valid_report))
return valid_report, valid_world | 3cf3fbd9dd6b1430f4f086786b26abc3e9c90e5b | 120,311 |
def shorten_unique(names, keep_first=4, keep_last=4):
"""
Shorten strings, inserting '(...)', while keeping them unique.
Parameters
----------
names: List[str]
list of strings to be shortened
keep_first: int
always keep the first N letters
keep_last: int
always keep the last N letters
Returns
-------
shortened_names: List[str]
list with shortened strings
"""
short, cut_chars, longest_str = [], 0, max([len(p) for p in names])
while len(set(short)) != len(set(names)) and cut_chars <= longest_str:
short = [p[:keep_first + cut_chars] + '(...)' + p[-keep_last:]
if len(p) > sum([keep_first, keep_last, cut_chars])
else p for p in names]
cut_chars += 1
return short | bf23e2f2eeddb5b5541613284291ba0b6a1e271f | 117,795 |
import string
import itertools
def standardize_col(col: str) -> str:
"""Standardize a column for Snowflake table.
(1) Replaces spaces with underscores, trims leading & trailing
underscores, forces upper-case
(2) Replaces special characters with underscores
(3) Reduces repeated special characters
Args:
col: A single string value of a column name
Returns:
A string that has been re-formatted/standardized for Snowflake
standards
"""
col = ((col.replace(' ', '_')).strip('_')).upper() # 1
invalid_punct = [punct for punct in string.punctuation if
punct != '_'] # 2
repl_invalid_punct = str.maketrans(''.join(invalid_punct),
'_' * len(invalid_punct))
col = ''.join(col.translate(repl_invalid_punct))
new_chars = [] # 3
for k, v in itertools.groupby(col):
if k in string.punctuation or k in string.whitespace:
new_chars.append(k)
else:
v_list = list(v)
new_chars.append(''.join(v_list))
col = ''.join(new_chars)
return col | 78a84d8d6951d7fe58645e32e34ec69ea3aeac64 | 611,863 |
import importlib
def timport(name):
"""
Try to import and return the module named `name`, and return `None` on
failure.
"""
try:
return importlib.import_module(name)
except ImportError:
return None | 60b34bf39304a56ff49a455e510b372c4f2dd2dc | 481,730 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
high = number
low = 0
while low <= high:
mid = (low + high) // 2
midsquare = mid * mid
next_midsquare = (mid+1) * (mid+1)
if midsquare == number or midsquare < number < next_midsquare:
return mid
elif midsquare > number:
high = mid - 1
else:
low = mid + 1 | 1dca451d1b96ec88a36753d9d07edd9ba2f34de8 | 19,652 |
def msg_mutator(plan, msg_proc):
"""
A simple preprocessor that mutates or deletes single messages in a plan
To *insert* messages, use ``plan_mutator`` instead.
Parameters
----------
plan : generator
a generator that yields messages (`Msg` objects)
msg_proc : callable
Expected signature `f(msg) -> new_msg or None`
Yields
------
msg : Msg
messages from `plan`, altered by `msg_proc`
See Also
--------
:func:`bluesky.plans.plan_mutator`
"""
ret = None
while True:
try:
msg = plan.send(ret)
msg = msg_proc(msg)
# if None, just skip message
# feed 'None' back down into the base plan,
# this may break some plans
if msg is None:
ret = None
continue
ret = yield msg
except StopIteration as e:
return e.value | 452ac6ba74b4a8a1258a071c025dba89ce586f9c | 501,825 |
def Kronecker(a,b):
"""
Kronecker delta function.
Parameters
----------
a: int
first index
b: int
second index
Returns
-------
Return value 0 if a and b are not equal; return value 1 if a and b
are equal.
"""
if a == b:
return 1
else:
return 0 | b91e4aed97220c106f73b7520f9a80b0f400e535 | 558,572 |
def find_parents(graph, node):
"""
Get the governing nodes of a given node in the graph
"""
return graph.reverse()[node].keys() | 22f63019f9725f3764b4c59392acc1cefaf433c9 | 570,867 |
def _convertTextToType(valueToConvert, defaultValue, desiredType=None):
"""
Ensure the value has the correct expected type by converting it.
Since the values are extracted from text, it is normal that they
don't have the expected type right away.
If the value cannot be converted, use the default value. This could
happen if the optionVar got corrupted, for example from corrupted user
prefs.
"""
if not desiredType:
desiredType = type(defaultValue)
if isinstance(valueToConvert, desiredType):
return valueToConvert
# Try to convert the value to the desired type.
# We only support a subset of types to avoid problems,
# for example trying to convert text to a list would
# create a list of single letters.
try:
textConvertibleTypes = [str, int, float]
if desiredType in textConvertibleTypes:
return desiredType(valueToConvert)
elif desiredType == bool:
if valueToConvert.lower() == 'true':
return True
if valueToConvert.lower() == 'false':
return False
return bool(int(valueToConvert))
except:
pass
# Verify to convert list values by converting each element.
# Unfortunately, for historical reasons, text lists have used
# comma-separated values, while floating-point used space-separated values.
try:
if isinstance(defaultValue, list):
if ',' in valueToConvert:
values = valueToConvert.split(',')
desiredType = str
else:
values = valueToConvert.split()
desiredType = float
convertedValues = []
for value in values:
value = value.strip()
if not value:
continue
convertedValue = _convertTextToType(value.strip(), None, desiredType)
if convertedValue is None:
continue
convertedValues.append(convertedValue)
return convertedValues
except:
pass
# Use the default value if the data is somehow corrupted,
# for example from corrupted user prefs.
return defaultValue | 5326f98674e6573a18e7b419903a7bc1b4172428 | 140,951 |
def strip_comment(line):
"""Get rid of fortran comments."""
idx = line.find("!")
if idx != -1:
return line[:idx].strip()
return line | db5a63466bae41d40336b6fbdc73d3d79832ce6c | 525,210 |
def format_freqs(counter):
"""
Format a counter object for display.
"""
return '\n'.join('%s: %d' % (tag, counter[tag])
for tag in sorted(counter.keys())) | f2a7c781a27ab1c60a3312f35ca44bf960e066a0 | 348,475 |
def index_range(raw):
"""Parse index ranges separated by commas e.g. '1,2-5,7-11'."""
if not raw:
return None
indices = set()
try:
with open(raw, 'r') as f:
for l in f:
l = l.strip()
if len(l) == 0 or l[0] == '#':
continue
if " " in l:
l = l.split()[0]
indices.add(int(l))
return indices
except FileNotFoundError:
pass
for s in raw.split(","):
if "-" in s:
start, end = s.split("-")
indices.update(range(int(start), int(end)+1))
else:
indices.add(int(s))
return indices | 1699abbb4b6ec8c4cfc69cd7428a01e84066caca | 581,060 |
def dxdt(y, z):
"""Computes the equation for x prime"""
dx = -y - z
return dx | 5307deada35d965dafa6e32576d67335c522d775 | 691,551 |
def source(*_):
"""Return a link to the repo for this bot."""
return (
"I'm an open source bot. If you want to contribute or are curious "
"how I work, my source is available for you to browse here: "
"https://github.com/esi/esi-bot/"
) | a8c25a3b5b24c98d711669f10e3a1485e578dffa | 206,207 |
def merge_codegen_params(reload_list, arg_list):
"""Merge the codegen reload params list additional arguments list with no duplicates"""
if reload_list:
new_reload_list = reload_list
else:
new_reload_list = []
if arg_list:
new_arg_list = arg_list
else:
new_arg_list = []
# Combine the reload and new argument list without duplicates
combined_args_list = list(set(new_reload_list).union(set(new_arg_list)))
return combined_args_list | 3fdb11bbded7f2300a159cc2510e4ee13c02fe1b | 69,961 |
def sci_format(x,lim):
"""
Ticks formatter scientific notation with base 10. Adapted from https://www.py4u.net/discuss/140199
"""
a, b = '{:.0e}'.format(x).split('e')
b = int(b)
return r'${} \times 10^{{{}}}$'.format(a, b) | 5737322630ccd4b32e29b8afe34544ead74686c4 | 181,437 |
def parse_dat_mantid_function_def(function):
"""
Helper function that parses the function definition of a NIST problem
and returns the function name and parameters.
@param function :: NIST function definition string
@returns :: formatted function name and the final function
parameters (after it has been fitted)
"""
first_comma = function.find(',')
second_comma = function.find(',', first_comma + 1)
function_name = function[first_comma + 9:second_comma]
function_parameters = function[second_comma + 1:]
function_parameters = function_parameters.replace(',', ', ')
return [function_name], [function_parameters] | 2f3287926f55dc542c03a24e9af9f95ac0a7e0d7 | 367,255 |
import hashlib
def get_hashed_name(name: str) -> str:
"""
Generate hashed name
Args:
name: string to be hashed
Returns:
str: hashed string
"""
return hashlib.sha224(name.encode('utf-8')).hexdigest() | 1784f92b8734f18bf0cf39660b2a07b2247ea8df | 390,386 |
def get_aside_from_xblock(xblock, aside_type):
"""
Gets an instance of an XBlock aside from the XBlock that it's decorating. This also
configures the aside instance with the runtime and fields of the given XBlock.
Args:
xblock (xblock.core.XBlock): The XBlock that the desired aside is decorating
aside_type (str): The aside type
Returns:
xblock.core.XBlockAside: Instance of an xblock aside
"""
return xblock.runtime.get_aside_of_type(xblock, aside_type) | 5cb375282144cfbbe0b23d5b224e6370cf9218d7 | 391,033 |
def get_boolean(value) -> bool:
"""Convert a value to a boolean.
Args:
value: String value to convert.
Return:
bool: True if string.lower() in ["yes", "true"]. False otherwise.
"""
bool_val = False
try:
if value.lower() in ["yes", "true"]:
bool_val = True
except AttributeError:
error = "Could not convert '%s' to bool, must be a string" % (value)
raise AttributeError(error)
return bool_val | cfd716167e288ae60b6a6545c9bba8eb98b5579c | 281,771 |
def is_springer_url(url):
"""determines whether the server is springer from url
@param url : parsed url
"""
return 'www.springerlink.com' in url.netloc | 16bea33374cf8c5a7e5050fa1019aa563f06906b | 607,662 |
from typing import Any
import json
def _handle_values_for_overrides_list(v: Any) -> Any:
"""
Handle the special massaging of some values of JSON need to for it to be supplied
to Hydra's overrides list.
"""
# python's None --> cmd line null for override list
v = "null" if v is None else v
# if value is a dict, convert it to string to work with override list.
# dump twice to escape quotes correctly.
v = json.dumps(json.dumps(v)) if type(v) is dict else v
# escape = char in value when present
v = v.replace(r"=", r"\=") if type(v) is str else v
return v | 5b89884dbaef4819c2da6eeecff0997570ccd475 | 516,589 |
def _get_func(module, func_name):
"""
Given a module and a function name, return the function.
func_name can be of the forms:
- 'foo': return a function
- 'Class.foo': return a method
"""
cls_name = None
cls = None
if '.' in func_name:
cls_name, func_name = func_name.split('.')
if cls_name:
cls = getattr(module, cls_name)
func = getattr(cls, func_name)
else:
func = getattr(module, func_name)
return cls, func | 6ff9af35a50e7dbcb4a0227e8bba2efef5bb7393 | 557,736 |
import re
def rename_dims(name):
"""Simplify dimension names
"""
dimname = re.sub("_[67]", "", name) # Remove _6 or _7
dimname = re.sub("jhisto_", "", dimname) # jhisto_
return(dimname) | d8627ba2d683e48a4b179b38276c5202ce946f35 | 415,579 |
def _put_into_original_order(X, columns_to_subset):
"""Put the columns returned by X.ww.select(...., return_schema=True) into the original order found in X."""
return [col_name for col_name in X.columns if col_name in columns_to_subset] | e0512e06a963aee1defad407c9c02d8d0879bfb9 | 244,609 |
import requests
def fetch(url):
"""Fetch data from url and return fetched JSON object"""
r = requests.get(url)
data = r.json()
return data | 4a1296242c315b88e30ccaecfa4aca1e20a4ed07 | 424,433 |
def to_signed(value):
"""Decode the sign from an unsigned value"""
if value & 1:
value = ~value
value >>= 1
return value | 00fad31f250de7cdb89b235f428bf928d5e00160 | 161,722 |
def get_current_site(request):
"""
Return current site.
This is a copy of Open edX's `openedx.core.djangoapps.theming.helpers.get_current_site`.
Returns:
(django.contrib.sites.models.Site): returns current site
"""
return getattr(request, 'site', None) | 8958df67fa2555055161c28bc35dd2bf81b0c36c | 360,632 |
def list_api_vs(client, resource_group_name, service_name):
"""Lists a collection of API Version Sets in the specified service instance."""
return client.api_version_set.list_by_service(resource_group_name, service_name) | c12a895195a0122afa53649c2cb351e118916a62 | 663,919 |
def wrap_with_links(obj, links, val, root_path, many=False):
"""Adds links key to object (first argument) based on links dictionary and value"""
if many:
for item in obj:
item['links'] = {}
for key in links:
item['links'][key] = root_path + links[key].format(item[val])
else:
obj['links'] = {}
for key in links:
obj['links'][key] = root_path + links[key].format(obj[val])
return obj | ea42bff363fe131a423501b8442449f03c3eccb7 | 646,921 |
def rtuFrameSize(data, byte_count_pos):
""" Calculates the size of the frame based on the byte count.
:param data: The buffer containing the frame.
:param byte_count_pos: The index of the byte count in the buffer.
:returns: The size of the frame.
The structure of frames with a byte count field is always the
same:
- first, there are some header fields
- then the byte count field
- then as many data bytes as indicated by the byte count,
- finally the CRC (two bytes).
To calculate the frame size, it is therefore sufficient to extract
the contents of the byte count field, add the position of this
field, and finally increment the sum by three (one byte for the
byte count field, two for the CRC).
"""
# return byte2int(data[byte_count_pos]) + byte_count_pos + 3
return data[byte_count_pos][0] + byte_count_pos + 3 | 12a7d85880a4d30e6ae2bb8978946f270985ac1f | 602,170 |
def num2str(element, decimal_sep='.'):
"""
A helper function that converts strings to numbers if possible
and replaces the float decimal separator with the given value
"""
if isinstance(element, float):
return str(element).replace('.', decimal_sep)
return str(element) | 61e5d7a9ae46c83081068e581b8e1881c4507915 | 173,760 |
def psi0(ctx, z):
"""Shortcut for psi(0,z) (the digamma function)"""
return ctx.psi(0, z) | d59412a12bffc32a3706d5d9469c27b2a2328a67 | 641,354 |
def get_show_name(vid_name):
"""
get tvshow name from vid_name
:param vid_name: video clip name
:return: tvshow name
"""
show_list = ["friends", "met", "castle", "house", "grey"]
vid_name_prefix = vid_name.split("_")[0]
show_name = vid_name_prefix if vid_name_prefix in show_list else "bbt"
return show_name | ec734f72fc3b61f00cc44d50f263af40e546a6a4 | 513,904 |
def tags_to_new_gone(tags):
"""Split a list of tags into a new_set and a gone_set."""
new_tags = set()
gone_tags = set()
for tag in tags:
if tag[0] == '-':
gone_tags.add(tag[1:])
else:
new_tags.add(tag)
return new_tags, gone_tags | 7689928d7c47fddad8566a0e66e1a7a1d9e42cc9 | 542,575 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.