content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_printer(msg):
"""
returns a printer function, that prints information about a tensor's gradient
Used by register_hook in the backward pass.
:param msg:
:return: printer function
"""
def printer(tensor):
if tensor.nelement == 1:
print("{} {}".format(msg, tensor))
... | 0aefa7449452f791d0c6a15326044a0171c7faf4 | 18,660 |
def remove_protocol(addr):
"""
Removes the first occurrence of the protocol string ('://') from the string `addr`
Parameters
----------
addr : str
The address from which to remove the address prefix.
Returns
-------
str
"""
name = addr.split("://", 1) # maxsplit = 1..... | f59c702be333671da3e9f202581acf6db3082c50 | 18,662 |
def find_duplicates(_list):
"""a more efficient way to return duplicated items
ref: https://www.iditect.com/guide/python/python_howto_find_the_duplicates_in_a_list.html
:arg list _list: a python list
"""
first_seen = set()
first_seen_add = first_seen.add
duplicates = set(i for i in _list if... | ed1ab9020d41b608dd6b8d3ce9e2448a096b1574 | 18,663 |
def first(iterable, default=None, key=None):
"""
Return the first truthy value of an iterable.
Shamelessly stolen from https://github.com/hynek/first
"""
if key is None:
for el in iterable:
if el:
return el
else:
for el in iterable:
if key(... | fd3eeeecf88b0dd29b3f689f61732e6502306016 | 18,664 |
def read_txt_file(file_name: str, encoding: str = "utf-8") -> str:
"""Reads a text file
:param file_name: path
:param encoding: encoding to use
:return: str content
"""
with open(file_name, "r", encoding=encoding) as txt_file:
return txt_file.read() | f97bd162596569b521121bd17da3edfdc04889d8 | 18,666 |
from typing import Dict
def prepare_note_create_output(record: Dict) -> Dict:
"""
Prepares context output for user_details_get command.
:param record: Dict containing note record.
:return: prepared context output Dict.
"""
return {
'Id': record.get('Id', ''),
'WorkInfoType': r... | a0cc6f71dae7527f2c8088d349b79921f163d2d7 | 18,667 |
def query_interval_tree_by_type(interval_tree, time, type):
"""
Returns only items of specified type from interval tree at given time.
"""
all_intervals = interval_tree[time]
selected_intervals = set()
for interval in all_intervals:
if isinstance(interval[-1], type):
selecte... | 68366bfe9413cdecd8b3551b8070d1cc30646358 | 18,668 |
import re
def parse_question_limits(question, for_items=False):
"""
Converts word and character length validators into JSON Schema-compatible maxLength and regex validators.
"""
limits = {}
word_length_validator = next(
iter(filter(None, (
re.match(r'under_(\d+)_words', validat... | 3b9400f27755e5f93de52665d7e8f9d209ad5e30 | 18,672 |
def cm2inch(*tupl, scale=3):
"""
Convert cm to inch and scale it up.
Parameters:
*tupl: *tuple(floats)
Measures in cm to convert and scale.
scale: float
Scale factor. Default: 3
"""
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(scale * i/inch for i ... | d84b3e60ac8a7ae2f46818510d224923dc39c730 | 18,673 |
def get_id_data_abstract_role_mappings(id_data):
"""Get the logical and physical names of the access control roles
defined by a resource group.
:param id_data: - Data extracted from a custom resource's physical id by
get_data_from_custom_physical_resource_id
:returns
A dictionary mappi... | d93acd5988f068ed5a203e811326c33ab5f6b8aa | 18,674 |
def normalizeName(name):
""" Make normalized user name
Prevent impersonating another user with names containing leading,
trailing or multiple whitespace, or using invisible unicode
characters.
Prevent creating user page as sub page, because '/' is not allowed
in user names.
Prevent using ... | 48ce83e2aef5e4bce993edd0e4cba230c2006641 | 18,683 |
def convert_to_int(byte_arr):
"""Converts an array of bytes into an array of integers"""
result = []
for i in byte_arr:
result.append(int.from_bytes(i, byteorder='big'))
#introducem termenul liber
result.insert(0, 1)
# print(result)
return result | 03e7095dcf4d49e78ffa406e49b217e30bef67f4 | 18,684 |
def insertion_sort(lst):
"""
Sorts list using insertion sort
:param lst: list of unsorted elements
:return comp: number of comparisons
"""
comp = 0
for i in range(1, len(lst)):
key = lst[i]
j = i - 1
cur_comp = 0
while j >= 0 and key < lst[j]:
lst[... | 37b48a6f35828dfe88d6e329f93cec44b557136c | 18,685 |
def error_rate(error_count, total):
"""
Calculate the error rate, given the error count and the total number
of words.
Args:
error_count (int): Number of errors.
total (int): Total number of words (of the same type).
Returns:
tuple (int, int, float): The error count, the to... | 92f9f10952f86087edf251ccaf3f1005fdd6cb57 | 18,690 |
def _runCrossValidate(fitter):
"""
Top level function that runs crossvalidation for a fitter.
Used in parallel processing.
Parameters
----------
AbstractFitter
Returns
-------
lmfit.Parameters, score
"""
fitter.fit()
score = fitter.score()
return fitter.parameters, ... | 6dccc89e3ca43d98f417caf0c66d7581fcd77b31 | 18,691 |
def markdown_format(input_data) -> str:
"""
Format input into nice markdown accordingly
Dict -> formatted list of key/value pairs
Everything Else -> Str
Args:
input_data (mixed):
Returns:
str:
"""
if isinstance(input_data, dict):
return "\n".join(["*{}*: {}".f... | d8602b3dce84504fcf6ef0bfaa6cc1b357bb0548 | 18,692 |
import pytz
def dt_to_ms(dt):
"""Converts a datetime to a POSIX timestamp in milliseconds"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=pytz.UTC)
return int(dt.timestamp() * 1000) | aa3050ce15e09b9c1ddeb1edbda8c6e4275f3ce6 | 18,693 |
def strip_data(df):
"""Remove unused columns from the data."""
names = [' dwpf', ' relh', ' drct',
' sknt', ' p01i', ' alti', ' mslp', ' vsby', ' gust', ' skyc1',
' skyc2', ' skyc3', ' skyc4', ' skyl1', ' skyl2', ' skyl3',
' skyl4', ' presentwx', ' metar']
for colname ... | 127c472d0b56c9360d2ac05715f1e614ab735941 | 18,694 |
def get_url(year_of_study, session):
"""
:param year_of_study: 1, 2, 3 or 4.
:param session: Examples: 20199 is fall 2019. 20195 is summer 2019.
:return:
"""
return "https://student.utm.utoronto.ca/timetable/timetable?yos={0}&subjectarea=&session={1}&courseCode=&sname=&delivery=&courseTitle=".... | 371e1ad7b1d0d147ad906fd5f7fedd4d7d1f825d | 18,698 |
def django_user_conversion(obj):
""" Convert a Django user either by returning USERNAME_FIELD or convert
it to str.
"""
if hasattr(obj, "USERNAME_FIELD"):
return getattr(obj, getattr(obj, "USERNAME_FIELD"), None)
else:
return str(obj) | 9e42f35f28799f732840a671ce9c16b67583ae19 | 18,702 |
def add_suffix(fname, suffix):
"""Adds a suffix to a file name."""
name, extension = fname.split(".")
return name + "_" + suffix + "." + extension | 53e8772bd5b974635010974d6373fbf5816ae520 | 18,709 |
def pos_pow(z,k):
"""z^k if k is positive, else 0.0"""
if k>=0:
return z**k
else:
return 0.0 | ba0a46e8711005b9ac0dbd603f600dfaa67fbdd4 | 18,713 |
def getNPoly(object):
"""
Return the number polygons in the object
"""
return len(object[1]) | 01a2808768d34c7ad31285100ee8c5440092a19f | 18,714 |
def sort_user_links(links):
"""Sorts the user's social/contact links.
Args:
links (list): User's links.
Returns:
Sorted list of links.
"""
return sorted(map(tuple, links), key=lambda kv: kv[0].lower()) | 1f9eb06af28def57c019fb026d9149f3f6f367b3 | 18,718 |
def deep_round(A, ndigits=5):
"""
Rounds numbers in a list of lists. Useful for approximate equality testing.
"""
return [[round(val, ndigits) for val in sublst] for sublst in A] | cebfb6b2dbe83bcc7222e0dc1b67ca98e95576c5 | 18,719 |
def nodestrength(mtx, mean=False):
"""
Compute the node strength of a graph.
Parameters
----------
mtx : numpy.ndarray
A matrix depicting a graph.
mean : bool, optional
If True, return the average node strength along the last axis of mtx.
Returns
-------
numpy.ndarr... | 0b8a30a6b1ab2218368c0af0f6bf8036b819d431 | 18,723 |
def file_urls_mutation(dataset_id, snapshot_tag, file_urls):
"""
Return the OpenNeuro mutation to update the file urls of a snapshot filetree
"""
file_update = {
'datasetId': dataset_id,
'tag': snapshot_tag,
'files': file_urls
}
return {
'query': 'mutation ($files... | ffa1ca42f5af7b93cfc6befb517b7909140b5b01 | 18,726 |
def get_marginal_topic_distrib(doc_topic_distrib, doc_lengths):
"""
Return marginal topic distribution p(T) (topic proportions) given the document-topic distribution (theta)
`doc_topic_distrib` and the document lengths `doc_lengths`. The latter can be calculated with `get_doc_lengths()`.
"""
unnorm ... | ebcb87a5ddb5e5e2e3c2446134c6ef2ab8a945fa | 18,729 |
from typing import OrderedDict
def replicate(d: OrderedDict):
"""
convert a dict with (element, count) into a list
with each element replicated count many times
"""
l = []
for element, count in d.items():
l.extend([element]*count)
return l | 276d7ea922c645d689a3ec70247427d031e0fa34 | 18,731 |
def get_count_limited_class(classes, class_name, min=1, max=1):
""" Find a class in an iterator over classes, and constrain its count
Args:
classes (:obj:`iterator`): an iterator over some classes
class_name (:obj:`str`): the desired class' name
min (:obj:`int`): the fewest instances of... | 4512bb22aa2ac1632813bea8f834785b9b7c5c20 | 18,735 |
import requests
def post_splunk(url, token, payload):
"""
Send a post request to Splunk API
"""
headers = {'Authorization': 'Splunk {}'.format(token)}
res = requests.post(url=url, headers=headers, data=payload, verify=False)
res.raise_for_status()
return res.json() | 45310cabaf65004217cd2bcd0196314cb4fbabd7 | 18,737 |
import math
def nu_e(n_n, n_e, T_e):
"""approximate calculation of electron collision frequency from Kelly 89
Parameters
----------
n_n : (float)
neutral density cm-3
n_e : (float)
electron density cm-3
T_e : (float)
electron temperature K
"""
nu_e_n = 5.4 * 10... | 3c73538dd97a4f03d0a98d8fe4427697089234e8 | 18,740 |
import math
def line(p0, p1):
"""
Create line between two points based on Bresenham algorithm
"""
steep = False
x0 = p0[0]
y0 = p0[1]
x1 = p1[0]
y1 = p1[1]
if math.fabs(x0 - x1) < math.fabs(y0 - y1):
x0, y0 = y0, x0
x1, y1 = y1, x1
steep = True
if x0 ... | 3f590e2416280dc67467b6d08bc39b50e84e0717 | 18,741 |
def ltd(balance_df):
"""Checks if the current LTD (Long Term Debt) was reduced since previous year
Explanation of LTD: https://www.investopedia.com/terms/l/longtermdebt.asp
balance_df = Balance Sheet of the specified company
"""
lt_debt_curr = balance_df.iloc[balance_df.index.get_loc("Long Term... | 3a43098da821e96d605f3bf579e0ca8e11d1a66b | 18,752 |
def quick_sort(arr):
"""Sort array of numbers with quicksort."""
if len(arr) == 1:
return arr
if len(arr) > 1:
pivot = arr[0]
left = 1
right = len(arr) - 1
while left <= right:
if arr[left] > pivot and arr[right] < pivot:
arr[left], arr[ri... | 9f40258588967247379d50532dd62ec0588365b1 | 18,753 |
def _include_exclude_list(include, exclude):
"""
create the list of queries that would be checked for include or exclude
"""
keys = []
if include:
for item in include:
keys.append((item, 'included'))
if exclude:
for item in exclude:
keys.append((item, 'exc... | ed968d56d6bb095de118f6526e277a54e1610cc4 | 18,754 |
def fetch_specie(specie_url, fetcher):
"""
Get Data of a specie.
"""
return fetcher(specie_url) | 5882affad01a750d2afb5ca047a9f82872d03c56 | 18,755 |
import pickle
def load_pik(pikFile):
"""Convenience function for simple loading of pickle files
"""
with open(pikFile, 'rb') as fid:
d = pickle.load(fid)
return d | f70f08bbf98fddad7bc1d99dee2049b8525c13e5 | 18,759 |
def classImplements(c, ms):
"""
c is a class, and ms is a set of method names.
Returns True if c implements all the methods in c.
Complains otherwise, and returns False
"""
result = True
for n in ms:
m = getattr(c, n, False)
if not (m and callable(m)):
print(c... | e459e9a50cce501356d5494fb616cfa4df32fff7 | 18,760 |
def datetime_to_grass_datetime_string(dt):
"""Convert a python datetime object into a GRASS datetime string
.. code-block:: python
>>> import grass.temporal as tgis
>>> import dateutil.parser as parser
>>> dt = parser.parse("2011-01-01 10:00:00 +01:30")
>>> tgis.datetime_to_gra... | 47495bb7a26fda2dfc40b1cbdbff045030fecc31 | 18,761 |
def flip_index(i, n):
"""Reorder qubit indices from largest to smallest.
>>> from sympy.physics.quantum.qasm import flip_index
>>> flip_index(0, 2)
1
>>> flip_index(1, 2)
0
"""
return n-i-1 | c6b8f7143bda5cdf80c7994041536b25d142c3cc | 18,763 |
def _splitquery(url):
"""splitquery('/path?query') --> '/path', 'query'."""
path, delim, query = url.rpartition('?')
if delim:
return path, query
return url, None | ea1d04538d90139bc257a439a0d6bf02e6b15b13 | 18,768 |
from typing import List
def position_util(cmd_line: List[str], word_position: int, word_before_cursor: str) -> bool:
"""
Util method for autocompletion conditions. Makes autocomplete work well.
:param cmd_line: the list of command line words
:param word_position: the position of the word we are attem... | 463bb420d7a7cc1aa336b8d664194cc99b5c4dcb | 18,774 |
def get_fmriprep_outlier_volumes_from_confounds(confounds_df):
"""extract which volume numbers are outliers from the fmriprep confounds df.
Returns:
bad_volumes: list
eg [34, 35, 100, 150]
"""
# get the motion columns
motion = confounds_df.filter(regex='motion')
# find any rows w... | b62d833ec2b7f000584354ca6470863acb33682c | 18,777 |
def _priority_connection(priority_route:dict, cost_matrix, mean_routes, std_routes, mean_weight, std_weigth, distance_weight) -> dict:
"""
Give us the priority connections dictionary for each route
Parameters
-----------
priority_route: dict
The dictionary with the priority routes
cost_matrix: dict of dicts
... | b4be98cd4fe07b3592e4fa44a63d38195a7dfd05 | 18,779 |
import jinja2
def fillHTMLTemplate(templateString, params):
"""Invokes the jinja2 methods to fill in the slots in the template."""
templateObject = jinja2.Template(templateString)
htmlContent = templateObject.render(params)
return htmlContent | bba20da7a5411bf8b252fffcdb108516a2d5afa9 | 18,790 |
def check_above_or_below(considering_pt, remaining_pt_1, remaining_pt_2):
"""
This function is used to check if the considering point is above or below
the line connecting two remaining points.\n
1: above\n
-1: below
"""
orthogonal_vector = remaining_pt_2 - remaining_pt_1
line_connecting... | 0da67abc45356260580beec22f37a56bd5f43398 | 18,792 |
from typing import Dict
from typing import Any
def _count_populations_in_params(params: Dict[str, Any], prefix: str) -> int:
"""
Counts the number of electron or ion populations in a ``params`` `dict`.
The number of populations is determined by counting the number of items in
the ``params`` `dict` wi... | 0678e198f6e5562eb26e8d2c68aad14422d0f820 | 18,801 |
def gps_to_utc(gpssec):
"""
Convert GPS seconds to UTC seconds.
Parameters
----------
gpssec: int
Time in GPS seconds.
Returns
-------
Time in UTC seconds.
Notes
-----
The code is ported from Offline.
Examples
--------
>>> gps_to_utc(0) # Jan 6th, 1980
... | 342c479df8d4c864592494e8d50452e9f02c04d5 | 18,804 |
def get_assoc_scheme_parameter(assoc_scheme):
"""
assoc_scheme - 3B, 3C, etc.
Output:
param - Thermopack parameter
"""
if assoc_scheme.upper() == "NONE":
param = "no_assoc"
else:
param = "assoc_scheme_{}".format(assoc_scheme)
return param | b0f7a09d157dcaa466cec2b2a47684a1ee2df80b | 18,806 |
import requests
from bs4 import BeautifulSoup
def get_page_soup(url):
"""
Returns html of a given url
Parameters:
url (string): complete url
Returns:
html: pageSoup
"""
headers = {'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,... | efbdbb92e0b93bf6390541a9608855da266d7682 | 18,808 |
import torch
def clip_boxes_to_image(boxes, size):
"""copy from torchvision.ops.boxes
Clip boxes so that they lie inside an image of size `size`.
Arguments:
boxes (Tensor[N, 4]): (left, top, right, bottom)
size (Tuple(H, W)): size of the image
Returns:
clipped_boxes (Tensor[... | 139e865f8137f1529141546a9d71877599adacd1 | 18,811 |
def extend_schema_field(field):
"""
Decorator for the "field" kind. Can be used with ``SerializerMethodField`` (annotate the actual
method) or with custom ``serializers.Field`` implementations.
If your custom serializer field base class is already the desired type, decoration is not necessary.
To o... | 91f665f927357813f43963ce9c348f8da7a2c5c8 | 18,812 |
def node_region(patched_ast_node):
"""Get the region of a patched ast node"""
return patched_ast_node.region | 870fc43f1b635d5b5eb5e5a4ffa80ab322af168d | 18,818 |
def _extract_target(data, target_col):
"""Removes the target column from a data frame, returns the target
col and a new data frame minus the target."""
target = data[target_col]
train_df = data.copy()
del train_df[target_col]
return target, train_df | 726a76e254c1d6dc120b590d9d7128986ddc9227 | 18,823 |
def score_compressed_state(total, trumps):
"""
Calculate score from compressed state
"""
score = 0
for num_trumps in range(trumps, -1, -1):
score = total + num_trumps * 10
if score <= 31:
break
return score | 0d6652174c2f3f409431c15f38874b8057b94921 | 18,824 |
from typing import List
from typing import Dict
import collections
def merge_series(list_of_metas: List[Dict]) -> Dict:
"""Merge series with the same SeriesUID.
"""
result = collections.defaultdict(list)
for metas in list_of_metas:
result[metas["SeriesInstanceUID"]].append(metas)
retur... | 42b23b504c6e973913f93da2e86f71f8ea9baec2 | 18,833 |
def _rlimit_min(one_val, nother_val):
"""Returns the more stringent rlimit value. -1 means no limit."""
if one_val < 0 or nother_val < 0 :
return max(one_val, nother_val)
else:
return min(one_val, nother_val) | ba286aa6b36a53d691a13b775bbbcfd8722c8b8e | 18,834 |
def _get_fields(line, delimiter=' ', remove_fields=['', '\n']):
"""Gets the fields from a line delimited by delimiter and without entries
in remove_fields
Parameters
----------
line : str
Line to find the fields
delimiter : str
Text separating fields in string
... | adfa2e6a1be18049b7b956bef7a0f3c121120641 | 18,839 |
def dict_alert_msg(form_is_valid, alert_title, alert_msg, alert_type):
"""
Function to call internal alert message to the user with the required
paramaters: form_is_valid[True/False all small letters for json format],
alert_title='string', alert_msg='string',
alert_type='success, error, warning, inf... | f9f82c9b809be2ad1d6d872d6e00610a5ebc3493 | 18,840 |
def check_no_overlap(op_start_times:list, machines_ops_map:dict, processing_time:dict):
"""
Check if the solution violates the no overlap constraint.
Returns True if the constraint is violated.
Keyword arguments:
op_start_times (list): Start times for the operations
machines_ops_... | 90736c066987466adcf641f9999542466c17fc8e | 18,842 |
import requests
def shock_download(url, token):
""" Download data from a Shock node.
Parameters
----------
url : str
URL to Shock node
token : str
Authentication token for Patric web services
Returns
-------
str
Data from Shock node
"""
response = req... | 7a2e9855ca807892cef16af370755eac3644f9f5 | 18,851 |
def create_html_email_href(email: str) -> str:
"""
HTML version of an email address
:param email: the email address
:return: email address for use in an HTML document
"""
return f'<a href="mailto:{email}">{email}</a>' if email else "" | c72bb76f3b1fc3d30571a879d1b8172d8c4e77cd | 18,858 |
def dummyListener(source, intent):
"""Sample intent listener
Intent listeners (see :any:`registerIntentListener`) should follow this function prototype.
The function can handle `intent` and perform appropriate action if desired.
If the function handled the intent, it should return True to mark the intent has hav... | c994b08f5d409debe80fb9f8a29380355a190e12 | 18,860 |
import sqlite3
def isSqlite3DB(filepath):
"""
Returns whether file at filepath is a sqlite3 database.
Args:
filepath (str): The file to check.
Returns:
bool: Whether the database could be opened and queried.
"""
try:
conn = sqlite3.connect(filepath)
conn.execu... | 54a0c42faea75ffa9d2571b78976db9116c81207 | 18,862 |
def get_sea_attribute_cmd(seaname):
"""
Get pvid, pvid_adapter, and virt_adapters from the configured SEA device.
Also get the state of the SEA.
:param seaname: sea device name
:returns: A VIOS command to get the sea adapter's attributes.
"""
return ("ioscli lsdev -dev %(sea)s -attr pvid,pv... | 18224e14e45b73ff716f4282aaff3e06c4584866 | 18,867 |
def zzx_neg(f):
"""Negate a polynomial in Z[x]. """
return [ -coeff for coeff in f ] | c813597dc9540c8d85221352da10db894de4aa4c | 18,877 |
def get_q_values(node):
"""
Return all triples (state, action, q)
Parameters
----------
node : Node
Initial node.
Returns
-------
Recursively transverse the tree, and return all triples (state, action, q)
"""
if node.children == None:
return [[node.state_va... | 8c3015f3b9c44ec7bfaaaf8833b39d167598f2bc | 18,890 |
def change_linewidth(ax, lw=3):
"""change linewidth for each line plot in given axis
Parameters
----------
ax : mpl.axis
axis to change fontsize of
lw : float, optional
[description], by default 3
Returns
-------
ax
mpl.axis
Examples
--------
... | b92294878351b6f251c99f43295a8e8e56995cd1 | 18,893 |
def find_upper_bound(x):
"""
find_upper_bound returns an integer n with n >= len(x), without using the
len() function. The complexity is O(log(len(x)).
"""
n = 1
while True:
try:
v = x[n]
except IndexError:
return n
n *= 2 | 4251791d0e270f29bc9f4d26bbf81c2292ffa50c | 18,896 |
def yes_or_no(question):
"""Asks a yes or no question, and captures input. Blank input is interpreted as Y."""
reply = str(input(question+' (Y/n): ')).capitalize().strip()
if reply == "": #pylint: disable=no-else-return
return True
elif reply[0] == 'Y':
return True
elif reply[0] ==... | f441e39b85dc7407bedce5c120aa9839f0a3064f | 18,897 |
def get_material_nodes_by_type(material, bl_idname):
""" Find material nodes with bl_idname type name """
return (node for node in material.node_tree.nodes if node.bl_idname == bl_idname) | 4406bf09a0d44ecb29e917dc7ff7d78b179cfbf8 | 18,898 |
def matching(tr_synth, tr_seis):
"""
matching zeroes all values of the seismic trace `tr_seis`
outside the limits of the synthetic trace `tr_synth`
Parameters
----------
tr_synth : numpy.array
The synthetic trace
tr_seis : numpy.array
The seismic trace
Returns
----... | 55527b1302fd099e88353ea7c1ee447633a5a494 | 18,904 |
def booleanize_if_possible(sample):
"""Boolean-ize truthy/falsey strings."""
if sample.lower() in ['true', 'yes', 'on', 1]:
sample = True
elif sample.lower() in ['false', 'no', 'off', 0]:
sample = False
return sample | 10ffb3481f15a7548512f01266027977a61a7e13 | 18,912 |
def normalize_feature_for_target_col(in_df, str_norm_target_col, abs_max_num):
"""
normalize designated column
e.g.
normalize col with max "60"
[20, 30, 70, 65, -90]
-> [0.333..., 0.5, 1.0, 1.0, -1.0]
:param in_df : pandas.DataFrame,
:param str_norm_t... | 63eaa8065d6485d6bdacb850d318ed993225204f | 18,913 |
import collections
import operator
def dnsbl_hit_count(log_data):
"""Counts how many hosts were found in each dnsbl."""
y = collections.defaultdict(int)
for v in log_data.values():
for bl in v:
y[bl] += 1
return sorted(y.items(), key=operator.itemgetter(1), reverse=True) | 6a03054b7f50b1cbb27e58e4edc1212bb7cc2abf | 18,915 |
def resize_lane(lane, x_ratio, y_ratio):
"""Resize the coordinate of a lane accroding image resize ratio.
:param lane: the lane need to be resized
:type lane: a list of dicts
:param x_ratio: correspond image resize ratio in x axes.
:type x_ratio: float
:param y_ratio: correspond image resize ra... | 23dacea6ac9820b73fad124433630a991ea14d37 | 18,916 |
def _attrfilter(label, value, expr):
"""
Build an `attrfilter(<label>, <value>, <expr>)` type query expression.
`expr` is a query expression of any supported type.
"""
return "attrfilter({label}, {value}, {expr})".format(
label = label,
value = value,
expr = expr,
) | 38dfc19bf043a9c327665c324f96d7f205ea6416 | 18,922 |
def genererate_principal(primary: str, instance: str, realm: str) -> str:
"""
Generate a Kerberos principal from the three different components.
"""
if instance:
principal = "{}/{}".format(primary, instance)
else:
principal = primary
return "{}@{}".format(principal, realm.upper(... | a39055e2029f044ce50107cb58860465491a5333 | 18,926 |
import re
def check_password_complexity(email, password):
"""
Check that a password meets the minimum complexity requirements,
returning True if the requirements are satisfied, False otherwise.
The rules are:
- minimum length 10
- at least one lowercase letter
- at least one u... | 16bd2d99777a7d0764ce3b697b1c3319c60ccf87 | 18,928 |
def autoname(index, sizes):
"""
Given an index and list of sizes, return a
name for the layer.
>>> autoname(0, sizes=4)
'input'
>>> autoname(1, sizes=4)
'hidden1'
>>> autoname(2, sizes=4)
'hidden2'
>>> autoname(3, sizes=4)
'output'
"""
if index == 0:
n = "inp... | c7b426f7b3865472e64b84cab4ddff003cd47576 | 18,933 |
def _standardize(dataframe):
"""Transform features by centering the distribution of the data
on the value 0 and the standard deviation to the value 1.
The transformation is given by:
scaled_value = (value - mean) / standard deviation
Parameters
----------
dataframe : pandas.DataFrame
... | 8db61585170223056e176e8b444a33a785cec591 | 18,934 |
def issues_data(record):
"""Retrieve issues data from record."""
total = int(record["total_files"])
issues = int(record["files_with_issues"])
correct = total - issues
return total, issues, correct | 9ff63711f50ef7df1c274d93eec3bd5780d2337d | 18,937 |
import inspect
def _wrapped_fn_argnames(fun):
"""Returns list of argnames of a (possibly wrapped) function."""
return tuple(inspect.signature(fun).parameters) | d68d744051c45c5992e700f06d91121af8738486 | 18,940 |
def clean_sql_statement(original: str) -> str:
"""
Cleans up SQL statements so that they end with a semicolon and don't have any
leading or trailing whitespace
"""
clean = original.strip()
if not clean.endswith(";"):
clean = clean + ";"
return clean | cf8bc73da26cd4cad363b8560170a37c6d5228de | 18,946 |
def sort_keypoints(kps):
""" Sort a list of cv2.KeyPoint based on their response """
responses = [kp.response for kp in kps]
indices = range(len(responses))
indices = sorted(indices, key=lambda i: responses[i], reverse=True)
return [kps[i] for i in indices] | 7b1cc49498571715b2715118fb3887384d4e386c | 18,948 |
def aumento_salarial(salario, porcentagem):
""" Recebe um salário e sua porcentagem de aumento, e retorna
o novo salário"""
novosalario = salario + (salario * porcentagem / 100)
return round (novosalario, 2) | 7578f69bf486ba58374b70be673c1453694b3a72 | 18,958 |
def ask(question: str, default: str = "") -> str:
"""A Simple interface for asking questions to user
Three options are given:
* question and no default -> This is plain input
* question and a default value -> with no user input dafault is returned
* question and 'yes'/'no' default -> us... | e0262592b32f893043b4bc48fd32e99e6b864732 | 18,961 |
def mock_check_version(*args, **kwargs):
"""Necessary mock for KafkaProducer not to connect on init."""
return 0, 10 | 6b989ed3e6226e17c38569c266c03bb94b3db0d3 | 18,965 |
def check_password_vs_blacklist(current_string, blacklist):
"""Checks a string to determine whether it is contained within a blacklist
Arguments:
current_string {string} -- the string to be checked against blacklist
blacklist {list} -- list of words defined within a given
... | e11223cc0c8ffcb0d03e9df2dbfa9a71a87e2667 | 18,967 |
def plusOneSum(arr):
"""returns the sum of the integers after adding 1 to each element"""
return sum(arr)+len(arr) | a3297841007deec4bf4430bbb18ff6405a7657fa | 18,972 |
def merge(*dicts):
"""Merges the given dictionaries into a single dictionary, ignoring overlapping keys."""
out = dict()
for dictionary in dicts:
for (key, val) in dictionary.items():
out[key] = val
return out | c9a3899407b36357c046bed594d5939bc7aab4b3 | 18,973 |
import math
def absolute_error(y, yhat):
"""Returns the maximal absolute error between y and yhat.
:param y: true function values
:param yhat: predicted function values
Lower is better.
>>> absolute_error([0,1,2,3], [0,0,1,1])
2.0
"""
return float(max(map(lambda x, y: math.fabs(x-y... | c1262e042d3895a9ba06c213b27a1d5cb23c96fb | 18,974 |
import re
def clean_wsj(txt, remove_fragments=True):
"""
Prepares WSJ transcripts according to Hannun et al., 2014:
https://arxiv.org/pdf/1408.2873.pdf
It is assumed that data has already been processed with Kaldi's s5 recipe.
A full overview of the wsj transcription guidelines is found here:
... | e1e7c4c3f984f4656a17ffddd6c54481083ac094 | 18,978 |
def bin_string_to_bytearray(binary_string: str) -> bytearray:
"""Converts a binary string to a bytearray
Parameters
----------
binary_string: str
The binary string used to build the bytearray
Returns
-------
bytearray
The generated bytearray
"""
# Fill in bits if the... | 5f1af3a46ee97ad23e3d0a6cb9ded9e1e8568a2b | 18,981 |
def truthy_string(s):
"""Determines if a string has a truthy value"""
return str(s).lower() in ['true', '1', 'y', 'yes'] | ee670b353de29165bd2922b53a13b0d4b3908d40 | 18,987 |
def expectedPrimerPair(l,r):
"""
Inputs:
left primer Segment
right primer Segment
Check if 2 primers come from the same primer pair
Returns:
Boolean
"""
return l[2] == r[2] | 7960463d6579c65ff66282a71c3e3d235d01bcf5 | 18,991 |
def lookup(obj):
""" returns all the methods and atributes of an object """
return dir(obj) | e26bae9a1eeb4460312963526e059268f3a61a35 | 18,994 |
def table_key_url(table_name: str, partition_key: str, row_key: str) -> str:
"""Creates the url path for the combination of a table and a key"""
partition_key = partition_key.replace("'", "''")
row_key = row_key.replace("'", "''")
return f"{table_name}(PartitionKey='{partition_key}',RowKey='{row_key}')" | ce3c4e0639d8b2d78b754fdf6377fd2a693b703e | 18,997 |
def reset_env(env):
"""Resets the pendulum in the safe area."""
env.reset()
env.env.state = env.np_random.uniform(low=[-0.1, -0.5], high=[0.1, 0.5])
env.env.last_u = None
return env.env._get_obs() | 55c987fb8bd9011d5fe16e70828bd4acac2b6be6 | 18,998 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.