content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re import binascii def b16decode(s, casefold=False): """Decode a Base16 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. The decoded string is returned. A ...
12753cf4bf55f8a792ee01eb186f76abe81f4de4
576,995
import torch def tagging_criterion(pred_labeled, y_labeled): """The loss function for tagging task (with float tensor input) Args: pred_labeled (Tensor): the predicted float tensor y_labeled (Tensor): the groundtruth float tensor Returns: Tensor: the cross entropy loss with the 0...
bd3f3201c1856a8dc1d55cad2475ea34d0d2e375
576,997
import yaml def read_yaml(filename): """ Reads the given config file and returns the contents of file in dict format """ try: with open(filename, 'r') as fh: return yaml.safe_load(fh) except OSError as error: return None
65dd09172f2bec8bb9db2a3b9caf02a15d2396f6
576,998
def get_original_order_from_reordered_list(L, ordering): """ Returns the original order from a reordered list. """ ret = [None] * len(ordering) for orig_idx, ordered_idx in enumerate(ordering): ret[ordered_idx] = L[orig_idx] return ret
390219d804668a2085ca07b6863b45eb7d5cbc69
577,001
def get_dimensions(table): """ Returns columns, rows for a table. >>> get_dimensions([['row1', 'apple', 'llama'], ['row2', 'plum', 'goat']]) (3, 2) >>> get_dimensions([['row1', 'apple', 'llama'], ['row2', 'banana']]) (3, 2) """ rows = len(table) try: cols = max(len(row) for r...
daab1ec476448c2df9765c8d406468bab74a9afe
577,004
def _parse_qstat_state(qstat_out, job_id): """Parse "state" column from `qstat` output for given job_id Returns state for the *first* job matching job_id. Returns 'u' if `qstat` output is empty or job_id is not found. """ if qstat_out.strip() == '': return 'u' lines = qstat_out.split('...
ecdc2c09d30b1a765f1a2dae98d901def69d3fdd
577,007
def stitch(folder, filenames, x_size, y_size, output_filename, x_start=0, y_start=0, overlap=10): """ Creates a Fiji Grid/Collection stitching macro. Parameters are the same as in the plugin and are described in further detail here: http://fiji.sc/Image_Stitching#Grid.2FCollection_Stitc...
cc78fd292bafb9349c2a0916518f4624d4e450e2
577,011
def rk4_constant_control(dynamics_fun, controller, x0, dt, constant_control_steps): """ Given a system ẋ=f(x, u) and a controller u=π(x), we simulate the system for duration = constant_control_steps * dt. During this duration the control action is fixed to u=controller(x0). dt ...
8cfb6061c8d0aad8e96b615c8ef357fe9db55961
577,016
def _strip_nul(text): """Remove NUL values from the text, so that it can be treated as text There should likely be no NUL values in human-readable logs anyway. """ return text.replace('\x00', '<NUL>')
6e10ea4fa9283461815cf6050a0e18db75c0ce86
577,018
def read_lines_from_a_file(pFromFile): """ Opens pFromFile , reads it and returns the lines as a list Args pFromFile the name of the file to write to. """ lines = [] f=open(pFromFile,"r") lines = f.readlines() f.close() return lines
9c059fb19634a4f44160b06d6d485f675c7fe073
577,020
import itertools def GetLatencyEvents(process, timeline_range): """Get LatencyInfo trace events from the process's trace buffer that are within the timeline_range. Input events dump their LatencyInfo into trace buffer as async trace event of name starting with "InputLatency". Non-input events with name st...
17e932bdd04c1efc069b84606fb104e340f7f9a2
577,021
import math def pack_ranks(nodesize,count): """!Spreads count MPI ranks over the fewest possible nodes whose maximum PETs per node (ppn) is nodesize. Attempts to distribute the ranks per node as equally as possible. Any node will never have more than one or less than one rank than any other node. ...
90b9998aa17e25b1ce2e5f59a0b49b461da3886f
577,023
def compact_form_errors(form): """ Build a compact dict of field errors without messages. This is a helper for errors, keeping it more easy to test since messages may be too long and can be translated which is more difficult to test. Arguments: form (django.forms.Form): A bounded form. ...
0cc39ebf35ceedc5485b76b317d8d437b78f8dc9
577,024
def get_and_transform(dict: dict, key: str, fn, default=None): """Get a value from a dictionary and transform it or return None if the key isn't present""" try: value = dict[key] if value is None: return value else: return fn(value) except KeyError: ...
360d151c720e63945762592697d52d14ac3d0869
577,025
def getDuplicateColumns(df): """ Get a list of duplicate columns. It will iterate over all the columns in dataframe and find the columns whose contents are duplicate. :param df: Dataframe object :return: List of columns whose contents are duplicates. """ duplicateColumnNames = set() # Iterate over all the colum...
96f36462d00c8d87fac0baeee713434ad018ee6f
577,027
import torch def reorder_gru_states(gru_state, order): """ gru_state: [num_layer * num_directions, batch, hidden_size] order: list of sequence length """ assert len(order) == gru_state.size(1) order = torch.LongTensor(order).to(gru_state.device) sorted_state = gru_state.index_select(index=...
160e8ec71af8c97041e5e68e4071b678394aa537
577,029
def prev(n, r): """The player after n.""" return (n - 1) % r.nPlayers
bdd1e398f6901c80b43c7e0f86668ca8870490f0
577,034
def _ValidateFeatureOptions(feature_options): """Checks that the feature_options is properly formatted. Args: feature_options (dict): A dictionary mapping feature to its configurations. For example: { 'TouchCrashedComponent': { 'blacklist': ['Internals>Core'], } ...
bd80a3fbfbaba0ca73fb5192f3d0cd04d80eed6f
577,036
def transform_gender(value): """ Transform any gender value into a normalized value. """ if value.lower() in ("male", "m"): return "male" elif value.lower() in ("female", "f"): return "female" elif value.lower() in ("other", "o"): return "other" elif value.lower() in ...
a3628423d1ddbc8eff7fc9d0c25ed12891ec8965
577,040
def mixr2spechum(r): """ Calculate specific humidity from mixing ratio. **Inputs/Outputs** Variable I/O Description Units -------- --- ----------- ----- r I Mixing ratio kg/kg q O Specific humidity kg/kg """ return r/(r+1)
0445cb389d0cc85b899c899a69abd64026b1dd34
577,043
import math def bearing(point1, point2): """ Calculates the initial bearing between point1 and point2 relative to north (zero degrees). """ lat1r = math.radians(point1.latitude) lat2r = math.radians(point2.latitude) dlon = math.radians(point2.longitude - point1.longitude) y = math.si...
473238c967d9d882c36343f2c3735ef8c7abb622
577,046
import json def file_uploaded_msg_to_json(file_name, repo_id, uploaded_to): """Encode file uploaded message to json string. """ return json.dumps({'file_name': file_name, 'repo_id': repo_id, 'uploaded_to': uploaded_to})
6375c09b32aa2bf75df7bf642f9ff752325ed7aa
577,051
def separate_negatives(lst): """ Seperate a list of numbers into negative and nonnegative (>= 0) """ neg_lst = tuple(val for val in lst if val < 0) pos_lst = tuple(val for val in lst if val >= 0) return neg_lst, pos_lst
9821d23c85b48c244047f9cdccb3b4f23e43034a
577,055
from typing import Tuple import math def _accept(random_sample: float, cost_diff: float, temp: float) -> Tuple[bool, float]: """Calculates probability and draws if solution should be accepted. Based on exp(-Delta*E/T) formula. Args: random_sample: Uniformly distributed random number ...
65769903dafba93842bb41752883357de4ec0e67
577,061
def auth_succeeded_prepared_stream_reader(connection_prepared_stream_reader): """Create StreamReader and fill it with auth succeeded.""" connection_prepared_stream_reader.feed_data(b"OK\n") return connection_prepared_stream_reader
04901c37e8d0083682af0f6df61792a5e6ec3ef2
577,068
def get_ngaussians(fit): """Determine the number of gaussians in a :class:`lmfit.model.Model`. Parameters ---------- fit : :class:`lmfit.model.Model` or :class:`lmfit.model.ModelResult` The model to analyze. Returns ------- int The number of components whose name contains "...
101bce1bc49b82d249b86f8cc8a10c8f296334d5
577,069
import hashlib def hashfile(srcFilePath, hashType, BLOCK_SIZE=65536): """ Hash any give file in its hash :param srcFilePath: path to the file from which the reference hash is supposed to originate from :param hashType: hash type to use :param BLOCK_SIZE: default is 65536; change to any ot...
c28cfabfd1275d165cce3549be7a16526ba07e21
577,071
def longest_collatz(ceiling): """ Returns the number below ceiling which produces the longest chain. """ # Trades space for time term_lengths = [0, 1] for i in range(2, ceiling): terms = 1 while i >= len(term_lengths): if i % 2 == 0: i = i // 2 ...
906534c85e106a816e52f1cfd74300bc0db5edfb
577,072
def read_qids(fname): """Reads the query id file, used typically with ranking Parameters ---------- fname : string input file name Returns ------- Q : list of n_queries index lists """ f = open(fname) qids = [] for line in f: qid = line.strip() ...
9812f90c55ef5786741d17f4fb0cf7826ed16711
577,075
def get_data_codewords(bits, codeword_size): """ Get codewords stream from data bits sequence Bit stuffing and padding are used to avoid all-zero and all-ones codewords :param bits: input data bits :param codeword_size: codeword size in bits :return: data codewords """ codewords = [] su...
64f32f2cf6b5484d3bfb16a280d09958e3da7af4
577,080
from functools import reduce def hash_seq(seq): """Given a sequence of hash values, return a combined xor'd hash.""" return reduce(lambda x, y: x ^ y, seq, 0)
d7cc1003f51249696ec0fd90d0911632c6dc5c34
577,083
import inspect def ensure_instance(obj, *args, **kwargs): """ If the given object is not an instance, instantiate with given arguments """ if inspect.isclass(obj): obj = obj(*args, **kwargs) return obj
439fb74362b0ff84a3e616575fbb51d66b29dac2
577,084
def literal_to_float_list(arg_literal : str): """Evaluate a string literal (e.g. '[1,2,3]') and return list of floats.""" try: result = eval(arg_literal) except SyntaxError: # Does not get caught by argparse ... raise ValueError() if not isinstance(result, list): print("Inv...
b91a089d626eb4454a40173c1ca88d5090387842
577,085
def repredict(dv, t1, t2): """ Takes decision values and returns predictions, given thresholds for the overall level and for distance to the row-wise maximum. Params: dv - 2d array of decision values t1 - either a scalar threshold, or a vector of length(dv.shape[1]) all dvs > t1 are positiv...
044f05bf267eebaedf7dc6623c5e2feee16646ab
577,090
def _careful_add(a, b): """Return the sum `a + b`, else whichever is not `None`, else `None`.""" if a is None: return b if b is None: return a return a + b
4075db5af18239d0b769eda3282a64b4b45c6544
577,092
from typing import Tuple from typing import List import re def _get_data_type_and_keys(target_attr: str) -> Tuple[str, List[str]]: """Extract the name of data_type and its associated keys in a list, if any.""" target_attr = re.sub(r"'|\"| ", "", target_attr) keys = re.findall(r"\[(.*?)\]", target_attr) ...
3a93f3aa6dfe14b5d9e4f0557bfb44a0e037262e
577,094
import hashlib def hash_file(file_obj, hash_function=hashlib.md5): """ Get the hash of an open file-like object. Parameters ------------ file_obj: file like object hash_function: function to use to hash data Returns --------- hashed: str, hex version of result "...
3683428c3a0ca3f50ce4dde282f7e1087f878c23
577,098
def vector_diff(a, b): """Computes difference between two vectors""" return tuple((ai - bi) for ai, bi in zip(a, b))
cd47666af90acf35bc64c4062fd6c38cb6c9ce51
577,100
def compareCards(index1, index2, myBoard, displayBoard): """Compare two guessed cards to see if they match, representing a game turn""" card1 = myBoard[index1] card2 = myBoard[index2] message = "The first card had value {}. ".format(card1) message += "The second card had value {}. ".format(card2...
dae037dc8dd8eaadf433c39c8af200642747857e
577,101
import re def parse_header(line, line_num): """ Parses a header line from hurricane data file. Documentation on header formats is available in the NOAA HURDAT2 format file: http://www.nhc.noaa.gov/data/hurdat/hurdat2-format-atlantic.pdf The first group indicates the basin, cyclone number wit...
32ef414ec7cfc5fe531aa3437455d4f52a796210
577,104
def sizeof_fmt(num): """Little helper to get size in human readable form. Size is rounded to a closest integer value (for simplicity). >>> sizeof_fmt(100) '100 B' >>> sizeof_fmt(1024) '1 KiB' >>> sizeof_fmt(1024*1024 + 100) '1 MiB' """ for unit in ['B', 'KiB', 'MiB']: i...
d058a558a455ff9d6848ae714c8494613f626fd9
577,106
import random def sample_baselines(bls, seed=None): """ Sample a set of baselines with replacement (to be used to generate a bootstrap sample). Parameters ---------- bls : list of either tuples or lists of tuples Set of unique baselines to be sampled from. If groups of baselines ...
e53c66141fa4a90b6d74d64d59ecfae112d93d67
577,109
def find_best_argname(iarg: int, pname: str, cname: str): """Find the best name for the ith argument of a function. Args: iarg: Index of the argument, use for default. pname: Name of the argument in the python signature. cname: Name of the argument in the C++ signature. Returns: ...
f4de3cf78348e860a9350aacfc5bb0bbb1a027ca
577,112
from typing import Counter def counted_lines_of_file(path): """ Return a dict keyed on the lines of the file, with values being the number of times that line was seen. """ print(f"Reading {path}") with open(path) as fp: fp.readline() # burn the header row counted = Counter(fp)...
86e384f71237a5a4577d5d93f807e5e5d4335214
577,113
def replace(body, keys): """For each key and value, replace '%key%' with value""" for key, value in keys.items(): body = body.replace("%" + key + "%", value) return body
24e7631dc1844ed992acbe18176eca9c4177e86a
577,114
def get_base_target_link(experiment_config): """Returns the base of the target link for this experiment so that get_instance_from_preempted_operation can return the instance.""" return ('https://www.googleapis.com/compute/v1/projects/{project}/zones/' '{zone}/instances/').format( ...
8248f0dbdd92580ff71b7c34d7ccf42612f3bafc
577,117
def ngram_from_tokens_gen(tokens, n=1): """Generates ngrams from list of tokens. Each ngram is a tuple of tokens. """ return zip(*[tokens[i:] for i in range(n)])
089d09be773fb6cbb24ec084c2ce867a2b4e4054
577,119
def nodeNameFromFullname(fullname): """Name of the node from a fullname The name of the node is the first part of a fullname Args: fullname(str): Fullname of a node, connector or port Returns: The name of the node, first part of a fullname """ n = fullname.split(':')[0] re...
759d9cc9a53d43832d87d8c20c878532caf1749c
577,120
def get_city_country(city, country): """Print the city and the country""" city_country = city.title() + ", " + country.title() return city_country
c411929dcebc85b5ac9fc0f5ad926a398042b93b
577,121
async def audio_playing(ctx): """Checks that audio is currently playing before continuing.""" client = ctx.guild.voice_client if client and client.channel and client.source: return True else: return False # raise commands.CommandError("Not currently playing any audio.")
e5f73bf062c03cfcf81baa54d32b07de51d880f5
577,122
import logging def custom_log(gear_context): """ Generate a log with level and name configured for the suite, gear name and gear-log-level :param gear_context: an instance of the flywheel gear context that includes the manifest_json attribute :type gear_context: flywheel.gear_context.GearContext :...
167cd49498bc71442387eb5a11e1ec741e55d0fe
577,123
def _get_channel_rank(image_format): """Returns the rank of the channel dimension.""" if image_format not in ['HWCN', 'NHWC', 'NCHW']: raise ValueError('Unimplemented images format: {:s}.'.format(image_format)) return image_format.find('C')
c8a8163fd49a95f62baf109b97d57869e57d63c3
577,124
def seconds_to_human(seconds): """Convert seconds to a human readable format. Args: seconds (int): Seconds. Returns: str: Return seconds into human readable format. """ units = ( ('week', 60 * 60 * 24 * 7), ('day', 60 * 60 * 24), ('hour', 60 * 60), ...
7aea36c236aad9bec1927b4704f322b19a9de308
577,125
from typing import Optional import torch def get_device(device: Optional[str] = None) -> torch.device: """Selects a device to perform an NST on. Args: device: If ``str``, returns the corresponding :class:`~torch.device`. If ``None`` selects CUDA if available and otherwise CPU. Defaults to...
3ca5272ff3181c855e696335b26e7105d0404080
577,127
def closest(lst, K): """ Find a number in list lst that is closest to the value K. """ return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]
a228aaeec890e1fb1a71d2418d6770fdb9ba4d8a
577,133
from functools import reduce def combine_alternatives(lists): """ Accepts a list of alternatives, and enumerates all their possible concatinations. Examples: >>> combine_alternatives([range(2), [4,5]]) [[0, 4], [0, 5], [1, 4], [1, 5]] >>> combine_alternatives(["abc", "xy", '$']) ...
9789e5350a2862ad1804a3853fdbb06653f56bd4
577,135
from typing import Dict def create_identity_parameters(identity: str) -> Dict[str, str]: """Creates request parameters containing identity""" return {"identity": identity}
38c038071b10bb14bb501d9d5c38f8cd51f3204c
577,146
def add_time_variation(df, exclude_columns=['時', '日付'], inplace=True): """ 時間変化量をDataFrameに追加する Args: df(DataFrame) : 変換対象のDataFrame exclude_columns(list) : 変換対象から除外する列 inplace(bool) : 元のDataFrameを変更するか否か Returns: DataFrame : 変換後のDataFrame """ ...
18218936000fa5b262e875f37437b668ca407555
577,151
import itertools def nth(iterable, n): """Returns the nth item""" return next(itertools.islice(iterable, n, None))
fe6251b6f7e6ff8e1135626fa360ba6f81d280f4
577,152
from typing import Any def is_none_or_int(obj: Any) -> bool: """Check if obj is None or an integer. :param obj: Object to check. :type obj: object :return: True if object is None or an integer. :rtype: bool """ return obj is None or (isinstance(obj, int) and obj >= 0)
cfc1f57e32f54b15360aa383282c9106660df012
577,153
def GetLoans(sliver_name): """Return the list of loans made by the specified sliver""" rec = sliver_name return rec.get('_loans', [])[:]
4736034a729a7135e851110b1f57c996367b7232
577,154
def splitKeep(s, delim): """ Similar to split, but keeps the delimiter as separate element, e.g. splitKeep("aaabaaabaa", "b") -> ["aaa", "b", "aaa", "b", "aa"] """ result = [] for e in s.split(delim): result.append(e) result.append(delim) return result[:-1]
dac0c0b126cf31af716e5bbc6f9bd76c2995cebb
577,165
def find_intersections(tree, s, e): """ Function to find inserts that bridge a region of a contig. Arguments: tree: interval tree of start/end positions of mate pair inserts s: start position of interval on contig e: end position of interval on contig Return a list of nodes from tr...
4b708c29d1aea52d4ad3f982401ab0647396af83
577,166
from datetime import datetime def to_date(epoch_micros): """ Transforms a timestamp in epoch microseconds to a more legible format. """ epoch_secs = epoch_micros / 1000000.0 return datetime.fromtimestamp(epoch_secs).strftime('%Y-%m-%d %H:%M:%S.%f')
8c468e0c9e53b5d07aa92b98ba36f94933bf5c15
577,168
def load_vocab(vocab_file): """ :param vocab_file: one character per line :return: labels: list of character """ labels = [] with open(vocab_file, "r", encoding="utf-8") as f: for line in f: line = line.strip() labels.append(line) return labels
d7cebbcdd529d11f8db5fe4d7d2e4c6300c0c023
577,176
def list_to_dict(dicts): """ Convert a list of dictionaries to a dictionary of list """ new_dict = dict() if isinstance(dicts, list): for key in dicts[0]: new_dict[key] = [d[key] for d in dicts] return new_dict
e01f1b9ea76f9f9642deb00a523079099945bfc6
577,177
def _read_me() -> str: """Return the README content from the file.""" with open("README.md", "rt", encoding="utf8") as fh: readme = fh.read() return readme
e50577612259e45e2fb149027de3e00968e6f03c
577,179
import statistics def sd(array): """ Calculates the standard deviation of an array/vector """ return statistics.stdev(array)
1710c2174d76649f3d8cce28a74048bd3d6b9b16
577,182
from typing import List def binary_search_iterative(array: List[int], value: int) -> int: """ An iterative implementation of binary search. Runs in O(log n) time and O(1) space. :param array: is the array to search. :param value: is the value to search for. :return: the index of the value, or...
b7cadb818903f02af72d169671a3a897e1aac26f
577,187
def get_range(upper): """Returns a list with integer between the range provided.""" return range(upper)
2dcf74fc98a9378aaabfa7633f57fa013232c1c1
577,190
def list_union(lst1, lst2): """ Combines two lists by the union of their values Parameters ---------- lst1, lst2 : list lists to combine Returns ------- final_list : list union of values in lst1 and lst2 """ final_list = set(lst1).union(set(lst2)) return f...
c55ebb899eccb7bce72eb733539a1b28b69f9b0f
577,192
import torch from typing import OrderedDict def update_parameters(model, loss, step_size=0.5, first_order=False): """Update the parameters of the model, with one step of gradient descent. Parameters ---------- model : `MetaModule` instance Model. loss : `torch.FloatTensor` instance ...
dc9d0bcc48257b594c140f3e832ccef2454191a4
577,199
def set_visible_size(width: int, height: int) -> dict: """Resizes the frame/viewport of the page. Note that this does not affect the frame's container (e.g. browser window). Can be used to produce screenshots of the specified size. Not supported on Android. Parameters ---------- width: int ...
ebabfc05117615d68b163bac3f446bb71fad5120
577,200
def as_hex(value): """Turn an integer into a hex string""" return format(value, '#02x')
1f6249f970c4bdaa46475ca98615968278bbd8b3
577,202
def get_ireq_version(ireq): """ Get version of a requirement even if it's editable. :type ireq: InstallRequirement|str """ if not ireq.req or not ireq.specifier or not ireq.specifier._specs: return None specs = (x._spec for x in ireq.specifier._specs) versions = set( versio...
8b70c05491fa12383cb8d9478986240b33783338
577,203
def is_upstream_processed(incoming_edges, edges_to_process): """ Check if all incoming edges have been processed. Return True if processed. :param incoming_edges: list of edges to check (incoming edges of a current edge) :type incoming_edges: list of Edge objects :param edges_to_process: l...
c71f81907525119a4dc0d61b30dec980769771f6
577,204
def underline_last(text, offset=0): """ Utility function to underline the last part of a path :param text: text to underline :param offset: add offset to underling :return: original text with underline on a new line """ index = [i for i, x in enumerate(text) if x in ['.', ' ']][-1] if...
65ffa5be229c4518f5d4c2baf5a7e583aaf1b665
577,207
def uses_host(f): """Decorate f with the attribute `uses_host`. When XMLRPC renders the given XML RPC method, it will pass the host as a named argument. """ f.uses_host = True return f
de91942dd0135a3a44d0c5621fbfa000983d79fb
577,208
def pad(val: str, spaces: int = 2) -> str: """Pad val on left and right with `spaces` whitespace chars Arguments: val {str} -- string to pad Keyword Arguments: spaces {int} -- number of spaces to pad on either side (default: {2}) Returns: str -- padded string """ pad_s...
5cbf2c9b29f3f243f9d79b9a9a43038c67aae891
577,210
def dict_contains_sub_dict(config, test_config): """ Determine whether a dictionary contains a sub-dictionary. Returns True if test_config is an empty dict. Parameters ---------- config : dict test_config : dict """ if not isinstance(config, dict) or not isinstance(test_config, dict...
3aff78ab67d3fdefc9290148015c688d7741726a
577,214
def levenshtein_distance(a, b): """Compute the Levenshtein edit distance between the sequences a and b.""" m = len(a) + 1 n = len(b) + 1 d = [[0]*n for _ in range(m)] for i in range(m): d[i][0] = i # deletion for j in range(n): d[0][j] = j # insertion for i in range(1, m): for j in...
349d00ff484347bca24badac657b49cdafb8d958
577,216
def fast_tabulated_fibonacci(n): """Returns the nth fibonacci number Time complexity: O(n) Parameters ---------- n : int the nth fibonacci position Returns ------- int the nth fibonacci number ------- >>> fast_tabulated_fibonacci(0) 0 >>> fast_tabulat...
946a4d26afbafc43f88aa3494b99f5daf1df90c6
577,217
def db_table_exists(db_cursor, tbl_name): """Check if table exists in given sqlite database""" db_cursor.execute(" SELECT count(name) FROM sqlite_master WHERE type='table' AND name=?", [tbl_name]) if not db_cursor.fetchone()[0] == 1: return False else: return True
8280622621b5bf7e08ba7c6870758703215d169f
577,222
def sqlalchemy_to_dict(_row, org_fields, geo_fields): """Pull relevant fields out of the JOIN'd org-geo object. Args: _row (sqlalchemy model): JOIN'd org-geo object. org_fields (list): List of Organization fields to extract. geo_fields (list): List of Geographic fields to extract. r...
1e67e5a8942cb54c0ebc8e99267d4606cc0e16e2
577,225
def encode_file_path(s): """Encodes an URL path from internal format for use in disk filenames""" # This doesn't change the string. # But, if we ever change the internal representation of paths, we'll # need to change the 3 functions here that deal with it return s
c8666c802a7079cf1e83fc6d93b6a24380b95047
577,226
def allocate_blocks(llvm_func, pykit_func): """Return a dict mapping pykit blocks to llvm blocks""" blocks = {} for block in pykit_func.blocks: blocks[block] = llvm_func.append_basic_block(pykit_func.name) return blocks
11b23f04f49a961bfebf3a92436458edca1ca685
577,228
import re def remove_word_from_word(word_to_remove: str, total_word: str) -> str: """ Remove the letters from word_to_remove from total_word >>> remove_word_from_word('ZOEN', 'ZOEVEN') 'VE' >>> remove_word_from_word('ZOEK', 'ZOEVEN') 'VEN' """ for letter in word_to_remove: t...
a5462abd2e6967f77eed480e64d9202dcbca3b38
577,231
def exception_string(e): """Return an interpreter like error string from an exception.""" s = type(e).__name__ # If e is not a built-in exception add module to exception name. if hasattr(e, '__module__'): s = '{}.{}'.format(e.__module__, s) # If e has a message add ':' and message. if ...
5faf3a786d4ed36996019160b17ea83fa9be6892
577,232
def align_skeleton(skeleton, code): """ Aligns the given skeleton with the given code, minimizing the edit distance between the two. Both skeleton and code are assumed to be valid one-line strings of code. >>> align_skeleton(skeleton="", code="") '' >>> align_skeleton(skeleton="", code="i") ...
799294dfde023276ba1fe159eacad4b0973beb49
577,241
import audioop def convert_framerate(fragment, width, nchannels, framerate_in, framerate_out): """ Convert framerate (sampling rate) of the input fragment. Parameters ---------- fragment : bytes object Specifies the original fragment. width : int Specifies the fragment's origi...
703290e1edc7b45742b3002faef81fc981b82642
577,244
def sum_formula_general_from_zero(d: int, n: int) -> int: """ SUM k=0 to n-1 of (k*d) = n/2 ((n-1)d) https://www.mathsisfun.com/algebra/sequences-sums-arithmetic.html d = difference between terms n = amount of terms """ assert n > 0, n return n * (n - 1) * d // 2
13307354222a4de54c509e13cd189a1acc07834a
577,246
from typing import List from typing import Tuple def mul_factor(factors: List[Tuple[int, int]]) -> int: """Computes an integer whose prime factorization is given """ n = 1 for f in factors: n *= f[0] ** f[1] return n
77ba2b51fbb18d60904c4c913318d6ea1fb90f25
577,247
def index(value, i): """Returns the index of the given value.""" return value[i]
0f444b3a4c3c545a967a49093f903be8225fa392
577,249
import math def double_cylindric_magnet( radius=0.00075, length=0.01, center_distance=0.0015, density=7500 ): """ Function to get the masse, volume and inertial moment of a double cylindre magnet, like for GEONAUTE R900 compass. International system units """ V = 2 * math.pow(radius, 2) * math...
547937634637e97f3dd17de1d5aada8da0c968d1
577,250
def _format_target(target, nb_samples): """ Formats target to return a list. Args: target (None or np.ndarray): Original target. nb_samples (int): Number of samples in the batch. """ return [t.astype(int) for t in target] if target is not None else None
49e98cd30d14769222a96e0624aca2edeeeae901
577,252
import torch def has_hooks(module: torch.nn.Module): """ Returns True if the module uses hooks. """ for hooks in (module._forward_pre_hooks, # pylint: disable=protected-access module._forward_hooks, module._backward_hooks): # pylint: disable=protected-access if hooks: ...
f46bba801c346448d3f3a92ac0932f4680dc98ea
577,254
import torch def rank_order( datum: torch.Tensor, time: int, dt: float = 1.0, **kwargs ) -> torch.Tensor: # language=rst """ Encodes data via a rank order coding-like representation. One spike per neuron, temporally ordered by decreasing intensity. Inputs must be non-negative. :param datum: T...
da54bd6af1fdde44afad5ea2eb3c016efe42d5d5
577,258
def iso_string_to_sql_utcdatetime_sqlite(x: str) -> str: """ Provides SQLite SQL to convert a column to a ``DATETIME`` in UTC. The argument ``x`` is the SQL expression to be converted (such as a column name). Output like: .. code-block:: none 2015-11-14 18:52:47.000 2015-11-14...
b6e3fee037e1f93a6ffbd7d48a51cc9927a8c2c4
577,259
def A_is_one_wkend_days_init(M, i, w, t, e): """ Initialize indicator for each weekend worked pattern as to whether each week is sandwiched by consec weekend days worked. :param M: Model :param i: weekend worked pattern :param w: week :param t: tour type :param e: weekend type (1=Sun an...
f427a043f19ac96698fcd0e3c2c6408b624dfa61
577,260
import re def invalid_year_format(command_line_arguments): """Checks the input year format, if invalid returns true.""" year_input_string = command_line_arguments.year if year_input_string and re.search(r"^\d+(-){1}\d+((,){1}(\s){1}\d+(-){1}\d+)*$", year_input_string) is None: return True return False
e2c1cd948795462fc68ebf5c482ccac3bfaf4c93
577,266