content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_targets(words, idx, window_size=5): """ 获取input word(idx下标对应的word)对应的上下文words :param words: 单词列表 :param idx: input word的下标 :param window_size: 窗口大小 :return: """ target_window = np.random.randint(1, window_size + 1) start_point = idx - target_window if (idx - target_window) > ...
a7b6cf14fc0fffb53cbf7d8fa4cd2e0785468018
3,600,600
from typing import Literal from typing import Callable import warnings def filter_warnings(level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "WARNING") -> Callable: """If filter (once) in warnings from 3rd party libraries don't work, this implements own filter. Args: level (Literal["D...
c934e428ebbf5c693a67c130f38075164bd2d33b
3,600,601
def sanitize_value(p_value): """Returns p_value or its part if it represents a sane simple value, else returns 'None'""" if isinstance(p_value, STR_TYPES): match = SIMPLE_VALUE_RE.match(p_value) if match: return match.groups()[match.lastindex - 1] else: return 'No...
21133a4810209f284da8ed3de1110c92f27dd7e9
3,600,602
def ysum_ysq_count(ysum, ysq, counts): """ calculate mean and error given accumulated sum of val and sq Args: ysum (np.array): accumulated sum of values, (nentry,) ysq (np.array): accumulated sum of squares, (nentry,) counts (np.array): number of hits for each entry, (nentry,) Return: (np.array, ...
ecdb04c291b28bb2ad8385be3b09a45a32a72c05
3,600,603
import sys def pre_action_drupal_readonly(s_db, s_cur, d_db, d_cur): """ Wrapper around drupal_readonly_status() for pre-action callbacks. Parameters: s_db: the source-database connection object to use s_cur: the source-database cursor object to use d_db: the destination-database c...
20287bd68ae90458028aa2047da6a8268ef482b4
3,600,604
def array_to_image(array, image_float=False): """ """ normalized_data = normalize_data(array) rgba = from_data_to_pixel_value(normalized_data, image_float) return rgba
01712bb81cfe15ca03ec99a4e76e0bb3fdc7c781
3,600,605
import textwrap def format_function_call(name, pdict): """ Formats a function call with named parameters. @param pdict dictionary @return string .. runpython:: :showcode: from mlinsights.helpers.parameters import format_function_call d = dict(...
efcadb3a41a6059faf778fc459658a480c98e539
3,600,606
from typing import Optional from typing import List import os import posixpath def safe_join(directory: str, path: str) -> Optional[str]: """Safely path to a base directory to avoid escaping the base directory. Borrowed from: werkzeug.security.safe_join""" _os_alt_seps: List[str] = list( sep for s...
678efd5ab00b4884355b5e9b02b09c4a6a1183b5
3,600,607
def _get_profile_image_urls(name, storage, file_extension=PROFILE_IMAGE_FILE_EXTENSION, version=None): """ Returns a dict containing the urls for a complete set of profile images, keyed by "friendly" name (e.g. "full", "large", "medium", "small"). """ def _make_url(size): url = storage.url( ...
bd98d22a154a5bb48b3e084c39de1640daf2e9cb
3,600,608
def load_torch_resnet152(scopes, return_fn=_assign): """Converted from the [Torch ResNets][5].""" filename = 'resnet_152_cpu.pth' weights_path = get_file( filename, __model_url__ + 'resnet/' + filename, cache_subdir='models', file_hash='3339f6aca7f746f8ae7f6ce577efc0c0') values =...
80e981ce53540e3c145320a8cb7dcebc2526f849
3,600,609
from typing import Iterable def merged_codepoints(cps: Iterable[CodePoint]): """return a list of codepoints (start, end) for inclusive ranges""" cps = sorted(cps, key=lambda cp: cp.codepoint) if not cps: return [] ranges = [(cps[0], cps[0])] for cp in cps[1:]: last_range = ranges[-...
e28c7f0a0a1298812f1770eb43f55f7573fd4304
3,600,610
def is_bool_type(type_): """ Checks if the given type is a bool type. :param type_: The type to check :return: True if the type is a bool type, otherwise False :rtype: bool """ return type_ in _get_types(Types.BOOL)
2c947f1dc4207f85908b8cdb71e16dd86f353a6f
3,600,611
def train (param): """ ************************************************************************** This function returns a Handle to the training process The training process is running in the background after the functions ends. ***********************************************************************...
7ceb97548a7155632234d7fa1a93b31fc2e24355
3,600,612
import matplotlib.pyplot as plt def plot_bl_bl_scatter(uvd1, uvd2, bls, component='real', whiten=False, colorbar=True, axes=None, colorax='freq', alpha=1, msize=1, marker='.', grid=True, one2one=True, loglog=False, freqs=None, times=None, figsize=None, ...
22acf7300aff91b7e51ced61a66c27583c56a47c
3,600,613
import json def pretty(ob, lexer=None): """ Return a pretty console text representation of 'ob'. If 'ob' is something else than plain text, specify it in 'lexer'. If 'ob' is not string, Json lexer is assumed. Command line switches can be used to control highlighting and style. """ if lex...
216c1457161c0b10ff98c1227408ce2238bf3f53
3,600,614
from typing import Optional from typing import List def browse_results( data: pd.DataFrame, severities: Optional[List[str]] = None, **kwargs ) -> SelectItem: """ Return TI Results list browser. Parameters ---------- data : pd.DataFrame TI Results data from TIProviders severities :...
c7d8bc6fe5bca86de81a186ff4d25a58e2d8c9d6
3,600,615
def infection_rate_symptomatic_10x80(): """ Real Name: b'infection rate symptomatic 10x80' Original Eqn: b'Susceptible 80*Infected symptomatic 10x80*contact infectivity symptomatic 10x80*(self quarantine policy SWITCH self 80\\\\ *self quarantine policy 80+(1-self quarantine policy SWITCH self 80))/non cont...
76522534c07d798608ed24da15b15054a832ae8b
3,600,616
import functools def _make_modules(is_train): """Returns modules, with split based on the boolean `is_train`.""" return { 'swr_p_sequence': functools.partial( swr_prob_sequence, is_train=is_train, sample_range=_SWR_SAMPLE_COUNT), 'swr_p_level_set': functools.partial( swr_prob_level...
675b30495080df5e8d2b57cf9f9dcb1f155b9c70
3,600,617
import ctypes def DMAR(val): """Create class based on decode of an DMAR table from address or filename.""" base_length = ctypes.sizeof(dmar_factory(list())) addr = val if isinstance(val, str): data = open(val).read() buf = ctypes.create_string_buffer(data, len(data)) addr = cty...
9c3cedf4b52d078e15488c683f39b594e4e6313d
3,600,618
def validate_device_name_text(device_name): """Extends the validate_device_name function with a return text if the validation fails. Can be used with the validate option of the questionary package. Args: device_name: Device name to validate as string. Returns: True if the given string ...
9957e9c8ebd91bf6d1dcce43a4b4d2fab3b2edeb
3,600,619
from datetime import datetime def get_chat_metadata_for_header(transcript, duration, wait): """Will generate the section that comes before the transcript on the HTML page. It contains metadata information such as Duration and Wait Time of the chat Args: transcript ([type]): [description] ...
6206e7a54d32b61a96d3615ef0475f946cb0c85a
3,600,620
import os from pathlib import Path import io def read_plot_modules(PATH_PLOT=os.path.join( Path(__file__).absolute().parent.parent, 'plots')): """Read required .mat files for plotting Parameters ---------- PATH_PLOT : regexp, optional pa...
1a4255631be3545ecfb7226a729ce7299d205514
3,600,621
def index(): """Main page.""" return render_template("index.html")
d776731cc585dd3006ca7aeb0f1dd2565106049c
3,600,622
import collections import random def gen_undirected_graph_rand(nodes = 1000, edge_factor = 3, costs = (1,1)): """ generates an undicrected graph with `nodes` nodes and up to `edge_factor` edges per node @param nodes amount of nodes @param edge_factor up to `edge_factor` edges per node @param ...
96947e153d235cad9b900492693cfb316eaff32d
3,600,623
import json def append_users(channel: str, *users_to_add: str): """ Appends users to the specified channel's user list. """ c = Channel.query.get(channel) if not c: return no_channel users = json.loads(c.users) for user in users_to_add: if user not in users: use...
2425f1abb0e621389b8db5d41de5c584a4cf7603
3,600,624
def get_service_offering(offering_name): """ Get the service offering with the specified name. @param offering_name: The name of the service offering to get. @return: Response. """ # We cannot use describe_item_request because there is a bug in # Cloudstack 4.0.0 which causes listServiceOf...
74f5ee98814815e0c92f40bd94d8dac4694c94ba
3,600,625
def symmetrized_csiszar_function(logu, csiszar_function, name=None): """Symmetrizes a Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The symmetrized Csiszar-function is defined as: ```none f_g(u) = 0.5 g(u) + 0.5 u g (1 / u) ``` wher...
931094ace56953e31cf65a78c1015dd1d1de59bd
3,600,626
def _int2farray(ftype, num, length=None): """Convert a signed integer to an farray.""" if num < 0: req_length = clog2(abs(num)) + 1 objs = _uint2objs(ftype, 2**req_length + num) else: req_length = clog2(num + 1) + 1 objs = _uint2objs(ftype, num, req_length) if length: ...
9be8cf28a3f379235d07718df8db9dff7e223d2f
3,600,627
def pick_coupons(user): """ Choose the coupons which would be used in redemptions by the user. There should be at most one coupon per program in the output. The heuristic is currently: - choose attached coupons over automatic coupons - choose the coupon which has been most recently attached, ...
886f3224f7925dfdbc7caace65903bf9ecbec741
3,600,628
def closer_ang(x,a,dir=0): """ find angle y (==x mod 2*PI) that is close to a dir == 0: minimize absolute value of difference dir == 1: y > x dir == 2: y < x """ if dir == 0: return a + smaller_ang(x-a) elif dir == 1: return a + (x-a)%(2*PI) elif dir =...
c87bf0976e87d195e10c4886be62ca9ee473702f
3,600,629
def make_name(name): """ Converts a given name to a lower snake case :param name: Name to convert :return: Lower snake case """ return to_snake_case(name)
1950402f193b1b8c4d14fa5e0e5e332b72b83891
3,600,630
import argparse def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Answer Generation arguments') parser.add_argument('--RUN', dest = 'RUN_MODE' ,choices = ['train','val','test'] ,type=str, required=True) ...
27124a5a7c28345e1973d6b987d5e8886dce613a
3,600,631
import re def update(): """Find up to 10 places within view.""" # ensure parameters are present if not request.args.get("sw"): raise RuntimeError("missing sw") if not request.args.get("ne"): raise RuntimeError("missing ne") # ensure parameters are in lat,lng format if not re....
18967e68dbea1b5d3c274005c9dfd92ae6c1295a
3,600,632
def _riccati_bessel_y(degree, argument): """ Riccati-Bessel function of first kind and derivative """ return (np.array(special.riccati_jn(degree, float(argument))) - 1j * np.array(special.riccati_yn(degree, float(argument))))
65162b85a0c2058702377fd209207b2d80e9c739
3,600,633
def fit_vfa_nonlinear(s, fa, tr): """Return T1 based on VFA signals using NLLS fitting. Parameters ---------- s: ndarray 1D array of signals. fa: ndarray 1D array of flip angles (deg). tr: float Repetition time (s). Returns ------- ...
667c4ac86a844bc110bcfcd0c89d51ec106e42a4
3,600,634
def newsletters(request, context): """back to balafon newsletters""" if request and request.user.is_authenticated and request.user.is_staff: view_name = 'admin:{0}_{1}_changelist'.format(get_model_app(Emailing), get_model_name(Emailing)) return make_link( reverse(view_name), _('Email...
5d220d1b5c5856c68a56354eb7d7f1e85a7f7389
3,600,635
def commands_overlap(first, second): """ Returns True if the two given commands overlap in their output targets (regardless of color) """ if isinstance(first, SetAll) or isinstance(second, SetAll): # SetAll will conflict with whatever return True if isinstance(first, SetStrand) or i...
b292d8b5f3bceb4e55a2a6e5b49448ecf662f73f
3,600,636
from functools import reduce def problem(): """ Solve the problem. 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Answer: 232792560 ...
442be80c10b9317c2fc4223ec55123a39c633da9
3,600,637
def overhang(wall): """Calculate the overhang parameter as a function of y along the wall. See _overhang() for details. Parameters ---------- wall : pandas.DataFrame or datautil.DomainWall Location of the zero crossing of Mz. Returns ------- np.ndarray or list of np.ndarray ...
25605af6628a237eae64724e473539c03ab873ff
3,600,638
def ssh_tailc(address:str, filename:str, **kwargs)->Popen: """tail cat and follow via ssh""" proc = Popen(f'ssh {address} "tail -Fc+0 {filename}"', stdout=PIPE, shell=True, **kwargs) return proc
051b244ca17f5b56ebdea30a7f05b82754f08309
3,600,639
import time def timer_profile(func): """ For debug purposes only. """ @wraps(func) def wrapped(*args, **kwargs): start = time.time() res = func(*args, **kwargs) elapsed = time.time() - start elapsed *= 1e3 Timer.timings[func.__name__].append(elapsed) ...
f557bdc60eb2b5d04eae0b3f75ba3f8379f15f51
3,600,640
def raj_logfact(n): """Ramanujan approximation of log(n!)""" f1 = n*np.log(n) f2 = -n f3 = np.log(n*(1+4*n*(1+2*n)))/6 f4 = np.log(np.pi)/2 return f1 + f2 + f3 + f4
ca5c93f83bb8b4956eb616d89f5697fa6be439c1
3,600,641
def post_permission_webhook_view(request): """ Permission webhook used for created or removed permission events. """ event = ar.get_multiformat_body(request, "event") ax.verify_param(event, param_name="event", param_compare=ValidOperations.values(), is_in=True...
c20b1f93ba8e973a608c4405300b870f75c46ce1
3,600,642
def convmtx2_valid(H, M, N): """ 2d convolution matrix with the boundary condition 'valid', i.e., only filter within the given data block. :param H: 2d filter :param M: input signal dimension is M x N :param N: input signal dimension is M x N :return: """ T = convmtx2(H, M, N) s_...
522beb76a5744534c5a5a4bfce707fcd680d8a93
3,600,643
def api_get_theme_display_data(): """ GET: 1.获取主题展示用的多媒体数据 conditions:<array:dict>, Such as:[{'type':<str>, 'names':<array>, 'name_regex':''}] 说明: type-可以是"text", "image", "video", "audio" names-数组,指定要获取数据的name name_regex-字符串,获取匹配此正则的me...
b0c0b75f4294e6d06d45bac250c419b10a7c9521
3,600,644
import json def list_fus_user_policies(fus_client, do_headers: bool = True): """ Call the Fusillade API to retrieve policies grouped by user. :param fus_client: the Fusillade API client :returns: list of tuples of two strings in the form (user_name, policy_name) """ users = list(fus_client.pa...
c77ced9f72968a6ee8121bf34d2b2635510ea572
3,600,645
def parse_netscape_bookmarks(bookmarkHTMFile): """Extract bookmarks and return them in a list of dictionaries formatted in the following way: [ {"url":"http://...", "title":"the title", "private":"0"/"1", "tags":"tag1,tag2,...", "posix_timestamp"="<unix time>", "note":"description"}] Raise a ValueError if the for...
03fbf11ea59bff898a25c9d1198a93a60cc447b3
3,600,646
def remote_call(method): """Decorator to set a method as callable remotely (remote call).""" method.remote_call = True return method
ab276cbdb190185c7e46c5205df25f022a56a097
3,600,647
from typing import Union from typing import Iterable def np_str_len(str_arr: Union[np.ndarray, Iterable[str]]) -> np.ndarray: """ Fast way to get string length in a numpy array with datatype string. Args: str_arr: Numpy array of strings with arbitrary shape. Returns: Numpy array of s...
f74a08d707431a56578a4d2eb84d4b7531d02a97
3,600,648
import argparse def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Find common kmers', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file1', help='Input file 1', me...
05b5494fcf4f94bed504e2e90d10840258fcd0f4
3,600,649
import functools def nodeop(target=None, **kwargs): """ Decorator for creating nodes from functions. """ # This is called when the decorator is used with arguments if target is None: return functools.partial(nodeop, **kwargs) # This is called when the decorator is used without argumen...
c66544db52749e306384495a42217d07eef28c80
3,600,650
def get_last(utdt, longitude): """ Local Apparent Sidereal Time (LAST) """ gast = get_gast(utdt) last = gast + longitude/15. last %= 24. return last
8ba1304a32b7eb9785da02b43450d9f81b30d1ff
3,600,651
from typing import List from typing import Tuple from typing import Optional def get_leader_by_sort(target_graph: nx.MultiDiGraph, clique_graph: nx.Graph, clique: List) -> Tuple[Optional[str], Optional[str]]: """ Get leader from clique based on the first selection from an alphabetical sort of the node id pref...
10e4ba72102f909075ec3f3a5ec0b036c2d3e240
3,600,652
import re def get_user_by_email(user_to_search: str) -> dict: """ Searches for a user when given the user's email. Args: user_to_search: the user's email we are searching for. Returns: Formatted user results if a user is found. """ if not re.match(emailRegex, user_to_search): ...
c4e6240c20e9d9481ca89d36157b80262de7788a
3,600,653
def prep_petroleum_water_intensity(): """ Takes county level petroleum-production values and determines the water intensity for the given county for both unconventional and conventional petroleum production. :return: Dataframe of county-level petroleum water intensity...
cbb5d458af89765374854a8156f0acc60a90b68d
3,600,654
from pathlib import Path def node(ph5, path, class_name): """ Get the node handle of a given path and class name :param ph5: an open ph5 object :type ph5: ph5 object :param path: path to node :type path: string :param class_name: name of class to get :type class_name: st...
2a8090952fdec3dda7490844990f41c8e154c3af
3,600,655
import os def individuals_all(): """Return path to .ttl-file containing _all_ triples.""" path = os.path.normpath( os.path.join( os.path.dirname(__file__), "data", "individuals_with_reasoning.ttl" ) ) return path
d51c5cf49acc4eab107429964518ecd52dbe916f
3,600,656
def delete_payload(): """ Invokes the ControlPlane APIs with a DELETE request. Supports IAM Authentication. Returns: Controlplane API result. """ return invoke_destination_api("DELETE", app.current_request.uri_params['proxy'])
16ce295d3b9acf30db24d405be25e1f86fb00412
3,600,657
def indian_word_currency(value): """ Converts a large integer number into a friendly text representation. Denominations used are: Hundred, Thousand, Lakh, Crore Examples: 1000 becomes 1 Thousand 15000 becomes 15 Thousands 15600 becomes 15.60 Thousands 100000 becomes 1 Lak...
d162725f588d96a7dc3ead80b5278d71187bf4c1
3,600,658
def cutout(image, size=16, color=None, name=None): """This is an implementation of Cutout as described in "Improved Regularization of Convolutional Neural Networks with Cutout" by DeVries & Taylor (https://arxiv.org/abs/1708.04552). It applies a random square patch of specified `size` over an `image` ...
1653f9df3bd91579c00868e7659fd06425a37895
3,600,659
from typing import Union from typing import Tuple import requests def fetch_nab(ts: str, return_X_y: bool = False ) -> Union[Bunch, Tuple[pd.DataFrame, pd.DataFrame]]: """ Get time series in a DataFrame from the Numenta Anomaly Benchmark: https://github.com/numenta/NAB. Parame...
c20c13c3836ad4391ba8cb4461e95141e6be6eb6
3,600,660
import os def listdir_matches(match): """Returns a list of filenames contained in the named directory. Only filenames which start with `match` will be returned. Directories will have a trailing slash. """ last_slash = match.rfind('/') if last_slash == -1: dirname = '.' ma...
8b47709f09453060739215a1b2ac275a4dfc7f11
3,600,661
def get_equips(equipments): """ Join all properties needed """ itens = [] for equip in equipments: equip_dict = prepares_equips(equip) itens.append(equip_dict) return itens
c642dee1582da1cd0d108aa3a3d991bc833c826a
3,600,662
def annual_NAIP(year, region): """Create an NAIP mosaic of a specified year for a specified region. Args: year (int): The specified year to create the mosaic for. region (object): ee.Geometry Returns: object: ee.Image """ start_date = ee.Date.fromYMD(year, 1, 1) end_...
ff9f1c54ce56869846baa8c59d08dd2bb1d370f2
3,600,663
import torch def decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in cen...
f523fb0d905aba612cf67816d6aa0ec549dbebce
3,600,664
def make_protocol(protocol_name, device): """Make a protocol object factory function.""" return protocol2object[protocol_name](device)
0d830962c47dcb4fe926a4d37d4503f76ad67749
3,600,665
def create_parser() -> OptionParser: """Initialize parser with options.""" formatter = IndentedHelpFormatter( indent_increment=2, max_help_position=56, width=120, short_first=1 ) parser = OptionParser(usage=USAGE, epilog=EPILOG, version=f'%prog {VERSION}', formatter=forma...
17fa20cb3c2d98696440991f646c6f7343d06ac2
3,600,666
def txfDate(date): """Returns a date string in the TXF format, which is MM/DD/YYYY.""" return date.strftime('%m/%d/%Y')
fd1f19b4080447379ec3ec57be0f2af047099673
3,600,667
from typing import Tuple async def check_audio_support(try_install: bool = False) -> Tuple[bool, bool, bool]: """Check if sox and/or ffmpeg are present.""" cache_key = "audio_support_cache" if cache := globals().get(cache_key): return cache # check for SoX presence returncode, output = awa...
5c8defaa5a7e20d9b8934532516388c879a1916a
3,600,668
from typing import Optional def clamp( data: NodeInput, min_value: ScalarData, max_value: ScalarData, name: Optional[str] = None ) -> Node: """Perform clamp element-wise on data from input node. @param data: Input tensor. One of: input node, array or scalar. @param min_value: The lower bound of the <...
4f45e1f2c2560ff60669f80e76bb969f88a03d97
3,600,669
def get_arcis_makeai_params(path_to_file): """ Returns dict {'param':value} """ params = np.genfromtxt(path_to_file, usecols=np.arange(0,3), skip_header=1, dtype='str') params[:,2] = params[:,2] params = params[:, [0,2]] params = dict(params) for key in params: params[k...
22a14c1d10311cf27b5eef89026a5c7634a74f62
3,600,670
import datetime def sobject_to_dict(obj, key_to_lower=False, json_serialize=False): """ Converts a suds object to a dict. Includes advanced features. :param json_serialize: If set, changes date and time types to iso string. :param key_to_lower: If set, changes index key name to lower case. :param ...
5915fdd52bee26a0f4bfac67fc1140ab3d6a49a3
3,600,671
def check_assist(exp): """ :param exp: expression string :return: True if assist operator """ return exp in Types.AssistOp
2d2a943d577e0a106839a2ae5dd952e0b9c19b25
3,600,672
from datetime import datetime def get_account_oldest_balance(account: Account) -> ty.Tuple[float, datetime]: """Compute and return the oldest possible account balance.""" current_balance: float = account.get_solde() now = datetime.now() long_before = now - timedelta(weeks=100 * 52) operations = l...
a0b853ff180ac3378cdb0e0e0a4753725f70f406
3,600,673
def _make_msa_df(chain_features: pipeline.FeatureDict) -> pd.DataFrame: """Makes dataframe with msa features needed for msa pairing.""" chain_msa = chain_features['msa_all_seq'] query_seq = chain_msa[0] per_seq_similarity = np.sum( query_seq[None] == chain_msa, axis=-1) / float(len(query_seq)) per_seq_g...
f2ec656d211adb4174596ae86a563b5fadc69726
3,600,674
def get_snapshot(connection, snapshot_id): """Returns a snapshot with *snapshot_id*.""" res_set = get_snapshots(connection, [snapshot_id]) if not res_set or len(res_set) != 1: raise Exception('unexpected result from get_snapshots') snapshot = res_set.pop() return snapshot
09df168af900ed16b593fe476f02dea70a3bc9cb
3,600,675
def rgba(r, g, b, a = 255) : """Create Rgba instance based on r,g,b,a values""" return Rgba( [r, g, b, a] )
4e4c05054836124acc6858aa4b4bb5472a07b7ab
3,600,676
import numpy def getgridparams(): """ return grid parameters in a python friendly way Output: [ Xul, Yul, xsize, ysize, rows, cols] - xul - x upper left centre - yul - y upper left centre - xsize - size of a cell in x direction - ysize - size of a cell in ...
efd3506699984ce5ad140f7f0a0a1ea6a8a938f7
3,600,677
def get_hospitals_current(): """ Return all Hospitals Developments """ hospitals = db.session.query(HospitalDevelopment).all() return jsonify(__as_feature_collection(hospitals)), 200
89c37beb196a70ada8934e33fba88e459efb8378
3,600,678
def get_option(*args, **kwargs): """ Returns value of any of the following OpenQL options: Opt. Name : Default : Possible values 'log_level' : LOG_NOTHING : 'LOG_{NOTHING/CRITICAL/ERROR/WARNING/INFO/DEBUG}' 'output_dir' : 'test_output' : <output directory> 'scheduler' : 'A...
448d75e2f7a2f02a7b46479021c8f88055abcb4f
3,600,679
from typing import Iterable from pathlib import Path def to_multi_path(paths: Iterable[Path]) -> Path: """Returns a multi-path object from all given paths and their sub-paths. .. versionadded:: 0.17 """ multi_path = Path() for p in paths: multi_path.extend_multi_path(p) return multi_...
f247379e4d36502909b3593d7ea116bb77366e90
3,600,680
def aligned_malloc(shape, dtype, alignment=16): """allocates numpy.array of specified shape, dtype and memory alignment such that array.ctypes.data is an aligned memory pointer shape is numpy.array shape dtype is numpy.array element type alignment is required memory alignment in bytes """ ...
9d5734f78a69e914279b21b8a0889fe26fa2c9b5
3,600,681
import cv2 from PIL import Image import io import base64 def embed_image_html(imgBGR, target_width=TARGET_WIDTH, target_height=TARGET_HEIGHT): """ Creates an image embedded in HTML base64 format. """ if target_width is not None: imgBGR = _resize(imgBGR, t_width=target_width) elif target_height is...
c117bb180f832872386965dde420ebda691e5309
3,600,682
def create_pitch(dff, strategy=None): """Creates the whisky returns by pitch chart""" data = [] if strategy == 2: xcol = 'annual_return' xtitle = 'Annual % return' ycol = 'APR_5%' ytitle = 'Compound Annual Return, %' else: xcol = 'days_to_close_spread' xti...
2ece1f812ecb3a7c3b3e1f127b88a5d8eb1abbaa
3,600,683
def get_institutes(variable): """Return the institutes given the dataset name in CMIP6.""" dataset = variable['dataset'] project = variable['project'] try: return CMOR_TABLES[project].institutes[dataset] except (KeyError, AttributeError): return []
1dc946496ff4b0ff6830adc7d2452378c1154b82
3,600,684
def unet(height, width, channels, classes, features=64, depth=4, temperature=1.0, padding='valid', batchnorm=False, dropout=0.0): """Generate U-Net model introduced in "U-Net: Convolutional Networks for Biomedical Image Segmentation" O. Ronneberger, P. Fischer, T. Brox (2015) Arbitrary numb...
b2b3c1a8ba5213b34ba8e1b7dc40a378a23cea9b
3,600,685
import requests import json def get_kml(dataset=None): """Return kml for dataset.""" # get callback, source, and dataset source = request.args.get('source') if dataset is None: return jsonify({ 'success': False, 'message': "Cannot recognize dataset: %s" % dataset, ...
b526688db10fe781afe80ff8ff92c9f95edce1e3
3,600,686
def construct_attrs_table(sub_layers_list, node_name2sub_layers=None, module_name=None): """ 构造不同属性的表格。 """ def get_node_name(sub_layers): for k, v in node_name2sub_layers.items(): if v == sub_layers: node_name = k break return node_name sub_la...
224ae069b013cafa51d2547825020e584f1bcb69
3,600,687
def diffuse_colors(n, l, dark, light): """ Shader calculation for a normal and a light vector and light and dark colors. Args: n(numpy.array): Unit normal vector l(numpy.array): Unit vector in the direction to the light dark(numpy.array): RGB dark color light(numpy.array)...
1644022d302299bb3288bd7bd113cf381bb35645
3,600,688
def allInstances(cls): """Return cls instances for each of this class's set""" items = [ (choice.value, cls(name=choice.name)) for choice in cls.set.values() ] items.sort() items = [v[1] for v in items] return items
702a77b9c247ec7976201cd0829a728c6c5fdd1f
3,600,689
def linspace(start: float = 0.0, stop: float = 1.0, num: int = 50): """ Returns evenly spaced numbers over a specified interval. See syntax here: https://numpy.org/doc/stable/reference/generated/numpy.linspace.html """ if not is_casadi_type([start, stop, num], recursive=True): return _onp.l...
aa6a2f003e43e399b7cb4e2eef4cf811860a1691
3,600,690
def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]): """Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ...
17e268540b344131130b022e2433a13d9e0d1330
3,600,691
def classify(train=None, test=None, data=None, res_dir="res/", disp=True, outfilename=None): """Description of compare compare multiple classifier and display the best one """ utils.print_success("Comparison of differents classifiers") if data is not None: train_features = data["train_featur...
4b8cfec3db44a5477fea766b2e676155121df95e
3,600,692
def _map_sbs_sigs( df: pd.DataFrame, ref_df: pd.DataFrame, ref_type: str, sub_index: str = 'Substitution Type', ) -> pd.Series: """ Map Single-Base Substitution Signatures. ----------------------- Args: * df: pandas.core.frame.DataFrame with index to be mapped * ref_d...
c93f170717b97981f27c642a7b64957d36d822c0
3,600,693
import os def get_test_library_paths(prepend=None): """Returns a sequence with all configured test library paths. Parameters ========== prepend : list sequence with additional paths that are prepended to the output """ # locations from configuration testlibdirs = [os.path.expandvars...
9fadacc511e2e1f50db12f693be044a2a97dfac9
3,600,694
def _dvalid_checkfocus( focus=None, focus_half_width=None, lines_keys=None, lines_lamb=None, lamb=None, ): """ Check the provided focus is properly formatted and convert it focus specifies the wavelength range of interest in which S/N is evaluated It can be provided as: - a spec...
b4a49ae53b128efb6f93c8783cfa25685d7a7b78
3,600,695
def mu_calc(Wv, delta): """ Calculates the mu function used by Thm. 1 (Katz and Reggia 2017). Wv should be the (N by 1) numpy.array W.dot(v) for some point v. delta should be an (N by K) array of deltas to Wv. returns (N by K) numpy.array mu, where mu[i,j] is the maximum of tanh'' over (Wv[i] ...
9b891ca74c0f2b12972d7137d82c3227c97b7a89
3,600,696
from typing import Union def get_json_url(year: Union[str, int], kind: str = "photos") -> str: """Returns url for the json data from news-navigator for given `year` and `kind`""" return f"https://news-navigator.labs.loc.gov/prepackaged/{year}_{kind}.json"
0c7650f667cb1fceebbd73e7a6eaf00145061d38
3,600,697
def d_linalg_norm__d_x(x, return_norm=False): """ Last dimension is normalized. Calculate Jacobian xn = x * (x^2 + y^2 + z^2)^(-1/2) d xn / d x = (y^2 + z^2) * (x^2 + y^2 + z^2)^(-3/2) d yn / d y = (x^2 + y^2) * (x^2 + y^2 + z^2)^(-3/2) d zn / d z= (x^2 + z^2) * (x^2 + y^2...
a4b2eefc93daa0959668b2905beaddbb76403520
3,600,698
def SEQUENCE(*args) -> Function: """ Returns an array of sequential numbers, such as 1, 2, 3, 4. Learn more: https//support.google.com/docs/answer/9368244. """ return Function("SEQUENCE", args)
37ff63df9df9ebf3b2294aaeb3d6126b00641949
3,600,699