content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import requests
import json
def getReqJSON(url, args={}):
"""Generic function to get json from an api request"""
if url.endswith("/"):
url = url[:-1]
arg_str = ""
if isinstance(args, dict):
if len(args) > 0:
arg_str = "?" + "&".join([str(k) + "=" + str(args[k]) for k in ar... | 48cb495976aca490242987460676cbe655d88ab9 | 634,141 |
def geojson_crs(epsg):
"""Generate a GeoJSON CRS member from an EPSG code."""
epsg = int(epsg)
if epsg == 4326:
coordinate_order = [1, 0]
else:
coordinate_order = [0, 1]
return {
'type': 'EPSG',
'properties': {'code': epsg, 'coordinate_order': coordinate_order}} | a2b962d260594e1c73bd700665b1f61375c8a4df | 634,145 |
def page_not_found(e):
"""Return a custom 404 error."""
return '<h1>Sorry, nothing at this URL.<h1>', 404 | f40fafec4a9df8a073d0efaf2fb2411531b1977a | 634,146 |
import re
import unicodedata
def slugify(name, allow_periods=False):
"""
Returns a tuple with slug and lowered slug based on name
"""
RE_NON_ALPHA_ETC = re.compile(r'[^.\w]+' if allow_periods else r'[^\w]+')
slug = RE_NON_ALPHA_ETC.sub('-', # replace non ". alphanum_" sequences into single -
... | 4b6ecff0f3e4b356b20d6d3ef1ddb336dba76d81 | 634,148 |
def sqkm2sqmiles(field_name, item, **kwargs):
"""
Convert square killometers to square miles
"""
sqkm_field = kwargs['source']
sqkm = item[sqkm_field].replace(',','')
return '{:,}'.format(int(float(sqkm)*0.386102159)) | c676e433352f1f6fb3fffe1a8c3b20ad5e3a6a1f | 634,151 |
import inspect
import warnings
def check_model_functionality(model_object: object,
require_probabilities: bool = False,
suppress_warning: bool = False) -> bool:
"""
Checks whether a model object has all the required functionality.
Examines a ``m... | e44ed26b519cde1bcb7011074840f17185a62cd7 | 634,156 |
def adlist_top3_by_comment(cur):
""" top 3 adlists by comment """
sql = "SELECT comment, count(*) FROM adlist GROUP BY comment LIMIT 3"
cur.execute(sql)
return cur.fetchall() | af04a6ad4bd991521b527ae8e237142cafe707c8 | 634,159 |
import torch
def lengths_to_mask(*lengths, **kwargs):
""" Given a list of lengths, create a batch mask.
Example:
>>> lengths_to_mask([1, 2, 3])
tensor([[ True, False, False],
[ True, True, False],
[ True, True, True]])
>>> lengths_to_mask([1, 2, 2], ... | 5b26e91bba7110a7421723f628924d9656cb007d | 634,161 |
from typing import Any
from typing import List
def to_list(obj: Any) -> List:
"""Converts an object to a list. If the object is already a list,
does nothing.
:param obj: Object to convert
"""
return obj if isinstance(obj, list) else [obj] | 67951b4d01267d594231dd04bb2b7930a392f849 | 634,163 |
import re
def split_column_name(column):
"""Split column name into a (name, unit) tuple."""
match = re.match(r"\s*([^ ([<]+)\s*[([<]?([^] )>]*)[])>]?", column)
if not match:
return column, ""
name, unit = match.groups()
return name, unit | baff57c42c6005e95bafb83206bd301fdb79c4c0 | 634,164 |
from typing import Callable
from datetime import datetime
def on_date(month: int, day: int) -> Callable[[datetime], bool]:
"""
Filter that allows events that match a specific date in any year
Args:
- month (int): the month as a number (1 = January)
- day (int): the day as a number
Re... | 4f2c166a12505b1d1e0e9aec55e06e0e94d5efc7 | 634,167 |
def a_source_username(plugin_ctx, fsm_ctx):
"""send source username."""
src_username = plugin_ctx.src_username
fsm_ctx.ctrl.sendline(src_username)
return True | c24c759ea6bc8025a48e75e8377025272a408ab0 | 634,169 |
def filter_datastores_by_hubs(hubs, datastores):
"""Get filtered subset of datastores corresponding to the given hub list.
:param hubs: list of PbmPlacementHub morefs
:param datastores: all candidate datastores
:returns: subset of datastores corresponding to the given hub list
"""
filtered_dss ... | 79278802dde4d46293d90df5375f225e8d2858f6 | 634,174 |
from typing import List
def _length_of_longest_path(file_paths: List[List[str]]) -> int:
"""Determines the length of the longest path out of all the paths
Args:
file_paths (List[List[str]]): a list containing all file paths which are lists of the parts
Ex.: [['home', 'usr', 'dir1'], [... | ecab8673f0d1c6220104423a48c0975340db7263 | 634,176 |
def _resource_id_from_record_tuple(record):
"""Extract resource_id from HBase tuple record
"""
return record[1]['f:resource_id'] | e35a780201d465783558e7e41cd3e1f1d37ff239 | 634,178 |
def is_following(user_, other_user):
"""Is this user following `other_use`?"""
found_user_list = [user for user in user_.following if user == other_user]
return len(found_user_list) == 1 | e9f56a756690807dfd1c140d0631092e0d3a462d | 634,181 |
def _identity_dynamics(x):
"""Returns same input as output."""
return x | 53b8612fec76e464608d17b2d4d37331ba760e9d | 634,183 |
def normalize_ip(ip):
"""
Transform the address into a fixed-length form, such as::
192.168.0.1 -> 192.168.000.001
:type ip: string
:param ip: An IP address.
:rtype: string
:return: The normalized IP.
"""
theip = ip.split('.')
if len(theip) != 4:
raise ValueError(... | 2b810e71befe544291d743492196065d5963a3d7 | 634,185 |
def _var_key(var):
"""Key for representing a primary variable, for looking up slots.
In graph mode the name is derived from the var shared name.
In eager mode the name is derived from the var unique id.
If distribution strategy exists, get the primary variable first.
Args:
var: the variable.
Returns:... | 77f45e0030488eab2d446b9bd8eca1432ffd365a | 634,186 |
def has_abba(code):
"""Checks for existence of a 4-letter palindromic substring within `code`
The palindromic substring must contain 2 unique characters
"""
palindrome = None
for i in range(len(code) - 4 + 1):
# substring = code[i:i + 4]
if code[i] == code[i + 3] and code[i + 1] == c... | a1a8235165ae99a7a8d2d26a778bbdcdaca592c6 | 634,188 |
import ast
def genAssignStraight(to: ast.Name, fieldName: str, processorFunc: ast.Attribute, o: ast.Name) -> ast.Assign:
"""Returns `to.fieldName = processorFunc(o.fieldName)`"""
return ast.Assign(
targets=[ast.Attribute(value=to, attr=fieldName, ctx=ast.Store())],
value=ast.Call(
func=processorFunc,
arg... | 70dabfd90cdc04c8038b70372bbd1b938059c203 | 634,191 |
def deploy_contract(revert_chain, deploy_contract_txhash):
"""Returns a function that deploys a compiled contract"""
def fn(
web3,
deployer_address,
abi,
bytecode,
args,
):
contract = web3.eth.contract(abi=abi, bytecode=bytecode)
tx... | b040d2ef50273860aa73271f744ef86918bd972e | 634,194 |
def min_encoded_value(n_bits):
"""The minimum value encoded by a signed bit-width."""
return 0 if n_bits >= 0 else -(2 ** (abs(n_bits))) | 36b52c4db902dc0548f8c18cee45042b7626551b | 634,195 |
from typing import List
def get_paragraphs(text: str) -> List[str]:
"""
Returns a list containing all paragraphs.
Input(s):
1) text - Original source text.
Output(s):
1) paragraphs - List containing all paragraphs.
"""
paragraphs = text.splitlines()
paragraphs = list(filter(lamb... | 9c5da93a3ee8cb9befc225742231f965cea610c8 | 634,199 |
import re
def get_name_and_email(address):
"""
Function to get name and email from addresses like
Company <contact@company.com>, returned as tuple (name, email)
"""
custom_sender_name = re.search(r'^([^<>]+)\s<([^<>]+)>$', address)
if custom_sender_name:
return custom_sender_name.group... | 20cc05de3317ffc8d7bd7724ab61296e01f1c532 | 634,200 |
import base64
def s_to_b64s(s: str) -> str:
"""convert string to base 64 string
:param s: input string
:type s: str
:return: output base 64 string
:rtype: str
"""
b64s = base64.b64encode(s.encode('utf8')).decode('utf8')
return b64s | 8498ff7365fbcc104ed138c61b543450c7d470f1 | 634,203 |
def format_error_message(exception_message):
"""Improve the formatting of an exception thrown by a remote function.
This method takes a traceback from an exception and makes it nicer by
removing a few uninformative lines and adding some space to indent the
remaining lines nicely.
Args:
exception_message... | 8723962be0ef70edd0b996a3b503b4793dd10016 | 634,204 |
from typing import Sequence
from typing import List
def make_beat_cycle(
beat_cycle: Sequence,
num_bars: int,
) -> List:
"""Given a beat cycle, extends it for the given number of bars.
"""
result = []
i = 0
while i < num_bars:
bar = []
for j in range(beat_cycle[i % len(be... | 0096c5d0f0dc0e53d0297d3e6bfa782a6a418310 | 634,205 |
def trim(s: str) -> str:
"""
Remove leading spaces
"""
for i, c in enumerate(s):
if c != ' ':
return s[i:]
return '' | 47aad91d4e8cd44e76a0eacd62ce532cecd6640e | 634,208 |
def module_path_from_object(o):
"""Returns the fully qualified class path of the instantiated object."""
return o.__class__.__module__ + "." + o.__class__.__name__ | 44eac16ce5c68a71a5d6bc797b8d69896b90bc8b | 634,217 |
import json
def read_bundles(bundle_list_file):
"""Read bundles in to a dict from a file.
This function expects the JSON file follows a pre-defined schema:
[
{"bundle_uuid": XXX, "bundle_version": XXX},
{"bundle_uuid": XXX, "bundle_version": XXX}
]
Args:
b... | 3e95def0ff01e25deafb3637bc5ec86850a2832c | 634,219 |
import json
def login_response_to_authorization_header(response):
""" given a response from login or register, return a dictionary containing a header for Authorization """
return dict(
Authorization='Bearer ' + json.loads(
response.data.decode()
... | 15e7d96fe5ae4df78001f675aa34aab517e7444a | 634,220 |
from typing import Tuple
def extract_hosts_from_arm(arm: str) -> Tuple[str, str]:
"""Arm names have the following format:
host1.metric1-host2.metric2
Extracts and returns the name of the two hosts from the arm them. The names
of the host might be the same.
Args:
arm (string): Name of the a... | 41b7b3eb6ba6959773653d32bc854bd15bdbeb90 | 634,221 |
import mmap
def file_contains(path, needle):
"""Check if the file residing on the given path contains the given needle
"""
# Since we have no idea if build.log is valid utf8, let's convert our ASCII
# needle to bytes and use bytes everywhere.
# This also allow us to use mmap on Python 3.
# Be ... | 87a8f7eca6f7db90fc2b27214b02947560a5956c | 634,223 |
def parse_str(value: str) -> str:
"""
Clean string.
:param str value: Original str.
:return: str: Cleaned str.
"""
return value.strip() | edf951982274b8f803f5152dcec9297a38de10e9 | 634,226 |
import ast
def parse_webhook(webhook_data):
"""
This function takes the string from tradingview and turns it into a python dict.
:param webhook_data: POST data from tradingview, as a string.
:return: Dictionary version of string.
"""
data = ast.literal_eval(webhook_data)
return data | 021950c233a35433a7431c871dc6c5381954ebc7 | 634,230 |
def users_to_string(users):
"""
Return users emails with <br> element for using them in tooltip's title.
User will hover over the text and see all emails.
"""
to_return_string = ""
for user in users:
to_return_string += user.email + "<br/>"
return to_return_string[:-5] | a4d51408372388f22b983d1974f965cb624123f8 | 634,231 |
def onedim_conversion(length_or_speed: float, mm_per_pixel: float):
"""
:param length_or_speed: in [px] or [px/s]
:param mm_per_pixel: in [mm/px]
:return: length i [mm] or speed in [mm/s]
"""
return length_or_speed * mm_per_pixel | 0eb707b0946fb917a7f93df62819a15b28135170 | 634,235 |
def concatenateDates(fullDates, yearMonthDates, years):
"""This function combines several dates in a human readable fashion.
>>> concatenateDates(set(['1988-04-25']), set(['1988-05']), set())
'1988-04-25 or 1988-05'
>>> concatenateDates(set(['1988-04-25', '1988-04-24']), set(['1988-05']), set())
'1988-04-24... | 9289d8cf39ec8e6ea4cc8c91a08d325a8d788600 | 634,236 |
from typing import Tuple
def hdf5_01_encode(uid: str, cksum: str, dset: int, dset_idx: int,
shape: Tuple[int]) -> bytes:
"""converts the hdf5 data has spec to an appropriate db value
Parameters
----------
uid : str
the file name prefix which the data is written to.
cksu... | e06977e53ee822eeabe5a95fc34bbce4b9ebf603 | 634,241 |
def verify_variant_type(variants, variant_type, pos, length):
""""Helper function for checking a specific variant type.
Args:
variants: List of variants to look through.
variant_type: The type of variant to verify.
pos: Position of the variant.
length: Size of the variant.
... | cfb0d6cd13198e0c8731650e28aafa9c4944e302 | 634,242 |
import math
def euclidian_distance(x, y):
"""Get euclidian distance between two segments.
Parameters
----------
x : float
length of the first edge
y : float
length of the second edge
Return: float
euclidian distance between the two edges
"""
return math.sqrt(x... | 10256318199800de45077d5ad081bd0bd4868deb | 634,246 |
def get_overlaps(inds_1, inds_2): #verified.
"""
Calculate the overlaps between two reads and the distance spanned by them.
The reads are each assumed to comprise two arms, a left and a right arm.
inds_1 and inds_2: [left start, left stop, right start, right stop]
Returns overlap_l, overlap_r, span_... | ff969b0d4d364d85b7af525c4f21e782c7516ed4 | 634,248 |
import random
def get_random_cluster_service_component(client, cluster, service) -> dict:
"""
Get random cluster service component
Args:
client: ADCM client API objects
cluster: some cluster object
service: some service object in cluster
Raises:
:py:class:`ValueError`... | 93ccbc71b7ff4ad88a0de0d08f222ea8d90b88fe | 634,249 |
import torch
def full_cosine_similarity(matrix1, matrix2):
"""
Expect 2 matrices P and Q of dimension (d, n1) and (d, n2) respectively.
Return a matrix A of dimension (n1, n2) with the result of comparing each
vector to one another. A[i, j] represents the cosine similarity between
vectors P[:, i] ... | 75f3c52d55761782606896eeb2a3bf3fb27c2cee | 634,251 |
def base_repr(number, base=2, padding=0):
"""
Return a string representation of a number in the given base system.
Parameters
----------
number : int
The value to convert. Positive and negative values are handled.
base : int, optional
Convert `number` to the `base` number system... | 1ff4609f475c248bf840c5ac1b82ad42d3c575b3 | 634,255 |
def stringify(obj):
"""Converts all objects in a dict to str, recursively."""
if isinstance(obj, dict):
return {str(key): stringify(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [stringify(value) for value in obj]
else:
return str(obj) | f150c6593065675ae220deac7bff5524cee0a4c0 | 634,256 |
def make_c_string(string):
"""Render a Python string into C string literal format."""
if string == None:
return "\"\""
string = string.replace("\n", "\\n")
string = string.replace("\t", "\\t")
string = string.replace('"', '\\"')
#string = string.replace("'", "\\'")
string = '"' + str... | 7744ff18ddbff9839dcb03d1ddd24558b1300f16 | 634,257 |
def get_fromtos_line(linestring_coords):
"""
Converts a list of linestring coordinates to a list of 'from-to'
dictionaries.
"""
line_coordinates_list_froms = linestring_coords[:-1]
line_coordinates_list_tos = linestring_coords[1:]
i = 0
fromtos = []
for i, val in enumerate(line_coo... | 2a05362815a71a718c300b4c05e2a3d4ef8796d0 | 634,258 |
def get_bucket_names(s3):
"""
Purpose:
Return an Bucket Names in S3
Args:
s3 (S3 Resource Object): S3 Object owning the Bucket
Return:
bucket_names (List of Strings): Name of buckets in S3
"""
return [bucket.name for bucket in s3.buckets.all()] | 4341d3d4c06d0ca54848d2af9395ed90610233aa | 634,259 |
def get_element_tag(element):
"""Returns the tag name string without namespace of the passed element."""
return element.tag.rsplit('}')[1] | 6b5ace48209a711db1c1d33e5acc28f7e245ea3e | 634,263 |
import re
def clean_len(s):
"""
Calculate the length of a string without it's color codes
"""
s = re.sub(r'\x1b\[[0-9;]*m', '', s)
return len(s) | 5148d6fe580e45e5e3ce11b6bbcda602d3886305 | 634,268 |
def get_models(model_key: str, model_type, json_dict: dict) -> list:
"""This converts json lists into a list of the specified SUSHI model type
:param model_key: The target key to get the list of JSONObjects
:param model_type: The target model type, e.g PerformanceModel
:param json_dict: The JSON dict t... | f84e9622823024fc0c94bd2dadb7fde6d14e05e8 | 634,271 |
def remove_dash(item):
"""
Remove the first character in a string.
:param item: String
:return: input string, with first character removed
"""
return item[1:] | 2fbabb1b2359f6e89b69fd1d65a411e4b1012e6d | 634,273 |
def func_calc_density(M,T,Tc,Pc,Vc,Tb):
"""
Function to calculate density
Parameters:
Tc : Critical temperature (K)
Pc : Critical pressure (bar)
Vc : Critical molar volume (cm^3/mol)
Tb : Normal boiling temperature (K)
M : Molecular weight (g/mol)
... | e94ab19fd9ec1cf00752d5c642fb4d80b3a559ba | 634,274 |
def create_auto_profile(role_session, user_session, session_name, source_profile_name, role_arn):
"""Create the profile that'll be stored in the credentials file for autoawsume.
Parameters
----------
- role_session - the session credentials from the assume-role api call
- user_session - the session... | a80e7058c0902ebfb7b5ce1ea556319dfb96851c | 634,279 |
def monthly_savings(future_savings, years_to_retirement, interest_rate, compounds_per_year=2, startwith=0):
"""
Calculates how much you need to save per month to retire given the parameters
"""
r, m, n = interest_rate, compounds_per_year, years_to_retirement * 12
efr = (1 + r/m) ** (m / 12) - 1
... | 9cc8c08f5c5371c985cb39f2c2831ad2f22d25fe | 634,281 |
def subject_module_id() -> str:
"""Return the Protocol Engine module ID of the subject."""
return "subject-module-id" | d7b184ac7432924a3496eec71a42c25d16daa62c | 634,282 |
from typing import List
from typing import Dict
def sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]:
"""Sorts a list of dictionaries by their first key."""
return sorted(dicts, key=lambda d: list(d.keys())[0]) | 623e16f0fbffeb47aecd2153143de2d258ebf4b7 | 634,283 |
import logging
def GFFAddIDAttributes(gff_data):
"""
Construct & insert a ID attribute for all features without one
For each feature in the input GFF data that doesn't
already have an an ID attribute, insert one of the form:
ID=<feature>:<Parent>:<n>
where <feature> is the feature type (e.g... | a172c66772f3106e20cfc6dafd9d7d1c834feb91 | 634,284 |
import functools
def simple(func):
"""
Simple Decorator
This is a simple decorator function. It takes the function
being decorating as input and returns a wrapped version of that
function as output. This makes it possible to inject custom
logic berore and after the function execution.
"""... | ae1fa12a64d91cfc41f765382475d266c8f36221 | 634,285 |
from datetime import datetime
def convert_time(y):
"""Convert time string and reformat
:param str y: Time string to convert
:return: Time string
:rtype: datetime
"""
time = datetime.strptime(y, '%H:%M:%S').time()
return time | 241ec82cae2ca48c7b1174b2241d324fcf4c3072 | 634,286 |
def get_timeout(run_type):
"""Get timeout for a each run type - daily, hourly etc
:param run_type: Run type
:type run_type: str
:return: Number of seconds the tool allowed to wait until other instances
finish
:rtype: int
"""
timeouts = {
'hourly': 3600 / 2,
'daily': 24... | 40c07cb61bb3fa4c43538c0bf265990fe763a929 | 634,294 |
def _get_var_names(posterior):
"""Extract latent and observed variable names from pyro.MCMC.
Parameters
----------
posterior : pyro.MCMC
Fitted MCMC object from Pyro
Returns
-------
list[str], list[str]
observed and latent variable names from the MCMC trace.
"""
sample_... | 63d263b1a6d8836c3f3c36e9181e79edddcf5bab | 634,295 |
import csv
def transform_csv(input_file, output_file, header_fx=None, row_fx=None):
"""
Transforms a csv using streaming technique. Calls a header function that
allows the caller to modify the header; also calls a row function that
allows the caller to modify each row in csv.
Allows the caller to pass arbitrar... | 9a722ddd5616a25aff23e7e2480202036b6bd5ab | 634,297 |
def preconvert_discriminator(discriminator):
"""
Converts the given `discriminator` to an acceptable value by the wrapper.
Parameters
----------
discriminator : `str` or `int`
The discriminator of an user to convert.
Returns
-------
discriminator : `int`
Raises... | ed13f11db04a05fac7eb4810a0c95bd5d8452bb8 | 634,303 |
def xact_name(xact):
"""Returns the payee of a transaction"""
return xact["name"] | beb6652a25ce51789c0d70fbf08927e0f9e45699 | 634,307 |
import pickle
def cargar_objeto(nombre_archivo):
"""
Carga un objeto en Python, desde un archivo Pickle cuya ubicación es determinada por el usuario.
:param nombre_archivo: (str). Ubicación del archivo que contiene el objeto que se desea cargar.
:return: (objeto Python). Objeto en Python contenido e... | ac44003d1396d6c389260f683e282fb0eecab356 | 634,313 |
import operator
def sorted_dict_items(d, reverse=False):
"""Sorted (key, value) pairs by value.
"""
result = sorted(d.items(), key=operator.itemgetter(1))
if reverse:
return result[::-1]
else:
return result | f1f0a19e8ee94ff38005de7b72e899d7badbabd7 | 634,316 |
def identify_climate_scenario_run(scen_info, target_scen):
"""Identify the first matching run for a given climate scenario.
Returns
----------
* str or None, run id
"""
for scen in scen_info:
if target_scen in scen_info[scen]['climate_scenario']:
return scen
# End for
... | 71c68e8e5ff8023c7edd65598b9861be2d0b5c85 | 634,317 |
import torch
def create_coref_tensors(pos_coref_mention_pairs, pos_eds,
neg_coref_mention_pairs=None, neg_eds=None):
""" Combines positive and negative corefeference samples into tensors """
neg_coref_mention_pairs = neg_coref_mention_pairs if neg_coref_mention_pairs else []
neg_e... | 272615e8c0416714772317ed95723e55624f7699 | 634,318 |
import re
def to_kebabcase(string):
"""
Converts the given string to kebab-case.
>>> to_kebabcase('HelloWorld')
'hello-world'
>>> to_kebabcase('__Init__File__')
'init-file'
>>> to_kebabcase('')
''
>>> to_kebabcase('already-kebab-case')
'already-kebab-case'
>>> to_kebabcase... | e964981195dc9679f7beb4c21d1cee234ae67599 | 634,321 |
import torch
def batch_mse_torch(estimation, origin):
"""
batch-wise mse caculation for multiple audio files.
estimation: (batch, nsource, frames, freq_bins)
origin: (batch, nsource, frames, freq_bins)
nsource = 2
"""
mse1 = torch.sqrt(torch.pow(estimation - origin, 2).mean([3])).mean([1,2... | daa0ee46dfe3b55d535e8fc625e36e358af2d461 | 634,324 |
import re
def split_msg(msg):
"""
splits msg
example: this: is, some msg -> [this, is, some, msg]
"""
return re.findall(r"[^\s]+", msg) | 5b892b67b3e4e6aff4cd8949032d03948eccab55 | 634,326 |
def direction_color_red_green(val: str) -> str:
"""Adds color tags to the Direction information: Buy -> Green, Sell -> Red
Parameters
----------
val : str
Direction string - either Buy or Sell
Returns
-------
str
Direction string with color tags added
"""
color = "g... | 6fdefe9e5d3b37facb2789747a87932f7961f91b | 634,327 |
def hashing(file,pp):
""" Map an input file and a postprocessing config to an unique hash.
The hash is used to store the item in the database. It
needs to be persistent across different python implementations
and platforms, so we implement the hashing manually.
"""
file = file.lower()
file... | 82afc2e8a996cf1b893dc6bffe1f2553d772df01 | 634,333 |
def _mapping_table_for(domain_table):
"""
Get name of mapping table generated for a domain table
:param domain_table: one of the domain tables (e.g. 'visit_occurrence',
'condition_occurrence')
:return: mapping table name
"""
return '_mapping_' + domain_table | 13488c7235b7c1052226d96c1c785ce5154d6aa5 | 634,335 |
def url_get_parent(url):
"""
http://one/two/three => http://one/two
http://one => http://one
"""
index = url.rfind("/")
if index > 8: # avoid https://
return url[0:index]
else:
return url | d7f7931384825febab86b7d59bfd1df972c7304a | 634,336 |
from typing import Tuple
import math
def get_xy_components(lon: float, lat: float) -> Tuple[int, int]:
"""For a given longitude and latitude, returns the relevant
components of the name of the zip file containing the SRTM data (for
example "35" and "02" in "srtm_35_02.zip").
"""
mod_lon = (int(mat... | 076a4339278766f59c91338fb95953455e4ae0eb | 634,337 |
def recursive_merge(original, addition):
"""Merge the content of ``addition`` into ``original``, recursing when
both arguments have a dictionary for the same key.
"""
for key, value in addition.iteritems():
if key in original:
source = original[key]
if isinstance(source,... | 471c0a8731dc90a11d92e9a50a12975e2001a234 | 634,339 |
import torch
def bounding_box_x0y0x1y1_to_xcycwh(bounding_boxes: torch.Tensor) -> torch.Tensor:
"""
This function converts a given bounding bix of the format
[batch size, instances, 4 (x0, y0, x1, y1)] to [batch size, instances, 4 (x center, y center, width, height)].
:param bounding_boxes: Bounding b... | c365ac94068836d78d728e430812a39c3cfc80f9 | 634,345 |
from typing import Any
from typing import MutableSequence
from typing import Tuple
def is_edge_list(item: Any) -> bool:
"""Returns whether 'item' is an edge list."""
return (isinstance(item, MutableSequence)
and all(isinstance(i, Tuple) for i in item)
and all(len(i) == 2 for i in item... | a164a34e1287b36250084aa76ebebad60f3346da | 634,348 |
import collections
def getDictFromAngles(angles):
"""
Converts angles of a JointState() to a dictionary
:param angles (sensor_msgs.msg.JointState): angles to be converted
:return (dict): dictionary with angles
"""
d=dict(zip(angles.name,angles.position))
return collection... | d919c0c52c25b8d6f6e894c8897b554190e8b88a | 634,349 |
def process_status(pid, run):
"""
Return the status of a process, obtained using the ps command.
The run option is used to run the command (so it could run on
a remote machine). The result is a dictionary; it is empty if
the given process is not running.
"""
fields = ['%cpu', '%mem', 'etime... | 86acac06e3316631c275c1569c39d1a6b1d6eaca | 634,351 |
def freq_str(freq_list):
"""
Function that transforms the array of frequency values into a string
of comma separated entries.
The array is converted into a string and the square brackets are removed
form it. The resulting string will be the list of frequencies to sweep
over, organized into com... | c7a92e6226139459512fbbd765ef04137e0b148f | 634,352 |
import json
def incident_to_incident_context(incident):
"""
Creates an incident context of a incident.
:type incident: ``dict``
:param incident: Single detection object
:return: Incident context representation of a incident
:rtype ``dict``
"""
... | 28f4f9d34a9dbb23fd09bdd253a9328d32892b3b | 634,354 |
def getSelectionShape(selection):
""" Return the shape of the given selection.
Examples (selection -> returned shape):
[(3,7,1)] -> [4]
[(3, 7, 3)] -> [1]
[(44, 52, 1), (48,52,1)] -> [8, 4]
"""
shape = []
rank = len(selection)
for i in range(rank):
s = selection[i]
... | 6918660af077e04ea28ade739dbaebce739963f6 | 634,358 |
from datetime import datetime
def make_sim_exp_name(config):
"""Helper to create a simulator directory name using datetime and config"""
time = datetime.now().strftime('%Y%m%d_%H%M%S')
n_nonmot = config['exp_params']['n_non_motile']
n_mot = config['exp_params']['n_motile']
return f'{time}_sim_ma... | bf23d6d461897081f2a4c95c22876839532e400e | 634,359 |
def _remove_extension(path, extension):
""" Removes the extension from a path. """
return path[:-len(extension)] if path.endswith(extension) else path | e819949ec396f70029df40e4a4aa3469e28ea613 | 634,361 |
def get_mock_loss_function(mock_value):
"""
A loss function that just returns a hardcoded value. Used for testing only.
:param mock_value:
:return:
"""
def mock_loss(y_true, y_pred):
return mock_value
return mock_loss | 182562a6ccf06944ef56dcb25f52918dc65a171e | 634,366 |
def feature_dict_map(weights):
"""construct a dict with features from a weights dictionary
:param weights: dictionary mapping features to numeric weights
:return: dictionary from features to a (index, weight)
"""
if type(weights) is dict:
result = {k: (i, weights[k]) for i, k in enumerate(... | b85f0e413348fce32b76bd6df14e7156da6a4caa | 634,367 |
def average(l):
"""The average value of a list"""
if len(l) == 0:
return 0
return sum(l)/len(l) | a91df0126004f8dbe1e3e007eb9b0098ae7d75e1 | 634,369 |
def letters_only(word:str, lower_case:bool = True):
"""
Return only letters of string input parameter
Parameters
----------
word : str
String from which letters are being returned
lower_case : bool
If set to True (default) return lower-case letters
Returns
-------
... | 915ab2e4422091c98cc54c7c53afba08e7958451 | 634,371 |
import inspect
import ctypes
def cdll_with_spec(lib_path, spec):
"""
Open a shared library using ctypes.CDLL and apply the given spec class'
type annotations to the argtypes and restype attributes of the shared
library's functions.
The spec is a stub class with type annotations for the argument a... | 56c42a9677e850f14b614e09fbbb061a4d482650 | 634,377 |
def remote_addr_from_request(request):
"""
Returns the correct remote address from the request object. If the
request was proxied, this correct information is in HTTP_X_FORWARDED_FOR
"""
if not request:
raise TypeError("No request passed to function")
if 'HTTP_X_FORWARDED_FOR' in request... | d14a36a9da635c525e7500686523d1659e9312c5 | 634,378 |
def create_choice_attribute(creator_type, value, choice_entry):
"""Create an instance of a subclass of ChoiceAttributeMixin for the given value.
Parameters
----------
creator_type : type
``ChoiceAttributeMixin`` or a subclass, from which we'll call the ``get_class_for_value``
class-meth... | da49acfab180a7d0d21aa031424d0187d3e3eb16 | 634,381 |
def intervalcheckstrict(a,b,c):
"""
Returns whether a < b < c is True or False
"""
if a<b and b<c:
return True
else:
return False | 49643ae8a9218c3599a43da4f395670043e7eea7 | 634,382 |
def generate500response(error: str) -> dict:
""" A function that generates a '500-Internal Server Error' message and returns it as a dict """
return {
"status": 500,
"message": "Internal Server Error",
"error": error
} | 781c0467067a08fcd015b8109c2e8d4927af3d7c | 634,385 |
def add_integers(a: int, b: int):
"""Sum two integers
Args:
a (int):
b (int):
Returns:
int: sum of the integer inputs a and b
"""
return a + b | 3cdd1be6670a649b69f0eaa4a274ebd4029a6d64 | 634,390 |
def standardize_input(score):
"""
Converts the score input of either a str, int, or float into the desired
input for percentage_to_gpa.
I don't care about some being int and some being float, still works all the same.
>>> standardize_input('95%')
95.0
>>> standardize_input(95)
95
... | 39a375da82003a715cec3965e7ad8f213d51b3a0 | 634,391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.