content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re def create_initials(s): """ Return the initial letter of each word in s, capitalized and strung together Example: John Smith -> JS """ return "".join(s[0] if s else '' for s in re.split(r"[\W_]+", s)).upper()
0e49cd252099bca284d9a9065b1e5ccc7e0dc8bb
616,622
def remove_falses(tup: tuple) -> tuple: """Removes all false occurences from a tuple.""" return tuple([i for i in tup if i])
602571acb30d02651988cbe72f149f5f3fa9d9dd
616,624
def get_single_language(kanton): """ Returns the language given the canton abbreviation for a single canton """ if (kanton == "TI"): return "IT" elif (kanton in ["FR", "VD", "NE", "JU", "GE", "VS"]): return "FR" else: return "DE"
05650364d3c6a3390d06b76ca7521a9aaf9bf988
616,626
def statustoresult(status): """ Convert the status returned from waitpid into a prettier numeric result. """ sig = status & 0xFF if sig: return -sig return status >>8
6db04ce96bae2ab4832f20b209c91981eb6233cf
616,629
def _convert(value, to_type, default=None): """Convert value to to_type, returns default if fails.""" try: return default if value is None else to_type(value) except ValueError: # If value could not be converted return default
d51a61e5e9a59f140bb6f5ad7fe9182c1203223d
616,631
def as_number(as_number_val: str) -> int: """Convert AS Number to standardized asplain notation as an integer.""" as_number_str = str(as_number_val) if "." in as_number_str: big, little = as_number_str.split(".") return (int(big) << 16) + int(little) else: return int(as_number_st...
083171f89b06259e849e49cf0b89b0459bb75ac9
616,632
def jsfunc(value): """Create a safe javascript function name.""" return value.replace('-', '_')
26cc28723539e4a21232150fb145fbf516bffd1c
616,636
def getRequestType(data): """ Returns the HTTP Method type from the given request """ return data[0].decode("utf-8")
e42034762a5e047e9fc76911a121c2eb597e208e
616,637
def alias_diff(refcounts_before, refcounts_after): """ Given the before and after copies of refcounts works out which aliases have been added to the after copy. """ return set(t for t in refcounts_after if refcounts_after[t] > refcounts_before.get(t, 0))
3e18de9767e8baacfa8fb8ed2bd2a212e0694058
616,640
def valid_book_definition(name, author, year, pages): """Does some simple checks on whether the provided arguments are sufficient to defien a book""" if len(name) <= 1: return False if len(author) <= 1: return False try: int(pages) int(year) except ValueError: ...
027cad73baec24ce0cb8a7003356d172192bc4a3
616,644
def look_up_data(input_string, logical_zero, logical_one): """Looks up the input data to determine if the string is a logical one, logical zero, or outside the code base. Parameters ---------- input_string : str data for analysis logical_zero : list list of strings represent...
3f63244b17f28dfb054ca33d09706c112012dd12
616,653
def flatten(target): """Flatten a list with nested lists into a single list. For example:: flatten([1, [2, 3]) # => [1, 2, 3] """ return [item for sublist in target for item in sublist]
524fb908fefeaf6073fd0350daa46384cff907b5
616,655
def get_matrix(filename): """Return a list of lists containing the content of the input text file. Note: each line of the text file corresponds to a list. Each item in the list is from splitting the line of text by the whitespace ' '. """ with open(filename, "r") as f: content = f.readlines...
37d96e91880535b3be7c806abcca7b297e5e256c
616,660
def max_arg_length(arg_list): """Returns the max length of the arguments in arg_list.""" return max([len(x) for x in arg_list])
16505d6159a8884943acf3a7f7429eafc642e883
616,661
def get_minor_matrix(q, i, j): """ Q = [ [1,2,3], [4,5,6], [7,8,9], ] Minor matrix corresponding to 0,0 is [ [5,6], [8,9], ] """ minor_matrix = [] for row in q[:i] + q[i + 1:]: temp = [] for item in row[:j] + row[j + 1:]: ...
f95c8c28ec3d0acc3d21546923a382fd9829369e
616,662
def count(element, seq): """Counts and returns the number of times element occurs in the sequence""" return seq.count(element)
0fc4c368a2b5e21afc49b325c44f4abd0bad07e6
616,663
def break_links(x): """ Break link to x by copying it""" x = x.copy() return x
3187da391c03d88165fe96cfed668081c70d9311
616,665
def clamp(value: float, n_min: float, n_max: float) -> float: """ returns a clamped value between min and max :param value: the value to clamp :param n_min: the minimum value :param n_max: the maximum value Example: >>> clamp(12, 0, 10) >>> 10 """ return max(min(value, n...
9d8d76276c1ffe05f8465dc7cb649fb561d66491
616,667
def load_config_auth(config_parser): """Convert an auth cfparser config into a dictionary :param config_parser: configparser configuration :type paths: class:`configparser.ConfigParser` :return: configuration as a dictionary :rtype: dict """ config = {'github': {'token': config_parser['gi...
17d689791e4077e9b73981b8747ba239781e49ee
616,670
def diff(x): """Differences between subsequent values of a numpy.array""" return x[1:] - x[:-1]
a71d1434637d0da238ae0e462ff1e323f8d19710
616,672
def lonely_integer(a): """Hackerrank Problem: https://www.hackerrank.com/challenges/lonely-integer/problem You will be given an array of integers. All of the integers except one occur twice. That one is unique in the array. Given an array of integers, find and print the unique element. For example, a...
1ea4e2d8bce87b38bde6ce9c26addb7de04e79e6
616,673
from pathlib import Path def get_download_and_data_dirs(notebook="local"): """ Return DOWNLOAD_DIR and DATA_DIR depending on the type of notebook being used. Parameters ---------- notebook : str, optional {'local', 'colab'} The type of notebook you are working in Returns ----...
d5beaa87187056e280b7a6ff448af45c47687feb
616,677
def ignore_this_demo(args, reward, t, last_extras): """In some cases, we should filter out demonstrations. Filter for if t == 0, which means the initial state was a success, and also if we have exit_gracefully, which means for the bag-items tasks, it may not have had visible item(s) at the start, for s...
24f90589e71fdf6da9eb7f2828a67d5d72e99a92
616,680
def encode_query(query, vocabulary): """Takes a textual query and a vocabulary (mapping from words to integers), returns the encoded query in a list. If a word is not in the dictionary, the function returns False. Args: query (list): A textual query vocabulary (dict): Mapping from all wo...
1627856b03eea9a8c8ff230cd4f5b3f8bc8c8f12
616,681
import time def wait_for_workload(client, workload_id, timeout=30): """Wait for a given workload to be active.""" def _get_result(): try: return client.by_id_workload(workload_id)["state"] except KeyError: return "" start = time.time() while _get_result() != "ac...
dac6aec7718649919082e9c210fb3de0c27577a2
616,691
from pathlib import Path def path_to_namespace(path: Path, root: Path) -> str: """ Given a path (in form R/A/B/C) and a root directory R, create a namespace string A.B.C. The path must be located under the root directory. :param path: Path to convert to namespace :param root: Path prefix to remov...
d354504d99c2efe2c81d9f9ab0eef246060493e5
616,693
def newPipe(x, y, w, h): """ Create pipe object """ return { "type": "rectangle", "pos": [x,y], "dim": [w, h] }
2ce581475bd3dda079031577ff9178dd08f5aa9a
616,695
def collapsible_section(title: str, text: str) -> str: """Creates a collapsible section with the given title, and when expanded will show the given text. :param title: The title for this collapsible section :param text: The text to be displayed inside this collapsible section """ return f'<details>...
85dcd53ecc3ad10dec4316b9c8a02e39368ca4e4
616,698
def rotate90(tensor, times): """Rotate tensor clockwise by 90 degrees a number of times. Assumes spatial dimensions are the last ones.""" if times == 1: # 90 deg return tensor.transpose(-2, -1).flip(-1) elif times == 2: # 180 deg return tensor.flip(-2).flip(-1) elif times == 3: # 270 deg return...
1ab42417abde47be4f7ec3ab3886226e6d8a1151
616,699
from typing import List import json def load_train_data(train_data_files: str) -> List: """Load jsonl train data as a list, ready to be ingested by spacy model. Args: train_data_local_path (str): Path of files to load. Returns: List: Tuple of texts and dict of entities to be used for tra...
78f0517c12b04a630d788ded3c56fd926b0990ec
616,700
import mpmath def pdf(x, dfn, dfd): """ Probability density function of the F distribution. `dfn` and `dfd` are the numerator and denominator degrees of freedom, resp. """ if x <= 0: return mpmath.mp.zero with mpmath.mp.extradps(5): x = mpmath.mp.mpf(x) dfn = mpmath.m...
d07113c6c684ba21f53afb733782520e874eef8e
616,701
from typing import Union from pathlib import Path def is_cwd(path: Union[Path, str]) -> bool: """Check whether a path is the current working directory. path (Union[Path, str]): The directory path. RETURNS (bool): Whether the path is the current working directory. """ return str(Path(path).resolve...
314645d38edde161dab55679e071f187ae0eb035
616,705
def listing(items: list[str], separator: str, conjunction: str = "") -> str: """Return human readable list separated by separator. Optional argument is conjuntion that substitutes the last separator. Args: items: list of items. separator: separator of items. conjunction: word/strin...
9c9e1ca8152147129a64df094692034acc0d4676
616,708
def get_measurements(region, core_info, data, extra_offset=0): """ Get the complete measurement info from likwid's region info. Args: region: The region we took a measurement in. core_info: The core information. data: The raw data. extra_offset (int): default = 0 Return...
6b03f342b16ecffd3a914794010ea8fc171cb70e
616,709
def is_value(s): """Test if parameter is a number or can be interpreted as a number""" s = str(s) return s.isdigit() or (len(s) == 1 and s[0] in "AJQK")
cae4960e25a394e3c305c2c715498acf671035af
616,710
import zipfile import io def open_zipfile(archive, filename, directory=None): """Retrieves a given file from a ZIP archive. Args: archive (:obj:`~zipfile.ZipFile`, str): The ZipFile object or path to the ZIP archive containing the desired file. filename (str): The name of the file...
26ca713bebaa90ddcd71007764adb2b5ab49d8d8
616,713
def aggregate_ravens(data, sub_num): """ Aggregate data from the Raven's Matrices task. Calculates various summary statistics for the Raven's Matrices task for a given subject. Parameters ---------- data : dataframe Pandas dataframe containing a single subjects trial data for the ...
35a4f2d1b080d8ddec77e9d42c84eae0463d20d0
616,718
def calculate_total_user_pp(osu_scores: list, member_id: str, osu_tracking: dict): """ Calculates the user's total PP. """ total_pp = 0 for i, osu_score in enumerate(osu_scores): total_pp += osu_score["pp"] * (0.95 ** i) total_pp_without_bonus_pp = 0 for osu_score in osu_tracking[member_id][...
eb23121d29636e62c28e64e7a83fd8c44484b7cb
616,721
def _get_field_value(field_to_get, object_to_search): """ Gets the value of a nested object, for example, if we search 'address.city.neighborhood' in the object: {'address': {'city': {'neighborhood': 'shapira'} } } The returned value will be 'shapira' :param fiel...
becf2e37d7cb8634f71b0d4a3dd36bb7c1f23608
616,748
import json def chk_err_in_payload(json_payload, exc: bool = True): """ Check if there are error(s) indicated in response. :param json_payload: :param exc: Should raise exception if error found. """ err_fields = {'error', 'errors'} for errf in err_fields: if errf in json_payload a...
9062a12249722c71975ba3698f020cae11e7f65e
616,751
import itertools def gen_permutations(names, items, hack=False): """Takes a list of string names and a list of string items. Returns len(name) sized permutations of items. """ if (not hack): p = itertools.permutations(items, len(names)) else: p = itertools.permutations(names, len(i...
b91c922e9de1e9c7f32bd70edfed3238bfa2feb3
616,754
def _calculate_number_rows_plot(n_media_channels: int, n_columns: int): """Calculates the number of rows of plots needed to fit n + 1 plots in n_cols. Args: n_media_channels: Number of media channels. The total of plots needed is n_media_channels + 1. n_columns: Number of columns in the plot grid. ...
770b83c1b5e171b31e21828f947abea8216354ba
616,755
def reporting_date(submission): """Format submission reporting date""" if not (submission.reporting_start_date or submission.reporting_end_date): return None if submission.is_quarter_format: return 'Q{}/{}'.format(submission.reporting_fiscal_period // 3, submis...
c9bd16b2fcb810c99d1c25b27f39f0368cbb89cd
616,762
def add_parameter_group_to_list_of_dicts( Dlist, names, values ): """ Copies and returns the given list of dictionaries but with names[0]=values[0] and names[1]=values[1] etc added to each. """ assert len(names) == len(values) N = len(names) new_Dlist = [] for D in Dlist: newD ...
2d70e8cb9c42985819b3272e150ef6543ad3c85f
616,764
def unset_bit(string: int, pos: int) -> int: """Return bitstring with the bit at the position unset Args: string (int): bit string pos (int): position in the bit string Returns: int: string with the pos bit set to 0 """ return int(string) & ~(1 << pos)
10c3ae77a19a9323758e5679f358c0f55c19c962
616,765
def _get(item_id, items, id_key): """Get item from list with given ID.""" return next(item for item in items if item[id_key] == item_id)
1bdeff82a3e4d0ebe08d6eff2f37c5aa9d65c755
616,767
import string import random def flaskify_endpoint(identifier, randomize=None): """ Converts the provided identifier in a valid flask endpoint name :type identifier: str :param randomize: If specified, add this many random characters (upper case and digits) to the endpoint name, separated by a...
955239f7b3d79bba167e5a0c96907d9d126f3e1e
616,768
def extract_best_aligns(aligns_df): """Extracts alignments with highest score from the provided alignments dataframe. """ mask = aligns_df.groupby('seq_index').agg({'score': 'idxmax'}) # get /!\ FIRST /!\ index of max align score for each sequence aligns_df_best = aligns_df.loc[mask['score']].rese...
a7b512631a96c87380a20bea90dd2228ea020396
616,769
import math def haversine(p1, p2): """Calculate the distance between two (degree) longitude/latitude points in meters""" lon1, lat1 = p1 lon2, lat2 = p2 # Earth radius in meters R = 6371e3 # φ, λ in radians φ1 = lat1 * math.pi / 180 φ2 = lat2 * math.pi / 180 Δφ = (lat2 - lat1) *...
949d63337609a324ad8278045ef1a16ff2437a98
616,770
def ones(m,n): """Return an m-by-n arrayList consisting of all ones. >>> ones(2,3) [[1, 1, 1], [1, 1, 1]] """ return m * [n * [1]]
051aef43731f959c71918445c63c433b62b80efa
616,771
def get_data_mask_functions(is_micro): """ Returns the data mask functions. ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50) Table 10 — Data mask pattern generation conditions (page 50) =============== ===================== ===================================== QR Code Pattern...
48b7554422ee5fbe28ad66fbc45cde2929c36317
616,772
def score_ap_from_ranks_1(ranks, nres): """ Compute the average precision of one search. ranks = ordered list of ranks of true positives nres = total number of positives in dataset """ # accumulate trapezoids in PR-plot ap = 0.0 # All have an x-size of: recall_step = 1.0 / nres f...
ad249838201c7ad1eb61f3b0b348a6e9db773563
616,773
import math def calc_prob_prior(iterations, lam): """ Calculates the alpha prob for the mixture as $$\alpha_i = \exp(-ki), \quad i = 0,1,\ldots,iterations$$ :param iterations: nbr of iterations for SPA :param lam: decay rate :return: list of length iterations with the prob. for prior in the...
f6144dcf0385a800cb5e9eaeb01e8b1e83970869
616,775
def are_relatively_prime(a, b): """Return ``True`` if ``a`` and ``b`` are two relatively prime numbers. Two numbers are relatively prime if they share no common factors, i.e. there is no integer (except 1) that divides both. """ for n in range(2, min(a, b) + 1): if a % n == b % n == 0: ...
f3f98b43a27f6da219e0c68f9da55df0a2774bde
616,781
import re def find_and_replace(items, updates): """ aka find_and_replace apply all updates in updates list to all items in items list updates consist of a list of lists where the sub lists contain: (search_string, replace_string) """ for u in updates: search_string = u[0]...
57f6f9ed15feb306584fd217d5b062307f2e6aac
616,783
def filter_length(d, n): """Select only the words in d that have n letters. d: map from word to list of anagrams n: integer number of letters returns: new map from word to list of anagrams """ res = {} for word, anagrams in d.items(): if len(word) == n: res[word] = anagra...
9d05600550d4c238be31266cf6b059cc4e51386c
616,785
def dict_to_sorted_pairs(d): #=============================================================================== """ Convert a dictionary to a list of key/value pairs sorted by key. """ keys = list(d.keys()) keys.sort() results = [] for key in keys: results.append((key, d[key])) ret...
1a2942ae59ca98a5427c53ffe4a941b0d946d7d4
616,789
def query_starts_with(formatted_sql, prefixes): """Check if the query starts with any item from *prefixes*.""" prefixes = [prefix.lower() for prefix in prefixes] return bool(formatted_sql) and formatted_sql.split()[0] in prefixes
8cc796222f379f7ac2ba6d9e101c39d22005bc89
616,795
def to_readable(src: int, unit: str = "bps") -> str: """ Convert number to human readable string. For example: 1,000,000 bps to 1Mbps. 1,000 bytes to 1KB :parameters: src : int the original data unit : str the unit ('bps', 'pps', or 'bytes') :returns: ...
2c27743d65b04239257b0f5f779d1bdbc4f8ead4
616,797
def ask_multi_lines(prompt="Type :", escape_string="."): """Get input from user provided multilines Keyword Arguments: prompt {str} -- the question message (default: {"Type :"}) escape_string {str} -- escape character (default: {"."}) Returns: str -- the text seperated by l...
54967fe4ca926ae2d7717a54bdebe9f9c904d85c
616,799
import string def load_phrases(filename): """Load phrases from file and strip punctuation characters.""" f = open(filename, 'r') punctuation_table = str.maketrans({key: None for key in string.punctuation}) phrases = [line.lower().rstrip("\r\n").translate(punctuation_table) for line in f] f.close() return phrase...
7f064d2e3e73dccefd4085520713503c0c94f846
616,801
def is_uvular(sound): """ Check if a sound is uvular or not. """ return sound.obj.place == "uvular"
97e2d08975624576dd8b6c375a2a4241fdc48162
616,802
from datetime import datetime def short_time(t=None): """ Time used in printed messages """ if t is None: t = datetime.now() return str(t.strftime("%H:%M:%S"))
167eb1a60c8b7c6ad7693f607ed7787a80ec401c
616,806
def is_number(num): """ Determine whether a string s is a number (i.e., any floating point representation of a number, including scientific notation) """ try: float(num) return True except ValueError: return False
aa0490bc9f3382ecadcce998cadb46b8556ad7f4
616,808
import torch def swish(tensor): """ Swish activation is simply f(x)=x⋅sigmoid(x) Paper: https://arxiv.org/abs/1710.05941 """ return tensor * torch.sigmoid(tensor)
55ee7040a985d63e4869fd2c964172039a3efca3
616,810
def seqid_to_filename(seqid): """ Makes a sequence id filename friendly. (eg, replaces '|' with '_') """ return seqid.replace("|", "_")
84a3220e2dc2d9b0dd4fd903dd7fa5055f88d39a
616,812
def needs_update(source, target): """Return True if a file does not exist or is out of sync :param pathlib.Path source: Source path :param pathlib.Path target: Target path """ if target.exists() and target.lstat().st_mtime == source.lstat().st_mtime: return False else: return Tr...
3b1f92ed8d7b59488ecebe47082ae5d0eaa89d3d
616,813
def norm(value, start, stop): """ Interpolate using a value between 0 and 1 See also: https://processing.org/reference/norm_.html """ return start + (stop-start) * value
f98b9705a182de92105a0cf7ff51f305b952c301
616,816
def get_viewconf_status(files): """ Determine the Higlass viewconf's status based on the files used to compose it. Args: files(list) : A list of file objects that contain a status. Returns: A string. """ # The viewconf will be in "released to lab" status if any fil...
873bbbb50082236e01a96ed6207e853e20e22ef9
616,817
def dict_to_json_keys(pydict: dict) -> dict: """this converts a dict using the python coding style to a dict where the keys are in JSON format style :pydict dict keys are strings in python style format :returns dict """ d = {} for key in pydict.keys(): new_key = key.title().replace('...
cf13453d16a3e90bbd974d7c2352221165765f5c
616,820
import re def tokenize(line): """Normalizes and tokenizes a line from a .tess file Capital letters are changed to lowercase, line numbering and extraneous whitespace is removed, and the result is given as a list of tokens. The tokenizer is intended to be applied to a line from a .tess file a...
88b2d0ab370555e39fea7684ca2266661632fbee
616,821
def mag_to_flux(catalog, mag_col, zeropoint=27.0, update=True): """ Convert AB magnitude into HSC image flux unit. """ flux = 10.0 ** ((zeropoint - catalog[mag_col]) / 2.5) if update: flux_col = mag_col.replace('mag', 'flux') if flux_col in catalog.colnames: catalog.remov...
a5e52431b926e89739ad4ae1f708755560a6e843
616,822
import string def _expand_wildcard(expr: str, num_wildcard_dims: int) -> str: """Replaces a wildcard with the correct number of axes. Args: expr: Shape expression containing '...'. num_wildcard_dims: Number of dimensions captured by the wildcard. Returns: Copy of `expr` with the wildcard '...' rep...
5cfc8d0ffd2086112c43e65b7e3bb1be0edb7f15
616,823
def calculate_chunks(dataset): """ For the given dataset, calculate if the size on any dimension is worth chunking. Any dimension larger than 4000 will be chunked. This is done to ensure that the variable can fit in memory. Parameters ---------- dataset : xarray.Dataset The dataset ...
f1ec289c9fe4284b15c40677b14abe1d1dabb180
616,824
def recursive_sort(v): """Recursively sort a nested python objects of lists, dicts, strings, ints, and floats """ def sort_key(v): if isinstance(v, (list, dict, tuple)): return str(type(v)) return f"{type(v)}-{v}" if isinstance(v, dict): sorted_keys = sorted(v....
5ad746b9aba24d99bb1b8694a89a0b54ae474ded
616,828
def wordgen(iters, base_cases, rule, return_all=False): """generate arbitrary recursive words Args: iters (int): number of iterations to run on top of base cases base_cases (list of strings): strings which your rule can refer to rule (method): A function that takes in previous strings a...
942a0ccc731af0d6ad090868e971a520686b8009
616,830
def get_headers(data): """Loop through the data and collect any headers. :param data list[dict]: :rtype: set[str] :returns: set of headers """ return {k for row in data for k, _ in row.iteritems()} if data is not None else None
2dc96ec2b34e7ff558a5c7d42a890db2c7f60274
616,832
def can_import_module(module_name): """ Check if the specified module can be imported. Intended as a silent module availability check, as it does not print ModuleNotFoundError traceback to stderr when the module is unavailable. Parameters ---------- module_name : str Fully-qualifie...
aefb5320074f1e1917efb7b2858dc8e600476ba2
616,834
def geo_db_path(type): """ Returns the full path of a specific GeoLite2 database Args: type (str): The type of database path to retrieve (ASN, City, Country) Raises: ValueError: An invalid database type has been provided Returns: str: The absolute path to the specified dat...
8c0fa54e902013129230bd11cf858553ef256d9f
616,839
def get_action_value(mdp, state_values, state, action, gamma): """ Computes Q(s,a) as in formula above """ q_value = 0.0 for next_state in mdp.get_next_states(state,action): q_value += (mdp.get_transition_prob(state, action, next_state)* (mdp.get_reward(state, action,next_state) + gamma*stat...
d1f113203dc04542ddaeea85950caefb3c32ee2e
616,841
def channels_to_last_dim(X): """ Takes a signal with channels on the second dimension (for convolutions) and returns it with channels on the last dimension (for most operations). """ return X.permute(*([0] + list(range(2, X.dim())) + [1]))
171113478bd5f7279b724390c2b57a86a088456b
616,843
def lzip(*args): """ zip(...) but returns list of lists instead of list of tuples """ return [list(el) for el in zip(*args)]
b0f7ff5f54ab8c7fe69b9a5276e33150280601a3
616,844
import click def _style(enabled, text, **kwargs): """ Helper function to enable/disable styled output text. Args: enable (bool): Turn on or off styling. text (string): The string that should be styled. kwargs (dict): Parameters that are passed through to click.style Returns: ...
2c4deb098955c3d574c5f41f20e654cbfb5eb919
616,850
def RerouteTensor(t0, t1, can_modify=None): """Reroute the end of the tensor t0 to the ends of the tensor t1. Args: t0: a tf.Tensor. t1: a tf.Tensor. can_modify: iterable of operations which can be modified. Any operation outside within_ops will be left untouched by this function. Returns: ...
e74e5d7b77d406d1987c74e02c5c739a35fa7295
616,851
def isiterable(o): """ Return True if the given object supports having iter() called on it BUT is not an instance of string. Otherwise return False. """ if isinstance(o, (str, bytes)): return False try: iter(o) except TypeError: return False else: return...
6577933baf41218364d8f47fec8b4e3c5854c6da
616,854
def message_context_from_workflow_context(ctx): """Build a message context from a CloudifyWorkflowContext instance""" return { 'blueprint_id': ctx.blueprint.id, 'deployment_id': ctx.deployment.id, 'execution_id': ctx.execution_id, 'workflow_id': ctx.workflow_id, }
64eaa82307834500856c347c1a442a32a4dcaee8
616,855
def generate_relating_lines(input_field, output_field, function_name, field_prefix=""): """ Generates lua lines that checks other fields related to input_field for feature engineering :param input_field: original censys field :param output_field: flattened version of censys field :param function_na...
406e857b8ebf1ece6ec0515c0fb7a6565e6c82e8
616,860
def _pbkdf1(hash_alg, passphrase, salt, count, key_size): """PKCS#5 v1.5 key derivation function for password-based encryption This function implements the PKCS#5 v1.5 algorithm for deriving an encryption key from a passphrase and salt. The standard PBKDF1 function cannot generate more key by...
2d1b72ebc1264caaf6ef8bb9d794bcef1cc67398
616,863
import calendar def _calculate_meeting_days_per_month(chosen_weekday, chosen_ordinals, year, month): """ Lots of city meeting websites describe their upcoming meetings by saying things like: "this committee meets the 1st and 3rd Tuesday of every month". This calculator is intended to help parse dates ...
319b8f2474ab79bc48c2e0d3ac9d1309be1af933
616,865
def strip_quotes(data): """ Strips whitespaces and then quotes (single or double) at both sides of data. :param data: string :return: dict: 'value': everything inside single or double quotes, 'error': empty string if no errors or 'syntax' if quote at the beginning has no matching ...
9509fe536403059dc21c7cce5a5dc56aa42b2a15
616,868
def list_from_file(file): """ Returns a list of tuples object based on a file of pipe-delimited key/value pairs """ l = [] with open(file) as f: for line in f: if not line.startswith('#') and line.strip(): line = line.strip() (key, val) = line.split('|')[:...
0b34e46da6a7ba6f234bcb871c823f7accf1c111
616,872
def normalize_title(title: str) -> str: """Normalize the wikitext article title by handling special characters.""" return title.replace( '@-@', '-').replace('@,@', ',').replace('@.@', '.').replace(' ', '')
906ce9cd1b123ff11d62187c56d2d7b389bd70f1
616,878
import json def json_dumps(value, **kwargs): """ Serializes an object as JSON. Optionally given keyword arguments are passed to json.dumps(), ensure_ascii however defaults to False. """ kwargs.setdefault('ensure_ascii', False) return json.dumps(value, **kwargs)
41c4c3865bb43e0f680cecec8e4075f31bf69f44
616,883
import hashlib def gen_gravatar(s, size=200): """Return URL for gravatar of md5 of string ``s``""" h = hashlib.md5(s).hexdigest() return ('http://www.gravatar.com/avatar/{0}.jpg' '?d=identicon&f=y&s={1}'.format(h, size))
2d7fd4a881fcf09a6f1d3cb025fcf8717b7635cd
616,891
import re def ref2equations(filestr): """ Replace references to equations. Unless "Equation(s)" already precedes the reference, the following transformations are done: (ref{my:label}) -> Equation (my:label) (ref{my:label1})-(ref{my:label2}) -> Equations (my:label1)-(my:label2) (ref{my:label1}...
a47547c9ca1cdccaa4bd2074e8bbd06c78c3a1d1
616,896
def make_columns(image, size): """ Processes an image and makes a list containing all one-pixel wide columns of the image. Parameters ---------- image : PIL Image File The image to be processed. size : (int, int) The dimensions of the image. Returns ------- lis...
878a84f97b431d09ba232dcb754490fb08d51b6b
616,902
def fib_table_for(n): """ Returns: fibonacci list [a0, a1, ..., an] Parameter n: the position in the fibonacci sequence Precondition: n >= 0 is an int """ if n == 0: return [1] # if for n==1 is unnecessary fib = [1,1] for k in range(2,n): fib.append(fib[-1] ...
8414d4894fff10e78130252ba74bc716cf4b1755
616,905
def gasKgKgDryToMoist(q,qh2o): """ Take Kg/Kg dry air to Kg/Kg moist air. """ r = q/(1+qh2o) return r
144f1bf285a79f51cf62cabbb509f572c8b9cb8d
616,906
def add_zero_to_age_breakpoints(breakpoints): """ append a zero on to a list if there isn't one already present, for the purposes of age stratification :param breakpoints: list integers for the age breakpoints requested :return: list age breakpoints with the zero value included """ ...
ac22762439ef294a6d5abc357c17dbda88230266
616,907
import requests def has_backoff(response: requests.Response) -> bool: """Check if response sets the `backoff` field. Args: response: HTTP response. Returns: True if the response contains a rate limiting backoff amount. """ try: return "backoff" in response.json() exce...
f37703d529ead7e69de0daad50f59b0c46195193
616,909