content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def calc_num_weights3(num_inputs, layer_sizes, num_outputs, m_trainable_arr, b_trainable_arr): """ accounts for fact that certain weight matrices / bias vectors may not be trainable """ n = 0 if len(layer_sizes) == 0: if m_trainable_arr[0]: n += num_inputs * num_outputs if b_trainable_arr[0]: n += num_o...
b6cc4afaffa020e3e3f912260c20a4a2fb7654e2
678,675
def drop_invalid_cassettes(cassettes, cassettes_to_drop): """ remove cassettes in cassettes_to_drop """ y = cassettes[['mO_name', 'forward_start']].apply(lambda x: list(x) in cassettes_to_drop, axis=1) return cassettes[~y].reset_index(drop=True)
5f614dcae90db3235411a2c810cab422a526a7a7
678,676
import torch from typing import OrderedDict def load_weights_to_gpu(weights_dir=None, gpu=None): """ docstring """ weights_dict = None if weights_dir is not None: if gpu is None: map_location = lambda storage, loc: storage else: map_location = lambda storage...
1e2d8366f7bc712fb9f1e3b14d805649cf64b6a1
678,677
def get_orientation(strategy, **kwargs): """ Determine a PV system's surface tilt and surface azimuth using a named strategy. Parameters ---------- strategy: str The orientation strategy. Allowed strategies include 'flat', 'south_at_latitude_tilt'. **kwargs: Strategy...
f1d27d67175bd2caa3bb95e8d31668ef07a4c8e2
678,678
def stockmax(prices_): """ Given an array of prices in a stock market find the highest profit you can gain. :param : int[] prices :rtype : int """ if len(prices_) < 2: return 0 profit, peak = 0, prices_[-1] for i in range(len(prices_) - 1, -1, -1): if prices_[i] > pea...
81bdaa94e5a8e2a737be85ff5ad32af9909e7bcb
678,679
import re def trPy(s, l='[,\\\\"/>()-]', char=' '): """In string 's' replace all the charachters from 'l' with 'char'.""" return re.sub(l, char, s)
116ca7fefe4f364b43db98a06b53846cbf7c2030
678,680
def iddofobject(data, commdct, key): """from commdct, return the idd of the object key""" dtls = data.dtls i = dtls.index(key) return commdct[i]
ce2acd6cf7e4e905b13e234b03f4e1ac6194dca1
678,683
import json def load_categories(filename): """Load categories from a file containing json data Parameters: filename (string): the name of the file Returns: object:the categories object """ with open(filename, 'r') as f: cat_to_name = json.load(f) return cat_to_name
cab0612bb83f59224cec31c951bee86c496a2dfe
678,684
def t_norm(a, b, norm=min): """ Equivalent to `a.t_norm(b, norm)`. """ return a.t_norm(b, norm)
81fca86cce391f9d8c67d2a0e3b3060c0d495ad4
678,685
import random import string def get_random_string(length=6): """ Return a random string 'length' characters long """ return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length))
8de81f82ab044a43608385a3fc8d150b6e08e035
678,686
import torch def det_randn(*args): """ deterministic random to track the same latent vars (and images) across training steps helps to visualize same image over training steps """ return torch.randn(*args)
89b468eaadd2751a93aa21f0cbf557dc133f7ccf
678,687
def mag_double_power_law(mag, phi_star, mag_star, alpha, beta): """Evaluate a broken double power law luminosity function as a function of magnitude. :param mag: Magnitude :type mag: float or np.ndarray :param phi_star: Normalization of the broken power law at a value of mag_star :type phi...
60c891ae6ce8c646ebc51eabc748b1b6c187dda0
678,688
def list_dict_to_list_list(players: list[dict]) -> list[list]: """Convert a list of dictionaries to a list of lists.""" new_list: list = [] for player in players: stats: list = [] for stat in player.values(): stats.append(stat) new_list.append(stats) return new_list
94ca274fad7373f2ca2eacc28d78afa1156fac73
678,689
import csv def samples(gnomAD_path: str): """Create dictionary of sample ID and haplogroup. :param gnomAD_path: path to the gnomAD VCF :return: matches_samples dictionary with the haplogroup of every sample """ with open(gnomAD_path + "t21/sample_annotations_gnomad.txt") as csv_file: samp...
039f52f238fe725f3e06edc7962f5496fb4b37a2
678,690
def fix_var_name(var_name): """Clean up and apply standard formatting to variable names.""" name = var_name.strip() for char in '(). /#,': name = name.replace(char, '_') name = name.replace('+', 'pos_') name = name.replace('-', 'neg_') if name.endswith('_'): name = name[:-1] ...
9022f32862b06e58fc4b6c65ca9f5c961c3148fc
678,691
import sys def readFromArguments(): """Reads from the arguments given""" # Concatenate all command line arguments into a long string arguments_in = sys.argv args_in = " ".join(arguments_in[1:]) return args_in
6ba94d402047511bbe8cc2883da129b5778cf8d5
678,693
def SIR (t, y, **kwargs): """ Three compartment SIR Model """ N, beta, gamma = \ kwargs['N'], kwargs['beta'], kwargs['gamma'] S, I, R = y[0]/N, y[1], y[2] return [-beta*S*I, beta*S*I-gamma*I, gamma*I]
f78272da23deadbbbcf73682fcad09d980d40f87
678,694
from typing import Sequence def variant_to_pair(variant: str) -> Sequence[str]: """Given a variant, splits it into an OS and ABI pair Parameters ---------- variant : str The variant received as input to the script (e.g. windows-win64) Returns ------- Sequence[str] A 2...
25f66b24095d529e59a6316aae7a72107572552f
678,695
def extract_properties_by_schema(group_objects_list, group_gid_number_attr, group_name_attr): """ Safeguard Authentication Services is designed to support any Active Directory schema configuration. If your Active Directory schema has built-in support for Unix attributes (Windows 2003 R2 schema, SFU sche...
9d3860ad6fa53ddc34275c61d0186937d58b9f41
678,696
import json def extract_event_from_queue_message(queued_event_message): # -*- coding: utf-8 -*- """This method takes a 'queued_event_message', and if it is an SQS structure (i.e. if 'eventSource' is 'aws:sqs'), then it extracts and returns just the value of the "body" key within it, but it returns it ...
04fb08f9abb8b855131bdefbb1d1594ff62da0f8
678,697
def coupling_list2dict(couplinglist): """Convert coupling map list into dictionary. Example list format: [[0, 1], [0, 2], [1, 2]] Example dictionary format: {0: [1, 2], 1: [2]} We do not do any checking of the input. Return coupling map in dict format. """ if not couplinglist: ret...
dffe72a5312bb8047683ac0784a4620913875d7e
678,698
def GetKnoteSummary(kn): """ Summarizes a knote and related information returns: str - summary of knote """ out_string = "" format_string = "{o: <#020x}" out_string += format_string.format(o=kn) return out_string
0933360ec9876154a4dd1433b874678b37307b81
678,699
def convert_ndarry(matrix): """ Convert pandas.series into numpy.ndarray """ try: return matrix.values.flatten() except AttributeError as e: print(e)
64e5bd23f3f7d2d5d36bf6142d35bfbfb06e6372
678,700
def scale(v,sc): """Scale a vector. Parameters ---------- v : list A 3D vector. sc : int or float A scaling factor. Returns ------- tuple Returns `v` scaled by `sc`. Examples -------- >>> from .pycgmKinetics import scale >>> v = [1,2,3] >>> ...
8ec979707ba9c4909ca797ec2ea4b0f2164e3776
678,701
def infix_to_postfix(expression): """ Function turns infix expression into postfix expression by iterating over the expression and moving operators after their operands whilst maintaining order of precedence. :param expression: Space delimited parenthetical expression containing of letters and the oper...
09bed208eb1f027ea0fece25a38a8abeeb72996e
678,702
def clean_csv_values(row): """Strip leading and trailing whitespace from row values. Could be used in the future for other normalization tasks. """ for field in row: if isinstance(row[field], str): row[field] = row[field].strip() return row
90c0be045d1c276d74be17c64c8529df9a6de39a
678,703
def q_max_ntu(c_min, temp_hot_in, temp_cold_in): """Computes the maximum q value for the NTU method Args: c_min (int, float): minimum C value for NTU calculations. temp_hot_in (int, float): Hot side inlet temeprature. temp_cold_in (int, float): Cold side inlet temeprature. ...
2e4e7fee30ed41ae2f4ad174c79ea7092c2d3df4
678,705
def dms_to_dmm(d, m, s): """Converts degrees, minutes and decimal seconds to degrees and decimal minutes. Example: (41, 24, 12.2) -> (41, 24.2033) :param int d: degrees :param int m: minutes :param float s: decimal seconds :rtype: str """ return d, m + s / 60
df6484e58393354c31d82b9498b9e9589221b525
678,706
import re def get_subsequences(seq): """ Now with hardcoded regular expressions """ match_p = re.match(r'TGATG[AT][AGTCN]{0,40}([AGTCN]{10})(?:(?:TGA)|(?:CGA)|(?:TGT)|(?:TTA)|(?:TGC))[AGTCN]{2,40}T[AGTCN]{2,35}([AGTCN]{10})CTGA', seq) if match_p: return list(match_p.groups()) match_n = re...
1a6e6104a3899666a457888ad6c6cbc81394ccd8
678,707
from datetime import datetime def get_date_by_standard_time(standard_time): """ 将yyyy-MM-DD HH:mm:ss格式的时间返回年月日 :param standard_time: :return: """ return datetime.strptime(standard_time, '%Y-%m-%d %H:%M:%S').date().__str__()
ae952c0fe8facd3d39c10c85d7fb6766e41b4e34
678,708
import re def prepare_cmd(config, oneseries, cmd_exec, x_value=None): """prepare cmd""" cmd = cmd_exec cmd_vars = re.findall(r'\${.+?}', cmd) for item in cmd_vars: replace_item = item.replace('${', '').replace('}', '') if replace_item in config: cmd = cmd.replace(item, str(...
9ff8c48195e9b60d9b2b4d9949045c974e93c6f3
678,709
def get_year_version_from_schema(schema_string): """ expects a schema string from xml like: 2015v2.1 """ [year, version] = schema_string.split('v') return({'year':int(year), 'version':version})
4db6a9184eac2a46b24c57a598ba0947bfd1bf32
678,710
def is_empty(value): """ Checks if a value is an empty string or None. """ if value is None or value == '': return True return False
8090e8a936df133bc9b0beff81b81eeee4283a79
678,711
def get_them(list_of_lists): """A very poor example of a function. This code is NOT clean. This is not clean for many reasons. Mostly that we have to know what list_of_lists is composed of in order to decipher it. What things are in the list? What is the 0th index of an item in the list about? What does 4 mean? H...
5fc66004378f0d92849685a9f3688bb6593eb497
678,712
def theme(dark=False, lighten=0.3, lighten_edges=None, lighten_text=None, lighten_grid=None, **kwargs): """ Create plotting parameters for different themes. Parameters ---------- dark : bool Dark or light theme. lighten : float with range [0.0, 1.0] Lighten lines by fr...
79892b846fd3ae47a05aa128feed8a86b707e87c
678,713
def is_close(a, b, rel_tol=1e-09, abs_tol=0.0): """Determines whether two floats are within a tolerance. Returns: bool: Returns True if the two floats are within a tolerance, False otherwise. """ return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
001278ed6a90e66f0006112fc6dae02ac0c40877
678,714
def fast_susceptible(g, ego, edge): """ Fast check for 'susceptible or already adopted' under triangle closing rule""" try: from_neighbors = set(g.node[ego]['M'][edge[0]]) # if concept not in network, raise if edge[1] in from_neighbors: # edge already exists return True to_...
7933b7afbfe2f043d402ec873170345ebfaa9e4e
678,717
def add_account(validator, whiptail): """ "Add account" dialog. :param dexbot.config_validator.ConfigValidator validator: dexbot config validator :param whiptail.Whiptail whiptail: instance of Whiptail or NoWhiptail :return str: user-supplied account name """ account = whiptail.prompt("You...
260ac45f017bcf713f6c7d0d22c590ed5b11c00d
678,719
import math def get_interleave_value_in_array(original_map, width, height, x, y): """x and y can be float value""" weight_next_x, base_x = math.modf(x) weight_preceding_x = 1.0 - weight_next_x weight_next_y, base_y = math.modf(y) weight_preceding_y = 1.0 - weight_next_y base_x = int(base_x) ...
9619ef88a0f5f46213748c4f09a6f1442eae21eb
678,720
def get_empty_gids(ibs, imgsetid=None): """ returns gid list without any chips """ gid_list = ibs.get_valid_gids(imgsetid=imgsetid) nRois_list = ibs.get_image_num_annotations(gid_list) empty_gids = [gid for gid, nRois in zip(gid_list, nRois_list) if nRois == 0] return empty_gids
b68b28993ace1c3f6d9b2cdc6b538b41b7d0dcd7
678,721
import sys import os def _p(p): """Converts path string **p** from posix format to os-specific format.""" drive = [] if p.startswith('/') and sys.platform == 'win32': drive = ['C:'] pieces = p.split('/') return os.path.sep.join(drive + pieces)
003e2d8c6275db6024497f0457c80eebe4d56f8f
678,722
def get_bibref_text(line): """Return the line with a text field concatenating parsed attributes. Expect a serialized bibref citation (grobid flavor)""" def get_dict_values(d): s = "" for k, v in d.items(): if v: s = " ".join([s, str(v)]) return s.strip() ...
ede51be28282ca5947a2ff83dc7c82045e78fe16
678,723
def everyone(connection, window_info, kwargs): """allow everyone to call a Python WS signal or remote function >>> @signal(is_allowed_to=everyone) ... def my_signal(request, arg1=None): ... # noinspection PyUnresolvedReferences ... print(request, arg1) """ return True
7304169766cbcffd5eb36abbc8b46bf3e8871506
678,724
import os from pathlib import Path def _name_fixup(name): """ >>> _name_fixup('foo.bar') 'foo.bar' >>> _name_fixup('/usr/lib/python3.5/abc.py') 'abc' >>> _name_fixup('/usr/lib/python3.5/distutils/__init__.py') 'distutils' """ if os.path.sep in name: # used with filename, li...
3b318f75bd97ac0e7ac6099e04404ffa51951810
678,725
def fix_ra_dec(ra, dec): """ Wraps input RA and DEC values into range expected by the extensions. Parameters ------------ RA: array-like, units must be degrees Right Ascension values (astronomical longitude) DEC: array-like, units must be degrees Declination values (astronomical ...
721aef6fe21128857d81185c8ea344edaaf9894c
678,726
def complete_cases(_data): """Return a logical vector indicating values of rows are complete. Args: _data: The dataframe Returns: A logical vector specifying which observations/rows have no missing values across the entire sequence. """ return _data.apply(lambda row: row.no...
3e6e294f11988d04fd1c3d7d46b409badf1f90f9
678,727
def is_odd(int): """Determine if an interger is odd using binary operations. Parameters ---------- int : `int` an integer Returns ------- `bool` true if odd, False if even """ return int & 0x1
f86b5f7b442883abe835c3c357a2efbb21b912af
678,728
def non_writable_folder(fs): """ A filesystem with a /dir directory that is not writable """ fs.create_dir('/dir', perm_bits=000) return fs
1259701e3aa8cce6d0fb7ce5ad471d260e55a3f1
678,730
def spatial_scale_conv_1x1_stride_2(s, p): """ This method computes the spatial scale of 1x1 convolutional layer with stride 2 in terms of its input feature map's spatial scale value (s) and spatial overal value (p). """ return s
4822766d32e9054489952741623b7db2f4909a3a
678,731
def _root(): """Returns the root node.""" return 0
80bef5f6513704f7b9c4dc094c5fd81badcfe56a
678,733
def compose(*funcs): """ Composes a series of functions, like the Haskell . operator. Args: *funcs: An arbitrary number of functions to be composed. Returns: A function that accepts whatever parameters funcs[-1] does, feeds those to funcs[-1], feeds the result of that into funcs[-2...
9ae2b6f012879f7e8d237e3b6e03b3cc8b17d5b2
678,734
def match_barcode_rule(trello_db, barcode): """Finds a barcode rule matching the given barcode. Returns the rule if it exists, otherwise returns None.""" rules = trello_db.get_all('barcode_rules') for r in rules: if r['barcode'] == barcode: return r return None
00f7b9226fefb738a830da050820dfb219bc55fb
678,735
def multiplica(x, y, z=None): """Multiplica x, y, z Multiplica x, y e z. O programador pode omitir a variável z, caso não tenha necessidade de usá-la. """ if z: return x * y else: return x * y * z
35c553175729102502d9c18365f834cd320d0638
678,736
import time def get_timestamp(): """ Returns current time for data logging. """ time_now = time.time() mlsec = repr(time_now).split('.')[1][:3] time_now = time.strftime("%H:%M:%S.{}-%d/%m/%Y".format(mlsec)) return time_now
f7fc8a05da2ece5ffdf3cea6734a34d4734c6169
678,737
import os def _NormalizeObjectPath(path): """Normalizes object paths. Prefixes are removed: obj/, ../../ Archive names made more pathy: foo/bar.a(baz.o) -> foo/bar.a/baz.o """ if path.startswith('obj/'): # Convert obj/third_party/... -> third_party/... path = path[4:] elif path.startswith('../../...
075cff0b543c8510fe12e634367c69fb90a132b5
678,738
import subprocess def generate_wireguard_psk(): """ Generate a WireGuard private & public key Requires that the 'wg' command is available on PATH Returns """ return subprocess.check_output("wg genpsk", shell=True).decode("utf-8").strip()
770fe8a064406301ce28aa877cb0bfdcc11d9646
678,739
def kelvin_to_celsius(thermals, scale=10): """ Convert kelvin values to celsius L2 processing for the thermal band (known as Brightness Temperature) is initially done in kelvin and has been scaled by a factor of 10 already, in the interest of keeping the values in integer space, a further factor ...
b8cf9d453c7b8b75ac7381c83621f212c1cfb946
678,740
import numpy def endianness(): """ Return the native endianness of the system """ if numpy.little_endian: return "LITTLE_ENDIAN" else: return "BIG_ENDIAN"
d6c838de9c26f74840f6d6db183fdf6f93f8ccda
678,741
def JoinDisjointDicts(dict_a, dict_b): """Joins dictionaries with no conflicting keys. Enforces the constraint that the two key sets must be disjoint, and then merges the two dictionaries in a new dictionary that is returned to the caller. @type dict_a: dict @param dict_a: the first dictionary @type dic...
d42600de9646b8eda5f94cce5961754eb72daa2d
678,742
def diff_single(arr, val): """ Return difference between array and scalar. """ return [i - val for i in arr]
c53d774322c03b6d96b632ed692e77e4792505cc
678,743
import time def run_time_calc(func): """ Calculate the run time of a function. """ def wrapper(*args, **kwargs): start = time.time() ans = func(*args, **kwargs) end = time.time() print('\nRun time of function [%s] is %.2f.' % (func.__name__, ...
dc4e6faae61faf627b20f237762d6cd43af4dc33
678,744
from typing import List import os def get_python_prefix() -> str: """ get the python_prefix including the command prefix like : 'wine python' >>> if 'TRAVIS' in os.environ: ... discard = get_python_prefix() """ c_parts: List[str] = list() c_parts.append(os.getenv("cPREFIX", "")) c...
21435460651130ca0363bcfb83ef864b0a12c781
678,745
from typing import Union from typing import List def build_gcm_identifier( gcm: str, scenario: str, train_period_start: str, train_period_end: str, predict_period_start: str, predict_period_end: str, variables: Union[str, List[str]], **kwargs, ) -> str: """ Build the common ide...
e7f826adab7637bce323a57ecc2e17407db02a8b
678,746
def promotion(metadata, reduction_indices): """Apply dimensionality promotion to reduced indices. The inverse of reduction. Returns indices. """ indices = [None] * metadata['dimensionality'] for k in range(metadata['reduction_dimensionality']): reduction_shape = metadata['reduction_shap...
aeb913a48b7acabaf49772dafaf97e67174618eb
678,747
def make_file_dict(butler, runlist, varlist=None): """Get a set of data_ids of the Butler and sort them into a dictionary Parameters ---------- butler : `Bulter` The data Butler runlist : `list` List of complete dataIDs varlist : `list` List of variables values to use as...
4b3659aa1671568949d6328de06326f4fb3b8b10
678,748
def setplot(plotdata): """ Plot solution using VisClaw. """ plotdata.clearfigures() # clear any old figures,axes,items data # Figure for q[0] plotfigure = plotdata.new_plotfigure(name='q[0]', figno=0) # Set up for axes in this figure: plotaxes = plotfigure.new_plotaxes() plotaxes....
919530b4a6eb282687d78abd21a265cf82759176
678,749
import re def _apply_extractor(extractor, X, ch_names, return_as_df): """Utility function to apply features extractor to ndarray X. Parameters ---------- extractor : Instance of :class:`~sklearn.pipeline.FeatureUnion` or :class:`~sklearn.pipeline.Pipeline`. X : ndarray, shape (n_channels, n_...
60c9bf56beb0639f4e33e91c43b8dbe0ab5269ad
678,750
def place_folder_in_tree(master_tree, folder, tree): """Place the forder tree in a provided master tree under the folders parent or return False if the parent is not in the tree. """ if folder.parent in list(master_tree): # Parent is found place the tree where it belongs. master_tre...
ff317fe4339e2a85a14c49dd1695b3d6033407b7
678,751
def keep_indexed(f): """For each enumerated collection, we can use a function that takes its index and the item to determine whether to keep the result and if so what form to keep it in.""" def generator(coll): for idx, item in enumerate(coll): res = f(idx, item) if res i...
3e57e82884b6f3eca30f200f2fa4ce796c3dac74
678,752
def get_inputs(depthdata_str_list): """ Given a list of strings composed of 3 floating pt nbrs x, y, z separated by commas, convert them to floats and return them as 3 individual lists. :param depthdata_str_list: list of floating point string pairs, separated by a comma (think .csv file) :return: ...
397937ca85dbd2836582ef37ae193f9929b79ab0
678,755
from pathlib import Path import os import sys import json def load_app_data_content_map(): """Loads and returns App Data file from persistent storage""" file_path = Path(os.environ['APP_DATA_REFERRAL_RELATION_FILE']) if not file_path.is_file(): # Must wait for the app_data-referrals relationships ...
630d41df0054a7e4baae0850d601bbd2141367f6
678,756
import importlib def str_to_type(classpath): """ convert class path in str format to a type :param classpath: class path :return: type """ module_name, class_name = classpath.rsplit(".", 1) cls = getattr(importlib.import_module(module_name), class_name) return cls
9be7b756ee89b2dbfc475f35514567a73a34e12b
678,757
def _mergeheaders(headers, params): """Merges the headers from the CSV file with the found parameters into a dictionary.""" result = {} for i, header in enumerate(headers[:-1]): result[header] = params.item(i) return result
6310961915d70476d468991233db8f30d26bba44
678,759
def order_edges(edges_lst, ref_nodes): """Reorder edges such as reference node is on the first position.""" ret = [] for edge in edges_lst: f_, s_ = edge if f_ in ref_nodes: ref_node = f_ que_node = s_ else: ref_node = s_ que_node = f_ ...
054771ff9571b197e6dab4395ac11fd94f150254
678,760
def read_file(path: str): """ Read a file from the filesystem. """ with open(path, "r") as file: data = file.read() return data
96920ee426d09f03ea8c11e86276af60d28f4826
678,761
def get_latest_reading(client, name): """Returns the value and timestamp of the latest reading.""" query = client.query(kind=name) query.order = ["-timestamp"] results = list(query.fetch(limit=1)) if not results: return None, None result = results[0] if "value" not in result: ...
5e427d7a79dcbd3ec484401993a8ffd3c2ca31a0
678,762
def biground(value, base=5): """ >>> biground(7) 10 >>> biground(11.0) 15 """ return int(base * round(float(value) / base)) + base return f
8112a904ebc14c5e3a132ec6b8b59ea3eeaec402
678,763
def string_transformer(s: str) -> str: """ Given a string, return a new string that has transformed based on the input: 1. Change case of every character, ie. lower case to upper case, upper case to lower case. 2. Reverse the order of words from the input. Note: You will have to handle multiple spaces, and ...
509de3ade824f11b5074322c9d9cbd09ace8bdde
678,764
import glob def populate_extra_files(): """ Creates a list of non-python data files to include in package distribution """ out = ['cauldron/settings.json'] for entry in glob.iglob('cauldron/resources/examples/**/*', recursive=True): out.append(entry) for entry in glob.iglob('cauldro...
9b28f499f39ca37fdddb290af574a2bd0be47b22
678,765
import subprocess def gpomx_camera_connected(): """Return True if a camera compatible with gPhoto2 is found. """ return False # This camera is not yet implemented try: process = subprocess.Popen(['omxplayer', '--version'], stdout=subprocess.PIPE, stderr=sub...
78458ace66480257cfdca9796b88947f1e084404
678,766
from typing import List import os import json def filter_input_hashes( data_dir: str, i_process: int, n_processes: int, i_job: int, n_jobs: int ) -> List[str]: """Get list of filtered input hashes assigned to worker.""" info_json = os.path.join(data_dir, 'info.json') with open(info_json) as f: ...
104d70d1d8671c920e1802727d884f168defe574
678,767
def isSubDict(dict_super, dict_sub): """ Tests if the second dictonary is a subset of the first. :param dict dict_super: :param dict dict_sub: :return bool: """ for key in dict_sub.keys(): if not key in dict_super: return False if not dict_sub[key] == dict_super[key]: return False re...
a0dead33cddf9482c0281479ad632faebd2501da
678,768
import sympy from typing import Iterable def parameter_checker(parameters): """Checks if any items in an iterable are sympy objects.""" for item in parameters: if isinstance(item, sympy.Expr): return True # This checks all the nested items if item is an iterable if isinsta...
51a20985f6b65aae42470b950475ba21474bd702
678,769
import re def title_year(m_file): """ Regex searching returns the title and year from the filename Currently optimized for: "Title (year).extension" """ name = re.compile(r'([\w+\W?]+)\s\(([0-9]{4})\)[\s\w]*[\d\.\d]*[\s\w]*\.\w{2,4}') fsearch = name.search(m_file) if fsearch: tit...
96640d45fa82aba0de31a6063638dfcb129c1394
678,770
def read_data(label_f, link_f): """ :param label_f: doc_membership_file :param link_f: keyword_cnt, <doc_id>\t<word1>\t<count1>\t<word2>\t<count2> :return: cells: key: cell_id (int), value: doc_id_list freq_data: key: doc_id, value: a dict...
6dd5eea37da48596bff3d44cfd900aece72b5090
678,771
def match_percent(str1=str(),str2=str()): """ match_percent(first string, second string)\n Comares 2 strings and returns the percentage of matching letters.\n If the string lenghts are different, whitespace will be added at the end of the short string """ if len(str1)==0: str1=" " i...
0fc17bfe9888217bfff0566410357b5f18371f80
678,772
def offset_format(utc_offset): """Display + or - in front of UTC offset number""" return str(utc_offset) if utc_offset < 0 else f"+{str(utc_offset)}"
cf23d1d15c8a3ec852d4099724947b8d2658f4f6
678,773
import os def upload_request_images(content, subdir): """ Upload request image to folder """ request_dir = os.path.join("request", subdir) if not os.path.exists(request_dir): os.makedirs(request_dir) file_name = content.filename file_path = os.path.join(request_dir, file_name) content...
7cdff2e989acb1c3a76b288ad056fcbfc313e89a
678,774
def fnSeconds_To_Hours(time_period): """ Convert from seconds to hours, minutes and seconds. Date: 16 October 2016 originally in AstroFunctions.py """ num_hrs = int(time_period/(60.*60.)); time_period =time_period - num_hrs*60.*60.; num_mins = int(time_period/60.); num_secs = t...
fbf5f66c35fb123a1906e8231b12f690bd3a4c50
678,775
def odd_even(x): """ odd_even tells if a number is odd (return True) or even (return False) Parameters ---------- x: the integer number to test Returns ------- bool : boolean """ if not isinstance(x, int): raise TypeError(f'{x} should be an integer') if int(x) % 2 =...
0475754117d2d5a126c2806b0c9107a1c60afc4e
678,776
def sort(d): """sort dictionary by keys""" if isinstance(d, dict): return {k: d[k] for k in sorted(d)} return d
613317358ab76e149de64a4106614c32374af15e
678,777
import pickle def read_data(path, n_vaues=None): """ Given a path, read the file and return the contents. Arguments: path (string) : File path with .pkl extension n_values (int) : Number of containers expected to be read. """ f = open(path, "rb") d = pickle.load(...
091ede2a909f8b99d94f94a938ffb60a7f802f1d
678,778
def quick_sort_2(data): """Sort the array by using quicksort.""" less = [] equal = [] greater = [] if len(data) > 1: pivot = data[0] for x in data: if x < pivot: less.append(x) elif x == pivot: equal.append(x) elif...
f6bb05e582a0b288455e349747b5341d4284258b
678,779
from typing import Any def _get_variant_args(name: str) -> Any: """Return self-attention variant specific list of attn args.""" standard_args = [ 'num_heads', 'x', 'qkv_features', 'out_features', 'broadcast_dropout', 'dropout_rate', 'deterministic', 'kernel_init', 'bias_init', 'bias', 'dtype', ...
10c7e2d1936029cbdc3ef0716529d097f4a26030
678,780
from pathlib import Path import json def load_config(path_config, config_type='json'): """ 加载配置文件。 如果不是绝对路径,则必须是在config目录下。 必须是json文件,可以不指定后缀。 :param path_config: Path变量或者是字符串。 :param config_type: 配置文件类型,值为'json'时,返回字典;为'txt'时,返回字符串列表 :return: """ assert config_type in ('json', 'tx...
674c1df2633ec90f55eeac8b113cffce91dd2ad9
678,781
import time def catalog_creation_payload(): """ :return: dict representing the payload """ return { "Filename": "", "SourcePath": "", "Repository": { "Name": 'Test' + time.strftime(":%Y:%m:%d-%H:%M:%S"), "Description": "Factory test", "RepositoryType": "...
45c289ce6b6fe01b5ee7354bfbe574f8a6541b86
678,782
def _apply_linear_trend(data, elevs, trend, direction): """ Detrend or retrend a set of data points using a given trend value. Parameters ---------- data : ndarray Detrended values. elevs : ndarray Elevations corresponding to the data points. trend : float Trend va...
f9cf5e68de2cbda3a1dddc0ee8ca4a5ab7e9820f
678,783
def _score_phrases(phrase_list, word_scores): """Score a phrase by tallying individual word scores""" phrase_scores = {} for phrase in phrase_list: phrase_score = 0 # cumulative score of words for word in phrase: phrase_score += word_scores[word] phrase_scores[" ...
abc85143bde20dc3097f6408712bfc0bc53c50fe
678,784
def snake_to_camel(name, title_case=False): """将下划线命名改为驼峰命名 .""" items = name.split("_") first_item = items[0].title() if title_case else items[0] if len(items) == 1: return first_item other_items = [item.title() for item in items[1:]] camel_name = "{}{}".format(first_item, ''.join(other...
db0098eaff5aa4877d125b45af37688087e8625a
678,785
import argparse def get_arguments(): """Gets arguments from the command line. Returns: A parser with the input arguments. """ # Creates the ArgumentParser parser = argparse.ArgumentParser( usage='Reconstructs an RBM with linear combination of original and sampled weights.') ...
f85e7ef8cf4d0b5710e21e5a32c8b6e7acbcddac
678,786