content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_frame_IDs(objects_archive, start, end, every): """ Returns list of ID numbers of the objects identified in each frame. Parameters ---------- objects_archive : dictionary Dictionary of objects identified in a video labeled by ID number start, end, every : ints start =...
4826a4d226460e07fbd015e59a052d9792e8ac6a
28,875
def plan_exists(plan): """This function can be used to check if a plan trajectory was computed. Parameters ---------- plan : :py:obj:`!moveit_msgs.msg.RobotTrajectory` The computed robot trajectory. Returns ------- :py:obj:`bool` Bool specifying if a trajectory is present ...
e2eb384119ed55cb3561e9485bddc3a221a03f92
28,876
def format_message_pagination(text, max_characters=1500): """Splits text with lines > the max_characters length into chunks. :param text: :returns: """ chunks = str() messages = [] def is_newline_character(char): # noqa: WPS430 if char == "\n": return True retu...
0ffa685ff084251f405f498e77490db0b300bfb6
28,878
import os def mock_env_settings_file(mock_os_environ, mock_settings_file): """Set the settings file env variable to a temporary settings file.""" os.environ["TEST_STUFF_SETTINGS_FILE"] = mock_settings_file[0] return mock_settings_file
0983959a9a57511f619e1f8f0f508bbf21fb0e45
28,879
def ISO_datestring(dt, cl): """ Convert a DateTime object to an ISO datestring. also fix an error in the conversion .isoformat() returns 12:00:00 for both Noon and Midnight. Also trim date to report only date, hours and minutes. """ isodatestr = dt.isoformat() if cl[4] == "12:00AM": # reset...
01ab02d2aa05405cd955670362bddf4a7467f3b1
28,880
import numpy def convert_ndarray_to_bytes(a): """Convert numpy array to numpy bytes array""" return a.view(numpy.uint8)
1c5a688bfca4bc58ff31e409a133070accb7eea6
28,881
def suggest_patience(epochs: int) -> int: """Current implementation: 10% of total epochs, but can't be less than 5.""" assert isinstance(epochs, int) return max(5, round(.1 * epochs))
e1631576d63dc3b62df636fb555739158035a25a
28,882
def offset_types(request): """ Fixture for all the datetime offsets available for a time series. """ return request.param
6ae26e175699dc3a304bff8755ce0fc6aecf0a32
28,883
def measure_diff(fakes, preds): """Measures difference between ground truth and prediction fakes (float array): generated "true" global scores preds (list list): list of [video_id: int, criteria_name: str, score: float, uncertainty: float] in ...
824052778fe02620d52ad0ff5987e1f62363d7fc
28,884
def stringify(vals): """Return a string version of vals (a list of object implementing __str__) Args: vals (List[any]): List of object that implements __str__ Returns: str: A string representation """ if type(vals) == list: return '_'.join([str(e) for e in vals]) else: ...
cbd681b2435a919a91a7eeb905ca3279a9baeea6
28,885
import logging def get_stream_handler( formatter: logging.Formatter, level: int ) -> logging.StreamHandler: """ Create a ready-to-go stream handler for a Logger. Parameters ---------- formatter : logging.Formater Formatter to apply to the handler. level : int Level to appl...
2c6de5bec9fbcb3f7f76c1c21c0db2091b649c96
28,886
def print_to_log(message, log_file): """Append a line to a log file :param message: The message to be appended. :type message: ``str`` :param log_file: The log file to write the message to. :type log_file: ``Path`` """ with open(log_file, "a") as file_handle: message.rstrip() ...
cc79449ac082e3e1053e43bfe6d87c7b617c1923
28,887
def OneWay(transform, name='unnamed'): # language=rst """ Wrapper for staxplusplus networks. :param transform: spp network """ _init_fun, _apply_fun = transform def init_fun(key, input_shape, condition_shape): transform_input_shape = input_shape if len(condition_shape) == 0 else (i...
7cc3ee9264395f7e01d1481ce869d319e3e2002f
28,888
def can_replace(func, n): """ Write a higher-order function that takes in a function func and a value n. It return a function such that it takes in another function func2 and it will return True if func could be replaced by func2 at value n; False otherwise. >>> can_replace(lambda x: x, 1)(lamb...
5c550700015194682e4aa0c32212c55df648dd93
28,890
def get_prefix_repr(prefix, activities): """ Gets the numeric representation (as vector) of a prefix Parameters ------------- prefix Prefix activities Activities Returns ------------- prefix_repr Representation of a prefix """ this_pref_repr = [0] * ...
3a194ba988ed5d1889e64df011cd7437e0354ce7
28,892
def sanitizeFilename(filename: str) -> str: """ Remove invalid characters <>:"/\\|?* from the filename. """ result = '' for c in filename: if c not in '<>:"/\\|?*': result += c return result
90068166ee5ca26cbe4713f2d4edb96be92b961c
28,893
def _os_symbol_file_path_prefix(): """ iOS系统相关符号文件路径前缀 """ return '~/Library/Developer/Xcode/iOS DeviceSupport'
046bb85a563ebb5c69539f7075fbe975f94583bf
28,895
import os def get_filename(path): """ Get the filename without extension input/a.txt -> a """ head, tail = os.path.split(path) return os.path.splitext(tail or os.path.basename(head))[0]
e7c3ec7899803ea701662aa3e57f7f576c6e5971
28,898
def format_time_delta(delta): """ Given a time delta object, convert it into a nice, human readable string. For example, given 290 seconds, return 4m 50s. """ d = delta.days h = delta.seconds / 3600 m = (delta.seconds % 3600) / 60 s = delta.seconds % 60 if d > 0: return '%sd...
8b795cdb716f78dc7c0be5b7454a9d63cd703463
28,899
import re def check_url(url): """ Check if url is actually a valid YouTube link using regexp. :param url: string url that is to be checked by regexp :return: boolean True if the url matches the regexp (it is a valid YouTube page), otherwise False """ youtube = re.compile(r'(https?://)?(w{3}\.)?(y...
ab0874af82ebe4d7e9435a57a96feb8339da9e70
28,901
def eval_args(parser, dval_iter=500, show_val_batch_size=False, dval_batch_size=256, show_val_set_size=False, dval_set_size=0): """This is a helper method of the method `parse_cmd_arguments` to add an argument group for validation and testing options. Arguments specified in this function: ...
66cc6e1862ca1db18d69c7826049605f21916835
28,902
def backends_mapping(custom_backend, private_base_url): """ Creates four echo-api backends with the private paths being the keys in the dict """ return {"/bar": custom_backend("backend1", endpoint=f"{private_base_url('echo_api')}/backend1"), "/foo/boo": custom_backend("backend2", endpoin...
30167e3165cc372d4812258a1bcb5e3973780642
28,903
def get_url_prefix(configdict, options): """ Get the url prefix based on options """ if 'servers' in options: urlprefix = configdict['servers']['http'][0] else: urlprefix = configdict['url_prefix'] return urlprefix
4f7065e9dd10f0f99dc9953fd8f22c0ec34746d2
28,904
def termcap_distance(ucs, cap, unit, term): """termcap_distance(S, cap, unit, term) -> int Match horizontal distance by simple ``cap`` capability name, ``cub1`` or ``cuf1``, with string matching the sequences identified by Terminal instance ``term`` and a distance of ``unit`` *1* or *-1*, for right and...
731c4e02378a626c6a3c3dd7ee30848d88cc2f8a
28,905
def create_subnet(ec2_c, vpc, rt_table, networks, lab_tag): """ Must have a least one subnet to provision EC2 instances. """ subnet = ec2_c.create_subnet(CidrBlock=networks, VpcId=vpc.id) rt_table.associate_with_subnet(SubnetId=subnet.id) return subnet
05fb3cce87e4134d1a0c149b72381f5d6bf45375
28,906
def _bytes_to_string(value: bytes) -> str: """Decode bytes to a UTF-8 string. Args: value (bytes): The bytes to decode Returns: str: UTF-8 representation of bytes Raises: UnicodeDecodeError """ return value.decode(encoding="utf-8")
b33508db0184f21854c734bbef126ec39d95c7b1
28,907
def merge(intervals): """ Turns `intervals` [[0,2],[1,5],[7,8]] to [[0,5],[7,8]]. """ out = [] for i in sorted(intervals, key=lambda i: i[0]): if out and i[0] <= out[-1][1]: out[-1][1] = max(out[-1][1], i[1]) else: out += i, return out
b0a9eb30f81132f0af568f442465bdd9ce19ab83
28,908
def date_day_of_week(date): """Return the day of the week on which the given date occurred.""" day_of_week = date.strftime('%A') return day_of_week
14e5a60b3089f2ec1aed18f71929c73ea1b50731
28,909
import torch def scatter_embs(input_embs, inputs): """ For inputs that have 'input_embs' field passed in, replace the entry in input_embs[i] with the entry from inputs[i]['input_embs']. This is useful for the Integrated Gradients - for which the predict is called with inputs with 'input_embs' field wh...
d0966c15f51b1b692995cd25076e455bea8a2b8a
28,910
def load_modules(agent_classes): """Each agent class must be in module class_name.lower(). Returns a dictionary class_name->class""" def load(class_name): module_name = class_name.lower() # by convention / fiat module = __import__(module_name) agent_class = module.__dict__[class_na...
958a11ceb8f9442af6dd0a1e210f8efda04d5461
28,911
import os import json def json_from_file(string: str) -> dict: """load a `string` JSON file Args: string: a path to a JSON file Return: An `output` dictionary composed of: - `output['input_file']` is the path of the JSON file - `output['json']` is the contents of the JSO...
bf3efe8027767a4ec6728cc222ead468721428e2
28,912
def sanitizeStr(data): """ Escape all char that will trigger an error. Parameters ---------- data: str the str to sanitize Returns ------- str The sanitized data. """ data = " ".join(data.split()) new_msg = [] for letter in data: if letter in ['"...
6fcd1455a01997d526cfd178d98ee3e9eca3c888
28,915
from typing import OrderedDict def group_unique_values(items): """group items (pairs) into dict of lists. Values in each group stay in the original order and must be unique Args: items: iterable of key-value pairs Returns: dict of key -> lists (of unique values) Raises: ...
cd25d657117b34fe408c27149ddf034f3956383d
28,917
import io import csv def scanlist_csv() -> io.StringIO: """ Generates a placeholder ScanList.csv """ header = [ "No.", "Scan List Name", "Scan Channel Member", "Scan Channel Member RX Frequency", "Scan Channel Member TX Frequency", "Scan Mode", ...
c5c4a8e6d860c3984c7c4af4ab869ca521b1c8cd
28,918
def standard_program_songs(): """ Standard program songs. """ standard_program_songs = [ "song1", "song2", "song3", "offering", "response", ] return standard_program_songs
b8e4a997541794894d875aa80ea11bad32abbdae
28,919
def getTableRADecKeys(tab): """Returns the column names in the table in which RA, dec coords are stored, after trying a few possible name variations. Args: tab (:obj:`astropy.table.Table`): The table to search. Returns: Name of the RA column, name of the dec. column ...
93807fe56826ac680605b0494af60ddc6a5014a8
28,920
def convert_price(price): """Convert a price""" if price[0] == u'\xa3': return float(price[1:]) return float(price)
d5875bd87a1e772bac1aed1e7dc78928f1fb81fe
28,921
import re def generate_filename_chart(series, args): """returns the generated basename for files for this series""" s = str(series.get("title")).strip().replace(' ', '_') title_slug = re.sub(r'(?u)[^-\w.]', '', s) return f'tv_show_ratings_{series["movie_id"]}_{title_slug}.{args.format}'
d08451aa3fc10129bf811c28e63ce322d88efd5c
28,923
import typing def to_camel(d: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]: """Converts dictionary keys from snake case to camel case.""" def convert(key: str) -> str: parts = key.split("_") return parts[0] + "".join(part.capitalize() for part in parts[1:]) return {conve...
799d295aef19fbf4017eba477ce2f0f3d6a6061e
28,924
import os def pid_list(ext_name): """ Return list of PIDs for program name and arguments Whitespace output is compressed to single space """ # Just grep up to first space in command line. It was failing on ! prg_name = ext_name.split(' ', 1)[0] all_lines = os.popen("ps aux | grep -v grep |...
09ff713b66c93a1fe0db59cf8cbb35b4b2732a6f
28,925
def create_astropy_time(py_obj, h_group, name, **kwargs): """ dumps an astropy Time object Args: py_obj: python object to dump; should be a python type (int, float, bool etc) h_group (h5.File.group): group to dump data into. call_id (int): index to identify object's relative...
c11fc0e3737913363ae4f60df3dfe52c744b48e3
28,926
def format_channel_link(name: str, channel_id: str): """ Formats a channel name and ID as a channel link using slack control sequences https://api.slack.com/docs/message-formatting#linking_to_channels_and_users >>> format_channel_link('general', 'C024BE7LR') '<#C024BE7LR|general>' """ retur...
2745a21960c7a2200e07e28bc5644a09f609b8ba
28,927
import pickle def load_pickle(filepath_str): """ Load pickled results. Inputs: filepath_str: path to the pickle file to load Returns: loaded pickle file """ with open(filepath_str, 'rb') as pickle_file: return pickle.load(pickle_file)
a7cd817327e928a8d1f3ff3290923e9b878d2a06
28,928
import os def find_recording_dir(test_file): """ Find the directory containing the recording of given test file based on current profile. """ return os.path.join(os.path.dirname(test_file), 'recordings')
4a0071a1cc87792f4cf8ad17b93ab0d443b71801
28,929
def local_ij_delta_to_class(local_ij_delta): """ :param local_ij_delta: tuple (i, j) returned from local_ij_delta :return: a value 0-5 for the each of the possible adjecent hexagons, or -1 if the (i,j) tuple is representing a non-adjecent hexagon coordinate """ if (local_ij_delta == (0,...
ed16645346353304c62b4c6bd7e73ee7b3fb2ead
28,930
import torch def get_devices(cuda_device="cuda:0", seed=1): """Gets cuda devices """ device = torch.device(cuda_device) torch.manual_seed(seed) # Multi GPU? num_gpus = torch.cuda.device_count() if device.type != 'cpu': print('\033[93m' + 'Using CUDA,', num_gpus, 'GPUs\033[0m') ...
c2115ed5409d0e73da25ab91f33dc8d479cd1034
28,933
def prior_creator(vector, priors_lowbounds, priors_highbounds): """ Generates flat priors between *priors_lowbounds and *priors_highbounds for parameters in *vector :param vector: array containing parameters optimized within flat priors :param priors_lowbounds: array containing lower bound of flat prio...
6351b1946daf2f956b45dc181d7192aa2e70fbbf
28,934
def read_dataset_file_metadata(client, dataset_name, filename): """Return metadata from dataset's YAML file.""" with client.with_dataset(dataset_name) as dataset: assert client.get_dataset_path(dataset.name).exists() for file_ in dataset.files: if file_.path.endswith(filename): ...
7bf9079614b02d984f722a593fbb81a3555705f2
28,935
import json def format_json(d): """ Covert a label like 'plate 1' to plate_1 """ return json.dumps(d)
1223ee362d7f5461bc9878eff5a57b84feafbd67
28,937
def to_string(pkt): """Pretty-prints a packet.""" name = pkt._name detail = '' if name == 'AppleMIDIExchangePacket': detail = '[command={} ssrc={} name={}]'.format( pkt.command.decode('utf-8'), pkt.ssrc, pkt.name ) elif name == 'MIDIPacket': items = [] fo...
ecdd0dfe3dd9bb2cb24351567520fd821619e19c
28,939
def overflow_error(): """Value doesn't fit in object.""" try: int(float('inf')) except OverflowError: return "infinite is too big"
ea07b420001e57d6efd1ab9fa4afb335f81c69fa
28,940
def parse_args(parser): """ Takes ArgumentParser and parses arguments """ parser.add_argument( "-p", "--path", required=True, help="Path to database", action="store", type=str) parser.add_argument( "-s", "--scema", required=True, ...
7978aca0fd9fd1a6659e03d4c8c5aa814e45c840
28,941
import copy import numpy def _determine_stream_spread_single(sigomatrixEig, thetasTrack, sigOmega, sigAngle, allinvjacsTrack): """sigAngle input may either be a function ...
d6e5e101d327b0fef714ae5d6d67abc94f92b069
28,942
from typing import List def get_input_size_with_dependencies( combiner_output_size: int, dependencies: List[str], other_output_features # Dict[str, "OutputFeature"] ): """Returns the input size for the first layer of this output feature's FC stack, accounting for dependencies on other output features. ...
bb4ad34718829a7e545f81b3b83089cb3d11eaaa
28,944
def delete_after(list, key): """ Return a list with the item after the first occurrence of the key (if any) deleted. """ if list == (): return () else: head1, tail1 = list if head1 == key: # Leave out the next item, if any if tail1 == (): ...
047ad50c25c1c6a2f2d25c5fba1d813b45bd1e17
28,945
def repeat(a, repeats, axis=None): """Repeat arrays along an axis. Args: a (cupy.ndarray): Array to transform. repeats (int, list or tuple): The number of repeats. axis (int): The axis to repeat. Returns: cupy.ndarray: Transformed array with repeats. .. seealso:: :func...
4a7a9382b9aa125dc66c2aaf8da0567c49d9aaf3
28,948
def resolve_variables(template_configuration: dict) -> dict: """ The first step of the lifecycle is to collect the variables provided in the configuration. This will add the name and value of each variable to the run-configuration. :param template_configuration: :return: """ run_configurat...
60fb49eaa7ffac3b677bac450402c778a6a8832f
28,950
def read_gr(filename): """Reas a single graph from a file.""" f = open(filename, "r") string = f.readline().split() num_nodes = int(string[0]) num_edges = int(string[1]) graph = {} indeg_graph = {} g_map = {} inv_map = {} g_list = [] counter = 0 for line in f: lin...
f9cd04b93977732cae46ec8f814f04bb1f21bbf0
28,951
import pickle def loadlists(): """Function to load all data""" with open("./data/members.txt", "rb") as file: members = pickle.load(file) with open("./data/signups.txt", "rb") as file: signups = pickle.load(file) with open("./data/joinrequests.txt", "rb") as file: joinrequest...
24a348d122fe11baa5075e84447a7c23746cac82
28,952
import json import base64 def extract_async_task_result_json_values(result_data): """Companion function to perform the inverse of `build_async_task_result()` """ payload = json.loads(result_data) content = base64.b64decode(payload['content']) content_type = payload['content_type'] filename = ...
460d992af67f5b31508449f622af3d413b24f37f
28,953
def mini_max_sum(array): """ Docs """ array.sort() min_sum = sum(array[:-1]) max_sum = sum(array[1:]) return min_sum, max_sum
5d54fe230c96cb155adbf950b0b4ca71502dbcbe
28,954
def getsupportedcommands(qhlp, dostrip=True): """Parse qHLP answer and return list of available command names. @param qhlp : Answer of qHLP() as string. @param dostrip : If True strip first and last line from 'qhlp'. @return : List of supported command names (not function names). """ qhlp = qhlp...
90cce0dd689f836b57788632681d33f3f717d239
28,955
def text_to_json(f): """Performs basic parsing of an AFDO text-based profile. This parsing expects an input file object with contents of the form generated by bin/llvm-profdata (within an LLVM build). """ results = {} curr_func = None curr_data = [] for line in f: if not line.startswith(' '): ...
efdf3cbba8fbacba78e05cf726dd619b54863866
28,956
def to_rational(s): """Convert a raw mpf to a rational number. Return integers (p, q) such that s = p/q exactly.""" sign, man, exp, bc = s if sign: man = -man if bc == -1: raise ValueError("cannot convert %s to a rational number" % man) if exp >= 0: return man * (1<<exp),...
3dccd2acc324d8b748fe95290c49d961f1c636e1
28,957
def int2ascii(i: int) -> str: """Convert an integer to an ASCII character. Args: i (int): Integer value to be converted to ASCII text. Note: The passed integer value must be <= 127. Raises: ValueError: If the passed integer is > 127. Returns: str: The ASCII charac...
f46ed05d425f9277ea6c97a0f8bafb070b15091c
28,958
def null_count(): """cleans Pandas Dataframes""" return 'this is a function'
4325a260f03c6e2de1d4e5cb56f0623628a53c4b
28,959
def strip_dollars(text): """ Remove all dollar symbols from text Parameters ---------- text : str Text to remove dollars from """ return text.strip('$')
ca084d64fb928f2374cbbf0a453bead52a2682a0
28,962
def get_from_dict_or_default(key, dict, default): """Returns value for `key` in `dict` otherwise returns `default`""" if key in dict: return dict[key] else: return default
14ad53c4cac7f554cfa537edeaf7a11e1e8ecac3
28,963
from typing import Mapping def genericDictValidator(value, prototype): """ Generic. (Added at version 3.) """ # not a dict if not isinstance(value, Mapping): return False # missing required keys for key, (typ, required) in prototype.items(): if not required: continue if key not in value: return Fal...
0ad002c33c38a50f06041f133e98fc79a2307d36
28,964
import math def distance_formula(x1: float, y1: float, x2: float, y2: float) -> float: """ Distance between two points is defined as the square root of (x2 - x1)^2 + (y2 - y1) ^ 2 :raises TypeError: Any of the values are non-numeric or None. """ return math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2...
5c1a4706365a2347bc23d7efcc74caa003405c0e
28,965
import os def _is_path_in(path, base): """Returns true if **path** is located under the **base** directory.""" if not path or not base: # empty path may happen, base too return False rp = os.path.relpath(path, base) return (not rp.startswith(os.path.pardir)) and (not rp == os.path.curdir)
c583bab64daae496973e6ea75738f5740d14b2b0
28,966
def validate_asn(asn): """ Validate the format of a 2-byte or 4-byte autonomous system number :param asn: User input of AS number :return: Boolean: True if valid format, False if invalid format """ try: if "." in str(asn): left_asn, right_asn = str(asn).split(".") ...
14806fc04132c06dbb75abb2ceefd0340b7845e6
28,967
def make_incrementtor(n): """Do thing , but document it jiushiwo """ return lambda x:x+n
92f82f8d17b587305c4e486cc826b7ddd3156de7
28,968
def bloch_sphere_plot_check(function): """Decorator to check the arguments of plotting bloch sphere function. Arguments: function {} -- The tested function """ def wrapper(u, v, w, xfigsize=15, yfigsize=7.5, frame_on=False, tight_layout_on=False, \ style='dark_background', surf...
a377a8b426ae004e0c22999c35b1a12dfb25e371
28,969
import math def get_points_distance(point1, point2): """ Gets the distance between two points :param point1: tuple with point 1 :param point2: tuple with point 2 :return: int distance """ return int(math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2))
40af84836715b49ba531fe5113e40230110d49b9
28,971
from typing import Tuple import unicodedata def validate_ae(value: str) -> Tuple[bool, str]: """Return ``True`` if `value` is a conformant **AE** value. An **AE** value: * Must be no more than 16 characters * Leading and trailing spaces are not significant * May only use ASCII characters, exclud...
aee3ec59ea1965bd745f1527368053c5c04e5c4b
28,972
def state2bin(s, num_bins, limits): """ :param s: a state. (possibly multidimensional) ndarray, with dimension d = dimensionality of state space. :param num_bins: the total number of bins in the discretization :param limits: 2 x d ndarray, where row[0] is a row vector of the lower limit...
c2a0cb48864e58481681e8c72074e618dda7ddb8
28,973
import pickle def load_db(pathname): """ returns the stored database from a pickle file Parameters ---------- pathname: string Returns ------- database: dictionary mapping names to profiles """ with open(pathname, mode="rb") as opened_file: database = pic...
2ca73cfaf500fd6a841cfb9dc12c3b21d320ac69
28,974
import numpy def _gauss_legendre(order, composite=1): """Backend function.""" inner = numpy.ones(order+1)*0.5 outer = numpy.arange(order+1)**2 outer = outer/(16*outer-4.) banded = numpy.diag(numpy.sqrt(outer[1:]), k=-1) + numpy.diag(inner) + \ numpy.diag(numpy.sqrt(outer[1:]), k=1) ...
70689e5644355f8c0c8658b59fca1c5bf4fcb0e1
28,976
def Read_Finished(filename): """Extracts sequences from a .seqs file""" f = open(filename,'r') lines = f.readlines() f.close() sequences = {} strands = {} for line in lines: # Check for comment if '#' in line: line = line.split('#')[0] parts = line.split(...
30f16fd03e6a62454f3a01fe3fe3fb1ed6f792bb
28,978
import struct def stringarray(string): """Output array of binary values in string. """ arrstr = "" if (len(string) != 0): for i in range(0,len(string)): arrstr += "%x " % struct.unpack("=B",string[i])[0] return arrstr
1c96a78f11bc1ea781658c3b23ce801a37dbde25
28,979
import os def parent(path, level=1, sep="/", realpath=False): """ Get the parent of a file or a directory :param path: :param level: :param sep: :return list: """ path = os.path.realpath(path) if realpath else path def dir_parent(path, level=1): return sep.join(path.split(...
aababa89db18c2a99c7c19053e75ac038829b7a1
28,981
def _is_user_author_or_privileged(cc_content, context): """ Check if the user is the author of a content object or a privileged user. Returns: Boolean """ return ( context["is_requester_privileged"] or context["cc_requester"]["id"] == cc_content["user_id"] )
7711d8fa31d3b6d590595ed0612cd19f6c1becc2
28,985
def gen_test_data(request): """ Generate test data. """ return request.param
18fcb668c1e46226289924f8f8a4f7d1d3588c36
28,988
def mkcol_mock(url, request): """Simulate collection creation.""" return {"status_code": 201}
313fb40302c282d102d6846980ce09ea3600c50c
28,989
def dict2bibtex(d): """ Simple function to return a bibtex entry from a python dictionary """ outstring = '@' + d.get('TYPE','UNKNOWN') + '{' + d.get('KEY','') + ',\n' kill_keys = ['TYPE','KEY','ORDER'] top_keys = ['AUTHOR','TITLE','YEAR'] top_items = [] rest_items = [] for k in d.keys(): if k in top_keys: ...
1ffbc9ec9754acf9904c959be05e0585302435a3
28,990
def random_permutation(df_list): """ Run permutations in the dataset Parameters --------- df_list: list list of pandas DataFrames, each DataFrames containing one traffic type Return ------ reordered_df_list: array Resulting array of pandas DataFrames """ df_list...
397328f9fe12a64d1cd4b552d680f4eea0fbbd89
28,991
def dict_as_args(input_dict: dict) -> str: """ Разложить словарь на последовательность аргументов будто это ключевые слова >>> dict_as_args(dict(a=1, b=2, c="test")) "a=1, b=2, c='test'" """ return ', '.join(f'{key}={value!r}' for key, value in input_dict.items())
9508c0517259056de8cf7570ab413d12eb4a65be
28,993
def generate_system_redaction_list_entry(newValue): """Create an entry for the redaction list for a redaction performed by the system.""" return { 'value': newValue, 'reason': 'System Redacted', }
22d7831106c6dd5350a3c86b51facc273835a1e6
28,994
from typing import Union def _print_result( start_quantity: Union[int, float], start_unit: str, end_unit: str, end_quantity: Union[int, float], ) -> str: """ Function to create final output string for conversion. :param start_quantity: Integer or float starting quantity which needed conve...
26228ea4c3064894748e5352ea117393031ee79b
28,995
import importlib def get_version(version_module_name): """Load currently declared package version.""" version_module = importlib.import_module(version_module_name) # always reload importlib.reload(version_module) version = f"{version_module.__version__}" print(f"version is {version}") re...
156d7e18e96ea0716011e0ca0536d38eaa078b9e
28,996
def _expand_task_collection(factory): """Parse task collection task factory object, and return task list. :param dict factory: A loaded JSON task factory object. """ return factory.tasks
1d2c0b2a763b9e3c78b4bea8d012575038a5804c
28,999
import platform def IsLinux(): """ Returns True if platform is Linux. Generic utility function. """ return (platform.uname()[0] == "Linux")
06ed6068d5914c25c5f24faf89979ca3e93620ca
29,002
from textwrap import dedent def dedent_docstr(s, n=1): """Dedent all lines except first n lines Args: s (type): some text to dedent n (int): number of lines to skip, (n == 0 is a normal dedent, n == 1 is useful for whole docstrings) """ lines = s.splitlines(keepends=True) ...
ce9d89bbba7ef6784e707fcae0ea6b127ee3cdcd
29,003
def _split_path(loc): """ Split S3 path into bucket and prefix strings """ bucket = loc.split("s3://")[1].split("/")[0] prefix = "/".join(loc.split("s3://")[1].split("/")[1:]) return bucket, prefix
46ace1084e7688847d60fe34e4b3958c89cfbd31
29,004
def strip_white_space_from_columns_of_dtype_str(df): """ Takes one parameter, a dataframe. """ for i in df.select_dtypes([object]).columns: s = df[i].copy() s.update(s.dropna().astype(str).str.strip()) df.loc[: ,i] = s.copy() del i, s return df
4857ab2938567c99770889be16356b92272c7ecc
29,006
def GetStepStartAndEndTime(build, full_step_name): """Gets a step's start_time and end_time from Build. Returns: (start_time, end_time) """ for step in build.steps or []: if step.name == full_step_name: return step.start_time.ToDatetime(), step.end_time.ToDatetime() return None, None
ef3d2a017ad6aa1e0b5c9c974a64d715ae62d1c1
29,008
def part1(adapters): """ Find adapters with jolt diff of 1 and 3 """ adapters.sort() adapters.insert(0, 0) # add 0 at start for the wall jolt adapters.append(max(adapters) + 3) # adding phone's inbuilt adapter diff_of_one = 0 diff_of_three = 0 for i in range(len(adapters) - 1): di...
639b0d46c3621a55f27fe4702688e8ae353060b0
29,009
import os def does_exist(file_with_path): """Checks if a file exists """ return os.path.isfile(file_with_path)
2e5266ca650b794a8039752817dbaca9602eed9c
29,010
import os def convert_audio_to_mono_wav(decoded_data): """ Поскольку vosk api принимает аудио определенного формата mono wav, а пользователь отправляет данные в другим расширением, например mp3, mp4a, mp4 etc, необходимо преобразовать их к нужному формату. input: decoded_data - аудио данные в исходном расширении...
e27f0981eeca30b85bbb92e9e930bff6922c391d
29,011