content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os import re def envVarDefined(value, name=None, evar=None): """Checks wether specified environment variable is already defined value - value of the environmental variable to be checked name - name of the environment var to be retrieved (required in evar is not specified) evar - retrieved value of the ...
21fd31da28ffcd73e2d99f7f99ebe35f307accc3
628,867
from typing import Callable import importlib def get_callable(function_string: str) -> Callable: """get_callable import a function based on its dot notation format as as string :param function_string: the dot notation location of the function. (i.e. foo_module.bar_function) :type function_string: str ...
d0e400dfc86d7782b03a94e94d9aedf4cb8447c8
628,868
import torch def my_permute_batch_split(batch_split, permutations): """Scrambles a batch of objects according to permutations. It takes a 3D tensor [batch_size, n_objects, object_size] and permutes items in axis=1 according to the 2D integer tensor permutations, (with shape [batch_size, n_objects]) a...
43b2f74fc8d1faad362642bb71c606b08d1e77ab
628,869
import numpy def bai(b4, b6, b7, b8a, b12): """ Burned Area Index for Sentinel-2 (Filipponi, 2018). .. math:: top = (1 - sqrt((b6*b7*b8a) / b4)) bottom = (((b12 - b8a) / sqrt(b12 + b8a)) + 1) BAI = top * bottom :param b4: Red. :type b4: numpy.ndarray or float :param b6: Red-edge 2. ...
6b34207d38d0f98da6a17bc2574fff412783eb82
628,870
import time def getSQLDateFromUnixTime(unixTime): """getSQLDateFromUnixTime. Args: unixTime: """ sqlDate = None try: sqlDate = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(unixTime))) except ValueError as e: sqlDate = None print("Unix time must be an integer.") ...
d9e5de3f307a1b68a149681beb4ee5b1eefc5445
628,871
def is_tracing(): # real signature unknown; restored from __doc__ """ is_tracing()->bool True if the tracemalloc module is tracing Python memory allocations, False otherwise. """ return False
3f8ec81c25b37531c4f361e876e0ce0468716ee1
628,872
from typing import Any import pickle def load_pickle(filename: str) -> Any: """Load object from pickle filename. Args: filename (string): The absolute path to the saved pickle. Returns: data (any): The loaded object. """ with open(filename, 'rb') as fp: data = pickle.load...
1bcbc2a70b51d0074fd4195bb32edc116e07d46d
628,873
import argparse def check_positive(value): """ Determine whether the input value is a positive integer. """ ivalue = int(value) if ivalue <= 0: raise argparse.ArgumentTypeError( f'{ivalue} needs to be a positive integer' ) return ivalue
1b26f8c1b773f4890c59767c1298d705f8d5488b
628,874
import requests def get_all_weather_data(city="st. john's"): """ Helper function. Makes a request to openweathermap server. :param city: :return: Returns entire current weather for the city. """ base_url = "https://api.openweathermap.org/data/2.5/weather?" api_key = "e3a3f627f93effe0dc13ea...
60d64cd3df7b38e4db14380b06a5e86c1c2e3c7c
628,875
import re def looks_like_formula(formula): """Return True if input string has expected format of a molecular formula.""" regexp = r"^(?:[A-Z][a-z]?(?:[1-9][0-9]*)?){2,}$" return re.search(regexp, formula) is not None
26ebdee1ab3e48f9120d7c50745326d150cfac27
628,876
def is_json(filename): """Predicate for checking if a filename is .json""" return filename.lower().endswith(".json")
f638e18a0c5cc5ff4c425b1ba89ec0fe84b8db0e
628,877
from typing import List def calc_low_actual_pd(actual_temps_dict: dict, final_low_rcp_list: list) -> List[float]: """ Return a list of percentage differences of low RCP values to actual temperature values """ actual_temps_list = list(actual_temps_dict.values()) low_rcp_pd = ...
bfde30ec5b918d9ebc36f88d026a1e842ebcc16f
628,879
def new_sequence(num, sequence): """ :param num: int, allow users to input a number that is used to offset the original order in the sequence (ALPHABET). :param sequence: str, the sequence (ALPHABET) that users want to shift the order. :return: str, the new sequence (ALPHABET) with a new order. """ ...
09d63c0984a8b2325efde44debd6afdec352f444
628,880
import pandas def value_value_counts(df, columns=None,): """ meta information about column return [(<col_name>, <#value_type>, <column_index_type>, <column_values_type>),..] # type may not always correct [ ('img-path', 442, dtype('O')), ('keyned-position', 2, dtype('int64')) ] ...
e6be7a0ac101a28d3c39e5469115b9557725287a
628,881
from typing import Dict from typing import Set import collections def load_qrels(path: str) -> Dict[str, Set[str]]: """Loads qrels into a dict of key: query_id, value: set of relevant doc ids.""" qrels = collections.defaultdict(set) with open(path) as f: for i, line in enumerate(f): li...
7d57310651e5b7d0f2b79b647d06faee905fb471
628,882
import argparse def read_cli_args(): """Read command-line interface arguments Parse the input to the command line with the argparse module. Args: N/A Returns: args (argparse.Namespace): parsed arguments """ # read command line arguments cli_description = 'Launcher for ex...
8e81b171125229c046e57dec7c227c8ad4d20912
628,883
def get_gap_HS_data(modeling_data, gap_period, gap_station): """ Get original HS data in the gap period. Only winter values (Nov-Apr) will be returned. """ y_true = (modeling_data .loc[modeling_data['stn']==gap_station, 'HS'] .loc[gap_period] ) y_true =...
9ffadff48be31253ec3b8ca450b62304c2a1e032
628,884
def market_columns(df): """Function that maps multiple entries in a column into individual columns and assings a score of 1 or 0 if the entry is question is within a given row. """ categories = [] for category in list(df['Market Category'].unique()): categories += category.split(',') un...
2536a19df282f6e037905d4e71accfe00b8e61a0
628,885
def remove_string_float(string): """Pandas dataframe returns integers sometimes as floats. This function takes a string and removes the unnecessary .0 if the next character is a tab or new line. Args: string: tsv file in string format Return: string: string with float removed ...
b9e586d8f8e96ecfad38cb57e29854863d8718dd
628,886
import base64 def get_base64_encoded_image(image_path): """ encode image to string for use in html later""" with open(image_path, "rb") as img_file: return base64.b64encode(img_file.read()).decode('utf-8')
7a28e9ae010cb2412aaff71ce3a8f0eb9f60604e
628,887
def help_description(): """ Returns description of program for help message """ return 'Help Description // To fill'
9c721370946add24c94cf6157f06d6e64f273037
628,888
import math def muller(functions, m_and_Ms, a, b, eps): """Muller method: """ f = functions[0] m, M = m_and_Ms c = 0.0 x0, x = a, b i = 1 fa, fb, fc = 0.0, 0.0, 0.0 ans = [x] while abs(((x - x0) ** 2) * M/m) > eps: # abs(x - x0) > eps: x0 = x c = (a + b) / 2....
c81eded228a56516e355c68ed199d99fb2250908
628,889
def agent_ids(cur, archetype): """Gets all agentids from Agententry table for wanted archetype agententry table has the following format: SimId / AgentId / Kind / Spec / Prototype / ParentID / Lifetime / EnterTime Parameters ---------- cur: cursor sqlite cursor3...
2bebea96d8f0ad83363e31443e1295866cbb2775
628,890
import argparse def get_input_args(): """ Retrieves and parses the command line arguments created and defined using the argparse module. This function returns these arguments as an ArgumentParser object. Parameters: None - simply using argparse module to create & store command line arguments ...
a4ac48512b432870ba2fd93d3f7e7f2489da7a22
628,892
def sql(conn, stmt, *vals): """ Runs the statement with binds and returns the list of tuples for select or None for a DML/DDL """ c = conn.cursor() c.execute(stmt, tuple(vals)) tuples = None if c.with_rows: tuples = c.fetchall() c.close() return tuples
71c41386df3c9521fcda8faf4b40212297c2e6a7
628,894
def sol_tracker(w2v_model, solution): """Keep a record of those solution words that do not appear in the W2V vocabulary Args : w2v_model : standard Word2Vec 'KeyedVectors' data structure solution : List of tokenised words representing solution """ sol_errors = [] for word in solution...
349b540f9b7a2b788f73e143ed5365c55ec47bef
628,896
from typing import Mapping def is_updated(dictionary: Mapping, update_dict: Mapping) -> bool: """Checks if the dictionary has been updated with the values from update_dict.""" for k, v in update_dict.items(): if isinstance(v, dict): if not is_updated(dictionary.get(k, {}), v): ...
8fcdf5a6f8c529e22481c5dcdfd7c72eb3adf8aa
628,897
def colorspace_prefixed_name(colorspace): """ Returns given *OCIO* colorspace prefixed name with its family name. Parameters ---------- colorspace : ColorSpace ColorSpace to prefix. Returns ------- str or unicode Family prefixed *OCIO* colorspace name. """ pref...
5bda395c9c67476333d3a52eefa90aff861c05d3
628,898
import re def extract_pmc(citation): """ Extract PMC from a given eutils XML tree. Parameters ---------- tree: Element An lxml Element parsed from eutil website Return ------ pmc: str PubMed Central ID (PMC) of an article """ pmc_text = [c for c in citation.sp...
4a65a77934d0e1b614058bba3bd05bda1b27ad7d
628,899
def PrefixFromPattern(pattern): """Given a path pattern, return the prefix to use in ListKeys. If a pattern ends with '*', the prefix is the pattern without the '*', otherwise, we format is as a directory. """ if pattern.endswith('*'): return pattern[:-1] elif pattern.endswith('/'): return '' if patte...
b503c3eb633cb405c26c64ec24ab7807a423d854
628,900
import json def create_blob(data): """Put the dasta into json format""" json_data = json.dumps(data) return json_data
37da56659ed87ee904702071f2fa74088a8fe42d
628,901
import subprocess def add_far_to_repo(amber_bin, name, far, key_dir, repo_dir, ver_scheme, version=0): """Add a FAR to the update repository under the specified name amber_bin : path to the amber binary name : name to publish the package as far : path to the FAR file to publish key_dir...
035f414b213974c6d93beca6376273724d58fe21
628,902
def get_room_vars(obj): """ Get Room Variables :param obj: :return: """ rm_vars = {} for var in obj.var: rm_vars[var.attrib["n"]] = var.text return rm_vars
24f0d56cefca32571cebb2a9535c36d179f489b8
628,903
def coords_to_lat_lon_lists(coords): """Converts a list of coordinates in tuple form (latitude,longitude) to a list of latitudes and a list of longitudes. Parameters ---------- coords : list(tuple) a list of coordinates in tuple form (latitude,longitude) Returns ------- ...
8da18ee4afb4b3ace26c9e847b9314e9e38a5432
628,904
def bin_filter(input: float, abs_boundary: float) -> float: """ Simple binary filter, will provide abs_ceiling as a binary output, according to the 'negativity' of the input value :param input : input value :param abs_boundary : abs boundary value :return : output binary value...
15a53d5602d618f57a538831212fa5814d7640bb
628,905
def bmr(W, H, A, S): """ Basal Metabolic Rate calculator Calculates the BMR based on the Harris-Benedict Formula Algorithm: http://www.healthfitonline.com/resources/harris_benedict.php :return: The BMR in kcal/day :rtype: float """ if S=='XX' or S=='xx': # Female res = 655 + (4.35*W) + (4.7*H) - (4.7*A) ...
bcd352608135604736bd3197ad52403295bbd035
628,906
def lsb(x, n): """Return the n least significant bits of x. >>> lsb(13, 3) 5 """ return x & ((2 ** n) - 1)
7e4021556e7136d0e38b70211f4c8e00ba67d2a4
628,907
import math def is_square(num : int) -> bool: """ Check if a number is perfect square number or not. Parameters: num: the number to be checked Returns: True if number is square number, otherwise False """ if num < 0: raise ValueError("math domain error") if m...
e8002cd9d65e53fd62f86fafa41284cb4c5efb6a
628,908
def join(liste, relier, transforme): """Join les éléments de liste avec le signe retourner par func(élément) et modifiant chaque élément de la liste avec transforme(élément). """ chaine = str(liste[0]) liste.pop(0) for elem in liste: chaine += relier(elem) + transforme(elem) retu...
b91ce02b03d28cd4b6e603a3a46555828b4bae65
628,909
def get_carrier_name(cheap_airfares): """Parse carrier's name and creates a list for one way and round trip search >>> cheap_airfares = ([{'carrier_name': u'United Airlines, Inc.'}, {'carrier_name': u'United Airlines, Inc.'}], None) >>> get_carrier_name(cheap_airfares) [[u'United', u'Airlines,', u'Inc....
8d7bf707acf100dd7550562991e4dd5a2d55baa4
628,910
def get_text(*dataframe, columns=["Question", "Dialogue", "Report"], concater=" "): """ 把训练集,测试集的文本拼接在一起 :param dataframe: 传入一个包含数个df的元组 :param columns: 要拼接的列 :param concater: 怎么拼接列,默认用空格拼接 :return: """ text = "" for df in dataframe: # 过滤掉数据集没有的特征 proc_columns = [] ...
0720849f7e9d84c716c7d873975fab7ff22ad570
628,911
def get_display_data_single(fields, data, missing_field_value=None): """Performs slicing of data by set of given fields. :param fields: Iterable containing names of fields to be retrieved from data :param data: Collection of objects representing some external entities :param missin...
bf73156ad3ced77852470625aa4812402231ffaa
628,912
import re def IsGitSha(revision): """Returns true if the given string is a valid hex-encoded sha""" return re.match('^[a-fA-F0-9]{6,40}$', revision) is not None
f97271c03109ca618b82180b8c928c8129a06ae3
628,913
def bits_table_l() -> dict[int, int]: """The table of the maximum amount of information (bits) for the version L. Returns: dict[int, int]: Dictionary of the form {version: number of bits} """ table = { 1: 152, 2: 272, 3: 440, 4: 640, 5: 864, 6: 1088, 7: 1248, 8: 1552, 9: 1856, 1...
cb001b77171c5af1423b542b17a7af9fbd027e20
628,914
def get_schlagworte_list(itemlist): """ extrahiert aus dem Pfad Schlagworte """ ret = '' for s in itemlist: ret += s.name + '\n' return ret
8b4f516ebea4eefee349b1e80f6a5b10d68d0945
628,915
def is_triangle(side_a, side_b, side_c): """Returns True if the input satisifes the sides of a triangle""" return side_a + side_b > side_c and side_a + side_c > side_b and side_b + side_c > side_a
1eb22261edb13c734430e3ef8207bd256436d1c5
628,916
def dumb_property_dict(style): """returns a hash of css attributes""" return dict([(x.strip(), y.strip()) for x, y in [z.split(':', 1) for z in style.split(';') if ':' in z]]);
7535b3798c64e82761c0ee2d2d58291871076b2c
628,919
def _get_list_feat_names(idx_feat_dict, num_pair): """Creates flattened list of (repeated) feature names. The indexing corresponds with the flattened list of T values and the flattened list of p-values obtained from _get_list_signif_scores(). Arguments: idx_feat_dict: {int: string} ...
7020a722646bdeff4bd520f2b1418fcf2b124fa1
628,920
def read_file(file: str) -> str: """ Reads a file. Args: file (str): file to read Returns: (str): content """ content = "" with open(file) as fp: content = fp.read() return content
7caf5b1d2cdf35cf1b847c082ad5c1c5f033eeca
628,921
from urllib.request import urlretrieve from typing import Optional import os def download(source: str, sink: Optional[str] = None) -> str: """ Download a file. Parameters ---------- source : str Where the file comes from. Some URL. sink : str, optional (default: same filename in curre...
47a9438ea5c041fdb582a1d5e2de9552a0cb50cb
628,924
from datetime import datetime import os import tempfile def create_tempfile(mode='ts', ts_fmt="%H%M%S", dir="/tmp", prefix="_", suffix=""): """Create temp file, mode: 'ts', 'str'. See Also -------- create_tempdir """ if mode == 'ts': fn = datetime.strftime(datetime...
0998d9c9ae8f1a0601517a0dcc47cf3ffcc7049d
628,925
def to_int(s): """Convert a column to ints usage: new_var = data.apply(lambda f : to_int(f['COLNAME']) , axis = 1) """ try: s1 = int(s) return s1 except ValueError: try: s1 = int(round(float(s))) return s1 except ValueError: retu...
5d26ca9253d557ff987c5351a3346307c5108272
628,926
def nprevzero(N, k, ncache): """ Return true if any previous result was zero """ for ix in range(k - 1, 2, -1): # print(ix) p = ncache['full'].get('N%dk%d' % (N, ix), -1) # p = ncache['full'].get('N%dk%d' % (N, ix), -1) if p == 0: return True return False
00917f7515300ad58625486b9858a0827b6e03d6
628,927
import string import random def _uname(name=None): """Append a 6-digit hash code to a specified name. Parameters ---------- name : str Name to append the hash code to. The default is ``"NewObject_"``. Returns ------- str """ char_set = string.ascii_uppercase + string.dig...
fb5bf289f60f8785fc2cae802abdf15a4817085e
628,928
import configparser def get_dwd_settings(): """ Gets the settings for the Deutscher Wetterdienst recent precipitation This public function reads the settings for the recent precipitation from the Deutscher Wetterdienst data. This contains: - path to the data on the DWD FTP server - local path of ...
978120d26d7ccec3215841eeb35d951593bcdd11
628,929
def is_box_inside(in_box, out_box): """ check if in_box is inside out_box (both are 4 dim box coordinates in [x1, y1, x2, y2] format) """ xmin_o, ymin_o, xmax_o, ymax_o = out_box xmin_i, ymin_i, xmax_i, ymax_i = in_box if (xmin_o > xmin_i) or (xmax_o < xmax_i) or (ymin_o > ymin_i) or (ymax_...
732101c29bb55758ad44836582a96652b6eb4d58
628,930
def convert_path_to_targetname(include_path): """Convert an included header file's path to a quickstep library target in cmake. Args: include_path (str): A header file path taken from a C++ include statement. Returns: str: The target name in CMake that corresponds to the sp...
9ae408e498825d031851ad8c7dd82fd6bd51e11c
628,932
from typing import Optional import os def has_parent_path(path: str, parent_path: Optional[str]) -> bool: """Verifies if path falls under parent_path.""" check = True if parent_path: check = os.path.commonpath([path, parent_path]) == parent_path return check
83c32f25e03b6d2ffe1b993daad202a23fd16e98
628,933
def parseMalformedBamHeader(headerDict): """ Parses the (probably) intended values out of the specified BAM header dictionary, which is incompletely parsed by pysam. This is caused by some tools incorrectly using spaces instead of tabs as a seperator. """ headerString = " ".join( "{}...
7daa8adb49b9cd4535407e112a4330b13809a45c
628,934
import socket def initialize_connection(): """Set up a socket a connection and return socket object.""" infos = socket.getaddrinfo('127.0.0.1', 5000) stream_info = [i for i in infos if i[1] == socket.SOCK_STREAM][0] client = socket.socket(*stream_info[:3]) client.connect(stream_info[-1]) retur...
8dda4c2742ad21bd09a33b10c85da6f404affc91
628,935
def user_password_middleware(user): """ Sets same user password for all users. Password = test. """ user.set_password('test') return user
a749c69a5bdc546c11dcdb131ef1db62a9d7fcbd
628,936
def parse_es_tag_results(response): """Parses results of es_tag_query such that a list of dicts is returned""" to_return = [] for hit in response: if tags := hit.to_dict().get('tags'): for key, value in tags.items(): to_return.append({'name': key, 'value': value}) ret...
f052d2741d4506c564cdfa3a240749c67e3e201e
628,937
def merge_clouds(old_dict, new_dict): """Like dict.update, except handling nested dicts.""" ret = old_dict.copy() for (k, v) in new_dict.items(): if isinstance(v, dict): if k in ret: ret[k] = merge_clouds(ret[k], v) else: ret[k] = v.copy() ...
941fe5b0a036f1b0cbbe1aef7e9b5792a42adee6
628,938
def _is_required_parameter(param): """Indicates whether the parameter is required or not.""" return param.default is param.empty and param.kind is not param.VAR_POSITIONAL
fdd80b0661ea05f62d8c7953b535623c240c3663
628,939
def set_out_names(count_p2sh, non_std_only): """ Set the name of the input / output files from the experiment depending on the given flags. :param count_p2sh: Whether P2SH should be taken into account. :type count_p2sh: bool :param non_std_only: Whether the experiment will be run only considering no...
61fb310affc0e56e56e3ca29f0c68ad499b31778
628,940
def constants(): """ Constant values to be used in all tests """ return { 'API_NAME': 'demoapi', 'HYDRUS_SERVER_URL': 'http://hydrus.com/', 'PAGE_SIZE': 1 }
2bce236e3283ce3b0dbf9f703c6d70ada05ae53f
628,941
def add_aliases(mention_cands, kb): """ Add all mentions with candidates to the Knowledge Base as aliases :param mention_cands: the dictionary with mentions and their candidates :param kb: the Knowledge Base that contains the company entities :return: the Knowledge Base with the added aliases "...
947d7d49d6b59f4a6f293b8c18c66d24ef611a57
628,942
def normalizeWeights(weights): """ Normalize a list of weights so the sum of the list is equal to one. :return: List of normalized weights :rtype: list of floats """ multiplier = 1/sum(weights) if multiplier == 1: return weights return [w*multiplier for w in weights]
1fb7721123393ae3e5d64ed01d7fe9fa634c8e76
628,943
def request_record_input_data(): """Input data to a Request record.""" return {}
f2802bc8503cc375fffc93957651ed931352ba56
628,944
import json def kernel_for(notebook): """Read the notebook and extract the kernel name, if any""" with open(notebook, "r") as f: nb = json.load(f) md = nb.get("metadata") if md: ks = md.get("kernelspec") if ks: return ks["name"] return None
d2e774a6095e66c3712325b24d0d9bb45c606202
628,946
def nearlyEqual(x,y): """ Like within, but with the tolerance built in """ return abs(x-y)<.0001
11499f81239b12794f625475a68fedc296515ad2
628,947
def find_parent(i3, window_id): """ Find the parent of a given window id """ def finder(con, parent): if con.id == window_id: return parent for node in con.nodes: res = finder(node, con) if res: return res return None ...
269575d7604e848652185040ad5466faec0fe655
628,948
def soft_dice_coef(output, target): """Dice coef metric function.""" num = target.size(0) m1 = output.view(num, -1) m2 = target.view(num, -1) intersection = (m1 * m2) score = 2. * (intersection.sum(1) + 1) / (m1.sum(1) + m2.sum(1) + 1) return score.sum()
609e5d61c655cb5e8901a1d2b9cce3537e974c93
628,949
import time import logging def get_uhfli_scope_records(device, daq, scopeModule, num_records=1): """ Obtain scope records from the device using an instance of the Scope Module. """ scopeModule.execute() # Enable the scope: Now the scope is ready to record data upon receiving triggers. daq.setI...
cf0f0d49608c4f19346446d7707690f6485c1a84
628,950
import os def get_shared_gcs_path(gcs_shared, use_shared_build): """return the shared path for this set of jobs using args and $PULL_REFS.""" build_file = '' if use_shared_build: build_file += use_shared_build + '-' build_file += 'build-location.txt' return os.path.join(gcs_shared, os.gete...
58f44385d1427dd886112381e3a970614f556fd4
628,951
import logging def setup_logger(options): """Configure Python logging module""" log_fmt = "OpenNESS Setup: [%(levelname)s] %(module)s(%(lineno)d): %(message)s" ts_fmt = "%Y-%m-%dT%H:%M:%S" handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(log_fmt, ts_fmt)) root_logger =...
1a84bdc5887234613c863dd5372107afb95309d3
628,953
def replace_fa_table_keywords(table_head, section_name, word_translation_yaml_data, language): """Replaces specific keywords from the focus area table templates. Also adds WG heading as section_name """ table_head = table_head.replace("$SECTION_NAME$", section_name) table_head = table_head.replac...
c79b3b47664f743849ace8e4c5011c624c5918d9
628,954
def clean_lccn(value): """Following the logic/examples described at: http://lccn.loc.gov/lccnperm-faq.html#n9 http://www.loc.gov/marc/lccn-namespace.html""" # remove all blanks value = value.replace(' ', '') # if there's a forward slash, remove it and all characters to its right if '/' i...
ee485d5209f717c080670d916f3fc0c8b1ef4a0d
628,955
import time def _measure_time(func, *args, **kwargs): """Utility function""" time_beg = time.time() ret = func(*args, **kwargs) time_end = time.time() return ret, time_end - time_beg
3821593702f8b3f9ade3774b0d4a399e4f0ea420
628,956
import calendar from datetime import datetime def date_n_month(date, n_month): """ returns the same date with "n_month" offset :param date: the date :param n_month: the number of month, 0 means this month, positive future month, negative previous month :return: the same date minus the "n_month_bac...
4f17807de7542e9e9167ff25aac80fcbf37d02a8
628,957
from typing import List from typing import Pattern import re from typing import Optional from typing import Match def _remove_blank_lines(*, expression: str) -> str: """ Remove blank (break or spaces only) lines from expression string. Parameters ---------- expression : str Target express...
bd6976ea6b38907c93fb53d2b445dd482875ab65
628,958
def notification_event(events): """ Property: NotificationConfig.NotificationEvents """ valid_events = ["All", "InProgress", "Success", "TimedOut", "Cancelled", "Failed"] for event in events: if event not in valid_events: raise ValueError( 'NotificationEvents mus...
166a4568f185da2f4e4a85563d6915e872097995
628,959
def largest_palindrome_from_product_of_two_n_digit_numbers(n): """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. :param n: :return: """ ans = max( i * j for i in range(10 ** (n - 1), 10 *...
2c1fcb2d3aacba34d3d0518e14e2dcce00b5bd6c
628,960
import os import requests import json def get_data(): """ This function queries the specified URL to retrieve the json out put. """ try: data_url = os.environ['DATA_URL'] r = requests.get(data_url) json_data = json.loads(r.text) return json_data except ValueError: ...
60606c7435a8f95965cfb733efe2231830bd514b
628,962
import re def clean_sentences( sent_list): """ sent_list: list of sentence strings desc: removes a bunch of large spaces and newline characters from the text """ return [re.sub(r" +", " ", re.sub(r"[\n\r]", "", s)).strip() for s in sent_list]
db8e5a04fd94008149ee681aa923e9839f05e552
628,963
from typing import Dict from typing import Callable from typing import Any import json def build_dumber(encoders: Dict[str, Callable[[Any], Any]]): """ Build a json dumber function from a map of encoders for fields that needs to be encoded differently. Args: encoders (Dict[str, Callable[[Any], Any]]): The ...
739d73e3dc4a29a44c569a6f03803aa53bb6b3fe
628,965
import shlex import logging import subprocess def run_child(cmd): """Use subrocess.check_output to run an external program with arguments.""" cml = shlex.split(cmd) logging.info('Running instance of %s', cml[0]) try: output = subprocess.check_output( cml, universal_newlines=True, s...
22f0343e7d8846cb331090c4f66f06caea4e9b5d
628,966
import binascii import os def generate_secret_key(length: int = 30) -> str: """Generate a secret key for the Flask Airflow Webserver. :param length: the length of the key to generate. :return: the random key. """ return binascii.b2a_hex(os.urandom(length)).decode("utf-8")
f4c3ca37c03d8c75c1d1a0295f9b41f53d9ad8d5
628,967
def butterworth(X, cutoff, order, mu=0, cutin=None): """ Butterworth transfer function. Parameters ---------- X : numpy.ndarray, required Range of values to plot over. cutoff : float, required Cut-off value for function. Note that if array X includes values both above a...
e6337d16f5b0755d4168d66e87da98536135b064
628,968
import os import hashlib def get_cache_dir(project_dir: str) -> str: """Compute cache directory to be used based on project path.""" # we only use the basename instead of the full path in order to ensure that # we would use the same key regardless the location of the user home # directory or where the...
58bde016e9e28dc353a46cb815a3ea3f25cde410
628,969
def is_from_module(obj, module): """Check if an object "belongs" to a module. >>> import collections >>> is_from_module(collections.ChainMap, collections) True >>> is_from_module(is_from_module, collections) False """ return getattr(obj, '__module__', '').startswith(module.__name__)
91024d94e480d71cfb28724470e52fceb92222d0
628,970
import os import sys def find_script(script_name="manage.py"): """ Locates the `script_name` file by searching in the current and parent directories. :param str script_name: Name of the manage script. Default is `manage.py`. :returns: Path to the manage script. :rtype: str """ searche...
0b6fbab6fdc83f091a3f67bfa25f338c7c08df7f
628,972
import os def get_project_root(): """ Traverses up until it finds the folder with `.carmeignore` in it. @return: The absolute path to the project root or None if not in a project """ cd = os.getcwd() while not os.path.exists(os.path.join(cd, ".carmeignore")): if cd == "/": ...
41d57906fd83d13af55ee9daa919aa4087aa3ea9
628,973
def has_all_permissions(user, permissions): """ Return `True` only if the user has all the permissions """ for perm in permissions: if not user.has_perm(perm): return False return True
5b82b3cceb7ea4cdb3ce52f1ba5f73364a542f70
628,974
def ip_range(starting_ip, ending_ip): """ Calculates a list of IPs between two given. :param starting_ip: Range starting IP address :param ending_ip: Range ending IP address :type starting_ip: str :type ending_ip: str :return: list """ # Create a list contaning the ...
6e5f6a4244995dc8460d494ec095859b8f4f2f2c
628,976
def diff_offset(base, diff): """Return the index where the two parameters differ.""" base = base.dump() diff = diff.dump() if len(base) != len(diff): raise ValueError('len(base)=%d != len(diff)=%d' % (len(base), len(diff))) for i in range(0, len(base)): if base[i] != diff[i]: ...
102eea741865a6dd791776c8023df5fbd4885ca6
628,977
def get_license(): """get the license""" return ""
a4df9080f4f4dffe7584d987709200a95f106d1d
628,979
def ensure_list(list_or_scalar): """Convert the input to a list if it is not.""" if isinstance(list_or_scalar, list): return list_or_scalar return [list_or_scalar]
e137404798a5d0d115a3835ca4601bfa0e66bdad
628,980
def remove_templates(text): """Remove all text contained between matched pairs of '{{' and '}}'. Args: text (str): Full text of a Wikipedia article as a single string. Returns: str: A copy of the full text with all templates removed. """ good_char_list = [] prev_char = None ...
97cd95160703aef8e74bbb4134c83eee2b195fa8
628,981
def _find_scalar_and_max_depth(pylist): """Finds nesting depth of scalar values in pylist. Args: pylist: A nested python `list` or `tuple`. Returns: A tuple `(scalar_depth, max_depth)`. `scalar_depth` is the nesting depth of scalar values in `pylist`, or `None` if `pylist` contains no scalars. ...
2e5dda0532d640c0cbb2a2d3169fc92dcc27b8e3
628,982