content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from functools import reduce def bitList32ToList4(lst): """Convert a 32-bit list into a 4-byte list""" def bitListToInt(lst): return reduce(lambda x,y:(x<<1)+y,lst) lst2 = [] for i in range(0,len(lst),8): lst2.append(bitListToInt(lst[i:i+8])) return list([0]*(4-len(lst2))...
dcf128642151effcb574c695e226ee8bc47a8aec
663,968
import torch def tensor_normalize(tensor, mean, std): """ Normalize a given tensor by subtracting the mean and dividing the std. Args: tensor (tensor): tensor to normalize. mean (tensor or list): mean value to subtract. std (tensor or list): std to divide. """ if tensor.dty...
a1cc8c7d261dcdea5b54ced5708bcc63139f7896
663,970
def parse_filename(fname): """ Parse an SAO .hf5 filename for date and source """ parts = fname[7:-8].split('.') UNIXtime = float('.'.join(parts[:2])) sourcename = '.'.join(parts[2:]) return UNIXtime, sourcename
5bd7b1cf1d44fb92db647cecc557a2d63221548e
663,976
def secant_method(tol, f, x0): """ Solve for x where f(x)=0, given starting x0 and tolerance. Arguments ---------- tol: tolerance as percentage of final result. If two subsequent x values are with tol percent, the function will return. f: a function of a single variable x0: a starting value...
6c465f68084365661f409616b55a4d88f2da573f
663,977
def checkOperatorPrecedence(a,b): """ 0 if a's precedence is more than b operator 1 otherwise """ check={} check['(']=1 check['*']=2 check['/']=2 check['-']=3 check['+']=3 if check[a] <= check[b]: return 1 else: return 0
0b63f1e66f6ae3818e8c67cd63a1a52acc7cc5ee
663,979
def get_unique_attribute_objects(graph, uniq_attrs): """Fetches objects from given scene graph with unique attributes. Args: graph: Scene graph constructed from the dialog generated so far uniq_attrs: List of unique attributes to get attributes Returns: obj_ids: List of object ids with the unique at...
1170f79039ae5efb0d7a16e65f9e1d46a84cdfb1
663,981
from typing import Union from typing import Optional def cast_to_num(value: Union[float, int, str]) -> Optional[Union[float, int]]: """Casts a value to an int/float >>> cast_to_num('5') 5 >>> cast_to_num('5.2') 5.2 >>> cast_to_num(10) 10 >>> cast_to_num(10.1) 10.1 >>> cast_to_...
dc42d7f98be8c9edb27b1a2ccc2beb3246283498
663,982
def deltaT_boil(t_boil, t_cond): """ Calculates the temperature difference of boiler. Parameters ---------- t_boil : float The boiling temperature of liquid, [С] t_cond : float The condensation temperature of steam, [C] Returns ------- deltaT_boil : float The ...
9539609b696ceaf03d8fffac704bfc28d6679c89
663,986
def full_classname(cls): """Return full class name with modules""" return cls.__module__ + "." + cls.__name__
eb8ba6bbf17d2ad2f0333540b0e3e043ea292b4e
663,987
import random def pick_event(event_intervals): """ Returns a randomly selected index of an event from a list of intervals proportional to the events' probabilities :param event_intervals: list of event intervals """ i_event = 0 cumul_intervals = [] cumul_interval = 0.0 for interva...
40856e66a272ce9a86b49b647bd85148cfd33703
663,989
async def read_status(): """Check if server is running.""" return {'message': 'Server is running'}
512daadea1a60248af41104d9d5340a9fa44340f
663,991
from functools import reduce def versionToInt(version): """ Converts a WebODM version string (major.minor.build) to a integer value for comparison >>> versionToInt("1.2.3") 100203 >>> versionToInt("1") 100000 >>> versionToInt("1.2.3.4") 100203 >>> versionToInt("wrong") -1 ...
cd847ca28cf6c3aa10d8d96137c1264c496baf31
663,992
def _aggregates_associated_with_providers(a, b, prov_aggs): """quickly check if the two rps are in the same aggregates :param a: resource provider ID for first provider :param b: resource provider ID for second provider :param prov_aggs: a dict keyed by resource provider IDs, of sets ...
b2da5ff44a0c8abf3204987d79a3eebdd783efb1
663,994
def get_closest_waveform(x, y, t, response): """ This function, given a point on the pixel pad and a time, returns the closest tabulated waveformm from the response array. Args: x (float): x coordinate of the point y (float): y coordinate of the point t (float): time of the wave...
64bf6649a6e84863dd3caa4cdf757f0a5960cfe9
663,995
def test_name(msg_name): """Generate the name of a serialization unit test given a message name""" return "test_{}_serialization".format(msg_name)
261c4c4e215b84c0358ca51cbbd4723208dedb12
664,000
import re def natural_key(string): """ Key to use with sort() in order to sort string lists in natural order. Example: [1_1, 1_2, 1_5, 1_10, 1_13]. """ return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string)]
a474360aa2d8d10ea9283627219c0e86645f79be
664,002
def flipra(coordinate): """Flips RA coordinates by 180 degrees""" coordinate = coordinate + 180 if coordinate > 360: coordinate = coordinate - 360 return coordinate
5db6cb5bc7c7cb0b23e0ea434b2f4815e75d4800
664,004
def get_location_from_object(loc_obj): """Return geo-location from a RefContext location object.""" if loc_obj.db_refs.get('GEOID'): return loc_obj.db_refs['GEOID'] elif loc_obj.name: return loc_obj.name else: return None
d97f9ebd442f1e32adf03c7d51a1d8acde65bfb7
664,005
def ExtractImageTag(obj): """ Function to extract and return all image tags present in a BeautifulSoup object """ taglist = obj.findAll("img") return taglist
0f50aa1a14836de59537ed557cafd8de7560ef13
664,006
from typing import Union from pathlib import Path from typing import Tuple from typing import List from typing import Dict def parse_synset_mapping( synset_mapping_filename: Union[Path, str] ) -> Tuple[List[str], Dict[str, str]]: """Parses the synset mapping file. Args: synset_mapping_filename: a...
25376c76f505e168e5be428d2deb62f2ed428568
664,008
def clear_all(client): """Delete all keys in configured memcached :param client: memcached client object """ client.flush_all() return True
e7a24f798a62aaa29c0e254cf1c22e0fee1d64ad
664,010
import json def convert_response_to_json(response): """Converts the response to a json type""" json_response = json.loads(response.data.decode('utf-8')) return json_response
cd89b2ff7e397bf84d0a6d717c1cb97ea6714e25
664,014
import re def extract_points_from(result): """ Expected line: "Unlocked 31/50 Git Achievements for 248 points" """ pattern = re.compile(r'[^0-9]*Unlocked[^0-9]+(\d+)[^0-9]+(\d+)[^0-9]+(\d+)') for line in result.readlines(): match = pattern.search(line) if match: return [int(n) for n in match.g...
15066339d021506d7c3882239d34673ceb5fc7d8
664,015
def write_gif(clip, path, sub_start, sub_end): """Write subclip of clip as gif.""" subclip = clip.subclip(sub_start, sub_end) subclip.write_gif(path) return subclip
64cdd6dafde695a093cf84bfec97f3644c904928
664,019
def decompose_chrstr(peak_str): """ Take peak name as input and return splitted strs. Args: peak_str (str): peak name. Returns: tuple: splitted peak name. Examples: >>> decompose_chrstr("chr1_111111_222222") "chr1", "111111", "222222" """ *chr_, start, end = ...
b9a495572892445cd87d20a1c1bc9f9a0f9f1c5e
664,024
def are_keys_binary_strings(input_dict): """Check if the input dictionary keys are binary strings. Args: input_dict (dict): dictionary. Returns: bool: boolean variable indicating whether dict keys are binary strings or not. """ return all(not any(char not in '10' for char in key) f...
ef970da51bfc2f64b092795507c2f5b8ffe6628f
664,026
def flatten_nparray(np_arr): """ Returns a 1D numpy array retulting from the flatten of the input """ return np_arr.reshape((len(np_arr)))
bb8700b65c327227cce43a7ec6ba7363ecf13b7f
664,029
def height(I): """returns the height of image""" return I.shape[0]
01e536605b8e65788506baa424614eb152908737
664,031
def read_names(filename): """File with name "filename" assumed to contain one leafname per line. Read and return set of names""" names = set() with open(filename, "r") as infile: for line in infile: leaf = line.strip() if leaf: names.add(leaf) return name...
29e3bf5a94fc32430b713c335b28e297cbeb0eca
664,032
def learning_rate_decay(alpha, decay_rate, global_step, decay_step): """ Updates the learning rate using inverse time decay in numpy alpha is the original learning rate decay_rate is the weight used to determine the rate at which alpha will decay global_step is the number of passes of gradien...
640f823ace92fdbd6fca198468864445a201b7e3
664,034
def tanimoto(e1, e2): """ Tanimoto coefficient measures the similarity of two bit patterns. Also referred to as the Jaccard similarity :return: real 0-1 similarity measure """ return (e1 & e2).count() / float((e1 | e2).count())
2fe750d95da75af0ea9ae6e00688430cf541b2c1
664,037
def scaleValues(values): """Scale a numpy array of values so that (min, max) = (0,1).""" values = values - values.min() return values/values.max()
a7b02a8b0d7d8cf041843fe31929acd03d22cc0f
664,041
import time def ValueOfDate() -> int: """ Return current unix time in milisecond (Rounded to nearest number) """ return round(time.time() * 1000)
cc0b51a1eb997ae12e19f40751fde28caad12877
664,050
def register_versions(role, versions=None): """Decorator for connecting methods in the views to api versions. Example: class MyView(BaseView): @register_versions('fetch', ['v4', 'v5']) def _get_data(self, param1, param2): ... @register_versions('re...
3b318530f4bc9c0673fbb1bf2af1e90d6841d44e
664,052
def latex_safe(s): """ Produce laTeX safe text """ s = s.replace('_','\_') return s
f816c96cb46b9707a5d173f61e6d956feade1fd5
664,058
def open_wordlist(path): """ open a wordlist Note: a wordlist should be a text document with one word per line Args: path(str): full path to the wordlist Returns: passwordlist(list): list of all the words (as strings) in the wordlist """ with open(path, 'r', errors...
55de8c0424b25090067c38f8ac38c5c124f9dcb5
664,059
def fahrenheit_to_celsius(temp): """Convert temperature in fahrenheit to celsius. Parameters ---------- temp : float or array_like Temperature(s) in fahrenheit. Returns ------- float or array_like Temperatures in celsius. bubbles """ try: ...
8fc52f77268d38219cfd16f21540f8409dd006b5
664,068
import functools def replace_all(text, replacements): """ Replace in `text` all strings specified in `replacements` Example: replacements = ('hello', 'goodbye'), ('world', 'earth') """ return functools.reduce(lambda a, kv: a.replace(*kv), replacements, text)
b23efcc6198eb2652021600d505266ae16c903f2
664,076
import glob def get_files(data_dir_list, data_ext): """ Given a list of directories containing data with extention 'date_ext', generate a list of paths for all files within these directories """ data_files = [] for sub_dir in data_dir_list: files = glob.glob(sub_dir + "/*" + data_ext)...
e473a94ba9542d4813d7bf1e87a0773aecdaf1ce
664,079
def supertype(tcon): """ Return the supertype of the given type constructor. """ return tcon.supertype
d12a1b1078a607b20da34aed2907507c75912f1d
664,080
def pfx_path(path : str) -> str: """ Prefix a path with the OS path separator if it is not already """ if path[0] != '/': return '/' + path else: return path
12b7068e850c7201e063f6b1cc559cf5e9c5a0d0
664,082
def check_entity_schema( sg, logger, entity_type, field_name, field_types, required_values ): """ Verifies that field_name of field_type exists in entity_type's schema. :param sg: An authenticated Shotgun Python API instance. :param entity_type: str, a Shotgun entity type. :param field_name: st...
5ae2ed8a36199d7b570a6934fc54926856f056d6
664,083
def split_into_sets(array, tindx, eindx): """ Split data into train and validation (or evaluation) set with indices. Args: array (ndarray): processed without nans tindx (array): train data indices eindx (array): validation/evaluation data indices """ array_t = array...
ea69869434a399945958395a2705e7fad5ff2c28
664,084
import re def get_module_runtime(yaml_path): """Finds 'runtime: ...' property in module YAML (or None if missing).""" # 'yaml' module is not available yet at this point (it is loaded from SDK). with open(yaml_path, 'rt') as f: m = re.search(r'^runtime\:\s+(.*)$', f.read(), re.MULTILINE) return m.group(1) ...
2e8bae6f20f55e25a7a91d5e385af646f875a525
664,085
def pixels_to_figsize(opt_dim, opt_dpi): """Converts pixel dimension to inches figsize """ w, h = opt_dim return (w / opt_dpi, h / opt_dpi)
6af279e64a8e2ba8d27a1815dec905436c0c3665
664,092
def get_line_slope_intercept(x1, y1, x2, y2): """Returns slope and intercept of lines defined by given coordinates""" m = (y2 - y1) / (x2 - x1) b = y1 - m*x1 return m, b
feba17f63579d514c47f82605a8de59d196a6eb7
664,093
def compare(n, p1, p2): """Compares two bits in an integer. Takes integers n, p1, p2. If the bit of n at positions p1 and p2 are the same, true is returned to the caller. Otherwise returns false. Bit positions start at 1 and go from low order to high. For example: n = 5, p1 = 1, p2 = 2 ...
b71af5efffb31623e7d83289ee9cdf6928178a1d
664,094
def getDisabled(self, pos): """Get a boolean representing whether or not cell (i,j) is disabled.""" self.__checkIndices__(pos) return self.__isdisabled__[pos[0]][pos[1]]
4407ee1ae7c559caffc8905c0f553104c9e19622
664,099
def Diff(li1, li2): """ get the difference between two lists """ list_dif = [i for i in li1 + li2 if i not in li1 or i not in li2] return list_dif
faaa50a9a37d21654611c1df522099c2a45669ec
664,101
from typing import List from typing import Dict import codecs def load_dict(dict_path: str, required: List[str] = ["<sos>", "<eos>"], reverse: bool = False) -> Dict: """ Load the dictionary object Args: dict_path: path of the vocabulary dictionary required: requ...
7a4398f7dbc0fef4a2b52971881c2824e4f7afec
664,103
def vander_det(x): """Vandermonde determinant for the points x""" prod = 1 num = x.shape[0] for j in range(1, num): for i in range(0, j): prod *= x[j] - x[i] return prod
a3b48149af03fd2235b389437d44d8e0b231119e
664,104
def argmax(pairs): """ Given an iterable of pairs (key, value), return the key corresponding to the greatest value. Raises `ValueError` on empty sequence. >>> argmax(zip(range(20), range(20, 0, -1))) 0 """ return max(pairs, key=lambda x: x[1])[0]
8b60662485b042eb815431e38961c9cbe77cd4ea
664,105
def _calc_detlam(xx, yy, zz, yx, zx, zy): """ Calculate determinant of symmetric 3x3 matrix [[xx,yx,xz], [yx,yy,zy], [zx,zy,zz]] """ return zz * (yy*xx - yx**2) - \ zy * (zy*xx - zx*yx) + \ zx * (zy*yx - zx*yy)
810c2e39f8c85dda255121394fbef5e0f21b8f24
664,114
import hashlib def get_sha512_sums(file_bytes): """ Hashes bytes with the SHA-512 algorithm """ return hashlib.sha512(file_bytes).hexdigest()
3f88cab516e0a8e2a209bef840cb112804cdac10
664,119
def _colorize(text, color): """Applies ANSI color codes around the given text.""" return "\033[1;{color}m{text}{reset}".format( color = color, reset = "\033[0m", text = text, )
7bf5313677f8d065ed01977bad8ad06196377c62
664,122
def factory_name(obj): """ Returns a string describing a DisCoPy object. """ return '{}.{}'.format(type(obj).__module__, type(obj).__name__)
86fae35d0884b9de59535f771aae81436e5906fb
664,123
def get_marker(func_item, mark): """ Getting mark which works in various pytest versions """ pytetstmark = [m for m in (getattr(func_item, 'pytestmark', None) or []) if m.name == mark] if pytetstmark: return pytetstmark[0]
d526b4265c8d8e2420c87955d44b3268d195a571
664,124
def _approx_equal(a, b, tolerance): """Check if difference between two numbers is inside tolerance range.""" if abs(a - b) <= tolerance * a: return True else: return False
2f2c2a15b21e96f7d34e669d99acd1f06c333829
664,126
def _field_name(name, prefix=None): """ Util for quick prefixes >>> _field_name(1) '1' >>> _field_name("henk") 'henk' >>> _field_name("henk", 1) '1henk' """ if prefix is None: return str(name) return "%s%s" % (prefix, name)
03efaaca97ceffb1da958032f6d5ec65509c079f
664,127
import re def title(value): """Converts a string into titlecase.""" t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)
9d9ee0185ec94226272f508a0cb0bc13b58c7a2d
664,136
from typing import OrderedDict def sort_dictionary(dictionary): """ This function will turn a dictionary with sortable keys into an OrderedDict with keys in the ordering of the keys. This dictionary will have two levels of nesting as it will be a mapping of the sort {State -> {State -> value}} ...
0eb6d8ba5ec0257938d726ad19925033c9cf319c
664,137
def square(n): """Square a Number.""" return n ** 2
ea8c204d4cf33d6bba216be09ce224ff523346a5
664,143
def parse_json_data(data,sep='\t'): """ Extract the data from json into a dictionary and a string """ # Set up the dictionary keys = ['date','rower','meters','duration','split','spm', 'watts','calories','resistance','instructor','workout'] workout = {} # Pointers to portions of the data...
4c446c548ab10265d5ac911853ef7660197506c7
664,144
def merge(L1: list, L2: list) -> list: """Merge sorted lists L1 and L2 into a new list and return that new list. >>> >>> merge([1, 3, 4, 6], [1, 2, 5, 7]) 1, 1, 2, 3, 4, 5, 6, 7] """ newL = [] i1 = 0 i2 = 0 # For each pair of items L1[i1] and L2[i2], copy the smaller into newL. whi...
9b6423a2ed8ac900668cef3221ca3db7e581500f
664,145
def filter_entity(org_name, app_name, collection_name, entity_data, source_client, target_client, attempts=0): """ This is an example handler function which can filter entities. Multiple handler functions can be used to process a entity. The response is an entity which will get passed to the next handler i...
301b989b19e4f62587ebc55546b6e84d8ca625a1
664,147
def get_host_id(session, hostname): """ Get host_id from the hostname. """ query = """ SELECT host_id FROM monitoring.hosts WHERE hostname = :hostname """ result = session.execute(query, {"hostname": hostname}) try: return result.fetchone()[0] except Exception: ...
7522eeebb9ebf8b0ff9c0f86bde7d6db59d43d87
664,150
def find_smallest_bin(b): """ Take boundary non-uniform vector and find smallest bin assuming they are multiple of each other Parameters ---------- b: array of floats boundaries, in mm returns: float minimal bin size """ minb = 10000000.0 prev = b[0] ll ...
bfeab80625eb939cc799946be49974c86a39cc0c
664,152
def _func_star(args): """ A function and argument expanding helper function. The first item in args is callable, and the remainder of the items are used as expanded arguments. This is to make the function header for reduce the same for the normal and parallel versions. Otherwise, the functions ...
56901a69afdc403188e46f9b80942d7af3f38e46
664,153
def always_none(x): """Returns None""" return None
fd19ec3bb5d0f76ebf79f1c4d600764d768243a1
664,156
def run_algo(op_list): """Execute all operations in a given list (multiply all matrices to each other).""" ops = op_list[::-1] # reverse the list; after all, it's matrix mult. result = ops[0] for op in ops[1:]: result = result * op return result
d7954d938162885b704bf479f63dcc6741e8e65d
664,157
def get_docomo_post_data(number, hidden_param): """Returns a mapping for POST data to Docomo's url to inquire for messages for the given number. Args: number: a normalized mobile number. Returns: a mapping for the POST data. """ return {'es': 1, 'si': 1, '...
ed46f080ac6cda8882bf826cad39f03512da334b
664,158
def AioNodeNameFromLightNickname(light): """Returns AIO node name for the specified light node.""" if light == 'BaseStation': return 'kAioNodeGpsBaseStation' else: return 'kAioNodeLight' + light
d2724e7443c4b7332851bbaa450c72968d1fa112
664,160
from typing import List def encode_message(message_string: str) -> List[int]: """Build a message to send in a sysex command.""" return [ord(char) for char in message_string]
94e798677aa6fa389f48d54aa033e919bb93c724
664,161
def parse_performance_data(response): """Parse metrics response to a map :param response: response from unispshere REST API :returns: map with key as metric name and value as dictionary containing {timestamp: value} for a the timestamps available """ metrics_map = {} for metrics in respo...
613f3029b4b8011b28dbbbdf35fad7be56906a71
664,162
def flat_node_list(graph): """ returns list of all non-compund nodes in a graph, inculding all the nodes that are inside compound nodes. """ node_ids = [] for node in graph: node_data = graph.node[node] #print(node_data) if 'components' in node_data: internal_...
b8997e9dfb7cc9dd569c609106142df586a56156
664,168
def calc_total_fuel_for_mass(mass:int) -> int: """Calculates the total amount of fuel needed for a given mass, including its needed fuel mass.""" fuel = (mass // 3) - 2 if fuel <= 0: return 0 return fuel + calc_total_fuel_for_mass(fuel)
fa934c8829321f34416ab27196e953ccbe0de3f4
664,170
def _plugin_url(name, version): """ Given a name and an optional version, return the jenkins plugin url. If there is no version, grab the latest version of the plugin. >>> _plugin_url("git", None) 'https://updates.jenkins-ci.org/latest/git.hpi' >>> _plugin_url("git", "2.3.5") 'https://updat...
7993dd55234d8a8c07d4426d3c18e12052340b24
664,171
import functools import builtins import logging def requires_ipython(fn): """Decorator for methods that can only be run in IPython.""" @functools.wraps(fn) def run_if_ipython(*args, **kwargs): """Invokes `fn` if called from IPython, otherwise just emits a warning.""" if getattr(builtins, '__IPYTHON__',...
f826621ff8a89720c932f1f396b746ae6aef4e64
664,174
from typing import OrderedDict def get_linking_log_headers() -> list: """ Get linking log headers for creating project master linking log :return: list of headers for linking log """ linking_headers = OrderedDict() linking_headers['SubjectID'] = 'subject_id' linking_headers['MedicalRecordN...
c36de71da596b62f64cf4b1bef1684d1ee9ce38d
664,177
def ErrorMessage(text): """Format an error output message """ return "\n\n" \ "********************************************************************\n" \ "{}\n" \ "********************************************************************" \ "\n\n".format(text)
de85fb28369b8efa0c33e5cc2c39f0a5f77b131f
664,179
import textwrap def wrap_text(text, width=90, indent=''): """Wrap each line of text to width characters wide with indent. Args: text (str): The text to wrap. width (str): width to wrap to. indent (str): the indent to prepend to each line. Returns: str: A wrapped block of ...
4cba6a5cfa41a8b21f5f9b4e9fcbbd4889a033eb
664,182
import re def expand_refs(comment_line): """Adds hrefs to markdown links that do not already have them; e.g. expands [Foo] to [Foo](#Foo) but leaves [Foo](https://foo) alone. """ result = comment_line result = re.sub(r"\[(\S+)\]([^(])", r"[\1](#\1)\2", result) result = re.sub(r"\[(\S+)\]$", r"...
3fc84773b12c27079aa96d2ced8bba9cfface969
664,183
def get_control_variation(campaign): """Returns control variation from a given campaign Args: campaign (dict): Running campaign Returns: variation (dict): Control variation from the campaign, ie having id = 1 """ for variation in campaign.get("variations"): if int(variation...
aee9e6474bbb0ab2baa0e3e296ed5bf00c0d0c36
664,191
def get_all_ngrams(words): """ Get all n-grams of words :param words: list of str :return: ngrams, list of (list of str) """ ngrams = [] N = len(words) for n in range(1, N + 1): for i in range(0, N - n + 1): ngrams.append([words[j] for j in range(i, i + n)]) retu...
979aa2e1bffd50f0f4478b0058ea15a0863f2cec
664,194
def total_hours(hours, days, weeks): """Total hours in w weeks + d days + h hours.""" return hours + 24 * (days + 7 * weeks)
3149069da9bb63bac66901c1c203e7604d4839dc
664,195
def to_port_num(str_in): """ Tries to coerce provided argument `str_in` to a port number integer value. Args: str_in (string): String to coerce to port number. Returns: (int) or (None): Integer port number if provided `str_in` is a valid port number string,...
7b922b8d809b87a45623ac398773180939ac0b0f
664,197
def contains_ingredients(ing, check_ing): """ IMPORTANT: You should NOT use loops or list comprehensions for this question. Instead, use lambda functions, map, and/or filter. Take a 2D list of ingredients you have and a list of pancake ingredients. Return a 2D list where each list only contains ing...
e46be3c1f0b1a91bd40d0764a668ebf07cd47290
664,202
def match_emoji(emoji: str, text: str) -> bool: """ True if the emoji matches with `text` (case insensitive), False otherwise. """ return emoji.lower().startswith(text.lower())
b304614614ffb6fab26382ae607b212f917ff6ab
664,207
import math def _find_utm_crs(lat, lon): """Find the UTM CRS based on lat/lon coordinates. Parameters ---------- lat : float Decimal latitude. lon : float Decimal longitude. Returns ------- crs : dict Corresponding UTM CRS. """ utm_zone = (math.floor((...
7dff30cbfb277d21728c0feadeb0018b6e793462
664,208
def format_states(states): """ Format logging states to prettify logging information Args: states: logging states Returns: - formated logging states """ formated_states = {} for key, val in states.items(): if isinstance(val, float): if val < 1e-3: ...
4612914f26813b9dd4cea527ec54f3d03ec5284f
664,209
def set_gte(left, right): """:yaql:operator >= Returns true if right set is subset of left set. :signature: left >= right :arg left: left set :argType left: set :arg right: right set :argType right: set :returnType: boolean .. code:: yaql> set(0, 1) >= set(0, 1) t...
6928d48115906f0e8c56b4f9cbdbd24c52ad6d05
664,214
from bs4 import BeautifulSoup def extract_data_by_class(raw_content, elem, class_name, is_all=False): """extract html tags by element and class name""" parser = "html.parser" soup = BeautifulSoup(str(raw_content), parser) if is_all: return soup.find_all(elem, class_=class_name) else: ...
5eac674f0ea6e48bac7d0c52e1c5d137377ecb0f
664,218
def str2bool(s): """ Turn a string s, holding some boolean value ('on', 'off', 'True', 'False', 'yes', 'no' - case insensitive) into boolean variable. s can also be a boolean. Example: >>> str2bool('OFF') False >>> str2bool('yes') True """ if isinstance(s, str): true_val...
a8c8dad6c468d5b983e6239b0e0d0e0096bf8ab0
664,220
def runtime_sync_hook_is_client_running(client): """ Runtime sync hook to check whether a slash command should be registered and synced instantly when added or removed. Parameters ---------- client : ``Client`` The respective client of the ``Slasher``. """ return client.running
21b53074756dcb7f9c322b369b862f00f6cfc41c
664,226
import math def root_ttr(n_terms, n_words): """ Root TTR (RTTR) computed as t/sqrt(w), where t is the number of unique terms/vocab, and w is the total number of words. Also known as Guiraud's R and Guiraud's index. (Guiraud 1954, 1960) """ if n_words == 0: return 0 retu...
bae5ed27e26e0f8751146717ff1a10192eed2ed1
664,227
def read_file(path): """ reads lines of a file and joins them into a single string """ try: with open(path, 'r') as text_file: return "".join(text_file.readlines()).strip() except IOError: exit("Error: file '%s' is not readable!" % path)
c1a246c42874c11a7dc1f2e94f18c2a1f633d092
664,229
import re import uuid def _replace_re_pattern(code, pattern): """Replace the given re pattern with a unique id. Return the replaced string and a list of replacement tuples: (unique_id, original_substring) """ replacements = [] matches = re.findall(pattern, code) code_ = code for m in m...
92f1d6a79e50c16d8175f75fc2fd4bac721e3393
664,230
import torch def cr_matrix_vector_product(m: torch.Tensor, x: torch.Tensor) -> torch.Tensor: """Returns the product of a complex matrix and a real vector. :param m: Matrix as ``(*, m, n, 2)`` tensor. :param x: Vector as ``(*, n)`` tensor. :return: Result as ``(*, m, 2)`` tensor. """ xr = x.un...
cafc5f19441fc1c47eb9f82d0ae8992918a8df72
664,232
def _CheckNoInterfacesInBase(input_api, output_api): """Checks to make sure no files in libbase.a have |@interface|.""" pattern = input_api.re.compile(r'@interface') files = [] for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile): if (f.LocalPath().find('base/') != -1 and f.LocalPath()...
12ea2309bdef26e6cb361b855ab1e97c0ac5c688
664,234
def _get_view_name(task_name: str, window_size: int) -> str: """Returns the view name for a given task name.""" return f"{task_name}_{window_size}_view"
fc247a0d486a12ec87ebc81de30d5d0729841b8b
664,235