content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from pathlib import Path def fssurf_to_gifti(surf, fn=None): """ Converts FreeSurfer `surf` surface file to GIFTI format Parameters ---------- obj : str or os.PathLike FreeSurfer surface file to be converted fn : str or os.PathLike, None Output filename. If not supplied uses i...
70e4709d9941da2db9b55702063503c1f692beb4
49,488
def dihedral_ranking_score(structure, residues, sec_struct_column="sec_struct_3state", original=True): """ Assess quality of structure model by twist of predicted alpha-helices and beta-sheets. This function re-implements the functionality of make_alpha_beta_score_table....
358141dce6678a25f89fc3660ae61eba6140cd77
49,489
def kernel(request): """Console kernel fixture""" # Get kernel instance kernel = get_kernel() kernel.namespace_view_settings = {'check_all': False, 'exclude_private': True, 'exclude_uppercase': True, ...
5f7937e5b307048cb28c38bde5c5fea7f38e35d0
49,490
from typing import Counter def character_replacement(s: str, k: int) -> int: """https://leetcode.com/problems/longest-repeating-character-replacement""" counter = Counter() left = 0 max_length = 0 current_max_frequency = 0 for right, char in enumerate(s): counter[char] += 1 cu...
ad67c5fbff990c0701d0c487b5aa6832d8bc2691
49,491
def build_sampler(tparams, options, use_noise, trng, sampling=True): """ Builds a sampler used for generating from the model Parameters ---------- See build_model function above Returns ------- f_init : theano function Input: annotation, Output: initial lstm state and memory ...
7ab927b5efd202841a4fe4a53338f0f2e9deb41a
49,492
import hashlib import time def generate_tag_version(): """ Generates a new unique identifier for tag version.""" hash_value = hashlib.md5("{0}{1}{2}".format( randrange(0, MAX_TAG_KEY), get_thread_id(), time.time() ).encode('utf8')).hexdigest() return hash_value
a74389b2ede195d80887c18cd963bcf0fbe13f98
49,494
def _stem_words_list(list_words): """Stem words using a nltk stemmer :param list_words: A list of strings representing words to stem :rtype: A list of strings representing stemmed words """ stemmer = snowball.SnowballStemmer('english') list_words_stemmed = {_stem(stemmer, word) for word in list...
a10cacc95e84b0abde38b2fa15a864b9cb8587c7
49,495
def read_data(location, type): """ This helps us read various filetypes directly into pyspark datframes. This is an allround solution. """ ftype = { 'avro' : "com.databricks.spark.avro", 'parquet' : "parquet", 'csv' : "com.databricks.spark.csv", 'json' : "json" } ...
4cc63fe1eead340e611552fddb863062bb5faca4
49,496
from typing import Optional def get_app_user_assignments(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppUserAssignmentsResult: """ Use this data source to retrieve the list of users assigned to the given Okta application (by ID). ## E...
c5662bf77b608e6396bbd98f6521f247072e48e3
49,497
def clean_hotel_location(string): """ """ if string is not None: r = HTMLParser.HTMLParser().unescape(string) r = commons.limpieza_barras_por_espacios(r) if r.find('(') >= 0: r = r[:r.find('(')] if r.find('•') >= 0: r = r[:r.find('•')] if r.find('Chatl') >= 0: r='El Chalten' r=decutf_...
3cdaf987d4e03eaf784c48d063cec97449e43817
49,498
from spatialpandas import GeoDataFrame, GeoSeries from shapely.geometry.base import BaseGeometry def from_shapely(data): """Converts shapely based data formats to spatialpandas.GeoDataFrame. Args: data: A list of shapely objects or dictionaries containing shapely objects Returns: ...
cb8ea3c5964dd5599e18d58c370d23d5d85d7f98
49,499
def handle(req): """handle a request to the function Args: req (str): request body """ ret_str = 'Hello OpenFaas. I received the following text:\n' return ret_str + req
9d4d4957bcd05c945b3e702f311cb81b8af74d73
49,500
def rlmErr(ols, w, spDcache): """ Robust LM error test. Implemented as presented in eq. (8) of Anselin et al. (1996) [Anselin1996a]_ NOTE: eq. (8) has an errata, the power -1 in the denominator should be inside the square bracket. ... Attributes ---------- ols : OLS_dev ...
edeedf967275934cc82d82369ae3ed3d4cabbdec
49,501
import numpy def max_ts(timeseries, nodata=-9999): """Maximum value of the time series. :param timeseries: Time series. :type timeseries: numpy.ndarray :param nodata: nodata of the time series. Default is -9999. :type nodata: int :returns: Maximum value of time series. """ ts = fixs...
77044f43b6fd8cb7fc872a18f7eb551f17225e7c
49,502
def get_hole_declarations(program_vars): """Helper function for creating hole declaration with a grammar blow.""" grammar_spec = """ ( (Start Int ( (Variable Int) (+ Start Start) )) ) """ grammar = templates.load_gramar_from_SYGUS_spec(grammar_spec...
8c6f8161cd0e36447e65acb55963a5ae8cee93a9
49,503
def unit_scalar_to_str(value, n_digits=6): """ Convert a UnitScalar to a string representation to display in text box. """ dimless_labels = [None, 'dimensionless', '1'] if value is None: return "" elif isinstance(value, UnitScalar): number = value.tolist() if isinstance(numbe...
b4512432862976bdd1327dc6d72bc8b97a9d8d9d
49,504
def find_paths(iterable, searchfor, max_=0, searchtype='key', **kwargs): """Returns paths to 'searchfor'. If 'max_' is 0 all matches will be found""" return objects.FindPath(iterable, searchfor, max_, searchtype, **kwargs).paths
fb458563e09085f1ef69e1d9711ff5c8ca21fc1b
49,505
import csv def process_overlap_files(inputfiles, header): """ :param inputfiles: :param header: :return: """ cage_cov = {'+': dict(), '-': dict()} feat_count = col.Counter() skip_partial = 0 for inpf in inputfiles: with open(inpf, 'r', newline='') as infile: row...
1f8eb6856d261d4b845ee2967956180822dc92ac
49,506
def where(cond, true_vals, false_vals=None): """ Use `true_vals` where `cond` is True, `false_vals` where `cond` is False to build a merged dataset. The result will be empty where `cond` is empty. `false_vals` are optional and if not provided, this will behave nearly the same as `true_vals.filter(c...
45883feeb0cfa8b24dbd53f18981677bb921d65d
49,507
import ssl def create_ssl_context(verify=True, cafile=None, capath=None): """Set up the SSL context. """ # This is somewhat tricky to do it right and still keep it # compatible across various Python versions. try: # The easiest and most secure way. # Requires either Python 2.7.9 o...
fe8db07f3d0043224cb3ca739fa43a1e3e69fdae
49,508
def extract_domain(url): """Extract domain name from URL string""" o = urlparse(url) if o.scheme == '' and o.netloc == '': o = urlparse("//" + url.lstrip("/")) return o.netloc
98ea9dbedb095f29e231095623baf7e24756d1f4
49,509
def diamond_graph(create_using=None): """Return the Diamond graph. """ description=[ "adjacencylist", "Diamond Graph", 4, [[2,3],[1,3,4],[1,2,4],[2,3]] ] G=make_small_undirected_graph(description, create_using) return G
59909cabc48c5f7468af25ba4f045bf9440df86c
49,510
def tensor_setitem_by_tuple_with_tensor(data, tuple_index, value): """Assigns the tensor by tuple with tensor value.""" op_name = const_utils.TENSOR_SETITEM tuple_index = _transform_ellipsis_to_slice(data, tuple_index, op_name) tuple_index, not_expanded_dim = remove_expanded_dims(tuple_index, F.shape(da...
fec629b57afd7b9e3ceb1ff8dd92501f2e297b03
49,511
def arpls(y, lam, ratio=1e-6, niter=1000, progressCallback=None): """ Return the baseline computed by asymmetric reweighted penalized least squares smoothing, arPLS. Ref: Baseline correction using asymmetrically reweighted penalized least squares smoothing Sung-June Baek, Aaron Park, Young-Jin Ahn a...
94ba343ebc7ec9b039bdef2e1d1e67da2a11b521
49,512
def compressnumbers(s): """Take a string that's got a lot of numbers and try to make something that represents that number. Tries to make unique strings from things like usb-0000:00:14.0-2 """ n = '' currentnum = '' for i in s: if i in '0123456789': #Exclude...
952fe1a56a1864ce41031bb9bbea0fd440f9c3ef
49,513
async def plot_index_bar_chart(tag_dict): """ Plots the index bar chart. """ x = np.array(list(tag_dict.keys())) y = np.array(list(tag_dict.values())) plt.clf() plt.bar(x, y, color="green") plt.xticks(fontsize=7) plt.xlabel("Index", fontsize=7) plt.ylabel("Number", fontsize=7) ...
8afe547bdf55f5991b48f1f7c170e1bb5ccc3453
49,514
def _get_tile_output_shape(shape, multiples): """compute output shape of tile""" if multiples is None: return shape if not isinstance(shape, (list, tuple)): raise TypeError("Input shape of Tile must be of type list or tuple") if not isinstance(multiples, (list, tuple)): raise Ty...
ca787b55bed7591c6cf46aa6908d2c8d7053e755
49,515
from typing import Dict import copy def get_clinical_strat(params: Parameters, stratified_adjusters: Dict[str, Dict[str, float]]) -> Stratification: """ Stratify the infectious compartments of the covid model by "clinical" status, into the following five groups: NON_SYMPT = "non_sympt" As...
566d5feb02f01b7082054968c73561caa758201e
49,516
import requests import logging def service_is_ready(): """ Used to show the "Haystack is loading..." message """ url = API_QUERY_ENDPOINT try: if requests.get(url).status_code < 400: return True except Exception as e: logging.exception(e) sleep(2) # To avoi...
761bc784837767411c65ebedc8c054f156a08214
49,517
def medianfilt(img, kernel_shape): """[summary] Aplies a median filter to an image, but adds the necessary padding to mantain the aspect ratio. Args: img (numpy array): Image array. kernel_shape (tuple): Tuple indicating kernel shape. Returns: output (numpy array): processed...
666ca3aa31cea2dbc8ba1dcf80ead5c1bd6a0fd0
49,518
import typing def cik(apikey: str, cik_id: str) -> typing.List[typing.Dict]: """ Query FMP /cik/ API. FORM 13F get company name by cik :param apikey: Your API key. :param cik_id: CIK value :return: A list of dictionaries. """ path = f"cik/{cik_id}" query_vars = {"apikey": apikey} ...
1809dffd9a36a19f3d0c5c3e5069b476a7f122d3
49,519
def dec_indicator(encoded): """decode a Fudge Indicator. Returns: A Singleton INDICATOR object""" return INDICATOR
55cad8be678dd41c706c905a5d79b6e0d78cff62
49,520
def unordered_inverse(matrix): """ Takes in a matrix of values and maps each distinct row to a unique value ex [[1 2 3] becomes [1,2,1] [4 5 6] [1 2 3]] """ num_rows = matrix.shape[0] result = np.zeros((num_rows,)) state_map = dict() state_count = 0 for index,row in enumerate(matrix): row = row....
3dea723ee10375e0452d03caff64e107cea8e72e
49,522
def _build_predict_signature(input_tensor, output_tensor_x, output_tensor_y): """Helper function for building a predict SignatureDef.""" input_tensor_info = tf.saved_model.utils.build_tensor_info(input_tensor) signature_inputs = {"input": input_tensor_info} output_tensor_info_x = tf.saved_model.utils.build_ten...
481465ec77e4632cc4fd50a5c2df1f0dd83e2844
49,523
def filter_error_nodes(nodes): """Filter out ERROR nodes from the given node list. :param nodes: candidate nodes for filter. :return: a tuple containing the chosen nodes' IDs and the undecided (good) nodes. """ good = [] bad = [] not_created = [] for n in nodes: if ...
409236f4f31abaecc999fb3fbc766d138c5c3618
49,524
def ds_cnn_params(): """Parameters for toy "depthwise convolutional neural network" stride model.""" params = Params() params.model_name = 'ds_cnn' params.cnn1_kernel_size = '(3,2)' params.cnn1_dilation_rate = '(1,1)' params.cnn1_strides = '(2,1)' params.cnn1_padding = 'same' params.cnn1_filters = 4 p...
086f34623b8500dbff09a13a724f7f6eaa957b63
49,526
import csv def LoadVNSIM(nsim_csv): """Returns dictionary with degraded file key and mean nsim value. The CSV should have three values: reference path, degraded path, nsim value Args: nsim_csv: Path to CSV file with NSIM values, format described above. Returns: Dictionary with degraded file key and...
919d1dcffab7e4a78e0ced2cbeee01126d586c27
49,527
def getCharOverlapCount(from1, to1, from2, to2): """Calculates the number of overlapping characters of the two given areas.""" #order such that from1 is always prior from2 if from1 > from2: tmp = from1 from1 = from2 from2 = tmp tmp = to1 to1 = to2 to2 = tmp ...
66ea7cbc9408d41de002c96e40705d4dd45f9ad5
49,528
def getPressure(): """ Method to get the angular position of the rocket. This method is only activated when the route /getAng is accessed. Data collected here is to be directly displayed as numbers on ReactApp. """ pressure = {'PTop':PT1,'PBottom':PT2,'P3':PT3} f = open("./AvionicsData/pressure.txt","a+") f...
7ec8261c091f2f832ac31ff4e8aff7c0494bfcfa
49,529
import warnings def label_color(label): """ Return a color from a set of predefined colors. Contains 80 colors in total. Args label: The label to get the color for. Returns A list of three values representing a RGB color. If no color is defined for a certain label, the color gre...
d08bcecdcc3c48f58b879fbbfd44a973c031693a
49,530
from pathlib import Path def file_path(cfg): """ Return the directory containing the description files as an absolute path. Returns None if the configuration does not define this. """ try: desc_path = Path(cfg['descriptions_dir']) except KeyError: raise ConfigKeyMissingError('...
34e8fb69fabdc6f014d52dbaf2b978dfb9022a9a
49,531
def angle_average(galactic_frame_func): """ @returns Angle-averaged function """ @np.vectorize def angle_averaged(v_galactic_frame): """ @returns Angle-averaged evaluation of function """ v = v_galactic_frame * np.ones_like(COS_THETA) integrand = galactic_fram...
9964a21289e400dc1f147cb4a8bc625c7e1fe5ea
49,533
def create(): """Create new event.""" form = CreateEventForm(request.form, csrf_enabled=False) print ("form received") if form.validate_on_submit(): print ("valid") RecEvent.create(title=form.title.data, date=form.date.data, time=form.time.data, location=form.loca...
71751dcae0db1b7fc70784ad6fae3fc7e22bbd18
49,534
def get_version(): """ Obtain the version of the ITU-R P.1853 recommendation currently being used. Returns ------- version: int Version currently being used. """ global __model return __model.__version__
87eb4e26e20089976e5863b65c7457e91c6844ed
49,535
def _random_bernoulli(shape, probs, dtype=tf.int32, seed=None, name=None): """Returns samples from a Bernoulli distribution.""" with tf.name_scope(name, "random_bernoulli", [shape, probs]): probs = tf.convert_to_tensor(probs) random_uniform = tf.random_uniform(shape, dtype=probs.dtype, seed=seed) return...
ba60cecbcc0ac7698839e6bb60f2ebdd0b698c59
49,539
import re def tokenize(text): """Return tokenized form of text Parameters ---------- text : str string to be tokenized Returns ------- list tokens of string text """ # Normalize and remove punctuations and extra chars such as (, # text = re.sub(r'[...
3f360e4fa253249e65ce66cdcdc292d99f344610
49,540
import string import csv def ReadData(name): """ Reads data from several files. """ f = open('%s-n.txt' % name,'rt') n = string.atoi(f.readline()) f.close() gammas = [] f = open('%s-gammas.csv' % name,'rt') for row in csv.reader(f,quoting=csv.QUOTE_NONNUMERIC): ...
24116b6fe7e1bcc0c003a4717520aa539dd7f3a0
49,541
from typing import Optional from typing import List def split_and_strip_without( string: str, exclude, separator_regexp: Optional[str] = None ) -> List[str]: """Split a string into items, and trim any excess spaces Any items in exclude are not in the returned list >>> split_and_strip_without('fred, ...
14d4496679a1c759e8f2752c8e6b052a810ba8ea
49,542
def _current_season(): """Return the current NHL season""" endpoint = "seasons/current" data = _api_request(endpoint) if data: season = data['seasons'][0]['seasonId'] return season else: raise JockBotNHLException('Unable to retrieve current NHL season')
df8ab4d7df4fc4071a4738eaea398f24b9c5cd9f
49,543
from typing import Tuple def load_file(path: str) -> Tuple[TestCase, ...]: """Load test cases from a file. Parameters ---------- path : str File path. Returns ------- Tuple[TestCase, ...] Test cases. """ with open(path, "r") as file: return tuple( ...
127bda88dc5aa98690a6f6bb7e5d793f3db7ac99
49,544
def get_interfaces(): """ Returns a list of your computer's IP configuration: ['lo0', 'gif0', 'stf0', 'XHC20', 'en0', 'p2p0', 'awdl0', 'en1', 'bridge0', 'utun0'] """ interfaces = netifaces.interfaces() return interfaces
7b8837c221f02baa70c6e6c3b848e8444f6daf50
49,545
import re def clean_python_name(s): """Method to convert string to Python 2 object name. Inteded for use in dataframe column names such : i) it complies to python 2.x object name standard: (letter|'_')(letter|digit|'_') ii) my preference to use lowercase and adhere ...
d77eaa81607aabf8cae62e2a9c36a51e8428aac4
49,546
import tempfile def mktemp_dump(data): """Create a temporary file under the current plugin tmp directory and write data to the file. """ ftmp = tempfile.mktemp(dir=HotSOSConfig.PLUGIN_TMP_DIR) with open(ftmp, 'w') as fd: fd.write(data) return ftmp
80dd7c499c6a27b1aabb90d42234f28483b7915b
49,549
def get_leagues_by_team(team_ids): """ https://developer.riotgames.com/api/methods#!/985/3352 Args: team_ids (str | list<str>): the team ID(s) to get leagues for Returns: dict<str, list<League>>: the team(s)' leagues """ # Can only have 10 teams max if it's a list if isinst...
004cb182ca85062b6552224eea35423313348fdb
49,550
def generate_asset_name (asset_id, block_index): """Create asset_name from asset_id.""" if asset_id == 0: return config.BTC elif asset_id == 1: return config.XCP if asset_id < 26**3: raise exceptions.AssetIDError('too low') if enabled('numeric_asset_names'): # Protocol change. if ...
5937da288062d9d9f98894e4534c3bd36feef3a3
49,551
from typing import Deque def parse_object(tokens: Deque[Token]) -> JSONObject: """Parses an object out of JSON tokens""" obj: JSONObject = {} # special case: if tokens[0].type == 'right_brace': tokens.popleft() return obj while tokens: token = tokens.popleft() if...
f7d7ac489dd03c04e6820f430c9d6cd09376c222
49,552
def calc_Asym_vs_emin_energies(det_df, dict_index_to_det, singles_hist_e_n, e_bin_edges_sh, bhp_nn_e, e_bin_edges, emins, emax, angle_bin_edges, plot_flag=True, show_flag = False, save_flag=True): """ Calculate Asym for variable emi...
4fb19fee0af8f1a2c9425e59c2634f8b49b72978
49,553
def get_best_of_n_avg(seq, n=3): """compute the average of first n numbers in the list ``seq`` sorted in ascending order """ return sum(sorted(seq)[:n])/n
6166bbeda10d81356a86151901f33a26f0ff1035
49,554
def py2_earth_hours_left(start_date=BITE_CREATED_DT): """Return how many hours, rounded to 2 decimals, Python 2 has left on Planet Earth (calculated from start_date)""" return round((PY2_DEATH_DT - start_date) / timedelta(hours=1), 2)
e958cfbcbe3f1d6d6c00e52a26c9dd4591b7c0f0
49,556
from typing import Dict from typing import Tuple def merge_model_results(results: Dict[str, Dict[Tuple[str, int], pd.DataFrame]]) -> pd.DataFrame: """ Combine the results of running :func:`util.analyze_model` across a corpus into a single dataframe. :param results: Mapping from model name to dict...
f231d47bca582158ac09065966bad83ea3427a02
49,557
def _float_feature(value): """Wrapper for inserting float features into Example proto.""" return tf.train.Feature(float_list=tf.train.FloatList(value=value))
2d286fd444e16fac47f76507cd68be99919346fe
49,558
def valid_bytes_128_after(valid_bytes_48_after): """ Fixture that yields a :class:`~bytes` that is 128 bits and is ordered "greater than" the result of the :func:`~valid_bytes_128_after` fixture. """ return valid_bytes_48_after + b'\0' * 10
03e39e1b2d58b97184b30d57367ef5ca5b636f0e
49,559
def const_coeffs(s=0.0, py=0.0, pz=0.0, px=0.0): """ Creates coefficients for seperated tunnelling to each orbital. The energies are set to zero. """ cc = np.array([s, py, pz, px]) != 0.0 coeffs = np.empty((sum(cc),4),) ene = np.zeros(sum(cc)) if s != 0.0: coeffs[sum(cc[:1])-1] ...
634d56731cdc07f28819a0e560193010457152cf
49,560
from re import VERBOSE import math def calcIntraElectroHydrophobic(pdb, interface, depthDistances): """ Calculated possible electro interactions, excluding 1-2 and 1-3 interactions (already included in angle and bond interactions """ HYDROPHOBIC_CHARGED_CUTOFF_DISTANCE = 6 # we could have 6? ...
a35674c36467d07c9225ae94bbc5f255a3d9c550
49,561
def positional_encoding(position: int, d_model: int) -> tf.Tensor: """Returns the positional encoding for a given position and timestamp""" angle_rads = get_angles(np.arange(position)[:, np.newaxis], np.arange(d_model)[np.newaxis, :], d_model) # apply...
294281053a256d95b27066499909ec9bd78c4000
49,562
from typing import List def add_multiple_of_row_of_square_matrix(matrix: List[List], source_row: int, k: int, target_row: int): """ add k * source_row to target_row of matrix m """ n = len(matrix) row_operator = make_identity(n) row_operator[target_row][source_row] = k return multiply_matr...
2ff7a31e0c52a34973510661a8e266f8c10abfcb
49,563
import torch def shadow_mapping(cam_results, light_results, rays, ppc, light_ppc, image_shape, batch_size, fine_sampling): """ cam_result: result dictionary with `depth_*`, `opacity_*` light_result: result dictionary with `depth_*`, `opacity_*` rays: generated rays ppc: [Batch_size] Camera Poses:...
8ff43760a1b09900edd70e5a9f0171d83ad756cf
49,564
def get_panelists(): """Retrieve a list of panelists and their corresponding information""" return panelists.get_panelists(database_connection)
db6ac71d72d3ac53f38c484a09c9ac91e3ac2ecb
49,565
def count_distinct_col(curs, table_name, col='y'): """Queries to find number of distinct values of col column in table in database. Args: curs (sqlite3.Cursor): cursor to database table_name (str): name of table to query col (str): name of column to find number of distinct values fo...
c346b8463eeb4faec645917831f7bde8f42ed5e1
49,566
def reduce_dataset_by_column_value(df, colname, values): """Returns the passed dataframe, with only the passed column values""" col_ids = df[colname].unique() nvals = len(col_ids) # Reduce dataset reduced = df.loc[df['locus_tag'].isin(values)] # create indices and values for probes new_ids...
ee8411dd5e1152b1ae1a9b78a70396c03a0c0f7c
49,569
def limitsSql(pageToken=0, pageSize=None): """ Takes parsed pagination data, spits out equivalent SQL 'limit' statement. :param pageToken: starting row position, can be an int or string containing an int :param pageSize: number of records requested for this transaciton, can be an int or...
9b188d405afb0c367a5f61b46c50a7c7a63e4879
49,570
def split(df): """ Splits the given dataframe into a 8/2 split for training and testing :param df:the dataframe you want to split :return: """ training, test = train_test_split(df, test_size=0.2, random_state=42) train, val = train_test_split(training, test_size=0.2, random_state=42) re...
0b4e99332a25ccc971abf099d90f3c8466741019
49,572
def test_wait_within_timeout(): """Test that we can wait for a job terminating before timeout. """ i = 0 def cond(): nonlocal i j = i i += 1 return j job = InstrJob(cond, 0) assert job.wait_for_completion(refresh_time=0.01) assert i == 2
48e01ca620829294e21aa54da0b0a811d89d2c52
49,573
def module_method(fn): """Decorates a function as a module method. The `module_method` allows modules to have multiple methods that make use of the modules parameters. Example:: class MyLinearModule(nn.Module): def apply(self, x, features, kernel_init): kernel = self.param('kernel', (x.shap...
02f0d422e0ca6352d56d6e3e9b05b1f288f55762
49,577
import re def add_http_if_no_scheme(url): """Add http as the default scheme if it is missing from the url.""" match = re.match(r"^\w+://", url, flags=re.I) if not match: parts = urlparse(url) scheme = "http:" if parts.netloc else "http://" url = scheme + url return url
ea7799616c0616fda85814139b7a36264cbc9e40
49,582
def _check_half_window(half_window, allow_zero=False): """ Ensures the half-window is an integer and has an appropriate value. Parameters ---------- half_window : int, optional The half-window used for the smoothing functions. Used to pad the left and right edges of the data to redu...
4e40b307242f3c1137251903b227144a4deb53d6
49,583
async def get_run_controller( runId: str, task_runner: TaskRunner = Depends(get_task_runner), engine_store: EngineStore = Depends(get_engine_store), run_store: RunStore = Depends(get_run_store), ) -> RunController: """Get a RunController for the current run. This ensures that a run exists and i...
10e08c4096764ee2e181083699d353edea551409
49,585
import io import click def get_pixel_ratio(img, img_path): """ Tries to read file metadata from dm file. If normal .tif images are provided instead, prompts user for the nm/pixel ratio, which can be found using the measurement tool in ImageJ or similar. For example, a scale bar of 100nm corresponds to...
5d50e4b4db7620256d62f359fca8608216a54b95
49,586
def gauss_kern(size, sizey=None): # smooth test """ Returns a normalized 2D gauss kernel array for convolutions """ size = int(size) if not sizey: sizey = size else: sizey = int(sizey) x, y = np.mgrid[-size:size+1, -sizey:sizey+1] g = np.exp(-(x**2/float(size)+y**2/float(sizey))...
ea0d9a4266942ae4e40d6815d6391ac4532ad808
49,587
def full_clean(string_in): """Call of my string cleaning functions in order""" #print('string_in = %s' % string_in) if string_in is None: return string_in elif type(string_in) == unicode: string_in = string_in.encode('UTF-8') elif type(string_in) not in [str, unicode]: return...
d4325f997bcf0c71d569155d72240ae7d11661de
49,588
def partitioned_variable_assign(partitioned_var, new_value): """Assign op for partitioned variables. Args: partitioned_var: A partitioned tensorflow variable new_value: Value to be assigned to the variable var Returns: A tensorflow op that groups the assign ops for each of the variable slices """ ...
f61f32ee5c948a1efe82ec329472eb841a4d8b78
49,589
from typing import Optional from typing import Set def process_df( df: pd.DataFrame, version: Optional[str] = None, skip_databases: Optional[Set[str]] = None, ) -> DGIProcessor: """Get a processor that extracted INDRA Statements from DGI content based on the given dataframe. Parameters --...
c63489b20073eda59cf15cb96e3fcfd5499a9efc
49,590
def coerce_levels(image_numpy, levels=255, method="divide", reference_image = [], reference_norm_range = [.075, 1], mask_value=0, coerce_positive=True): """ In volumes with huge outliers, the divide method will likely result in many zero values. This happens in practice quite often. TO-DO: find a b...
9bf458c551d71a7d43841209d2e5d3aad5d6da15
49,591
from typing import List def merge_and_count(ll: List[int], lr: List[int]) -> (int, List[int]): """ :param ll: :param lr: :return: >>> merge_and_count([1, 2, 4], [3, 5]) (1, [1, 2, 3, 4, 5]) >>> merge_and_count([1, 2, 6], [3, 5]) (2, [1, 2, 3, 5, 6]) """ result = [] coun...
b513ce03b317a2cc5332aa3c50abd612380b08b6
49,592
def get_ap_bboxes(img, model, dataset_name, verbose=False): """ Detect appearance based foreground bounding boxes on a frame by a pre-trained object detector. Args: img (ndarray): The frame to be detected. model (nn.Module): The loaded detector. dataset_name (str): The name of datase...
41f5dcec8868cf19e10ba98a5a5ff91b375bf618
49,593
def delete_user_entitlement(user, organization=None, detect=None): """Remove user from an organization. :param user: Email ID or ID of the user. :type user: str """ organization = resolve_instance(detect=detect, organization=organization) if '@' in user: user = resolve_identity_as_id(use...
c9b5d440f42eeb5da0746974a1b598cab72d4e03
49,595
import struct def encode_string(input_string): """Encode the string value in binary using utf-8 as well as its length (valuable info when decoding later on). Length will be encoded as an unsigned short (max 65535). """ input_string_encoded = input_string.encode("utf-8") length = len(input...
ecb26ce97cbebfe79b694e96b6e16d50069858b4
49,596
def resnet152(block, layers, pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(block, layers, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet...
b9e291a6c958b70e684d46bb63a31583d91e514b
49,597
def parse_vmin_vmax(container, field, vmin, vmax): """ Parse and return vmin and vmax parameters. """ field_dict = container.fields[field] if vmin is None: if 'valid_min' in field_dict: vmin = field_dict['valid_min'] else: vmin = -6 # default value if vmax is No...
a7c096e4648662a5efe59c38de016e586c718ffb
49,602
import json def to_dict(url: str) -> dict: """Method to convert and return as dictionary.""" return json.loads(fetch_data(url))
d75ade236379f61d0443610f91e2d090077028fe
49,603
def polygon_iou(poly1, poly2): """Compute the IoU of polygons.""" return polygon_geo_cpu.polygon_iou(poly1, poly2)
8e7bec12e3e0dfd99a040e5e256fedb6526a16de
49,604
def fit( X, y, batch_size = 4, validation_split = 0.05, epochs = 1250, learning_rate=0.001): """Fit a BNN with mean field posterior and trainable prior to a data set X,y. Args: X (np.array): Input data x (features) y (np.array): Input data y (target) batch_size (int, optional): Batch si...
2e3e940e4e0cc2a4537cf5e3619da58f5632aad4
49,605
import math def jacob_f(x, u): """ Jacobian of Motion Model motion model x_{t+1} = x_t+v*dt*cos(yaw) y_{t+1} = y_t+v*dt*sin(yaw) yaw_{t+1} = yaw_t+omega*dt v_{t+1} = v{t} so dx/dyaw = -v*dt*sin(yaw) dx/dv = dt*cos(yaw) dy/dyaw = v*dt*cos(yaw) dy/dv = dt*sin(yaw) ""...
4e9c88a8187d4c8bc76a7f954a68570ffb4a08bf
49,606
from datetime import datetime def save_by_name(admin: dict): """ Save a new admin with field name as index :return: """ name = admin.get('name') if not name: raise Error(10003, 'Field name required!') admin['updated_at'] = china_tz(datetime.now()) admin['created_at'] = china_tz...
7fe9db58896df4ce443e8919896a7fabc4f2fcfa
49,608
from typing import Any def create(tknzr_name: str, **kwargs: Any) -> BaseTknzr: """Create tokenizer instance by tokenizer's name. Tokenizer's arguments are collected in ``**kwargs`` and are passed directly to tokenizer's constructor. Parameters ---------- tknzr_name: str Name of the tokenizer to creat...
5f01ec7a380f715c71174bafd1ba7c51bbaf3c22
49,609
def logitRegression(data): """ 训练模型,并画出模型的ROC曲线 """ data = transLabel(data) features = ["age", "education_num", "capital_gain", "capital_loss", "hours_per_week"] labels = "label_code" trainSet, testSet = train_test_split(data, test_size=0.3, random_state=2310) model = trainModel(trainSet...
ca0357cdb6aae5b847b86082a39308dce319a572
49,610
import copy def jet_libes_get_data(exp_id=None, data_name=None, no_data=False, options={}, coordinates=None, data_source="JET_LIBES"): """ Data read function for the JET Li-BES diagnostic data_name: channel data can be reached under: "BES-ADCxx", "JPF/DH/KY6D-DOWN:xxx", ...
e58e92b2e3878867eccde22b6976bbbc3fa04b23
49,611
import numbers def is_numlike(obj): """return true if *obj* looks like a number""" return isinstance(obj, (numbers.Number, np.number))
b31365cf1e71d96b88d7a61b595fd85a7196cc81
49,612
def float2bin(afloat: float): """소수점 이하의 값이 있는 실수를 이진수로 변환 Args: afloat: 이진수로 변환할 실수 Returns: 이진수 ('0b' prefix가 없는 실수의 형태) """ integer_part = int(afloat) # 정수부분 decimal_part = afloat - integer_part # 소수부분 decimal_bin = "." # 소수부문에 대한 이진표현 while decimal_part != 0.0: ...
7873450858b3753a5da1f6a70f96d82204e37f8b
49,614
def get_sequential_param_pairs(params, name1, name2): """Returns a dict of two sets of sequentially named parameters using the value of name1 as the key and the value of name2 of the value. """ one = get_sequential_params(params, name1) two = get_sequential_params(params, name2) if len(one) != l...
fa2e810391e60c89acd43b7931212090a2adb9db
49,615