content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def qsfilter(qs, filter_items=[]): """ This function will take a query string of the form a=1&b=2&c=3 and return a string filter based on values. For example, passing in filter=['b'] will return a=1&c=3 """ result = [] params = qs.split('&') for param in params: if param.find('...
b07140975b8ed6232ebc1b1b0d08e9a4ac4a0f47
626,147
def cumsum(x): """The cumulative sum of an array.""" total = 0 sums = [] for el in x: total += el sums.append(total) return sums
8263fb81d1b4482f2cc895428ddec78e76b0f02b
626,150
import itertools def _create_combinations(ctx, **parameters: dict): """ Creates all the possible combinations of hyper parameters passed :param parameters: Dictionary containing hyperparameter names and their possible values :return: A list containing all the combinations and a list containing the hyp...
e23c9e16589303f6c36f9e9cd043790f9709ee04
626,151
def tip(bill): """Adds 15% tip to a restaurant bill.""" bill *= 1.15 print("With tip: %f" % bill) return bill
c013111fd3eadeccc45d9d01315f460ed75acd32
626,152
def filter_nth_play(data, keep_range): """Filter gameplay data to only retain games for which the nth play is within the range keep_range. Args ---- data (dict): Preprocessed gameplay data. keep_range (array like): An interval which defines the range of gameplays to keep. For example,...
d515e9a33d29fea5dcc59d13dc7c88172a4171a7
626,153
def binary_search(items, item): """Return True if items includes the item, otherwise False. Assume the items are in non-decreasing order. Assume item and items are all of the same type. """ first = 0 last = len(items) - 1 while first <= last: # Base case: the item is in the middle. ...
963f4647ce540465c961d20d457a0b058583780e
626,155
def find_section(lines, MF=3, MT=3): """Locate and return a certain section""" v = [l[70:75] for l in lines] n = len(v) cmpstr = '%2s%3s' % (MF, MT) # search string i0 = v.index(cmpstr) # first occurrence i1 = n - v[::-1].index(cmpstr) # last occurrence return lines[i0: i1]
a377698995af92886453402d2bedc0bc533a8098
626,158
def fit_info(pressures, temp_dct, err_dct): """ Write the string detailing the temperature ranges and fitting errors associated with the rate-constant fits at each pressure. :param pressures: pressures the k(T,P)s were calculated at :type pressures: list(float) :param temp_dct: temp...
cdcbcd52c559d1c06b8594c523d813fc4ccead5d
626,161
def filter_by_term(course: tuple[str, str, set], term: str) -> tuple[str, str, set]: """Return a copy of the given course with only sections that meet in the given term. The returned tuple has the same course code and title as the given course, and its sections set is a subset of the original. Note th...
382629f891af5b1744591a1465989068ed9adc22
626,171
def six_digits(x): """ Return string of six digits. """ return f"{x:06}"
5f1298409ebca80f88048b89c01de77d91877eb8
626,172
import math def entropy(text): """ Compute the entropy of a string. Taken from https://rosettacode.org/wiki/Entropy#Uses_Python_2. @param text (str) The string for which to compute the entropy. """ log2=lambda x:math.log(x)/math.log(2) exr={} infoc=0 for each in text: ...
db92ddaaf77c3618ca265bb240de890fa8b8b20f
626,173
def moment_from_magnitude(magnitude): """ Compute moment from moment magnitude. Args: magnitude (float): Moment magnitude. Returns: float: Seismic moment (dyne-cm). """ # As given in Boore (2003): # return 10**(1.5 * magnitude + 10.7) # But this appears to ...
cba2fce2cecffbd0def80c86702e982d933f2c68
626,175
def _convert_list_of_objs_to_list_of_dicts(list_of_objects): """ Recursively convert a list of objects to a list of dicts. This works recursively and is needed because the NLP Textanalyzer sometimes gives back a list of non-json-serializable objects, which need to be converted to dicts. The list st...
1a56b8ea1bd4cc985335ed013b0b6c7a90f60a4d
626,176
def extends_doc(extended_func): """ A function decorator for use when wrapping an existing function but adding additional functionality. This copies the docstring from the original function, and appends to it (along with a newline) the docstring of the wrapper function. Example ------- ...
29b1a4b29e3fd88643892ed9e3badc31ad3a866d
626,177
from pathlib import Path def root_directory(request): """Gets root directory""" return Path(request.config.rootdir)
76a8b20ec2186c1f7b4233c2d200c61b6e4ecc81
626,183
def _find_healpix_extension_index(pth): """Find the first HEALPIX extension in a FITS file and return the extension number. Raises IndexError if none is found. """ for i, hdu in enumerate(pth): if hdu.header.get('PIXTYPE') == 'HEALPIX': return i else: raise IndexError("N...
bda0f1698ad1d099c8a6db909469bfc5acd1e36d
626,184
def _validate_term(term_text: str, allowed_ids: list): """ Check term is a valid format. :param term_text: text to validate, e.g. "NCBITaxon:9606" or "UBERON:12391203". :param allowed_ids: a list of allowed identifier prefixes, e.g. ['GO', 'UBERON'] or None if dont' want to restrict. :return: bool ...
4598240038f5a27f5b163bd8a5f24d5c0feb2d61
626,185
from datetime import datetime def str_to_datetime(s) -> datetime: """ Parse datetime from string. """ return datetime.fromisoformat(s)
c02d79f28361535f09d3199c5476d855dbfc7397
626,186
def get_gauss_job_type(setting_dict): """ Check the job type according to the setting_dict Args: setting_dict (str): A dict containing setting generated from parse_gauss_options Returns: (str): A str represents the job type """ # Check if composi...
4356bc5167d143ea7b5f8125b8480cf9d37be72f
626,189
def obj_to_str(obj): """ Convert an object to a string if it's not already a string. If it's a list, join its items into a single string. Parameters ---------- obj : str or list[str] Object to convert to string Returns ------- Str Object as a string """ r...
99390ea2edc3ca3f0e1f0ba7664b6824ed3d4775
626,190
def image(index): """Return the image name for the given index.""" return f'im-{index}.png'
c4085b9a1f3de3404048ef1d175da332c8b993e8
626,191
def _stft_frames_to_samples(frames, size, shift): """ Calculates samples in time domain from STFT frames Args: frames: Number of STFT frames. size: FFT size. shift: Hop in samples. Returns: Number of samples in time domain. """ return frames * shift + size - shi...
bc306a76e7e007b0252dc2ea01c70b615d1cc566
626,192
import torch def logabsdet(x): """Returns the log absolute determinant of square matrix x.""" # Note: torch.logdet() only works for positive determinant. _, res = torch.slogdet(x) return res
ad76da6d4ddc8bffdcb07025c98facf869380e80
626,194
def member_needs_update(before, after): """ See if the given member update is something we care about. Returns 'False' for no difference or change we will ignore. """ for attr in ("nick", "avatar", "roles"): if getattr(before, attr) != getattr(after, attr): return True ...
5803e9affa7028e36e2bd5a74049ecc3771896ca
626,196
from datetime import datetime def create_timestamp_csv(destination): """ create csv file name based on timestamp """ today = datetime.now() csvName = destination + "/" + today.strftime('%Y%m%d-%H-%M-%S') + ".csv" return csvName
7030fc5fa7db9123fc2c6fd1be725f504fe72fab
626,200
def get_start_index(idx, log_msgs, start_time): """ Function that searches for the index of the oldest log message whose ts >= start_time (starting from idx) Args: idx (int): Index to start from log_msgs (list(DistributedLogLines)): List of messages to process start_time (float): The...
d4d73c75cb72179256e0c8401ddb7ad1fa21c1d9
626,204
def copy_location(new_node, old_node): """ Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ for attr in 'lineno', 'col_offset': if attr in old_node._attributes and attr in new_node._attributes \ and h...
2ac38290ea69c97b28b6121c851f5899e03ac9dd
626,205
import base64 def encode_byte_array(byte_arr): """ Encodes the byte array as a base64-encoded string :param byte_arr: A bytearray containing the bytes to convert :return: A base64 encoded string """ enc_string = base64.b64encode(bytes(byte_arr)) return enc_string
0134d159d869b3adb7f371848f6a60818660ee0d
626,206
def rgb_to_xy(red, green, blue): """ conversion of RGB colors to CIE1931 XY colors Formulas implemented from: https://gist.github.com/popcorn245/30afa0f98eea1c2fd34d Parameters: red (float): a number between 0.0 and 1.0 representing red in the RGB space green (float): a number between 0.0 ...
3eef26117dbb9aa32ec00bffd92a39fa30ca7399
626,208
def recuperer_classe(data): """ Renvoie une liste contenant la classe de chaque point. Paramètres ---------- data : array_like Liste de la forme (nb_point, nb_parametre + 1) contenant les points dont on veut extraire les classes. Retours ------- classes : array_like ...
d94cd09b465174365332795635d4228a415cda9a
626,210
def to_str(value): """converts int to string""" return str(value)
935142228f1ebacb5ab9708cd8bff1cd5aa82af1
626,211
def multiaxis_reduce(ufunc, arr, startaxis=0): """ used to get max/min over all axes after <startaxis> CommandLine: python -m vtool.numpy_utils --test-multiaxis_reduce Example: >>> # ENABLE_DOCTEST >>> from vtool.numpy_utils import * # NOQA >>> rng = np.random.RandomSt...
0210e151993442e4f0c8b91c5bb9ba256147b584
626,213
def binize(data, bin_size): """Binning a numpy array.""" return data[:(data.size // bin_size) * bin_size].reshape(-1, bin_size)
e6695d955c9b8ebc85c70803763721af75e4f8df
626,214
def project_dict(project): """Convert the project object to a result dict""" if project: return { 'projectname': project.id, 'project_manager_id': project.project_manager_id, 'description': project.description} else: return {}
b093ed7eee5928cdf8ca9416fcce0c622198defe
626,215
import math def perpendicular(angle): """ Returns the perpendicular angle to the given angle. Parameters ---------- angle : float or int The given angle in radians Returns ------- perpendicular : float The perpendicular to the given angle in radians """ perp =...
555cad5f9f57244f9c375d3b3111575a6eb9ef88
626,217
def printBond(bond): """Generate bond line Parameters ---------- bond : Bond Object Bond Object Returns ------- bondLine : str Bond line data """ R0 = 0.1*bond.R0 K0 = bond.K0*836.80 return '<Bond class1=\"%s\" class2=\"%s\" length=\"%0.6f\" k=\"%0.6f\"/>\...
813b5d67eaa9119efc74bf018e647486faa0074b
626,219
def find_hpo_row(sheet, hpo, sheet_name, selective_rows, analytics_type): """ Finds the row index of a particular HPO site within a larger sheet. :param sheet (dataframe): dataframe with all of the data quality metrics for the sites. hpo (string): represents the HPO si...
b40c0ee7408053842fd29924f45be5b5af4672bf
626,223
def word_size(word): """ Returns the length of the word """ return len(str(word))
561b9c6a5a169c542c29e935aebc17c0ec589b8d
626,226
def _age_map_select(seq_to_age_tup, age): """Return a map from keys to the second item in age_tup, optionally limited to those <= the provided age.""" if age is None: return {k: v[1] for k, v in seq_to_age_tup.iteritems()} else: age = float(age) return {k: v[1] for k, v in seq_to_age_tup.iteritems()...
14fdc1da75cbc625e588839e8b65b172d0ce8900
626,227
def verts_equal(v0, v1, epsilon=1e-8): """ Test if two given vertices are equal within a certain epsilon. WARNING: This is slower than ==, but it allows for a tolerance level of equality. """ assert epsilon >= 0.0 if len(v0) != len(v1): return False for a, b in zip(v0, v1): ...
566fbba47e0814fe0f9e16ae39ba7a237425de67
626,229
def get_yaml_var(hparam_file): """Extracts from the input yaml file (hparams_file) the list of variables that should be used in the script file. Arguments --------- hparam_file : path Path of the yaml file containing the hyperparameters. Returns ------- var_list: list l...
b13c6e0e5fecb5d8ac58a141a522d80291aef3bb
626,232
def get_ratios(L1, L2): """Assumes: L1 and L2 are lists of equal length of numbers Returns: a list containing L1[i]/L2[1] >>> get_ratios([1, 2, 3, 4], [2, 4, 6, 8]) [0.5, 0.5, 0.5, 0.5] >>> get_ratios([4, 9, 10, 7], [3, 2, 9, 11]) [1.3333333333333333, 4.5, 1.1111111111111112, 0.6363636363636364...
aedbbeca1c7631df38c069eecef441305b6cd8aa
626,238
def _set_dim_and_center(dim, center, default_dim=2): """ A helper function to check that a user provided dim and center match, or if no user provided dim and center exist sets default values: dim=2 and center=the origin in R^dim. """ # Set the dimension if dim is None: if center is None:...
8f15d31fe8f35b050ab77cd326f1d8b54b6137b2
626,239
def common(n): """ Returns true if the node is in the common directory. """ filename = n.filename.replace("\\", "/") if filename.startswith("common/") or filename.startswith("renpy/common/"): return True else: return False
a14b680b6a016b5d13385df07071091127d7b72e
626,240
def resolve_ref(spec: dict, ref: str) -> dict: """ Parameters ---------- spec full openapi spec of the app ref reference to look up Returns ------- Part of the schema at the ref """ if not ref.startswith("#/"): raise ValueError(f"Invalid OpenAPI ref {ref}...
9cd9f1cb4596baf5f0840d11294830f459d19385
626,241
def ConstructViceroyBuildDetailsURL(build_id): """Return the dashboard (viceroy) URL for this run. Args: build_id: CIDB id for the master build. Returns: The fully formed URL. """ _link = ('https://viceroy.corp.google.com/' 'chromeos/build_details?build_id=%(build_id)s') return _link % ...
94eca6bb5b089e2379f814195954317ef7181bb1
626,242
def get_object(context): """ Get an object from the context or view. """ object = None view = context.get("view") if view: # View is more reliable then an 'object' variable in the context. # Works if this is a SingleObjectMixin object = getattr(view, "object", None) ...
27f4b346d6e50d9bfe684643133d69511ea9ca22
626,243
def get_next_speaker_and_last_speaker(conversation_posts, author, partner): """ Input: All the current posts in a 2 speaker conversation The two speakers Output: Based on the given list of posts, return who speaks next and who spoke last """ last_speaker = author next_spe...
bb1e06d7f2556eef03f1341ef82349d21dec10ae
626,244
def interaction_lifeline_group(parent, element): """Add lifeline to interaction.""" element.interaction = parent return True
71b9cb82efc3a16d03c55f91b9090f23ea37a1d4
626,248
def get_schema(buf): """ Extract the schema code embedded in the buffer :param buf: The raw buffer of the FlatBuffers message. :return: The schema name """ return buf[4:8].decode("utf-8")
de99cb7347b39239ee57976b2d3c9c4c4c172040
626,249
def convert_to_ascii(string: str) -> str: """Given a string, omit any non-ascii characters. The knowledge graph only supports ascii. Args: string (str): the string to convert. Returns: str: the same string, without any non-ascii characters. "ñàlom" would be converted to "lom". ...
7c727eed92947199e14472036c7e866b63f863d8
626,262
def predict_logits(img_x, phrases_x, f_similarity): """ Compute given similarity measure over the last dimension (features) of `img_x` and `phrases_x`. :param img_x: A [*, d1, d2, d3] tensor :param phrases_x: A [*, d1, d2, d3] tensor :param f_similarity: A similarity measure between [*, d3] tensors...
8659a82e2502e3ed9945eb208b4b4eeed0d6a28c
626,270
import json def schema_to_json(schema: dict, indent: int = 2) -> str: """Convert the given JSON schema (dict) into a JSON string.""" return json.dumps(schema, indent=indent)
4424f3dd5548eadb9ee9a36208766a8b6f6f290a
626,271
def _iframe(src, width=650, height=365, content=None, link=None): """Create an iframe html snippet.""" html = ( '<iframe width="%s" height="%s" src="%s" ' 'frameborder="0" allowfullscreen></iframe>' ) % (width, height, src) if not content: return html if link: content...
e1bab08c060b808dc669d7b2d774a67ec6c8b8ee
626,272
def generate_time_str(time): """convert time (in seconds) to a text string""" hours = int(time // 60**2) minutes = int((time - hours*60**2) // 60) seconds = int((time - hours*60**2 - minutes*60) // 1) ret = '' if hours: unit = 'hr' if hours == 1 else 'hrs' ret += f'{hours} {unit...
b1ea7441feb33cbfdb39ec08997ca101eefba21d
626,274
import json def load_json(fil): """ Loads a json file. """ dat = None with open(fil, "rt") as fh: dat = json.load(fh) return dat
56ac60be3583ba82e9116b3d56482d52efe80400
626,280
def _aperture_mean_nomask(ap, image, **kwargs): """ Calculate the mean flux of an image for a given photutils aperture object. Note that we do not use ``_aperture_area`` here. Instead, we divide by the full area of the aperture, regardless of masked and out-of-range pixels. This avoids problems ...
666c367823f33f9754c8b3277a9c651699e0b994
626,284
def RB_decay_to_gate_fidelity(rb_decay, dimension): """ Derived from eq. 5 of [RB] arxiv paper. Note that 'gate' here typically means an element of the Clifford group, which comprise standard rb sequences. :param rb_decay: Observed decay parameter in standard rb experiment. :param dimension: Dimens...
ecb756c25e3c4b328b85e57c251b636d1e157d34
626,285
def add(summand_a: int, summand_b: int) -> int: """Adds to integers and returns its sum""" return summand_a + summand_b # x = 'this is very very very very long script that has no obvious reason to exist'
dd72c3f31a101e9061023542aafb558a9e79c5e4
626,287
import glob def case_insensitive_glob(pattern, **kwargs): """ Glob without case sensitivity Args: pattern (:obj:`str`): glob pattern **kwargs Returns: :obj:`list` of :obj:`str`: path of files that match the glob pattern """ def either(c): if c.isalpha(): ...
ebbe5ab8674c5aef57bd1beaf632a86f701480b3
626,289
import requests def fetch_player_history(player_id): """ Fetch JSON of a single player's FPL history. """ url = "https://fantasy.premierleague.com/drf/element-summary/{}".format(player_id) r = requests.get(url) return r.json()["history_past"]
07e07bd793c02430eb9605f177301eef00d9bd98
626,294
import copy def sanity_check_states(states_spec): """ Sanity checks a states dict, used to define the state space for an MDP. Throws an error or warns if mismatches are found. Args: states_spec (Union[None,dict]): The spec-dict to check (or None). Returns: Tuple of 1) the state space des...
f53e57b1c36ba120fd7f03259ff19df033ba4143
626,297
def rr_and_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with AND logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array ...
71099115ffe2a30a4055c42764ff4587493066d8
626,302
def quadsplit(quad): """Split ccw quad to two triangles""" v1, v2, v3, v4 = quad return [ [v1, v2, v3], [v3, v4, v1]]
9e567beeefad574efbba0b10b7134c78456446ee
626,306
import torch def synthetic_data(w, b, num_examples): #@save """Generate y = X w + b + noise.""" X = torch.zeros(size=(num_examples, len(w))).normal_() y = torch.matmul(X, w) + b y += torch.zeros(size=y.shape).normal_(std=0.01) return X, y
784d9b00f6d67023d4a90c335cc2e7e7f2bb5088
626,308
def rivers_with_station(stations): """ Returns a set of all rivers monitored by 'stations'. 'stations' is a list of 'MonitoringStation' objects. Documentation for object 'station' can be found by importing 'station' from 'floodsystem' and typing 'help(station.MonitoringStation)' """ river_lis...
09116b99992ef32dd1506a37e4e39622b29c5bd6
626,309
def newton_sqrt1(x): """Return the square root of x using Newton's method""" val = x while True: last = val val = (val + x / val) * 0.5 if abs(val - last) < 1e-9: break return val
27c699eb1b26956ca630fce063ee12a336e02883
626,312
def prepend_indent(string, indent_level): """ Add a given indent before every line of the string :string: string to which we want to append the indent :indent_level: integer number of spaces to prepend """ indented = "".join("{}{}\n".format(" "*indent_level, line) for line in string.splitlines(...
191a2c9903278dba23e01c7d215e773b237553cf
626,313
def get_is_head_of_word(naive_tokens, sequence_tokens): """ Return a list of flags whether the token is head(prefix) of naively split tokens ex) naive_tokens: ["hello.", "how", "are", "you?"] sequence_tokens: ["hello", ".", "how", "are", "you", "?"] => [1, 0, 1, 1, 1, 0] *...
d3cb375bf8a6a7eb2e469b0a16c19a7b7089573c
626,322
def half_period_uncoupled(t, x, par): """ Returns the event function Zero of this function is used as the event criteria to stop integration along a trajectory. For symmetric periodic orbits this acts as the half period event when the momentum coordinate is zero. Parameters ---------- t :...
c44c772f60691a31f98b4143341dbf567847e5e7
626,323
def part_device(part_number): """Given partition number (but string type), return the device for that partition.""" return "/dev/mmcblk0p" + part_number
2e4feb3ad1c93166ebade7fafe8ddccabdc3b9f1
626,327
def wrap_to_pm(x, to): """Wrap x to [-to,to).""" return (x + to)%(2*to) - to
a6a0bb614972121529dec3e379ce3378587c082d
626,332
from typing import Dict from typing import List def create_dict(n: int) -> Dict[int, List[int]]: """Returns Dictionary with numbers from 0 to n as keys which are mapped to lists containing squares and cubes of the respective keys. doctests: >>> create_dict(1) {0: [0, 0], 1: [1, 1]} ...
c208e595d8724b3a716b30f4db675cbe5368b642
626,333
def err_response(reqid, code, msg, data=None): """ Formats a JSON-RPC error as a dict with keys: 'jsonrpc', 'id', 'error' """ err = {"code": code, "message": msg} if data: err["data"] = data return {"jsonrpc": "2.0", "id": reqid, "error": err}
d8f62af41c25b271c8433b48887ae5ac94564466
626,334
def magic_square_params(diagonal_size): """ This is a helper function to create the gene_set, optimal_fitness and the expected sum of all the rows, columns and diagonals. :param diagonal_size: The diagonal length of the magic square. :type diagonal_size: int """ numbers = list(range(1, ...
5c1c57388fd94c25c4c4ec6ee26e5519780af135
626,336
def get_translate_str(type_name: str, namespace_: str, name: str) -> str: """ 规范得到翻译序列 :param type_name: 类型 :param namespace_: 命名空间 :param name: 名称 :return: 翻译序列 """ return f"{type_name}.{namespace_}.{name}"
cf03e653ed74ef9df5d30418b6e9e21c05a541bf
626,338
def quick_pow(n: int, k: int, p: int) -> int: """Find n^k % p quickly""" if k == 0: return 1 tmp = quick_pow(n, k // 2, p) ** 2 return tmp % p if k % 2 == 0 else tmp * n % p
b6acec3d10903d41af59882a1a6d708c238a8661
626,339
import itertools def combine_bucket( parts: list, threshold: int, truncate: bool = False, keep_remain: bool = False) -> list: """ Convert parts to buckets with given length(threshold). Parameters ---------- parts: the given parts. threshold: bucket length. ...
c994a6cd19a538ea572f24ed17b100db68877f89
626,341
def remove_dataset_id(df, ds1_trend_column, ds2_trend_column): """deletes the data set id from a given ptcf :param df: PTCF data frame :ds1_trend_column: column name ds 1 :ds2_trend_column: column name ds 2 :return: ds without data set information """ df[ds1_trend_column] = df[ds1_trend_column].str.split('...
b95339fe0d2b7eb6cc6df6cd6c34bc999b7d8c44
626,342
import re def strip_number(number): """Strips the number down to just digits.""" number = re.sub("[^0-9]", "", number) return number
12f627d9ad6f526f39f1919f67c1b1943f82f2fe
626,343
from typing import List from typing import Tuple def stretch_in_row_or_column( stretched_list: list, two_coordinates: tuple ) -> List[Tuple[int, int]]: """ Update a list of coordinates by coordinates between two boundaries of a line. Form a line in horizontal or vertical direction. Args: ...
29840aa92950c11aca997131726b592c934d4645
626,344
import math def normalize_function(foo, interval=(0, 1), precision=100): """ Normalizes function on given interval. Args: foo (function): Function to be normalized. interval (tuple): Interval of normalization. precision (int): Precision of numerical calculations. Returns: ...
449ed42542ec5c86878c6a5ab7507bea1235afee
626,354
def num_in_base(num, base): """Converts an integer to its representation in base in big-endian. e.g., num_in_base(14, 2) = [1, 1, 1, 0]. Args: num: the number to convert. base: the base of the representation. Returns: The list of digits in big-endian. """ if num == 0: return [0] digits...
a75353c571b0cb9db84025d558884b126983b76a
626,356
def compare_lists(list1: list, list2: list): """Returns the diff of the two lists. Returns ------- - (added, removed) ``added`` is a list of elements that are in ``list2`` but not in ``list1``. ``removed`` is a list of elements that are in ``list1`` but not in ``list2``. """ added = ...
dcc7f97c02b6b2b846179772dd81211c9b0cc040
626,357
import time def get_local_time_str(for_file_name=False) -> str: """Return current time str in the format %Y-%m-%d %H:%M:%S""" if not for_file_name: cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) else: cur_time = time.strftime("%Y-%m-%d--%H-%M-%S", time.localtime()) ret...
aeaae88c1ed33aa30318c486a3ecb8a413ce2f34
626,358
import importlib def load_module(module_name): """ Dynamically imports the specified module and returns it. :param str module_name: Name of the module to be imported as a string. """ return importlib.import_module(module_name)
0b74e6facf1b8ee16b316b5d3d62260c86e3c0df
626,363
def item_empty_filter(d): """return a dict with only nonempty values""" pairs = [(k, v) for (k, v) in d.items() if v] return dict(pairs)
177c15a58438f5a231d153cf1866051caf29a2fa
626,371
def unicode_double_escape(s: str) -> str: """Remove double escaped unicode characters in a string.""" return bytes(bytes(s, "ascii").decode("unicode-escape"), "ascii").decode( "unicode_escape" )
f3d652ec9b50a64bae198b2dac73261bc87a2db0
626,378
def write_csv_file(dataframe, path): """ Write new file with provided dataframe path: the path to the new file dataframe: the data that need to be saved """ file_name = path+".csv" dataframe.to_csv(file_name, sep='\t', encoding='utf-8') print( "File {}.csv created".format(path)) ret...
be45f8285f1b5ad7975a41878d507efa9479d14c
626,379
import pathlib import xxhash def _get_xxhash(file_path: pathlib.Path) -> str: """Compute the hash of the content of file_pathpath""" n = file_path.stat().st_size x = xxhash.xxh128() m = 2 ** 23 # read 8MB each time with file_path.open('rb') as f: if n < m * 128: # <= 1GB, check the whole ...
45c5fa74ecec96b6b7018e2c2af0069324b3989f
626,380
def find_image_essex(client, image_name): """ Looks up the image of a given name in Glance. Returns the image metadata or None if no image is found. """ images = client.get_images(filters={'name': image_name}) if images: return images[0] else: return None
6bbd2657dbcf5d519a91565c198b769f48d9cd87
626,381
def parse_remote(path,loopback=False,login_flag=False): """parse remote connection string of the form ``[[user@]host:]path`` Args: path (str): remote connection string. loopback (bool, default=False): if True, ensure *host* is used. login_flag (bool, default=False): if True, prepend use...
37e08f871551426c098a92803adbaf9a02d57308
626,383
def one_api(testCase, core): """ Get the only API registered against a given MimicCore. :return: 2-tuple of ``region`` and ``service_id`` """ service_id = None api = None # Since there is only 1 API it can be assumed to be either an internal # or external API. if len(core._uuid_to_...
4935400c3ca03cdbb65605182c74ced8f2c594e6
626,384
def compose1(f, g): """Return the composition function which given x, computes f(g(x)). >>> add_one = lambda x: x + 1 # adds one to x >>> square = lambda x: x**2 >>> a1 = compose1(square, add_one) # (x + 1)^2 >>> a1(4) 25 >>> mul_three = lambda x: x * 3 # multiplies 3 to x ...
b387466b2b4ae56dea2dd8a30ed77119ce8185f4
626,385
def parsenumber(v, strict=False): """ Attempt to parse the value as a number, trying :func:`int`, :func:`long`, :func:`float` and :func:`complex` in that order. If all fail, return the value as-is. .. versionadded:: 0.4 .. versionchanged:: 0.7 Set ``strict=True`` to get an exception if...
43e65d7aad52003d217cc74d0e6929f61300b592
626,388
def missing_layers(dm_layers, ds_layers): """Find missing datamodel-layers in datasets.""" layers = [i.lower() for i in ds_layers] layers = [i for i in dm_layers if i not in layers] return layers
ec805b48405e1eb56a04dc28768da0fe1bafee7a
626,397
import requests def get_installation_token(installation_id, integration_jwt): """Create a GitHub token for an integration installation. Parameters ---------- installation_id : `int` Installation ID. This is available in the URL of the integration's **installation** ID. integration...
f9c9a21635d00dc2c0ef4aaff91ff41f7e25a177
626,398
def make_words(text): """ make a list of words from a large bunch of text Strips all the punctuation and other stuff from a large string, and returns a list of words """ replace_punc = [('-', ' '), (',', ''), (',', ''), ('.', ''), ...
a45b2b0cf4c9fd83addc002426da3b5196da15e8
626,402
def is_external(config): """ Checks if the configuration is for an external transport. :param dict config: configuration to check :return: True if external, False otherwise :rtype: bool """ return config.get("external") == "1"
814a5b7bcf8c1a3a71a49c945180f8f18fc2fceb
626,408
def obj_frequencies(df): """Total number of occurrences of individual objects over all frames.""" return df.noraw.OId.value_counts()
6b642185dbd9f10201452bcad076c8a0da813949
626,410