content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def format_docstring(docstr: str) -> str:
"""Removes \n and 4 consecutive spaces."""
return docstr.replace('\n', '').replace(' ', '') | 47b9103961a5a87436e52b55c1ae13206c6ee918 | 519,016 |
def has_local_name(agent):
"""Loops through all the agent names and returns True if any of them have
a source of `local`, `ingest`, `nad`, or `naf`"""
for name in agent.names:
if name.source in ['local', 'ingest', 'nad', 'naf']:
return True
return False | c259b01fdc9f1118877a215713e8e0ffa23425ae | 473,747 |
def flip_1d_index_vertically(index, rows, columns):
"""Finds the index to the corresponding vertically flipped 1d matrix value.
Consider a 1d matrix [1, 2, 3, 4, 5, 6] with 3 rows and 2 columns. The
original and vertically flipped representations are shown below.
1 2 5 6
3 4 -> 3 4
... | ca8fb78915bd278b3ef397a1c9a1d3b2a6af1e15 | 602,407 |
def _make_class_name(name):
""" Make a ufunc model class name from the name of the ufunc. """
return name[0].upper() + name[1:] + 'Ufunc' | 7f5e2b0c81b81532c4222efb1ab58b8126906628 | 171,473 |
def issolved(cube: list) -> bool:
"""
Return True if the cube is solved, False otherwise.
A cube is a solved cube if every sticker of each side of the cube is
the same.
"""
return all(all(x == s[0][0] for y in s for x in y) for s in cube) | bb6d0e35061b54a0476adfd90e80bd5a3b878807 | 594,115 |
from datetime import datetime
def getDateFromDatetime(inputDateString):
"""
Given a datetime string - return a date object + 1 day ahead since
tweets from day X are registered to midnight at day X+1
"""
dateOnly = inputDateString.split(" ")[0]
dateOnlyList = [int(x) for x in dateOnly.split("-"... | d6b5168c68145f029b8a79c8a5682fe7948692e5 | 285,969 |
def binary_tag_to_tags(text_df, tag_values):
"""
+++INPUT+++
text_df: dataframe with binary tags, fillna with 0
tag_values: array of tag strings
example: tag_values = text_df.columns[2:].values
+++OUTPUT+++
text_df: with Tags column added containing tags
"""
tags_list = []
fo... | d63aa63f67490b4372706a99afa39f7d9fa6acda | 535,328 |
import torch
def densify_features(x, shape):
"""
Densify features from a sparse tensor
Parameters
----------
x : Sparse tensor
shape : Dense shape [B,C,H,W]
Returns
-------
Dense tensor containing sparse information
"""
stride = x.tensor_stride
coords, feats = x.C.lon... | 4ef60f15a1bae846009ddfa76595fa9121fc3035 | 575,298 |
def exp_chem_list(rdict):
"""extract the chemicals that were used.
:param rdict: see DataStructures_README.md
:return: a set of the chemicals used in all the experiments
"""
chemicalslist = []
for reagentnum, reagentobject in rdict.items():
for chemical in reagentobject.chemicals:
... | 0280e99cf3af3860320a23b0314a630d4b373648 | 424,939 |
def del_comment(string):
"""Delete the comment from the parameter setting string.
Parameters
----------
string : str, default None
The parameter setting string probably with the comment.
Returns
-------
string : str
The parameter setting string without the comment.
"""
... | 127130208c08f676dbc9258f0fe86ecf6d2b9f75 | 257,319 |
from pathlib import Path
def read_file_to_list(p4pfile: str) -> list:
"""
Reads a file and returns a list without line endings.
"""
p4plist = []
try:
p4plist = Path(p4pfile).read_text().splitlines(keepends=False)
except IOError as e:
print(e)
print('*** CANNOT READ FILE... | bc0681fc3da1a547a40fe2e437dcc23d24487ea4 | 475,746 |
def _req_input_to_args(req_input):
"""
Given a list of the required inputs for the build command, create an args
string
:param list[str] req_input: input names
:return str: args string
"""
return ["--" + x + " <arg_here>" for x in req_input] | 7f4418ee7e020d3747511d197c33dec5d541248d | 441,953 |
def is_vm(obj):
"""
Checks if object is a vim.VirtualMachine.
:param obj: The object to check
:return: If the object is a VM
:rtype: bool
"""
return hasattr(obj, "summary") | 263c26d1cf15de663bc00371edaec6173bb800dc | 533,465 |
def data_has_value_from_substring_list(data, needle_list):
"""Recursively search for any values that contain a substring from the specified list
Args:
data (dict, list, primitive)
needle_list (list)
Returns:
(bool) True or False if found
"""
if isinstance(data, list):
... | e5516aa0abb5e54b918b23e2ac35e4dc2a89c183 | 433,847 |
def set_regex_parentheses(parent_paragraph_id):
""" Adds parentheses if the paragraph has a parent.
Paragraphs with a parent ( = subparagraphs ) have
their identifiers wrapped in parentheses and an em dash.
"""
par_open = r""
par_close = r""
if parent_paragraph_id:
par_open += r"—\("... | 5ffd5e15783ccade0fbcc67634a4dff2ebb869d5 | 548,281 |
import json
def load_json(file):
"""Loads a JSON file and returns it as a dict"""
with open(file) as f:
return json.load(f) | d2e593c2d698223ad28103e4c1d7d91426137f53 | 655,876 |
import asyncio
def wrap(fn, fn_name, called):
"""Wrap fn to add fn_name to called on invocation.
"""
async def async_wrapper(*args, **kwargs):
await fn(*args, **kwargs)
called.add(fn_name)
def wrapper(*args, **kwargs):
fn(*args, **kwargs)
called.add(fn_name)
return ... | b5059656c44d0fc22697f78b3c67a832dd99448b | 255,663 |
import logging
import copy
def graph_directional_to_undirectional(graph):
"""
Convert a directional to an undirectional graph
Returns a deep copy of the full graph with all directional edges
duplicated as undirectional ones.
Undirectional edges share the same data dictionary. In converting
di... | 045ad1f1a7d455ca05ffe50aa4fb117957cb4ed1 | 607,279 |
import heapq
def sort_and_trim_beams(beams: list, beam_width: int):
"""
https://github.com/kensho-technologies/pyctcdecode/blob/v0.1.0/pyctcdecode/decoder.py#L68
"""
return heapq.nlargest(beam_width, beams, key=lambda x: x.score_lm) | 91087ed3a9e4633c1bb2580d265ab59c1a521c09 | 353,934 |
def drop_zero_columns(dtf):
"""
Drop all columns from a dataframe if they are composed of only zeros
"""
return dtf.loc[:, (dtf != 0).any(axis=0)] | 5710ffe6db72c59d22ff03430d9c07a6faf653d6 | 144,829 |
def uniform(random, n):
"""Returns a bytestring of length n, distributed uniformly at random."""
return random.getrandbits(n * 8).to_bytes(n, "big") | 1076d1a1bc4d6838386fb6419d5f1ba58591f2a2 | 210,276 |
def get_snaps_for_instance(client, rds_instance, snapshot_type=''):
""" Gets all snapshots for a RDS instance"""
snapshots = []
resp = client.describe_db_snapshots(
DBInstanceIdentifier=rds_instance['DBInstanceIdentifier'],
SnapshotType=snapshot_type
)
while 'Marker' in resp:
... | 03d0c752476822f8f231c8794ac2c1f5c3bca7d6 | 435,807 |
def get_unique_list_values(list_to_review):
"""Helper function, takes in a list as a single argument and returns a unique list.
"""
unique_list = []
# traverse for all elements
for item in list_to_review:
# check if exists in unique_list or not
if item not in unique_l... | f9014c27bccc3f58524ad59c553b951e5150e7a6 | 227,661 |
def _attachment_v2_to_v1(vol):
"""Converts v2 attachment details to v1 format."""
d = []
attachments = vol.pop('attachments', [])
for attachment in attachments:
a = {'id': attachment.get('id'),
'attachment_id': attachment.get('attachment_id'),
'volume_id': attachment.ge... | 061e7dd81e61ed1dab4e2ea529218bc51df8c9aa | 155,174 |
def get_size_of_wordlist(filename):
"""Reuturn the number of lines in the file."""
return sum(1 for _ in open(filename)) | 67db2a86419dd3a5beb6053ad8b4a8b69542cee6 | 172,737 |
def get(lst, index, default=None):
"""
Retourne l'élément de `lst` situé à `index`.
Si aucun élément ne se trouve à `index`,
retourne la valeur par défaut.
"""
try:
return lst[index]
except IndexError:
return default | 273345d2acf1c4aecbf584d600f67ff095a710ea | 53,490 |
import yaml
def configuration(configuration_path):
"""Load our configuration."""
with open(configuration_path, 'r') as stream:
return yaml.load(stream, Loader=yaml.FullLoader) | 5fab251f28ca9eca955cd396b92a6c5c7ae8ee97 | 33,149 |
def decode(string):
"""Unescape string originating from XML
:param string: string to decode
:type: str
:returns: decoded string
:rtype: str
"""
if ''' not in string and '"' not in string and '<' not in string and '>' not in string and '&' not in string: # already de... | a4432c0b22b239e51f96b2f0fb06d5ec28735b86 | 516,835 |
from typing import OrderedDict
import math
def get_latencies_summary(latencies):
"""
Given a raw timeseries of latencies, create a summary of each point in time,
with the average standard deviation and mean, the minimum and maximum, and
the minimum/maximum range for the percentiles (as we can't averag... | cd8e00cb218924aa72e8839b55099b3b9a45c661 | 561,839 |
def get_file_extension(fn):
"""
get file extension and check if it is compressed
:param: str, file path
:return: str,bool
"""
# assert isinstance(fn, str)
compressed_file_ext = ["gz"]
fn_part = fn.split(".")
compressed = False
ext = fn_part[-1]
if ext in compressed_file_ext:... | bce96d08f28381f42f329e4fa08c4b858401e019 | 418,303 |
from dateutil import tz
from datetime import datetime
def convert_datetime_string_to_object(datetime_string):
"""
Helper function to convert datetime string to object with local timezone
"""
local_tz = tz.tzlocal()
datetime_object = datetime.strptime(datetime_string, '%Y-%m-%d %H:%M:%S')
retur... | 9e4c6007806b8932f7cb07ccaa4df068202ffaf5 | 334,301 |
import unicodedata
def normalize_grapheme(grapheme, bipa):
"""
Normalizes a grapheme.
Does Unicode normalization, splitting in case of Phoible/slash-notation,
BIPA default selection.
"""
# Unicode normalization
grapheme = unicodedata.normalize("NFC", grapheme)
# Split over slash not... | 98af5b3f88bc88a482ee01c1193ab2a58e6aa907 | 562,614 |
def _trimmed_text(node):
"""Returns the trimmed text contained in the given DOM node or None if
empty or if node is None.
"""
try:
return node.text.strip() or None
except AttributeError:
return None | 62f3e5c93d0d4a8a12b95f48a05380047407323e | 529,017 |
from typing import List
import glob
def get_stock_symbols(market: str) -> List[str]:
"""
Read stock symbols from internal file
Parameters
----------
market: str
The stock market (NASDAQ | NYSE)
Returns
-------
List
A list of symbols for the given market
"""
... | 59471448192e6987fdedbd293f0a40f9e5495306 | 221,040 |
def cleanup(data, clean='layers', keep=None, copy=False):
"""Deletes attributes not needed.
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
clean: `str` or list of `str` (default: `layers`)
Which attributes to consider for freeing memory.
keep: `str` o... | 36127ef66a04a83ba78d4e8c1e78fdfe7edf94fe | 513,330 |
import itertools
def _preorder_walk(node, _app=None):
"""Walk the tree in preorder"""
return itertools.chain(
[node],
*[_preorder_walk(child) for child in node.children]
) | b3503c892d4adb347032dbfe1e6e5cd0e4c203e2 | 431,040 |
def initial_fragment(string, words=20):
"""Get the first `words` words from `string`, joining any linebreaks."""
return " ".join(string.split()[:words]) | 5b390cb5f98c9e940f2a964101b9593f0fa1ffb8 | 32,365 |
def moving_average(data, target_var, features_list, num_days = 7):
"""
Cacluate moving average of target variable and store result in a new column
Parameters
----------
data: data frame
It has columns location, date, and a column with the response variable to forecast.
This data fr... | 1d1b63e76a84a6d6a76fd3ce0ce61e3a82b11b51 | 211,730 |
def is_by_sources(module):
"""
Returns whether module defined by sources
"""
return module.location is not None | 56bf8041fd53d98b4699eca722d56e637324bf49 | 555,039 |
def load_login_file(fpath):
"""
Load login name and password from file.
"""
with open(fpath) as f:
name = f.readline().rstrip('\n')
passwd = f.readline().rstrip('\n')
return name, passwd | 52e4f5e23d4b05e2a5c447bbace40fb8450162f6 | 262,302 |
def numeric_filter(operation, value, column, df):
"""Filters a data column numerically.
Arguments:
operation: Operator used to filter data (e.g. ">", "<", "==", ">=", "<=", "!=")
value: Operand
column: String for column name
df: DataFrame
Returns: Boolean column that indicates whether each... | 868907d2fed5947c0974896af73a9277fcef0ae8 | 640,693 |
def public_dict(obj):
"""Same as obj.__dict__, but without private fields."""
return {k: v for k, v in obj.__dict__.items() if not k.startswith('_')} | 2edee1a17d0dad6ab4268f80eb565406656a77b4 | 704,317 |
def readUntilNull(s):
"""
Read a string until a null is encountered
returns (string up to null , remainder after null)
"""
item = s.split(b'\0' , 1)
if len(item) == 1:
return (item[0] , None)
else:
return (item[0] , item[1]) | 62933ee1c30f8b077fe13f8f2074612c8b090213 | 445,879 |
def hex_bytes(data: bytes, sep: str= " "):
""" Format a bytes() object as a hex dump """
return sep.join("{:02x}".format(bval) for bval in data) | aacc0366a7e20cc3ead71559dba55bafd5d4275e | 499,261 |
def _response_ok(response, call_type):
"""
Checks whether API HTTP response contains the associated OK code.
:param response: Response object.
:param call_type: String containing the HTTP request type.
:return: True if response was OK.
"""
ok_codes = {
"GET": [200],
"PUT": [2... | e47516e51c7de8e3dd5e7c4eed88705055952803 | 312,507 |
def contains_test_passer(t, test):
"""
Return whether t contains a value that test(value) returns True for.
@param Tree t: tree to search for values that pass test
@param function[Any, bool] test: predicate to check values with
@rtype: bool
>>> t = descendants_from_list(Tree(0), [1, 2, 3, 4.5,... | 56cbd48f9c416c64c1822b637fd4e8780ce72bc5 | 650,058 |
def _is_decimal(col):
"""Check for decimal data types
Returns bool - True if column is decimal or numeric.
"""
return col['field_type_name'].upper() in ['DECIMAL', 'NUMERIC'] | a48efd2f2b0c9883d0c09e786e209e1b8cb47778 | 480,047 |
def create_idea(conn, idea):
"""
Add a new idea into the ideas table
:param conn:
:param idea:
:return: idea id
"""
sql = """INSERT INTO ideas(name, description, tags)
VALUES(?,?,?)"""
cur = conn.cursor()
cur.execute(sql, idea)
conn.commit()
return cur.lastrowid | 8df51c3e6361d2dbbfe03cc18cbae7f9c47841de | 152,041 |
def put_bucket_policy(s3_obj, bucketname, policy):
"""
Adds bucket policy to a bucket
Args:
s3_obj (obj): MCG or OBC object
bucketname (str): Name of the bucket
policy (str): Bucket policy in Json format
Returns:
dict : Bucket policy response
"""
return s3_obj.... | c1f098a49e743f180ed7882951f0bd38ba9eeb39 | 571,855 |
from pathlib import Path
import re
def check_files_exist(directory, pattern_list):
"""Check that a list of file patterns exist in a given directory."""
existing_files = [str(i.relative_to(directory)) for i in sorted(Path(directory).rglob("*"))]
try:
assert len(existing_files) == len(pattern_list)
... | 79ecee0d74606c37aef21ed72e7c4c735ad022f7 | 131,423 |
import ast
def has_node(code, node):
"""Given an AST or code string returns True if the code contains
any particular node statement.
Parameters
----------
code: A code string or the result of an ast.parse.
node: A node type or tuple of node types to check for. If a tuple is passed
it r... | 9e1555a3393e3c91f35f6e3fc468eab14d5147b4 | 600,096 |
def unique(x):
"""Convert a list in a unique list."""
return list(set(x)) | 105df86a8a5df1cd1981bbfab304bc4f8b759fa0 | 580,550 |
def _date_long_form(date):
""" Displays a date in long form, eg 'Monday 29th April 2019'. """
second_last = (date.day // 10) % 10
last = date.day % 10
if second_last != 1 and last == 1:
ordinal = "st"
elif second_last != 1 and last == 2:
ordinal = "nd"
elif second_last != 1 and l... | 248cdaaba72e6252d6fdcec6499a4332e50a85c9 | 646,725 |
def is_iterable(posibleList):
"""Validate if element is iterable
Args:
posibleList (Any): posible iterable element
Returns:
bool: if element is iterable
"""
try:
if isinstance(posibleList, (tuple, list)) or hasattr(posibleList, "__iter__"):
_ = posibleList[0]
... | 9f07a3fa1f21423b477c535020063d6abe376f58 | 542,062 |
import random
def random_every_time(context, values):
"""Choose a random value.
Unlike Jinja's random filter,
this is context-dependent to avoid caching the chosen value.
"""
return random.choice(values) | 4e8a6294a1bf4ccbdfc9714c720ca83df24a6760 | 170,682 |
def flatten_dict(d, prefix="", separator="."):
"""
Flatten netsted dictionaries into a single level by joining key names with a separator.
:param d: The dictionary to be flattened
:param prefix: Initial prefix (if any)
:param separator: The character to use when concatenating key names
"""
... | c7e53cb66db8938a196e9adc22e7013e20191d31 | 394,490 |
def beaufort(n):
"""Converts windspeed in m/s into Beaufort Scale descriptor."""
s = ''
if n < 0.3:
s = 'calm'
elif n < 1.6:
s = 'light air'
elif n < 3.4:
s = 'light breeze'
elif n < 5.5:
s = 'gentle breeze'
elif n < 8.0:
s = 'moderate breeze'
elif... | 75b6150a8530ea174c447d11ea2e5c212cdd0e93 | 442,093 |
def translate_direct(adata, direct, no_index):
"""Translate all direct hit genes into their orthologs.
Genes not found in the index of the table will be upper-cased, after
excluding some gene symbols that usually do not have an ortholog, i.e. genes
- Starting with 'Gm'
- Starting with 'RP'
- End... | 8d8ab2efd60463603fa5b8c212ae6878d5d68a36 | 142,888 |
from typing import Optional
from typing import Match
import re
def find_word(word, src) -> Optional[Match[str]]:
"""Find word in a src using regex"""
return re.compile(r'\b({0})\b'.format(word),
flags=re.IGNORECASE).search(src) | 5619f472db8256ad7524529911cc190fc3140c46 | 440,393 |
def squish(tup):
"""Squishes a singleton tuple ('A',) to 'A'
If tup is a singleton tuple, return the underlying singleton. Otherwise,
return the original tuple.
Args:
tup (tuple): Tuple to squish
"""
if len(tup) == 1:
return tup[0]
else:
return tup | ddaa8e53edc9fbda2ba07185b98bf934171d92bf | 170,911 |
import logging
def get_handler_filename(logger):
"""Gets logger filename
Parameters:
* logger (object): log file object
Returns:
* str: Log file name if any, None if not
"""
for handler in logger.handlers:
if isinstance( handler, logging.FileHandler ):
return handler.baseFilename
re... | bdaa47977c14601aa2217fc8a3c734e97b9a0295 | 37,729 |
def check_weights(data_ps):
"""Check if sum of propensity score weights match sample size
Args:
data_ps (pandas.DataFrame): dataframe with propensity score
Return:
tuple: sample size, treated size from weigths, untreated size froms weigths
"""
weight_t = 1./data_ps.query("nudge==1")[... | 85abaf40e7a7e24318ba31797264361d3780ebbd | 140,377 |
import __main__ as m
def is_running_interactive() -> bool:
"""Check if we're running in an REPL"""
try:
return not hasattr(m, "__file__")
except Exception as e:
print(e)
pass
return False | bafe84caf9e40c97a2f000136ca77546850e26c0 | 114,931 |
def find_between(s, first, last):
"""
Find sting between two sub-strings
Args:
s: Main string
first: first sub-string
last: second sub-string
Example find_between('[Hello]', '[', ']') -> returns 'Hello'
Returns:
String between the first and second sub-strings, if any... | d2df4c89d63f07678cba8283849917ff767b0903 | 673,284 |
def is_range(obj):
"""Helper function to test if object is valid "range"."""
keys = ['start', 'step', 'stop']
return isinstance(obj, dict) and all(k in obj for k in keys) and \
all(isinstance(obj[k], float) for k in keys) | 4bb1d210ebb0a7265671b3d7070912052f71601e | 33,963 |
def is_redirect(page):
"""
Checks if a page is a redirect
Returns
--------
bool
True if the page is a redirect
False if the page is not a redirect
"""
redirect = page.getElementsByTagName('redirect')
if len(redirect) > 0:
return True
return False | c5913b1fb66099c9d38a9851496bfacb76b046aa | 126,615 |
def description_length(user):
"""
Get the length of user description in words
:param user: the user object in json tweet
:return: vector length of 1 indicating the length of description. If user
if user has no description, [0] will be returned
"""
des_length=0
if user['descri... | 41e9ec6800b6fe86b14297114179d91955431100 | 107,571 |
def _endpoint_from_image_ref(image_href):
"""Return the image_ref and guessed endpoint from an image url.
:param image_href: href of an image
:returns: a tuple of the form (image_id, endpoint_url)
"""
parts = image_href.split('/')
image_id = parts[-1]
# the endpoint is everything in the url... | 626484976a35b89ecaf5b363503ac993ee231613 | 90,570 |
def sanitize_list_input(_list: list, _def: list) -> list:
"""Sanitize the _list by reducing it to distinct values.
If _list is None, then return second parameters value _def
:param _list: list, if not None, will be reduced to its distinct values
:param _def: list, the value to be returned, if _list is ... | a2cec282d8ff38290e9249ba692ef696ee40abf9 | 149,163 |
def extract_name(row):
""" Helper function for comparing datasets, this extracts the name from the db name
Args:
row: row in the dataframe representing the db model
Returns:
name extracted from agency_name or np.nan
"""
return row['agency_name'][:row['agency_name'].... | 84d525d008cf35e4ee0b1347caf0909a67cad1e3 | 663,852 |
def get_true_positives(data, classifier):
"""Find the total positives that also are selected by our classifier."""
return data[data["foundSegment"] & classifier(data)].size | 2d1581e5f9ade4ff299557c76f3a9507c4dc5a55 | 10,474 |
def generate_community_tags_scores(database, community):
"""
This function generates the most important terms that describe
a community of similar documents, alongside their pagerank and in-degree scores.
"""
# Get all intersecting nodes of the speficied community,
# ranked by their in-degree (... | c7623fdbad3389ec5c3dbf55c6758036c7cfce03 | 660,460 |
def encode_info_token_http_auth(token):
"""
Encodes the token to be sent in the Authenticate header.
:param token: token to be sent. Assumes the token is already decoded
:return: the body of the `Authorization` header
"""
return ' Token {}'.format(token) | 5cacc6b899cec0ab4db486b327646932e595253c | 282,762 |
def _unfill(v, l = 5):
"""unfill takes a zfilled string and returns it to the original value"""
return [
str(int(v[l * i:l * (i + 1)]))
for i in range(len(v) // l)
] | 28c9adfe90efe2b2e1f895b59844990e2455f183 | 147,892 |
import calendar
def which_ten(d):
"""
Determine which ten-day period a date falls in.
:type d: datetime.date
:param d: day of date, e.g. 2016-01-02 in format %Y-%m-%d is 2
:return: an integer that is the prefix of the relevant ten-day period.
"""
if not calendar.monthrange(d.year, d.month... | 25b7ac3de60a7b0407191875f8c60f5f614bee1a | 470,523 |
import torch
def ohe(input_vector, dim, device="cpu"):
"""Does one-hot encoding of input vector."""
batch_size = len(input_vector)
nb_digits = dim
y = input_vector.reshape(-1, 1)
y_onehot = torch.FloatTensor(batch_size, nb_digits).to(device)
y_onehot.zero_()
y_onehot.scatter_(1, y, 1)
... | 1b0406471d3755cf2f99d23f6873727b0986036a | 84,907 |
def always_true(result, previous_state):
""" Not really necessary since no filters results in an always true result,
but this is useful to show an example of what a filter is without actually
doing anything.
"""
return True | 157fe783cfe14049d6c9bf742eb41064fc9b1ef7 | 387,684 |
def process_gps_data(gps_df, threshold_record_length=5, threshold_uplift=5):
"""
Thin the gps data to remove stations with short record lengths and
unrealistically high uplift or subsidence rates
"""
gps_df = gps_df[gps_df['record_length'] > threshold_record_length]
gps_df = gps_df[gps_df['RU(mm... | 8a5247182f3132d0e693f6eb03c48b3edcae12bf | 468,708 |
def rgb_to_hsv(rgb):
"""
Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the
red, green, and blue value.
:return: HSV represent... | aa2c75b92c9830c7e798b0ca6ee9feac20793de4 | 24,361 |
from pathlib import Path
from typing import List
def collect_app_bundles(source_dir: Path) -> List[Path]:
"""
Collect all app bundles which are to be put into DMG
If the source directory points to FOO.app it will be the only app bundle
packed.
Otherwise all .app bundles from given directory are ... | 50a4bf767eb0208045257a2ebf8a760ae7a5fc6d | 667,184 |
def parsesep(s:str, sep:str=","):
"""Get the next word from a string, separated ny sep. Return (word,remainder)"""
i=s.find(sep)
if i<0:
i=len(s)
result=s[0:i]
remain=s[i+len(sep):]
return (result,remain) | ebc09edf1f361768db15d1dfefd3d9d00efba795 | 451,028 |
def energy_value(h, J, sol):
"""
Obtain energy of an Ising solution for a given Ising problem (h,J).
:param h: External magnectic term of the Ising problem. List.
:param J: Interaction term of the Ising problem. Dictionary.
:param sol: Ising solution. List.
:return: Energy of the Ising string.
... | 866e3175534f5c1e1d606b12e6815cf520a467b0 | 663,403 |
def get_scalebin(x, rmin=0, rmax=100, tmin=0, tmax=100, step=10):
"""
Scale variable x from rdomain to tdomain with step sizes
return key, index
:param `x`: Number to scale
:type `x`: number
:param `rmin`: The minimum of the range of your measurement
:type `rmin`: number, optional
:para... | 7cd22ca13e6dde43bada1557fabf3cb217047243 | 522,541 |
def get_rad_factor(rad, emission, solar_irr, emissivity=None):
"""
Return radiance factor (I/F) given observed radiance, modeled emission,
solar irradiance and emissivity. If no emissivity is supplied,
assume Kirchoff's Law (eq. 6, Bandfield et al., 2018).
Parameters
----------
rad (num or ... | 5d02a0e31012e4116e048e0a23e273824d926664 | 579,434 |
def filter_dict(original_dict, pattern_dict):
"""
Return a dict that contains all items of original_dict if item key is in pattern_dict.keys()
:param original_dict:
:param pattern_dict:
:return:
"""
keys = set(original_dict.keys()).intersection(pattern_dict.keys())
return {key: original_... | 2e5ea5bd2590ebf71ca1174b7d7572f78555bd35 | 429,601 |
def parse_rrset_record_values(e_resource_records):
"""
Used to parse the various Values from the ResourceRecords tags on
most rrset types.
:param lxml.etree._Element e_resource_records: A ResourceRecords tag
beneath a ResourceRecordSet.
:rtype: list
:returns: A list of resource record s... | 92d758407e557301f766f122a4f6bca952035350 | 541,955 |
def create_point_datatype(records):
"""
Creates point datatype to enable fetching GeoJSON from Socrata
:param records: list - List of record dicts
"""
for record in records:
latitude = record["latitude"]
longitude = record["longitude"]
# Socrata rejects point upserts with no ... | 3c762ad4cfbad5ef66cb84a91b5a9dcd0e7bfb4f | 620,037 |
import re
def get_config_name(config):
"""
Return sample sheet configuration name. Remove any identifying local
directory information if present.
:param config_val: Original configuration name (string)
:return: String
"""
if config.find('/') == -1 and config.find('\\') == -1:
retu... | bc6634dcc1030fc6b4929dd223b1b8611f922eed | 554,939 |
def add_inference_args(parser):
"""Add parser arguments for inference options."""
parser.add_argument('--inference-type', metavar='<inference-type>', type=str, required=False, choices=['cvlib', 'fastmot'], default='cvlib', help='Input type for inference ["cvlib", "fastmot"].')
parser.add_argument('--names',... | b65ce0a0a2cc9fd270fa46a8eb9c96e045a5c24d | 426,946 |
def check_fit(image, text_file):
"""
Checks if the supplied data will fit the image.
Args:
image: The image object of the PIL image.
text_file: the text file you want to embed to the image.
Returns:
True: If the supplied text fits the image.
False: If the supplied te... | 8b6ea04b0b7c40db9e464b2fd38214e9d9ae868e | 437,725 |
def convert_int_to_bits(int_value, index, size):
"""
:param int_value: The integer value to convert to shifted bit representation.
:param index: Start index of value in desired 4-byte output. Least significant bit of output is index zero.
:param size: Size in bits that integer value should take up in re... | aade4c823495305c517a7f573c0f752dcdd4bc38 | 542,437 |
import torch
def find_intersection(line_a, line_b):
"""Find the intersection point (if it exists) of two line segments, a and b.
This uses an algorithm based upon LeMothe's "Tricks of the Windows Game Programming Gurus". We
could have used some fancy cross product stuff here, but this is much more compre... | bb0fcc8cd3992abef05d13bdc18c1eae407fe5c1 | 277,294 |
def _check_1d_vector(vector):
"""Check 1D vector shape
Check 1D vector shape. array with shape
[n, 1] or [n, ] are accepted. Will return
a 1 dimension vector.
Parameters
----------
vector : array (n,) or (n, 1)
rank one vector
Returns
-------
vector : array, (n,)
... | ff8cc78d71f8fdfa714c351dc7662a470c9f510a | 547,500 |
def get_array_type(arr):
"""Returns if the array is a scalar ('scalars'), vector
('vectors') or tensor ('tensors'). It looks at the number of
components to decide. If it has a wierd number of components it
returns the empty string.
"""
n = arr.number_of_components
ret = {1: 'scalar... | 886949122ea3d4b2ea395c9fbdec618e0af973a8 | 578,484 |
def find_key_symptom(tariffs, cause_reduction, cause, endorsements,
rules=None):
"""Find the key endorsed symptom for a cause
Args:
tariffs (dict): processed tariff matrix
cause_reduction (dict): mapping from cause46 to cause34
cause (int): cause number at the cause... | e8805fd29bf09cd3e0269ae4203f4fd7912f5c72 | 8,678 |
from typing import TextIO
import csv
def process_ethnics(data: TextIO):
"""Returns a generator of ethnics dictionary
Args:
data (TextIO): A file-like object of ethnics data
"""
next(data)
datas = csv.reader(data)
return [item for item in datas] | 517099893895b0e53d633c6c573ea767701455cd | 298,080 |
def get_cmd_args(argv):
"""
Take the `argv` arguments apart and split up in arguments and options.
Options start with `-` and can be stacked. Options starting with `--` cannot
be stacked.
"""
args = []
options = []
i = 1
while (i < len(argv)):
if argv[i].strip()[0] == ... | 73b725a2215c845c97e0839f9f8b5f6768671798 | 448,728 |
def two_level_minus_r_over_t(g1d, gprime, Delta1):
"""
Minus the reflection coefficient of a two-level atom divided
by the transmission coefficient. The transfer matrix for the
two-level atoms will be written in terms of this ratio.
"""
#Assume real Omega
return g1d/(gprime-2j*Delta1) | 27632dd9e2b048384624afd3dee05f2e1414841d | 356,726 |
def formatTime(time):
"""Convert a datetime object to a string in the format expected
by the AppAssure API.
"""
return time.isoformat()[:-7] | 47defe4d47b37bdf72442ff17e097bf05cb48f29 | 521,260 |
def adjust_timescales_from_daily(ds, tstep):
"""Adjust continuous growth rate parameters from daily scale to the scale of a
single timestep in the dynamic model.
Parameters
----------
ds : :class:`xarray.Dataset`
Dataset containing coords or variables corresponding to rate parameters, ... | 802b472138be70934ff3e37af367d224970b5517 | 69,597 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.