content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def split_by_comma(line): """ Converts the given line of text into comma-delimited tokens :param line: the line of text to process :return: an array of tokens contained in the line of text """ return line.split(",")
2d65538fa5a5cbcd14fefc269318baf9dcff926b
670,830
import ast def parse_migration(f): """ Parse migration file and return (frozen_models, complete_apps). The returned objects are full-fledged Python data structures, as if we actually imported the migration file. But because we use ast.literal_eval(), this is safe to run on untrusted code. """...
c216c9cc5d11fdf9e62274b53678909032abcb0c
670,832
def set_conn_string(server, db_name, username, password): """ Sets connection string to SSAS database, in this case designed for Azure Analysis Services """ conn_string = ( "Provider=MSOLAP;Data Source={};Initial Catalog={};User ID={};" "Password={};Persist Security Info=True;Impers...
9b7d63a0ef97eb4012163550ed0548c5e531fe39
670,833
def _is_number(s: str) -> bool: # pylint: disable=invalid-name """Return True if string is a number.""" return s.replace(".", "", 1).isdigit()
ec741bf8a140b2cb95f7389b77aba4ec98aad3b8
670,838
def safe_int(string_, default=1): """Convert a string into a integer. If the conversion fails, return the default value. """ try: ret = int(float(string_)) except ValueError: return default else: return ret
838f3a479a0181a5bcba00c9a058ac5d342d8e22
670,846
def reverse_bits(x, n): """reverse n bits of x""" rev = 0 for i in range(n): rev = (rev << 1) + (x & 1) x >>= 1 return rev
6a5daff588df545883b3dff6cd4f69d1f8988db5
670,848
def noop(sample, feat_idxs): """Don't expand.""" return []
d4844a6efea8e514be327390f2b320d8acb7a6a7
670,849
def get_approvals_from_scrape(soup): """Take a BeautifulSouped page and return a clean list of all approval dates.""" table = soup.find('table', attrs={'class':'approvals'}) approvals = [] if table: for tr in table.find_all('tr'): country = tr.find('th') date = tr.find('t...
91f57f1560f6d00811538fd523107b922b8e84be
670,850
import csv def write_colocated_gates(coloc_gates, fname): """ Writes the position of gates colocated with two radars Parameters ---------- coloc_gates : dict dictionary containing the colocated gates parameters fname : str file name where to store the data Returns ---...
aaf7421036f39c898a3ee9e7c166ce24cdda6b4e
670,851
def winners(metrics, metric_name, point_values): """Awards points to the top scoring users in a particular metric point_values should be a list of point values like [1000, 500, 200]. In this example, 1000 points are awarded to the top scoring member, 500 to the second place, and 200 to the third. Any n...
3361db63f498ad948d5d7c7882c5af73905fc762
670,852
def rgb2hex(colorin): """ Convert (r,g,b) to hex """ r = int(colorin.split('(')[1].split(')')[0].split(',')[0]) g = int(colorin.split('(')[1].split(')')[0].split(',')[1]) b = int(colorin.split('(')[1].split(')')[0].split(',')[2]) return "#{:02x}{:02x}{:02x}".format(r,g,b)
1210f8e0c9188d92384fe50b8844be5de1a3689c
670,857
def count_groups(generator): """ Count the number of distinct elements in the stream, assuming that the elements come in groups. For example: >>> each(1, 2, 1, 10, 10, 5, 5) >> count_groups() 5 """ # Instead of using a sentinel value, just look at the first value output by # the...
edbdea6af044025ea7c82f62efce6dc21f01045e
670,858
def GetDetailedHelpForRemoveIamPolicyBinding(collection, example_id, role='roles/editor'): """Returns a detailed_help for a remove-iam-policy-binding command. Args: collection: Name of the command collection (ex: "project", "dataset") example_id: Collection iden...
f6d54cd3e3882155444fd720b0514ceda274fbb7
670,859
def simple_function(x): """Docstring.""" return x # comment
b949354a00f068f74459050baa85a85222dadd7a
670,861
import json def load_coupling(name): """ Loads the coupling map that is given as a json file from a subfolder named layouts Args: name (string): name of the coupling map that was used when saving (corresponds to the filename without the extension .json) Returns: ...
067f9016dd1352c0f55f2e44edc947fd5674086d
670,863
import functools def deep_merge(*args): """Deep merge multiple dictionaries. >>> value_1 = { 'a': [1, 2], 'b': {'c': 1, 'z': [5, 6]}, 'e': {'f': {'g': {}}}, 'm': 1, } >>> value_2 = { 'a': [3, 4], 'b': {'d': 2, 'z': [7]}, 'e': {'f': {'h': 1}}, 'm': [1],...
9714b6c9173956e83b674ce4291bc9c47f736c64
670,864
def str_to_bool(string): """Convert a string to a boolean value.""" if string.upper() in ["1", "ON", "TRUE", "YES"]: return True return False
bfd0858b1cd1bb6349abbec2dbf2c0b15b1f19d6
670,868
def _get_QCheckTreeWidget(self): """ Get currently checked values in QCheckTreeWidget via re-mapping filter. Selected values are returned as a list. """ return [self._get_map(s) for s in self._checked_item_cache]
389c35fcfb651607d85bd28a6c0c5a46b63c46d4
670,873
def transpose(xs): """ Transpose a matrix """ return map(list, zip(*xs))
09979f5b3995b1f3b893b0a754317f70f66a975d
670,877
def remove_prefix(text: str, prefix: str) -> str: """ Removes the prefix from the beginning of the text if the text starts with the prefix :param str text: text that potentially starts with a prefix :param str prefix: prefix that the text potentially starts with :return: the text with stripped pref...
c2a835695b6e505ecdd8ac66a00feda769dea143
670,878
def recognize_destination(line: str) -> bool: """ Recognizes .po file target string. """ if line.startswith("msgstr"): return True return False
da6c3f9344318fbd6cf5f1c636edf1586a0f1682
670,879
def flatten_list_prime(l): """ Flattens a list so that all prime numbers in embedded lists are returned in a flat list Parameters: - l: a list of numbers; largest prime cannot be greater than 1000 Returns: - flat_l: a flat list that has all the prime numbers in l ...
04b54f8927fd330e5cc33d8dbf2715799df951b0
670,880
def ignore_background(array, num_classes, ignore=0): """ :param array: [*],values in [0,num_classes) :param num_classes: C :param ignore: ignore value of background, here is 0 :return: [*] which ignore_index=num_classes """ array[array == ignore] = -1 array[array > ignore] -= 1 retur...
0d486b283eb096fd7a41900b2037c9c956934204
670,881
def apply_iam_bindings_patch(current_policy, bindings_patch, action): """ Patches the current policy with the supplied patch. action can be add or remove. """ for item in bindings_patch['bindings']: members = item['members'] roles = item['roles'] for role in roles: if role not in current_pol...
2bc2a9204aaeb0680933fddef43ee62f103f1f39
670,885
import inspect from typing import Callable import gc def func_in_frame_info(frame_info: inspect.FrameInfo) -> Callable: """Find callable corresponding to given frame_info.""" f_code = frame_info.frame.f_code for obj in gc.get_referrers(f_code): if hasattr(obj, '__code__') and obj.__code__ is f_cod...
dab29216e7e8d0561e0c5b150b42e4b8a1890ec7
670,886
def convertType(pair: tuple): """Convert items to the appropriate types Arguments: pair: A tuple containing 2 items Returns: pair: A tuple containing 2 items where the second item is converted to the appropriate types """ # If it is not a pair if len(pair) != 2: ...
97a9012ea78de834f19ffdd28d144c374c2379e9
670,887
def header(text, color='black'): """Create an HTML header""" raw_html = f'<h1 style="margin-top:12px;color: {color};font-size:54px"><center>' + str( text) + '</center></h1>' return raw_html
666ce695b5814f657a283d2ef09d947158a37444
670,888
import json def load_json(location): """ Read JSON file at `location` and return a list of ordered dicts, one for each entry. """ with open(location) as json_file: results = json.load(json_file) if isinstance(results, list): results = sorted(results) else: results =...
08549abd9c822dac6628c77871a4c03d018524d5
670,890
def gateway_environment(gateway_environment): """Enables path routing on gateway""" gateway_environment.update({"APICAST_PATH_ROUTING": True}) return gateway_environment
1c89bc7891696a3fab21b0caa968660ab8ff586b
670,896
def merge_words(current_words, new_words): """ Determine words to add and delete for words update. Parameters: list(dict). Currently existing words list(dict). Words after update Return: list(dict). Words to keep list(dict). Words to remove ...
0abe26bcbd5deb2c5bae5a6d7c8c3fb4c9427bd7
670,903
def for_each_in(cls, f, struct): """ Recursively traversing all lists and tuples in struct, apply f to each element that is an instance of cls. Returns structure with f applied. """ if isinstance(struct, list): return map(lambda x: for_each_in(cls, f, x), struct) elif isinstance(struct, tupl...
b81dd5bfeb7f140ef49a48bfd590e407568f913b
670,904
import collections def get_sectors(n_con): """ INPUTS: n_con (mysql) - A "normal" pymysql database connection OUTPUT: Dictionary with sectors as keys, and lists of ticker_id's as values """ sectors = collections.defaultdict(list) with n_con.cursor() as n_cur: n_cur.exec...
298741eedd8cffc96453882d449d479cd29e2f3c
670,908
import unicodedata def unaccent(string): """ Receives a string and return it without accents :param string: accented string :return: unaccented string """ text = unicodedata.normalize('NFD', string) text = text.encode('ascii', 'ignore') text = text.decode("utf-8") return str(text...
4f49c9959ff9ae6bcf45fa5268a84e148dc9de68
670,910
def _recover_uid(good_id) -> int: """ Get the uid part of the good id. :param str good_id: the good id :return: the uid """ uid = int(good_id.split("_")[-2]) return uid
698fe08bb50011e989809d78002ab671af40f355
670,911
def rgba2int(r, g, b, a): """ rgba2int: Converts an RGBA value into an integer :param r The red value (0-255) :param g The green value (0-255) :param b The blue value (0-255) :param a The alpha value (0-255) :returns: The RGBA value compact into a 4 byte integer. """ return (r << 24) ...
4aeb6612798de342556dbcd46e0f552e3c842be2
670,917
import re def findurls(text): """ Finds all urls in a string """ urls = re.findall('href="(.*?)"', text) return urls
e5d435dd073c7e781b14fd44c22a81c9c2019930
670,918
def table( caption="", thead="", tbody="", striped=True, bordered=False, hover=True, condensed=False, span=False): """ *Generate a table - TBS style* **Key Arguments:** - ``caption`` -- the table caption - ``thead`` -- the tabl...
b381a61757addf8457e9381708e60b21ecd01dba
670,919
def get_order(order): """ All the orders they create look something like this: "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza" Their preference is to get the orders as a nice clean string with spaces and capitals like so: "Burger Fries Chicken Pizza Pizza Pizza Sandwich Milksha...
b58620758a05a53dadd4e6b1d99491430a932bb1
670,920
import logging def get_logger(name=__name__, level=logging.INFO): """ This pattern prevents creates implicitly creating a root logger by creating the sub-logger named __name__ Also by default sets level to INFO """ logger = logging.getLogger(name) logger.setLevel(level) return logger
8849d4964045fe05dca7d107c792062bc3163f71
670,923
def bit_invert(value, width=32): """! @brief Return the bitwise inverted value of the argument given a specified width. @param value Integer value to be inverted. @param width Bit width of both the input and output. If not supplied, this defaults to 32. @return Integer of the bitwise inversion of @...
bef9becb3e4fd3f291ac1ad1352630e6437f7fc3
670,926
import copy def get_fillin_graph2(old_graph, peo): """ Provided a graph and an order of its indices, returns a triangulation of that graph corresponding to the order. The algorithm is copied from "Simple Linear Time Algorithm To Test Chordality of Graph" by R. E. Tarjan and M. Yannakakis ...
737b86b9fe1aa5eb02f2e4a527c49abae383c040
670,932
def isint(val): """ check if the entry can become an integer (integer or string of integer) Parameters ---------- val an entry of any type Returns ------- bool True if the input can become an integer, False otherwise """ try: int(val) return Tru...
5ca720162b31fdaae5c536d3e89c01ff12dad059
670,933
def update_vocab(vocab): """Add relevant special tokens to vocab.""" vocab_size = len(vocab) vocab["<unk>"] = vocab_size vocab["<s>"] = vocab_size + 1 vocab["</s>"] = vocab_size + 2 return vocab
c8ce10a70e522301e7fb78b66bd35c11aa5c12f6
670,936
def json_for_user(user, session_id): """ Convert the provided user to a dictionary (for JSON) Args: user: the User object Returns: An object containing user details """ return { "user_id": user.user_id, "name": user.name, "title": user.title,...
7d18539352b17d5d84c2041256645ae56300ea37
670,937
def parse_vec(s, size = 3): """Parse a vector and return it as a list of values. Upon failure, return a vector containing all 0s. """ if s.count(" ") < size - 1: return [0] * size try: return [float(value) for value in s.split(" ")] except ValueError: return [0] * size
5aec04e1c43067fb58a671393b266354f96c94f2
670,938
from typing import Callable def _integrate(function: Callable[[float, ], float], start: float, end: float, n: int) -> float: """ Calculate defined integral of given `function` in range of [start, end] :param function: Function to integrate :param start: Left bound :param end: R...
34dd7c962dd329cff73c4f9c4a4878d6aefd7143
670,940
def reject(position_store, particles, random_particle): """Reject the move and return the particle to the original place. Parameters ---------- position_store: float, array_like The x and y positions previously held by the particle that has moved. particles: util.particle.dt, array_like ...
b268d9125d70b872efa8737aa622e946abbd9b63
670,944
from functools import reduce def factors(n): """ Decomposes a number into its factors. :param n: Number to decompose. :type n: int :return: List of values into which n can be decomposed. :rtype: list """ return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(...
7526528966fefb32d430f3a58735ae312ed02280
670,947
import traceback def atomic_method(method): """ Decorator to catch the exceptions that happen in detached thread atomic tasks and display them in the logs. """ def wrapper(*args, **kwargs): try: method(*args, **kwargs) except Exception: args[0].exceptionq.put("A...
b85f429886bdd0da137e02e073c0f1cf2af6c3cb
670,956
def _font_pt_to_inches(x): """Convert points to inches (1 inch = 72 points).""" return x / 72.
6edcd171a1d943be2b51178da19b4ee6df5fa0eb
670,957
def dimcolor(rgb, prop): """ Dims a given rgb color to prop, which should be in the interval 0.0 - 1.0. """ return tuple(map(lambda x: int(round(x * prop)), rgb))
dfe049720f2b95a81ba384b640dce8428bb9438d
670,959
import struct import binascii def hex2double(s): """Convert Ephemeris Time hex string into double.""" return struct.unpack('d', binascii.unhexlify(s))[0]
2320ba8352cf880ec61e8d867ac7d648f818ae45
670,963
def decode_edges(edges): """ Decodes the specified integer representing edges in Cortex graph. Returns a tuple (forward, reverse) which contain the list of nucleotides that we append to a kmer and its reverse complement to obtain other kmers in the Cortex graph. """ bases = ["A", "C", "G", "...
3ac84f466a059302d58e0e6204587c715c381016
670,964
def query_default(param, args): """ Allow for a parameter to be queried, and return defaults for those not provided. Parameters ---------- param : str The parameter being queried args : object Namespace object Returns ------- Queried value or default """ va...
a4bc265f0f0ebe6dd2e3d9bd511243718bc122a8
670,965
def lookup(name, namespaces=None, modules=None): """ Look up the given name and return its binding. Return `None` if not found. namespaces: Iterable of namespaces / dictionaries to search. modules: Iterable of modules / objects to search. """ if namespaces is not None: ...
0f2342d31ec1500599b666afccdcf4f8a228d4ee
670,968
def metadata_to_dict(metadata): """ Takes metadata as specified in seperate_metadata_and_content() documentation and\ converts it to a dictionary. Note that white space on either side of the metadata tags and values will be stripped; \ also, if there are any duplicate metadata key names, the value o...
9fe4eb2fc1a99fcb206af84fb64cd729c9f64ae9
670,974
def max_sequence_length_from_log(log): """ Returns length of the longest sequence in the event log. :param log: event log. :return: max_seq_length. """ max_seq_length = 0 for sequence in log: max_seq_length_temp = 0 for activity_ in sequence: max_seq_length_temp...
626a045a344e37e3e99f864665e9990fb12d87a2
670,975
import re def remove_duplicate_spacing(text): """Replace multiple spaces by one space""" pattern = r'[\s]+' return re.sub(pattern, " ", text) pass
bd3960825bddcc784808ed52fbf85d7882973608
670,976
def point_in_box(bbox, point): """check if a point falls with in a bounding box, bbox""" LB = bbox[0] RU = bbox[1] x = point[0] y = point[1] if x < LB[0] or x > RU[0]: return False elif y < LB[1] or y > RU[1]: return False else: return True
c6b44b55609136aa728d35c0cc2966f94d415bd9
670,977
from typing import Tuple def manhattan(coord_1: Tuple[int, int], coord_2: Tuple[int, int]) -> int: """ Returns the manhattan distance between 2 coordinates. """ return abs(coord_1[0] - coord_2[0]) + abs(coord_1[1] - coord_2[1])
cfee64a68b1f2aaace9b27c73899d42a0ab3f5c4
670,981
def parse_lines(s): """ parser for line-separated string fields :s: the input string to parse, which should be of the format string 1 string 2 string 3 :returns: tuple('string 1', ...) """ return tuple(map(lambda ss: ss.strip...
1b406d4efd0afa92188efb221299b1ac64d95e2e
670,985
def gen_namespace(dbname, collname): """ Generate namespace. """ return '%s.%s' % (dbname, collname)
96cbd4f7874eb87584fdb00d87ee5f062805f173
670,990
def calculate_score(given_answers: dict, correct_answers: dict) -> int: """Returns the number of correct answers. given_answers: {"question1": "X", "question2": "Y", ... "questionN": "Z"} correct_answers: {"question1": "A", "...
adcd2df940af9d3937c097d1d4e2144657b3e5de
670,991
def multiply(a, b): """Function to multiply two numbers. Parameters ---------- a: float First number of the multiplication. b: float Second number of the multiplication. Returns ------- float The product of a and b, a*b. """ return a * b
7f74478bfae2a5512cb15c8b1b3a6f1a7e6aedcf
670,993
def get_mnsp_period_collection_attribute(data, attribute, func) -> dict: """ Get MNSP period collection attribute Parameters ---------- data : dict NEMDE case file dictionary attribute : str Name of attribute to extract func : function Function used to parse extrac...
5670969badd5d881257692e4e63ea706ad64ddbc
670,996
def box(keyword): """Validation for the ``<box>`` type used in ``background-clip`` and ``background-origin``.""" return keyword in ('border-box', 'padding-box', 'content-box')
31af2163ee6592f96fd32277ce3ff7697171eba0
670,998
def sort_keypoints_by_response_and_get_n_best(keypoint_list, n=500): """ Sorts keypoint list by "response" field and returns the first n best keypoints. If the length of the list is smaller than n, than return the whole list. input: keypoint_list - list of keypoints n - no of keypoints to be...
34bc3116ed6acecd652bfdd7176624bd02948ff0
671,003
def dirac_measure(a,b): """ Returns 1 iff a=b and 0 otherwise. """ if a==[] or b==[]: return 0.0 return float(a==b)
37d8215d30c962441ef3b09d7e077de62da89f7e
671,005
def anchor(post): """Return anchor string for posts that arepage sections.""" if post.section: return '#' + post.section else: return ''
a48dba92060aaac6f7322469669a9becc83bd847
671,007
import re def _ParseFixed(fixed_or_percent_str): """Retrieves int value from string.""" if re.match(r'^\d+$', fixed_or_percent_str): return int(fixed_or_percent_str) return None
7d0cc19f22f7d6c174d41f3d76916972ccb49a17
671,008
import math def __calculateGridAxis(length, local): """ Calculates the grid axis. Parameters ---------- length : int. Global length. local : int. Local size. Returns ------- grid : int Calculated grid size. """ return int(math.ceil(float(length) ...
35ccbec9395f82e2152c9142b5607705c7de2a39
671,009
import copy import logging def MergeConfigs(default_config, override_config, warn_new_key=False): """Merges the override config into the default config. This function will recursively merge two nested dicts. The override_config represents overrides to the default_config dict, so any leaf key/value pairs whic...
dcd6a758cbbd1f8bc3d0a1d59a080731608521d7
671,016
def SampleZipped(sample_file, input_api): """Return True if the zipfile that should contain |sample_file| is in this change. """ sample_path = sample_file.LocalPath() for af in input_api.AffectedFiles(): root, ext = input_api.os_path.splitext(af.LocalPath()) if ext == '.zip' and sample_path.startswith...
27ceca5086843920dd2e8594728b722f450e9de9
671,020
def _find_traces(traces, trace_type, item_id): """Find traces for a script or automation.""" return [ trace for trace in traces if trace["domain"] == trace_type and trace["item_id"] == item_id ]
973b6460a86e793e54a914d799c4c0d2ee1c8fcd
671,022
def GenerateTableHtml(items, keys_to_print, display_index=True): """Given a list of object values and keys to print, make an HTML table. Args: items: Items to print an array of dicts. keys_to_print: (key, display_fn). `key` is a key in the object. i.e. items[0][key] should exist. display_fn is the ma...
351959b5d5e2ecfdc00070cf6b6c0e6ca8f42edf
671,024
def polyToBox(poly:list): """ Converts a polygon in COCO lists of lists format to a bounding box in [x, y, w, h]. """ xmin = 1e10 xmax = -1e10 ymin = 1e10 ymax = -1e10 for poly_comp in poly: for i in range(len(poly_comp) // 2): x = poly_comp[2*i + 0] y = poly_comp[2*i + 1] xmin = min(x, xmin) xma...
95858b53790f5de922d3fe4e4d4d8587fa190c34
671,032
import re def char_tokenizer(sentence): """Cut the sentence into the format we want: - continuous letters and symbols like back-slash and parenthese - single Chinese character - other symbols """ regex = [] # English and number part for type name. regex += [r'[0-9a-zA-Z\\+()\-<>]+'] ...
8845cf677671af3a270a9e6bc0f2860df5c763b1
671,034
import re def match_pattern(file, pattern): """ Continue reading file line by line and look for regular expression pattern. Returns True if the pattern was found, False if not. """ for line in file: if re.search(pattern, line): return True return False
4fb3fb2dbb242e03577af0eff5532561f9ef8e0a
671,035
def GetTimestampEventName(process): """ Returns the name of the events used to count frame timestamps. """ event_name = 'BenchmarkInstrumentation::DisplayRenderingStats' for event in process.IterAllSlicesOfName(event_name): if 'data' in event.args and event.args['data']['frame_count'] == 1: return event...
7cda78cd87f4f75ab84e3b412a229fb248b9f48b
671,038
import math def radial_decay(r_nmi, rmax_nmi): """ Calculates the radial decay factor for a given radius. Rmax_nmi < r_nmi: NWS 23 pdf page 53, page 27, Figure 2.12, empirical fit Rmax_nmi > r_nmi: NWS 23 pdf page 54, page 28, Figure 2.13, empirical fit (logistic regression) :param r_nmi: int Poin...
2cc26601fb3cc4c4d45788fb049e60ceaeb18438
671,042
import time def get_date(basename): """Return date object representing date of M3 observation""" return time.strptime(basename[3:11], "%Y%m%d")
09b58050380d703eb85ad22e91e81581c39c9e59
671,045
def subset(data: list, default_length: int): """ Get a subset of a list :param data: list :param default_length: default length of list :return: list """ # Stop if nothing was found: if len(data) == 0: return [] # Select some IDs length = default_length if len(data) > d...
90350f53451b4ef287e47f167b23283340f059ea
671,049
def _MakeOptional(property_dict, test_key): """Iterates through all key/value pairs in the property dictionary. If the "test_key" function returns True for a particular property key, then makes that property optional. Returns the updated property dict. """ for key, value in property_dict.items(): if test_...
eb358f149b41a165efe6bff7c51b2978e176c017
671,050
def find_index_of_minimum(arr): """Returns the index of the minimum number Arguments: arr {list} -- the input list Returns: int -- the index of the minimum number """ minimum = arr[0] index_of_minimum = 0 for index, item in enumerate(arr): if item < minimum: ...
097ae01d7f69a7cad38cb0fded141240fc42ebd7
671,052
def stars(number_of_stars, max_stars): """ For a given number of stars, will return number of stars. :param int number_of_stars: number of stars :param int max_stars: max number of stars :return: a string """ star_true = "★" star_false = "☆" return star_true * number_of_stars + star...
6e72e2d1839641152fa272505108c93cf1d259b6
671,054
def _get_match_groups(ping_output, regex): """ Get groups by matching regex in output from ping command. """ match = regex.search(ping_output) if not match: raise Exception('Invalid PING output:\n' + ping_output) return match.groups()
7780b40cef696167907ce4dd145aa4b178ec81d4
671,055
from typing import Union from pathlib import Path import sqlite3 def is_database_locked(db: Union[str, Path]) -> bool: """Checks is database locked Notice: This function will block the thread for a while (the timeout is set to 0) """ conn = sqlite3.connect(str(db), timeout=0) try: conn.e...
33f0f95e3d0bedf48dce1620ebcc2852da5c5c4a
671,057
def _need_loop(v): """ if a variable should loop to concat string :param v: any variable :return: Boolean """ return isinstance(v, list) or isinstance(v, dict) or isinstance(v, tuple)
b6f2a98e49f2233b2a368a1716f904a7845c3ca8
671,059
def struct2spglib(st): """Transform :class:`~pwtools.crys.Structure` to spglib input tuple (cell, coords_frac, znucl). """ return st.get_spglib()
a8d2e08c7e17e507eb9b2992ae834009403bd4e9
671,060
def get_partners(bam, bams): """ Returns the partner bam files having the same ID """ partners = [] for bam_iter in bams: if bam in bam_iter: partners.append(bam_iter) return partners
d691918b5f7ac8149c5afd0002b8ef245aed4f15
671,065
import random import string def _generate_random_string(N: int = 6) -> str: """ Generate some random characers to use in the captcha. Parameters ---------- N : int Number of characters to generate. Returns ------- str A pseudo-random sequence of lowercase letters and ...
7a6baf14665efa99ad75d431b0d809d28ff1a9c8
671,066
def decrease(raw_table, base_index): """ Convert decrease flag to english """ if raw_table[base_index] == 0: return "stop" else: return "lowering"
4c4d728eec90fb20386a2dc5d7edacfb6a6e69ad
671,068
from passlib.context import CryptContext def make_passwordmanager(schemes=None): """ schemes contains a list of replace this list with the hash(es) you wish to support. this example sets pbkdf2_sha256 as the default, with support for legacy bcrypt hashes. :param schemes: :return: CryptCon...
fe278c057e735aca56716ecf397f7664ff010a37
671,069
import torch def predict_fn(input_data, model): """ Predict stock prices Parameters: ---------- input_data(num of samples, lookback): input data model: trained model Returns: -------- output (num of samples, output_size): predictions """ ...
5a2848a9fbcaa82d04ec97747d821346fbda8d2f
671,072
def missing_metadata_field() -> str: """Return a schema with missing metadata key.""" return """{ "type": "struct", "fields": [ { "type": "string", "nullable": true, "name": "name", "metadata": {} }, { "type": "integer", "nullable": true, "...
16d199d5b0f6ba3fc869c0395d60278baaf0bb37
671,074
def after_space(s): """ Returns a copy of s after the first space Parameter s: the string to slice Precondition: s is a string with at least one space """ return s[s.find(' ') + 1:]
d16fe547b562a7089a0babf9578e7a06f7a1f69e
671,077
def binom(n, k): """ *DESCRIPTION OF FUNCTION* Parameters ---------- n : int First number in the binomial coefficient. Can be thought of as the set being drawn from k : int Second number in the binomial coefficient. Can be thought of as being the nuber of items drawn from the se...
af29dd2f5e9848391898b9fd010cb66a1eec3faf
671,081
def no_duplicates(route): """ This function removes duplicate nodes that may be present in a route, ensuring it can be plotted. Parameters ---------- route : list list of nodes traversed by route, in order Returns ------- route : list list of nodes traversed by route, i...
aeb97e7370c0bf1d4a25c40264d5673fcea7f162
671,082
def single_function_to_run(batch, function_to_run): """ apply a list of functions on a batch of data """ for fn in function_to_run: batch = fn(batch) return batch
6bf769541346177b45156c8d1c9c93318f3fddf1
671,083
import re def de_camel(s: str, separator: str = "_", _lowercase: bool = True) -> str: """ Returns the string with CamelCase converted to underscores, e.g., de_camel("TomDeSmedt", "-") => "tom-de-smedt" de_camel("getHTTPResponse2) => "get_http_response2" """ s = re.sub(r"([a-z0-9])([A-Z])",...
604d149f809720d1912421e5a634429ceb2990d3
671,085