content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from bs4 import BeautifulSoup import requests def _parse_side_menu_urls(url: str): """ Parses the side menu, that represent different campuses where the courses are given :param url: url of a page (say, page representing Experimental-field courses :return: urls of the pages including the course detail...
f157aa86d84275506d0278f0b81fdf2a26613bb2
572,912
def or_array_in(dictionary, *keys): """Check if at least one key in the array is in the dictionary. The funcionality is the same as the keyword ``in``, but testing each and every key in the array as an ``or`` operation. :param keys: List of keys to test against the dictionary :type keys: args ...
4c104f3b71bf0b50da67990ec273395e34ee8485
572,914
import re def get_sale_head(line): """Return the date of the livestock sale.""" head_pattern = re.compile(r'receipts.*?\b(?P<date>[0-9]+)\s*hd', re.IGNORECASE) match = False while not match: this_line = line.pop(0) match = head_pattern.search(this_line) sale_head = match.group('da...
cd107df385d9c237bbbc8ddbaac8f0ab8dc7bdd8
572,919
import six def safe_bytes(str): """Returns bytes on Py3 and a string on Py2.""" if six.PY3: try: return bytes(str, 'utf-8') except TypeError: return str else: return str
2448ad3de94638d4882525ae0f7f87d72919557c
572,920
def get_github_connector(opsdroid): """Get the github connector""" for connector in opsdroid.connectors: if connector.name == 'github': return connector return None
33311498fdb54967ce06963cc3e2e5cbb3bfe0c4
572,929
def drop_lsb_bits(val, n_bits): """Drop the lowest bits in a number.""" return (val >> n_bits) << n_bits
d46f0812153fcd8cc738283cb405f55c37166b48
572,930
def import_split(import_name): """ takes a dotted string path and returns the components: import_split('path') == 'path', None, None import_split('path.part.object') == 'path.part', 'object', None import_split('path.part:object') == 'path.part', 'object', None import_split('path.part...
beeafe537f41f2fc7d89bad87151efe2600fa3b1
572,933
def rebuild_row(lst, is_collocation): """ Re-construct csv row as expected by data.py `read_csv_file_data` method Args: lst (list(str)): list with a string containing '\t' is_collocation (bool): if collocation True, else False Returns: list(str): list of string where the first ...
87671e299f12cf92e98178c29fed8caf158b934b
572,940
def findBoneIndex(arm, bone): """Find index of given bone in an armature.""" for ii in range(len(arm.bones)): if arm.bones[ii] == bone: return ii return -1
e9774cbc2a1e3a61cd425532b4b444972016c06c
572,942
import logging def setup_logger(log_level): """Setup logger for the module""" logger = logging.getLogger('email_client') logger.setLevel(log_level) sh = logging.StreamHandler() sh.setLevel(log_level) format = logging.Formatter('%(asctime)s %(levelname)-7s %(name)-10s %(message)s') sh.setF...
9904698af9aa485d554b7afc7dd54d378fc655b5
572,946
import json def prepare_lists(path_lists): """ Parse evaluation lists (i.e., probe and gallery lists) """ path_gallery = path_lists.joinpath("gallery.json") path_probes = path_lists.joinpath("probes.json") path_gt = path_lists.joinpath("true_relatives.json") with open(path_gallery) as f: ...
533b0ae2a4f5cc043afc4ac4d12ac1d7bb019af1
572,947
import re def remove_trailing_punctuation(string): """removes leading and trailing punctuation from a string. Needed for Alpino word nodes""" return re.sub(r"^\W*\b(.*)\b\W*$", r"\1", string)
e6784731dd824cc5dc1570b261d7bc1d8bc52041
572,948
def get_chunks_list(lst, chunk_length): """Separate the long list into separate chunks. :param lst: list to be separated into smaller lists (or chunks) :param chunk_length: int, the length of the lists the longer list is to be split up into Return a list of nested lists. """ chunks = [] fo...
91523e8d69bb07c426829e21770f1d687547bbc3
572,950
def _remove_localizers_by_imagetype(dicoms): """ Search dicoms for localizers and delete them """ # Loop overall files and build dict filtered_dicoms = [] for dicom_ in dicoms: if 'ImageType' in dicom_ and 'LOCALIZER' in dicom_.ImageType: continue # 'Projection Image'...
c59ec5a038381c300749088a63903e13ef26a274
572,952
import json def _updateStatsFromStdout(settings, line): """Parses 'line' and tries to extract encoded 'vfxtest-stats' that the subprocess might have logged. If any 'vfxtest-stats' were found the corresponding settings get updated. Args: settings (dict) : settings dictionary line (str...
384a136a55694c9c44c715ae26b2b8971fde1008
572,955
def classify_images_into_tiltgroups(tiltgroupList, fileList): """ Create a dictionary for each tilt group, e.g. { "tilt_1" : [ "img1.mrc", ... ] , "tilt_2" : [ "img2.mrc", ... ] , ... "tilt_n" : [ "img3.mrc", ... ] , } """ classified_...
85217901ea0fa0fbb42f6b20bcd31e872bd217f0
572,956
def remove_tag(toolbox_line: str, tag: str) -> str: """Removes beginning tag from toolbox_line.""" new_line = toolbox_line.replace(rf"\{tag} ", "", 1) return rf"{new_line}"
b22e0e692e57222446a2636a3249e95262493a58
572,959
import math def next_power_of_2(n): """ Return the smallest power of 2 which is bigger than n """ return 2 ** math.ceil(math.log2(n))
e195efe0c21e931b0c1b21f1f2a7c767a6d027f9
572,964
def add_missing_cat_services_provided(df): """Replaces nan with 'Missing' for 'services provided' variables.""" # Care_Provided Y/N to Y/N/Miss cp_vars = [ "Care_Provided_Assisted_Living", "Care_Provided_Home", "Care_Provided_Inpatient_Hospice", "Care_Provided_Inpatient_Hosp...
64ca7d0157a9d0fb02449436101939e550da6b1a
572,965
def encrypt(passwd: str) -> str: """ The encrypt method used to encrypt password, hacked from the following js: .. code-block:: javascript function securityEncode(b) { a = 'RDpbLfCPsJZ7fiv' c = 'yLwVl0zKqws7LgKPRQ84Mdt708T1qQ3Ha7xv3H7NyU84p21BriUWBU43odz3iP4rBL3cD02KZci...
da8d7695603ea897d4dff7aff3fcc22af98ed9b6
572,966
from typing import Dict from datetime import datetime def check_dates(d_date: Dict) -> str: """Check valid dates Parameters ---------- d_date : Dict dictionary with dates from open insider Returns ---------- error : str error message. If empty, no error. """ possi...
b06918380c306166d1f4a7706435fbe6aa211a4b
572,967
def currentTOflux(I): """ Converts beam current (µA) into flux """ I = I/1e6 # conversion from microamps to amps qp = 1.6e-19 # charge of proton in Coulombs flux = I / (qp) return flux
d6ff8d378fa80e829512eb66111bed8bacf0aaaf
572,973
def rho_Wright97(S, T, P=0): """ Returns the density of seawater for the given salinity, potential temperature and pressure. Units: salinity in PSU, potential temperature in degrees Celsius and pressure in Pascals. """ a0 = 7.057924e-4; a1 = 3.480336e-7; a2 = -1.112733e-7 b0 = 5.790749e8; b1 = 3.516535e...
04a7dfb830b15eec97630552f05e80d95530e36c
572,974
import math def transPos(elbowPos, objPos): """ Change the orientation of the axis and origin to the elbow position so that we can calculate the angle of the elbow to reach the object position. :param elbowPos: the cartesian coordinates of the elbow position relative to the shoul...
4082ca9b9fb75eb81e444612f78e9b12bb4f7d80
572,976
def check_dimension(in_value): """ Convert common dimension names to a preset value.""" if in_value in ('t', 'time', 'temporal'): return 'time' elif in_value in ('s', 'band', 'bands', 'spectral'): return 'bands' return in_value
6041a148dd4a4d82b26c96615b9a70272c0c06a8
572,977
def fleiss_kappa_interpret(kappa): """Return a string containing the human readable interpretation of the value of kappa. """ if kappa >= 1.0: return "Perfect Agreement" if kappa > 0.8: return "Almost Perfect Agrement" if kappa > 0.6: return "Substantial Agreement" i...
d606504d181434c00d35f81f3eaa78fd32983ed7
572,978
def repeating_interval(interval): """ Returns a ``can_retry`` function for :py:func:retry` that returns the specified interval all the time. :return: a function that accepts a :class:`Failure` and returns ``interval`` """ return lambda f: interval
a7bf7e72d28e67fcd42331978545663d281289a5
572,979
def PowerlawPlusConstant(q, A, alpha, C): """A power-law curve plus a constant Inputs: ------- ``q``: independent variable (momentum transfer) ``A``: scaling factor ``alpha``: exponent ``C``: additive constant Formula: -------- ``A*q^alpha + C`` """ ...
a9280ea54e59b03d68ec16e6d0827f6120fd3f75
572,980
from typing import Tuple import re def parse_value(value: str) -> Tuple[str, str, str]: """ Given a value break it down by the ilk of node (usb or pci), the vendor, and the device or product.""" value_pattern = r'^(usb|pci)\(([^:]{4}):([^:]{4})\)$' matches = re.match(value_pattern, value) assert match...
1132ed00b83b929e00adf8be18907ba263101ea7
572,982
def find_trigger(trigger_wrapper, trigger_name): """Search through a collection of triggers and return the trigger with the given name :param trigger_wrapper: A collection of triggers in the Google Tag Manager List Response format :type trigger_wrapper: dict :param tri...
ce8ab05a1a50aa714de5259d9c4b676c0e354c0d
572,984
def get_ilvl(li, w_namespace): """ The ilvl on an li tag tells the li tag at what level of indentation this tag is at. This is used to determine if the li tag needs to be nested or not. """ ilvls = li.xpath('.//w:ilvl', namespaces=li.nsmap) if len(ilvls) == 0: return -1 return in...
524577ded9aec18653c69ab63cfcf1aab7471923
572,987
def best_dist(fit): """From a powerlaw fit, find the best distribution (see powerlaw package) """ distName = 'power_law' dist = "PL" R, p = fit.distribution_compare('truncated_power_law', 'power_law', normalized_ratio=True) if R > 0 and p <= 0.05: distName = 'truncated_power_law' di...
8d816443affbe3a1dc413db7f90950b1b4abe9de
572,990
import yaml from typing import OrderedDict def yaml_load(stream, loader=yaml.Loader, object_pairs_hook=OrderedDict): """ Custom yaml loader. Make all YAML dictionaries load as ordered Dicts. http://stackoverflow.com/a/21912744/3609487 Load all strings as unicode. http://stackoverflow.com/a/29...
a2aa877f65d73e85f286a89348606c4ca247afd2
572,992
def node_name(node): """Return the name of the node.""" return node.name or '{} {}'.format( node.manufacturer_name, node.product_name)
a57fe9529d07f9516e1aace3e86a1eb332428283
572,993
def format_warning(topline,details): """Format warning text clearly Parameters ---------- topline : str One-line description of warning details : str Multiline, detailed description of warning (e.g. exception info) Returns ------- str Multiline warning message...
e29852bad632469a2e7bc44b979576562868e49c
572,997
def get_output_at(output, at): """ get one output """ return output[at]
e5c138a23836d0a98ca54f3363ad455bc3753455
572,998
def indent(text: str, amount: int = 4) -> str: """ Indent :code:`text` by :code:`amount` spaces. Args: text (str): some text amount (int): an indentation amount Returns: indented text """ return '\n'.join((' ' * amount + line) for line in text.splitlines())
521cdfb62755c2e313c1352d1d55d34941122fa6
573,000
def page_count(n, p): """Hackerrank Problem: https://www.hackerrank.com/challenges/drawing-book/problem Brie's Drawing teacher asks her class to open their books to a page number. Brie can either start turning pages from the front of the book or from the back of the book. She always turns pages one at a ti...
ede4ee6ed8aa54a5cde89960ffe49d405ce16b05
573,004
def _compressbits(bitvector, wordsize=32): """Compress binary vector into vector of long ints. This function is used by the Fingerprint class. >>> _compressbits([0, 1, 0, 0, 0, 1], 2) [2, 0, 2] """ ans = [] for start in range(0, len(bitvector), wordsize): compressed = 0 for...
d9f3728e7342cb2a507b3f115ae8f961d2310775
573,005
def get_line(merged_vcf): """Build a list of relevant data to be printed. Args: merged_vcf (dict): an object from project merge VCF response Returns: str: tab delimited list of relevant data to be printed """ return "\t".join( [ str(merged_vcf.id), m...
b684b6bffc3bf6b603c2fbcee9abfc0cdbbe4943
573,009
import torch def bernoulli(p, size): """ Returns a tensor of 1. (True) or 0. (False) resulting from the outcome of a bernoulli random variable of parameter p. Args: p (float): Parameter p of the Bernoulli distribution size (int...): A sequence of integers defining hte shape of the output ...
b14cf0ccff90d5066fd5b57ed6b271e6fc45c23e
573,024
def gini(reads): """Gini index for a set of reads. Gini index, a common measure of income inequality in economics, can measure the evenness of sgRNA read counts [14]. It is perfectly normal for later time points in positive selection experiments to have higher Gini index since a few surviving clones (a...
214103676a42dba4d758c207a7bf517e16aa4ee0
573,025
def prime_factors(n): """ Return the prime factors of the given number. """ # < 1 is a special case if n <= 1: return [1] factors = [] lastresult = n while True: if lastresult == 1: break c = 2 while True: if lastresult % c == 0: break c += 1 factors.append(c) lastresult /= c return fact...
effa7326907bf0fc820837a6eb687919fc85bfb7
573,027
def parse_token(bn,token): """ Obtains the value associated with the given within the basename. Parameters ---------- bn: string, expected. The basename fo the file. token: string, expected. The token to be parsed. Returns ------- The value associated with the t...
a1f57a079eb015a3e9d2281164863432b906bd1c
573,028
async def _build_markdown_hyperlink(text, url): """ Convert text and url into a markdown hyperlink :param text: the text to display :param url: the website the text links to :return: a markdown hyperlink string """ return '[' + text + '](' + url + ')'
c15f29b1b1e9c71f6bdcd80c67c6b5efea6dd345
573,029
from functools import reduce def add_list_elements(in_list): """ Add list elements together, e.g. [1,2,3,4,5,6] -> 1+2+3+4+5+6=21 Note: Guido van Rossum prefers using list comprehension instead of reduce, lambda (https://www.python-course.eu). """ return reduce(lambda x, y: x+y, in_list)
03185155d87a33d76e036ade11d9e611c26683b4
573,034
def round_float(value): """Rounds a float to the nearest integer value.""" return int(value + 0.5)
cea8ded0d8ece4c6e32f269a41fd2ed8c8fffc65
573,039
def KGtoLB(mkg): """ Convertie une masse en kg vers lb note: 1 kg = 2.20462 lb :param mkg: masse [kg] :return mlb: masse [lb] """ mlb = mkg * 2.20462 return mlb
05ecbe4fb668b6c52da9c43243145cabc61699a2
573,043
from typing import Any from typing import Dict def try_get_key(key: Any, dct: Dict[Any, Any]) -> Any: """ Tires to get a key from a dictionary, returns None if it does not exist. """ if key in dct: return dct[key] return None
7f9c4b8799f5b6a58e577f7089703c1f52e6f6c1
573,045
def process_discriminators(effect): """ Determine which discriminators apply to each effect """ discriminators = { 'faction': False, 'class': False, 'tonnage': False } # Effect has a discriminator; Faction discriminator is default if effect.attrib['value'] == '0.0': ...
6670f66b6461015f1cfb6d7d13cb757bd30e554c
573,052
def flatten(input_dict: dict) -> dict: """ Given an input dictionary that may contain nested dictionaries, return a new dictionary that is flattened such that there are no dictionary values. Keys in the returned dictionary are a period-delimited list of the keys used to index the original dicti...
b95864d25c279d6de9e79250a647b20212c2bd42
573,054
def sol(arr, n): """ If the array is 3,5,2,1 Following are the subarrays (3), (3,5), (3,5,2), (3,5,2,1) - 3 occurs 4 times (5), (5, 2), (5,2,1) - 5 is 3 times (2), (2, 1) - 2 twice (1) - once It can be deduced that element at ith position will have its frequency n-i*(i+1). We care fo...
22f06fd112d94127d7ffe341ab91a8fa80d29e60
573,065
def get_xml(request): """Strips the request tag from a response and returns the xml""" open_tag_end = request.find('>') close_tag_start = request.rfind('</') return request[open_tag_end + 1:close_tag_start]
29ad6e0fa8f07ebc3abd2b53ed404b6398554b01
573,067
def iloss(price_ratio, numerical=False): """return the impermanent loss result in compare with buy&hold A&B assets Args: price_ratio (float): Variation A Asset / Variation B Asset price_ratio formula: price_ratio = (var_A/100 + 1) / (var_B/100 + 1) ...
1dfe3917bcb47a9a7f8b6103a02d0fe3d850f0aa
573,074
def compare(a, b): """Replacement for Python 2.x cmp(), https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons""" return (a > b) - (a < b)
1c90ce8d256cde9292e68be796955c2735dcfeb2
573,076
def GetConfigSuffix(config): """Create a string to be used as a file suffix. Args: config: A dict that was the result of ParseConfig(). Returns: A string that concatenates the frontend and backend attributes. """ return config['frontend_attr'] + '_' + config['backend_attr']
5eef78fcc156b241954dc9480937291e987675b2
573,077
def calcula_fatorial(numero): """ Calcula o fatorial de um número recursivamente """ if numero == 0: return 1 return numero * calcula_fatorial(numero - 1)
682b575cf4b486591ae6b88985e1711feb350cc7
573,078
import mimetypes import cgi def _get_content_type(conn) -> str: """Pull out mime type from a connection. Prefer explicit header if available, otherwise guess from url. """ content_type = mimetypes.guess_type(conn.url)[0] or "" if hasattr(conn, "getheaders"): content_type = dict(conn.gethe...
665b72fa653429e421a949d3e2b9fc722513a46e
573,081
import itertools def arbitrary_string(size=4, base_text=None): """Return size characters from base_text This generates a string with an arbitrary number of characters, generated by looping the base_text string. If the size is smaller than the size of base_text, returning string is shrunk to the size....
f756b1a000a3daf21f5e7109c9da1d80b10fcf9c
573,083
import re def get_users_in_message(message): """ Scan a message for any user identifiers. Returns an array of user IDs, no order or uniqueness guarantees. message: a single message dict. """ # We're going to look in two places: # - the "user" identifier in the message # - the text fo...
c0cdfb57f0a06fee78575c358b635be1303b8890
573,084
from bs4 import BeautifulSoup def parse_scimma_sample_response(text): """Extract the SAML Response assertion from from a CILogon SAML Proxy response. """ soup = BeautifulSoup(text, features="lxml") assertion = '' for inputtag in soup.find_all('input'): if (inputtag.get('name') == 'SAMLRespons...
9588245d2f922c81164faa67fb4997552cafd35b
573,087
def page_data(total_count: int, paginator: dict) -> dict: """Build a payload object out of paginator data.""" return { "total_count": total_count, "page": paginator["page"], "max_per_page": paginator["max_per_page"], }
80e6154ac9a9cf7a580b2d203a154ca646cd701d
573,088
def rename_index(df): """If the DataFrame contains a column or index named `index`, this will produce errors. We rename the {index,column} to be `df_index`. Args: df: DataFrame to process. Returns: The DataFrame with {index,column} `index` replaced by `df_index`, unchanged if the DataF...
52cf44a8895edb44b22aeaaf34c5dcca3e46b324
573,093
def calculate_grade(is_elective, grade): """ (bool, int) -> object Precondition: 0 <= grade <= 100 is_elective refers to True iff this course is being taken as an elective. Return the grade if the course is not being taken as an elective, and either 'Pass' or 'Fail' (depending on whether grade is at least 50) ...
9f443b8512ddcaa4b7db3325cec875448cf13596
573,097
def query_delete_table(table): """Generate table delete query for table with name 'table'""" return 'DROP TABLE IF EXISTS ' + table
58c0c81175814861b924b439f016aa4752429d5d
573,107
def extract_image_from_mjpeg(stream): """Take in a MJPEG stream object, return the jpg from it.""" data = b'' for chunk in stream: data += chunk jpg_start = data.find(b'\xff\xd8') jpg_end = data.find(b'\xff\xd9') if jpg_start != -1 and jpg_end != -1: jpg = data[jp...
2d6665d0e1f891468e25a2fe5bc2274b4f68e2f7
573,113
def get_keyword_index(lines, keyword): """ Helper function used for parsing TSPLIB files. It searchs for the given `keyword` across the list of `lines`. Parameters ---------- lines: list List of lines. Each element of this list is a string. keyword: str The input keyword Returns ------- in...
f4c2e013c421caa9a767e4ca06f5a8bb64532e31
573,114
def _calc_csi(tp: int, fp: int, fn: int) -> float: """ Calculate critical success index defined as. Can be interpreted as accuracy that considers rare events, the class that is not rare should be the false class. Values range from [0, 1] where 1 is perfect accuracy? :param tp: true positives :param...
c1caceabd1ad386f780b96049146e053cc2f028f
573,116
def getPostGISVersion(cur): """Retrieve PostGIS full version information from a pyscopg2 connection cursor :param cur: PostGIS database cursor :type cur: psycopg2.extensions.cursor :return: PostGIS version information list :rtype: list """ cur.execute("SELECT PostGIS_Full_Version();") ...
13e981e6bf878f71b2b13b59afb84de103c3b84a
573,118
def get_total_assam_bhuttan(classification_training_data): """ calculates total number of assam and bhuttan people in given dataset :param classification_training_data: data set that contains record for both assam and bhuttan people :return: number of assam and bhuttan people """ # count of bhu...
bfda27b7335f740a8d302b434abc702eb65f5cea
573,119
def _monyearstrings(mon, year, mon_dict, meteoyearfunc): """ Increment the months and potentially the years. Assemble the strings that will allow ``_meteofinder`` to get correct files. Parameters ---------- mon : int Integer representation of the month year : int Integer re...
08ce272af59325d709b180c533492e2cc0ad0e9a
573,120
def area(box): """Returns the area of a box""" x1, y1, x2, y2 = box return (x2-x1)*(y2-y1)
347cf0110d8cd371fd46da6e92feb7f5edec06f8
573,122
def check_pool_method(pool_method): """Check valid pooling method.""" # ('interp', 'maxval', 'maxarea', 'learn') graph pool_method = pool_method.lower() return(pool_method)
55dce1edffc2992fbccab65ccc9e042c0c3243ac
573,125
def _lower(string): """Custom lower string function. Examples: FooBar -> foo_bar """ if not string: return "" new_string = [string[0].lower()] for char in string[1:]: if char.isupper(): new_string.append("_") new_string.append(char.lower()) retu...
8812e26bbcd48946056ee0f57f5f4dad8a6e447a
573,126
def calculate_recall(total_correct: int, total_acronyms: int) -> float: """ Calculate reall as the ratio of correct acronyms to all acronyms. :param total_correct: :param total_acronyms: :return: """ return total_correct / total_acronyms if total_acronyms != 0 else 0
6bdca0ed4f93f58a0335a413e6f4e32e92b04018
573,127
def torch_dot_eye_gen_explicit_map(_, args_pt): """ Generate explicit_map for torch.eye. Args: args_pt (dict): Args for APIPt. Returns: dict, map between frames. """ explicit_map = {'t': 'mindspore.int32'} if args_pt.get('m'): explicit_map.update({'m': args_pt.get('...
e50ff5cb09e9996407f336a40e82d301c1749dad
573,129
def is_float(f): """Check if a variable is a `float` type. Args: f: The object to check. Returns: :obj:`bool`: If the object can be converted to a :obj:`float`. """ if not f: return False try: float(f) return True except ValueError: retu...
f9a844e9c8a0c5fa29be43dda1b5f27ff518a6fa
573,130
from functools import reduce def to_int_be(data): """Convert an arbitrarily-long string to a long using big-endian byte order.""" return reduce(lambda a, b: (a << 8) + b, bytearray(data), 0)
e5172bdeab7326056dda9320081e3db29f74be03
573,137
def balanced_paranthesis(exp): """Return True if exp has balanced parantheses, else False.""" pair = {')': '(', ']': '[', '}': '{'} stack = [] for i in exp: if i in pair.values(): stack.append(i) elif i in pair.keys(): if stack.pop() != pair[i]: re...
3aceb8be21b06dfe8a3ac3a70cb8dff4ad9532aa
573,140
def _choice_evaluator(choice_array, choice_condition): """ Determines which rows in `choice_array` meet the given `choice_condition`, where `choice_condition` is in the set `{0.0, 1.0}`. Parameters ---------- choice_array : 1D ndarray of ints that are either 0 or 1. choice_condition : int i...
82e1ae37884b486342c375e630c567387766d5fd
573,150
def _total_seconds_backport(offset): """Backport of timedelta.total_seconds() from python 2.7+. :type offset: :class:`datetime.timedelta` :param offset: A timedelta object. :rtype: int :returns: The total seconds (including microseconds) in the duration. """ seconds = offset....
4b5e57e967c47837df9de9f7db8430aa012a519a
573,153
def _map_extent_to_bbox_filter(source_map): """Return formatted coordinates, from ipylealet format to owslib.wfs format. This function takes the result of ipyleaflet's Map.bounds() function and formats it so it can be used as a bbox filter in an owslib WFS request. Parameters ---------- source...
df84a7ee773ba0385bbd197659c48afb4e65a404
573,155
def summarize_timesteps(hdf5_file): """Summarizes total read/write bytes at each timestamp. Summarizes read/write bytes for each time step using the HDF5 interface instead of converting to a DataFrame or TimeSeries first. Returns a dict of form:: { "1546761600": { ...
502b0c1c80505388470bfcc342115878b5403489
573,156
def first_or_none(iterable): """ Returns the first item in an iterable, or None if the iterable is empty Args: iterable (iterable): Some iterable Returns: first item or None """ return next((x for x in iterable), None)
73699b3a85ae5e8cd89e5a5af893f41c9fcedd2a
573,165
def is_facebook_bot(request): """Check the request's User-Agent against the Facebook bot's User-Agent.""" ua = request.META.get('HTTP_USER_AGENT', '') return ua.startswith('facebookexternalhit')
e95a58b7f104872fac1d38bb349b25961079513d
573,167
import yaml def yaml_loader(filepath, log): """Load a yaml file""" try: with open(filepath, "r") as myfile: return yaml.load(myfile, Loader=yaml.BaseLoader) except FileNotFoundError as e: log.error(e) quit()
55de05c37aebb724e101b306f439a2836929d09f
573,175
def process_dataset(file_dataset_path): """ Process the dataset file and returns a list with the proxy values for each pair of entities. :param file_dataset_path: dataset file path. The format of each line of the dataset files is "Ent1 Ent2 Proxy"; :return: a list of lists. Each list represents a ent...
8843596959580e238ae00da2c35fa33c24781b21
573,180
import six def int_to_bytes(value): """Convert integer -> bytes.""" hex_value = '{:x}'.format(value) if len(hex_value) % 2: hex_value = '0' + hex_value array = bytearray.fromhex(hex_value) # First bit must be zero. If it isn't, the bytes must be prepended by zero byte. # See http://ope...
b7dbba662b516dabcd624816bc6c5a4a27af2fc0
573,181
import random def check_episode_has_noise(lat_noise_percent, long_noise_percent): """ Checks if the noise is to be added to the current episode (only for inject triangular perturbations) Args: lat_noise_percent: % noise to inject in steering long_noise_percent: % noise to inject in thrott...
38dedd1e4ed157b086f3285aaebff4c14e87d63c
573,183
def pooled_autocorr_lag2(df): """Compute the pooled autocorrelation with lag 2.""" ds = df.query("period > 2")["e2"] ds.reset_index(drop=True, inplace=True) ds_lag = df.query("period < 9")["e2"] ds_lag.reset_index(drop=True, inplace=True) return ds.corr(ds_lag)
9e69d4ef342c0b7e16b8a48b7840452b0e702ec3
573,185
def max_bits_to_hide(image, num_lsb): """Returns the number of bits we're able to hide in the image using num_lsb least significant bits.""" # 3 color channels per pixel, num_lsb bits per color channel. return int(3 * image.size[0] * image.size[1] * num_lsb)
52e7950dd00272d908d9c8e45b79d5d1e2c05040
573,188
import socket def hostname(full=True): """ Returns the hostname of the current machine. """ return socket.gethostbyaddr(socket.gethostname())[0]
846a70392d323e61e7774b206dcc3e73bfb3e31f
573,190
def GroupByProject(locations): """Group locations by project field.""" result = {} for location in locations or []: if location.project not in result: result[location.project] = [] result[location.project].append(location) return result
a440afd0fde54252daa2803c2bf25b2a8915a00e
573,192
def strip_code_cell_warnings(cell): """Strip any warning outputs and traceback from a code cell.""" if cell['cell_type'] != 'code': return cell outputs = cell['outputs'] cell['outputs'] = [ output for output in outputs if output['output_type'] != 'stream' or output['name'] != '...
1ea02c2b0d5a09d7b7015a9d24cb483abb1fe5d6
573,197
def subclassof(obj, classinfo): """Wrap issubclass to only return True/False""" try: return issubclass(obj, classinfo) except TypeError: return False
e291daa3e6c3fd6dc628e502d514bc6dceca4497
573,199
def find_parameters_in_dataset(dataset) -> list: """ Figure out which parameter is in dataset and where :param dataset: hdf5 dataset with a dimension labels :type dataset: hdf5 dataset :return: parameters :rtype: list """ dims = dataset.attrs.get("DIMENSION_LABELS")[1].decode() ...
8da48205d1f5a2ea37b0a1470e34c7b9d77034c9
573,200
def conn2str(a_conn): """Convert connective tuple to string. Args: a_conn (tuple): tuple of connective tokens Returns: str: connective string """ return '_'.join(itok for ipart in a_conn for itok in ipart)
05c32afbc3d7a27a6f8f655bab287e52be2217d7
573,204
import re def is_simple_string(element): """Return True if the element is a simple string simple string is a one word string. """ match = None if type(element) == str: regex = re.compile("^([A-Za-z0-9_-]+)$") match = regex.match(element) return True if match else False
fd2eff4f1d37c721b7a41ea066c6fd5858d8e118
573,208
def count_combination(visit_to_fid_to_sequence_type_to_filename, nb_augmented_images): """ Description: Counts the number of combinations for the T2, DWI and ADC images of a specific patient. Params: - visit_to_fid_to_sequence_type_to_filename: dictionary {'visit': {'fid': {'t2': [filenames], 'dwi':...
d62540eda9a958e35c3803a5ed02f044971da721
573,209
def validate_data(data): """ Validate that the request from Slack contains all the data we need :param dict data: :return bool: """ if not data.get("response_url"): return False if not data.get("token"): return False if not data.get("command"): return False i...
739030f28fd2e1779c648de56b5be5080d84f887
573,210