content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_2_digit_sector_ranges(fba_df):
"""
BLS publishes activity ranges of '31-33', 44-45', '48-49... drop these ranges.
The individual 2 digit naics are summed later.
:param fba_df: df, BLS QCEW in FBA format
:return: df, no sector ranges
"""
df = fba_df[~fba_df['ActivityProducedBy'].s... | 02b559fc491b84c7af983307aa512ae93c3ad740 | 622,807 |
def extend_box(bbox, image_size, extend_ratio):
"""Zoom the input bbox
Args:
bbox: Input bbox
image_size: Input image original size
extend_ratio: Zoom ratio
Returns:
a box extand from input bbox
"""
x_x = (bbox[2] - bbox[0]) * extend_ratio
y_y = (bbox[3] - bbox[1]) * extend_ratio
... | a976f5c5b73af83b39a559af8feb55ed45e104d6 | 622,809 |
def rt_to_r(rt):
"""Convert RT matrix to R, removing T."""
result = []
for i in range(3):
for j in range(3):
result.append(rt[4 * i + j])
return result | 22e31d9e20948480c91d4b8cf4df6ba44b2feffa | 622,814 |
def _preprocess_transcript(phrase, use_phonemes, word_phoneme_dict):
"""
transform the input phrase. if use_phonemes is true, the words in phrase
are transformed into phoneme labels specified in word_phoneme_dict
Arguments:
phrase (list): list of words
use_phonemes (b... | f65a168069aa045782cb243718a6747cebdfbaef | 622,815 |
def upd_flag_g_smaller_g_min(flag, g, g_min):
"""
Update the flag to 'o' for small RDF.
Take a flag list, copy it, and set the flag to 'o'utside if g is smaller
g_min.
"""
flag_new = flag.copy()
for i, gg in enumerate(g):
if gg < g_min:
flag_new[i] = 'o'
return flag... | 77719e2df05809ce13c00c57e635cdf04fed37eb | 622,816 |
def format_hex(num):
"""Format an integer as a hex number"""
return "0x%x" % num | 3aebdad54c34e467ab6e07dd707bc60e96db9267 | 622,817 |
def threshold_pixel(image, center, x, y):
"""Calculate if Pixel(x, y) intensity is greater than center intensity of neighborhood.
:param image: Input image to pull from
:type: numpy.ndarray
:param center: Value of center pixel in 3x3 neighborhood
:type: int
... | 53dcc8ab2faabfa199992496e906164c47ca3853 | 622,818 |
def readSeq(inputfile):
"""Reads the DNA sequence and returns as string. Removes all the special characters."""
# opne data
with open(inputfile, "r") as seqfile:
# read data
seq = seqfile.read()
# remove special characters \n and \t
seq = seq.replace("\n", "")
s... | f0f76c468c671fd4d16524ef7f1a75ce5c6d7b44 | 622,819 |
def textToBool(text):
"""
Converts a text to a boolean.
"""
true_values = ['True', 'true', 't', 'T', '1']
if text in true_values:
return True
return False | 5a5b758090fb0af0a81c88d289183072b28d8bc4 | 622,820 |
def mandatory_keys_check(list_mandatory, list_dict_keys):
"""
Check if the payload json file have the mandatory keys
:param list_mandatory: list
:param list_dict_keys: list
:return True or False
"""
check = all(item in list_dict_keys for item in list_mandatory)
return check | e56c8e55c0ea7cccb64818ddf82f19d247081907 | 622,821 |
def calculate_test_code_to_production_code_ratio(production_code_metrics, test_code_metrics):
"""Calculate the ratio between the test code and the production code."""
lines_of_code = production_code_metrics["SUM"]["code"]
lines_of_test_code = test_code_metrics["SUM"]["code"]
return float(lines_of_test... | 8137d89842e9624521c48d83ec313b55d7333a4b | 622,823 |
def otherPicks(df, ct):
""" Returns a list of the top ranked non-QB's currently available.
df : DataFrame - dataframe to parse for player data. Should only contain 1
position classification
ct : int - number of QB entries to return.
"""
df = df.iloc[1:]
if int(ct) > len(df):
entrie... | 1201be1900dca581208192043533e0451ddd32ce | 622,824 |
import time
def retry(function, timeout=10, delay=.001, max_delay=1):
"""Call function until it returns a true value or timeout expires.
Double the delay for each retry up to max_delay.
Returns what function returns if true, None if timeout expires."""
deadline = time.time() + timeout
ret = None
... | 86a2972bff80755fc681e33cd9ddd2be4915a9f5 | 622,827 |
import json
def verify_json(filename):
""" Checks that a JSON file is valid JSON """
try:
with open(filename) as jsonfile:
json.loads(jsonfile.read())
return True
except ValueError:
return False | ba3a0bce0acbb321b7f7071d008f2b92cbc56875 | 622,828 |
def flatten(m, im_shape):
"""Flatten matrix in shape of (batches, channels, rows, cols)
to (batches, -1).
This function has no side effect, that is, it doesn't modify
argument "m" directly.
Arguments
---------
m : np.array
4D matrix in shape of (batches, channels, rows, cols).
... | dbd77f5bf683f276c478859c697d70b408fdefe4 | 622,833 |
def _map_step_size(map_size: int, lod: int) -> int:
"""Return the step size in the tile grid for the given map.
Args:
map_size (int): The base map size in map units
lod (int): The LOD level for which to calculate step size
Returns:
int: The coordinate distance between two tiles in ... | f746383ebbd54a46f9c06e74d02f248d99733255 | 622,834 |
import json
def fetch(filepath):
"""Fetch content of the given file into memory."""
with open(filepath, 'r') as infile:
return json.load(infile) | 7b0b09ae781c807de2bbaf1c08b1b0608c31762a | 622,837 |
def find_duplicate_schedule_items(all_items):
"""Find talks / pages assigned to mulitple schedule items"""
duplicates = []
seen_talks = {}
for item in all_items:
if item.talk and item.talk in seen_talks:
duplicates.append(item)
if seen_talks[item.talk] not in duplicates:
... | a4019dc471a072b536d6f39c47aed06ce3650556 | 622,842 |
import pkgutil
def avail_approaches(pkg):
"""Create list of available modules.
Parameters
----------
pkg : module
module to inspect
Returns
---------
method : list
A list of available submodules
"""
methods = [modname for importer, modname, ispkg in
... | 5b9245b3a96f4de2a4e609abfa9d8b8026074640 | 622,843 |
def user_info_query(user_id: str) -> dict:
"""
Build User information query.
:param user_id: User id
:return: Query
"""
return {
"id": 3,
"operationName": "ProfileGet",
"query": "query ProfileGet($user_id: ID!) {userprofile {get(user_id: $user_id) {... on UserProfile {id user {"
"id... | 12569baac48c52f5c5bddabd42be35a32e1d2021 | 622,845 |
def to_float(val):
"""Convert string to float, but also handles None and 'null'."""
if val is None:
return None
if str(val) == "null":
return None
return float(val) | 3a4fe68fa215b414a36e009d56aeb16c7a38573a | 622,846 |
import itertools
def flatten(list_of_lists):
"""Flatten a list-of-lists into a single list."""
return list(itertools.chain.from_iterable(list_of_lists)) | f572a09d0dbf81f95f27be3475e611ee0c164a60 | 622,847 |
def train_batch(sess, model, batch_data):
"""
Given a Tensorflow session, train the provided model on a single batch.
Args:
sess: a Tensorflow session
model: an Attalos model
batch_data: a batch generated by model.to_batches
Returns:
Training loss for this batch.
""... | 4d4248718307189a83d7d94f4580ddea5f0833a7 | 622,855 |
import torch
def iou(occ1, occ2, weights=None, average=True):
"""Compute the intersection over union (IoU) for two sets of occupancy
values.
Arguments:
----------
occ1: Tensor of size BxN containing the first set of occupancy values
occ2: Tensor of size BxN containing the first set of... | 8e01e270110a4c7e78fd8f2efa4ffff16565511c | 622,857 |
def hasIntersectionCost(criterion, frRow, exRow):
"""Returns 1 if the two do not share an answer on the specified question, else 0"""
frQ = criterion['frQ']
exQ = criterion['exQ']
if 'singleFr' in criterion and criterion['singleFr']:
frSet = set([frRow[frQ]])
else:
frSet = set(frRow[... | 35fd3a5673a99fcf3c01543f6620695b196ebaff | 622,858 |
def unscale_coordinates(point, M):
"""
Unscale coordinates by M
:param point: Point
:param M: Scaling factor
:return: Unscaled points
"""
return point * M | b528625c7a7d1f9ef135609d1d22fd7b2faeb756 | 622,859 |
def update(pos, dims, orig_dims):
""" Finds neg number in dims and restores it to the value in
original-dims and subtracts one from the number after it
e.g (0 -1 0) (0 1 0)-> (0 1 -1) """
ret_dim = []
for i, dim in enumerate(dims):
if pos == i:
ret_dim.insert(i, orig_dims[i])
... | 1c6c1618890d6c73fcaee28053cec5b946309a44 | 622,861 |
def generate_booty_pts(criteria_left, criteria_top, item_width, item_height,
margin_width, margin_height):
"""
ScreenShot#booty_pts() が返すべき座標リストを生成する。
全戦利品画像が等間隔に並んでいることを仮定している。
criteria_left ... 左上にある戦利品の left 座標
criteria_top ... 左上にある戦利品の top 座標
item... | 08ea58386df117bd7bafd0dcf2c9bfe9cd6e245b | 622,862 |
def select_keys(records, keys):
"""Filter the records extracting only the selected fields.
Args:
records (list(dict)): the list of dicts to be filtered.
keys (list(str)): the keys to select from the records.
Returns:
list(dict): the list of records containing only the specified key... | b5a0b12d82ddb5f7d508e8b6ff7bf5d146d68183 | 622,864 |
def has_merge_task(job):
""" Check if user has specified a mergeTask on the task factory
:param job_obj: The JSON job entity loaded from a template.:
:return: true if merge task present
"""
if job.task_factory.type in ['parametricSweep', 'taskPerFile'] and job.task_factory.merge_task:
return... | 70252553aab41c80f868c409fd0cab5bea01141e | 622,866 |
def split_args_for_flags(args):
"""Returns `split_args, other_args` for `args`.
Split occurs using the last occurrence of `--` in `args`.
If `arg` does not contain `--` returns `args, []`.
"""
for i in range(len(args) - 1, -1, -1):
if args[i] == "--":
return args[i + 1 :], args... | d3aa598d518d598dbfb5df0cbe4000cb0841019e | 622,868 |
def packed_to_index(ix):
"""Convert 0-63 index to 0x88 index"""
return ix + (ix & ~7) | b4b2db1f30494fd6573569f4ce0218c848a46371 | 622,873 |
import csv
def load_aitlas_format_dataset(file_path):
"""Reads the images from a CSV. Format: (image_path, class_name)"""
data = []
with open(file_path, "r") as f:
csv_reader = csv.reader(f)
for index, row in enumerate(csv_reader):
path = row[0]
item = (path, row[1... | b36b9b213c88e6cd66ee88d0f3b5a76e113c320c | 622,878 |
import math
def euclidian_distance(point1, point2):
"""
Returns the euclidian distance of the 2 given points.
:param point1: tuple (x, y)
:param point2: tuple (x, y)
:return: float
"""
return math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2)) | 273c2d61d3136fec952443842c94cdb25918b6a4 | 622,879 |
import base64
import hashlib
def stable_filename(value: str):
"""Generate a stable filename by Base32 encoding the sha256 of a string"""
return str(
base64.b32encode(hashlib.sha256(value.encode("utf-8")).digest()), "utf-8"
).replace("====", "") | 812d8f74eb84074546313c67881f147001680fc6 | 622,883 |
import csv # import a library
def parse_csv_file(filename):
"""
Read the contents of a .csv file and put them into a useful data structure:
ddict = {
"category1": { "location1": [entry1, entry2], "location2": [entry3] },
"category2": { "location1": []}
}
Parameters
---------... | 260f53cd2daeacdbd13d7111c3b85c6589534830 | 622,889 |
def MOSQ_MSB(A):
"""get most significant byte."""
return (( A & 0xFF00) >> 8) | dfae93ca110771e8c9959e343401549ebdf25c3a | 622,891 |
def is_payload_in_json(content_type):
"""
Verify the content_type.
If "Content-Type" is NOT specified pass the payload to the "json" argument - return True.
If "Content-Type" is specified:
- if the value is "application/json" pass the payload to the "json" argument - return True.
- if t... | ca0871017bff8cc280992471a7b41403dfe5dd4f | 622,892 |
import string
import random
def get_random_string(length):
""" Generates a random string of upper & lower case letters. """
letters = string.ascii_letters
rand_string = ''.join(random.choice(letters) for i in range(length))
return rand_string | e9d0d84cdd6104c412497f44334bebfdf49cb4ee | 622,901 |
import requests
def fetch_json_package(url, host, referer, encoding):
"""
JSON抓包函数
:param url: AJAX API地址
:param host: 目标服务器
:param referer: header的引用页
:param encoding: 编码
:return: 字典格式的JSON数据包
"""
kv = {'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ... | c8d21f955fb4a92bfdb466c72bb0dccf27090c27 | 622,902 |
from typing import Iterable
from typing import Tuple
from typing import Optional
def fromCode(
desc: str, code_list: Iterable[Tuple[str, str]]
) -> Optional[Tuple[str, str]]:
"""
Returns the matched element by code in the give code list. None otherwise.
"""
res = [item for item in code_list if ite... | ada3b397e174161744bf6a3767140a47a23f8534 | 622,904 |
def srm_to_lovibond(srm: float) -> float:
"""
Convert from Degrees Lovibond color system to
Standard Reference Method (SRM) color system.
"""
return (srm + 0.76) / 1.3546 | 526f23dc826676a27bab125b659a72af7cbe2d05 | 622,907 |
def add_to_fw_spec(original_wf, metadata):
"""
Add metadata to fireworks to make them easy for querying.
Arags:
original_wf (Workflow)
metadata (dict): metadata to be added to "spec"
Returns:
modified workflows
"""
for fwork in original_wf.fws:
for key, value in... | 8cdeffc59fe285cdc0cefd525e07e1a76182bfbe | 622,909 |
def construct_authorperm(*args):
""" Create a post identifier from comment/post object or arguments.
Examples:
.. code-block:: python
>>> from beem.utils import construct_authorperm
>>> print(construct_authorperm('username', 'permlink'))
@username/permlink
... | ffca295bf10e8cd28bbce453d16d68d3d24cfb51 | 622,912 |
def friendly_boolean(boolean):
"""
Returns 'Yes' if a boolean is equal to True, else 'No'
"""
if boolean is True or str(boolean).lower() == "true":
return "Yes"
else:
return "No" | 6505885bb2dbac90b4674865d6dc339e4d021c00 | 622,913 |
def visiblename(name):
"""
Checks whether a given name should be documented/displayed by
ignoring builtin ones.
"""
return not (name.startswith('__') and name.endswith('__')) | 5390791cac22b24b8e6ac9887b828b1df51b145f | 622,919 |
def is_redirect(endpoint):
"""
Endpoint is a redirect if it is a redirect to an external site
"""
return endpoint.redirect_eventually_to_external | b33e83568eae3053421a03f1ef677094ed8f1e17 | 622,921 |
def msg_err_missing_children(tag, *children):
"""Format message for missing children.
:param tag: tag name
:param children: list of children
:return: message
:rtype: str
"""
return "Missing one or more required children (%s) in xml tag %s" % ('|'.join(children), tag) | b6d4ba9a5b56ca198718c6944b0baa95fedf07e2 | 622,923 |
def adjust_var_name(var_to_check, var_names):
"""
Check if upper or lower case version of name is in namelist and adjust.
Parameters
----------
var_to_check : Str.
var_names : List of Str.
Returns
-------
var_to_check : Str.
"""
if var_to_check not in var_names:
fo... | 850f3261f6f359cde8243c15b1ea790372d057fb | 622,924 |
import re
def clean_text(text):
"""Clean our tweets using regex. Remove weird characters and links."""
cleanedup = text.lower()
return re.sub("(@[A-Za-z0-9]+)|(#[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", "", cleanedup) | 656a1fd38062905b895e736a2b9e6d7803c3b02a | 622,925 |
import six
def FormatTagSpecifications(resource_type, tags_dict):
"""Format a dict of tags into arguments for 'tag-specifications' parameter.
Args:
resource_type: resource type to be tagged.
tags_dict: Tags to be formatted.
Returns:
A list of tags formatted as arguments for 'tag-specifications' pa... | 9db57935ea724a7334b98a5160f0eb09f6325ded | 622,927 |
from pathlib import Path
import hashlib
def files_identical(path1: Path, path2: Path) -> bool:
"""Compares content of file using md5 checksum"""
with open(path1, 'rb') as f1, open(path2, 'rb') as f2:
f1 = f1.read()
f2 = f2.read()
if hashlib.md5(f1).hexdigest() == hashlib.md5(f2).hexdigest(... | e3352c210e976ae986c02357f52bd8aba8ce1f18 | 622,930 |
def extract_year(paper_id: str) -> int:
""" Tries to extract the publication year from the ArXiv paper id
:param paper_id: original paper id
:type paper_id: str
:return: year, 0 if no year was found.
:rtype: int
"""
try:
year = 2000 + int(paper_id[:2])
except BaseException:
... | 507874e3dd77f3bced48e6f87b6c9927790b9592 | 622,933 |
import json
def jsonToText(jsonObject, indent='\t'):
"""
Return a JSON object as text
indent: The indent argument to json.dumps. Defaults to '\t' for readability.
Set to None for default json.dumps behavior.
"""
return json.dumps(jsonObject, indent=indent) | 57f905bfc029db1b9d8e54862c3204be664e174d | 622,934 |
import math
def prime_check(number: int) -> bool:
"""Checks to see if a number is a prime in O(sqrt(n)).
A number is prime if it has exactly two factors: 1 and itself.
>>> prime_check(0)
False
>>> prime_check(1)
False
>>> prime_check(2)
True
>>> prime_check(3)
True
>>> pr... | 6e67b379262437f5eb04473c9259d98997566a3e | 622,937 |
def _stft_frames_to_samples(frames, size, shift):
"""
Calculates samples in time domain from STFT frames
:param frames: Number of STFT frames.
:param size: FFT size.
:param shift: Hop in samples.
:return: Number of samples in time domain.
"""
return frames * shift + size - shift | 35acf0d1a1563ceb7af6854162306108676b7a8f | 622,940 |
import hashlib
def get_document_uid(title, body):
"""Generates a nearly unique ID for a document.
Uses the SHA1 hash. Deterministically produces the same result for a given
input, and almost never collides.
Args:
title (bytes): document title
body (bytes): document body text
Returns:
uid (int... | 16f70ab3e6be999708ddfdc341b267bb4f2ee072 | 622,942 |
import torch
def macro_f1(logits, targets, th=0.5):
"""
pytorch implementation
:param logits: Tensor of shape (B, num_class)
:param targets: Tensor of shape (B, num_class)
:param th: Float threshold
:return: Float
"""
preds = (logits.sigmoid() > th).float()
targets = targets.float(... | 8c18d3ccd4f1dfb3471c12109da4ba47d58c655a | 622,949 |
def get_history_slice(
frame_index: int, history_num_states: int, history_step_size: int, include_current_state: bool = False
) -> slice:
"""Given a frame index and history settings returns a slice that returns the given data in the right order.
Note that this history returned starts with the most "rece... | 185d472bd2b92e77a016473fb1afdc99c4534955 | 622,952 |
from typing import Optional
import re
def sub_clyde(username: Optional[str]) -> Optional[str]:
"""
Replace "e"/"E" in any "clyde" in `username` with a Cyrillic "е"/"E" and return the new string.
Discord disallows "clyde" anywhere in the username for webhooks. It will return a 400.
Return None only if... | a65bad8d9b0b2bd3472491aec9c856b35c548633 | 622,953 |
def subst_plural(wikitext):
"""
Substitutes {{PLURAL}} in wikitext
@param wikitext: Wikitext to process
@type wikitext: str
@rtype: str
"""
return wikitext.replace('{{PLURAL:', '{{subst:PLURAL:') | 87d545266d8cda4ad05cb2b664d044605c3ec671 | 622,955 |
from typing import Any
def is_string(obj: Any) -> bool:
"""Check whether an object is a string."""
return isinstance(obj, str) | 6ca07a3d0c695fe04308c5565bce3cc28accd0b8 | 622,958 |
def convert_to_list(obj):
""" receives an object and if type tuple or list, return list. Else
return a list containing the one object
"""
if type(obj) is None: return [] # None implies empty list...
if type(obj) is list: return obj
if type(obj) is tuple:
return [x for x in obj]
... | aa78ea08f06ffab91feead5898a4433807966c02 | 622,964 |
def b_if_a_is_none(a, b):
""" Returns 'b' if 'a' is None, otherwise returns 'a' """
if a is None:
return b
else:
return a | 6417466e85e1044aa0c2b3b7dab8ca1e44e570f5 | 622,965 |
def compile_word(word):
"""Compile a word of uppercase letters as numeric digits.
E.g., compile_word('YOU') => '(1 * U + 10 * O + 100 * Y)'
Non-uppercase words unchanged; compile_word('+') => '+'"""
if word.isupper():
terms = [('%s*%s' % (10 ** i, d))
for (i, d) in enumerate(word[::-1])]
return '(' + '+'.jo... | c4db5f578dcfd72ca1ba2ffa5a7c6550485eac98 | 622,976 |
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a
# single token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a ga... | aa2ce42d893a7273184047ed0aff3c0d8f9bd189 | 622,979 |
def partition(arr: list, low: int, high: int) -> int:
"""Partition the array
Args:
arr (list): the array to partition
low (int): the left-most index
high (int): the right-most index
Returns:
int: the new pivot location
"""
i = low - 1
pivot = arr[high]
# Sw... | 6963fd4398ac8be7b9a532a5fff4e05e0d356036 | 622,980 |
import re
def __replace_all(repls: dict, input: str) -> str:
""" Replaces from the string **input** all the occurrence of the
keys element of the dictionary **repls** with their relative
value.
:param dict repls: dictionary containing the mapping
between the values to be changed and... | dedfce66d06122d88b9f7ca799480c0d4a0af956 | 622,981 |
def subtract(a,b):
"""Subtract a from b and return value"""
return b - a | df86497456b9040aed2a39a19ef2de004b40286e | 622,983 |
def _splitList(data, n):
"""Split data list to n sized sub lists."""
return [data[i : i + n] for i in range(0, len(data), n)] | 6f976fea84c26269693f1c5d7594c70351a2f1fb | 622,989 |
def str_to_int(value):
"""Converts an input string
into int value, or returns input
if input is already int
Method curated by Anuj Som
Args:
value (int, str): Accepts an int or string to convert to int
Returns:
tuple (int, bool): returns (integer value, True) if conversion suc... | 5cccc5f32c1226048625b459cc505fdd09667bd3 | 622,993 |
from functools import reduce
def uniform_property(section_list, attribute_path):
"""
Define a property that will have a uniform value across a list of sections.
For example, suppose we define a neuron model as a class A, which contains
three compartments: soma, dendrite and axon. Then placing
... | 42fa669248c35eeb6b635bf0e417f6a0c39d726f | 622,995 |
import sqlite3
def get_prof(prof_identifier):
"""
Returns all professors that match the identifier entered in the query
"""
#Fetching professor from DB acc to query
conn = sqlite3.connect('./db.sqlite3')
cursor = conn.cursor()
cursor.execute("SELECT * FROM professor WHERE name LIKE ?;", (f... | d503e2130e75d28680b86c1cd901c7f747839b9a | 622,997 |
import random
def _shuffle_list(a, b, c, d):
"""
shuffle a, b, c, d simultaneously
"""
x = list(zip(a, b, c, d))
random.shuffle(x)
a, b, c, d = zip(*x)
return a, b, c, d | 8e086d1f8e6826984526adef027f303b8cf3874a | 623,000 |
import math
def dist(pos1, pos2):
"""Returns the distance between pos1 and pos2"""
x1, y1 = pos1
x2, y2 = pos2
return math.sqrt(math.pow(x1-x2, 2) + math.pow(y1-y2, 2)) | 3e6c7d68ef5b50ce35cb09cca8332f4bb61ad760 | 623,001 |
def center_axes(ax):
"""
Makes a plot's axes meet at the
center instead of at the bottom left corner
"""
ax.spines["bottom"].set_position("zero")
ax.spines["left"].set_position("zero")
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
return ax | 8115a194fcd4ebc536c79b633ab1ff07e293e5a2 | 623,003 |
from typing import List
from typing import Dict
from typing import Any
def sanitize_pet_field(pets: List[Dict[str, Any]], field: str = "id") -> str:
"""Concatenate pet fields and return them as a string."""
if len(pets) > 1:
return ", ".join(str(pet[field]) for pet in pets)
if len(pets) == 0:
... | 67ffe2d31c3d2705d2a004a5d5b87d9830ab2633 | 623,009 |
def _get_name(manifest):
"""Returns the name from the manifest metadata
Args:
manifest (dict): K8s manifests
Returns:
string: Name of the Kubernetes object, or None
"""
try:
name = manifest["metadata"]["name"].lower()
kind = manifest["kind"].lower()
return f... | 7c00703341f863cfb71f6e82f42f9c87dcda5deb | 623,016 |
import re
def insensitize(string):
"""Change upper and lowercase letters to be case insensitive in
the provided string. e.g., 'a' becomes '[Aa]', 'B' becomes
'[bB]', etc. Use for building regexes."""
def to_ins(match):
char = match.group(1)
return '[%s%s]' % (char.lower(), char... | 472b997e0461ea9b05ccc3abe08ee247a203cbd4 | 623,017 |
def create_response(body, headers):
"""Create a simple HTTP response
:type body: str
:type headers: dict[str, str]
:rtype: bytes
"""
final_headers = {
'Connection': 'keep-alive',
'Content-Type': 'text/plain; charset=utf-8',
'Content-Encoding': 'UTF-8'
}
final_he... | 37bbeabb7d4db4b9e9f27799f070d52b24e5ef0c | 623,019 |
import hashlib
def make_hash_bytes(data, length=20):
"""
Creates a hash of length *length*.
"""
m = hashlib.sha256()
m.update(data)
res = m.hexdigest()[:length]
return res | 97d49913313d7853075f35fd4ee711d5098b385f | 623,021 |
def fifo_pre_sequencing(dataset, *args, **kwargs):
"""
Generates an initial job sequence based on the first-in-first-out
dispatching strategy. The job sequence will be feed to the model.
"""
sequence = [job for job in dataset.values()]
return sequence | f0f9889e3066ccb370f61d4f222a09d0ccbadf9a | 623,022 |
def lammps_copy_files(job):
"""Check if the submission scripts have been copied over for the job."""
return (
job.isfile("submit.pbs")
and job.isfile("in.minimize")
and job.isfile("in.equilibration")
and job.isfile("in.production-npt")
) | 4d360f905f537069100eef90dd83f7f978782b96 | 623,024 |
def get_maze_centers(maze_path, maze_verts):
"""find the centre of each edge in maze_path and the co-ordinates of the
maze verts - these will be matched to face after the selection is bevelled
input:
maze_path: list of BMEDges that form the links in the maze
output:
link_centers: list of... | db17517d175ac44e03c0a2721263333c3e2ba1fe | 623,026 |
import torch
def make_target(label, label_to_ix):
"""Turn target labels into a numeric vector where each label has a
unique index"""
return torch.LongTensor([label_to_ix[label]]) | 33b8f92868d1de685154cda236de4bbe53a9df70 | 623,030 |
def view_kwargs(check_url):
"""Return a dict of valid kwargs to pass to SecurityView(**view_kwargs)."""
return {
"allow_all": False,
"allowed_referrers": ["lms.hypothes.is"],
"authentication_required": True,
"check_url": check_url,
} | 94fccd0fbc4897e7d4b5daed842211a7c2a7c4ca | 623,033 |
import json
def load_json(path):
"""
Load json file
Args:
path (str): Path to JSON file
Returns:
data (dict): Dictionary form of JSON file
"""
with open(path, "r") as fp:
data = json.load(fp)
return data | 868646749cedcf5e4b375b74de428a85289a8352 | 623,034 |
import random
def introduce_errors(s,
corruption_rate=3e-3,
infill_marker="|?|",
max_infill_len=8):
"""Artificially add spelling errors and infill markers.
This function should be applied to the inputs of a correction model.
The artificial errors ... | 772ee4c54cb9bdca836e685263c3588d9ec0ba3b | 623,035 |
import sympy
def make_commutative(expr, *symbols):
"""Make sure that specified symbols are defined as commutative.
Parameters
----------
expr: sympy.Expr or sympy.Matrix
symbols: sequace of symbols
Set of symbols that are requiered to be commutative. It doesn't matter
of symbol is... | 636511f42cb397595423daaacfef669ec0fa9cae | 623,036 |
def remove_space(a_string, replace_character):
""" Remove all spaces from a string and return a 'spaceless' version of
the original string.
"""
modified_string = a_string.replace(' ', '')
return modified_string | fd7071c3c2eb9647883c2e17df51dd4950e0a88f | 623,042 |
def decode_variable_value(coded, limits):
"""Transform coded values between -1 and +1 into real scale values.
Parameters
----------
coded : float
Coded variable value.
limits : Tuple of 2 floats.
Minimum and maximum real variable values.
Returns
-------
float
Va... | c2704208570a2011c62e34ca64c38f3ed751358d | 623,043 |
def get_session_summary(sessions):
"""
Takes a list of sessions and extract a summary-dictonary.
"""
summary = dict()
summary['all'] = len(sessions)
summary['waiting'] = len([s for s in sessions if s.proc_status == 'initialized'])
summary['running'] = len([s for s in sessions if s.proc_statu... | cdaf2c25f9cdca9578fe2ef3413db0869645b36d | 623,044 |
import math
def round_32(x, base=32):
"""Round x to base. Default 32."""
if x == 0:
return 0
else:
return int(math.ceil(float(x) / base)) - 1 | 57c4230f193a528b1fcf15d94cc157ba5f1168b1 | 623,046 |
def isolate_opening(df, sweepnum, window):
"""
This function will isolate a window in a time series.
Arguments
-------------------
df: dataframe
A pandas dataframe with columns p, ti, tp, and i.
sweepnum: int
The
window: iterable
an iterable with the start and end c... | b75971f000972c123a7575f60a66d0361aa61ed6 | 623,048 |
import math
def lr_func_cosine(base_lr, cur_epoch, num_optimizer_epochs):
"""
Retrieve the learning rate of the current step using the cosine learning
rate schedule.
"""
return (
base_lr
* (math.cos(math.pi * cur_epoch / num_optimizer_epochs) + 1.0)
* 0.5
) | 1f14ee24a41922aa48452bdc19f1cec6f6618ebc | 623,053 |
import re
def parse(data: list) -> list:
# Python Notation: https://www.python.org/dev/peps/pep-3107/
"""
Prase each line of the data
Return a nested list, such as [[id1, id2, id2,...],...]
"""
parsed_data = []
for line in data:
# remove \n at the end of each line
line = re... | 332d24644fb9c174c200af7912cb2ee3d6750e93 | 623,055 |
def setVariable(var, lenght):
"""
Creates set of values defined in 'var' of lenght 'lenght' by doing cylcing (modulo operation)
Example
var = [1, 2, 3], lenght=5, return [1, 2, 3, 1, 2]
"""
nvar = []
l = len(var)
for i in range(lenght):
nvar.append(var[i % l])
return nva... | f38f467753f3862cdae7e9fe1bc918e2e6328bc0 | 623,056 |
def in_group(user, group_name):
""" Return if a user is in a group called group_name """
try:
return user.groups.filter(name=group_name).exists()
except:
return False | df7b49cffcc79d8c0455b25cef2a61a7eccbfd48 | 623,059 |
import re
def expand_ios_ifname(ifname: str) -> str:
"""Get expanded interface name for IOSXR/XE given its short form
:param ifname: str, short form of IOSXR interface name
:returns: Expanded version of short form interface name
:rtype: str
"""
ifmap = {'BE': 'Bundle-Ether',
'BV... | 9cd8f6f5dc858b94436cbce60c9eb0e755a2fccf | 623,060 |
def iterable(x):
""" Is x iterable?
>>> iterable([1, 2, 3])
True
>>> iterable('abc')
True
>>> iterable(5)
False
"""
try:
iter(x)
return True
except TypeError:
return False | 09dc43ac5377ea50a5ebd20ac71abbf93add687a | 623,068 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.