content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_valid_time_levels(): """Checks files defined in Common and decides what time levels to return """ if isinstance(loaders.get_parameter("DaySlices"), pd.DataFrame): levels = [s.upper() for s in constant.TIME_SLICES] elif isinstance(loaders.get_parameter("DayTypes"), pd.DataFrame): ...
1c407857f6787918240859e5dd44cf755bbafc9e
3,606,520
import random def move_network_to_new_agent(network_id, old_agent_id, agents): """Move network from one DHCP agent to another one If adding to new agent will success then network will be also removed from old agent. :param network_id: id of network to move :param old_agent_id: id of existing age...
8ec3051627f361412439a32735483f7f4a815c5b
3,606,521
import calendar def download_month(variable, yyyy, mm): """ Function to attempt to retrieve data for a specific month. Args: variable: string of variable name used by API (e.g. 'rainfall') yyyy: string containing year (e.g. '2017') mm: string containing month (e.g. '05') Outp...
5f33a6c7be67a7f1cf0cb8d74e551284681f3e98
3,606,522
def is_dir_tracked(path, p4=None): """ Return True if the given directory is currently tracked in perforce """ if p4 is None: p4 = get_p4_from_path(path) try: info = p4.run_dirs(path) except P4.P4Exception: return False else: if len(p4.errors): return Fals...
038966012700f24df6d901f0edb70ed27860e103
3,606,523
import re def getStructuralDistance( target_structure, Cseq, path, RNAfold, verbose, LP, BP, RNAfold_pattern, IUPAC_compatibles, degreeOfSequenceInducement, pseudoknots, strategy, ): """ Calculator for Structural Distance """ # fold the current solution'...
028e4707468aba3fa961a26b8dc0ac570e1718aa
3,606,524
def compose(first: VIDEOGRAIN.ConversionFunc, intermediate: CogFrameFormat, second: VIDEOGRAIN.ConversionFunc) -> VIDEOGRAIN.ConversionFunc: """Compose two conversion functions together""" def _inner(grain_in: VIDEOGRAIN, grain_out: VIDEOGRAIN): grain_intermediate = grain_in._sim...
fcc80a078510b30157795e6851701eab5efc4b3c
3,606,525
import ast def ast_argspec(node): """ Get the argspec equivalent from ast.Call and ast.FunctionDef. Both: def func(arg1, arg2, *args, **kwargs): pass func(arg1, arg2, *args, **kwargs) will return the same argspec. Note: The defaults will ast.Node since we don't know the values...
1eab3568a848a221136bd9995f9be1db2bb743e1
3,606,526
def _ToCamelCase(name): """Converts hyphen-case name to CamelCase.""" parts = name.split('-') return ''.join(x.title() for x in parts)
c164572c386e16c9fdf193eac24f350ee8218cfc
3,606,527
def tree_intersection(tree_one,tree_two): """[given two binarytrees as parameters returns the itersection of the trees values] Args: tree_one ([binarytree]): [description] tree_two ([binarytree]): [description] Returns: [list]: [intersection of trees] """ intersection = [] ...
b2277a8121ce24446ef6ff1957d46c0e0853e79e
3,606,528
def generate_tech_options(): """ Generate technology strategy options. """ output = [] scenarios = ['low_20_20_20', 'baseline_20_20_20', 'high_20_20_20', 'low_10_10_10', 'baseline_10_10_10', 'high_10_10_10', 'low_5_5_5', 'baseline_5_5_5', 'high_5_5_5', ...
ab0ae37c6c9ddbdbcf8126f7f37bd4c54804d1cb
3,606,529
def has_strange(pdgid: PDGID_TYPE) -> bool: """Does this particle contain a strange quark?""" return _has_quark_q(pdgid, 3)
4d279588819d769fc4f5a672c2f92bdf6ecb8480
3,606,530
import json import io def boxes(): """ Draws bounding boxes around detected objects. See the Swagger UI for an example request. :return: The image with bounding boxes otherwise json with error message """ if request.content_length > 4194304: return Response(json.dumps({'error': 'Exceed...
b8073f50d6d9e49b6afc7434337ed15bfa4a6925
3,606,531
def name_records_summary(self): """ Count records for every name record. Args: mod_name (str): Return: None """ counts = {} for mod, records in self.records.items(): for rec in records: if rec['id'] not in counts: counts[rec['id']] = {...
4c23d37bb8aac839afcb2a2cb724d352db8e5d8c
3,606,532
def getVectorMultipolygon(polygonfile): """ Read the given vector file and return a ogr.Geometry object of a single multipolygon of the whole layer, projected into lat/long (EPSG:4326). """ ds = ogr.Open(polygonfile) lyr = ds.GetLayer() feat = lyr.GetNextFeature() wholeGeom = N...
93698b91782d4de987abae7b092274d2e82267c5
3,606,533
import hashlib def same_files(fname, fname2): """ Two files are the same if they have the same hash. :param fname String: The first filename. :param fname2 String: The second filename. """ try: hash1 = hashlib.sha512() with open(fname, 'rb') as fin: hash1.update(fi...
502b7b6942d8766edad78d7aa0c7de9ddd85a7cb
3,606,534
def encode_msg(msg: dict, enc: str) -> str: """ Encode the given message using the serialization specified :param msg: message to encode :param enc: serialization to encode :return: encoded message """ enc = enc.lower() msg = general.default_encode(msg) if enc not in serializations....
617398a21aca632107826d32db2d5f26a2479cdb
3,606,535
import time def opening_web(web,path,wait_time): """ Open a webpage using selenium ChromeDriver We'll be using this function to open webpages that we want to collect data from Args: web (str): An url adress. This is the web page will be opening path (str): The path to the chromedriver us...
fd64b72168298064598562d636411a67f3e354db
3,606,536
def get_callbacks(model_name, checkpoint_dir = "/content/checkpoint.h5", decoder = False): """ Returns a list of callbacks. Args: checkpoint_dir (str, path): make sure to have the actually .h5 file in the path decoder (boolean): whether or not your model uses the decoder Returns: ...
e5475e7524d86e5416f59a4971c17201116a9ab0
3,606,537
def make_pdf_table(df: pd.DataFrame) -> platypus.Table: """Формирует и форматирует pdf-таблицу доходности портфеля и индекса.""" list_of_lists_table = make_list_of_lists_table(df) style = platypus.TableStyle( [ ("LINEBEFORE", *_SECOND_COLUMN, LINE_WIDTH, LINE_COLOR), ("LINEAB...
22009deaa454213a3047401fbf057a04aeb3dcfb
3,606,538
import time def get_all_cscs(): """Get fiscal year IDs and return their SbFiscalYear objects as a list. Using the legal CSCs, get their fiscal years, tracking their corresponding CSCs, and return the SbFiscalYear objects for them as a list that was created in create_fy_objs(). Returns: R...
5c06a6bdea2b1c86bba0ef314e7ee3928d5a8f16
3,606,539
import csv def get_total_reward() -> float: """ to check the calculated rewards, sum up all results in the output file :return: sum of all rewards """ s = 0 with open(output_file, newline='') as output: reader = csv.reader(output) for row in reader: s += float(row[...
90c61284102ecc9863261825eda226f7561604d4
3,606,540
def get_key(key, starting_dict=None, update_chained=True, chained=None, chained_status=None): """ Given a dictionary, return an element by ``key``. By default, ``chained`` will have ``.update()`` called on it with ``starting_dict`` as the only argument. Set ``extend_chained`` to False to ignore ``s...
95cf54eae15475745c7a8ff46c7c8c26a47e6142
3,606,541
import numpy from numpy import newaxis, zeros, resize, transpose, floor, arange, array def bshow(f1, f2=None, f3=None, factor=17): """ y = bshow(f1, f2=None, f3=None, factor=17) Generate a graphical representation of overlaid binary images. Does **not** actually display the image anywhere! Gener...
88f435b2d9f6b38cb29ff59daf1b509d27702464
3,606,542
def microservice_api_grpc_feedback(prediction_request: prediction_pb2.SeldonMessage = None, prediction_response: prediction_pb2.SeldonMessage = None, reward: float = 0, microservice_endpoint: str = None, grpc_max_se...
0c2eab4b50d10791612bfe22fc32b1812a9e6827
3,606,544
def constraint_currents(sim, return_magnitudes=False, constraint_ids=None): """ Calculate the time series of current for each constraint in the ChargingNetwork for a simulation. Args: sim (Simulator): A Simulator object which has been run. return_magnitudes (bool): If true, return constraint cu...
33032659d134576435fe7feb41812d7b2b7e1936
3,606,545
def num_minima(x): """ Count occurrences of maximum value of the series :param x: the time series to calculate the feature of :type x: pandas.Series :return: the value of this feature :return type: float """ if not isinstance(x, (np.ndarray, pd.Series)): x = np.asarray(x) mi...
4eb65b8ad09c4ce1e913860acf427f3cd00807f7
3,606,546
def simulate_dataset( model_dict, params, n_obs, control_means=None, control_sds=None, policies=None ): """Simulate datasets generated by a latent factor model. Args: model_dict (dict): The model specification. See: :ref:`model_specs` params (pandas.DataFrame): DataFrame with model paramet...
58409330e3d44496dc46c27cce1ba777930671c6
3,606,548
def line_animation(line, idx, limit=10, step=1): """ Animate long string """ line = line+' | ' line_start = 0 line_end = len(line) short_line_start = line_start+idx short_line_end = limit+idx short_line = line[short_line_start:short_line_end] add_line_end = abs(len(short_line)-limit) ...
85f84c524c45ea81b2b83d14bff743791d126137
3,606,549
def compute_chunksize(df, num_splits, default_block_size=32, axis=None): """Computes the number of rows and/or columns to include in each partition. Args: df: The DataFrame to split. num_splits: The maximum number of splits to separate the DataFrame into. default_block_size: Minimum num...
4fe0b363e82a51c67f6a5fd69dbc9188bddd3803
3,606,550
def format_date(value): """Return value as string.""" return_value = None if value: return_value = str(value) return return_value
76887bb3be2c858102f1b37e0a1ed8ba42235353
3,606,551
def bbox2points(bbox): """ From bounding box yolo format to corner points cv2 rectangle """ x, y, w, h = bbox xmin = int(round(x - (w / 2))) xmax = int(round(x + (w / 2))) ymin = int(round(y - (h / 2))) ymax = int(round(y + (h / 2))) return xmin, ymin, xmax, ymax
e6c3de2477e16a74c4c4c6d00d97eca473073f1d
3,606,552
def makeBondList(size, xperiodic): """ create bond list in the square lattice Parameters -------------- size : (int, int) linear size of the square lattice xperiodic : boolean indicates PBC along x """ # bondlist format # (0,1,2) -> (x,y,'r'/'d') # 3 -> bond numb...
8500d58195e3d375837cf73a9b8b33b9c7920640
3,606,554
def level_to_rgb(level, background): """ Converts internal consept of level to a gray color for text in RGB :param level: range from 1 to 15 :return: tuple referring to (R, G, B) """ #Level goes from 1 to 15, starting from level1:(30,30,30), and getting darker with 1 point if level not in ra...
5183e72f4422031f2aed9881be1cce869c8b2606
3,606,555
def dmp_sub_term(f, c, i, u, K): """Subtract `c(x_2..x_u)*x_0**i` from `f` in `K[X]`. """ if not u: return dup_add_term(f, -c, i, K) v = u-1 if dmp_zero_p(c, v): return f n = len(f) m = n-i-1 if i == n-1: return dmp_strip([dmp_sub(f[0], c, v, K)] + f[1:], u) e...
8d9aabbf3dac02e450f3af5c83dd44943b5ed1fb
3,606,556
def sendRawTxs(config, objRpcB, xTxBlocks, strAddrMiner): """ sends raw transactions and creates blocks. All txs will have at least 6 confirmations. :param objRpcB: :param spendBlocks: lists of "blocks" that are lists of transactions. Txs in each "block" is assumed to fit in a single bitcoin block :...
4682b91430fae637c88d8dd6f4b8fa84d6d373b3
3,606,557
def run_copy( src_path: str, dst_path: StrOrPath = ".", data: AnyByStrDict = None, **kwargs, ) -> Worker: """Copy a template to a destination, from zero. This is a shortcut for [run_copy][copier.main.Worker.run_copy]. See [Worker][copier.main.Worker] fields to understand this function's ar...
6ff63984a6d2bb1c1c725a472e465ede4de284a2
3,606,559
def get_message_relay(celery_app): """ Function that return a celery task list. """ return celery_app.tasks['eduid_msg.tasks.send_message']
d024b6c95013d8fbd854d833e74dbedf0220a7df
3,606,560
def validate_premium_registry(cmd, registry_name, resource_group_name=None, message=None): """Raise CLIError if the registry in not in Premium SKU. :param str registry_name: The name of container registry :param str resource_group_name: The name of resource group """ registry, resource_group_name = ...
8fe021d6b1a13b57ed16dd18f4f845ed6d58cb29
3,606,561
def weapon_list(fn): """ Decorator to set up weapon list .. versionadded:: 0.8 """ def weapon_setup(*args, **kwargs): """ Setup weapon list """ context = args[0] if not hasattr(context, 'weapon_list'): context.weapon_list = {} context...
a54baf7a292898da62da6fb3ff06454ce8e7719a
3,606,562
def serialize(cluster, nodes, ignore_customized=False): """Serialize cluster for provisioning.""" objects.NodeCollection.prepare_for_provisioning(nodes) return ProvisioningSerializer.serialize( cluster, nodes, ignore_customized=ignore_customized)
c6d68c3cb200ac6ee91212a892120e94ac0d4d33
3,606,563
def get_ontology(*args, **kwargs): """Returns a new Ontology from `base_iri`. This is a convenient function for calling World.get_ontology().""" return World().get_ontology(*args, **kwargs)
8af18e65efadccf885f45327a55e08151db499c8
3,606,564
from typing import Optional def can_use_local_differ(repo: Optional[git.Repo]): """On some non-master branch""" return repo is not None and repo.head.ref.name != 'master'
8a8f62609e79048dadda221659ff3a520b4ecfac
3,606,565
def edit_tag(tag_id): """ PUT endpoint that edits an existing club tag. """ new_tag_name = g.clean_json['name'] old_tag = Tag.objects(id=tag_id).first() if old_tag is None: raise JsonError(status='error', reason='Old tag does not exist!') new_tag = Tag.objects(name=new_tag_name).f...
652aadd6c4d4b9a0a3839ee67a3d97b30f48c4f4
3,606,566
import json def get_boxnote_text(filepath): """Convert a boxnote to plain text. Parameters: filepath (str): the path to the boxfile Returns: the text of the boxfile as a string """ f = open(filepath, encoding="utf8") text = json.loads(f.read())["atext"]["text"] f.close() return ...
ba41e36d534931b9e2d1a401d7317ee4f8956f13
3,606,568
def define_ising_helper_functions(): """Functions for plugging into solvers for +/-1 Ising model with fields h_i and couplings J_ij. Returns ------- function calc_e function calc_observables function mch_approximation """ @njit(cache=True) def fast_sum(J...
3d034fab74665d2260ba59280610894286bf5a22
3,606,569
def create_obs_vectors_singular(raw_obs, which_unit): """Creates a singular observation vector from the persepctive of which_unit See the link below for a list of available features and corresponding indices https://github.com/jjlee0802cu/pylol/blob/main/pylol/lib/features.py ""...
b032a96152446e21c067a7dc881b96b5a762f1c0
3,606,570
def discriminator_xz(x_inp, z_inp, is_training=False, getter=None, reuse=False, do_spectral_norm=True): """ Discriminator architecture in tensorflow Discriminates between pairs (E(x), x) and (z, G(z)) Args: x_inp (tensor): input data for the discriminator. z_inp (tenso...
ea90fb0ef4a1beb9ddbc9bfe93b11fb06f37fabb
3,606,571
def func_args_realizer(args): """ Using an ast.FunctionDef node, create a items list node that will give us the passed in args by name. def whee(bob, frank=1): pass whee(1, 3) => [('bob', 1), ('frank', 3)] whee(1) => [('bob', 1), ('frank', 1)] """ items = map("('{0}', {0})".for...
d8f4bc8b7a79796e9512b6c6c2ad884e79389ebc
3,606,572
def flatten_list_bytes(list_of_data): """Concatenate a sequence of bytes-like objects.""" if not PY34: # On Python 3.3 and older, bytes.join() doesn't handle # memoryview. list_of_data = ( bytes(data) if isinstance(data, memoryview) else data for data in list_of_d...
567f29f808adf80e400098d457d6c5d08cc0059f
3,606,573
from tqdm import tqdm from tqdm import tqdm import functools import collections import logging def generate_rerouters_process(parameters): """ Compute the rerouters for the given parking areas.""" sumo_net = sumolib.net.readNet(parameters['net_file']) ret_rerouters = dict() @functools.lru_cache(maxs...
1a19d6534eb37470937c6784b9d5817b9f9d8155
3,606,575
import io def load_ffme_returns(cols: list = None): """ Load the Fama-French Dataset for the returns of the Top and Bottom Deciles by MarketCap """ with resources.open_binary("tests.data", Params.DATA_FFME_FILE) as file: file = file.read() file = io.BytesIO(file) df = pd.read_csv(f...
cdb769df3a91368735b7e932be8d7bf35ca0f3ca
3,606,576
def verify_stereo(zz_stereo, zz_mono, disparity_x, disparity_y): """Verify disparities based on coefficient of variation, maximum y difference and z difference wrt monoloco""" # COV_MIN = 0.1 y_max_difference = (80 / zz_mono) z_max_difference = 1 * zz_mono cov = float(np.nanstd(disparity_x) / np.a...
f51c6c1099393333e68870b5b06160d569b3be44
3,606,577
def W_true_insurance(): """Returns the ground true DAG for Insurance data.""" # The output s are ig.graph object of ground truth dag of insurance dataset # and grouth truth dag of the insurance dataset in adjacency matrix format. vertex_label = [ 'PropCost', 'GoodStudent', 'Age', 'SocioEcon', 'RiskAvers...
57bd5f649f41fe9a7648aa586a74c1718734a275
3,606,578
def return_numbers_names_colors(): """ Return lists of numbers, names, and colors representing anatomical brain regions derived from FreeSurfer's FreeSurferColorLUT.txt lookup file. Returns ------- numbers : list of integers numbers representing anatomical labels from FreeSurferColorLUT...
ed9d9282fd5ef729b57b8e6cb42704e1827caf07
3,606,579
import math async def cos(regular_message: Message.Message, event:Event.MessageEvent, *, bot) -> Message.Message: """ 三角函数cos。 格式:cos x x: 要求的数 """ x = float(regular_message[1].data['text']) ans = math.cos(x) return Message.Message.init_with_segments( Message....
fb22f05876f8c32dde0c9a1c76786c4f20d09530
3,606,580
def _GetBrowserDumpEvents(track): """Get the browser memory dump events from a tracing track. Args: track: The tracing_track.TracingTrack. Returns: List of memory dump events. """ assert sandwich_runner.MEMORY_DUMP_CATEGORY in track.Categories() browser_pid = _GetBrowserPID(track) browser_dumps_...
1471f749f16afe6d932e589962df5f85c612bd49
3,606,581
import base64 def _compile_source(source: str) -> bytes: """Compile and return teal binary code.""" compile_response = _algod_client().compile(source) return base64.b64decode(compile_response["result"])
d5c1d8196bdb125b1590eb74da99a6694d1b50fe
3,606,582
def roman_to_int(input): """ Convert a roman numeral to an integer. >>> r = range(1, 4000) >>> nums = [int_to_roman(i) for i in r] >>> ints = [roman_to_int(n) for n in nums] >>> print r == ints 1 >>> roman_to_int('VVVIV') Traceback (most recent call last): ... ValueError: ...
329cefa78c2429de931fa89c4605b023e68f6a13
3,606,584
def blur_bg(img, mask, kernel_size=(5, 5)): """ blur the background of image (black region of mask). Args: img (np.uint8): image to blur mask (np.uint8): mask to use as reference kernel_size (tuple, optional): kernel size to use for blur. Defaults to (5, 5). Returns: img_bl...
e6bb783a898ae39ce6c34e0a173e4e20d437eb3c
3,606,585
def convert_to_canonical(P=[]): """Convertion function to convert from shapely object to canonical form. Args: P: Shapely object representing a polygon. Returns: poly: A polygon represented in canonical form. [] otherwise. """ if type(P) is not Polygon: logger.warn("Polygon conversion requested but wrong ...
ffb08362e73e9ab467db0e4f12b9b574b6e48e6f
3,606,586
def categorical_log_prob(self, logits): """ torch RelaxedOneHotCategorical log_prob is weird (uses that of TransformedDistribution) need to use log_prob from base_dist instead """ return self.base_dist.log_prob(logits)
50b9124ddbdd04696b4b152d55cb0ec4ffd86b05
3,606,587
def showCategory(category_name, category_id): # Add SQLAlchemy statements """Takes in a specified category_name and returns the the items associated with it. Renders a web page showing all the categories on one side and the items on the other side of the page. """ # NOTE IMPORTA...
b803de6214674404fa3c91117444926fb4187717
3,606,588
from typing import Dict def filter_val_not_none(d: Dict) -> Dict: """ Return a new dictionary composed of all key-value pairs (k, v) in d where v is not None. :param d: original dictionary :return: d, without key-value pairs where value is None >>> filter_val_not_none({"a": 5, "b": 10, "c": None}...
21aaf90a4407a690ce76d09dfb54d93c1293c953
3,606,589
def get_card_ids(db) -> list: """ Gets a list of all card IDs in the datase. :return: List of card IDs. """ return db['cards'].distinct('_id')
48e6e1880253603233ccdc55fb38269f75375f8f
3,606,590
from typing import List def filter_rows( df_filter:pd.DataFrame, df_to_keep:pd.DataFrame, filter_on:List[str], to_keep_on:List[str], drop_duplicates:bool=True) -> pd.DataFrame: """ Filter rows from `df_to_keep` which have matches in `df_filter` **N.B.** The order o...
08d75fa426f46e9d4affcb60256ea9f059f3d15f
3,606,591
def factorial(n): """ Computes n! Parameters ---------- n : int A positive integer Returns ------- f : int n! Raises ------ TypeError If `n` is not a number. ValueError If `n` is not non-negative integer. """ if not is_number(n):...
e58a5ac0195c0d49d04f9888cba9b45b353992d7
3,606,592
import curses def create(): """Create zti instance. """ if Zti._zti: return Zti._zti try: Zti._stdscr = curses.initscr() except curses.error: _logger.exception("initscr error") return None try: curses.cbreak() except curses.error: _logger.e...
52b3356eda0ff537a10c1231e29edd05ce0e5bda
3,606,593
def format_system_date(date=None): """Formats a system date. (Format: YYYY-MM-DD) """ return u'%d-%02d-%02d' % (date.year, date.month, date.day)
f34db708b467d07827de7efed8242b821b38020a
3,606,595
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.registry.registerUtility(link_attrs, interfaces.ILinkAttrs) config.include('clldmpg') config.include('clld_glottologfamily_plugin') config.registry.r...
72c1abc8382416224e18a3f26b81aeeadd55e46c
3,606,596
def lofarHBAAntPositions(ants, lofarStation, elem): """Update the antenna positions using the HBADeltas file ants: [nants, 3] array, antenna positions in XYZ lofarStation: instance, see lofarConfig.py elem: hex/base-16 string of tile element IDs returns: updated [N, 3] antenna position array ""...
770665fb58ba116dc5ba5d63535f67bd00a999cf
3,606,597
import time def datetime_to_integer(datetime): """Convert datetime object to integer value. 'datetime' is the datetime object""" return time.mktime(datetime.timetuple())
8d4d94fac947c3dd9e82ee3d60a1a57a6440457d
3,606,598
def _django_test_command(settings_module): """Get the manage.py test command for Django""" manage_script = conf.SITE_ROOT / 'manage.py' if not manage_script.exists(): print yellow("Django script manage.py doesn't exist in %s" % conf.SITE_ROOT) return None return '{MANAGE_PY} test --sett...
907e503b8fdd8f1a1188a24ddc928896f204eb27
3,606,599
from datetime import datetime def get_remaining_submission_for_a_phase( user, challenge_phase_pk, challenge_pk ): """ Returns the number of remaining submissions that a participant can do daily, monthly and in total to a particular challenge phase of a challenge. """ get_challenge_model(c...
23728989736086e45d4d8201bd7640510edce568
3,606,600
def _get_more_basis_columns(A, basis): """ Called when the auxiliary problem terminates with artificial columns in the basis, which must be removed and replaced with non-artificial columns. Finds additional columns that do not make the matrix singular. """ m, n = A.shape # options for inclu...
360c4999771e26987c0d50584f095da9b7937671
3,606,601
def generate_peptide(model, alphabet_list, network_input, n_alphabets): """ Generate peptide from the neural network based on a sequence of amino acids """ # pick a random sequence from the input as a starting point for the prediction alphabets = sorted(set(alphabet_list)) start = np.random.ra...
65a6c64ac20fd15cc260f3ee090503ba7a6fc420
3,606,602
def polyfit(dates, levels, p): """Returns the polynomial object of a degree p least-squares polynomial fit to the dates, levels input.""" dates_float = matplotlib.dates.date2num(dates) d0 = -1*dates_float[0] p_coeff = np.polyfit(dates_float + d0, levels, p) poly = np.poly1d(p_coeff) return po...
1c27110e1e42f43b71859fecb11ed8d489e4bc9b
3,606,603
def spm_hrf(RT, P=None, fMRI_T=16): """ python implementation of spm_hrf see spm_hrf for implementation details % RT - scan repeat time % p - parameters of the response function (two gamma % functions) % defaults (seconds) % p(0) - delay of response (relative to onset) 6 % p(1...
2bb8f11a5f2b3be3852be2b6c9fc63ff75964973
3,606,604
import operator def sort_load_list_by_time(load_list): """Given the standard load list return a list orderd by time The list contains a tuple of the load_id and the actual load_set """ return sorted(load_list, key=operator.itemgetter(1))
1ae00f8ffe0cf4ef7ab899b9e6d3c9a0051c7e91
3,606,605
def product_moment_corr(x, y): """ Product-moment correlation for two ndarrays x, y """ r, n = _product_moment_corr(x, y) # From scipy.stats.pearsonr: # As explained in the docstring, the p-value can be computed as # p = 2*dist.cdf(-abs(r)) # where dist is the beta distribution on [-1, 1] wi...
ca54c6aa218553878ced0d500549c8bf370a904f
3,606,606
import functools def singleton(cls): """ Singleton decorator """ @functools.wraps(cls) def wrapper(): if not wrapper.instance: wrapper.instance = cls() return wrapper.instance wrapper.instance = None return wrapper
7d99cf00603ee05be47b4579e9671c246a7b793f
3,606,607
def is_blackout(date): """Returns true if the date falls in the Resource Blackout dates.""" return ResourceBlackoutDate.objects.filter(date=date).exists()
86de14f2c5ba26ccb5c78aea501ff2ad5d139ec8
3,606,608
def mseuclidean(u, v, V): """ Returns the standardized Euclidean distance between two n-vectors ``u`` and ``v``. ``V`` is an m-dimensional vector of component variances. It is usually computed among a larger collection vectors. Parameters ---------- u : ndarray An :math:`n`-dime...
76b518cd6cfe97eb8820c81f1d4c15a6833bcf9c
3,606,609
def crop_to_ratio(im, desired_ratio=4 / 3): """ Crop (either) the rows or columns of an image to match (as best as possible) the desired ratio. Arguments: im (np.array): Image to be processed. desired_ratio (float): The desired ratio of the output image expressed as width/...
dd2301708aa514b2d9b87758ce38d7bd9f9d874c
3,606,611
def generate_weights(rows, cols, zeros=False): """ Generates a Matrix of weights according to the specified rows and columns """ if zeros: return np.zeros((rows, cols)) return np.random.rand(rows, cols)
ab08d85989d3f3c15049b452ba9070f27d433066
3,606,613
import json def post(url, data): """ 发送post请求 :param url: str, url地址 :param data: dict, post请求的查询数据 :return: str, 请求返回的数据 """ data = bytes(json.dumps(data), encoding="utf-8") request_obj = request.Request(url, headers={'Content-Type': 'application/json'}) with request.urlopen(requ...
814951a9b8b860f8b20f3a32be12018f7f943afd
3,606,614
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up Paradox from a config entry.""" if DOMAIN not in hass.data: hass.data[DOMAIN] = {} module = ParadoxDevice(hass, entry) if not await module.async_setup(): return False if not module.available...
92852a4164f181926e5c93b745d0df667171a4b2
3,606,615
def cot(x): """Returns a new Var with cotangent applied to the input Var x :param x: object on which cotangent is applied, required :type x: AD_Object.Var :return: new object with cotangent applied to input :rtype: AD_Object.Var :example: >>> from autodiff.AD_BasicMath import cos ...
9ebca0d35c5023a0a8eedc76c97d9c76a010f419
3,606,616
def grompp_npt(job): """Run GROMACS grompp for the npt step.""" npt_mdp_path = "npt.mdp" msg = f"gmx grompp -f {npt_mdp_path} -o npt.tpr -c em.gro -p init.top --maxwarn 1" return msg
7afdf17586250a62106c67b2594d1aa057fef09e
3,606,617
def set_figure_title_anchor(obj_title, anchor_params): # type: (object, Dict) -> object """Set the anchor properties of the figure title Args: obj_title (object): a matplotlib Text object anchor_params (dict): anchor parameter dict Returns: same as input obj_title """ if...
24730bf8305b36ce67ca673158854e409fa60a78
3,606,618
import math def pad_image(image, size=(352, 512)): """Helper function to pad image to size (height, width)""" pad_h = max((size[0] - image.shape[0]) / 2, 0) pad_w = max((size[1] - image.shape[1]) / 2, 0) pad_h = (math.floor(pad_h), math.ceil(pad_h)) pad_w = (math.floor(pad_w), math.ceil(pad_w)) ...
2f2ce22db96499778899e33e9f1bf94897502a39
3,606,619
def uri_leaf(uri): """ Get the "leaf" - fragment id or last segment - of a URI. Useful e.g. for getting a term from a "namespace like" URI. >>> uri_leaf("http://purl.org/dc/terms/title") == 'title' True >>> uri_leaf("http://www.w3.org/2004/02/skos/core#Concept") == 'Concept' True >>> ur...
3045806ac56124331c58b6daffb5c1b5c202c0eb
3,606,620
def create_single_item_trie(in_dict, out_file=""): """Creates a marisa trie from the input dictionary. We assume the dictionary has string keys and integer values. Args: in_dict: Dict[str] -> Int out_file: marisa file to save (useful for reading as memmap) (optional) Returns: marisa tr...
b9c40430b356866cdd76b88f669bb81c609f3660
3,606,621
def reader_conf(path: str, encoding: str = 'UTF-8') -> dict: """读取配置文件 [capitalize] a b :param path: 配置文件路径 :param encoding: 文件编码 """ cx = {} with open(path, encoding=encoding)as fp: for data in fp: data = data.strip() if data.startswith('[') and data...
bad9774cd302605061b26d65e3c0bfe26a1f6984
3,606,622
def connect_leaf_device_client(): """ connect the device client for the leaf device and return the client object """ current_config = runtime_config.get_current_config() client = adapters.LeafDeviceClient() client.connect( current_config.leaf_device.transport, current_config.leaf...
d3f4122ef49b6971739bd7e4e484cd8b8ad4a37a
3,606,623
def setup_tent(model, args): """Set up tent adaptation. Configure the model for training + feature modulation by batch statistics, collect the parameters for feature modulation by gradient optimization, set up the optimizer, and then tent the model. """ model = configure_model(model) params,...
0027c0566b25631a9db37300f3c53d344db4b681
3,606,624
def reshape_spectrum_lines(energy, weights=None, normalize=True, **others): """ Args: energy(num or array): source energies shape = [nSource x] nSourceLines weights(Optional(num or array): source line weights shape= [nSource x...
4499d77c569e6c6cc996313beee7c0a9cc1da319
3,606,625
def L1_Norm(arr: _Array) -> float: """Compute the L_1 norm of input vector `x`. This implementation is generally faster than np.norm(arr, ord=1). """ return _np.abs(arr).sum(axis=0)
1a8797f58d60abf7f228e0f9be4edebafd4494b3
3,606,627
def solution(source, destination): """ Identifies shortest distance a knight would have to move between two points of a chess board. Accepts a source cell number and a destination cell number Parameters: source: int destination: int Returns: int: Shortest number of levels traverse...
b23aaaa2747ed47ed7c02fde76856ef650eef1cd
3,606,628
import yaml def load_yaml_config(filename): """Load a YAML configuration file.""" with open(filename, "rt", encoding='utf-8') as file: config_dict = yaml.safe_load(file) return config_dict
771dbf8fdaca1575bc9bdb472d6aa1405c689e7a
3,606,629
def getConvolutionOutputShape(tensor_shape, conv): """ compute the output shape of a convolution given the input tensor shape args: tensor_shape (tuple): input tensor shape (B x C x D) conv (nn.Module): convolution object returns: output_shape (tuple): expected output shape "...
d7e2a0d8806a93af10ae3fac9bbc9132cf7d615f
3,606,630