content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Any def replace(strx: Any, old: str, new: str) -> Any: """ In allen Strings der Struktur ersetzen. :param strx: In dieser Struktur ersetzen. :param old: Diesen Teil ersetzen. :param new: Diesen Teil einsetzen :return: Kopie mit der Ersetzung """ if type(strx) is str:...
196be389694be74bc71bf2ea894c4b2f4adf7568
676,888
def parse_input(file): """ Parse input file's lines into dictionary Args: file: a str represent the path to input Returns: input_dic: a dictionary where key is origin city name and value is destination ciry and distance. """ input_dic = {} with open(file, 'r'...
e9a0684e7bc1c96cee17759271632d87a9cd7bd9
676,889
import torch def zero_out_col_span(xfft, col, start_row, end_row=None): """ Zero out values for all data points, channels, in the given column and row span. :param xfft: input complex tensor :param col: the col number to zero out value :param start_row: the start row (inclusive, it is zeroed ...
5a17aeb49abaee53c19cf8451657e13def7cc7eb
676,890
def segt2PathT(path, seg, t): # formerly segt2PathT """finds T s.t path(T) = seg(t), for any seg in path and t in [0,1]""" # path._calc_lengths() # # Find which segment the point we search for is located on: # segment_start = 0 # for index, segment in enumerate(path._segments): # ...
403ed3aeaeb747e9bc1dd7701a4f67ccfec64cb3
676,891
def get_classification_result_brief(crslt): """ crslt: an instance of classrslts returns a string with each category/classification pair """ return {cat: cla[0] for cat,cla in crslt.classification_result.items()}
edbc0a3c05da418190030932c95aae39d93a75f6
676,892
import selectors # Inline import: Python3 only! def _python3_selectors(read_fds, timeout): """ Use of the Python3 'selectors' module. NOTE: Only use on Python 3.5 or newer! """ sel = selectors.DefaultSelector() for fd in read_fds: sel.register(fd, selectors.EVENT_READ, None) ev...
f384019437990190dfd596f96090c41e099b855c
676,893
from typing import OrderedDict def _Net_layer_dict(self): """ An OrderedDict (bottom to top, i.e., input to output) of network layers indexed by name """ if not hasattr(self, '_layer_dict'): self._layer_dict = OrderedDict(zip(self._layer_names, self.layers)) return self._layer_dict
4421d7e1c728d113329a5c99435c8d1355dde406
676,894
def weWantThisPixel(col, row): """ a function that returns True if we want # @IndentOk the pixel at col, row and False otherwise """ if col%10 == 0 and row%10 == 0: return True else: return False
7dfd084e845df8c927a31d9565ba386ed9132e1b
676,895
def get_module_details(baseurl, modules): """Get extended details for the modules in the list. Args: modules (list): [description] Returns: list: List of modules including details """ module_details = [] for mod in modules: data = mod.split("/") details = { ...
b1a1ac9e6c0b1be0b263741e5b292e20a0eba37d
676,896
def clean_data(data): """ Takes a DataFrame with incomplete values and fills in NaN fields, dropping constant columns, returning array """ data.fillna(value=data.mean(), inplace=True) # fills numerical NaN values with mean data.fillna(value=str(0), inplace=True) # fills categorical NaN values with zero s...
78bf4d44700b8642c421e98a2fab614b673e2279
676,897
def lookup_tlv_type(type_id): """Convert TLV type to human readable strings by best guess""" result = 'unknown' if type_id == 0x01: result = 'MAC address' elif type_id == 0x02: result = 'address' elif type_id == 0x03: result = 'software' elif type_id == 0x06: re...
a77737d68e85844a25e1dde2ecbbff26a0438640
676,898
def __find_name_column(df, scientific_names): """Return a tuple of (name_column, overla_size).""" max_overlap, name_col_name = -1, None for col_name in df.columns: unique_col_vals = set(df[col_name]) overlap_size = len(unique_col_vals & scientific_names) if overlap_size > max_overlap...
9334c52dc7fe16d12c7deef2cf4d0657b3aa76c0
676,899
import os def find(name, limit=2): """Check if path (file or directory) exists somewhere in the directory tree, up to given distance limit, default 2. :param name: path checked for existence :param limit: number of directory levels to traverse while searching for the path :return: valid existing stri...
2300b4997c9fbc84763a89d3b205196fb9482884
676,900
def are_gtids_in_executed_set(gtid_executed, ranges, *, exclude_uuid=None): """Takes a dict of {uuid: [[start1, end1], ...]} mappings and binlog ranges as arguments and determines whether the dict contains all of the binlog ranges.""" if not gtid_executed: return False for rng in ranges: ...
ca2b01cd8dfda26e0ca34fa7b490d696c1fd9dc0
676,901
import requests import json def get_app_config(app_id): """ Get specific configuration for 'app_id'. """ try: req = requests.get( ("https://clients3.google.com/" "cast/chromecast/device/app?a={}").format(app_id)) return json.loads(req.text[4:]) if req.status_code == 2...
d0966508c0bf86237d978479a42a01d7badaecba
676,902
import calendar def date_to_dow(y, m, d): """ Gets the integer day of week for a date. Sunday is 0. """ # Python uses Monday week start, so wrap around w = calendar.weekday(y, m, d) + 1 if w == 7: w = 0 return w
2598df93dbf1b36f93af2b6e26f522cd6f60d328
676,903
def get_user_login_info(login, users, user_login_rel): """ Return a dict of data for each user; it's important that the users remain in the same order. """ login_is_active = login.is_active and login.machine.is_active info = [] for user in users: is_allowed = (user.pk, login.pk) in ...
43500b720be07689e63e3fe59b5c95a2df04fe0c
676,904
def hi_to_wbgt(HI): """ Convert HI to WBGT using emprical relationship from Bernard and Iheanacho 2015 WBGT [◦C] = −0.0034 HI2 + 0.96 HI−34; for HI [◦F] Args: HI = heat index as an array """ WBGT = -0.0034*HI**2 + 0.96*HI - 34 return WBGT
f34a646a89b3da6d4fa2c068e4142ab86753aa9b
676,905
import numpy def simpson(dim: int) -> numpy.ndarray: """ Make H matrix for estimating Fredholm equations as in (Twomey 1963). Parameters ---------- dim : int The dimension of the H matrix. Returns ------- weights : 1-D array The quadrature weights according to Simpson...
4ff03acf43976d63894d3d3139675a0cdd6841b4
676,906
def dict_from_json(dictionary): """Takes a dictionary and recursively int's every key where possible.""" new_dict = {} for key, value in dictionary.items(): try: new_key = int(key) except ValueError: new_key = key if isinstance(value, dict): value ...
a2dddb18d1603e75756f44708eec2e3d2f38e39a
676,907
import json def decode_conversations_from_json(json_string): """Helper method to decode a conversations dict (that uses tuples as keys) from a JSON-string created with :attr:`_encode_conversations_to_json`. Args: json_string (:obj:`str`): The conversations dict as JSON string. Returns: ...
2251e90d3fd29d2562396712c36d61cf7069b076
676,908
def shimbel(w): """ Find the Shimbel matrix for first order contiguity matrix. Parameters ---------- w : W spatial weights object Returns ------- info : list list of lists; one list for each observation which stores the shortest order between i...
86da578da800bb719d709bf31d9ffcc27aa19074
676,909
def count_keys_less(equal, m): """ Supporting function for counting_sort. """ less = [0] * m for j in range(1, m): less[j] = less[j - 1] + equal[j - 1] return less
836905da2a61086a0e41cef4f7fd057d4bc05667
676,910
def filterWithSelections(self, name, selections): """ This function is intended to be used as an argument to the filter built-in. It filters out unwanted traces (only those variables specified in selections will be passed through). :param name: The symbol we want to potentially filter :param select...
de6469f1385100eab94c979489beac3c8e3f4b67
676,911
import functools import numpy def _fp16_mixed_precision_helper(fn): """Decorator to perform computation in FP32 for FP16 inputs/outputs Decorator to perform forward computation in FP32 for FP16 inputs, returning outputs casted back to FP16. Do nothing for FP32 and FP64 inputs. """ @functools....
d914dbe693a97f0dd4803979bd58411e609dfa73
676,912
def merge_dict(base, new): """Recursively merge new into base. :param base: Base dictionary to load items into :type base: Dictionary :param new: New dictionary to merge items from :type new: Dictionary :returns: Dictionary """ if isinstance(new, dict): for key, value in new.it...
30aa4925657e14818fe89738b6f660b2e69b20e8
676,913
def counts_to_probabilities(counts): """ Convert a dictionary of counts to probalities. Argument: counts - a dictionary mapping from items to integers Returns: A new dictionary where each count has been divided by the sum of all entries in counts. Example: >>> counts_to_prob...
92974f6dafa0222995a77c336ab884fc34586dd3
676,914
def array_set_diag(arr, val, row_labels, col_labels): """ Sets the diagonal of an 2D array to a value. Diagonal in this case is anything where row label == column label. :param arr: Array to modify in place :type arr: np.ndarray :param val: Value to insert into any cells where row label == column l...
f4248a46253080407f2f6b569f99faf9a896937b
676,915
import json def _format_modules(data): """Form module data for JSON.""" modules = [] # Format modules data for json usage for item in data: if item.startswith('module_'): val_json = json.loads(data[item]) modules.append(val_json) return modules
1bc2cb303b1a1c116d33ed862006e99e8a378535
676,916
import itertools def compute(): """ method 2 """ arr = list(range(10)) temp = itertools.islice(itertools.permutations(arr), 999999, None) return "".join(str(x) for x in next(temp))
a9483bbcb3dc3a129aa787ad1179bdf594d574ed
676,917
def find_bleeding_location_columns(columns): """This method find bleeding column sites. .. note: bleeding_severe is not a location and therefore should not be included. Also we should double check that they are all boolean variables. .. warning: Include other, severe...
281ba214671d18f42ea73059e34cac71091fc364
676,918
def get_sparkconfig(session): """ Returns config information used in the SparkSession Parameters ---------- session : SparkSession Returns ------- dict : Dictionary representing spark session configuration """ conf = session.sparkContext.getConf().getAll() return conf
147dec4dbe21781d0fff6e1484e3f3c8e35821eb
676,919
def stride_chainid_to_pdb_chainid(stride_chainid): """ Convert a STRIDE chainid to a PDB chainid. STRIDE uses '-' for a 'blank' chainid while PDB uses ' ' (space). So all this does is return the stride_chainid unless it is '-', then it returns ' '. Parameters: stride_chainid - the STRID...
137fdcc67557d9faa22c0b2496bc8f340a6f3206
676,920
def encode_units(x): """ Returns 1 if x is higher than 1, returns 0 if x is lower than 0 Args: x (int): integer to be examined Returns: integer 0 or 1 """ if x <= 0: return 0 if x >= 1: return 1
8c21183568be744c3033ec6b0443d9bcee955293
676,921
def doc_to_labels(document): """ Converts document to a label: list of cluster ids. :param document: Document object :return: list of cluster ids. """ labels = [] word_to_cluster = document.words_to_clusters() cluster_to_id = {cluster:cluster_id for cluster_id, cluster in enumerate(docum...
71d6d521dc26012ddb169185473010a7ee6571f5
676,922
def _GetChangePath(change): """Given a change id, return a path prefix for the change.""" return 'changes/%s' % str(change).replace('/', '%2F')
c468f31c38903da50f8f950cdba3764ca29b26f9
676,924
import hashlib def list_hash(str_list): """ Return a hash value for a given list of string. :param str_list: a list of strings (e.g. x_test) :type str_list: list (of str) :returns: an MD5 hash value :rtype: str """ m = hashlib.md5() for doc in str_list: try: m....
e9b3c7fbdd05f63cdd92a3d20fec0c1ef971b532
676,925
def get_rv_toolkits(): """Returns a list of reference viewer supported toolkits.""" return ['qt4', 'qt5', 'pyside', 'gtk2', 'gtk3', 'pg']
3176fd95122670d6da09b51be536753f7352640f
676,926
import numpy as np import torch def dtype_to_torch(dtype): """ Convert an np.dtype to torch.dtype Args: dtype: (np.dtype) a np datatype """ dict_dtype = { np.dtype('int64') : torch.int64, np.dtype('float32') : torch.float32 } return dict_dtype[dtype]
c18cd347b558dcd6bb5e8a56ae9d677ed8f4d2da
676,928
from pathlib import Path import os def _is_extra_newline_necessary(file): """ Returns True if in the specific file, at the specified path (parameter file is a path to the file) an extra newline shall be added when writing a line to it. Sometimes there is no newline at the end of the file so this f...
f4b0fd41988a54dce9e371abb29737c14da7c753
676,929
def computeDelayMatrix(lengthMat, signalV, segmentLength=1): """ Compute the delay matrix from the fiber length matrix and the signal velocity :param lengthMat: A matrix containing the connection length in segment :param signalV: Signal velocity in m/s :par...
71ceaf48520c21f96f2de2ed38161cbb27e56c35
676,930
def present(ds, t0): """ Return clouds that are present at time `t0` """ # time of appearance tmin = ds.tmin # time of disappearance tmax = ds.tmax m = (tmin <= t0) & (t0 <= tmax) return m
1a36b390d232601f1d9c4c32e4d6d789fabeb135
676,931
import argparse def Usage(): """Provide instructions and explanation of TAF decoder/encoder command line arguments""" d = argparse.ArgumentParser(description="Run the TAF decoder/encoder unit testing", epilog="""Decoder will wait for input on standard input. Pressing ...
742f3561c68e773dc4ab056ee6e791291ce38d26
676,932
def get_strings(src_file): """getting strings from file""" res = [] try: res = open(src_file,'r').readlines() res = [x.strip() for x in res] except: res = [] return res
3ef167b91e0465b3763598d818ec9d3452a4bd79
676,933
def WI_statewide_eqn(Qm, A, Qr, Q90): """Regression equation of Gebert and others (2007, 2011) for estimating average annual baseflow from a field measurement of streamflow during low-flow conditions. Parameters ---------- Qm : float or 1-D array of floats Measured streamflow. A : f...
e02dc3ef384435d93eab7fdc6f96d60e98fe4c6f
676,934
def rectangle_vol(length,width,height): """Usage: rectangle_vol(length rectangle, width of rectangle, height of rectangle)""" return length*width*height
12d016a664529ae0a9cdeba05fa46a943e0f4223
676,935
def instantaneous_temperature(snapshot): """ Returns ------- instantaneous_temperature : float instantaneous temperature from the kinetic energy of this snapshot """ masses = snapshot.masses velocities = snapshot.velocities double_ke = sum([masses[i] * velocities[i].dot(velocitie...
2ffda67e98f2a1f8693687c3f4464b0e7a3818bf
676,936
def text_cov_lb6(): """JEFF-3.2 covariance for 10-Ne-20g (changed MAT1 from 10020 to 0 and MT1 from 91 to 16)""" text = \ """ 1.002000+4 1.982070+1 0 0 0 1102533 16 1 0.000000+0 0.000000+0 0 16 0 1102533 16 23 0.000000+0 0.00...
1d2c2f1c623b402ee8fbdd8379fcd94a7b744df8
676,937
def minimumpath(paths, position): """minimumpath(paths, position) Takes an iterable of paths and returns the path with the lowest cost for the position. Prerequisite: All of the paths are actually valid for that position, otherwise the calculation is wrong. """ return min(paths,key=lambda path: pat...
d0b962e5e5bed626bd3eee40707b1f56fe157b94
676,938
def read_frames(filename): """ Opens a second text file to read in protein FASTAs for motif generation. This file should consist of JUST protein FASTAs. # may be used for comments. Example FASTA: >CRY1_Drosophila_pseudoobscura MVPRGANVLWFRHGLRLHDNPALLAALEEKDQGIPLIPVFIFDGESAGTKSVGYNRMRFL ...
db06791c13fe952c77c512e856798e6464fb90e4
676,940
def _get_error_message_from_exception(e): """ This method is used to get appropriate error message from the exception. :param e: Exception object :return: error message """ error_msg = "Unknown error occured. Please check asset configuration and/or action parameters" error_code = "Error code una...
3bce20115964ebbe8736f35ed29c69eb63d3b034
676,941
from datetime import datetime def time_elapsed_since(start): """Computes elapsed time since start.""" timedelta = datetime.now() - start string = str(timedelta)[:-7] ms = int(timedelta.total_seconds() * 1000) return string, ms
6fba7d4cb7a7f3ec2241914b6b53f269b5e26ee0
676,942
def saniscript(POST, FILES): """Sanitize text or file input """ sanitized = [] if POST['protein'] == '': attachment = FILES.get('protein_file', False) for line in attachment: try: sanitized.append(str(line)[2:-2][:30]) # sanitized.append(curate...
4474b1166dcdfee1f08bf88ffa58657eb6a83c35
676,943
def make_integer_value_getter(value_name): """ return a function that fetches the value from the registry key """ def _value_getter(key): try: return key[0].get_value_by_name(value_name).get_data_as_integer() except: return None return _value_getter
97d232c955e253e4aeedc739e3100308bf30dc8e
676,944
def update_search_param(request, parameter, new_value): """Update the request ``parameter`` with a ``new_value``, overwriting any existing value.""" params = [] found = False for key in request.params.keys(): if key == parameter: found = True params.append((key, new_value...
63050ebefcf8ba210610c55d3450d869722bb0b3
676,947
def triple(x): """ Triples an input number >>> triple(3) 9 """ return x * 3
ce70dd6615b9a72185ff093e08f49eec1c8a3c77
676,948
import argparse def getopts(): """Parse command line arguments""" parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", type=argparse.FileType('r'), required=True, help="input file (.csv)") return parser.parse_args()
7a0c9796be95531649d00fbcb68e80c53f248379
676,949
import ipaddress def is_valid_ip(ip: str): """Return True if IP address is valid.""" try: if ipaddress.ip_address(ip).version == (4 or 6): return True except ValueError: return False
ab81c50164977d54bf10426149e78340ce461785
676,950
def get_format(suffix): """Get the archive format. Get the archive format of the archive file with its suffix. Args: suffix: suffix of the archive file. Return: the archive format of the suffix. """ format_map = { "bz2": "bztar", "gz": "gztar", } if suff...
633681b7f143af18bff6207f1e4d3ba30a0bf706
676,951
def get_user_id(user): """Return id attribute of the object if it is relation, otherwise return given value.""" return user.id if type(user).__name__ == "User" else user
7c9ef7e2511e6f111546994d08f9c699bcb7cbf3
676,952
import json import pkg_resources def _get_package_version(): """ Version of wcwidth (produces module-level ``__version__`` val). :rtype: str :return: the version of the wcwidth library package. """ return json.loads( pkg_resources.resource_string( 'wcwidth', "version.json"...
9d560fd3c522177c375d48a1a7332338f04189c1
676,953
def question43(array, target): """ for a array and a positive integer, find the minimun length of a contigous subarray that sums up to the integer """ max_sum = float('-inf') length = 1 while max_sum < target: for i in range(len(array)-length+1): max_sum == sum(array[i:i+length+1]) length +=1 return ...
10dba9eeb9d6c251ff8db88b8c09e102ba52bda6
676,955
def append_a(string): """Append "_a" to string and return the modified string""" string = '{}{}'.format(string, '_a') return string
7249063bbb9331de5163ef343399d51884312cd0
676,956
import uuid def default_nonce_factory(): """Generate a random string for digest authentication challenges. The string should be cryptographicaly secure random pattern. :return: the string generated. :returntype: `bytes` """ return uuid.uuid4().hex.encode("us-ascii")
4720bd5dd29fba39f09eac5a37b18c57b67129b7
676,957
import pkg_resources import argparse def process_cmd_opts(): """ Parse, process, and return cmd options. """ def print_version(): pkg_name = 'ndn-python-repo' version = pkg_resources.require(pkg_name)[0].version print(pkg_name + ' ' + version) def parse_cmd_opts(): ...
6c5bbc9fc8699f3c10fedfb4b1a98d71c387265c
676,958
def disable_control_flow_v2(unused_msg): """Decorator for a function in a with_control_flow_v2 enabled test class. Blocks the function from being run with v2 control flow ops. Args: unused_msg: Reason for disabling. Returns: The wrapped function with _disable_control_flow_v2 attr set to True. """ ...
90998bc0400e1d8e0c267ca130f7e6a31f552470
676,960
def get_list_uniques(_list): """ This function returns the unique/s value/s of a given list. :param _list: List :return: List containing unique values. """ ret = [] for it in _list: if it not in ret: ret.append(it) return ret
126059fee80f2505ffdbf373228e476e6c6e3526
676,961
def Range(i): """ Dummy test function """ return range(i)
a7d53da8b3f562a40ce3d8193be127fc02d1e5e3
676,963
def hasDuplicateValue_On(list): """ 参数 list: 待检查重复的队列 返回值 True | False:有重复值就返回 True, 否则返回 False 效率: O(n) 用集合 set 会更快一点 """ tag = {} for i in list: if (i not in tag): # 判断元素是否已经被标记 tag[i] = 1 # 标记新元素 else: return True return Fa...
4230855c66f7202981fc15361f0d697d867e75ac
676,964
def walk(path, visit, arg): """Calls the function *visit* with arguments ``(arg, dirname, names)`` for each directory in the directory tree rooted at *path* (including *path* itself, if it is a directory). The argument *dirname* specifies the visited directory, the argument *names* lists the f...
dd95ba790dcc91d3b9e6222f24dedaea2e41a9f5
676,965
def vi700(b4, b5): """ Vegetation Index 700 (Gitelson et al., 2002). .. math:: VI700 = (b5 - b4)/(b5 + b4) :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-edge 1. :type b5: numpy.ndarray or float :returns VI700: Index value .. Tip:: Gitelson, A. A., Kaufm...
2e9bc9f8092e225711754b816e8b588dfbc462b4
676,967
import json def get_json(json_str, encoding='utf-8'): """ Return a list or dictionary converted from an encoded json_str. json_str (str): JSON string to be decoded and converted encoding (str): encoding used by json_str """ return json.loads(json_str.decode(encoding))
abedb4def38c8403872074f2de3cfaca31df5695
676,968
import copy def _remove_repeated_slices(tensor_layout): """generate unrepeated tensor layout""" new_tensor_layout = copy.deepcopy(tensor_layout) dev_mat = tensor_layout[0][:] tensor_map = tensor_layout[1] for dim in range(len(dev_mat)): if dim not in tensor_map: dev_mat[-1-dim]...
79606ddf814ef521ffe89073affa7843fa293537
676,971
def joueur_continuer() -> bool: """ Cette fonction est utilisée pour demander au joueur s'il veut continuer ou non de piocher. Returns: bool: Retourne True si le joueur veut piocher, False sinon. """ continuer_le_jeux = input("Voulez-vous piocher? y ou n ") if continuer_le_jeux == "y": ...
36b29d5c4115b3a84edd4eba79f86813762aa492
676,972
def batch_flatten(x): """Batch wise flattenting of an array.""" shape = x.shape return x.view(-1, shape[-1]), shape
33cabe65e59ad2881650c935ac6ad5578ac8eba8
676,973
def create_result_section(param, result): """Function creating appropriate section in result dictionary""" if param not in result: result[param] = {} if "HMI_API" not in result[param]: result[param]["HMI_API"] = {} if "Mobile_API" not in result[param]: result[param]["Mobile_API"]...
4803cb09b023b09d494c64ed113cc9766571d6ac
676,974
def resend_strawpoll(jenni, input): """.resendstrawpoll - Resends the last strawpoll link created""" if hasattr(jenni.config, "last_strawpoll"): channel = input.sender if channel in jenni.config.last_strawpoll: return jenni.say(jenni.config.last_strawpoll[channel]) jenni.say("No ...
59f4399536fc23ccf124ca026929fa0ec64f3f11
676,975
def f(): # 2 """Fn with return.""" # 3 x = 3 # 4 return x
7a7744b837519752cbf47aa08b855fc59e4579e0
676,976
import re def replaceTags(value, data_record): """ As efficiently as possible, replace tags in input string with corresponding values in data_record dictionary. The idea is to iterate through all of the elements of the data_record, and replace each instance of a bracketed key in the input string ...
88e1e2d6c279eb50a615e9a6648fa5d08f525f18
676,977
def LastLineLength(s): """Returns the length of the last line in s. Args: s: A multi-line string, including newlines. Returns: The length of the last line in s, in characters. """ if s.rfind('\n') == -1: return len(s) return len(s) - s.rfind('\n') - len('\n')
c2bd1a2973cc4c041cd56a75d1c0e44ce5b4eb88
676,978
import re def is_camel_case(id_name): """Check if id_name is written in camel case. >>> is_camel_case('') False >>> is_camel_case('_') False >>> is_camel_case('h') False >>> is_camel_case('H') True >>> is_camel_case('HW') False >>> is_camel_case('hW') False >>>...
33977d51397413bfdb009f7e74b7202e76a87beb
676,979
def input_int(prompt: str, min_val: int = 1, max_val: int = 5) -> int: """Get an integer from the user""" while True: try: user_input = int(input(prompt)) if min_val <= user_input <= max_val: return user_input print("Value not within range. Try again!"...
15040b8110c8b0fb6c53e620a24d9c539369a486
676,980
import pathlib def get_test_cases(which_subset): """Return a list of test case files.""" assert which_subset in ("valid", "invalid") cwd = pathlib.Path(__file__).parent.resolve() test_dir = cwd / ".." / "demes-spec" / "test-cases" / which_subset files = [str(file) for file in test_dir.glob("*.yaml...
a6f90df366f222b37a90d818660624ec5b189a09
676,981
def is_info_hash_valid(data: bytes, info_hash: bytes) -> bool: """ Checks if the info_hash sent by another peer matches ours. """ return data[28:48] == info_hash
05443f7ede4c6bb85eb7d86d68239a3ef778e629
676,982
def dict_diff(a, b): """Returns the difference between two dictionaries. Parameters ---------- a : dict The dictionary to prefer different results from. b : dict The dictionary to compare against. Returns ------- dict A dictionary with only the different keys: v...
cfd20ce51d8bd7cb4f245819ba43813f0bbfa8bf
676,985
import os def get_untracked_files(store, dataset): """Get file listing and size metadata for all files in the working tree.""" ds_path = store.get_dataset_path(dataset) fileMeta = [] for root, dirs, files in os.walk(ds_path): if '.git' in dirs: dirs.remove('.git') if '.data...
69901401ce2981342fbbf4e8a446de3b372e6342
676,986
def read_ccloud_config(config_file): """Read Confluent Cloud configuration for librdkafka clients""" conf = {} with open(config_file) as fh: for line in fh: line = line.strip() if line[0] != "#" and len(line) != 0: parameter, value = line.strip().split('=', 1...
86ec495ad4c1d2b552b79d001add8aebf3cfe8a5
676,987
def trim_block(multiline_str): """Remove empty lines and leading whitespace""" result = "" for line in multiline_str.split("\n"): line = line.lstrip() if line != '': result += "%s\n" % line return result.rstrip()
9f38770d2c8c6728f035f14dd55a5bbd610c2117
676,988
def intersect_trees(tree1, tree2): """Shrink two trees to contain only overlapping taxa. Parameters ---------- tree1 : skbio.TreeNode first tree to intersect tree2 : skbio.TreeNode second tree to intersect Returns ------- tuple of two TreeNodes resulting trees c...
344ace1e867748f1db0b514b7b1339775cadbe4a
676,989
def filter_none(kwargs): """ Remove all `None` values froma given dict. SQLAlchemy does not like to have values that are None passed to it. :param kwargs: Dict to filter :return: Dict without any 'None' values """ n_kwargs = {} for k, v in kwargs.items(): if v: n_kwa...
0a753232fe09ebbe91a0ceadeba70eb2a6c7f7bb
676,990
def _quote(text): """Enclose the string with quotation characters""" return '\'{0}\''.format(text)
c7e0cc88bf4777026afe2d909cd4ceec9c78596a
676,991
def filter_by_year(df, filter_cat="conc_yy", year=1990): """Filter df by year, either with conception year ('conc_yy') or birth year ('dob_yy') """ df = ( df[df[filter_cat] == year] .groupby( [ "conc_yy", "conc_month", "dob_yy",...
2b3a06d2b7a572e983a3253a7db6c1c688c57b68
676,992
from pathlib import Path import shutil def get_config(repo_path: Path, filename: str) -> Path: """Get a config file, copied from the test directory into repo_path. :param repo_path: path to the repo into which to copy the config file. :param filename: name of the file from the test directory. :return...
4ac87766cd61e4202a3b73bd373009f8b6f52d34
676,993
def create_tag_cloud_html(tag_cloud_name, tags, level_weights): """Create HTML code for the tag cloud. ``tag_cloud_name`` is the CSS style name used for the generated tag cloud. It should be the same value as passed to ``create_tag_cloud_css``. ``tags`` and ``level_weights`` are the return values ...
7aa41dc9e92c6041a884e12957f3f29f7ff1bd06
676,995
def get_tables_from_mapping(source_table, dest_fields, source_dest_map): """ Obtain a petl tables from a source petl table and some mappings source_table: petl table dest_fields: list source_dest_map: dict Returns dest_table: petl table """ source_fields = list(source_table...
26eab2187e6a3c0729331750d5adb50c760155a8
676,996
def align_text(text, symbol, position, heading): """Align text properly in the center.""" maxsize = 100 if(maxsize % 2 == 1): maxsize += 1 if len(text) >= (maxsize-4): return False headingCorner = "+" if not heading: headingCorner = "|" if position == "center": ...
ee76c79736608b2a12338e197f890a1ffeb4a267
676,997
def second(xs): """Grab the second item from a list-like thing.""" return xs[1]
3ec189fb8a7e17517bc04ea5ee52a84fc0c836b8
676,998
from threading import Thread import asyncio def start_loop_in_thread(): """Launches a asyncio loop in a different thread and start it""" def start_loop(loop): asyncio.set_event_loop(loop) loop.run_forever() new_loop = asyncio.new_event_loop() t = Thread(target=start_loop, args=(new_l...
ed4d7fadc1657755256a81ecafc708fa6ce33a79
676,999
from typing import Callable import re def remove_link_ids() -> Callable[[str], str]: """Create function to remove link ids from rendered hyperlinks.""" def _remove_link_ids(render: str) -> str: """Remove link ids from rendered hyperlinks.""" re_link_ids = re.compile(r"id=[\d\.\-]*?;") ...
cbddaca54c205d54f8c2e1baba504c14d31e7676
677,000
def cut(image, matrix): """ Cut resized image into small pieces. :param image: :param matrix: :return a list of lists of tuples of RGB: """ bricks_list = [] for i in matrix: temp_brick = image.crop(i) temp = temp_brick.getdata() bricks_list.append(list(temp)) ...
2ccf19b8f82eda93fa4c8a4702b1f77c14c7f364
677,001