content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def fill_zero(df):
"""Fill NaN with zero."""
df = df.fillna(0)
return df | 6d55c249a8c28da1fc8debe7bf47727e67ca1271 | 647,683 |
def form_template_to_dict(formtemplate):
"""
Initializes a dictionary of form data from the given list-of-dictionaries
form template, as formatted above.
Args:
formtemplate (list of dicts): Tempate for the form to be initialized.
Returns:
formdata (dict): Dictionary of initalized f... | bca5d6cbec70520df34f2d32afe1db46c1a08888 | 647,684 |
def get_channel(driver, team_name, channel_name):
"""
Retrieve a channel given a team and channel name.
Returns the JSON response from the Mattermost API.
"""
response = driver.channels.get_channel_by_name_and_team_name(
team_name, channel_name)
return response | d928f25d12ba931bb4b795db96412c03f2c559d8 | 647,689 |
def make_ewma_metric(metric, alpha):
""" Format the name of an EWMA metric. """
return f"{metric}-ewma-alpha{alpha}" | 7af137592ef6d2e8d8fd871a0f96b4d9b760d1b2 | 647,691 |
def reporting_date(submission):
""" Format submission reporting date in MM/YYYY format for monthly submissions and Q#/YYYY for quarterly
Args:
submission: submission whose dates to format
Returns:
Formatted dates in the format specified above
"""
if not (submission.... | 5ef78cb819bddfa127a953b7d4a774e921a5124f | 647,692 |
def matrix_inverse(matrix):
"""Invert a 6-item homogenous transform matrix.
A transform matrix [a, b, c, d, e, f] is part of a 3x3 matrix:
a b 0
c d 0
e f 1
Invert it using the formula for the inverse of a 3x3 matrix from
http://mathworld.wolfram.com/MatrixInverse.html
"""... | e2a45f3ca1e082c2192e98b7e2f8344e803de703 | 647,695 |
def build_code(codes_dict):
"""
Builds a code based on a codes dictionary
:param codes_dict: A dictionary with the code and whether it's flagged or not.
:return: The full code
"""
code = 0x00000000
for value in codes_dict.values():
if value[0]:
code += value[1]
retu... | ddbfd409a2d2b2ccae445c7863ac1fef0e566e43 | 647,698 |
def count_ints(cxs):
"""
Given cxs, a list of [(name, set([id1,id2...])), ...], return the number of
possible positive pairwise interactions implied.
"""
def count_pairs(items):
n = len(items)
return int(n*(n-1)/2)
return sum([count_pairs(c[1]) for c in cxs]) | b6a8a02f73c6bed8ca6884baced2072f5fbb6ffc | 647,699 |
def intersection(a, b):
"""
Returns the intersection of sets a and b.
In plain english:
Returns all the items that are in both a and b.
"""
return a.intersection(b) | 0e3496306f103ccabb6f142203ea11942cdfc3d8 | 647,700 |
def options_as_dictionary(meta):
"""
Transforms a list of tuples to a dictionary
Args:
meta (list): A list ot option tuples
Retuns:
dict: A dictionary of options key - values
"""
module_config = {}
for seltuple in meta:
module_config.update({seltuple[0]: seltuple[1]})... | fc82aaca0bebfd22d4a17c6dd6e92f8b30d35e3d | 647,705 |
def del_char_val(inline, char):
"""
Delete all chars matching the given parameter.
Args:
inline(str): Input string.
char(char): A character value which has to be deleted.
"""
return inline.replace(char, '') | 19aac570b0ddb5507c383cf2400ea906fe0d6317 | 647,706 |
def get_subregion(row):
"""
Parse subregion and month names from SUBREGION row.
"""
cell_text = [cell.text_content().strip() for cell in row]
return cell_text[0], cell_text[3:] | c73f9b012c556a080a989284bcf6ccbc4bd054af | 647,708 |
def is_str_or_list_str(s):
"""
Return boolean whether `s` is a string or list of strings.
"""
return isinstance(s, str) or \
(isinstance(s, list) and all(isinstance(x, str) for x in s)) | b8972eb2c77989acb57886c135e5753180025747 | 647,709 |
def _namespaceTag(xmlns, tagName):
"""Preface an XML tag name with the provided namespace"""
return ''.join(["{", xmlns, "}", tagName]) | 0783f95f4e2a77771fd163835b3be706a375b2f1 | 647,710 |
def format_card(note: str) -> str:
"""Formats a single org-mode note as an HTML card."""
lines = note.split('\n')
if lines[0].startswith('* '):
card_front = '<br />{}<br />'.format(lines[0][2:])
else:
print('Received an incorrectly formatted note: {}'.format(note))
return ''
... | b05c6d9e2419f3aa7c78811faf7c4ebf171d3073 | 647,711 |
import requests
def get_files_from_pr(pr_num):
"""Return a list of changed files from a GitHub Pull Request
Arguments:
pr_num {str} -- Pull Request number to get modified files from
Returns:
{list} -- List of modified filenames
"""
files = []
pr_url = f"https://api.github.com... | 6b31ee4dd71e5d472d3ded5ae237d6884d27883d | 647,712 |
def is_right(gaze):
"""Returns true if the user is looking to the right"""
if gaze.pupils_located:
return gaze.horizontal_ratio() <= 0.5 | b5adeee8e8be252a9379efc3a5531ce9b6b20aa9 | 647,713 |
def str_to_list(string, delim=',', type='float'):
""" Convert a str (that originated from a list) back
to a list of floats."""
if string[0] in ('[', '(') and string[-1] in (']', ')'):
string = string[1:-1]
if type == 'float':
lst = [float(num) for num in string.split(delim)]
elif ty... | 7edb5ac9382f2bc225bae4937b6406642b9349e3 | 647,714 |
def argsort(seq, key=None):
""" equivalent of numpy's argsort in basic python
Modified after http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python
>>> a = ['a', 'd', 'c']
>>> argsort(a)
[0, 2, 1]
>>> argsort(a, key=lambda x: {'a':2,'c':1,'d':0}[x])
[1, 2, 0... | ee35f1190f64bb7a9e8cdce12c132eb762897164 | 647,715 |
from typing import Dict
from typing import Any
def get_dict_value_recursively(dct: Dict, key: str) -> Any:
"""
Nest into the dict given a key like root.container.subcontainer
Args:
dct: Dict to get the value from.
key: Key that can describe several nesting steps at one.
Returns:
... | 1d6bcc6998c3523890845733362f41bc09d1a62c | 647,716 |
def base_agreement(hparams):
"""Adds base hparams for AgreementMultilingualNmt."""
# Encoder agreement.
hparams.add_hparam("enc_agreement_coeff", 0.0001)
hparams.add_hparam("enc_agreement_loss", "cosine")
hparams.add_hparam("enc_agreement_pool", True)
hparams.add_hparam("enc_agreement_enable_step", 100000)
... | 6d3478e0feca9ccc6e8531676a4f6ab2524f9566 | 647,717 |
def Crossing1Files(fileName, ind=None):
"""
Takes a filename of the structure used for the Crossing 1 videos - YYYMMDD_hhmmss-suffix.mkv
Retrieves the datetime of the start of the video
Input:
fileName: Name of the file
ind: Indicator of whether it is the left or right crop of the video... | 9228908b6f95dd0ef2e61e7cb2a2a2c52eb77cb4 | 647,718 |
import inspect
def is_fitted(model):
"""Checks if model object has any attributes ending with an underscore"""
return 0 < len( [k for k,v in inspect.getmembers(model) if k.endswith('_') and not k.startswith('__')] ) | 7a7a7479d1718d0af2c3a01b9c92bf2d714ec9bf | 647,721 |
def permission_to_string(perm):
"""
Transforms a Permission instance
into a string representation.
"""
app_label = perm.content_type.app_label
codename = perm.codename
return '%s.%s' % (app_label, codename) | c65c29734792d2b56a84630a638cac275a263c4e | 647,722 |
def convert_language_code_to_iso639_2(lang_code):
"""
Translate OpenSubtitle language code to its iso-639-2 equivalent.
OpenSubtitles seem to support some extensions to iso-639-2, for instance
"pob" means "brazilian portuguese".
See http://www.opensubtitles.org/addons/export_languages.php.
:p... | dfd7ca6139c7c833e44e63c117638ddcf773800f | 647,726 |
import re
def _except(txt, pattern):
"""
Show only text that does not match a pattern.
"""
rgx = "^.*({pattern}).*$".format(pattern=pattern)
unmatched = [
line for line in txt.splitlines() if not re.search(rgx, line, re.I)
]
return "\n".join(unmatched) | 537e6631c09040e172f8309d171715d3c0794602 | 647,727 |
def find_largest_anysize_at_xy(grid, x, y):
"""
Finds the largest sizexsize grid with top-left location (x,y).
"""
maxsize = min(300 - x, 300 - y)
record = grid[(x,y)]
record_tuple = (x, y, 1)
prevsize = record
for size in range(2, maxsize + 1):
cand = prevsize
for i in r... | a5d70616f9988db6d0bbbf8612d7c81f37e1e3e0 | 647,730 |
import pytz
def validate_timezone(zone):
"""Return an IETF timezone from the given IETF zone or common abbreviation.
If the length of the zone is 4 or less, it will be upper-cased before being
looked up; otherwise it will be title-cased. This is the expected
case-insensitivity behavior in the majorit... | 41673d0f70ead61b74a186206d198f2278ace0b7 | 647,733 |
def good(seconds,needed_number_of_copies,x_seconds,y_seconds):
"""
This function is a little tricky
We need to make 2 copies as fast as possible. To do this, we need to use the copier that uses the minimum amount of time.
This minimum copier needs to run once to generate an extra copy
Consequentl... | b2e03d87f945c07dee1fc0fb2c39754c1ff7520c | 647,743 |
def xy(x:int, y:int) -> int:
"""Converts coordinates [x,y] in [(0-8),(0-8)] to [0-80] array location
"""
return y*9 + x | a9925c9ff1aead156b7157114638696f95765f79 | 647,744 |
def divide(x, y, use_floor=False):
"""
Divides two number
:param x: dividend
:param y: divisor
:param use_floor: flag to use floor division
:return: division of two numbers
"""
if use_floor:
return x // y
return x / y | dabd0c577daf78e4193e5b04383bf09910b2441e | 647,746 |
import json
def _get_as_str(input_value):
"""
Helper method to serialize.
:param input_value:
:type input_value: str or List of str
:return: serialized string
:rtype: str
"""
result = None
if input_value:
if type(input_value) == str:
result = input_value
... | 1c921ed12e3894ec1477b063220453871c9bfd9d | 647,747 |
def assign_rows_helper(note_fields, table_row):
"""
Builds and returns a String of notes from the fields specified in :param
note_fields and populated with the data for those fields in :param
table_row
:param note_fields: Note fields from profile the user wants included in
the match sent to the... | dce7b8a4343fb07666c92a1fbc6e810886d10808 | 647,752 |
import json
def read_json_file(input_data):
"""Read data source file. File is in json format"""
with open(input_data, "r") as src:
data = json.load(src)
return data | b6ba37796c5cce7605ab346f456b6e14ab9fe6cd | 647,755 |
def get_weight(item):
"""Get sort weight of a given viewlet"""
_, viewlet = item
try:
return int(viewlet.weight)
except (TypeError, AttributeError):
return 0 | 1e60b2731cf69384a4f55a958afff2ecc3577247 | 647,757 |
def nopat(operating_income, tax_rate):
"""
nopat = Net Operating Profit After Tax
"""
return operating_income * (1-(tax_rate/100)) | de002f10b5deebf22e6a53428bbef663df649783 | 647,760 |
def encryptxor(key, message):
"""
Takes two strings, key and message, and returns an encrypted ascii string
"""
message_ord = [ord(char) for char in message]
key_ord = [ord(key[index%len(key)]) for index in range(len(message))]
return "".join([chr(key_ord[i] ^ message_ord[i]) for i in range(len(... | 4aa7da290cf418594148d8d373b34fba04ca35ac | 647,762 |
import torch
def sqrt_PEHE(po: torch.Tensor, hat_te: torch.Tensor) -> torch.Tensor:
"""
Precision in Estimation of Heterogeneous Effect(PyTorch version).
PEHE reflects the ability to capture individual variation in treatment effects.
Args:
po: expected outcome.
hat_te: estimated outcom... | 16d600efde81f5e3a59ee0573e59cbe50b01a8d7 | 647,763 |
def is_unique(digit, cell, grid):
"""
Checks if a given digit is unique across its row, column and subgrid.
Arguments:
digit {number} -- The digit to check for
cell {tuple} -- The (x, y) coordinates of the digit on the grid
grid {number matrix} -- The matrix to check the digit a... | 397d6629ad37129f4c7465c02f84046800adbc61 | 647,767 |
def _calc_bin_size(n_bins, t_start, t_stop):
"""
Calculates the stop point from given parameters.
Calculates the size of bins `bin_size` from the three parameters
`n_bins`, `t_start` and `t_stop`.
Parameters
----------
n_bins : int
Number of bins
t_start : pq.Quantity
S... | 2aed891ff22fbae567b12b47ee430f5b1127230d | 647,768 |
def getShowId(show, conn):
"""
Return the show id given its name. (Database query)
:param show:
:param conn:
:return: id_show (integer)
"""
cur = conn.cursor()
cur.execute("SELECT id_show FROM show WHERE name=?", (show,))
id_show = cur.fetchone()[0]
return id_show | ca2cb90be09d0fa745819c9300d4f45937b6e4d5 | 647,769 |
def _explode_indexes(df, axis_type, drop_original=False):
"""
Performs an operation similar to explode, but uses the index of the cell as the differentiator.
:param df: the input dataframe of body cells
:param axis_type: either ``"row"`` or ``"column"``, determining which axis to be operating on.
:p... | ebfe8621bec25e7204a3596f817443a355eb9fc9 | 647,771 |
import re
def containChinese(content: str) -> bool:
""" 判断内容是否含有中文字符
Arguments:
content {string} -- 要检测的内容
Returns:
{bool} -- 是否包含中文
"""
zh_pattern = re.compile(
u'([\u4E00-\u9FA5]|[\u9FA6-\u9FEF]|[\u3400-\u4DB5]|[\U00020000-\U0002A6D6]|[\U0002A700-\U0002B734]|[\U0002B740... | 08788234fe323f154a1b962f740f1acacbca68b7 | 647,775 |
import re
def _translate(pat):
"""Given a pattern, returns a regexp string for it."""
out = '^'
for c in pat:
if c == '*':
out += '.*'
else:
out += re.escape(c)
out += '$'
return out | ffec38a7b7cbe65b1da0fd67b389ff5d422fc2aa | 647,778 |
def _downsample_simple(arr, n):
"""
Skip n elements of a 1D array.
:param arr: 1D array.
:param n: integer which defines the skips.
:return: Downsampled 1D array.
"""
return arr[::n] | bd531cf5a5771966dfb3edba5136dd69ea2e2849 | 647,779 |
def substitution_costs(c1, c2):
"""defines the costs of substitutions for the alignment"""
if c1[-1] == c2[-1]:
return 2
else:
return -3 | 62df44a6d5afd047a79845043b7e0d3de51fca49 | 647,784 |
def get_extrapolated_flux(flux_ref, freq_ref, spectral_index):
"""
Computes the flux density at 843 MHz extrapolated from a higher/lower flux
density measurement & some assumed spectral index.
input:
------
flux_ref: float
Reference flux density, usually S400 or S1400 [mJy].
freq_re... | 27ab6d5416b3ecd2fcea970e2dacb5460a8185c6 | 647,785 |
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
e... | 0f2ad5aab0cd0e440f711987cf10f9ec59a55ae5 | 647,787 |
def remove_double_blanks(lines):
""" Takes a list of lines and condenses multiple blank lines into a single
blank line.
"""
new_lines = []
prev_line = "" # empty line here will remove leading blank space
for line in lines:
if len(line.strip()) or len(prev_line.strip()):
new_... | a2c18a66f3cf06cdcf7a5f742168fd7b5b51b048 | 647,788 |
def interpolation(x0, y0, x1, y1, x):
"""
Performs interpolation.
Parameters
----------
x0 : float.
The coordinate of the first point on the x axis.
y0 : float.
The coordinate of the first point on the y axis.
x1 : float.
The coordinate of the second point on the x a... | 7e78c5f9cb697c58d6a7ef405cc8e37cff84641d | 647,789 |
def make_component_header(component, header):
"""
Function that extracts information from components
and adds it to the data header. The input header is
expected to come from Data.coords.header by default.
Parameters
----------
component: glue Component
Glue component to extract info... | 8607303a43f7e1fe993b38da95c1d00f876fd9d0 | 647,794 |
def _get_screenshot_data(driver) -> None:
"""
Returns the screenshot as base64 encoded data.
"""
return driver.get_screenshot_as_png() | dda711072bf54ed1a87afec91c242f0099e7e337 | 647,795 |
def to_secs(delta):
"""Convert a :py:class:`datetime.timedelta` to a number of seconds.
(This is basically a backport of
:py:meth:`datetime.timedelta.total_seconds`.)
"""
return (delta.days * 86400.0 +
delta.seconds +
delta.microseconds / 1000000.0) | 1ff9c8b2a857f713d7bda2691b0b2cfe8a1611dc | 647,801 |
def fst(l):
"""Returns the first item in any list
Parameters
---------
l : list
the list we want to extract the first item from
Returns
-------
first item in list
"""
if isinstance(l, list):
return fst(l[0])
else:
return l | 9b46e31fca7e5c18cf999ed071fa25a261bd3dc4 | 647,804 |
def get_max_profit(stock_prices):
"""
Time Complexity: O(n)
Space Complexity: O(1)
n: number of stocks (length of the list)
"""
if len(stock_prices) < 2:
raise ValueError('Getting a profit requires at least 2 prices')
min_price = stock_prices[0]
max_profit = stock_prices[1] - s... | a636037d9ba3d82fc7e262e3ef84ce29d6a034e8 | 647,806 |
def is_builtin_type(tp):
"""Checks if the given type is a builtin one.
"""
return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__) | 786a9928b45883df68608a45a0e6efa6d4dfe27e | 647,807 |
def _prepare_hunk(hunk):
"""Drop all information but the username and patch"""
cleanhunk = []
for line in hunk.splitlines():
if line.startswith(b'# User') or not line.startswith(b'#'):
if line.startswith(b'@@'):
line = b'@@\n'
cleanhunk.append(line)
return... | 31a2e482c207b4dade2527d0852b7b99695e0eaa | 647,809 |
def odorant_distances(results, subject_id=None):
"""
Given the test results, returns a dictionary whose keys are odorant pairs
and whose values are psychometric distances between those pairs,
defined as the fraction of discriminations that were incorrect.
This can be limited to one subject indicated... | 9153057ac06ea0c2df8bb34b40bc1af7fd00625a | 647,811 |
def get_fps_number(avg_fps_msg: str) -> float:
"""Decodes FPS number from given "Avg FPS" string output by Peeking Duck
in the format: "... Avg FPS over last n frames: x.xx ..."
Args:
avg_fps_msg (str): Peeking Duck's average FPS message string
Returns:
float: Frames per second number
... | c955e00d1f1235014ed02d9a2907815b2a5e7ad0 | 647,815 |
import re
def get_info_float(lines, rege):
"""Get the infromation form contents based on the regular expression."""
cp = re.compile(rege)
energy = 1000
for line in lines:
match = cp.search(line)
if match:
energy = float(match.group(1))
return energy | 9e23b84312167e1b01ae8e7326e147311db22f3c | 647,820 |
def bbox_transform(bbox):
"""
[analog of SqueezeDet src/utils/util.py:bbox_transform()]
convert a bbox of form [cx, cy, w, h] to [xmin, ymin, xmax, ymax].
Works for numpy array or list of tensors.
"""
cx, cy, w, h = bbox
out_box = [[]]*4
out_box[0] = cx-w/2
out_box[1] = cy-h/2
out_box[2] = cx+w/... | 015ee040b745ccc0a21a3694a8b1d5239a50dd7c | 647,826 |
def boost_node(n, label, next_label):
"""Returns code snippet for a leaf/boost node."""
return "%s: return %s;" % (label, n['score']) | e0cd5d42351d1dc4bea30e812b20f57d8dc82bb5 | 647,828 |
import re
def remove_agritrop_link(s):
"""
Removes the domain name of agritrop
:param s: String to remove
"""
s = re.sub("https://agritrop.cirad.fr/","",s)
return s | cc0d5de9f73a32b8cba2e34c61fa0d8e2107e87a | 647,829 |
def _Dij(A, i, j):
"""Sum of lower-left and upper-right blocks of contingency table."""
# See [2] bottom of page 309
return A[i+1:, :j].sum() + A[:i, j+1:].sum() | b57910ea124940d133e23321b0e970f30183b514 | 647,830 |
def is_active(drone):
"""Check if the drone is in active state."""
return drone["State"]["Status"] == "Active" | dd91eb2d9e8dd23ae1debe9dd7302ed93990b396 | 647,835 |
def get_title(soup):
"""
Get a topic title.
Examples
--------
>>> title_tag = '<title>title</title>'
>>> soup = make_soup(title_tag)
>>> get_title(soup)
'title'
"""
return soup.find('title').text.split('|')[0].strip() | d5ae3581338940f7ac7ddc4949fc294ed16d197e | 647,836 |
def create_indicator_entry(
indicator_type,
value,
pkg_id,
ind_id,
timestamp,
source=None,
score=None,
):
"""Creating a JSON object of given args
Args:
indicator_type: (str) indicator type
value: (str) indicator value
pkg_id: (str)... | d64f00dad16eeb07f46ccd44acd012b3fef8a023 | 647,838 |
def create_document1(args):
""" Creates document 1 -- an html document"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family:sans-serif;margin-left:2em;">
<h1 style="font-family: 'Trebuchet MS', Helvetica, sans-ser... | 9f75267e13440cfbf98b0bdc94bdc86f50ffda92 | 647,841 |
def train_test_split(features, target, split_ts):
"""
Splits all provided TimeSeries instances into train and test sets according to the provided timestamp.
:param features: Feature TimeSeries instances to be split.
:param target: Target TimeSeries instance to be split.
:return: 4-tuple of the form... | f40ccedb24132aa4d03896290185aa5599456e07 | 647,845 |
def get_item(config, section, key, *args):
"""
Return property value.
:param config: Configuration parser instance.
:param section: Section name in configuration with property to look for.
:param key: Name of the key to look for in section.
:param args: Can contains the default value (consi... | eed94329598da7a241e3b7ce1a4b23c05e898d2c | 647,848 |
def ndim(array, dims):
"""Return True IFF CRDS `array` object has number of dimensions `dims`.
>>> array = utils.Struct({"KIND":"IMAGE", "SHAPE" : (2048,2048), "TYPE": "float32"})
>>> ndim(array, 2)
True
>>> ndim(array, 3)
False
"""
return len(array.SHAPE) == dims | 281febc77629240e5993b39e12d8b491ae9e9911 | 647,849 |
import re
def extract_sb_ticket_id(ticket_url):
"""Extracts the supportbee ticket id from url"""
match = re.search(r'\/(\d+)', ticket_url)
return match.group(1) if match else None | 1cc51a6fb4e87c0e0455bc0733b58af85228131d | 647,850 |
import base64
def b64d(s):
"""b64d(s) -> str
Base64 decodes a string
Example:
>>> b64d('dGVzdA==')
'test'
"""
return base64.b64decode(s) | e174460759f0cf0c1ab2b2c6997dc4c351049891 | 647,854 |
import re
def remove_whitespaces_and_hyphens(value):
"""
Returns value without whitespaces or -
"""
if not value:
return value
return re.sub(r'[\s-]+', '', value) | ce83c37d66bd487b335e35e7e6e7a445cc4d1e5e | 647,855 |
def double(x: int) -> int:
"""
Doubles a number.
"""
return 2 * x | bdacf4e2aee5e1d487454ca6bda85c578d5de60b | 647,858 |
import pickle
def load_state(filename):
"""Load the annotation state stored in filename.
"""
with open(filename, 'rb') as input_state_file:
loaded_state = pickle.load(input_state_file)
return loaded_state | ee1fd8d5a703d6b830ea83b0d623bde4b6158039 | 647,863 |
def property_from_topic(mqtt_topic):
"""Extract the RuuviTag's property from the MQTT topic."""
return mqtt_topic.split("/")[3] | 59a1cb0b362c1d8908681c5701cd2b7785381a4d | 647,864 |
def get_image_class_name(self, image_id):
""" Retrieves the image class name given an image id """
return self.image_infos[image_id]['class_name'] | fd2c3c4dcf1cd09779a8f31c3b96bee33738822f | 647,866 |
import re
def shorten_module(mod):
"""
Return a module name that is shorter but still useful, for
being displayed in logs
>>> shorten_module("civicboom/lib/helpers.py")
'lib.helpers'
"""
return re.sub("civicboom/(.*).py", "\\1", mod).replace("/", ".") | 9e5727a1ccb1b79fdc865fc758ab1ba50c25c149 | 647,868 |
from typing import List
from typing import Tuple
def build_sorted_text_output(headline: str, content: List[Tuple[str, str, int]]) -> str:
"""
Takes a headline and a list of items and their respective descriptions,
sorts it and returns a nicely readable output
"""
content.sort()
output: str =... | b8fe12c8b05ed2fd55f0b05cbecb73c39d3d1eef | 647,871 |
def get_rad_weekday(date):
"""
Returns numeric representation of a weekday according to RAD's data load
schedule.
:param date: date to return weekday for
:type value: datetime.date
"""
isoday = date.isoweekday()
if isoday == 7:
# Sunday
return 0
else:
return ... | d6c0bfd8a7dec7c969cdb73bbf4c11457d0b9894 | 647,874 |
def chunk_to_parameter(chunk):
"""
:param chunk: List of numbers.
:return: String of numbers, comma delimited, no spaces.
"""
numbers = ''
for number in chunk:
numbers += '%s,' % number
# Remove last comma.
numbers = numbers[:-1]
return numbers | da794c9a767e3e71b25821f97fce8a473c43959c | 647,881 |
import click
def _validate_repo_name(ctx, param, value):
"""Callback used to check if repository argument was given."""
if "/" not in value:
raise click.BadParameter('Expected format for REPOSITORY is '
'"<org_name>/<project_name>" (e.g "jcfr/sandbox")')
return val... | 4468081bea703c193c8417885a71d30b3fcd6f10 | 647,884 |
from typing import TextIO
def skip_header(reader: TextIO) -> str:
"""Skip the header in reader and return the first real piece of data.
>>> infile = StringIO('Example\\n# Comment\\n# Comment\\nData line\\n')
>>> skip_header(infile)
'Data line\\n'
"""
# Read the descript... | 89617cf0fca71822e4c3c54b2a6a8d7aeb05abfe | 647,887 |
import random
def tr_get_asset_ip(params):
"""
return a random host IP, If params is defined as a network address returns an IP from that subnet
:param str params: Network address of the subnet from which to return a host IP
:return: Host IP
:rtype: str
"""
try:
if params ... | cba106ccf0fc4e174e8b92a035f90030a3dc1363 | 647,888 |
def clean_corpus(df):
"""
Clean corpus of text for all documents.
"""
df.Text = df.Text.replace('\s+', ' ', regex=True) # Remove duplicate spaces
df.Text = df.Text.str.encode('ascii', 'ignore').str.decode('utf-8') # Encode in ascii to remove weird characters such as \uf0a7
#df.Text = df.Text.... | 8eddc7ea5f88a5288320619b60351268964dd5db | 647,891 |
def list_member(i_list1: list, i_list2: list):
"""
Compute the element common among i_list1 and i_list2;
not common among i_list1 and i_list2
:param i_list1: The source list
:param i_list2: The reference list
:return: (Common list, Not Common list)
"""
if len(i_list1) == 0:
... | 9e60d37aa8b5b0e5d0ce53cb35e84c8fa036ccaa | 647,897 |
def get_4x4_translation(x,y,z):
"""return a matrix 4x4 for translation"""
a= [1,0,0,0]
b= [0,1,0,0]
c= [0,0,1,0]
d= [x,y,z,1]
return [a,b,c,d] | 706d25094e18bf573a58c633723e495ee66b171e | 647,898 |
def decorate_token(t, z_):
"""Make selected text boldface in Markdown format"""
dec = "**" if z_ == 1 else ""
return dec + t + dec | 42769c22547de19771ebd9309fcd723c14ef5359 | 647,899 |
import grp
import pwd
def _get_user_groups(user_name):
"""
Get a list of groups for the user ``user_name``.
"""
groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]
gid = pwd.getpwnam(user_name).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
return groups | b971dc2095f61c179d4cce98f2ccadbc1cbdc125 | 647,902 |
from typing import Dict
from typing import Any
def _inverse_dict_lookup(dict: Dict[str, Any], value: Any):
""" Finds the first key in a dictionary with the input value. """
for k, v in dict.items():
if v == value:
return k
return None | 1b78ba4d56f0c3ac011d07c671c2ce715ad6a06d | 647,908 |
import re
def get_words(text, dedupe=True):
"""Get the words from a piece of text.
Args:
text: The text from which words should be extracted.
dedupe: Flag indicating if only unique words should be returned. Defaults to true.
Returns:
Iterable over string words found from the input... | 78bb0ab727c825ce177093c1f04a80a4e881f190 | 647,910 |
from typing import Optional
def create_year(datum: str) -> Optional[int]:
"""Parse a year from the datum field."""
if datum is None or len(datum) < 4 or not datum[:4].isdigit():
return None
jaar = int(datum[:4])
if 1000 < jaar < 2000:
return jaar
return None | fb6d20fc22fc61dfe0d04345cf8e6e3a0e58d3b2 | 647,913 |
import pickle
def load_pickle(filepath: str) -> object:
"""
Loads a pickle file to memory.
:param filepath: Path pointing to file
"""
with open(filepath, 'rb') as handle:
return pickle.load(handle) | 12e7cc7825814b4e9e1d2e15ac87e95e22315004 | 647,914 |
def _TailSet(start_point, listing):
"""Returns set of object name tails.
Tails can be compared between source and dest, past the point at which rsync
was done. For example if test ran rsync gs://bucket1/dir gs://bucket2/dir2,
the tails for listings from bucket1 would start after "dir", while the tails
for l... | d683823020239318e26a5ec19b9b263757cab28f | 647,917 |
def get_colour_set(n_colours, rng):
"""
Generates a (unique) list of randomly generated RGB colours.
# Arguments:
n_colours: the number of colours to generate.
rng: an instance of numpy.random.Generator.
# Returns:
colours: a list of randomly generated colours.
"""
colo... | ff72461744996ced60cc677be56acfbf573f47e7 | 647,918 |
import warnings
def ignore_warnings(method):
"""Decorator for ignoring warnings"""
def _inner(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
result = method(*args, **kwargs)
return result
return _inner | b382775eb913b98245944ac0a2e96b8936944a37 | 647,920 |
import torch
def subsequent_mask(size, device):
"""Mask out subsequent positions (adapted from
http://nlp.seas.harvard.edu/2018/04/03/attention.html)"""
attn_shape = (1, size, size)
subsequent_mask = torch.triu(torch.ones(attn_shape, device=device), diagonal=1)
return subsequent_mask == 0 | d1a8a26476ef9d8f012c9f35947b6a0392f8a2a5 | 647,922 |
def factorial(n):
"""Returns the factorial of a number n > 0.
This is a recursive function.
"""
if n == 0:
return 1
else:
return n * factorial(n-1) | fa2ce021ab09a969522f981f74fb7b0893c58012 | 647,923 |
import string
def is_valid_file_name(str_input):
"""Returns if str is valid file name.
May only contain: ascii_lowercase, ascii_uppercase, digits, dot, dash, underscore
"""
allowed = set(string.ascii_lowercase + string.ascii_uppercase + string.digits + '.-_')
if str_input is not '':
return... | 1f0499245417b7b39283e1be11512c10ac1db367 | 647,925 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.