content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def matched_iou(boxlist1, boxlist2, scope=None): """Compute intersection-over-union between corresponding boxes in boxlists. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding N boxes scope: name scope. Returns: a tensor with shape [N] representing pairwise iou score...
845f401a61bd4fc80d381f3783e6906c180694fb
3,596,036
def do_combine(self, other): """ :param ProGlyph self: :param ProGlyph other: 0 :return: """ score, yell = 0, "" s, t = self.best_char, other.best_char ss, st = self.strength(), other.strength() suspects = ['ఏ', '-', '"', "'", '.', 'ై'] ghpsshh = 'ఘపసషహఎ' heads = ['ి', 'ీ', ...
2c346001cd9aaf692896152b8c6690d7800e8995
3,596,037
def get_version(): """Endpoint for getting the current version.""" return jsonify( status='OK', version=VERSION, message='AIOPS Data Collector Version 0.0.1' )
71272375ad0af06a3c18587cdfce77be27eaf863
3,596,038
import random def remove_edge_random_stochastic(G, p, random_seed=None, copy=True): """ Recieves a Graph and p (uniform probability of failure). Returns a degraded Graph """ if copy: G_ = G.copy() else: G_ = G if random_seed is not None: random.seed(r...
6591c79ccf14513adf58b0f59e569c6586d85d5f
3,596,040
def gas_attached(): """ :returns gas attached to Tx: """ configuration = ServiceConfiguration() tx = GetScriptContainer() # type:Transaction references = tx.References receiver_addr = GetExecutingScriptHash() if len(references) > 0: sent_amount_gas = 0 for output in tx...
c7e03e6c8b4e48d53c012b3bed5c72c2d9bac9e0
3,596,041
def list_services(config_dict): """ List available services Args: config_dict (dict): configuration dictionary Returns: list: list of available services """ return list(config_dict.keys())
a3226589405292f0bcef99aabaec71722aaeb1db
3,596,042
def get_big_wall(vk_session, user_id=1): """ Метод для скачивания стены во Вконтакте :param vk_session: Передаём авторизованную сессию VkApi :type vk_session: class VkApi :param user_id: Передаём ID пользователя, чью стенку надо получить :type user_id: int :return: Возвращается стена пользо...
c06d439b28e8d65e02fe887781562c74ad9547d0
3,596,044
def unet_block(x, filters: int, a=0.01, dr=0.05): """ U-net functional block Edit this block as needed Args: x: Input tensor. filters (int): No. of filters in convolution layer. a (float, optional): Leakage rate for ReLU. Defaults to 0.01. dr (float, optional): Dropout ...
5d4c1044fe68a8188bca450a6ea6c855b287204f
3,596,045
def stratification(rules): """Returns a dictionary from table names to an integer representing the strata to which the table is assigned or None if the rules are not stratified. """ return head_to_body_dependency_graph(rules).stratification([True])
11b7ba21cb7dc5c7625438c10d56310421732bd1
3,596,047
from typing import Type from datetime import datetime def _parse(json_str: str, primitive_cls: Type[Instant]) -> Instant: """Parses the json_str into an Instant FHIR primitive. Args: json_str: The raw JSON string to parse. primitive_cls: The FHIR primitive to parse into. Returns: A FHIR primitive ...
673ac08ba52e1f54b18f71059754ff02ee577b70
3,596,048
import requests def generate_access_token(consumer_key, consumer_secret): """This will generate the autorization token we need to make the daraja request for a stk push Args: consumer_key (str): -- consumer_key (above) consumer_secret (str): -- consumer_secret (above) Returns: ...
0119b6db0870b07f30080c096306d82976e0c7d5
3,596,049
def actions_by_behavior(actions): """ Gather a dictionary grouping the actions by behavior (not SubBehaviors). The actions in each list are still sorted by order of their execution in the script. @param actions (list) of Action objects @return (dict) where the keys are behaviors and the values are...
ebf97a5837a8d7de735207c5df5e19af2438510a
3,596,050
import decimal def decimal_round(val, prec=1e-4): """wrapper for rounding according to precision """ DD = decimal.Decimal val_ = DD(val).quantize(DD(f'{prec}'), rounding=decimal.ROUND_DOWN) return float(val_)
d0e37277df94ddbd95a60c1380cf3eb93531c6a7
3,596,051
def split_into_test_and_training( source_file, target_file, source_tree_name, branches_to_store=[] ): """ Splits the given ROOT file into a target file with two trees: one with a test sample set and one with a training sample set. The events are splitted 50% and 50%. Returns the amount of entrie...
f641a89a31fc2d023b00594958b2821e3834e2aa
3,596,052
def load_properties(filepath, sep='=', comment_char='#'): """ Read the file passed as parameter as a properties file. """ props = {} with open(filepath, "rt") as f: for line in f: l = line.strip() if l and not l.startswith(comment_char): if l.endswith(...
5663f8aa1197aeb7648228247df1ab65e39a2f5a
3,596,053
import logging from typing import Concatenate def apply_unet( input_tensor, output_name='output', params={}, output_mask_logit=False): """ Apply a convolutionnal U-net to model a single instrument (one U-net is used for each instrument). :param input_tensor: :param out...
e7dc6983bff73ba91de2be4607bb7b8166fbfaf6
3,596,054
def runScheduledTask(): """ Purpose: This function executes the given scheduled task Params: - In : None - Out: None """ # Retrieve all tasks from endpoint _endpoint = URL + '/sessions/scheduledtasks' _response = mkAPIcall( _endpoint, 'get', _hdr, '', None ) # Retrieve task_id for given scheduled tas...
352ab94bfc86f16738808829eb3bfdffc133157c
3,596,055
def best_star(lst, Year_NOW, star_dict=None, catalog=None, lat=salt_lat): """Given an lst and a catalog of stars, determine the best star in the list. The best star is determined to have an airmass less than 1.2, a magnitude below 3.0, and an hour angle greater than 0.5. And we will pic it to b...
94499def158c51181fee710fd24a019c6bb01d66
3,596,056
def sample_split_node(node: LeafNode) -> DecisionNode: """ Split a leaf node into a decision node with two leaf children The variable and value to split on is determined by sampling from their respective distributions """ conditions = sample_split_condition(node) if conditions is None: r...
91e2b5c71669a44ce27e3256b98f3a2152b37ebc
3,596,057
def postgres_checkpoints_config(): """ Shared setup for PostgresCheckpointsAPITest and subclasses. """ config = Config() config.NotebookApp.contents_manager_class = FileContentsManager config.FileContentsManager.delete_to_trash = False config.ContentsManager.checkpoints_class = PostgresCheck...
516bd69b1376ef380991964b30c2bea11b455bf3
3,596,058
import optparse def csv_validator(optdict, name, value): """validate and return a converted value for option of type 'csv' """ return optparse.check_csv(None, name, value)
2c4d2a6be7773231dfb610304359f3041ac2f524
3,596,059
import random def select_anchors_classification(data, n, classifier): """randomly selects n different anchors for evaluation. Only LoS-classified anchors are selected Returns: -------- nodes: numpy matrix with nodes positions and ranges + + | array([x1,y1]) | r1 | | array([x2,y2]) | r2 | ...
e428330f920ef3100edb8ac145e28b35c158b284
3,596,060
import urllib def register(request, template_name='authopenid/complete.html', redirect_field_name=REDIRECT_FIELD_NAME, register_form=OpenidRegisterForm, auth_form=AuthenticationForm, register_account=register_account, send_email=True, extra_context=None): """ ...
b6f2d94c68c4927833d998160ba5c498690a0375
3,596,061
def batch_norm(x, n_out, phase_train): """ Batch normalization on convolutional maps. Ref.: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow Args: x: Tensor, 4D BHWD input maps n_out: integer, depth of input maps phase_...
8acabdbd13f6c0f18990202e9deba722a992c26b
3,596,062
import requests def reddit_ass(bot, trigger): """Posts a random ass pic from Reddit. #nsfw only.""" msg = nsfw_check(trigger) if msg: return bot.reply(msg) url = "https://old.reddit.com/search.json" params = { "q": "(ass OR butt OR booty) AND nsfw:yes AND (site:reddit.com OR site:...
9fd30306962e174b4ba50087a973f07c348c770a
3,596,063
def conv7x7(inchannel, outchannel, stride=1, bias=False, dilation=1): """Create Convolution 7x7.""" return ops.Conv2d(inchannel, outchannel, kernel_size=7, stride=stride, padding=3, dilation=dilation, bias=bias)
4aac4f78f84f8ca1edc6ea11fee4c50c9d3a6207
3,596,064
def make_chain_tanh_fill(length=100, name_prefix="a", node_mbs=1): """Creates chain of length length. First node is Variable, rest are tanh. Returns nodes. Note, if length is 1, there are no non-linearities in the graph, hence gradients do not need to store any activations.""" dtype = np.float32 n = node_mbs...
2b303719de94e5cd1483587231451f20d3db16c7
3,596,065
def check_wind_component(df): """ Ensure that CC/HN models where mass != mass_final, that a row is added to store wind composition """ elements = list(set(df.columns).intersection(set(el2z.keys()))) for i, model in df[(df.type == 'cc') & (df.mass != df.mass_final)].iterrows(): if not '...
e6f7493ef5b0b4dce47a90ab7752f8574245d1cb
3,596,066
def plugin_reconfigure(handle, new_config): """ Reconfigures the plugin, it should be called when the configuration of the plugin is changed during the operation of the device service. The new configuration category should be passed. Args: handle: handle returned by the plugin initialis...
b65c246d90e8ab6740c0481849ab2da22a90b872
3,596,067
import logging def get_loglevel(loglevel): """ Check whether a valid log level has been supplied, and return the numeric log level that corresponds to the given string level. Parameters ---------- loglevel: str The loglevel that has been requested Returns ------- int ...
a662e00caa21bf5632b28f26cbb604229db9705a
3,596,068
import ipdb def add_to_tfrecord(im_path, gt2d, gt3d, cam, coder, writer, model=None, sub_path=None): """ gt2d is 14 x 2 (lsp order) gt3d is 14 x 3 cam is (3,) ...
1df333aa08c008a84d6933179662572e785270aa
3,596,070
def syrk(A, C=None, uplo='u', trans='n', alpha=1.0, beta=1.0, lda=None, ldc=None): """ Perform a symmetric rank-k update operation. C := beta * C + alpha * A * A_T [trans='n'] or C := beta * C + alpha * A_T * A [trans='t'] where alpha and beta are scalars, A is a general matrix, and C is a s...
436071568f9a6b741c9d75c53a2eec150a94ca01
3,596,071
import logging import time def is_valid_date(strdate): """ 判断是否是一个有效的日期字符串 :param strdate: :return: """ logging.info('is_valid_date') try: if ":" in strdate: time.strptime(strdate, "%Y-%m-%d %H:%M:%S") else: time.strptime(strdate, "%Y-%m-%d") ...
7dd157a3bf970057233066faa563dee627a61dbf
3,596,072
def _IsRegressionReproduced(known_good_result, known_bad_result, required_initial_confidence): """Checks whether the regression was reproduced based on the initial values. Args: known_good_result: A dict with the keys "values", "mean" and "std_err". known_bad_result: Same as abo...
38d20e0030d707b42d3330bafdf92e4dde9b5296
3,596,073
from datetime import datetime def getTimeDelta(startDatetime): """ get a timedelta object. Get seconds elapsed with timedelta.total_seconds(). """ endDatetime = datetime.datetime.utcnow() timedeltaObj = endDatetime - startDatetime return timedeltaObj
59739cde93125b7fb6f44ad555ea47e0c19b5c3f
3,596,074
def update(time): """Updates all active widgets or modal widgets each frame.""" def _fade(widget): """Fade widget.""" if widget._fade is not None: widget.image.set_alpha(widget._fade) if widget._fade_up: widget._fade += time / 3. else: ...
0c7d8d029d936425a5ef03a7a926220dd67eb32e
3,596,075
def comp_spearman(data_u, data_v): """Compute the spearmanr correlation index. Suggestion: use tonparray to converta data (pd.series, non-flatten numpy.array) to a flatten numpy.array and drop nans.""" return spearmanr(data_u, data_v)[0]
ff5f1e6ba5e6ce685472a5064b6c2a0a8cf8923d
3,596,076
def pixel_precision_recall_f1(seg, gt): """ :param seg: 2d array, int, estimated targets as returned by a classifier :param gt: 2d array, int, ground truth :return: precision, recall, f1: float """ seg_flt, gt_flt = seg.flatten(), gt.flatten() seg_flt[seg_flt ...
a91bc66449cb96a6d0332589b4f893b22d02818c
3,596,078
def _label_col_dict(row: pd.Series, column: str): """Add label from the Provider column to the details.""" if not isinstance(row[column], dict): return row[column] return ( {row.Provider: row[column]} if row.Provider not in row[column] else row[column] )
c5ff10e238b000d21bbf8fe610eb96e1496c0925
3,596,079
def vs_error_control(cg_itp, bead_id, vs_type, func, line_nb, vs_def_beads_ids=None): """Check itpd fields; vs_type in [2, 3, 4, n], then they each have specific functions to define their positions""" if bead_id >= len(cg_itp["atoms"]): msg = ( f"A virtual site is defined for ID {bead_id...
727885d33c711ebb953c59040ac0bef9f66707d9
3,596,080
from typing import Union async def try_to_send_buffer(messagable: Messageable, buffer: str, force: bool = False) -> Union[Message, str]: """ Parses a string buffer and either sends or returns the buffer in an optimal break point. Parameters: messagable (discord.abc.Messageable): The channel to se...
a18821ff2e698bfc9ef95081bdafe09514dabde5
3,596,081
def load_initializer_tdata_and_vdata( fn, n_train, ran_key, low_logmh, high_logmh, n_mh=200, n_validate=100, tol=-2.5 ): """Load from disk the training and validation data for SHAMnet. Parameters ---------- fn : string h5 filename storing the best-fit SMHM params corresponding to SMF params...
6097c7937824c24e5df8114e2dc5117f86e62600
3,596,083
def binary_cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None, class_weight=None): """Calculate the binary CrossEntropy loss. Args: pred (torch.Tensor): Th...
6b170b8e7964b37b24df68d27b0790efe0cdd023
3,596,084
import base64 import requests import json def retrieve_appdevtools_access_token(username, password, auth_endpoint): """ Retrieve access token for appdev tools Args: username: username password: password auth_endpoint: authorization endpoint Returns: token """ # Form c...
8f08f4be45998199aa9db151fec26722a13eb060
3,596,086
def delete(isamAppliance, instance_name, file_name, check_mode=False, force=False): """ Deleting a file or directory from the API Access Control """ exists, warnings = _check_exist(isamAppliance, instance_name, file_name) if force is True or exists is True: if check_mode is True: ...
7ccbc9d4cc60f0de8b9fc6539ceca84e260f6eec
3,596,087
def struct(typename, attrnames): """ Generate simple and fast data class """ attrnames = tuple(attrnames.replace(',', ' ').split()) reprfmt = '(' + ', '.join(name + '=%r' for name in attrnames) + ')' def __init__(self, *args, **kwargs): if len(args) > len(attrnames): msg = ...
9e4789e8960e48cd3a80c8907321d23013d29b87
3,596,089
import shutil def generalizeCFF(otfPath, do_sfnt=True): """ Adapted from similar routine in 'buildmasterotfs'. This uses temp files for both tx output and sfntedit output instead of overwriting 'otfPath', and also provides an option to skip the sfntedit step (so 'otfPath' can be either a .otf file...
1f15de94a9ff1210efc5e1c445982d36d998f28c
3,596,090
async def async_setup_entry(hass, config_entry): """Set up PyFoldingAtHomeControl from config entry.""" client = FoldingAtHomeControlClient(hass, config_entry) hass.data.setdefault(DOMAIN, {})[config_entry.entry_id] = client if not await client.async_setup(): return False await async_setup_...
63ec5f7ada4103d72ce357aed18e660234fc1115
3,596,091
def ADOSC(barDs, count, fastperiod=-2**31, slowperiod=-2**31): """Chaikin A/D Oscillator""" return call_talib_with_hlcv(barDs, count, talib.ADOSC, fastperiod, slowperiod)
f54d38b93cd0e97619201d02f4efb123859df5f0
3,596,092
def indentify_taxon_notation(taxon_string): """Identifies taxonomic notation from `taxon_string` . Currently available conventions are Greengenens, sintax and SILVA. Examples: Parameters ---------- taxon_string : str String with taxonomy/lineage to test Returns ------- str...
823e52449a5f16199e786bc9d901e0cf3f81cf72
3,596,093
def quatmultiply(q, p): """ クォータニオン積 引数 : q: クォータニオン (1x4) p: クォータニオン (1x4) 返り値 : o: クォータニオン積 (1x4) 正規化してからリターンする """ o1 = q[0] * p[0] - q[1] * p[1] - q[2] * p[2] - q[3] * p[3] o2 = q[1] * p[0] + q[0] * p[1] - q[3] * p[2] + q[2] * p[3] o3 = q[2] * p[0] + q[3] * p[1]...
b4adafc9d915cac415ff14d537a3553d9211a2a7
3,596,095
async def get_entree(entree_id): """ Get an entree by id - **entree_id**: the unique id of the entree """ rows = simple_query('SELECT * FROM test.entree WHERE entree_id = :entree_id', {'entree_id': entree_id}) if (len(rows) == 0): raise HTTPException(status_code=404, detail="Entree {} do...
41a6868d3430adedee5cc0acf01ea3695d63fc49
3,596,096
def Positive(thetype): """Demand a positive number type""" if thetype == int: return All(thetype, Range(1, float('inf'))) else: return All(thetype, Range(0, float('inf')), NotIn([0]))
cce1490105e29eeadf76a640f94c92f32bd6c211
3,596,097
def decode_base64_gzip_to_string(base64_gzip_data: str) -> str: """Decode Base64 GZIP into string.""" data_bytes = decode_base64_gzip_to_bytes(base64_gzip_data) return data_bytes.decode("utf-8")
158af0e71625234593c99eb432fbdad8340dc5d3
3,596,098
def count_literals(term): """ Counts the number of literals in a term Args: term : A string containing literals Returns: The number of literals in term """ count = 0 for char in term: if char != "_": count+=1 re...
48bb0066f09994627a4b7c2b04a657df1106a1c3
3,596,099
def calculate_glucose_from_effects(effects, recent_glucose, momentum=()): """Calculates predicted glucose values from effect schedules starting from the end of measured glucose history Each effect should be a list of dicts containing at least 2 keys: { 'date': # An ISO timestamp 'amount': #...
7cd466999068a506274d3d8c62acf40aed87be69
3,596,100
def separable_conv(x, kernel_size, activation): """Apply a depthwise separable 1d convolution.""" tf.assert_rank(x, 3) net = tf.expand_dims(x, 2) net = tf.layers.separable_conv2d( net, filters=_depth(x), kernel_size=(kernel_size, 1), padding='same', activation=activation) net = t...
0723776f6eb477d6c0da2ba257d9dfe9fee3289f
3,596,101
def get_cache(maxsize=10000): """ Get an instance of cachetools.cache Parameters ---------- maxsize: int The max size for the cache (``10000``, by default) Returns ------- cachetools.cache An instance of cachetools.cache """ global cache if cache is None: ...
6da71fd4fdbefecc0e6e2a2ebb4fea351bf4215a
3,596,102
def simple_mask(dataf, maskf, outfile, thr=0): """ sets values in data to zero if they are zero in mask""" img = nibabel.load(dataf) dat = img.get_data() mask = nibabel.load(maskf).get_data() if not dat.shape == mask.shape: raise IOError('shape mismatch {0}, {1}'.format(dataf, maskf)) da...
0b35a23c86388c4a7b121842a6a862cf3e5a59aa
3,596,103
def group_by_node(notifications): """Take list of notifications and group by node. :param notifications: List of stored email notifications :return: """ emails = NotificationsDict() for notification in notifications: emails.add_message(notification['node_lineage'], notification['message...
b2d1f82c578afc805babd0f5e4eb41886373371c
3,596,104
def line_search_wolfe2( f, myfprime, xk, pk, gfk=None, fk=None, old_fval=None, old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=None, extra_condition=None, maxiter=10, ): """Find alpha that satisfies strong Wolfe conditions. Parameters ---------- ...
6ac9785bbe2b0bed30aa2d505765724232af3f3d
3,596,105
def get_project_size(project_report, language): """ Obtains the project size that was calculated for a specific language by the ProjectMetrics task from the project report :param project_report: The project report to obtain the project size from :param language...
e08d8b40ad66baf52a50c4d6c84b9a15a720add9
3,596,106
def resample_to_1d_resolution(df, column): """ Have at most one data point per day. For days w/o change, have no data point. Before: 2020-03-18 16:42:31+00:00 1 2020-03-19 20:17:10+00:00 2 2020-03-20 05:31:25+00:00 3 2020-03-20 09:01:38+00:00 4 2020-03-20 14:03:...
9739c348e095967015e238606e23b2896d584099
3,596,107
def get_storageaccount_key(): # type: (None) -> str """Get storage account key :rtype: str :return: storage account key """ return _STORAGEACCOUNTKEY
1dcec8ea06bf7c68a9b5def69658c71044014eae
3,596,108
def encode_collection(collection, encoding='utf-8'): """Encodes all the string keys and values in a collection with specified encoding""" if isinstance(collection, dict): return dict((encode_collection(key), encode_collection(value)) for key, value in collection.iteritems()) elif isinstance(collect...
60ec0ec41d852d8d3801c815654b0edde8d763dc
3,596,109
def _thompson_star( regular_expression: RegularExpression, alphabet: Alphabet, index: int = 0) -> FiniteAutomaton: """Thompson's algorithm, ``STAR`` case """ inner = thompson(regular_expression.inner, alphabet, index) index += len(inner.states) q_init_inner = list(inner.initi...
26cade9d0fea4c8642125a6617de1db15cbb1807
3,596,111
def BmV_to_gmr( BmV ): """Relation from Cook+2014 (2014MNRAS.445..890C) to transform galaxy B-V color to g-r. """ ii_bad = [i for i in range(len(BmV)) if BmV[i] == -99.0] gmr = 1.12*BmV - 0.18 gmr[ii_bad] = -99.0 return gmr
e5b4d1748d403e206cfb74f640d5e04e5b84f5a1
3,596,112
def generate_map_legend() -> MacroElement: """ Generates a legend for the map. :return: MacroElement, html added to the map """ template = """ {% macro html(this, kwargs) %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="wi...
3943f5d48b0e9464d7252070e0ac5b553183d7bf
3,596,113
def remove_redundant_after_inosine_addition(data, min_increase): """ Removes oligos that don't increase coverage after inosine addition. Arguments: -data: a pandas dataframe with sequences detected by the oligo as returned by measure_coverage_oligos -min_increase: minimal increase of coverag...
5b96d4dc8fe2ed92e422d2c05a2d257fbe1795fa
3,596,114
from typing import Any from typing import List def flatten(item: Any) -> List[Any]: """Recursively flatten any sequence but a string or bytes. Args: item: a sequence or a single item. A single item will be packet into a list. Returns: a list with tuples got flattened. >>> from redex...
15b4579626a36d912c0e453efe85537cd0a59a18
3,596,115
def brent(f, a, b, t, args=()): """ Find a zero of a univariate function within a given range This is a bracketed root-finding method, so f(a) and f(b) must differ in sign. If they do, a root is guaranteed to be found. Parameters ---------- f : function Continuous function of a si...
6b474619162d5dc471f7d85ea4cabddc79930bd5
3,596,116
import json def get_json_from_file(filename, warn = False): """Loads json from a file. Optionally specify warn = True to warn, rather than fail if file not found.""" f = open(filename, 'r') return json.loads(f.read())
6916e0239067b977d0671e1e38006f457da94ae7
3,596,117
def filter_grantable_permissions(session, grants, all_permissions=None): """For a given set of PERMISSION_GRANT permissions, return all permissions that are grantable. Args: session (sqlalchemy.orm.session.Session); database session grants ([Permission, ...]): PERMISSION_GRANT permissions ...
21ba3eaaaa73cddffbbe2bf010810a37db192e4c
3,596,118
def fit_plane_3_points(points): """ compute the plane that passes through all 3 points in the list Parameters ---------- points : array_like The Points """ # compute normal direction which is perpendicular to vectors p1-p0, p2-p0 # use np.subtact instead of "-" operator so that points...
02ab3a7fb1149422012f77a913ce7d0e3550f4b7
3,596,119
def segments_to_tabs(segments, ax, thickness): """ genrates tabs from a segmented point list You can change if the first tab is male of female by changing the sign of the tab-size """ arr_x = np.repeat(segments[:,ax], 2) arr_y = np.tile([0,0, thickness, thickness], len(segments)//2+1)[1:-3] ...
dfe842267830993835f8ed8c8edc2f57e49b1d71
3,596,121
def ellipsecoords(pars,npoints=100): """ Create coordinates of an ellipse.""" # [x,y,asemi,bsemi,theta] # copied from ellipsecoords.pro xc = pars[0] yc = pars[1] asemi = pars[2] bsemi = pars[3] pos_ang = pars[4] phi = 2*np.pi*(np.arange(npoints)/(npoints-1)) # Divide circle into Np...
fb2b2339eed9c8e639083042c1f499ddc6fd125c
3,596,123
import itertools def take_while(collection, predicate): """:yaql:takeWhile Returns elements from the collection as long as the predicate is true. :signature: collection.takeWhile(predicate) :receiverArg collection: input collection :argType collection: iterable :arg predicate: function of on...
dd1fe4f97db991d1323b814ddd1f7c2e0fe52c88
3,596,124
def ip_has_digit(matched_str): """Checks to make sure the PII span is not just :: or whatever that may accidentally be picked up by making sure there are digits.""" return any(map(str.isdigit, matched_str))
3ed765a04c1b920addc7e3ab538575ac4edc7651
3,596,125
def idz_estrank(eps, A): """ Estimate rank of a complex matrix to a specified relative precision using random sampling. The output rank is typically about 8 higher than the actual rank. :param eps: Relative precision. :type eps: float :param A: Matrix. :type A: :class:`...
b4d188352ee9f78b6b6a2b6630ab3bc93fe63388
3,596,126
def batch_from_image(file_name, batch_size, output_height=224, output_width=224, num_channels=3): """Produce a batch of data from the passed image file. Args: file_name: string, path to file containing a JPEG image batch_size: int, the size of the desired batch of data output_heigh...
0c929672ce6dea7c5f29afaac6947158bc7d3885
3,596,127
def login(): """ Login page """ # Forget any user_id session.clear() # check if POST used if request.method == "POST": # store userName in variable userName = request.form.get("username") # return apology for blank username if not userName: return ap...
2f48fc956bd63c46ff2ae007290093372f77914b
3,596,128
from importlib.util import spec_from_file_location, module_from_spec def load_config_from_py(filename): """ Load the configuration parameters from a python file into dict. """ spec = spec_from_file_location('f', filename) f = module_from_spec(spec) spec.loader.exec_module(f) return {name: value fo...
600562b4d3f239f675354dc138b685caf26f35d9
3,596,131
def list_frequencies(list_of_items): """ Determine frequency of items in list_of_items. """ itemfreq = [list_of_items.count(p) for p in list_of_items] return dict(zip(list_of_items,itemfreq))
8772e64d0abd400dfe333747e7fce0d816a0f59f
3,596,132
import scipy def calc_delta(texp, start_time, lam, vol, fee, gmdb, account, spot): """Delta to put on against the VA portfolio""" t_fwd = texp - start_time n_int = max(2, int(round(0.4 * t_fwd))) dt_int = t_fwd / n_int deltas = -fee * account * np.exp(-lam * start_time) / spot * (1 - np.exp(-(fee...
bf251bed22ef4d5edc0aefabce9973f7202bb9ba
3,596,133
def get_host_credentials(config, hostname): """Get login information for a host `hostip` (ipv4) from marvin's `config` @return the tuple username, password for the host else raise keyerror""" for zone in config.zones: for pod in zone.pods: for cluster in pod.clusters: fo...
82bb146418c77a916b974b328f1cdf25817ddc69
3,596,134
import typing from datetime import datetime def terminate() -> typing.RouteReturn: """Room terminate page.""" room = flask.g.rezident.current_room if not room: # No current rental: go to register return utils.ensure_safe_redirect( "rooms.register", doas=flask.g.doas...
fba275d0e550765b5b5bd31fe803a30ca20313a6
3,596,135
import pandas def extract_mean_activation_parallel(celltype, chrom, start, end): """ For a given genomic locus, calculate the 60bp average coverage for this celltype *** N.B: need to normalize for library size, not yet done IIRC *** """ my_peak = '\t'.join([chrom,str(start),str(end)]) ...
e4146d59d0a960f620a61b44f25cec4ffc8fe255
3,596,136
def euclideanDistance(p0,p1): """ Return the Euclidean distance between two points. Parameters: ----------- p0: pandas dataframe p0 must coantain three columns labeled 'x', 'y' and 'z'. p1: pandas dataframe p1 must coantain three columns labeled 'x', 'y' and 'z'. Returns: ...
00d6202b4488ae914be0751c1c186fc441b53273
3,596,137
def request_from_master(request): """Returns True if the request appears to be coming from the master""" return request.getHeader("User-Agent") == config["master_user_agent"]
d3379051a094c9c6f4c22e9ea2df72b500aca063
3,596,138
def _get_sparse_representation(feature): """ Create sparse representation of the features, i.e. indices and values format. :param feature: A list of floats. Assume the input is dense. :return: indices and values. """ indices = np.arange(len(feature)) values = feature return indices, valu...
a1ce40e777b70980a3c79ee466161324efb51618
3,596,139
def containstring(strtocheckinanother,checkstr): """Check if a string contains substring or not return True if string is a substring else return False Note: Dependent on 'get_all_substrings_of_String_in_array(checkstr)' method Example: >>> containstring("ello","Hello") True ...
d02eeb1972ad746f383d49141f93ef19a9949055
3,596,140
def define_struct(defn): """ Register a struct definition globally >>> define_struct('struct abcd {int x; int y;}') """ struct = parse_type(defn) ALL_TYPES[struct.name] = struct return struct
a7b6b8f2a17b2036de5f8ab632dd86eec5f3d2e0
3,596,141
def DiffusionMaps(*args, **kwargs): """Convenience function to select the right diffusion map routine. Consult the documentation for BaseDiffusionMaps and its constructor for details. """ cut_off = kwargs.get('cut_off') if cut_off is None or np.isinf(cut_off): kwargs['cut_off'] = None...
50347316ac954d26914f9e86f9a058587076832a
3,596,142
import base64 def authenticateRequest(request, storeSessionCookie=False): """ Authenticates an API request. Returns a StoreUser object if the authentication is successful, None if unsuccessful, or a string error message if an error occurs. """ if SESSION_KEY in request.session: user = ezidapp...
231ddaf97c69d8f3f359946f95caf86eec1f67ef
3,596,143
def is_new_nice(chars): """ New rules for part 2 """ return ( has_non_overlapping_pairs(chars) and has_repeat_char_with_one_between(chars) )
2b5517bb775e4a17898bb04587be71b1bfbdbd4a
3,596,144
def _pool(x): """ max pooling""" x = MaxPooling2D(pool_size=2,strides=2,padding='same')(x) return x
22c8db1bd38132eb22ea0854bd005c5c154fd4d9
3,596,145
import numpy as np def eigenvector_centrality_numpy(G): """Compute the eigenvector centrality for the graph G. Parameters ---------- G : graph A networkx graph Returns ------- nodes : dictionary Dictionary of nodes with eigenvector centrality as the value. Examples ...
6ab315920f5aefa672f7aef4af5887cc26684ef6
3,596,147
from typing import List def get_records( vcf_path: str, sample_name: str, group: str, no_alt: bool = False, autosomes_only: bool = True, ) -> List[dict]: """ Load records from VCF and create a list of dictionaries with their relevant info """ hs_autosomes = [str(x) for x in range(1...
1a3ace194ee0bfb9b504dcc56894e3d338f2d016
3,596,148
import numpy def maxDist(src, dst): """ Src and dst are both matrices of the same size with each column representing a different position """ diff = dst - src max_dist = 0 for entry in range(diff.shape[1]): dist = numpy.linalg.norm(diff[:, entry]) if dist > max_dist: ...
f943ebf703fe57cc79b03efa8100e8d8c3cb947a
3,596,150
import six import re def partition_volumes(volumes, downsample=True): """Paritition volumes into training and validation based on configuration. Uses the regexes mapping partition sizes and indices in diluvian.config.TrainingConfig by applying them to matching volumes based on name. Parameters ...
7d3c3ca91f23396145814dbf526bceef8eb8c7a7
3,596,151