content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def begin(stacklogger): """Log the default begin message""" return stacklogger.log()
c934693d83c32715c73a44b440b8fbab55cea919
649,004
import struct def int2bytes(i): """ Convert int to bytes. :param i: 32 bit integer inside range -2147483648, 2147483647 :return: 4 bytes """ if not isinstance(i, int): raise TypeError("i must be int") return struct.pack("i", i)
56ac6d09ce065c0446555ce513e4508e0e3e6d94
649,012
def build_speechlet_response(output, card_title=None, card_content=None, reprompt='', should_end_session=True): """ Contructs ``response`` dictionary with the proper struture to allow Alexa to talk to the user. Optionally takes ``card_title`` and ``card_content`` to build ou...
875ff03bd6bd3e346bb7168591aaf8cd09a7496c
649,013
def format_number(num: float) -> str: """ Format strings at limited precision :param num: anything that can print as a float. :return: str I've read articles that recommend no more than four digits before and two digits after the decimal point to ensure good svg rendering. I'm being generous a...
26bb37ab8b417a44c53c2b1c3b14961075472d0c
649,020
def get_attribute_values(elements,name): """ returns a list of attributes 'name' from a list of elements """ attribute_values = [] for element in elements: attributes = element.attributes for n in range(attributes.length): attribute = attributes.item(n) if attribute.n...
953ae221b0dd88812fc9b59e5dc86add9d9ededb
649,022
def _get_request(context): """ Fetch the request from the context. This enforces the use of the template :class:`~django.template.RequestContext`, and provides meaningful errors if this is omitted. """ assert 'request' in context, "The fluent_pages_tags library requires a 'request' object in the...
f710014c47e32bafc06ec4da20284f1c04e4862b
649,023
def vals_are_multiples(num, vals, digits=4): """decide whether every value in 'vals' is a multiple of 'num' (vals can be a single float or a list of them) Note, 'digits' can be used to specify the number of digits of accuracy in the test to see if a ratio is integral. For example: ...
3ffc25020c87c41a1b2d678b71081d73d7613874
649,024
def parse_callback(callback, reduce=True): """ Parses callbacks for CellRenderers: it splits the callback from its arguments if present. Additionally this method will not create singleton argument lists, but pass them as a single argument. Returns the callback and its argu...
b925a0e82ee8046e48594fb6f8a99a5aaa017ded
649,029
def _ComputeIpv4NumHosts(network_size): """Derives the number of hosts in an IPv4 network from the size. """ return 2 ** (32 - network_size)
64733cc341f5eb0772a7d2df1753f6f67ac3f7f8
649,030
def linear(u, v, d): """ Linear interpolation. Args: u (float) v (float) d (float): the relative distance between the two to return. Returns: float. The interpolated value. """ return u + d*(v-u)
ab92ed03b61ac902dcec1630b41dd317b11efc3a
649,032
import pickle def read_pickle(filename): """ Function that reads pickled data and returns it in memory INPUTS: filename (str): name of pickle file to be read OUTPUTS: unserialized_data (?): data read from pickle file, can be nearly any form """ with open(filename, 'rb') as handle: unserialized_data ...
9ad5b81f5217ac4e4a205d71027bc50919fa47d4
649,034
def str_to_bytes(string): """Encode a string in bytes.""" return string.encode("utf-8")
04b62d54b59dceadcda9b137e08f327ec7805170
649,035
def in_polygon(x, y, vertices): """ Determine if a point (x,y) is inside a polygon with given vertices Ref: https://www.eecs.umich.edu/courses/eecs380/HANDOUTS/PROJ2/InsidePoly.html """ n_pts = len(vertices) i = 0 j = n_pts - 1 c = False while i < n_pts: if ( # ...
d0250dc1bf43f5f3a40323565a6b9f47b3d98c66
649,036
import base64 def bytes_to_b64str(data_bytes) -> str: """Convert binary to base64-encoded string.""" encoded_bytes = base64.b64encode(data_bytes) return encoded_bytes.decode("ascii")
64d098db96391a9749d36f9953b9e9b4b00750c6
649,037
def prepare(data): """Restructure/prepare data about merges for output.""" sha = data.get("sha") commit = data.get("commit") message = commit.get("message") tree = commit.get("tree") tree_sha = tree.get("sha") return {"message": message, "sha": sha, "tree": {"sha": tree_sha}}
ec5d5a2e6ee5613e0970716083f341d503b95db9
649,044
def lin_func_2(pars, xvals): """Return quadratic function of the form pars[0]*x + pars[1]*x*x""" return pars[0]*xvals + pars[1]*xvals*xvals
c8d91302a3f542a46fffc5b5b92dc4646215d6cf
649,050
import random def random_bdays(n): """ Returns a list of integers between 1 and 365, with length (n) """ t = [] for i in range(n): bday = random.randint(1, 365) t.append(bday) return t
682b4a1928f3199772b608267bd236670295ef31
649,051
def get_category(output, categories): """ Return the most probable category/language from output tensor. """ top_n, top_i = output.data.topk(1) category_i = top_i[0][0] return categories[category_i], category_i
d3ac9534f2b92ba43ab33c446017015665376609
649,053
def len_str_list(lis): """returns sum of lengths of strings in list()""" res = 0 for x in lis: res += len(x) return res
789d670b0bbf0dd5ee270e2d00c0047eba3f8b7e
649,055
def safe_get_key(dictionary, keys, default): """ Examples -------- >>> d = dict(a=2, b=2, c=dict(d=12, e=45, f=dict(g=32))) >>> safe_get_key(d, 'a', 1) 2 >>> safe_get_key(d, ['a'], 1) 2 >>> safe_get_key(d, ['asdf'], 1) 1 >>> safe_get_key(d, ['c', 'f', 'g'], 1) 32 >>> ...
981f882e7aed3bf7643b1cb1335ddca7fc98bc16
649,059
def create_partitions(aut, partition_list, state_function, obs_events): """ Compute the fixed point of the partioning. @param aut: Automaton being partioned. @type aut: L{BaseAutomaton} @param partition_list: Initial state partitions. @type partition_list: C{list} of C{set} of L{State} ...
a762729601b07bcb433127205fd225904a132b74
649,061
def _denormalize_to_coco_bbox(bbox, height, width): """Denormalize bounding box. Args: bbox: numpy.array[float]. Normalized bounding box. Format: ['ymin', 'xmin', 'ymax', 'xmax']. height: int. image height. width: int. image width. Returns: [x, y, width, height] """ y1, x1, y2, x2 = bb...
49545db2914dd52657eceb4dcd94207f29050ae8
649,063
def health() -> dict: """Health Check for the server. Returns: dict: Health status in a dictionary. """ return {'Message': 'Healthy'}
90a8184b6d689d236dbfe7c50f33c8de10411222
649,066
def _parse_redis_connection(connection): """ Parse redis connection to host, db :param connection: redis connection :return: host, db """ connection_kwargs = connection.connection_pool.connection_kwargs return ( connection_kwargs.get('host', 'local'), connection_kwargs.get('p...
171e2eeeb9eb9e2ec9719a16d4dec68ac4ba9ef1
649,068
from typing import Iterable from typing import List def _fmt(a: Iterable) -> List[str]: """Formats each element in `a` into strings. Args: a (Iterable): Iterable. Returns: List[str]: Returns a list with the formatted elements. """ return list(map(lambda a: f'{a:.3f}', a))
59add8462a3e41faecfcc5e0abcbc122ff669e05
649,070
def subset_data(data, col): """ Creates list of categories for column used to populate dropdown menus :param data: pd.DataFrame generated from app_wrangling.call_boardgame_data() :param col: string, column generate list for :return list(exp_series.unique()): list of strings """ ...
718292c77bc35af33164c6176ec065df4f01dc32
649,074
def lines_to_list(infile): """ put all words in a file into a list """ nested_list = [line.split() for line in infile] # nested_list = [] # for line in infile: # nested_list.append(line.split()) flat_list = [item for inner_list in nested_list for item in inner_list] # flat_list = [] ...
1398bd382a29f7187773074fa08b8e14b2b31f9e
649,075
def _1(value): """ Integer decoder. ```python >>> from Tyf import decoders >>> decoders._1((1, )) 1 >>> decoders._1((1.0, "6", 0b111)) (1, 6, 7) ``` """ return int(value[0]) if len(value) == 1 else tuple(int(v) for v in value)
a2882998bce36cbb6e7a258bb469944d4bd46f99
649,077
import re def normalize_newlines(string): """Adjust all line endings to be the Linux line break, \\x0a.""" return re.compile("\x0d\x0a|\x0d").sub("\x0a", string)
971fd278732a043ead47e765a6845862a12c485b
649,084
def parse_years(year_range): """Parse year_range into year list. Args: year_range: A string in the format aaaa-bbbb. Returns: A list of years from aaaa to bbbb, including both ends. """ st, ed = year_range.split("-") st, ed = int(st), int(ed) return [year for year in range(st...
836c1108df2451ae16042382a5c7988875487a6a
649,085
def kebab_to_snake(name: str) -> str: """Convert `name` from kebab-case to snake_case.""" return name.replace("-", "_").lower()
7b0d4217a4c85294bf2b6c546387ad05b7eb8fdd
649,086
def tail1(filepath, n): """Similate Unix' tail -n, read in filepath, parse it into a list, strip newlines and return a list of the last n lines""" with open(filepath) as f: return [line.strip() for line in f.readlines()[-n:]]
f094e7453e153bd4ed84e9eea705659a10d3e58b
649,087
def is_a(x, n=None): """ Check whether a list is a non-decreasing parking function. If a size `n` is specified, checks if a list is a non-decreasing parking function of size `n`. TESTS:: sage: from sage.combinat.non_decreasing_parking_function import is_a sage: is_a([1,1,2]) ...
2a58f73870b7eaac037f0a974421200fe8cbcebc
649,088
from typing import Any def bytes_to_string(obj: Any): """ Converts a bytes object into a string :param obj: Any type of object :return: If the object is of type bytes it returns it's string representation, else returns the object itself """ if isinstance(obj, bytes): return obj.dec...
692da29496f71fcbc100625d9c1e9bf95f8d5da9
649,090
import functools def accumulate( items, func=lambda x, y: x + y): """ Cumulatively apply the specified function to the elements of the list. Args: items (iterable): The items to process. func (callable): func(x,y) -> z The function applied cumulatively to the f...
deed252b22eb225ae58535c4b0bcc3571a139917
649,093
def _center_to_coco_bbox(bbox): """ from center format to (tlx, tly, w, h) :param bbox: :return: """ tlx = bbox[0] - bbox[2] / 2 tly = bbox[1] - bbox[3] / 2 return [(tlx), (tly), (bbox[2]), (bbox[3])]
3562de01e117b9ccd435f584f1bf8f2a5b1382e6
649,094
def capitalize_header(key): """ Returns a capitalized version of the header line such as 'content-type' -> 'Content-Type'. """ return "-".join([ item if item[0].isupper() else item[0].upper() + item[1:] for item in key.split("-") ])
9cdb9b8e3fba451a5dccaaab2196780fc6387472
649,098
def complement_strand(dna): """ Finds the reverse complement of a dna. Args: dna (str): DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T'). Returns: str: the reverse complement string of a dna. """ reverse_complement = "" for character in dna[::-1]: ...
6e54664d9b7cacf8ac07b99129bb27eacea3e9e1
649,101
def get_grouping_from_another_yang_model(yang_model_name: str, conf_mgmt) -> list: """ Get the YANG 'grouping' entity Args: yang_model_name - YANG model to search conf_mgmt - reference to ConfigMgmt class instance, it have yJs...
31d6fcfbafe4e8c7a0da73a0909b33017976c602
649,102
def create_device_name(tracked_asset_pair: str) -> str: """Create the device name for a given tracked asset pair.""" return f"{tracked_asset_pair.split('/')[0]} {tracked_asset_pair.split('/')[1]}"
91e84665ae9eb405cb8dd0d6db249f9809bed450
649,103
def to_std_dicts(value): """Convert nested ordered dicts to normal dicts for better comparison.""" if isinstance(value, dict): return {k: to_std_dicts(v) for k, v in value.items()} elif isinstance(value, list): return [to_std_dicts(v) for v in value] else: return value
0dd423df87438d745782477b8ea1471a8b196c2a
649,106
def process_param(param, offset): """Process a single parameter produced by `get_function_parameter_names`.""" # Ignore args with default values, since Rope considers them assignments. if "=" in param: return [] # Strip off any type annotation. first_colon_index = param.find(":") if fir...
15ac5d71f9d3deefd218ccaa9d2d93085d673aeb
649,108
def reformat_replace_star_list_with_dash_list(text): """ Replaces bullet lists starting with `*` with the lists starting with `-` :param text: Original text :return: New text without `*` bullet lists """ lines = text.split('\n') new_text = '' for line in lines: if line.strip().s...
d80d1abae6c54daecabf9434e083ec3abd24bcc3
649,111
def ec_list(mod): """ Retuns a list of elasticity coefficients of a model. The list contains both species and parameter elasticity coefficients and elasticity coefficients follow the syntax of 'ec_reaction_sp-or-param'. Parameters ---------- mod : PysMod The Pysces model contains t...
fe78578aea738e1da379ec9736634d24095b1715
649,112
def get_spec_padding(ispec, nspec, bundlesize): """ Calculate padding needed for boundary spectra Args: ispec: starting spectrum index nspec: number of spectra to extract (not including padding) bundlesize: size of fiber bundles; padding not needed on their edges returns specmi...
10a7d90e903ea2a7d4c5a6be328d028cb2a7241a
649,115
from typing import Dict from typing import Any def remove_unused_flags(user_calc_params: Dict[str, Any]) -> Dict[str, Any]: """ Removes unused flags in the INCAR, like EDIFFG if you are doing NSW = 0. Parameters ---------- user_calc_params User-specified calculation parameters Return...
6772212ab5ab398bc0db750219d98f6489dbcd08
649,121
def bBalancedPar(p): """check if parenthesis are balanced no matter the content""" l = 0 for c in p: if c == ord(b"("): l += 1 elif c == ord(b")"): l -= 1 if l < 0: return False if l != 0: return False return True
9480891316cc9661afdaae5bf1a76915d712e34f
649,123
def unary_plus(op): """:yaql:operator unary + Returns +op. :signature: +op :arg op: operand :argType op: number :returnType: number .. code:: yaql> +2 2 """ return +op
75ff2254d46f7d72a1b27c2e9df9e56556a3f32c
649,125
from typing import Mapping def delimited_file_to_dict(path : str, delimiter : str=',') -> Mapping[str,str]: """ Returns a dictionary populated by lines from a file where the first delimited element of each line is the key and the second delimited element is the value. ...
7687dfc0e59462455f8b90877d5232a342a6c789
649,127
def pil_coord_to_tesseract(pil_x, pil_y, tif_h): """ Convert PIL coordinates into Tesseract boxfile coordinates: in PIL, (0,0) is at the top left corner and in tesseract boxfile format, (0,0) is at the bottom left corner. """ return pil_x, tif_h - pil_y
86e2bfd1a49875613234d3cd489ed7b1a90e041e
649,128
def sort_fractions_by_denominator(fractions): """ The function takes a list of `Fraction` objects as its argument. It returns a list of the fractions sorted by its denominator. Use a lambda expression for the key function. For example, INPUT: [1/2, 3/4, 2/3] OUTPUT: [3/4, 2/3, 1/2] """ ...
45f9dac8e4c55a8a9edc1839e9e870c501beff82
649,129
import requests import time def get_mac_address_vendor(mac_address: str, retries: int = 10) -> str: """ """ # Can also use https://macvendors.co/api/{mac_address} for a richer payload prefix = ''.join(mac_address.split(':')[0:3]) response = requests.get(f'https://macvendors.com/query/{prefix}') ...
d683815e371469722068940e229d03f077cf440f
649,131
def fixture_env_name() -> str: """Get the name of a testing environment""" return "D_marshmallow"
a9e7be55f21b5cec725fd01eeb636b18e6a7b713
649,133
def get_optimizer(dataset_name): """ Arguments --------- dataset_name (str): name of dataset being trained Returns ------- optimizer (dict): parameters defining the optimizer to use during training. """ if "noscope" in dataset_name: # We use...
51b5c8f745f093868c30b5ce0249195ef0d11209
649,134
def get_training_status(api, cfg, job_id, model_name): """ Gets the status of the given training job id Arguments : api : object, API object to access CloudML Engine cfg : dict, Configurations from yaml file job_id : string, Job ID of the training job model_name : string, Na...
e985fd66115cf86c76172557515e53bb8ab9d10e
649,135
def grazing(vs, eaten, zooplankton): """Zooplankton grows by amount digested, eaten decreases by amount grazed""" return {eaten: - vs.grazing[eaten], zooplankton: vs.grazing[eaten]}
9e955c3cc16e00f8fffd9ef210093ecd82ac11df
649,138
def normalize(lines: str) -> str: """ Remove trailing whitespace from each line, keeping all line breaks except the last.""" return '\n'.join(line.rstrip() for line in lines.strip().splitlines())
d90c7f2ce3ac4cbe2c3318df260a88d6ffdd0075
649,140
from typing import Dict from typing import Tuple def dense_dict(dictionary: Dict, removables: Tuple = (None,)) -> Dict: """Return a dictionary ignoring keys with None values, recursively.""" return { k: dense_dict(v) if isinstance(v, dict) else v for k, v in dictionary.items() if v not...
10c160d1d2acf364ffce8e4da8b83e099a8de450
649,143
def combine_lines(components, element_list, background): """ Combine results for different lines of the same element. And also add pileup, userpeak, background, compton and elastic. Parameters ---------- components : dict output results from lmfit element_list : list list of...
6c2498eb0886e096cf6ddf0a5e990936ea8dade6
649,144
def alg_int(u, v): """ Given two slopes, compute their algebraic intersection number. """ a, b = u c, d = v return a*d - b*c
7d75b0a2464f3e28c31a43b9ff9142386082fe82
649,146
import torch def bound_and_scale(scale, bounds): """ Combination of scaling and bounding Args: scale (torch.tensor): divide input by this value bounds (torch.tensor): tuple, clamp to (bounds[0], bounds[1]) """ return lambda x: torch.clamp(x / scale, bounds[0], bounds[1])
63e2ca0c3c135c98bf14bbe159dc2615b756f337
649,150
def nexus_infile(myid,itwist): """ nexus style input name Args: myid (str): prefix itwist (int): twist index Returns: str: input filename """ prefix = myid.split('.')[0] infile = '.'.join([prefix,'g%s'%str(itwist).zfill(3),'twistnum_%d'%itwist,'in','xml']) return infile
ac3c2482d2fb572ad994241fe2e944c9a74448ba
649,153
def flip_subarray_params(input_params): """ Helper function to switch the row and column entries in a SUBARRAY tuple """ assert isinstance(input_params, (tuple,list)) assert len(input_params) == 4 output_params = [input_params[1], input_params[0], ...
5d30f3c1f5c2b3601f3e8cab65b0d1061d4e920e
649,154
def count(catalog): """Given a Catalog, return the number of strings actually translated.""" translated = [m for m in catalog if m.string] return len(translated)
0cbc7074423a9ea9a19f61a3e16e25821527576c
649,159
def _parse_user_ids(users, client): """parse a string of users separated by commas into IDS""" ids = [] split_users = users.split(',') for u in split_users: u = u.strip() if len(u) > 0: uid = client.users.list(query=u) if uid: ids.append(uid[0]['id...
9603d964d6567efcd0150f365da0991472e19b82
649,175
import socket def IPv4(ip_addr): """ Validate a string as an IPv4 address. See `man 3 inet` for details. """ ip_addr = str(ip_addr) try: socket.inet_aton(ip_addr) except socket.error: raise ValueError('Invalid IPv4 address: %s' % ip_addr) return ip_addr
209f54390b02bbf24ff3a2d3cc6a917eaaf975ed
649,178
def cg_has_node(cg, node): """ Return True if the cluster graph contains the corresponding node :param cg: :param node: :return: """ return cg.nodes().__contains__(node)
b967c1ecb856219ab94a174ede69a482aa8ad2a9
649,179
def get_movie_data_both_channels (data, movie_ID): """Pull out track data in both channels for one movie out of a dataframe. Args: data (Pandas dataframe): Parsed tracks for each movie, as created by the read_2color_data function of the parse_trackmate module. Contains the follo...
75a526fbac70f69ff95d79e62977df135c9c1090
649,180
def create_in_term_for_db_queries(values, as_string=False): """ Utility method converting a collection of values (iterable) into a tuple that can be used for an IN statement in a DB query. :param as_string: If *True* the values of the list will be surrounded by quoting. :type as_string: :cl...
626cec3ab25623b16708eb0250598171064dc17d
649,181
def __pos__(self) : """Return self""" return self;
00e3a77f75161bedeb4d26302bfa163362c937cf
649,184
def parse_bq_record(bq_record): """Parses a bq_record to a dictionary.""" output = {} for key in bq_record: output[key] = [bq_record[key]] return output
c72ad597a5f5a7fabe8f36212ba7ae42b878f1f4
649,186
def dumps(blackbird): """Serialize a blackbird program to a string. Args: blackbird (BlackbirdProgram): a :class:`BlackbirdProgram` object Returns: str: the serialized Blackbird program """ return blackbird.serialize()
f3e8bedcd84d2579c0966f7d4843a626099c25a9
649,191
def select_all_photo_thumbnail(session): """Get a list of all image thumbnails from db""" session.execute(""" SELECT url, title FROM photos """) return session.fetchall()
71b866de0261ae7f772d326eaa8c3a1c79dd931b
649,197
import re def is_copy_modify_with_no_change(diff_header): """Returns true if similarity index is 100% in the diff header.""" return re.search(r"(?m)^similarity index 100%", diff_header)
ad0e9146e097503db2b58e5f40052281f0f1a35b
649,200
from functools import reduce def modeOfLengths(input): """ PROTOTYPE: modeOfLengths(input) DESCRIPTION: Finds the mode (most frequently occurring value) of the lengths of the lines. ARGUMENTS: - input is list of lists of data RETURNS: mode as integer """ freq = {} ...
57a8248a5448e3a6af226bf94585a00eb501fd8a
649,201
def create_route_map(obj): """ Iterates of all attributes of the class looking for attributes which have been decorated by the @on() decorator It returns a dictionary where the action name are the keys and the decorated functions are the values. To illustrate this with an example, consider the foll...
3aed962296b953bac1ab23d46b4bd36e4c2d8adb
649,202
from typing import BinaryIO def _bytes_match(fd: BinaryIO, expected: bytes) -> bool: """Peeks at the next bytes to see if they match the expected.""" try: offset = fd.tell() data = fd.read(len(expected)) fd.seek(offset) return data == expected except IOError: return...
69a1063cb46203db78d362d04f731ac98d283ffa
649,203
def splitPath(path, sep='/'): """ Chops the first part of a /-separated path and returns a tuple of the first part and the tail. If no separator in the path, the tail is None """ sepIdx = path.find(sep) if sepIdx < 0: return (path, None) return path[:sepIdx], path[se...
e9b3d529731dba4462a425629898a6e0e4ed0c2e
649,206
def is_valid_deck(deck): """(list of int) -> bool Precondition: the length of input list is a list of number. Return true iff the input deck is a valid deck of cards, which means number of cards in the deck is consecutive. Return false if the input deck is not a valid deck of cards. >>> deck ...
9de58d4ffb721073efb79a2579b89722e9e3346a
649,208
import math def _daylight_hours(sunset_hour_angle_radians): """ Calculate daylight hours from a sunset hour angle. Based on FAO equation 34 in Allen et al (1998). :param sunset_hour_angle_radians: sunset hour angle, in radians :return: number of daylight hours corresponding to the sunset hour an...
7eef992832103f0fefdfaa3d936aa7015f3fdc61
649,214
import math def lg(n): """ Returns logarithm of n in base 2. """ return math.log(n, 2)
a311ac43e226357870454f92370390b38c274d1d
649,220
def strip_quotes(string): """ Strips quotes off the ends of `string` if it is quoted and returns it. """ if len(string) >= 2: if string[0] == string[-1]: if string[0] in ('"', "'"): string = string[1:-1] return string
88d4a725c4fd6dd33f2eb43c3a2558cc44a88609
649,221
def __get_token(path: str): """ Get the API token from the container's file system. """ with open(path, "r", encoding="utf-8") as file: return file.read()
3a807fa00311f664e596dcfd025798994349078b
649,222
def _get_element_attr_or_none(document, selector, attribute): """ Using a CSS selector, get the element and return the given attribute value, or None if no element. Args: document (HTMLElement) - HTMLElement document selector (str) - CSS selector attribute (str) - The attribute to g...
0945c41531e5a1452129c764f81983a5855247ea
649,224
import pickle def load_from_file(filename): """Load a past state from file. """ f=open(filename,'rb') try: return pickle.load(f) except EOFError: print('Nothing written to file.')
3ccc2938e90bd886a18b583568391b2a975d2a52
649,227
def invert_sign(num): """Change sign of number or add/remove leading sign of str.""" if isinstance(num, (float, int)): return -1 * num elif isinstance(num, str): if num.startswith('-'): return num[1:] return '-{0}'.format(num) raise ValueError( 'Num needs to b...
f21385da55d984732266ea1086163e590f2628eb
649,230
def as_microsoft(expression): """ Decorated function is added to the provided expression as the Microsoft vender specific as_sql override. """ def dec(func): setattr(expression, 'as_microsoft', func) return func return dec
bf5ef460324ff33dddf266f23b8a67d8fb506982
649,232
def _get_like_function_shapes_chunks(a, chunks, shape): """ Helper function for finding shapes and chunks for *_like() array creation functions. """ if shape is None: shape = a.shape if chunks is None: chunks = a.chunks elif chunks is None: chunks = "auto" ...
c56187a7fc92b1a69f75d7defe9a57bb6376515c
649,235
def get_div_ids_by_level(divs, level): """ Returns a list of all div ids with level. """ if not isinstance(divs, list): divs = [divs] ids = [] for div in divs: if div['level'] == level: ids.append(div['id']) # no need to check subdivs cont...
3db3c7c0f2882c04fa0c15afaf348d890097aea2
649,240
def new_admin(user, password_hasher): """ Create new admin user for testing. """ User = user # Admin user mock data admin_user_data = { "username": "admin", "email": "admin@email.com", "password": password_hasher.hash("admin"), } new_admin = User(**admin_user_data) ...
bc095d270ccb1f124a408a65b6a3684f407bbda0
649,241
import six def flatten_content_tree(roots, depth=0): """ Transforms a tree into a list with ``indent`` as the depth of a node in the original tree. """ results = [] for key, values in six.iteritems(roots): elem, nodes = values elem.update({ 'path': key, ...
ac6b2eeefd2d6bf4b38147822106a4c36dec7687
649,244
def image_count(list_bboxes, list_classes): """ 统计全图各个类别的数量。 :param list_bboxes: BoundingBoxs list :param list_classes: Classes list :return: 各个类别的数量. """ class_num = [0]*len(list_classes) for i in range(0, len(list_bboxes)): x1 = list_bboxes[i].xmin y1 = list_bboxes[i...
a038228ae5e74b1e2e73d7245dbd76d63fe6243c
649,245
def bdev_ocf_create(client, name, mode, cache_line_size, cache_bdev_name, core_bdev_name): """Add an OCF block device Args: name: name of constructed OCF bdev mode: OCF cache mode: {'wb', 'wt', 'pt', 'wa', 'wi', 'wo'} cache_line_size: OCF cache line size. The unit is KiB: {4, 8, 16, 32,...
cb632d906f8d5ef3192388886aa11f01db9f0e6b
649,247
def binary_search(search_list, search_key): """Find the index of a value of a key in a sorted list using a binary search algorithm. Returns the index of the value if found. Otherwise, returns -1. """ left_idx, right_idx = 0, len(search_list) - 1 # while True: while left_idx <= right_idx: ...
17738b9cc392f18d1f51f86a3c8d1b3fd3e14e47
649,248
from typing import List def beam_options_to_args(options: dict) -> List[str]: """ Returns a formatted pipeline options from a dictionary of arguments The logic of this method should be compatible with Apache Beam: https://github.com/apache/beam/blob/b56740f0e8cd80c2873412847d0b336837429fb9/sdks/pytho...
3c370e2949dd21fd9840d6e7cddb051866d4157b
649,251
def tasks_get_filtered(taskid_list, module): """ Get tasks information from a list of tasks. Parameters ---------- taskid_list : list List of task IDs to get. module : AnsibleModule Ansible module. Returns ------- list List of tasks from CVP. """ tas...
3aa195792a42e17d91c637cb76382b82967e01dc
649,256
import math def cos_sin_deg(deg): """Return the cosine and sin for the given angle in degrees, with special-case handling of multiples of 90 for perfect right angles """ deg = deg % 360.0 if deg == 90.0: return 0.0, 1.0 elif deg == 180.0: return -1.0, 0 elif deg == 270....
1f3672e8447285b6ce4ac4d35b4c68fda41c85c3
649,258
def get_header_idx(fname): """ Opens the file from fname and returns the row index corresponding to the header row (with all the column name field information) """ blanks = [] with open(fname,'r') as f: lines = f.readlines() for i, line in enumerate(lines): if li...
c0bd6021ea021f1d372572f2b42e866be1533c9f
649,261
def get_dotfield_value(dotfield, d): """ Explore dictionary d using dotfield notation and return value. Ex: d = {"a":{"b":1}}. get_dotfield_value("a.b",d) => 1 """ fields = dotfield.split(".") if len(fields) == 1: return d[fields[0]] else: first = fields[0] re...
914cd8e0fd65e8c641c6166b0dbe9ab9b6cb4e30
649,262
def permutations(numbers, descents): """Compute number of permutations with specified number of descents""" if descents in (0, numbers - 1): return 1 add0 = (descents + 1) * permutations(numbers - 1, descents) add1 = (numbers - descents) * permutations(numbers - 1, descents - 1) return (ad...
9cb97e6075746539e99f30b59ebeafcc812edc1d
649,263