content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def dataParser (path): """ This function parses all files in the directory specified by the path input variable. It is assumed that all said files are valid .wav files. """ waves = [] rates = [] digits = [] speakers = [] files = [f for f in listdir (path) if isfile (join (path, f...
921d7381f3daff233fb5e568b414c97d726b8c5d
3,631,732
def deserialize_function(serial, function_type): """Deserializes the Keras-serialized function. (De)serializing Python functions from/to bytecode is unsafe. Therefore we also use the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case...
eb76660c494bf43497dde32617583c17f6ba8ef3
3,631,733
from src.datasets import VOC2007 from src.datasets import VOC2012 import torch def _dataset( dataset_type: str, train_val_test: str = 'train' ) -> torch.utils.data.Dataset: """ Dataset: voc2007 voc2012 """ if dataset_type == "voc2007": if train_val_test == "val": t...
1c818013d04ec33e10df57b5f40c2c38351fd36b
3,631,734
def disaggregate_forecast(history, aggregated_history, aggregated_forecast, dt_units='D', period_agg=7, period_disagg=1, x_reg=None, x_fut...
e74f42335af23325d08f7ad9aa593b85b6917078
3,631,735
def get_path_cost(latency_dict, path): """ Cost of all links over a path combined :param latency_dict: :param path: :return: """ cost = 0 for i in range(len(path) - 1): cost += get_link_cost(latency_dict, path[i], path[i+1]) return cost
ed7be1c7a1a38fcc5ad0904a7a784e8bcf0f4941
3,631,736
def qderiv(array): # TAKE THE ABSOLUTE DERIVATIVE OF A NUMARRY OBJECT """Take the absolute derivate of an image in memory.""" #Create 2 empty arrays in memory of the same dimensions as 'array' tmpArray = np.zeros(array.shape,dtype=np.float64) outArray = np.zeros(array.shape, dtype=np.float64) # Ge...
ebe0242b829409a9844c1d36ac151cbddcf12391
3,631,738
def byte(number): """Return the given bytes as a human friendly KB, MB, GB, or TB string""" B = float(number) KB = float(1024) # 1024 b, 1 εƒε­—θŠ‚=1024 ε­—θŠ‚ MB = float(KB ** 2) # 1024 kb, 1 ε…†ε­—θŠ‚=1048576 ε­—θŠ‚ GB = float(KB ** 3) # 1024 mb, 1 εƒε…†ε­—θŠ‚(GB)=1073741824 ε­—θŠ‚(B) TB = float(KB ** 4) # 1024 gb ...
88c062d97645741025731e2f2cde2646be2891f9
3,631,739
def compute_optimal_warping_path_subsequence_dtw(D, m=-1): """Given an accumulated cost matrix, compute the warping path for subsequence dynamic time warping with step sizes {(1, 0), (0, 1), (1, 1)} Notebook: C7/C7S2_SubsequenceDTW.ipynb Args: D (np.ndarray): Accumulated cost matrix m ...
ba1b86ef7bfd8c5d322b27d5a9c0f264a97351ef
3,631,740
from typing import Dict from typing import Any from typing import Union def _start_tracker(n_workers: int) -> Dict[str, Any]: """Start Rabit tracker """ env: Dict[str, Union[int, str]] = {'DMLC_NUM_WORKER': n_workers} host = get_host_ip('auto') rabit_context = RabitTracker(hostIP=host, n_workers=n_wor...
a8be8ca89fd6ba9383f9b029ac936579b1f164d5
3,631,741
def get_type_path(type, type_hierarchy): """Gets the type's path in the hierarchy (excluding the root type, like owl:Thing). The path for each type is computed only once then cached in type_hierarchy, to save computation. """ if 'path' not in type_hierarchy[type]: type_path = [] ...
29344b63197f4ea6650d059767100401c693990a
3,631,742
def get_required_webots_version(): """Return the Webots version compatible with this version of the package.""" return 'R2020b revision 1'
89e6e458c2409670d70a833996c76f05e77bd7b1
3,631,743
def ScoreStatistics(scores, percentile): """ Capture statistics related to the gencall score distribution Args: scores (list(float)): A list of gencall scores percentile (int): percentile to calculate gc_10 : 10th percentile of Gencall score distribution gc_50 : 50th...
35c3b98681a53cec82908e5634b1c49439b5b044
3,631,744
def download_drill(load=True): # pragma: no cover """Download scan of a power drill. Originally obtained from Laser Design. Parameters ---------- load : bool, optional Load the dataset after downloading it when ``True``. Set this to ``False`` and only the filename will be returne...
c40635c718afd404f5df55004a32cb5108d8b370
3,631,745
def schlieren_colormap(color=[0, 0, 0]): """ Creates and returns a colormap suitable for schlieren plots. """ if color == 'k': color = [0, 0, 0] if color == 'r': color = [1, 0, 0] if color == 'b': color = [0, 0, 1] if color == 'g': color = [0, 0.5, 0] if c...
7becf570f5af8368d2f169fe9c222d72d22f04d7
3,631,746
def evaluate_binned_cut(values, bin_values, cut_table, op): """ Evaluate a binned cut as defined in cut_table on given events Parameters ---------- values: ``~numpy.ndarray`` or ``~astropy.units.Quantity`` The values on which the cut should be evaluated bin_values: ``~numpy.ndarray`` or...
541a1bf7196e41d2db2bdf4ab272a9cfa760591b
3,631,747
import tempfile def add_EVM(final_update, wd, consensus_mapped_gff3): """ """ db_evm = gffutils.create_db(final_update, ':memory:', merge_strategy='create_unique', keep_order=True) ids_evm = [gene.attributes["ID"][0] for gene in db_evm.features_of_type("mRNA")] db_gmap = gffutils.create_db(cons...
c36945fe984d82245247271210683d81880a757a
3,631,748
def function_linenumber(function_index=1, function_name=None, width=5): """ :param width: :param function_index: int of how many frames back the program should look (2 will give the parent of the caller) :param function_name: str of what function to look for (should not be used with function_index ...
ba046f1106eacb998a6728a6878bb48822920270
3,631,751
def init_base_item(mocker): """Initialize a dummy BaseItem for testing.""" mocker.patch.multiple( houdini_package_runner.items.base.BaseItem, __abstractmethods__=set(), __init__=lambda x, y: None, ) def _create(): return houdini_package_runner.items.base.BaseItem(None) ...
d7d4c0951e4013583f8ea89574da9735daa9aa21
3,631,753
def create_sftp_client2(host, port, username, password, keyfilepath, keyfiletype): """ create_sftp_client(host, port, username, password, keyfilepath, keyfiletype) -> SFTPClient Creates a SFTP client connected to the supplied host on the supplied port authenticating as the user with supplied username ...
c489850945ffc9387781f23f6d58b3c675de8928
3,631,754
def get_vectorize_layer(max_features=10000, sequence_length=250) \ -> tf.keras.layers.experimental.preprocessing.TextVectorization: """Transforms a batch of strings into either a list of token indices or a dense representation. Parameters ---------- max_features : int The maximum size o...
bfd677757a8347f521c53445a2f4bddd2fd57d06
3,631,755
def test_login_success(self): """ In this case both are false, meaning the if statements doesn't get executed """ return login_user(test_user.email, test_user.password) == test_user
53c1599b9a2c442e0be093e90522d08a905f0503
3,631,756
async def tally(): """ Get the results of all election tallies. Returns: Tally results for each contest in the election """ tally = election.get_election_tally() results = { "contests": [ { "contest": contest, "selections": [ ...
144de5592804fd5e6f950385b2789ba1a7c3e195
3,631,757
def expand_parameters_from_remanence_array(magnet_parameters, params, prefix): """ Return a new parameters dict with the magnet parameters in the form '<prefix>_<magnet>_<segment>', with the values from 'magnet_parameters' and other parameters from 'params'. The length of the array 'magnet_paramete...
e087f5b1e8ea264f074f921a5283d7806178664b
3,631,758
import math def addToOrStartNewRange(oldRange, tissueRangeScores, newPosition, vals, tissues, tissueFhs): """For all the tissues in vals, figure out if we are still in the same exon and adding to the previous range/score combo, or if we are in the same exon but with a different score, or a...
addbe75f611995c05dd6aa1998f0d66b1f038798
3,631,759
def transformNode(doc, newTag, node=None, **attrDict): """Transform a DOM node into new node and copy selected attributes. Creates a new DOM node with tag name 'newTag' for document 'doc' and copies selected attributes from an existing 'node' as provided in 'attrDict'. The source 'node' can be None. At...
2329858a02c643077f67d5c705fb3df72c2a96ee
3,631,760
def jsonify(status=200, indent=2, sort_keys=True, **kwargs): """ Creates a jsonified response. Necessary because the default flask.jsonify doesn't correctly handle sets, dates, or iterators Args: status (int): The status code (default: 200). indent (int): Number of spaces to indent (default...
d32eb4418d49802872bbf96fafa29a4704374b1b
3,631,761
import datasets def browse(dataset_id=None, endpoint_id=None, endpoint_path=None): """ - Get list of files for the selected dataset or endpoint ID/path - Return a list of files to a browse view The target template (browse.jinja2) expects an `endpoint_uri` (if available for the endpoint), `target`...
ca88068558e9e32e52ac032c891f28579a9d03b0
3,631,763
def tag_group(tag_group, tag): """Select a tag group and a tag.""" payload = {"group": tag_group, "tag": tag} return payload
f22ccd817145282729876b0234c8309c24450140
3,631,764
from typing import Iterable def rollup(step: Step, store: TableStore): """Rollup a table to produce an aggregation summary. :param step: Parameters to execute the operation. See :py:class:`~data_wrangling_components.engine.verbs.rollup.RollupArgs`. :type step: Step :param store: ...
ee8302a4605fd5ad850b3c1d466276259a12736e
3,631,765
from optimade.server.config import CONFIG def prefix_provider(string: str) -> str: """Prefix string with `_{provider}_`""" if string in CONFIG.provider_fields.get("structures", []): return f"_{CONFIG.provider.prefix}_{string}" return string
6faa8af6d24e4f5ae17a7997b097545415ce53b8
3,631,766
def combine_sequences(vsequences, jsequences): """ Do a pairwise combination of the v and j sequences to get putative germline sequences for the species. """ combined_sequences = {} for v in vsequences: vspecies, vallele = v for j in jsequences: _, jallele= j ...
dac2aea73bd078bcf96dc8e7b44c5dcdeade2759
3,631,767
def read_seq_file(filename): """Reads data from sequence alignment test file. Args: filename (str): The file containing the edge list. Returns: str: The first sequence of characters. str: The second sequence of characters. int: The cost per gap in a sequence. ...
9160bb0b2643deae669818cea1bc1ebeb51506b8
3,631,768
import scipy import numpy def OrthogonalInit(rng, sizeX, sizeY, sparsity=-1, scale=1): """ Orthogonal Initialization """ sizeX = int(sizeX) sizeY = int(sizeY) assert sizeX == sizeY, 'for orthogonal init, sizeX == sizeY' if sparsity < 0: sparsity = sizeY else: sparsit...
98b53e11d6c3a641d6e8fede0d28651c48aa5407
3,631,769
def build_complement(dna): """ :param dna: str, the DNA strand that user gives(all letters are upper case) :return: str, the complement of dna """ new_dna = '' for base in dna: if base == 'A': new_dna += 'T' elif base == 'T': new_dna += 'A' elif ba...
dffdf6345ec25ea80e89996aef7c85a41f38d6f4
3,631,770
def _seasonal_prediction_with_confidence(arima_res, start, end, exog, alpha, **kwargs): """Compute the prediction for a SARIMAX and get a conf interval Unfortunately, SARIMAX does not really provide a nice way to get the confidence intervals out of the box, so we ha...
9520bf1a60eeb39c25e9a369b0b337905df9afb8
3,631,771
def attack(X_train, y_train, X_test, y_test, unmon_label, args, VERBOSE=1): """ Perform WF training and testing """ classes = len(set(list(y_train))) print(classes) # shuffle and split for val s = np.arange(X_test.shape[0]) np.random.shuffle(s) sp = X_test.shape[0]//2 X_va = X_t...
57c33e5e26f04412650bf65a5032cb81fb7d46bf
3,631,772
from typing import Counter def create_lexicon(pos, neg): """Create Lexicon.""" lexicon = [] for fi in [pos, neg]: with open(fi, 'r') as f: contents = f.readlines() for l in contents[:hm_lines]: all_words = word_tokenize(l.lower()) lexicon += ...
f1f81310d0e12e6aa23589c98e0fcb1eb3283dc1
3,631,773
def trailing_zeros(x): """ Number of trailing zeros in a number.""" if x % 1 != 0 | x == 0: return 0 magn = floor(log10(x)) trailing = 0 for i in range(1, magn + 1): if x % (10 ** i) == 0: trailing = i else: break return trailing
d712afc601866eafc8ea1d6fac8e33c50e053b64
3,631,774
def top_height(sz): """Returns the height of the top part of size `sz' AS-Waksman network.""" return sz // 2
1e4a43a8935cc5c3ccf104e93f87919205baf4a4
3,631,776
def constructAuxGraph(path): """ This function constructs the auxiliary graph given a python dictionary as argument wich consists of the # of the path as the key of the dictionary and the path (source, intermediate nodes, destination) that a predifined route has to traverse in order to go from the sou...
04441f20a9d55e6dcf88c64f9c54efa320dc8ee1
3,631,778
from typing import Callable import logging import time def eval_time(function: Callable): """decorator to log the duration of the decorated method""" def timed(*args, **kwargs): log = logging.getLogger(__name__) time_start = time.time() result = function(*args, **kwargs) time_...
3f40394c5638bf0fc6371d4247c8980da1f6363f
3,631,779
from typing import Union from typing import Optional from typing import Iterable from typing import Tuple def parse_data( data: Union[AnnData, DataFrame, np.ndarray], gene_names: Optional[Iterable[str]] = None, sample_names: Optional[Iterable[str]] = None ) -> Tuple[np.ndarray, list, list]: """Reduces...
03fdf88e3160d41f976d6ebdb336588958a16a91
3,631,780
def german_actionset_unaligned(german_X): """Generate an actionset for German data.""" # setup actionset action_set = ActionSet(X = german_X) immutable_attributes = ['Age', 'Single', 'JobClassIsSkilled', 'ForeignWorker', 'OwnsHouse', 'RentsHouse'] action_set[immutable_attributes].mutable = False ...
5166d4d07d127cc6fa0166a719edca0c78a34150
3,631,781
def test_mode(user, godmode=False, questions_list=None, quiz_id=None): """creates a trial question paper for the moderators""" if questions_list is not None: trial_course = Course.objects.create_trial_course(user) trial_quiz = Quiz.objects.create_trial_quiz(trial_course, user) trial_que...
600a4391ffd016387f2210db62a3fe9e452cf55a
3,631,784
from typing import Optional def add_auth_token(auth_token: str, desc: Optional[str], call_count_limit: Optional[int] = None, call_count_limit_relative: bool = False) -> bool: """ Add or update an auth token to the DB. Local cache will be updated during next API request in...
243ea14badc4dd3f54f2f5147c38f81bf64be83f
3,631,785
import re def id_for_new_id_style(old_id, is_metabolite=False): """ Get the new style id""" new_id = old_id def _join_parts(the_id, the_compartment): if the_compartment: the_id = the_id + '_' + the_compartment return the_id def _remove_d_underscore(s): """Removed ...
34c21ddfe20eb3e173c176763f6323d5cd4f3d3b
3,631,786
def analysis_instance_start_success(instance_uuid, instance_name, records, action=False, guest_hb=False): """ Analyze records and determine if instance is started """ always = True possible_records \ = [(action, NFV_VIM.INSTANCE_NFVI_ACTION_START), ...
effb9e52a48067160b6a468af6a35cc4a380070c
3,631,787
import scipy from typing import OrderedDict def evaluate_on_semeval_2012_2(w): """ Simple method to score embedding using SimpleAnalogySolver Parameters ---------- w : Embedding or dict Embedding or dict instance. Returns ------- result: pandas.DataFrame Results with spea...
5b6e6cee3a62af1aa5320ae7a549357194a2a334
3,631,788
def valid_lsi(addr): """Is the string a valid Local Scope Identifier? >>> valid_lsi('1.0.0.1') True >>> valid_lsi('127.0.0.1') False >>> valid_lsi('1.0.1') False >>> valid_lsi('1.0.0.365') False >>> valid_lsi('1.foobar') False """ parts = addr.split('.') if not ...
8a90547f239ea6d2a5aa971115c2015edc42932b
3,631,790
def imshow_coocc(coocc, percent=True, ax=None): """visualize profile class co-occurrence matrix""" ax = ax or plt.gca() size = coocc.shape[0] annot = (coocc*100).round().astype(int).values if percent else coocc.values ax.imshow(coocc.T) for x in range(size): for y in range(size): ...
45f259dd2702714793be2dddccc1fdc8d77de55e
3,631,791
def sub_m(D, C_lasso, C_group, C_ridge, eta=1e0): """Solve the Sub_m subproblem.""" return shrink(D, C_lasso * eta, C_group * eta, C_ridge * eta)
7ed14e2f455e1af3645fdc4557ee5b7b4668a7b0
3,631,792
def grade(morse_code, inputs): """Grades how well the `inputs` represents the expected `morse_code`. Returns a tuple with three elements. The first is a Boolean telling if we consider the input good enough (this is the pass/fail evaluation). The next two elements are strings to be show, respectively, in...
43038fa81ff9a5d39d337b38b5afed1c3ca57e4d
3,631,793
def create_test_endpoint(client, ec2_client, name=None, tags=None): """Create an endpoint that can be used for testing purposes. Can't be used for unit tests that need to know/test the arguments. """ if not tags: tags = [] random_num = get_random_hex(10) subnet_ids = create_subnets(ec2_...
8c266beec2d49d5139e08b42aad0df9a9e8bd400
3,631,794
def plot_clusters(estimator, X, chart=None, fig=None, axes=None, n_rows=None, n_cols=None, sample_labels=None, cluster_colors=None, cluster_labels=None, center_colors=None, center_labels=None, center_width=3, col...
59fa26e28233815335e5377c4523e35c9b21e22e
3,631,795
import requests def head(url): """ Make a HEAD request to the URL. If we do not get a 404 then the URL is valid. If there are any exceptions then return False. """ try: resp = s.head(url, timeout=5, verify=False) except requests.exceptions.RequestException: return False ...
e602cc7ad498cacbe7defc955464b701c316d8db
3,631,796
import pathlib def long_description(): """Reads the README file""" with open(pathlib.Path(WORKING_DIRECTORY, "README.rst")) as stream: return stream.read()
1573b8c5dba81e1f7e345b77a49085d0066c4dca
3,631,797
import csv import io def load_embeddings(embeddings_path, aws=False): """Loads pre-trained word embeddings from tsv file. Args: embeddings_path - path to the embeddings file. Returns: embeddings - dict mapping words to vectors; dim - dimension of the vectors. """ if aws: embeddings = {} ...
c2879b05f9110f64aacbc8253e1d095e05c16ee7
3,631,798
from typing import Dict from typing import Any import json import requests async def create_check_request( installation_url: str, repo_name: str, token: str, check_name: str, head_sha: str ) -> Dict[str, Any]: """ Initiate Check after Pull Request was created. It contains terminal hash from PR, name, ...
5afa8efeb6a438520f75cbb0fa486c34102f94b5
3,631,799
def get_public_key() -> bytes: """ Retrieve the raw public key. :return: Bytes of key """ key = Ed25519PrivateKey.from_private_bytes(config.WEBHOOK_KEY) return key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
2cdad670643c215405bd0b988031f7485f0f9c5b
3,631,800
def create_empty_array(n_k, n_vals_i, n_feats): """Create null measure in the array form. Parameters ---------- n_k: int the number of perturbations n_vals_i: int the number of indices of the output measure. n_feats: int the number of features. Returns ------- ...
58ae0dc05bd0c256c8cad41e8f43cf3f87a11d1d
3,631,801
def transform_bbox(x): """ Function purpose: Transform bounding box (str) into geometry x: bounding box (str) """ try: ring = ogr.Geometry(ogr.wkbLinearRing) ring.AddPoint(x[0], x[1]) ring.AddPoint(x[2], x[1]) ring.AddPoint(x[2], x[3]) ring.AddPoint(x[0], x[3...
a8946a9f54307e82e3a9e82294371695f3d5eb86
3,631,802
from ressources.interactions import getIntKey def addUser(username: str, autoGenerateKeys: bool = True, keys: list = []): """ Create an user with the corresponding username to the users list and return the corresponding user id which can be used as index username: name of the user autoGenerateKeys: g...
ea01b6480a6953f9f4132e5245d98be29c8e77cd
3,631,803
import json def remove_conf(module): """ Remove specified module from db Module is identified by its name in lowercase """ # Get the original document res = db.delete("configuration", 'name', str(module).lower()) if res == None: raise ConfError("Module '%s' wasn't deleted" % mo...
1c7b4d70dabe05d1a9ac8d253b89e1c2bff6c9eb
3,631,805
import re def video(package): """method for download video """ params = package.get('params') video_id = params.get(ParamType.VideoID) request = package.get('request') range_header = request.META.get('HTTP_RANGE', '').strip() range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I) ...
6bf9fff7b49e5a22da945a4ff87784b408ab6086
3,631,806
import sqlite3 def task_items(max_entries=None): """Information about the items in the task queue. Returns a generator of QueueItems. Keyword arguments: max_entries - (int) (Default: None) Maximum number of items to return. Default is to return all entries. """ con = sqlite3.connect(s...
9bbe72d6fadc134b0654a8e2736ff66e6aa718ec
3,631,807
from typing import Tuple from typing import Optional def _remove_anchors_in_pattern(pattern: str) -> Tuple[Optional[str], Optional[str]]: """ We need to remove the anchors (``^``, ``$``) since schemas are always anchored. This is necessary since otherwise the schema validation fails. See: https://sta...
9ff66372943df6b4e0c0243c18a82d1ea5c49008
3,631,808
def bfs(connections, start, goal=None): """ Requires a connections dict with tuples with neighbors per node. Or a connections function returning neighbors per node Returns if goal == None: return dict of locations with neighbor closest to start elif goal found: returns path to goal el...
c93e619def9ca183ab5224bee50b021531d85f4a
3,631,809
def reverse_complement(dna): """ Reverse-complement a DNA sequence :param dna: string, DNA sequence :type dna: str :return: reverse-complement of a DNA sequence """ complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} return ''.join([complement[base] for base in dna[::-1]])
efcb38e06fc494adabeb304934ebef9bd932a11f
3,631,810
import pyarrow def df_to_bytes(df: pd.DataFrame) -> bytes: """Write dataframe to bytes. Use pyarrow parquet if available, otherwise csv. """ if pyarrow is None: return df_to_bytes_csv(df) return df_to_bytes_parquet(df)
145eb7204ae77f5fd457eeb82c54e2e8b2f65b27
3,631,811
import tqdm def select_training_voxels(input_masks, threshold=0.1, datatype=np.float32, t1=0): """ Select voxels for training based on a intensity threshold Inputs: - input_masks: list containing all subject image paths for a single modality - threshold: minimum threshold to apply (after ...
f5868ce28f51abb4e8f84539b5bfffa028d2a184
3,631,812
import itertools def find_intersections(formula_lists,group_labels,exclusive = True): """ Docstring for function pyKrev.find_intersections ==================== This function compares n lists of molecular formula and outputs a dictionary containing the intersections between each list. Use ---- f...
ae023b053dc98f34b99ab1aa70161eb306a197f6
3,631,813
import starlink.Ast as Ast import starlink.Atl as Atl def wcs_align(hdu_in, header, outname=None, clobber=False): """ This function is used to align one FITS image to a specified header. It takes the following arguments: :param hdu_in: the HDU to reproject (must have header and data) :param header: t...
41a0da7943845bbd63f5634d65b45804f1caaf7c
3,631,814
from typing import Dict def merge_flag_dictionaries(a: Dict[str, str], b: Dict[str, str]) -> Dict[str, str]: """ >>> a = {'CFLAGS': '-1'} >>> b = {'CFLAGS': ' -2'} >>> merge_flag_dictionaries(a, b) {'CFLAGS': '-1 -2'} """ a_copy = deepcopy(a) b_copy = deepcopy(b) ...
3d83f5083cfdb1a280c54fb42bd5bf0c89304b5f
3,631,816
def _delete_magic(line): """Returns an empty line if it starts with the # [magic] prefix """ return '' if line.startswith(_PREFIX) else line
9e14cb7cac1f3c991cfad01bde7e0c2bf1a24a72
3,631,817
import odbc import pyodbc import psycopg2 import pgdb def init_db_conn(connect_string, username, passwd, show_connection_info, show_version_info=True): """initializes db connections, can work with PyGres or psycopg2""" global _CONN try: dbinfo = connect_string if show_connection_info: print(dbinfo) if USE...
02487f08519d25203e9eabd3a504795114bc020a
3,631,818
import re def untokenize(words): """ Source: https://github.com/commonsense/metanl/blob/master/metanl/token_utils.py Untokenizing a text undoes the tokenizing operation, restoring punctuation and spaces to the places that people expect them to be. Ideally, `untokenize(tokenize(text))` should be id...
e62720d5a5fc7048e73659d013cb92e274671533
3,631,819
def create_new_course(request_ctx, account_id, course_name=None, course_course_code=None, course_start_at=None, course_end_at=None, course_license=None, course_is_public=None, course_is_public_to_auth_users=None, course_public_syllabus=None, course_public_description=None, course_allow_student_wiki_edits=None, course_a...
fa5aea3872506356a60776093bca4faefe1caea0
3,631,820
from copy import deepcopy def addReference(inData, reference): """ """ data = deepcopy(inData) existing_refs = [x for x in data['relatedIdentifiers'] if x['relationType']=='References'] ref_list = [ x['relatedIdentifier'] for x in existing_refs] if ( reference not in ref_list): prin...
85dd0c18966b632a2173c27e913bfe94a4d5ec29
3,631,821
def len_path_in_limit(p, n=128): """if path len in limit, return True""" return len(p) < n
988858918109902e662144a6650a33e593ba90b7
3,631,822
import torch def threshold(tensor, density): """ Computes a magnitude-based threshold for given tensor. :param tensor: PyTorch tensor :type tensor: `torch.Tensor` :param density: Desired ratio of nonzeros to total elements :type density: `float` :return: Magnitude threshold :rtype: `f...
d0c5a2726a2df195b0588af8af95dac187f50e1b
3,631,823
def _nt_quote_args(args): """Quote command-line arguments for DOS/Windows conventions. Just wraps every argument which contains blanks in double quotes, and returns a new argument list. """ # XXX this doesn't seem very robust to me -- but if the Windows guys # say it'll work, I guess I'll have ...
a4281afcbc572f02e719f97f92ec30bdf4ddb138
3,631,824
def algorithm_free_one_only_over_isls( output_dynamic_state_dir, time_since_epoch_ns, satellites, ground_stations, sat_net_graph_only_satellites_with_isls, ground_station_satellites_in_range, num_isls_per_sat, sat_neighbor_to_if, list_gsl_interface...
ca540acb71218579c63f9d19b8f3597fb376488f
3,631,825
def combine_fo_m(m, moved_f): """ derate 1 -> available 0 -> not available rules for combing after moving fo r -> min(m,fo) """ df = pd.DataFrame({"m": m, "newf": moved_f}) return df.apply(min, axis=1)
7e966becd686fca955ac77e13b685f85bc3d4e86
3,631,826
import random import copy def modify_drone(solution, simulation): """Modifies the drone of a random operation. ... Parameters: solution(List[Transportation]): The list of the transportations of the solution simulation(Simulation): The simulation Returns: List[Transportation]:...
69debcb5a42e52248b6b8e18c62642f8290126f6
3,631,827
def keygen(): """ Generates random RSA keys """ a = gen_prime() b = gen_prime() if a == b: keygen() c = a * b m = (a - 1) * (b - 1) e = coPrime(m) d = mod_inverse(e, m) return (e, d, c)
e5bb7d6b8c7c52f6328dc3ce1955b513f49d45a4
3,631,828
def _succ(p, l): """ retrieve the successor of p in list l """ pos = l.index(p) if pos + 1 >= len(l): return l[0] else: return l[pos + 1]
0eea63bd24da4079b9718af437c6d7e38ef25444
3,631,829
def generate_diff_mos(laygen, objectname_pfix, placement_grid, routing_grid_m1m2, devname_mos_boundary, devname_mos_body, devname_mos_dmy, m=1, m_dmy=0, origin=np.array([0,0])): """generate an analog differential mos structure with dummmies """ pg = placement_grid rg12 = routing_grid_m...
d851371ea4c513a4a77661ffb177ef3d41d39189
3,631,830
def fetch_rrlyrae_templates(**kwargs): """Access the RR Lyrae template data (table 1 of Sesar 2010) These return approximately 23 ugriz RR Lyrae templates, with normalized phase and amplitude. Parameters ---------- Returns ------- templates: :class:`RRLyraeTemplates` object co...
90b965be26a18481fa60bf1b49a956d90fc559ba
3,631,831
def BVHTreeAndVerticesInWorldFromObj(obj): """ Input: Object of Blender type Object Output: BVH Tree necessary for ray tracing and vertsInWorld = verts in global coordinate system. """ mWorld = obj.matrix_world vertsInWorld = [mWorld @ v.co for v in obj.data.vertices] bvh = BVHTree.FromPoly...
81154ee936785c14a1228c705190114a9a84fecf
3,631,832
def _readline(ser): """Read a line from device on 'ser'. ser open serial port Returns all characters up to, but not including, a newline character. """ line = bytearray() # collect data in a byte array while True: c = ser.read(1) if c: if c == b'\n': ...
469c5b6afa786d8bf94dec72a918b6df3b3ba4d7
3,631,833
def getPermCityState(permRecord): """Returns a string with the 'location' of the perm. It is generated from the starting city and starting state. This important conversion is used in many places and thus warrants its own commonized utility method. Input: a CSVRecord/permanent object. Output: a ...
6d7bc3f6f10fc7f04a22318292a94aad3fa64cae
3,631,835
def elem_to_Z(sym: str) -> int: """ Converts element symbol to atomic number. Parameters ---------- sym : str Element string. Returns ------- int Atomic number. Examples -------- >>> rd.utils.elem_to_Z('H') 1 >>> rd.utils.elem_to_Z('Br') 35 ...
8539658768e25dece01583031e161927c766adc8
3,631,838
def fn_I_axion_p(omega,xi_11,zeta_11,h_11,c_11,P_nuc,l,v,a,b,beta_11,k2,L_squid, R_squid, L_i, k_i, C_1, L_1, L_2, k_f, N_series,N_parallel): """Total axion-induced current through primary circuit, as a function of: -- angular frequency omega -- piezoaxionic tensor component xi_11 -- electroaxionic tens...
8eb0cd4c5e221e425551604677151865bca7f70a
3,631,839
def _C(startmat,endmat): """Calculate right Cauchy-Green deformation tensor to go from start to end :startmat: ndarray :endmat: ndarray :returns: ndarray """ F=_F(startmat,endmat) C=np.dot(F.T,F) return C
2f83b7423ecd0611b6f6baf8e015fd8da28ea5e7
3,631,840
import re def valid_uuid(uuid): """ Check if the given string is a valid uuid """ regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) match = regex.match(uuid) return bool(match)
0fd773851b8aa9ef65fda4a0c9ac0b24fdda8588
3,631,841
def get_products_stats_data(domains, datespan, interval, datefield='created_at'): """ Number of products by created time """ # groups products by the interval and returns the time interval and count ret = (SQLProduct.objects .filter(domain__in=domains, ...
5be8a75bb9157fc1ac000a9c91caa2fd6584133a
3,631,842
def task_schemas_json_orchestrator(): """Schemas - generate hat-orchestrator JSON schema repository data""" return _get_task_json( [schemas_json_dir / 'orchestrator.yaml'], [src_py_dir / 'hat/orchestrator/json_schema_repo.json'])
4c988e9efa0a077e64da685b27c3c1281cf9ddf0
3,631,843
def stopStreaming(): """ Stop streaming. Will return an `error` if streaming is not active. """ return __createJSON("StopStreaming", {})
abc164be9756a186d12bc90ebf56eedc9c04aff3
3,631,844
from bs4 import BeautifulSoup from typing import Callable from typing import Union from typing import Dict from typing import List def process_doc( doc: BeautifulSoup, proc: Callable = None, log: bool = True ) -> Union[None, Dict[str, Union[str, List]]]: """ Process soup to extract text in sections recurs...
fb97a6eb1a63bb9ef4cbff6d0abfceca886fbb73
3,631,845
def gain_corr_double_ExpDecayFunc(t, tau_A, tau_B, amp_A, amp_B, gc): """ Specific form of an exponential decay used for flux corrections. Includes a "gain correction" parameter that is ignored when correcting the distortions. """ y = gc * (1 + amp_A * np.exp(-t / tau_A) + amp_B * np.exp(-t / ta...
998af4a236b0d11893319e59401bada9e70f9957
3,631,846