content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Any def cost(exprenv: ExprWithEnv, inputs: Any = None, approx_mode: bool = True) -> float: """Evaluates the cost of the expression `expr`. If `expr` evaluates to a lambda, and `inputs` is not None or `approx_mode` is true, then returns the cost of evaluating the lambda on the provided ...
6e22e01d74959078382f743ca62daf149641c214
3,597,437
import numpy def classifier_summary_stats(table, stat, factors): """returns a table of summary statistics from the table""" dvs = table.distinct_values(factors) rows = [] for dv in dvs: sub = table.filtered(lambda x: tuple(x) == dv, columns=factors) est = sub.tolist(columns=stat) ...
4673134f3d233428031f40c467b2a3294e6b2d31
3,597,439
def list_annotations_for_paring(_base_path, _split, threads): """ List Annotations by Split :param _base_path: Base Path of Dataset :param _split: one of ["train", "test", "validation"] :param threads: N Threads for Multi-Threading. [Default Cpu_Count] :return: List of Annotations (Dicts) ""...
53c38257184e33d2f272f5900b1f9b3e6c8760b6
3,597,440
def get_website_url(site_settings=None): """ A shortand to retrieve the full website URL according to Site ID and HTTP protocole settings. Keyword Arguments: site_settings (django.conf.settings): Settings object, if not given the method will be unable to determine if HTTPS is enable...
d7629af51ca68ba3a604b53a5e01cd4e62a2b6d9
3,597,441
def is_schema_valid(dataframe, schema): """Check if a schema is valid for initializing Woodwork on a dataframe Args: dataframe (DataFrame): The dataframe against which to check the schema. schema (ww.TableSchema): The schema to use in the validity check. Returns: boolean: Boolean i...
f99a26e4bc1646c4a784e8146b763a83f1ddae72
3,597,442
def recent_events(num=10): """ Returns a QuerySet of Events that happened recently. `num` is the number returned. """ return Event.objects.select_related("venue").order_by("-date")[:num]
3a088ac170efde4beaeadeb1e4592a38d5f6f88a
3,597,443
def xl_col_to_name(col, col_abs=False): """ Convert a zero indexed column cell reference to a string. Args: col: The cell column. Int. col_abs: Optional flag to make the column absolute. Bool. Returns: Column style string. """ col_num = col if col_num < 0: ...
62fcc4d6c4d0ac77098e49f3de74eaecea54313c
3,597,444
async def gotoStow60(command: HALCommandType): """Send the telescope to (121, 60, 0).""" return await goto_position(command, "stow_60")
0bc3ccafaf30c1a8da6cb469976ca96d3649e2be
3,597,445
def main(args): """Compute the QR decomposition of a matrix. .. Keyword Arguments: :param args: The program arguments. .. Types: :type args: A argparse namespace ojects containing the program arguments. .. Returns: :returns: 0 If the program ran successfully, otherwise non-zero. :rtyp...
1d44977c6e44a3f144e0492a1c560ba682a81009
3,597,446
def _noise_estimation_worker(N, nctr, metric, mode, center, summary_center, summary_spread, seed=0, n_iter=DEF_BITER, sync=True): """Helper function for noise_estimation(). N: list of one neuron's responses. Each element's shape = (# of reps, # of images) nctr: the central tendencie...
bbdbfbcc6ae02c0d152126a33c23d5c889955d55
3,597,447
def make_layout(): """Define the layout.""" layout = Layout(name="root") layout.split(Layout(name="header", size=4), Layout(name="main")) layout["main"].split_column( Layout(name="info", size=4), Layout(name="body", ratio=2, minimum_size=60) ) layout["info"].split_row(Layout(name="time")...
b32291d51b228a7f465406db7a9640f46a6800e5
3,597,448
def get_topic_command(config: ConfigType) -> str: """Get command topic.""" return _get_topic_cmnd(config)
8e15b36c36ca9b061998e69f817feebc83693df9
3,597,449
def base58_encode(num, alphabet=ALPHABET): """Encode a number in Base X `num`: The number to encode `alphabet`: The alphabet to use for encoding """ if (num == 0): return alphabet[0] arr = [] base = len(alphabet) while num: rem = num % base num = num // base ...
a5d32cf31d0d1e06178032ff9b0aa71662f13143
3,597,450
def nereid_default_template_ctx_processor(): """Add Decimal and make_crumbs to template context""" return dict( Decimal=Decimal, make_crumbs=make_crumbs, )
7f104c78a9a089d47fe15f8eb2e0ec0f7a7e9a35
3,597,451
def find_symbol(app, loctx, key, locals=None, dependencies=None): """Look up a symbol, using the universal laws of symbol-looking-up. To wit: - "_" and other immutables - locals (which may be predefined or start with "_") - instance properties - world properties - realm-level instance proper...
d7ada942c3cfb6d19f2c1172bea3667f392cf913
3,597,452
from pathlib import Path def create_h5temp(rows: int, cols: int, tr: int, ts: int, ) -> Path: """Create temporary HDF5 rawfile. Args: rows (int): Number of rows. cols (int): Number of columns. tr (int): Temporal r...
b9809a9f48d74be23b20b76cbad74a4f488fdd6d
3,597,453
from pm4py.algo.filtering.ocel import objects_ot_count from typing import Dict def filter_ocel_object_per_type_count(ocel: OCEL, min_num_obj_type: Dict[str, int]) -> OCEL: """ Filters the events of the object-centric logs which are related to at least the specified amount of objects per type. E.g. pm...
5b39e14073b37ac2b7967cb23db0d41c8561603b
3,597,454
def sell(): """Sell shares of stock.""" if request.method == "POST": try: sell_shares = int(request.form.get("shares")) except ValueError: return apology("invalid shares") share_quote = lookup(request.form.get("symbol")) try: user_shares = db...
8684c0527cb8c27933a9a2ae508a33766231d41b
3,597,455
def resize(image, IMG_SIZE = 512): """ resize the image to have the same size between all the images (because of different image resolutions) and conversion of the color of the image because by default cv2 reads image in blue color in the resize, the ration = 1 by default because pixel height = pixel width imag...
64eb6f2e3a2d20bb0305c081926177e59e47fb7d
3,597,456
def extract_target_sdk_version(doc): """Returns the targetSdkVersion from the manifest. Args: doc: The XML document. Raises: RuntimeError: invalid manifest """ manifest = parse_manifest(doc) # Get or insert the uses-sdk element uses_sdk = get_children_with_tag(manifest, 'uses-sdk') if len(use...
4f9632cb1bf219ab789afdef00715da046694323
3,597,457
def crop_square(img: np.ndarray, square: chess.Square, turn: chess.Color) -> np.ndarray: """Crop a chess square from the warped input image for occupancy classification. Args: img (np.ndarray): the warped input image square (chess.Square): the square to crop turn (chess.Color): the curr...
859cb6c2b3cb671625dd2a7315667fbe0342b0ff
3,597,458
def compute_average(objectives, results, n_samples=10**6): """Compute the average value of the provided objective functions using a monte carlo estimate Input dictionary `objectives` must be of the same form as `objective_functions.objectives` Input results must be output from `optimize....
7bcc0c1c3a99947500ed6485c3793d26583021b4
3,597,459
def noncentral_chi_square(df, nconc, shape=[]): """noncentral_chi_square(df, nconc) or chi_square(df, nconc, [n, m, ...]) returns array of noncentral chi squared distributed random numbers with df degrees of freedom and noncentrality parameter.""" if shape == []: shape = None return mt.noncentral_ch...
f0a30d23add781edb251977062d867fbd0dbb6a3
3,597,460
def susceptible(): """ Real Name: b'Susceptible' Original Eqn: b'INTEG ( -IR, 9999)' Units: b'' Limits: (None, None) Type: component b'' """ return integ_susceptible()
c85b38874fdbbd4d945c822f6001b6b211616fe6
3,597,461
def get_all_interfaces(): """Get all interfaces, up or down..""" return InterfaceInfos.from_system(require_up=False)
566d7daa8d76365fc747ca355c7af651f516d124
3,597,462
def fopen(space, fname, mode, use_include_path=False, w_ctx=None): """ fopen - Opens file or URL """ if not is_in_basedir(space, 'fopen', fname): space.ec.warn("fopen(%s): failed to open stream: " "Operation not permitted" % fname) return space.w_False try: ret...
fba65a55a82c3833155a357e1234579732ac4c1e
3,597,463
def get_object_filename_from_hash(hash_value: str) -> str: """ 根据Hash得到Object文件路径 :param hash_value: :return: """ return f"{namespace_path}/assets/objects/{hash_value[:2]}/{hash_value}"
e6300eafdd1b0571ca0d2713083c2c1a3ee0f38f
3,597,465
def _pointed_type(tp): """Return the pointed type if this is a pointer, otherwise None.""" tp_nam = tp.__name__ if tp_nam.startswith("LP_"): if tp_nam.startswith("LP_c_") or tp_nam.startswith("LP_4_") or tp_nam.startswith("LP_8_"): return tp_nam[5:] return None if tp_nam ==...
bcd92c3b824016c552c77627cd9ec8b411179a26
3,597,466
def make_image_carousel_column(image_url=None, image_resource_id=None, action=None, i18n_image_urls=None, i18n_image_resource_ids=None): """ Create a image carousel column object. ...
7abf182f2255d0486136dcbe64ea8de4a63146c9
3,597,467
def euclidean(x,y): """ Euclidean distance is a well-known distance metric. It is defined as follows: Sum of ( sqrt of (x - y)^2 ) """ assert (isinstance(x, BayesNet) and isinstance(y, BayesNet)), 'Must pass in BayesNet objects.' assert (x==y), 'Passed-in BayesNet objects are not structurally equal.' distanc...
d75337c279f2b39abe8f3c816598aa217bd603c6
3,597,468
from typing import Dict def mock_influxdb(monkeypatch): """mock pms.extra.influxdb.client_pub""" def client_pub( *, host: str, port: int, username: str, password: str, db_name: str ) -> PubFunction: def pub(*, time: int, tags: Dict[str, str], data: Dict[str, float]) -> None: p...
9fa561cc13aa4077e5b8509ef02a77789d67a2f4
3,597,469
def db_size(): """returns the number of entries in the database INPUT OUTPUT n the number of entries in the database """ out = False try: con = psycopg2.connect("host='localhost' dbname='nba_tracking' port='5432'") cur = con.cursor() cur.execute("SELECT COU...
4a4b147e6c8eb5bd90ba7f9172b6bdb8d54a4da2
3,597,470
import binascii def from_address(text): """Convert an IPv4 or IPv6 address in textual form into a Name object whose value is the reverse-map domain name of the address. *text*, a ``text``, is an IPv4 or IPv6 address in textual form (e.g. '10.28.141.171', '::1') Raises ``dns.exception.SyntaxError...
b174fa451d63123733ffc8716ce2e703cdd9d641
3,597,471
def activity(request, atype=None, value=None): """ Generate the Recent Activity page. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param atype: How to limit the results ("byuser", "bytag", "bycomment"). :type atype: str :param value: If l...
bd59e0239c677cc87c9be096c3b402056c7a7e81
3,597,472
import ctypes def _NativeStructToH5T(ctype): """Creates an HDF5 Type object from a ctypes type. This function exists as h5t.py_create does not respect field alignment, and the conversion of ctypes.c_char to length one strings is undesired. Args: ctype: Type to convert. Returns: HDF5 type object...
daecb552cc8bb2e542563287d7c54248ad134f1f
3,597,473
def date_converter(): """Converter for date.""" return Converter(date_decode, date_encode)
7a3b6e391ffd63b862b55941775ff8f0ef8859f7
3,597,474
from typing import Optional async def get_project_summary( request: Request, limit: int = 20, token: Optional[str] = None, connection: Connection = get_project_readonly_connection, ) -> ProjectSummaryResponse: """Creates a new sample, and returns the internal sample ID""" st = WebLayer(connect...
3b9d1349425fe6f9c7bbcc338c8503eaa72e7edc
3,597,475
def LCS(seq1, seq2, gap_open_penalty=0, gap_extend_penalty=0, match_reward=1, mismatch_penalty=-np.inf): """return Longest common subsequence alignment Parameters ---------- seq1 : list list of activities, which is the first sequence to be aligned seq2 : list list of activities, whi...
ac922e72352b149b0e627879dc8e831df3bdec3b
3,597,476
def convert_dtype_to_np_dtype_(dtype): """ Convert paddle's data type to corrsponding numpy data type. Args: dtype(np.dtype): the data type in paddle. Returns: type: the data type in numpy. """ if dtype is core.VarDesc.VarType.FP32: return np.float32 elif dtype is ...
133f277190927734e2b182d5284ffed4342045e5
3,597,477
from typing import Dict from typing import Callable def _signature_changed(intent: Intent, intents: Dict[Text, Callable]) -> bool: """ Denotes if function signature has been altered in the UI :param intent: an intent from UI :param intents: dictionary of intent implementations :return: """ ...
5fef4ebcc7d56b67899efca68427245b27da9d67
3,597,478
def find_match(subtime, time_array, mode="larger"): """find closet value in an array to a given value subtime (float): time_array (np.ndarray): (N, ) """ if mode == "nearest": return (np.abs(subtime - time_array)).argsort()[:2].tolist() elif mode == "larger": idx = max(0, np.sear...
c042e3574998f8cb4fcb305b6aa9222a95738e79
3,597,480
def split_count_and_lensing_maps_by_datasets(val=False, config="g", name="map-f1z1.fits.gz", path_to_output=PATH_TO_OUTPUT, field=0, covariance=False, zscale=False, nest=True, npix=NPIX...
b40aa10dc180bcd468c8d69edc0c5808e754e893
3,597,481
from typing import List def convert_kusto_response_to_dict(kusto_response: KustoResponseDataSet, page: int = None, page_size: int = None, limit: int = None) -> List[dict]: """ Converting KustoResponseDataSet object to dict type. Support two use cases of pagination: 'Manu...
aa628f29b4b629e8d5299c443ef9109c7af8af65
3,597,482
import numpy def isnan(s): """ calls :epkg:`numpy:isnan` but checks it is a float first @param s object @return boolean @raise TypeError if ``s`` is not a ``float`` The function imports :epkg:`numpy` (delayed import). """ if isinstance(s, float): ...
f9a3fd11f4697468084659f1375e8fea2328908a
3,597,483
def getNextSetOfImages(form, sampling_method): """ Uses a sampling method to get the next set of images needed to be labeled. Parameters ---------- form : LabelForm class object form to be used when displaying label.html sampling_method : SamplingMethods Function function that r...
ba38df19ab05cb4b6e797f136cd9797465404330
3,597,484
def compute_distance_to_nearest_corner(xy, arena_size): """Returns euclidean distance to nearest corner of the arena. Assumes that one corner of the rectangular environment is (0, 0) and others are defined by environment shape limits set by arena_size. :param xy: array like (x_position, y_position) ...
ef3cf2885393e7b203ca1312e8aab7c1fd32a3d2
3,597,485
def is_supported_anonymization_type(arg): """Returns true if anonymization type is supported""" return arg in SUPPORTED_ANONYMIZATION_TYPES
43b2d1c4c1b5624f9c9cb5480031310b23cc0a7c
3,597,486
def set_style(name, height, bold=False): """ set style for excel """ style = xlwt.XFStyle() # 初始化样式 font = xlwt.Font() # 为样式创建字体 font.name = name # 'Times New Roman' font.bold = bold font.color_index = 4 font.height = height # borders = xlwt.Borders() # borders.left = 6 ...
5f91c4d911a93fa504769e5796962497f7161f26
3,597,487
def print_element(element): """ Pretty- print an lxml.etree element. Parameters ------------ element : etree element """ pretty = etree.tostring( element, pretty_print=True).decode('utf-8') print(pretty) return pretty
cdeeaee51f858121364e87919401bef4917c16cf
3,597,488
def releaseJ1939Address(address) -> bytes: """ Release a J1939 Address (31) (1 byte) Args: - Address (1 byte) - the address to release. This doesn't do anything special with the J1939 bus. All it does is tell your adapter not to use this address anymore. """ return sanitize_msg_param(a...
e883695002f0f65796e0430619f34caea29495c1
3,597,489
def failover_segment_create(context, values): """Insert failover segment to database. :param context: context to query under :param values: dictionary of failover segment attributes to create :returns: dictionary-like object containing created failover segment :raises exception.FailoverSegmentExi...
13fa7dc94e5ba12394509f4bf87934c85003b759
3,597,490
def make_dirsig_command(sim, options=None, dirsig='dirsig', logfile='log'): """ Makes a command to rund dirsig. Args: sim (str): A string containing the name of the sim file. options (str, optional): A string contating options to pass to dirsig. The default is None. dirsig (...
0cf84907d08fcc60bac4f1a10d8be5ea9f01eddb
3,597,491
def percentage(part, whole): """Calculating the coverage of Acidobacteria reads from the set of sequences.""" return 100 * float(part)/float(whole)
c1a5778c57da8ad008a9d0d5a99e1c5214d42426
3,597,493
def asym_tanh(x, a, b, c1, c2, d): """Return asymmetric tanh. Arguments: x, a, b, c1, c2, d Return: x >= d: a + b*tanh(c1(x-d)) x < d: a + b*tanh(c2(x-d)) """ if hasattr(x, '__iter__'): y1 = np.array(a + b*np.tanh(c1*(x[x >= d] - d))) y2 = np.array(a + b*np....
3854cff12d9e8ea9d092171b1dae1d5852fac7be
3,597,495
import hashlib def md5_(value: str) -> str: """ A function to return the md5 hash of the given string. :param value: The string to hash. :return: The hashed string. """ return str(hashlib.md5(value.encode()).hexdigest())
e86553ab1c57f48f5e972df1e7abb5237f4d3972
3,597,496
import requests import json def compute_value(model_id, passport_data): """ passport-data acts as a signaling div for the site to determine if any data from the CMP API has been loaded. If not (API down or model not present), only the tissue and cancer type will show. """ if passport_data is n...
3037293fea1c83a9d70baf57e145ef5a93990d1f
3,597,497
def sharpe(w, mean, cov, benchmark_rate=0.02): """ Computes: :math:`-(r_{p} - r_{bm})/\sigma_p` :param w: asset weights :param cov: annaulized portfolio covariance :param mean: annualized portfolio mean returns :param benchmark_rate: risk free rate or some other benchmark :return: sharpe ra...
f51b7c1c053ab701e6dc0c26b40791623c49fa0e
3,597,498
from functools import reduce import operator def get_from_dict(data_dict, map_list): """ get_from_dict """ return reduce(operator.getitem, map_list, data_dict)
d0055c144eee26d4d6548ccc76bdc858345b2471
3,597,499
def make_dist(): """ Returns: The class size distribution """ class_size_dist = { 7: 8, 12: 8, 17: 14, 22: 4, 27: 6, 32:12, 37: 8, 42: 3, 47: 2 } return class_size_dist
5f9164052d8ea51a749919e470b3cc08e6a7cc06
3,597,500
def dc_user(request, username, data=None): """ Show (:http:get:`GET </dc/(dc)/user/(username)>`) details of a user (username) with access to a specific datacenter (dc). .. http:get:: /dc/(dc)/user/(username) :DC-bound?: * |dc-yes| :Permissions: * |Admin| ...
61f80021f2fb03526c4751c26b59b3b74d6f5b2d
3,597,501
def has_multiple(data): """Checks if data has multiple entries (list of lists or (n,d) numpy array)""" return (is_numpy(data) and len(data.shape) > 1) or is_double_list(data)
c45d8f7494483200f887a1e2cb52b5bef79e49a5
3,597,503
def _item_to_entry(iterator, resource, loggers): """Convert a log entry resource to the native object. .. note:: This method does not have the correct signature to be used as the ``item_to_value`` argument to :class:`~google.api_core.page_iterator.Iterator`. It is intended to be ...
d70e72930a7c5e54d70183e8bcd8dffbe689ae83
3,597,504
def brightness_transform(data_sample, mu=0.0, sigma=0.3, num_patches=324, num_channel=2, shape_data=None, per_channel=True, p_per_channel=1): """Performs additive brightness transformation""" assert shape_data is not None, "Data shape should not be None" data_sample_patch = [] ...
5e019972db8fb351a38ba58e7cde86b34f9488b9
3,597,505
def idFormat(id_num): """Format a numeric id into 5-digit string. Paramters --------- id_num: str A unique string number assigned to a User or Request. """ if len(id_num) == 1: id_num = "0000" + id_num elif len(id_num) == 2: id_num = "000" + id_num e...
a3afb52dd552fe7eb6e971bd3f889bb114ee505c
3,597,506
def thumbnail(path, filename, description): """ Returns the HTML to show an image including thumbnail. Assumes the thumbnail is called 'thumbnail_foo.jpg.png' if the image is called 'foo.jpg'. Path should be relative inside static root. Description is used for alt-text and mouseover....
9b2b04518da48dfa3899bf50b706ecd244c6a5be
3,597,507
def obtemDadosCadastraisCVM(compAtivas=True, codCVM=False): """ Returns a dataframe of Registration data for all Companies available at http://dados.cvm.gov.br/dados/CIA_ABERTA/CAD/DADOS/cad_cia_aberta.csv """ url = "http://dados.cvm.gov.br/dados/CIA_ABERTA/CAD/DADOS/cad_cia_aberta.csv" #s = request...
f6795f1e5ae3c46cae2d4dbf57a245f078293a84
3,597,508
def rand_alt_mat(N): """ Generates a random N x N permutation matrix of determinant +1. """ Q = np.eye(N, dtype='int') s = 1 while s > 0: p = np.random.permutation(np.arange(N)) s = perm_parity(p) return Q[:, p]
762f2a83e93b8a177df070f870ed3a4668c8e847
3,597,509
import time def eeccsd_matvec_singlet(eom, vector, kshift, imds=None, diag=None): """Spin-restricted, k-point EOM-EE-CCSD equations for singlet excitation only. This implementation can be checked against the spin-orbital version in `eom_kccsd_ghf.eeccsd_matvec()`. """ cput0 = (time.clock(), ...
f6268542b4f54e264fa279aeabc73d2ecf0063fb
3,597,510
def clip_catch(automated_df,manual_df): """ Function that determines whether or not a human label has been found across all of the automated labels. Args: automated_df (Dataframe) - Dataframe of automated labels for an audio clip. manual_df (Dataframe) - Dataframe of human labels for an aud...
1c391f7ba8677cce1bd33be57b3bc4b7cc89675f
3,597,511
def get_latest_update(feed): """ Retrieves the date of the last update from an RSS feed. Args: feed: URL to the feed or FeedParser representing the parsed feed. Returns: The date of last update as a struct_time. """ feed = _parse_feed_if_necessary(feed) update_dates = (e.ge...
705b91c619285ed987394194e16dd595cd86d9d3
3,597,512
def next_multiple(query, multiple): """Get the next multiple Args: query (int): To test multiple (int): Divider Returns: int: Next multiple of divider """ result = query while result % multiple: result += 1 return result
e76e59e94e7ac72dbcf86a6c99a17229acc7a15d
3,597,513
def prime(var): """Return primed variable.""" assert not isprimed(var), var return var + PRIME
bc937ea754c1cced59f57d3eff8f51512ba5326d
3,597,515
import re def parse_requirements(file_name): """ from: http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy """ requirements = [] with open(file_name, 'r') as f: for line in f: if re.match(r'(\s*#)|(\s*$)', line): continue if re.match(r'\s*-e\s+', l...
e599607bf8d4cc4137f07c4d57041fc795fa540d
3,597,516
def load(fp, key_delimiter=DEFAULT_KEY_DELIMITER, dict_delimiter=DEFAULT_DICT_DELIMITER): """ Load dictionary from FDF file in file-like object :param TextIOWrapper fp: the file-like object to open :param str key_delimiter: the delimiter between the key and value :param str dict_delimiter: the delimite...
015dc5ff5f8435981932b394539d3d1cef623164
3,597,517
import time def nlinvns(Y, n, *arg, DTYPE=np.complex64, DTYPE_real=np.float32): """Non-linear inversen based Coil sensitivity estimation. Parameters ---------- Y : numpy.array Data used for estimation n : int number of Gausse-Newton iteration steps realConstr : bool ...
03754af211a7392625c85788d186f59c4ba20e5e
3,597,518
def astar_search_graph(problem, h=None): """A* search is best-first graph search with f(n) = g(n)+h(n). You need to specify the h function when you call astar_search, or else in your Problem subclass.""" h = memoize(h or problem.h, 'h') iterations, all_node_colors, node = best_first_graph_search_for...
850385eaffd6f73ee88fe6a09fef42f7143229d6
3,597,519
def cmd_factory(cmd, doc=None): """ Factory to create GCode Command Functions. """ def cmd_fcn(self, **kwargs): f""" {cmd}:""" args = list() # Loop through each of the given arguments for key, value in kwargs.items(): # If the value is a known numeric type ...
438d787795fe82cf581a11d680932cecadb18349
3,597,520
def tierpsy_trajectories_summary( fname, filter_params, time_windows, time_units, only_abs_ventral=False, selected_feat=None, is_manual_index=False, delta_time=1/3): """ Calculate the trajectory summaries for a given file fname, within a given time window (units of start time and end...
ff504d0983a6208b36ca6350fa5dc046ac278c16
3,597,521
import tempfile def burn_subtitles_into_video(video_path, subtitle_path, output_path): """ Create new video with subtitles burned in :param video_path: input video path :param subtitle_path: subtitle input path :param output_path: video output path :return: File name that it has written to ...
410fb27fd73a541323086a32ff5e52e6d1f3e078
3,597,522
def change_dict_structure(dict_list): """Takes list of dicts from db_query and changes to dict with key=id, value = text (used for metrices). Args: dict_list (list): List of dictionaries from db_query. Returns: texts (dictionary): Dictionary with document IDs as keys and document text as val...
1e31055606a692f4e743a61f8a394134b9e72126
3,597,523
def _convert_json_keywords(json_dict, conversion_dict): """ Makes a shallow copy of a dictionary with JSON-formatted, producing a dictionary with Python-formatted keys :param json_dict: the JSON dictionary :param conversion_dict: a dictionary that maps JSON keywords to their Python equivalents. Any ...
bef2749d49411489b61a6692eea15c06004ab264
3,597,524
import json def get_block_ledger(db, block_index): """Return the block's ledger.""" cursor = db.cursor() debits = list(cursor.execute('''SELECT * FROM debits WHERE block_index = ?''', (block_index,))) credits = list(cursor.execute('''SELECT * FROM credits WHERE block_index = ?''', (block_index,))) ...
d35fb07ed1c2e3a250172c11baf9072911e465fe
3,597,525
def _transform_cetera_result(result, result_position, num_rows, num_columns): """ Utility function for transforming Cetera result dictionary into something more suitable for the crowdsourcing task. Presently, we're grabbing name, link (ie. URL), and the first sentence of description. Args: ...
06fb6232a40fe9aefb5f36c510ae43ad673271f2
3,597,526
def _flat_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"): """Make a sequential palette that blends from gray to ``color``. Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name n_colors : int, optional number of co...
8edb9f3cdd1b67d300b1d3ccbb478bbe316dc789
3,597,527
from typing import Optional def get_route(resource_group_name: Optional[str] = None, route_name: Optional[str] = None, route_table_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRouteResult: """ Route resource. :param str...
47fe6cc3db32ac01cead5e293e60facaa433be4a
3,597,528
def DSER(results): """DA Segmentation Rate: number of segments of the reference incorrectly segmented over number of reference segments. """ assert len(results) == 2 CorrectSegs = results[0] TotalSegs = results[1] return ((TotalSegs-CorrectSegs)/TotalSegs) * 100
5d74c7bd3329448609fe36fa4d7778155c54d7c1
3,597,529
def fetch_activity_between_dates(activity_type: str, start_date: str, end_date: str) -> dict: """ Fetch and return Activity objects within the specified date range for the given activity type. These dates refer to the posting date of the account (not necessarily when the record was added to the DB). ...
1dbf9cdf863b8143c626d804c292e548a3a5630c
3,597,530
def sign(x): """ np.sign(0) = 0 but here to avoid value 0, we redefine it as def sign(0) = 1 """ return 1.0 if x >= 0 else -1.0
9fcaceee5506f16500d36382dd4582a766c3bba1
3,597,531
def filter_current_symbol(view, point, symbol, locations): """ Filter the point specified from the list of symbol locations. This results in a nicer user experience so the current symbol doesn't pop up when hovering over a class definition. We don't just skip all class and function definitions for t...
bf46bbbd57381cbd06d1aa80ec0688abf7280dd0
3,597,532
import json def trigger_simulation(demoGuid): """ Trigger a simulation in the given demo Creates a Snow Storm in the DC area """ try: payload = dict() payload['demoGuid'] = demoGuid event = dict() event = json.loads(open('./sample_event.json').read()) paylo...
95db3f38671f5e2423220cd10d476d18dee2bdc3
3,597,533
def get_file_info(var_dict, lu_df): """ determine which raw files are needed to pull specified variales :param var_dict: variable info dict returned from get_var_info :param lu_df: column lookup dataframe ready from output of prep_acs.py :returns: list of necessary files, dict of vars per file """ all_vars = l...
66af4599b4ac7e5e070a34ec2b4956ec75b4d0c8
3,597,535
def equal_twists(t1, t2): """ Determines if two Twist actions are equal Args: t1, t2: the Twist actions in question """ return all([np.isclose(t1.linear.x, t2.linear.x), np.isclose(t1.linear.y, t2.linear.y), np.isclose(t1.linear.z, t2.linear.z), n...
95ffa6dec56d14e77fbc95bfd0f29186e1b3cfd8
3,597,537
def dPdT(eff, freqs): """ Change in power on the detector with change in CMB temperature [W/K] Args: eff (float): detector efficiency freqs (float): observation frequencies [Hz] """ temp = np.array([physics.Tcmb for f in freqs]) return np.trapz(physics.ani_pow_spec( np.array(fre...
d65f9870ee510674a65074223371223c1c7dc63e
3,597,538
def remove_named_entities(doc, ent_list): """ function to remove named entities @param doc - input text @param ent_list - A list of labels @return String A string that has the named entities removed """ if not doc.strip(): raise Exception("doc is empty") if not iter(ent_list)...
7ecd4321d21c20d7bb9452e687083dee60fe8cc5
3,597,539
def build_sliding_net( window_size, num_filters_list, activation, apply_negativity_transform=True): """Builds neural network sliding over the input. The receptive field of this network is window_size. Args: window_size: Integer, the window size of the input, window_size >= 1. num_filters_list: List ...
7cee75213c940dc3b13ded65e53df1749130731e
3,597,540
def conv_layer(input_tensor, kernel_nr, kernel_size, stride, train, summary=False, bnorm=True, relu=True, data_format="NCHW", bn_decay=0.95): """Builds a full conv layer, with variables and relu Args: input_tensor: input tensor kernel_nr: This layer's number of filters kern...
cbdca99cd93859cc122a20006f59ca5ae4a507d0
3,597,541
def count_params(trainable_weights): """ Count the number of trainable parameters in a model George: Could have used tf.size(tensor) = num of elements in a tensor """ count = 0 for weight in trainable_weights: try: count += tf.shape(weight).numpy()[0] * tf.shape(weight)...
3929cd708890693892843fd7a056e96015a2f378
3,597,542
from typing import Tuple def generate_rsa_keypair() -> Tuple[str, str]: """ Generate an RSA keypair with a key size of 2048 bits and an exponent of 65537. Serialize the public key in the the X.509 SubjectPublicKeyInfo/OpenSSL PEM public key format (RFC 5280). Serialize the private key in the PKCS#...
0927508ced65a7e28a3587956ceedab011b05046
3,597,545
def partialDOIMatch(d1, d2): """ Assumes d1 is a "full DOI", like '10.1145/1166253.1166292', and d2 is a partial DOI, like '1166292' or '1166253.1166292'. Returns true if they match and false otherwise. Note that in the previous case, a partial like '292' would be a negative match. The partia...
8a2c21ec4d2c847609bc9f25f1c3705e3801e269
3,597,546
def compute_clustering(local_X, local_centroids): """ Compute local clustering by associating each data instance with the nearest centroid Input: local_X, centroids as above Output: cluster_labels- a list of N many integers, the labels for each i...
293e3bc098cacea924a3f0270775509424b2c0d6
3,597,547