content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def conv_layer(num_conv, output_size, nodes, children, feature_size): """Creates a convolution layer with num_conv convolutions merged together at the output. Final output will be a tensor with shape [batch_size, num_nodes, output_size * num_conv]""" with tf.name_scope('conv_layer'): nodes = [ ...
2e4c7d552199acb47db65a1ae219e436dbe595ba
3,611,400
def send_message(request): """发送消息,AJAX POST 请求""" sender = request.user recipient_user_name = request.POST['to'] recipient = get_user_model().objects.get(username=recipient_user_name) message = request.POST['message'] if len(message.strip()) != 0 and sender != recipient: msg = Message.o...
37e06a4497ab7ffc607eb6c6b7a3e512eb3f14ff
3,611,401
def half_preserve_energy_index(xfft, energy_rate=None, index_back=None): """ The same as the function preserve_energy_index but we discard half of the input signal since it is Hermitian symmetric. """ initial_length = len(xfft) half_fftsize = initial_length // 2 # the signal in frequency domain...
882e854ce3f5be3066cb20a0a00193730a77be2d
3,611,402
import re def local_action_factory(action_classes, action_names, utter_templates): # type: (List[Text], List[Text], List[Text]) -> List[Action] """Converts the names of actions into class instances.""" def _action_class(action_name): # type: (Text) -> Action """Tries to create an instance...
b96fbd5687b6a49fe79acf53b90b50aac63ad5b9
3,611,403
def listPalettes(show=True, getdescriptions=True): """ Function listPalettes Gets the list of available palette names Arguments show: If set (default) prints the list of palettes to the terminal as well as returning it getdescriptions: If set (default) returns and if required prints the ...
b8122b9b97b557259500a9a2629201521a9eb65a
3,611,404
def subtract(x, y): """ Subtracts two number :param x: minuend :param y: subtrahend :return: difference between two numbers """ return x - y
cb9165d72a3aa0ec7b82f0ad89e53bcf8beffa3a
3,611,405
from typing import Dict def file_name_convention() -> Dict: """ This function returns the file name taxonomy which is used by ImageAutoOutput and Dataset class """ file_name_convention = {"CT": "image", "MR": "image", "RTDOSE_CT": "dose", ...
f3c56306c8dd0f3c228064e8a72bef51b70a4d93
3,611,406
import re def detokenize(tokens): """ Detokenizing a text undoes the tokenizing operation, restores punctuation and spaces to the places that people expect them to be. Ideally, `detokenize(tokenize(text))` should be identical to `text`, except for line breaks. """ text = ' '.join(tokens) ...
6bed45c07c68ad97fecab2f2bf7424b97d2a8f82
3,611,407
def read_file(path): """ lit le conllu et donne en sortie une liste d'objets Sent chaque objet Sent a : .id, .text, .tree les éléments de l'arbre d'un Sent sont des Word un Word : .nid, .form, .lemma, .upos, .xpos, .feats, .head, .deprel, .deps, .misc si le résultat est stocké dans une variable corpus on aura : ...
27dbafff196ee953958eb09733f5bed1d3d391cf
3,611,408
def from_dateutil_rrule(rrule): """ Convert a `dateutil.rrule.rrule` instance to a `Rule` instance. :Returns: A `Rrule` instance. """ kwargs = {} kwargs['freq'] = rrule._freq kwargs['interval'] = rrule._interval if rrule._wkst != 0: kwargs['wkst'] = rrule._wkst kwarg...
037309c1376a11d515b4dce4281aab4bf6a52b59
3,611,409
def vpncredential_create(request, **kwargs): """Create VPNCredential :param request: request context :param admin_state_up: admin state (default on) :param name: name for VPN Credential :param description: description for VPN Credential """ body = {'vpn_credential': {'name':...
e21624af83e40c77689dc4d36cf03cdc8671abfa
3,611,410
def find_similar(): """ Finds relevant articles based on provided keywords and parameters args: List[String] keywords: list of keywords to search Int recency: max age (in days) of returned articles, 0 for any time List[String] blacklist: list of top level domains blocked by user ...
d3429a09791d04b980ca5afb7668e10784bbc98f
3,611,411
import os def ensure_dir(directory): """Make sure the directory exists. If not, create it.""" if not os.path.exists(directory): os.makedirs(directory) return directory
b02c55d000eb024dbe8e54a2648bf3e8200c136f
3,611,412
def classify(feature_matrix, theta, theta_0): """ A classification function that uses theta and theta_0 to classify a set of data points. Args: feature_matrix - A numpy matrix describing the given data. Each row represents a single data point. theta - A numpy array d...
8f368f84e6084a1b586d45f1189d3ceafdd938cd
3,611,413
def rebuild(request): """Rebuild ``XPI`` file. It can be provided as POST['location'] :returns: (JSON) contains one field - hashtag it is later used to download the xpi using :meth:`xpi.views.check_download` and :meth:`xpi.views.get_download` """ # log whole request without ...
a395430c749330a968fc08f72a9dc3ff1cb92751
3,611,414
import os def abspath(*args): """convert relative paths to absolute paths relative to PROJECT_ROOT""" return os.path.join(PROJECT_ROOT, *args)
eee9021ce73b8d79e3fa964b0e517cba16542a24
3,611,415
def create_sum_squares(): """Returns a code dag for sum of squares.""" num_squares = Variable('N', var_type="int") sum_var = Variable('sum_var', var_type="int") sum_squares = FunctionNode('sum_squares', ret_type="int", inputs=[num_squares], output=sum_var) sum_squares.add_object(sum_var) sum_sq...
be703c5d385ee2ca4115306e97cc45977deadf9b
3,611,416
def get_ps_url(ra, dec, size=240, output_size=None, filters="grizy", format="fits", color=False): """ Get URL for images in the table Parameters ---------- ra, dec: [floats] position in degrees size: [float] image size in pixels (0.25 arcsec/pixel) filters: [strings...
dbc129d870c4c390b4411c5fc1b32204c3a7813d
3,611,417
def mcb(l, bit, mlb, tiebreaker = "1"): """ l = list of bits, e.g. ["00100", "11110", "10110"] bit = index of the bit to consider, integer mlb = most ("1") or least ("0") bit tiebreaker = if there's an even split, default to this value. returns the most common occurrencs, subjec...
9256db43f5564ac62f8f83a27332a408a496fc3e
3,611,418
def weight_variable(stddev): """Weight variable.""" return TruncatedNormal(stddev)
8146da796079cec2f39847476d9881739e13ceca
3,611,419
import re def convert_dict(txtfile): """ convert this to dictonary, where key = CISC and val = ADIE""" with open(txtfile) as f: rename = {} for line in f: (key, val) = line.split() # Remove any non-digit i.e. 'CISC' rename[str(re.sub("[^0-9]", "", key))] = s...
29f61550fe59f1075e1a822916aae7b54c06c18a
3,611,420
import logging def get_query_for_oracle_load_full(table_name, columns, owner): """ JDBC query for full ingestion of one table """ logging.info(f"BUILDING FULL QUERY for {table_name}") select_cols = ",".join(str(x) for x in columns) return f"select {select_cols} from {owner}.{table_name}"
e91497cae2cf5804c89b063e77943694397a2d62
3,611,421
def get_container_ipv_from_arguments(arguments): """ Determine the container IP version from the arguments. :param arguments: Docopt processed arguments. :return: The IP version. 4, 6 or None. """ version = None if arguments.get("--ipv4"): version = 4 elif arguments.get("--ipv6...
68a4fc60f20bdb6e7fcaf267dacc7d6cb5754426
3,611,422
def gradient_method(obj_function, start_point, init_step_size, shrink_factor, grad_function=approx_gradient, step_function=descent_step, max_iterations=float("inf"), stop_norm=1e-8...
64a9ed0a712de0db9196d0a23f57ad80d6ccd1c1
3,611,423
import argparse import sys def main(): """Console script for pact_testgen.""" parser = argparse.ArgumentParser() parser.add_argument("pact_file", help="Path to a Pact file.") parser.add_argument( "output_dir", help="Output for generated Python files.", type=directory ) parser.add_argum...
60ef8095f12c5c04e164abf1a3f18b947dcb74e4
3,611,424
from datetime import datetime def add_vacation_food_request(request, student): """ This function is to record vacation food requests :param request: start_date: Starting date of food request end_date: Last date of food request purpose: purpose for vacation food ...
4e7f2e103efe4b15020911b57f17830efc3474fc
3,611,425
def info() -> flask.Response: """API endpoint to retrive information about the current status. Return a description of the current status, e.g in which state the crawler is, which config is used, etc. Returns: flask.Response: REST response """ global TW_STATE response = TW_STATE.i...
dadb6ae6ad76c86b4567b0db21434ae463917c90
3,611,426
def bandwidth_usage(context, instance_ref, audit_start, ignore_missing_network_data=True): """Get bandwidth usage information for the instance for the specified audit period. """ admin_context = context.elevated(read_deleted='yes') def _get_nwinfo_old_skool(): """Support for getting...
66a8072d248ef4c2050e6a30ac98f9767d987734
3,611,427
import json import traceback def updateEventRange(event_range_id, eventRangeList, jobId, pandaProxySecretKey, status='finished', os_bucket_id=-1, errorCode=None): """ Update an list of event ranges on the Event Server """ # parameter eventRangeList is not used try: tolog("Updating an event range....
732b34ca894b85ce6e56587a3af7c7c748f5939e
3,611,428
def __voxel_normal_distribution(pointcloud, voxel_hashes, is_sorted: bool = False): """ Computes the normal distribution of points in each voxel Args: pointcloud (np.ndarray): The input pointcloud `(n, 3)` [np.float32] voxel_hashes (np.ndarray): The voxel hashes `(n,)` [np.int64] ...
0526981f0d055bb1499c9e25c20945f324f15939
3,611,429
import uuid def plot_event_label(axis, starttime, endtime, **options): """ Plot event label on current axis. Provide required ``eventtype`` field in the options to specify which event to plot. Plot style can be updated by providing keyword ``style`` in the extensions plot entry. Default...
b93a20e1e8aec71416d49ed3cac8d3ebfca14028
3,611,430
import os def generate_submission_file(weight_path, model_name, target_size, test_path, use_folds): """ Generates rle encoded submission files of model - model_name use_folds - if True - a weighted average prediction of folds is used from weight files in folder - 'weights/model_name' - if Fa...
f19315589b895dc566168b303ac4894fa98588b6
3,611,431
def balance(text, bal=0): """ Checks whether the parens in the text are balanced: - zero: balanced - negative: too many right parens - positive: too many left parens """ if text == '': return bal elif text[0] == '(' and bal >= 0: return balance(text[1:], bal +...
e3e523d2c0bab114c3ac243b9fabc934ce92a694
3,611,432
def test_qrs_detection(): """Main function - print quick test example """ try: print("Example MIT-BIT Quick Test") # Quick test # load ECG data from ludb database into pandas dataframes ecg, rpeaks = read_mit_bit_files() print(ecg) # load raw ECG signal ...
5ee7037cdda01176203a35e81ccc06f0695c3f54
3,611,433
def _inches_to_meters(length): """Convert length from inches to meters""" return length * 2.54 / 100.0
fccd2937b87c7b1c7eba793b66b4b8573de1e472
3,611,434
import copy def mo_tch_asy_ts(gps, anc_data): """ Returns a recommendation via TS with Tchebychev Scalarization in the asynchronous setting for MOO """ anc_data = copy(anc_data) # Always use a random optimiser with a vectorised sampler for TS. if anc_data.acq_opt_method != 'rand': anc_data.acq_opt_metho...
3191c98a6ded0a8d5bbef5fe774f7ff39ed85c8a
3,611,435
import numbers def preprocess(inputs, seeds = []): """ Function that produces a list of FuncInput objects with respect to each input. To be used within forward() to process inputs. PARAMETERS ========== inputs : iterable type (list, np.array(), etc.) Iterable containing the input ...
45fcffa9ab1559a1f4e854a1caa5cbcfcf75ac7a
3,611,436
def trajectory_derivatives(etas, es): """ given an eta-trajectory es(etas) compute the first derivative and its absolute value as well as the second derivatives these are logarithmic derivatives: dE/dln(eta) returns: corrs: corrected trajectory, corr = E - dE/dln(eta) absd1, absd...
41adf8e9ca2a0f294fc6c5cae25941f682183eab
3,611,437
import copy def ensure_correct_degeneracies(reaction_isotopomer_list, print_data = False, r_tol_small_flux=1e-5, r_tol_deviation = 0.0001): """ given a list of isotopomers (reaction objects), returns True if the correct degeneracy values are detected. False if incorrect degeneracy values exist. T...
790772d85463df3a59fda210952496067226d79f
3,611,438
import re def run_io_in_bg(pod_obj, expect_to_fail=False): """ Run I/O in the background Args: pod_obj (Pod): The object of the pod expect_to_fail (bool): True for the command to be expected to fail (disruptive operations), False otherwise Returns: Thread: A threa...
0713ddbe13d5cc2aa8371468cb14d0f44f291edb
3,611,439
import numpy def glexsort( keys: numpy.typing.ArrayLike, graded: bool = False, reverse: bool = False, ) -> numpy.ndarray: """ Sort keys using graded lexicographical ordering. Same as ``numpy.lexsort``, but also support graded and reverse lexicographical ordering. Args: keys: ...
661205de37617c0401527673f4884ec451f9d7d3
3,611,440
def vector_norm(x): """computes the L2-norm along axis 1 (e.g. genes or embedding dimensions) equivalent to np.linalg.norm(A, axis=1) """ return np.sqrt(np.einsum("i, i -> ", x, x))
e44cff1b7f8a1df1583ed6311e458cf948f1cf66
3,611,441
def _validate_node(node): """Validate the local, or username, portion of a JID. :raises InvalidJID: :returns: The local portion of a JID, as validated by nodeprep. """ try: if node is not None: node = nodeprep(node) if not node: raise InvalidJID('Lo...
3dea0dd184baace58cb0276e3ecf51b3d8b9904c
3,611,442
import requests import json def get_blogs(keywords, client_id, client_secret): """ Naver 검색-블로그 api를 사용해서 특정 키워드에 대한 Blog 정보 수집 :Params list keywords : 키워드 리스 :Params str client_id : Api 사용 아이디 :Params str client_pw : Api 사용 비밀번호 :return blogs_items : Api 검색 결과 중 블로그 아이템들 :rtype list "...
b44a17e0af8d0cac32fbcf2ead2cfc3fa9a05d19
3,611,443
from typing import Union from typing import List def pull_team_ids(game_id: str) -> Union[int, int, bool, List]: """ This function pulls the JSON file for a game's play-by-play data and converts it into a Pandas DataFrame @param game_id (str): 10-digit string \ that represents a unique game. The format i...
2126187c61f78f93dbfea8bc1d3bf409a0e2f74f
3,611,444
from parametertransform import donothing def generate_full2vc(model, times, icell=None, set_parameters=None, return_parameters=False, return_voltage=False, add_linleak=False, transform=None, fakedatanoise=20.0): """ Generate synthetic data Input ===== model: Pints forward model ...
30228f4597aa3dee56d706db4bec901fc6c9e9e8
3,611,445
def get_lazy_args(argval, request_or_item): """ Possibly calls the lazy values contained in argval if needed, before returning it. Since the lazy values cache their result to ensure that their underlying function is called only once per test node, the `request` argument here is mandatory. :param re...
7195d8d1bc9e3214c2acddc416bb27e00e124eda
3,611,446
from typing import Union def parse_scan_interval(scan_interval: Union[timedelta, str]) -> timedelta: """Parse and validate scan_interval.""" if isinstance(scan_interval, str): if isinstance(scan_interval, str): if scan_interval.lower() == "none": scan_interval = None ...
c9efd8415a3857bc578a6cddcc27dcdce555f848
3,611,447
def closest_point(geom1,geom2): """ Use the PostGIS function ST_ClosestPoint() to return the 2-dimensional point on geom1 that is closest to geom2. This requires PostGIS 1.5 or newer. """ cursor = connection.cursor() query = "select st_asewkt(ST_ClosestPoint('%s'::geometry, '%s'::geometry) ) ...
5dbc97ca3d80b5fb73fc7b0b1e711b25a280f88a
3,611,448
def prepare_arguments_for_callable(combination_of_reactant_species, reactant_string_list, rate_function_arguments): """ This function prepares the requested arguments to the rate function for a given reaction by creating objects of the Specific_Species_Operator class Parameters: ...
af5cb45848e4658ef3eb5a9425157b6e79ebb127
3,611,449
import os def set_context(args, rank_size): """set context""" if rank_size > 1: if args.device_target == "Ascend": device_id = int(os.getenv('DEVICE_ID')) context.set_context( mode=context.GRAPH_MODE, device_target=args.device_target, ...
b3f488e8f5ca748a1364b2faed7ed1c2fdd2b5b2
3,611,450
def image_tag(): """used to deploy a particular tag of a Docker image. May return: - a commit - a branch name such as `approved` - the conventional `latest`""" revision = cfg('project.revision') if revision == 'master': return 'latest' # conventionally stable Docker tag if n...
20c4ef78e1a6899aa2005bb46d4a83e2ee53925f
3,611,451
from astropy.cosmology import WMAP9 as cosmo from astropy.cosmology import Planck15 as cosmo from astropy.cosmology import FlatLambdaCDM def cosmoScale(redshift, WMAP9=True, H0=69.3, Om0=0.287, Planck15=True): """ Get the Angular Scale (kpc/") at redshift=z. This is simply a wrapper of ast...
486736ee919b13c376e5c5bc2344d4126ff626f8
3,611,452
def getUserInterfaceHandlers(): """ Parse the UI handlers and create routes. Assert that the route is specified. """ NO_ROUTE_SPECIFIED = "The class {0} did not specify its route." handlers = [] for func in [eval("user_interface." + f) for f in dir(user_interface) if "Handler" in f an...
377999b50888ccd3eed7c8c57ce9421e7c378ee8
3,611,453
def prepare_const(): """ Using a function to prepare the const we need. :return: this file's const """ const = Const() const.SRC_FILE_NAME = '' const.DES_FILE_NAME = '' return const
bd3e4ed9496105fcb34c4601ee9d77d1adb72edf
3,611,454
def _write_function(schema): """Add a write method for named schema to a class. """ def func( data, filename=None, schema=schema, id_col='id', sequence_col='sequence', extra_data=None, mtype=None, **kwargs): # Use generic write class to...
e5fe05b39ee24848d98336545e0ee1216fb9804d
3,611,455
def is_valid_tag(tag): """Only some tags are acceptable in the whoosh schema, this function checks if the tag is acceptable. """ try: Schema(**{tag: TEXT}) except FieldConfigurationError as e: return False, e.args[0] else: return True, 'OK'
faf1ef03f39cdfc61831004f55d3ff7abd35e1b7
3,611,456
def plot_trend(timeSeries, **kwargs): """ Plot trand of a time series Parameters: -------------------------------------------------------------------- * timeSeries: list of float data * `ax` [`Axes`, optional]: The matplotlib axes on which to draw the plot, or `None` to create a ne...
efab9db10b06c5c42d42136dbaebbfca2d9599f8
3,611,457
from typing import Dict from typing import Union from typing import Any def parse_pr(pr_txt: str) -> Dict[str, Union[dt.date, int, Dict[str, Any]]]: """Parses each section of the daily COVID-19 report and places everything in a single object. """ new_cases, new_deaths = _get_new_cases_deaths(pr_t...
08d04ad28c3423286889def81e3cc1892ff5446f
3,611,458
def np_linspace(start: float = 0, stop: float = 0, num: int = 50, endpoint: bool = True, retstep: bool = False, dtype: np.dtype = None): """ returns a numpy linear space. Refer to numpy linspace function for argument description Parameters ---------- start : float stop : float n...
9b618e06775667b67651fe0337ae72254e1630e7
3,611,459
def read_image(image_path: str): """ Loads image as numpy array from given path. """ # read image image = cv2.imread(image_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # return image return image
aa89930ff7fcdf500d807f89a9cdf1d092a2a5c1
3,611,460
import httpx async def fetch_posts(names_dict): """Fetch dict of posts.""" results = {} async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as async_client: async with trio.open_nursery() as nursery: for label, name in names_dict.items(): assembler = partial(_assemble...
89c322dd413a1ffa054f155eef3ed333d631e0f3
3,611,461
def area(box): """Calculates area of a given bounding box.""" return float((box[1][0]-box[0][0]) * (box[1][1] - box[0][1]))
3c2fac0d92c8b9cc05dff3cba59d2a83670392e0
3,611,462
def get_world_transform(axes): """ Get the transformation to world coordinates. If the axes is a `wcaxes.WCSAxes` instance this returns the transform to the ``'world'`` coordinates, otherwise it returns the transform to the matplotlib data coordinates, which are assumed to be in world coordinates. ...
bbc0d9f3950ddce86f10ba7c7aadfc1725c18f0e
3,611,463
import os import platform def validate_can_run(): """ Returns False if CI_PROJECT_DIR exists and platform is Windows, and True otherwise. """ if 'CI_PROJECT_DIR' in os.environ and platform.system() == 'Windows': return True return True
e7eb6f7aef4538291c7031d8863a71b51538cbe0
3,611,464
def get_symbol(x): """ Return an appropriate symbol to use for MyBayes, always returning the same symbol for the same input. """ if x in _sym_map: return _sym_map[x] else: sym = _possible_symbols.pop(0) _sym_map[x] = sym return sym
b5f078efe60a88fad1787afda6ed221af01e6cab
3,611,465
def retrieve_shared_secret(service, attempts=3): """ Retrieve the shared secret for a service from the distributed key value store. If it can't be retrieved or is empty, retry it a couple of times just in case there is no consensus in the cluster. If we re-create a new secret we split the networ...
fecfc124f24822a563b387c85e5e30863d1909d7
3,611,466
def densecrf3d(I, P, param): """ input parameters: I: a numpy array of shape [D, H, W, C], where C is the channel number type of I should be np.uint8, and the values are in [0, 255] P: a probability map of shape [D, H, W, L], where L is the number of classes type of P shoul...
0e8693d6342d0b3bf32e537dc38f2c73e901fb24
3,611,467
def isolated_40(): """ Real Name: b'Isolated 40' Original Eqn: b'INTEG ( isolation rate symptomatic 40+isolation rate asymptomatic 40-isolated recovery rate 40\\\\ -isolated critical case rate 40, init Isolated 40)' Units: b'person' Limits: (None, None) Type: component b'' """ retur...
1d9e24d56607aa08f3bbd728fe00f9b7fa96e8d1
3,611,468
def intersect_bed(file_a, file_b, u=False, v=False): """ function intersect bed files and return new intersection bed file paramenters: file_a=path to a bed (str) file_b=path to b bed (str) u=unique intervals (bool) v=not matching intervals (bool) """ a_obj = BedTool(file_a) ...
43d819745f63cff627fad56f3dbc0a73e268fd73
3,611,469
def funequal(x, y): """Utility for `equal_dimensions`. # Arguments x: Tensor or variable. y: Tensor or variable. # Returns A tensor """ new_y = zeros([1, 1, 1, 1]) new_y = set_subtensor(new_y[:, :, :-1, :-1], y) return new_y
2068cc3eacdc958b6eafaccc31b4b6abd6f92728
3,611,470
def sentence_to_token_ids(sentence, word2id): """ Gets token id's of each word in the sentence and returns a list of those words. Is called by data_to_token_ids and the Lexer. Args: sentence: A list of word tokens. word2id: A dictionary that maps words to its given id. This c...
e5ce8510574a40ac761beae2596d7e04873b9b1e
3,611,471
def drawxband(refval, xlims=None, color='gray', bandwidths=[-0.1, 0.1], ua=None): """ draw a shaded band of color color of certain width around a single reference value refval Parameters ---------- refval : float , mandatory scalar...
201ec73ae9402423e1b4d834f440f8d07a06d3b8
3,611,472
def change_control_mode(requested_mode): """ Change the controller mode of the DP controller. Although this is technically breaking the design idea that FSM and controller should not talk to eachother, it makes sense to keep it for now, seeing as some guidance systems may rely on one of the con...
2196a22a8620182c1e142488ec4fa2b41d927d54
3,611,473
def _treat_outliers(data: "DataFrame", n_quantiles: int = 4) -> "DataFrame": """Find and edit outliers based on quantiles.""" q_low = data.quantile(1 / n_quantiles) q_high = data.quantile((n_quantiles - 1) / n_quantiles) iqr = q_high - q_low # interquartile range # Either: Flooring and capping. ...
72f13aa11249bd3ea7aaae76a30687dda12ab555
3,611,474
def load_word_embedding(vectors_file): """ Load the word vectors""" vectors= np.genfromtxt(vectors_file, delimiter='\t', comments='#--#',dtype=None, names=['Word']+['EV{}'.format(i) for i in range(1,51)]) #51 is embedding length + 1, change accoridngly if the size of embedding is not ...
f71d36e3e4dc13c1d1c8f2490f856767ebda33df
3,611,475
def dtype_to_ome_type(npdtype: np.dtype) -> PixelType: """ Convert numpy dtype to OME PixelType Parameters ---------- npdtype: numpy.dtype A numpy datatype. Returns ------- ome_type: PixelType One of the supported OME Pixels types Raises ------ ValueError ...
b948c82a9cc265a922cb10453311adf3ace666f5
3,611,476
def get_fps_points(): """key is str(obj_id) generated by core/gdrn_modeling/tools/hb/hb_1_compute_fps.py.""" fps_points_path = osp.join(model_dir, "fps_points.pkl") assert osp.exists(fps_points_path), fps_points_path fps_dict = mmcv.load(fps_points_path) return fps_dict
7c52cc7676707104353085e3230be53d22b99d2a
3,611,477
import os def Generate_Raven_Timeseries_rvt_String( outFolderraven, outObsfileFolder, obsnm, Model_Name ): # Modify_template_rvt(outFolderraven,outObsfileFolder,obsnm): """Generate a string in Raven time series rvt input file format Function that used to modify raven model timeseries rvt file (Model_Na...
a200bc7e350278b78018cf014ea948b98d56b0f5
3,611,478
def insert_clause(table_name, keys): """ Create a insert clause string for SQL. Args: table_name: The table where the insertion will happen. keys: An iterator with strings specifying the fields to change. Returns: The query as a string """ fields...
7c57bff8dec2242ed2ba1c7efa7543296ce1242f
3,611,479
def knn_graph_quantile(mat, self_loops=False, k=8, symmetric=True): """ Takes an input correlation matrix and returns a k-Nearest Neighbour weighted undirected adjacency matrix. """ if not (mat.shape[0] == mat.shape[1]): raise ValueError("Adjacency matrix must be square.") dim = mat.sh...
95a966270bbfb9da188e7534a70c4f7966041fa0
3,611,480
import os def createLocalRealm(user, domain): """ Administra localmente las claves publicas/privadas """ try: print("[] Generating pair keys...") publicKey, privateKey = crypto.PairKey(plain=True) print("[] Saving keys ...") save(constant.USER_PUBLIC_KEY.format(user), publicKey...
2560fa3d5338c3f55bec8e0131ee6a8fc574dd7d
3,611,481
def strip_non_alpa(text): """ Strip string from non alpha caracters """ letters = [] for let in list(text): if let.isalpha(): letters.append(let) return letters
131e48d7782a5949855c0391669da4413c293801
3,611,482
def uniform_weight(labels, inputs): """apply same weight to every voxel/example""" return tf.constant(1.0)
ea120af3d49e825a8979925c48f35bf22d34658a
3,611,483
import json def handler(event, context): """ Returns all of the Vulnerabilities """ vulnerabilities = dynamodb.query( table_name=table_name, query=Key('category').eq('vuln'), ) if vulnerabilities: vulnerabilities = sorted(vulnerabilities, key = lambda i: i['count'], rev...
1f27454604a073562966722842fbb8e819669f86
3,611,484
def Normal_logZ(mu, cov): #tested """ compute the log normalizing constant of a normal distribution given a mean vector and a covariance *vector arguments mu : jnp.array(Dx) mean vector cov : jnp.array(Dx) covariance vector returns logZ : float ...
5d97d4cb343fc9e251ad7983c9197a4815679c0b
3,611,485
def implicit_euler(xs, h, y0, f, **derivatives): """Implicit Euler""" ys = [y0] for k in range(len(xs) - 1): subsidiary_y = ys[k] + f(xs[k], ys[k]) * h next_y = ys[k] + f(xs[k + 1], subsidiary_y) * h ys.append(next_y) return ys
3700ceef618dfb8485486f2b9c5695af1483ffd2
3,611,486
from reportlab.platypus.doctemplate import randomText from random import randint def getSampleStory(depth=3): """Makes a story with lots of paragraphs. Uses the random TOC data and makes paragraphs to correspond to each.""" styles = getSampleStyleSheet() TOCData = getSampleTOCData(depth) story ...
fcbf95bc45a17d03653fcf4856ab0687e338a487
3,611,487
def gen_pca_system(l, q): """make random PCA linear system Parameters ---------- l : {int} dimension of observations q : {int} dimension of PC system Returns ------- :class:`~numpy:numpy.ndarray` shape `(l, )` array of eigenvalues :class:`~numpy:numpy.nd...
c13de529aaeca80afeb6bd801c4479baa2dfb71c
3,611,488
def autoconfirm(*param_decls, **kwargs): """Add a ``--yes`` option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit. :param param_decls: One or more option names. Defaults to the single value ``"--yes"``. :param kwargs: Extra arguments are passe...
169e49755b5f1de3c28bd745f37018aff1d2c2bf
3,611,489
def hidden_shift(nbits=6, expected_output=None, measure=True): """ Nbits should always be even. This is a nbit hiddenshift algorithm that finds the hidden shift string "s" for which f(x) = f(x + s) reference: https://www.pnas.org/content/114/13/3305.full """ if expected_output is Non...
dd35ac70e50adfed272383482a4b6e00d14a3083
3,611,490
import math def getEdgeMask(match_array, hull_concavity=0.5, crop=None, res=None, min_data_cluster=1000): """ Return an array masking ON bad edges on a mass of good data (see Notes) in a matchtag array. Parameters ---------- match_array : ndarray, 2D Binary array to ma...
c3e71eed435143f1e9aa5d3b3a7cc9fa1a7ee103
3,611,491
def resnet3d50(num_classes=339, pretrained=True, **kwargs): """Constructs a ResNet3D-50 model.""" model = modify_resnets(ResNet3D(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, **kwargs)) if pretrained: model.load_state_dict(load_checkpoint(weights['resnet3d50'])) return model
1b4e4c194e2f95d444a766855fa3ca05a9ca92d9
3,611,492
def get_encrypted_picture_from_string(encrypted_picture_str): """ :param user: str, ID of the user who ask for authentication for retrieving the linked encrypted picture :return: numpy.ndarray, ecnrypted picture linked to the user account """ if isinstance(encrypted_picture_str, str) is False: ...
781b0da05014e7ce734a038ff93267bc396e2d66
3,611,493
from functools import reduce def _graham_scan(points): """Returns points on convex hull of an array of points in CCW order.""" points.sort() lh = reduce(_keep_left, points, []) uh = reduce(_keep_left, reversed(points), []) return lh.extend(uh[i] for i in xrange(1, len(uh) - 1)) or lh
dc3237e7a04495b4a6beeb001a4515ac65b12ee4
3,611,494
from typing import Iterator def coin_partitions(n, coin_types=COINS_AMOUNT) -> Iterator[list[int]]: """ Yields number n partitions using 1, 2, 5, 10, 20, 50, 100 and 200. Partition i represented as 8 element array showing amount of every cons: [0, 1, 2, 0, 0, 0, 0, 1] = 207. """ def update_pa...
187b0aa8c042165e6199f3a03f4739b32031f671
3,611,495
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) return model if pretrained is False else load_pretrained(model, 'resnet18')
f073d1c2a159ad1749297baeadc533c974b7ab2a
3,611,496
import requests from bs4 import BeautifulSoup def get_the_content(url, date): """ 컴퓨터 공학과 홈페이지 내용들 가져오기. """ ret = [] res = requests.get(url) soup = BeautifulSoup(res.content, "html.parser") update = soup.select('div.total-wrap > span') ret.append("오늘 업데이트 된 게시글 : " + update[1].text) fi...
2f25ca0a877ad8e801992d1ddc2b92c558dc7851
3,611,497
def MergeBaseClass(cls, base): """Merge a base class into a subclass. Arguments: cls: The subclass to merge values into. pytd.Class. base: The superclass whose values will be merged. pytd.Class. Returns: a pytd.Class of the two merged classes. """ bases = tuple(b for b in cls.bases if b != base)...
713801316e2c6dde799b9c57b7e2e513d1bc6352
3,611,498
def chart_data_to_df(func): """获取df""" @wraps(func) def inner(self, *args, **kwargs): if self.df.empty: columns = ["datetime", "open", "high", "low", "close", "volume"].extend(self.extend_field) self.df = pd.DataFrame(self.list_dict, columns=columns) return func(self,...
6164835b9943cfc6711202aa46baa48558da83cf
3,611,499