content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def build_answers_xml(selector, args): """ builds an answers xml string for a selector class using default answers for the selector's questions. If any other attributes were included in the call, they are appended to as part of the work-info. """ # build an answers xml tree answers = ET.Ele...
9290190fef3396990a3a4199d81c50f413ee3bc1
3,632,400
import time def give_me_the_answer(question, clever=False): """This gives you the answer. Parameters ---------- question: str the question you are asking. clever: bool, optional whether or not the answer should be clever or not Returns ------- The answer """ ...
a2b8f7fd9cd131caa6d2d99c694d76cef34ead82
3,632,401
def round_down(x: float, decimal_places: int) -> float: """ Round a float down to decimal_places. Parameters ---------- x : float decimal_places : int Returns ------- rounded_float : float Examples -------- >>> round_down(1.23456, 3) 1.234 >>> round_down(1.2345...
f1accd23ffef4fbceb0aa75098862dfb75e03c61
3,632,402
import importlib def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: parts = val.split(".") module_path, class_name = ".".join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr...
45bd96b219c808a5cf928e1b7364aa3c3178160a
3,632,403
def datatype_to_tracktype(datatype): """ Infer a default track type from a data type. There can be other track types that can display a given data type. Parameters ---------- datatype: str A datatype identifier (e.g. 'matrix') Returns ------- str, str: A track type ...
fb0679ade37478ee0b9a451ce667bfd23f86e1ae
3,632,404
def rossler(x, y, z, a, b, c): """ Rössler System of Ordinary Differential Equations """ dx = - y - z dy = x + a*y dz = b + z*(x - c) return dx, dy, dz
bcf27c7ff8223681d6dc7d0c49497e975b826d80
3,632,405
import os def comparePlistVersion(item): """Gets the version string from the plist at path and compares versions. Returns 0 if the plist isn't installed -1 if it's older 1 if the version is the same 2 if the version is newer Raises munkicommon.Error if there's an e...
2b02a43fd5460ee6fd826093abca66f91c10ce0d
3,632,406
import re def get_extension(filename): """ Extract file extension from filename using regex. Args: filename (str): name of file Returns: str: the file extension """ match = re.search(r"\.(?P<ext>[^.]+)$", filename) if match: return match.group("ext") raise Val...
8f5195b339a153d5fa144182505dba986992d4df
3,632,407
import asyncio def run_async(func): """ Allows you to run a click command asynchronously. """ func = asyncio.coroutine(func) def inner_handler(*args, **kwargs): run(func(*args, **kwargs)) return update_wrapper(inner_handler, func)
29b0d731d101159f7ec7311dc6beb6ab56523022
3,632,408
def Conv2D(input_tensor, input_shape, filter_size, num_filters, strides=1, name=None): """ Handy helper function for convnets. Performs 2D convolution with a default stride of 1. The kernel has shape filter_size x filter_size with num_filters output filters. """ shape = [filter_size, filter_size, input_shape, nu...
91505ed82eaf1585023edba55848a33e4145bbc3
3,632,409
def scale_val(val, factor, direction): """Scale val by factor either 'up' or 'down'.""" if direction == 'up': return val+(val*factor) if direction == 'down': return val-(val*factor) raise ValueError('direction must be "up" or "down"')
16c2efe16fc787fe4461fb0ae640e2cf22d556e0
3,632,410
def ttee(iterable, n=2): """ >>> ttee("ABC") (('A', 'B', 'C'), ('A', 'B', 'C')) """ return tuple(map(tuple, tee(iterable, n)))
7b5b6ff83492f4df5cbe845367d73bbadd0c6b10
3,632,411
def addattrs(field, css): """ 在模板的form的field中,特别是input中添加各种attr """ attrs = {} definition = css.split(',') for d in definition: if '=' not in d: attrs['class'] = d else: t, v = d.split('=') attrs[t] = v return field.as_widget(attrs=attrs)
cdbb2b4b44b6e7facbe2af44d503c3118eb31ef7
3,632,412
def regular_periodic(freqs, amplitudes, phase, size=501): """Generate periodic test data sampled at regular intervals: superposition of multiple sine waves, each with multiple harmonics. """ times = np.linspace(0, 2, size) values = np.zeros(size) for (i,j), amplitude in np.ndenumerate(amplitudes...
bfe23122e8edd3a279caed27a758edd353f15bc7
3,632,413
from bread.contrib.reports.fields.queryfield import parsequeryexpression def generate_excel_view(queryset, fields, filterstr=None): """ Generates an excel file from the given queryset with the specified fields. fields: list [<fieldname1>, <fieldname2>, ...] or dict with {<fieldname>: formatting_function(o...
ca03a09ee3a6a2e17df542ab4c124c4078677b4a
3,632,414
import os def makeDir(dirName): """Makes a new directory with the specified name. If the directory already exists then raise a new exception.""" if (os.access(dirName, os.F_OK)): raise Exception("Directory already exists: " + dirName) return commands.getstatusoutput("mkdir " + dirName)
73f5d0f9fe8671b91abb528584e0714073925110
3,632,415
def get_tag_by_name(repo: Repository, tag_name: str) -> Tag: """Fetches a tag by name from the given repository""" ref = get_ref_for_tag(repo, tag_name) try: return repo.tag(ref.object.sha) except github3.exceptions.NotFoundError: raise DependencyLookupError( f"Could not find...
d8191f819e7a2f1cdcaeabb52cda452fd3e555bf
3,632,416
def get_geo_selected(results, datas, extras, filters=False): """Get specific Geography based on existing ids.""" wards = [] all_list = get_all_geo_list(filters) datas.remove('') if '' in datas else datas extras.remove('') if '' in extras else extras results['wards'] = datas area_ids = list(m...
755b8461f0decc320c54174541bef0672585bcc8
3,632,417
def notify(text, boxwidth=60): """Create a 'notification' styled textbox""" return box(text, decor="*", boxwidth=boxwidth)
1fe8d98b890bf7c2cd6aaee27b2c11dca6b8046c
3,632,418
def returns_player(method): """ Decorator: Always returns a single result or None. """ def func(self, *args, **kwargs): "decorator" rfunc = returns_player_list(method) match = rfunc(self, *args, **kwargs) if match: return match[0] else: ret...
22549888600556804ae3446a6c7442e94841813f
3,632,419
def tracks(date): """ Query the charts/beatport/tracks endpoint for the given date. Data available on Fridays. https://api.chartmetric.com/api/charts/beatport **Parameters** - `date`: string date in ISO format %Y-%m-%d **Returns** A list of dictionary of tracks on Beatport ch...
e117fe57e78eb4780f2ba8850b1fe80d7ab43c0c
3,632,420
def cos_sim(A_mat, B_vec): """ item-vevtorの行列(またはベクトル)が与えられた際にitem-vevtor間のコサイン類似度行列を求める """ d = np.dot(A_mat, B_vec) # 各ベクトル同士の内積を要素とする行列 # 各ベクトルの大きさの平方根 A_norm = (A_mat ** 2).sum(axis=1, keepdims=True) ** .5 B_norm = (B_vec ** 2).sum(axis=0, keepdims=True) ** .5 # それぞれのベクトルの大きさの平方根で...
823778eaaeb8bb85e93544c5b6d09001cba0e236
3,632,421
def parse_dtype(space): """Get a tensor dtype from a OpenAI Gym space. Args: space: Gym space. Returns: TensorFlow data type. """ if isinstance(space, gym.spaces.Discrete): return tf.int32 if isinstance(space, gym.spaces.Box): return tf.float32 raise NotImplementedError()
903824c5c013c9081bd988ca437f123ebb322ef8
3,632,422
def tf_efficientnet_b2_ap(pretrained=True, **kwargs): """ EfficientNet-B2. Tensorflow compatible variant """ kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' out_indices = [1, 2, 4, 6] model = _gen_efficientnet( 'tf_efficientnet_b2_ap', channel_multiplier=1.1, depth_multipli...
61ebd0953be7024d262ecd509bfd6d4886431afb
3,632,423
def plot_ld_curves(ld_stats, stats_to_plot=[], rows=None, cols=None, statistics=None, fig_size=(6,6), dpi=150, r_edges=None, numfig=1, cM=False, output=None, show=False): """ Plot single set of LD curves LD curves are named as given in statistics ld_stats is th...
5bf8128cce7a4b85347787e4552444f69f68873a
3,632,424
def onehottify_2d_array(a): """ https://stackoverflow.com/questions/36960320/convert-a-2d-matrix-to-a-3d-one-hot-matrix-numpy :param a: 2-dimensional array. :return: 3-dim array where last dim corresponds to one-hot encoded vectors. """ # https://stackoverflow.com/a/46103129/ @Divakar def a...
a612b6fa7ba2bc59f48aec85ee2e63e9d3cf86ac
3,632,425
def getUserCompetencies(cnx, exceptUserIDs): """ Returns array of persons with their competences as values """ competencies = {} cnx = establishDBConnection(dbconfig) cursor = cnx.cursor() placeholder = '%s' placeholders = ', '.join(placeholder for unused in exceptUserIDs) query = ("...
4cd73c2e01fe76abad337cfd4929edcce297c92e
3,632,426
def add_induct_def(name, T, eqs): """Add the given inductive definition. The inductive definition is specified by the name and type of the constant, and a list of equations. For example, addition on natural numbers is specified by: ('plus', nat => nat => nat, [(plus(0,n) = n, plus(Suc(m), n) ...
7de7884e36cceba2a49377230a7932ff133f902f
3,632,427
def cropDetectionSegments(ffBinRead, segmentList, cropSize = 64): """ Crops small images around detections. ffBinRead: read FF bin structure segmentList: list of coordinate tuples [(x1, y1), (x2, y2),...] cropSize: image square size in pixels (e.g. 64x64 pixels)""" ncols = ffBinRead.ncols - 1...
749f13efabc60f9b443ea84cabd459d9a8a70241
3,632,428
def delete_site_request(site_id): """Request deletion of a site.""" site = InventorySite.query.filter_by(id=site_id).first() if site is None: abort(404) return render_template('inventory/manage_site.html', site=site)
3b137e3140fb5fa9cf9f79dce2cc8b283d3a4a70
3,632,429
def twoD_Gaussian(tup, amplitude, xo, yo, sigma_x, sigma_y, theta, offset): """ A 2D Gaussian to be used to fit the cross-correlation Args: tup (tuple): A two element tuple containing the (x,y) coordinates where the 2D Gaussian will be evaluated amplitude (float): The am...
35a4d6362f8751294e460dc7ae529bcb7a48022a
3,632,430
from itertools import combinations def generate_synthetic_example(n_stations=65, lat_lims=(45, 50), lon_lims=(10, 20), u_0=0, A=.1, phi_2=60, B=.01, phi_4=20, amplitude_noise=.05): """ Helper function to generate a simple synthetic example. Constant anisotropy in entire region. :param n_stations: Num...
7879af1efcbb7204f454b337f2197f0442673e1f
3,632,431
import logging def _extractStringType(newTypeName, newProperty, propDict, modelTypes, modelFileContainer): """extract the specific string type depending on the given format and return the specific type Keyword arguments: newType -- current type name newProperty -- current property propDict --...
02fac4de96466cb311c64ffb0acf5d8d7f20f79b
3,632,432
import yaml def get_palette(col, col_unique=None, as_dict=True): """Get palette for column. Parameters ---------- col : {'subject_name', 'model', 'scaling', 'cell_type', str} The column to return the palette for. If we don't have a particular palette picked out, the palette will conta...
ab134032798d1679366533968c4bc0f277f764bf
3,632,433
import ROOT def array2hist(array, hist, errors=None): """Convert a NumPy array into a ROOT histogram Parameters ---------- array : numpy array A 1, 2, or 3-d numpy array that will set the bin contents of the ROOT histogram. hist : ROOT TH1, TH2, or TH3 A ROOT histogram. ...
40522a374321b768fac800a4fce22440991de05f
3,632,434
def adjust_update_rules_for_fixed_nodes(predecessor_node_lists, truth_tables, fixed_nodes): """ Adjust "update rules" matrix and its free element vector so that the fixed nodes will end up in their fixed states on each time step automatically, with no manual interventions required. :param predecessor_n...
f41609ae25c3622100674372de5a364b095650f8
3,632,435
def obs_data(): """ Dictionary with variables as top keys and available observations directly below. For each observation data set, path and file pattern must be defined. """ meta_dict = { # ------------------------------------------------------------------------ # 2m temperature '...
f3db013fa2b99cdaee26b82075674a69a662030c
3,632,436
def create_class_prediction_error_chart(classifier, X_train, X_test, y_train, y_test): """Create class prediction error chart. Tip: Check Sklearn-Neptune integration `documentation <https://docs-beta.neptune.ai/essentials/integrations/machine-learning-frameworks/sklearn>`_ for the full ...
c0aadac243614914952d10d484ea4a9a7c89da26
3,632,437
def footer_embed(message: str, title) -> Embed: """ Constructs embed with fixed green color and fixed footer showing website, privacy url and rules url. :param message: embed description :param title: title of embed :return: Embed object """ content_footer = ( f"Links: [Website]({co...
cb4637e479d5eabb3afedb965209271553e1f238
3,632,438
from .criteria import aic_eigen, mdl_eigen import logging def _get_signal_space(S, NP, verbose=False, threshold=None, NSIG=None, criteria='aic'): """todo """ # This section selects automatically the noise and signal subspaces. # NSIG being the number of eigenvalues corresponding...
3318f23f92b78362dd91cfe5b49e061b12790ba1
3,632,439
def joins_for_results(basetables, external_info): """ Form and return the `results` table """ # Get one table per result_type, then stack them, # kind_problem # kind_pathproblem # # Concatenation with an empty table triggers type conversion to float, so don't # include empty ta...
1b2821a11a9a3df65ef9a3dfbf11262175307b9d
3,632,440
def newton_wedge_fringe_sep(alpha, wavelength): """Calculate the separation between fringes for an optical flat with angle alpha.""" d = wavelength/(2*np.sin(alpha)) return d
fc29c6bfcfb6ed19e91588263ef12190bb9ec699
3,632,441
def hs_classify(scope): """ A mapper ``Function -> (Dimension -> [HaloLabel]`` describing what type of halo exchange is expected by the various :class:`TensorFunction`s in a :class:`Scope`. """ mapper = {} for f, r in scope.reads.items(): if not f.is_TensorFunction: conti...
adcf5f795fb5eb505ad1c6e860c038ab31290932
3,632,442
def train_test_split(shp, savedir, config, client = None): """Create the train test split Args: shp: a filter pandas dataframe (or geodataframe) savedir: directly to save train/test and metadata csv files client: optional dask client Returns: None: train.shp and test.shp ar...
46c8becd416877306e9d28914f3032ff99946321
3,632,443
def parse_list_from_string(value): """ Handle array fields by converting them to a list. Example: 1,2,3 -> ['1','2','3'] """ return [x.strip() for x in value.split(",")]
51e9c654b9d18b8be61c37aab5f5029dfdea2213
3,632,444
def add_evaluation_args(parser): """Evaluation arguments.""" group = parser.add_argument_group('validation', 'validation configurations') group.add_argument('--eval-batch-size', type=int, default=None, help='Data Loader batch size for evaluation datasets.' 'De...
437a77987e9a4a461b98c9cb08b78a016efca9e9
3,632,445
import itertools def merge(d1, d2): """Merge to dicts into one. Args: d1 (dict): dataset 1 d2 (dict): dataset 2 Returns: dict: merged dict """ return dict(itertools.chain(list(d1.items()), list(d2.items())))
bb1d38f3cb45de6e98855fb04ae1d3d7e73e4a40
3,632,446
import re def is_valid(number): """ Check if number is roman :param number: string to check :type number: str :return: True or False :rtype: bool """ return re.match( r"^(M{0,3})(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$", number )
52e1937418d28701ee3d30da139f16ae64cfe480
3,632,447
def lammps_created_gsd(job): """Check if the mdtraj has converted the production to a gsd trajectory for the job.""" return job.isfile("prod.gsd")
1b05e085970de4d875044e2e6604c1874a0a0e83
3,632,448
def has_open_quotes(s): """Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Returns ------- If there is an open quote, the quote character is returned. Else, return False. """ # We check " first...
a9adbcd42518a71458c69c9aa1ff751fa3998573
3,632,449
def get_task(name, context=None, exception_if_not_exists=True): """ Returns item for specified task :param name: Name of the task :param context: Lambda context :param exception_if_not_exists: true if an exception should be raised if the item does not exist :return: Task item, raises exception i...
9eb3007c230b75543c5227a44d282ed2ca6b3d9e
3,632,450
def GetResourceReference(project, organization): """Get the resource reference of a project or organization. Args: project: A project name string. organization: An organization id string. Returns: The resource reference of the given project or organization. """ if project: return resources.R...
fd986df9ced20a6b8edbd910d7268806841d2139
3,632,451
def pauli_block_y(M, norb): """ y compoenent of a matrix, see pauli_block """ ret = zeros_like(M) tmp = (M[:norb, norb:] * 1j + M[norb:, :norb] * (-1j)) / 2 ret[:norb, norb:] = tmp * (-1j) ret[norb:, :norb] = tmp * 1j return tmp, ret
848d70de19723ee22f2adc750c7dd9ec8c47d784
3,632,452
def permission_required_raise(perm, login_url=None, raise_exception=True): """ A permission_required decorator that raises by default. """ return permission_required(perm, login_url=login_url, raise_exception=raise_exception)
7a26f7ac1e858cfcba6961856ecf428d0de03982
3,632,453
def list_objects(root_checkpointable): """Traverse the object graph and list all accessible objects. Looks for `Checkpointable` objects which are dependencies of `root_checkpointable`. Includes slot variables only if the variable they are slotting for and the optimizer are dependencies of `root_checkpointable`...
47715222f0f357cfb0f18f1a28b81fb908055197
3,632,454
def get_dips_value_around_300(l_cusp): """ 300°付近の凹みの L* 値および、それを指す Hue の Index を計算する。 """ dips_300 = np.min(l_cusp[DIPS_300_SAMPLE_ST:DIPS_300_SAMPLE_ED]) dips_300_idx = np.argmin(l_cusp[DIPS_300_SAMPLE_ST:DIPS_300_SAMPLE_ED]) dips_300_idx += DIPS_300_SAMPLE_ST return dips_300, dips_300_idx
6db8f0ee9d92c14c50bee096830a9fa0cadc6a94
3,632,455
def get_filtered_enviro_df(lat_filter, long_filter): """ This function takes the latitude and longitude filters and queries the database to obtain City of Chicago Environmental complaint and enforcement information that fits within those filters. A pandas dataframe of filtered database information ...
b09c2cced6f17c8b4814982eb68f2af1589ad97a
3,632,456
def is_valid_time_stamp_normal_response(response): """ Returns true if a time_stamp_normal response is valid. str -> bool """ try: respones_to_datetime(response, constants.DATETIME_FORMATE_NORMAL) return True except ValueError: return False
37e521ab18f8a21f311b07a96082ea65d2c3a57e
3,632,457
def status(repo="."): """Returns staged, unstaged, and untracked changes relative to the HEAD. :param repo: Path to repository or repository object :return: GitStatus tuple, staged - list of staged paths (diff index/HEAD) unstaged - list of unstaged paths (diff index/working-tree) ...
afc18280842b4fdc9bdcb330796be2a12e5edc1e
3,632,458
def find_best_capacity_value(desired_capacity, data_file='data/capacities.csv'): """Return the closest capacity to the desired one from the possible capacity combinations. Parameters ---------- desired_capacity: float The desired capacity value needed for the circuit. data_file: str Re...
19fd7cca9b45b088c2dafa97f75d37c8bae570d8
3,632,459
def _qt(add_row, secondary_dict_ptr, cols, key): """ This sub-function is called by view_utils.qt to add keys to the secondary_dict and is NOT meant to be called directly. """ if cols[key]: if cols[key] in secondary_dict_ptr: return add_row, secondary_dict_ptr[cols[key]] ...
ce1cec842822077cbfbd908ff92b1552626cd5f2
3,632,460
from datetime import datetime def conv_to_schedule(src: datetime) -> str: """Convert given datetime to schedule date string.""" return datetime.strftime(src, FMT_STD)
571fd18bff08e4e9be9929a75b23c5b023122400
3,632,461
def create(title): """Create a Tk root title - a title for the application """ assert isinstance(title, str) root = tk.Tk() root.title = title rx.concurrency.TkinterScheduler(root) return root
aaa710b6429c0abafe40e7c7ea51f886f15624c4
3,632,462
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Homekit lock.""" hkid = config_entry.data["AccessoryPairingID"] conn = hass.data[KNOWN_DEVICES][hkid] @callback def async_add_service(service): if service.short_type != ServicesTypes.LOCK_MECHANISM: r...
1ebfa72ffc700a873cff642cbd0a92b2a64cdc35
3,632,463
from typing import List from typing import Tuple import torch def bounding_boxes_to_tensor(bboxes: List[dict], image_size: Tuple[int, int], cell_size: Tuple[int, int], classes: List[str], device: torch.device) -> Tuple[torch.Tensor]: """ Converts a lis...
1530748ddc02527edea938542b1e60dcfac5a36b
3,632,464
def compartment_size_uncommon_keys(base): """ Provide a model with different amounts metabolites for each compartment. """ base.add_metabolites( [cobra.Metabolite(i, compartment='ml') for i in "ABCD"]) base.add_metabolites( [cobra.Metabolite(i, compartment='om') for i in "EFG"]) ...
d00f1da728b5f8cf9399a8e8810d90cd919c45c6
3,632,465
def steady_state_step(population: list, reproduction_pipeline: list, insert, probes = (), evaluation_op = ops.evaluate): """An operator that performs steady-state evolution when placed in an (otherwise generational) pipeline. This is a metaheuristic component that can be parameterized to define many kinds ...
e6e03e4b0d70ba4b3a10124e4170988b0774e9f1
3,632,466
def get_gym_environs(): """ List all valid OpenAI ``gym`` environment ids. """ return [e.id for e in gym.envs.registry.all()]
899013b5621e63b44bd0600bd037da389fcdb0ff
3,632,467
import time def single_classic_cv_evaluation( dx_train, dy_train, name, model, sample_weight, scoring, outer_cv, average_scores_across_outer_folds, scores_of_best_model, results, names, random_state): """Non nested cross validation of single model.""" if (isinstance(scoring, list) or i...
530fd65ed867a4f43a1fcc688970c6a6b1e6ffc7
3,632,468
from nnabla import logger def get_extension_context(ext_name, **kw): """Get the context of the specified extension. All extension's module must provide `context(**kw)` function. Args: ext_name (str) : Module path relative to `nnabla_ext`. kw (dict) : Additional keyword arguments for cont...
c5f3bf4c6f4053207009e3412c23133df28d6b61
3,632,469
def resolve_byprop(prop, value, minimum=1, timeout=FOREVER): """Resolve all streams with a specific value for a given property. If the goal is to resolve a specific stream, this method is preferred over resolving all streams and then selecting the desired one. Keyword arguments: prop -- The St...
a3c81185ad3d972e997399d41480e3f814945c52
3,632,470
import math def create_plot(model_filenames, ncols=3, projection=None, nplots_increment=0): """Create base figure for multipanel plot. Creates matplotlib figure and set of axis that corespond to the number of models that should be plotted. Parameters ---------- model_filenames: OrderedDict ...
11a5e36b641946c5994919845818dcecef98eadf
3,632,471
import time def get_sample_records(n): """get sample records for testing""" tsk, target = get_sample_task() inps, ress = [], [] for i in range(n): inps.append(MeasureInput(target, tsk, tsk.config_space.get(i))) ress.append(MeasureResult((i + 1,), 0, i, time.time())) return list(zi...
136398926d2638aa0542e76e1e6757484aaf82d1
3,632,472
def build_get_boolean_tfft_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Get boolean array value [true, false, false, true]. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azu...
0711739e4a97a7356f5f69a12e27f940e03e79ff
3,632,473
def grøn(tekst: str): """ Farv en tekst der udskrives via Click grøn. """ return farvelæg(tekst, "green")
b85629c384c8918bca38093af99a7840cce0aec2
3,632,474
from typing import Union from typing import Dict from pathlib import Path def init_config(config: Union[Dict, Path, Text, None]) -> ConfigParser: """ Initialize skill configuration: 1. Defaults from SDK 2. Additional locations 3. "skill.conf" :param config: :return: """ ...
41be149851d052efb456f276d56dad62b0294cef
3,632,475
def update(dbs, user, role_id=None, org_id=None, create_user=None): """ 更新用户信息 :param dbs: :param user: :param role_id: :param org_id: :param create_user: :return: """ try: with transaction.manager: if org_id and org_id != '' and org_id != 0: d...
a345e9edfd0e7174c7ce8e881d3b3699a9222610
3,632,476
def analogy_making_model(inputs, params, is_training, reuse, output_length=None): """Factory function to retrieve analogy-making model.""" latent_encoder = _get_network(Z_ENC_FN) latent_decoder = _get_network(Z_DEC_FN) outputs = analogy_seq_encoding_model(inputs, params, is_training, reuse) with tf.variable...
3c83c27ebefcc9d3b080441be5a45c52193a40eb
3,632,477
import torch def test_model(dataloader, model, gpu=False): """Tests model performance on a data from dataloader and prints accuracy. Args: dataloader (DataLoader) model (torchvision model) gpu (bool): Use GPU if True, otherwise CPU Returns: test_acc (float): model predict...
f5e1f63b8e0a3e2ee94d579f552807af103e2c1a
3,632,478
import io import struct def decrypt_chunk(chunk, password=None): """Decrypts the given encrypted chunk with the given password and returns the decrypted chunk. If password is None then saq.ENCRYPTION_PASSWORD is used instead. password must be a byte string 32 bytes in length.""" if password is ...
f6578fd445c44a2fd4aecc3009278ddd2a45add0
3,632,479
import time from datetime import datetime def epochFromNice(timeToConvert=None): """ Get the epoch time from the passed in string of the format: YYYY-mm-dd_HH-MM-SS.UUUUUU returns time.time() if timeToConvert is not specified """ if timeToConvert is None: retTime = time.time() else: year...
db6378dd2d47cc17377507474d9726a2f6de22b0
3,632,480
def prepare_tensor_SVD(tensor, direction, D=None, thresh=1E-32, normalize=False): """ prepares and truncates an mps tensor using svd Parameters: --------------------- tensor: np.ndarray of shape(D1,D2,d) an mps tensor direction: int if >0 returns left orthogonal decomp...
ad71c7f2b16624bc9f24e060376a9359c8585c07
3,632,481
from datetime import datetime def calc_easter(year): """ Returns Easter as a date object. Because Easter is a floating mess year - the year to calc easter for """ a = year % 19 b = year // 100 c = year % 100 d = (19 * a + b - b // 4 - ((b - (b + 8) // 25 + 1) // 3) + 15) % 30 ...
c02c2a45f55a8f80273759bbf9c06bb2234b0b8a
3,632,482
def MACDFIX(ds, count, signalperiod=-2**31): """Moving Average Convergence/Divergence Fix 12/26""" ret = call_talib_with_ds(ds, count, talib.MACDFIX, signalperiod) if ret == None: ret = (None, None, None) return ret
8b440e666d0ac1c669e26da9974136fdd18f5e6e
3,632,483
def create_dataset(form_data, params=None, use_doi=False): """ Create dataset in Metax. Arguments: form_data {object} -- Object with the dataset data that has been validated and converted to comply with the Metax schema. params {dict} -- Dictionary of key-value pairs of query parameters. ...
b288c021df3cf37467ea304c2105eceb0fc5f2be
3,632,484
def blrPredict(W, data): """ blrObjFunction predicts the label of data given the data and parameter W of Logistic Regression Input: W: the matrix of weight of size (D + 1) x 10. Each column is the weight vector of a Logistic Regression classifier. X: the data matrix of siz...
86374a43e6c7cbe69a6789f532ea3be3bf3238f5
3,632,485
def _compare_objects(obj1, obj2): """ FIXME: CALL: print(f'compare_objects (ops2,operations): {_compare_objects (ops2,operations)}') DEBUG Helper to compare 2 numpy arrays """ result = (obj1 == obj2).all() return result
98d730a8f56df3938933d22cde1dba2fe314147f
3,632,486
import torch def mds_torch(pre_dist_mat, weights=None, iters=10, tol=1e-5, verbose=2): """ Gets distance matrix. Outputs 3d. See below for wrapper. Assumes (for now) distrogram is (N x N) and symmetric Outs: * best_3d_coords: (3 x N) * historic_stress """ if weights is N...
bb1302a5cec2f79f665ef801b9b0dc5a75a79330
3,632,487
def get_pair(expr, index): """Get the field of an expression using python syntax Arguments: - `expr`: an expression - `index`: an integer equal to 0 or 1 """ if index == 0: return Fst(expr) elif index == 1: return Snd(expr) else: raise Exception("Index applie...
5b25163562fb8399d2e948dd8fc9d47aa6467b07
3,632,488
import functools def get_standardized_layers(hparams, dp=None, ps_devices=None): """Get the common attention and feed-forward layers. The returned layer functions will have the following signature: y, extra_loss = fct(x) extra_loss is set to 0.0 if the layer doesn't have extra loss. If dp is provided, ...
99972e4106928ff4c71e0f52c159a74650310c74
3,632,489
def row_contains_data(fieldnames, row): """Returns True if the value of atleast on of the fields is truthy""" for field in fieldnames: if row.get(field): return True return False
7575d1280186c582a652ab37deb4a93e667b51b2
3,632,490
def create_model(name, batch_size, learning_rate = 0.0001, wd = 0.00001, concat = False, l2_loss = False, penalty = False, coef = 0.4, verbosity = 0): """ Create a model from model.py with the given configuration Args: name : name of the model (used to create a specific folder to save/load para...
63b4755e20fc877d9231427ed2cf118efbe37bb0
3,632,491
def fs(path:str, mode:Mode='rb'): """Opens file locally or via s3 depending on path string.""" s3 = s3fs.S3FileSystem() return partial( {True: s3.open, False: open}[is_s3_path(path)], mode=mode )(path)
18ffc654e66bdd2c9315d5104fa145a195ee2ce3
3,632,492
import logging def create_logger(log_file): """ Zack's Generic Logger function to create onscreen and file logger Parameters ---------- log_file: string `log_file` is the string of the absolute filepathname for writing the log file too which is a mirror of the onscreen display. R...
791fb5dc202b4a01dbb829fc4a890a3443bdf6d3
3,632,493
import six def _check_stop_list(stop): """ Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 """ if stop == "thai": return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError("not...
8c47875f42fdfcb1f0b7c7c18b8363783f1ebcbb
3,632,494
from typing import Callable from typing import Any def protect_with_lock() -> Callable: """ This is a decorator for protecting a call of an object with a lock The objects must adhere to the interface of having: - A mapping of ids to query_lock objects Objects adhering to this interface(LockableQu...
60901e775f1a6a8d3408000f3517f1c3ddedd199
3,632,495
from datetime import datetime def _handle_dates(): """Collect and return data information.""" currentdate = datetime.date.today() year = currentdate.year month = currentdate.month print(f"[INFO] Current year / month: {year:04d} / {month:02d}") return currentdate
54735562fe0366f286eeac33f897a98a8d34374a
3,632,496
def add_to_five(number): """Add to the 5 by any number. :param number: """ gifs = FrozenGif() acceptable = (int, float) type_number = type(number) if type_number in acceptable: # get answer answer = 5 + number response = int(input("Ente...
0387af4a7d8587865c3c7e38eeab1af5a00423a2
3,632,497
def mergeticklists(list1, list2, mergeequal=1): """helper function to merge tick lists - return a merged list of ticks out of list1 and list2 - CAUTION: original lists have to be ordered (the returned list is also ordered)""" # TODO: improve along the lines of http://aspn.activestate.com/ASPN/Cook...
6e89944cdeb1d74357cf8dc5a0a434db930d1cf0
3,632,498
def test_url(url, size=17): """Test whether the given URL is accessible.""" try: with gopen(url) as stream: data = stream.read(size) if len(data) == size: return True return False except Exception as e: print(e) return False
13023fc5fd346572b3c31e4f4dd491e285e33b6b
3,632,499