content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def request_pet_name(): """Requests users pet name as input. Args: NONE Returns: User's name. Raises: ValueError: If input is not a character. """ while True: try: if (pet_name := input("Enter your pet's name: \n")).isalpha(): break ...
efef2cfb0792b89f158f5a0bb42d10cf9bd1655d
28,500
def butter_bandpass_filter(voltage, lowcut, highcut, fs, order=5): """Filter data with a bandpass, butterworth filter Args: voltage: array of voltage data from an ECG signal lowcut: low frequency cutoff highcut: high frequency cutoff fs: sampling frequency ...
31892cc5c98289f2e8af3a610b9f4ad1f1cbb58b
28,501
def _get_variable_names(expression): """Return the list of variable names in the Numexpr `expression`.""" names = [] stack = [expression] while stack: node = stack.pop() if node.astType == 'variable': names.append(node.value) elif hasattr(node, 'children'): ...
db75b0066b89bc7a6a022a56b28981910836524c
28,502
from pathlib import Path import typing import pathlib import os def is_readable(path: Path, access_by: typing.Union[ReadBy, str, None] = None) -> bool: """ :return: True if the object at the path `path` is readable """ path = pathlib.Path(path).resolve() if access_by is None or (i...
4c6ad5f9d9de756277e2762cdee785ddb0400042
28,503
def add(data_path, _): """add templates based on arguments and configurations.""" ask_option = AskOption(data_path) library_chosen = LibraryChosen() confirmation = Confirmation() add_library = AddLibrary() type_library_name = TypeLibraryName() possible_states = [ ask_option, librar...
09472c91394e41d345d5ac648c7b90a0e80cfcf3
28,504
from scipy.special import gamma def GGD(x,d=2,p=1): """Two parameter generalized gamma distribution (GGD) Parameters ---------- x : array_like (positive) d : float (positive) p : float (positive) Returns ------- pdf : array_like Notes ----- .. math:: G(x;d,p...
c18914f118870ff535d039f136e08a21e386ba43
28,505
def update_imported_docs(version_pk): """ Check out or update the given project's repository. """ version_data = api.version(version_pk).get() version = make_api_version(version_data) project = version.project # Make Dirs if not os.path.exists(project.doc_path): os.makedirs(proj...
c9bcbf369cbe329c6e82c3634b537a2d31df995a
28,506
def t(string): """ add \t """ return (string.count(".")) * "\t" + string
a394ac3983369836666d0610c345c6ef3c095994
28,507
def get_boundary_levels(eris): """Get boundary levels for eris.""" return [func(eris.keys()) for func in (min, max)]
20d98447e600fecc3b9495e9fb5e5d09ff3b3c1e
28,508
import os import glob import json def summary_to_json(d): """ convert to one json path: dataset1195/attic/json dataset1195/json *map.json *fastqc.json *dhs.json, *frip.json *pbc.json *meta.json *macs2*.json """ f = open(os.path.basename(d) + "_compiled_database.x...
a0cc165f8a6004d6e1f2f12574b65d0d9f218c9e
28,509
import json def team_changepass(): """The ``/team/changepass`` endpoint requires authentication and expects the ``team_id`` and ``password`` as arguments. The team's password will be set to ``password`` Note that this endpoint requires a POST request. It can be reached at ``/team/changepass?secr...
47f9921e9e457828a44e27f2b055ab47df52142e
28,510
def load_options(parser=None, argv=[], positional_args=True): """ parses sys.argv, possibly exiting if there are mistakes If you set parser to a ConfigParser object, then you have control over the usage string and you can prepopulate it with options you intend to use. But don't set a ``--config`` / ``...
d0114ba8473b7a0b9283d65ec9fe97a19f54019f
28,511
def read_spans(fname, separator = ';'): """ Read in a span file, of the form Polynomial;NumberOfComplexPlaces;Root;SpanDimension;VolumeSpan;ManifoldSpan;FitRatio Returns a dictionary object (certainly NOT a Dataset) such that they keys are polynomials, and the values are dictionaries. These dic...
3bec0157f5905dd1c3ffa80cc0d1999f50ecc48c
28,512
import argparse def compress_image(args: argparse.Namespace) -> None: """ Compresses an image by applying SVD decomposition """ def rescale(x: Matrix) -> Matrix: return (x - x.min()) / (x.max() - x.min()) img = np.array(Image.open(args.file)) / 255. n_components = args.k if args.k is not Non...
4c6bf91a10b83f90f08888a6778c38f5f5822b7c
28,513
from typing import Dict def merge_hooks(hooks1: Dict[str, list], hooks2: Dict[str, list]) -> Dict[str, list]: """ Overview: merge two hooks, which has the same keys, each value is sorted by hook priority with stable method Arguments: - hooks1 (:obj:`dict`): hooks1 to be merged - ho...
add5ae72917ca9aff109e8ac86a4d6902c14b298
28,514
import os def frame_extraction(src , annotationPath, short_side): """Extract frames given video_path. Args: video_path (str): The video_path. """ videoPaths = open(annotationPath, 'r') video_paths = [] videoLabels = [] frameHW = None for line in videoPaths.readlines(): ...
ad07535463fbc0336fe7ac6b4cb5b2813da97832
28,515
def get_max_assocs_in_sample_csr(assoc_mat): """ Returns the maximum number of co-associations a sample has and the index of that sample. """ first_col = assoc_mat.indptr n_cols = first_col[1:] - first_col[:-1] max_row_size = n_cols.max() max_row_idx = n_cols.argmax() return max_ro...
a341153afa0398cb2a43b97614cd39129e6b2ac5
28,516
def command_mood(self, args): """ /mood [<mood> [text]] """ if not args: return self.xmpp.plugin['xep_0107'].stop() mood = args[0] if mood not in pep.MOODS: return self.information('%s is not a correct value for a mood.' % mood, ...
43d383711f56e70440dd61ff5485f649ad96626b
28,517
def putativePrimer(seq,lastShared): """ Generate a mock primer based on desired TM or length and end position. This is used to estimate whether an exact match restriction site found in the shared region of two sequences is likely to be captured by a primer (rendering it necessary to modify the site or throw o...
0efa964ba834735bb71f3c8e2d565762ec7cfb8d
28,518
import argparse def default_arg_parser(formatter_class=None): """ This function creates an ArgParser to parse command line arguments. :param formatter_class: Formatting the arg_parser output into a specific form. For example: In the manpage format. """ formatter_class ...
6b70c16622a0eefa7709c12beb357d1a94542ad8
28,519
import random def get_config(runner, raw_uri: str, root_uri: str, target: str = BUILDINGS, nochip: bool = True, test: bool = False) -> SemanticSegmentationConfig: """Generate the pipeline config for this task. This function will be called ...
d30651205d500850a32f0be6364653d4d7f638fa
28,520
def readfmt(s, fmt=DEFAULT_INPUTFMT): """Reads a given string into an array of floats using the given format""" ret = map(float, s.strip().split()) return ret
30024e27450ab6f350d7829894865f68e13d95f2
28,521
def is_image_sharable(context, image, **kwargs): """Return True if the image can be shared to others in this context.""" # Is admin == image sharable if context.is_admin: return True # Only allow sharing if we have an owner if context.owner is None: return False # If we own the...
778ca70c4b12c0f20586ce25a35551e1356d20c8
28,522
import sys from io import StringIO def run_fct_get_stdout(fct: callable, *args) -> str: """Runs a function and collects stdout :param fct: function to be run :param args: arguments for the function :return: collected stdout """ # redirect stdout stdout_old = sys.stdout stdout_read = S...
58f9832c2f9d82e7d884314060c23003521052f3
28,523
def ksz_radial_function(z,ombh2, Yp, gasfrac = 0.9,xe=1, tau=0, params=None): """ K(z) = - T_CMB sigma_T n_e0 x_e(z) exp(-tau(z)) (1+z)^2 Eq 4 of 1810.13423 """ if params is None: params = default_params T_CMB_muk = params['T_CMB'] # muK thompson_SI = constants['thompson_SI'] meterToMega...
64551363c6b3c99028ebfd3f7cee69c0c273a2e2
28,524
def find_commits(repo, ref='HEAD', grep=None): """ Find git commits. :returns: List of matching commits' SHA1. :param ref: Git reference passed to ``git log`` :type ref: str :param grep: Passed to ``git log --grep`` :type grep: str or None """ opts = [] if grep: opts +...
8adb5e0dfebfc5ef86f0a17b2b4a7596ab91a382
28,525
def stft(y, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, dtype=np.complex64, pad_mode='reflect'): """Short-time Fourier transform (STFT) Returns a complex-valued matrix D such that `np.abs(D[f, t])` is the magnitude of frequency bin `f` at frame `t` ...
5c32d84d424da643d5e73c4a7d068267c7c70afc
28,526
import sys def user(cmd, directory=None, auto_assert=True, return_io=False, bash_only=False, silent=True): """Used in system tests to emulate a user action""" if type(cmd) in [list, tuple]: cmd = ' '.join(cmd) if not bash_only: # Handle special cases for case in _special_u...
7d89de3ee02e2006aad03575d70932de29fd4d4f
28,527
def findMatches(arg_by_ref, checkForName=False): """Finds POIs with the same geometry in 2 datasets. For each POI in the first dataset, check whether there is a corresponding POI in the 2nd one. If it exists, move the POI from the second dataset to a resulting dataset B. In any case, the POIs from the first dataset...
68f32bc29b970bb86663060c46490698a0e1b3b9
28,528
def _decicelsius_to_kelvins(temperatures_decicelsius): """Converts from temperatures from decidegrees Celsius to Kelvins. :param temperatures_decicelsius: numpy array of temperatures in decidegrees Celsius. :return: temperatures_kelvins: numpy array of temperatures in Kelvins, with same sha...
880d42637970c680cd241b5418890468443c6a5b
28,529
def emails_to_warn(): """ who should get warning about errors messages in the chestfreezer? """ emails_for_escalation = _get_array_option_with_default('emails_to_warn', DEFAULT_EMAILS_TO_WARN) return emails_for_escalation
f7135f2b55e813391ee86fae65e8f6cc10ccd31e
28,530
import matplotlib.collections as collections from matplotlib.colors import LogNorm from mpl_toolkits.axes_grid1 import make_axes_locatable import time def plot_bondcurrents(f, idx_elec, only='+', E=0.0, k='avg', zaxis=2, avg=True, scale='raw', xyz_origin=None, vmin=None, vmax=None, lw=5, log=False, adosmap=False...
4ba1265966be42c6838af01df740e0e545e2f215
28,531
import types from typing import Sequence from typing import Tuple def get_public_symbols( root_module: types.ModuleType) -> Sequence[Tuple[str, types.FunctionType]]: """Returns `(symbol_name, symbol)` for all symbols of `root_module`.""" fns = [] for name in getattr(root_module, '__all__'): o = getattr(...
96be2bf9d2548f1c7b5b8b12b926996105b084ca
28,532
def NewStandardEnv(packager, provider): """NewStandardEnv(object packager, object provider) object NewStandardEnv returns a new *Env with the given params plus standard declarations. """ return Env(handle=_checker.checker_NewStandardEnv(packager.handle, provider.handle))
ff8842553a2dc1676c0b4abe4b8f1f5bee41b753
28,533
def get_ecs_secret_access_key(config_fpath, bucket_name): """Return the ECS secret access key. :param config_fpath: path to the dtool config file :param bucket_name: name of the bucket in a ECS namespace :returns: the ECS secret access key or an empty string """ key = ECS_SECRET_ACCESS_KEY_KEY_...
3583d5d45a9d8f70f839c33ab7007b85977483e4
28,534
def solve_naked_quads(sudoku, verbose): """Exclude the candidates of seen quad-value cell quads from unsolved cells in their unit.""" return solve_naked_n_tuples(sudoku, 4, verbose)
0a8a67928e7c3cb65fa5868cc30b60c08823ce6a
28,535
def prototypical_spectra_plot( dataset, results_df, plot_type="imshow", fig=None, fig_kws={}, plot_kws={}, cbar_kws={}, **kwargs ): """Plot the prototypical spectra from the calibration samples. Args: dataset (pyeem.datasets.Dataset): [description] results_df (pa...
96bd2d6b283b01257b35c4ec436ecc9e3457db7b
28,536
import os def parse(name, **kwargs): """ Parse a C/C++ file """ idx = clang.cindex.Index.create() assert os.path.exists(name) tu = idx.parse(name, **kwargs) return _ensure_parse_valid(tu)
2c655e49fb4a086341fb9f37fb3e0825b69e33b0
28,537
def generate_gate_piover8( c_sys: CompositeSystem, is_physicality_required: bool = True ) -> "Gate": """Return the Gate class for the pi/8 (T) gate on the composite system. Parameters ---------- c_sys: CompositeSystem is_physicality_required: bool = True whether the generated object is...
5c3cd7721a3bf7de2eb96521f2b9c04e82845dee
28,538
def get_ftext_trials_fast(review_id): """ retrieve all ftext trials related to a review @param review_id: pmid of review @return: all registered trials and their linked publications """ conn = dblib.create_con(VERBOSE=True) cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) cur...
e4fd91e93a5b32b083ddf9d0dccd282dee339601
28,539
from typing import List from typing import Tuple def find_edges(names: List[str]) -> List[Tuple[str, str]]: """ Given a set of short lineages, return a list of pairs of parent-child relationships among lineages. """ longnames = [decompress(name) for name in names] edges = [] for x in longn...
9fd254de99a1be4647c476cfcd997b580cb44605
28,540
import argparse import os def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Apples and bananas', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text', metavar='text', ...
8d4c1a4baba3d6998234897e9283193df2e52d88
28,541
def get_plot_spec_binstat_abs(energy, bins = 50, range = (0, 5)): """ Create `PlotSpec` for plot of some stat of abs energy resolution vs TrueE. """ # pylint: disable=redefined-builtin return PlotSpec( title = None, label_x = 'True %s Energy [GeV]' % (energy), label_y = '(R...
4b6b1d5e32234ac3d5c3b9acece4b4fcae795fee
28,542
def generate_token(data): """Generate a token for given data object""" serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) return serializer.dumps(data, salt=current_app.config['SECURITY_PASSWORD_SALT'])
0df4e85179da9b4d5bf56a868b652f490df4887a
28,543
import time def monitor_gcp(vm_name: str, job_arguments: dict): """Monitor status of job based on vm_name. Requires stable connection.""" # Check VM status from command line while True: try: check_cmd = ( [ "gcloud", "alpha", ...
ba78353b84267a48e0dbd9c4ae7b8da280ddf471
28,544
import sys def CleanError(ErrorMessage,subproc=False): """Clean Errors from Log File when using import statement""" try: error = ErrorMessage[-2]#.split(':') except: sys.stdout.write("\n%s%s%s%s%s" % (bcolors.red,bcolors.underline,bcolors.bold,"Something Went Wrong - Seems You might have Imported De...
09b207bc72cf77be62d33e1c98ed72d4977abf26
28,545
def five_top_workers(month, year): """ Top 5 presence users with information about them. """ dict_months = [] monthly_grouped = group_by_month(get_data(), year) for user in monthly_grouped: try: dict_months.append((user.items()[0][0], user.items()[0][1][month])) excep...
75a63d49e11f528b90a90509b87ab22d58a87c72
28,546
import collections import re def get_assignment_map_from_checkpoint(tvars, init_checkpoint, prefix=""): """Compute the union of the current variables and checkpoint variables.""" name_to_variable = collections.OrderedDict() for var in tvars: name = var.name m = re.match("^(.*):\\d+$", name) if m is not None:...
5469356a8b70da9268f42c08588bed0c765446c8
28,547
def u_rce_hh80(lats, thermal_ro, rot_rate=ROT_RATE_EARTH, radius=RAD_EARTH): """Zonal wind in gradient balance with equilibrium temperatures.""" return rot_rate*radius*cosdeg(lats)*((1 + 2*thermal_ro)**0.5 - 1)
2fe0aba3f66a6429cbeb6674a46769d4474e31a4
28,548
def CreatePiecewiseFunction(**params): """Create and return a piecewise function. Optionally, parameters can be given to assign to the piecewise function. """ pfunc = servermanager.piecewise_functions.PiecewiseFunction() controller = servermanager.ParaViewPipelineController() controller.Initial...
6d0e55676a7abf98e967a354e321524b82f2c674
28,549
import json def cancelCardTransactionPayload(cancel_time): """ Function for constructing payload for cancelCardTransaction API call. Note: All parameters are of type String unless otherwise stated below. :param cancel_time: Date and time of the request. Format - YYYY-MM-DD HH:mm:ss :return: JSON ...
e96ee75bbc4c20a094283fa664bca6ddd6b9556c
28,550
import re def remove_elongation(word): """ :param word: the input word to remove elongation :return: delongated word """ regex_tatweel = r'(\w)\1{2,}' # loop over the number of times the regex matched the word for index_ in range(len(re.findall(regex_tatweel, word))): if re.search(regex_tatweel, wo...
a0b4be8640193568075f053009e5761894f302c1
28,551
def coevolve_alignment(method,alignment,**kwargs): """ Apply coevolution method to alignment (for intramolecular coevolution) method: f(alignment,**kwargs) -> 2D array of coevolution scores alignment: alignment object for which coevolve scores should be calculated **kwargs: para...
056813427f21b806742fd2bf613dcd2b769e709f
28,552
from textwrap import dedent, wrap def compute_known_facts(known_facts, known_facts_keys): """Compute the various forms of knowledge compilation used by the assumptions system. This function is typically applied to the results of the ``get_known_facts`` and ``get_known_facts_keys`` functions defined a...
39744ee1bd56ad0bc2fc6412a06da772f45d1a2b
28,553
def mro(*bases): """Calculate the Method Resolution Order of bases using the C3 algorithm. Suppose you intended creating a class K with the given base classes. This function returns the MRO which K would have, *excluding* K itself (since it doesn't yet exist), as if you had actually created the class. ...
bbc3fde351c92c4ae0a5c82a3e06e95de29e2e8d
28,554
import os import subprocess def getPeaksAt(peaks, bigwigs, folder='', bigwignames=[], peaknames=[], window=1000, title='', numpeaks=4000, numthreads=8, width=5, length=10,torecompute=False, name='temp/peaksat.pdf', refpoint="TSS", scale=None, sort=False, withDeeptools=True, onlyProfile=False, cluster=1,...
fa8706c47b2c045270d177aacba5a178994ddfd6
28,555
def CalculatepHfromTA(param, TA, val, TP, TSi): """ SUB CalculatepHfromTATC, version 04.01, 10-13-96, written by Ernie Lewis. Inputs: TA, TC, TP, TSi Output: pH This calculates pH from TA and TC using K1 and K2 by Newton's method. It tries to solve for the pH at which Residual = 0. The starting ...
b160decae54b25677b1158f77bbc9818abcfd0df
28,556
from operator import inv def transform_image(image, shiftx, shifty, angle, order=1): """ Apply shift and rotation to the image. The translation is applied first, then the rotation. If no rotation is requested (``angle=0``), then ``scipy.ndimage.shift()`` is called to perform a translation. Otherw...
203f06c42b68de0db834924fd302193c37629669
28,557
import json import time from typing import Callable import dill def instate(): """ Same as calculate() but the results are not saved to the database Use this to update the state of the server to further analyse the model :return: id of the simulation and result of the calculation """ # get th...
e50549ff8ae5e9e49cd972799ce0abffed213912
28,558
import pickle def pickler(obj=None, filename: str= None, mode: str = 'pickle'): """ pickles the file to filename, or unpickles and returns the file (to save the result of long running calculations) Parameters ---------- obj : the object to pickle filename : str file to pickle to mode: ...
b57e85a15099b5eed4e6c3d425bc4df7ff73d657
28,559
def csrgeam(m, n, descrA, csrValA, csrRowPtrA, csrColIndA, descrB, csrValB, csrRowPtrB, csrColIndB, handle=None, alpha=1.0, beta=0.0, nnzA=None, nnzB=None, check_inputs=True): """ add two sparse matrices: C = alpha*A + beta*B. higher level wrapper to cusparse<t>csrgemm routines. ""...
c51338336fda4a6e49529cee1f2137a826eb0b4d
28,560
def is_json_request_accept(req): """Test if http request 'accept' header configured for JSON response. :param req: HTTP request :return: True if need to return JSON response. """ return ( type(req.accept) is accept.NoHeaderType or type(req.accept) is accept.ValidHeaderType and ( ...
1a73946c5d090b905ceb09d2841efc316659a90d
28,561
def make_hierarchy(parent_ps, relative_size, make_subsys, *args, **kwargs): """ """ parent_size = parent_ps.radial_size ps = ParticleSystem() for p in parent_ps: subsys = make_subsys(*args, **kwargs) subsys.dynrescale_total_mass(p.mass) subsys_size = relative_size * parent_...
3381290bca4791f1ad342b9478855bdaf1646b22
28,562
import os def device_exists(device): """Check if ethernet device exists.""" return os.path.exists('/sys/class/net/%s' % device)
94c42317eb42007b9c96896a58e1b179b47e297e
28,563
def get_site_stats(array, player_names): """ Return the summarized statistics for a given array corresponding to the values sampled for a latent or response site. """ if len(array.shape) == 1: df = pd.DataFrame(array).transpose() else: df = pd.DataFrame(array, columns=player_name...
7105e5cd932675f812ec9b7c3c4299b138af49b2
28,564
def new(data=None, custom=None): """Return a fresh instance of a KangarooTwelve object. Args: data (bytes/bytearray/memoryview): Optional. The very first chunk of the message to hash. It is equivalent to an early call to :meth:`update`. custom (bytes): Optional. ...
5177ce6dccdc7ec7b764f90748bfda48b1c6bf6f
28,565
def document_edit(document_id: int): """Edits document entry. Args: document_id: ID of the document to be edited """ document = Upload.get_by_id(document_id) if not document: return abort(404) form = DocumentEditForm() if request.method == 'GET': form.name.data = do...
5233466553b98566c624a887e0d14556f6edeae9
28,566
from typing import Union from typing import List def get_output_tensors(graph: Union[tf.Graph, GraphDef]) -> List[str]: """ Return the names of the graph's output tensors. Args: graph: Graph or GraphDef object Returns: List of tensor names """ return [node.tensor for node in ...
598e1e5d223875bc2e094127ab40dfc84a05f2f8
28,567
def create_build_list(select_repo, all_repos_opt): """Create a list of repos to build depending on a menu that the user picks from.""" if all_repos_opt is True: build_list = repo_info.REPO_LIST print "Building repos: " + str(build_list) print "\n" return build_list # If the ...
3976d4479c2c8ee8c8381362e00aadb161dc5701
28,568
import os import sys def homeFolder(): """ home folder for current user """ f = os.path.abspath(os.curdir) toks = f.split(os.sep) if (sys.platform == 'win32'): t = toks[0:2] else: t = toks[0:3] return os.sep.join(t)
cd6467d76972a6765619a5280fb288bd8fe0e1bf
28,569
def hinton(matrix, significant=None, max_weight=None, ax=None): """Draw Hinton diagram for visualizing a weight matrix.""" ax = ax if ax is not None else plt.gca() if not max_weight: max_weight = [2 ** np.ceil(np.log(np.abs(matrix[i]).max()) / np.log(2)) for i in range(matrix.shape[0])] ax.pat...
93e3b4ed863e7542d243ccb5c33fe5187046f3a6
28,570
def to_bin(s): """ :param s: string to represent as binary """ r = [] for c in s: if not c: continue t = "{:08b}".format(ord(c)) r.append(t) return '\n'.join(r)
b4c819ae25983a66e6562b3677decd8389f5fbe2
28,571
def get_bppair(bamfile, bp_cand_df, \ seq_len = 50, seed_len = 5, min_nt = 5, match_method = 'fuzzy_match'): """ get the bppairs from bp_cand_stats (a list of bps) parameters: seq_len - # bases within breakend seed_len - # of bases up and down stream of the breakend in assembled b s...
be37ded59aac2cd481e3891e8660b4c08c7327ee
28,572
def get_dropdown_items(df: pd.DataFrame, attribute: str) -> list: """ Returns a list of dropdown elements for a given attribute name. :param df: Pandas DataFrame object which contains the attribute :param attribute: str, can be either port, vessel_type, year, or month :return: list of unique attrib...
c66b17cc4e47e05604b7cc6fde83fd2536b25962
28,573
import time def RunFromFile(): """Take robot commands as input""" lm = ev3.LargeMotor("outC") assert lm.connected # left motor rm = ev3.LargeMotor("outA") assert rm.connected # right motor drive = ReadInDirection() t0 = time.time() a = True while a: a = drive.run() t1...
e77546cef50c27d292deb22f65a524a7d402a640
28,574
def veljavna(barva, di, dj, polje, i, j): """Če je poteza v smeri (di,dj) na polju (i,j) veljavna, vrne True, sicer vrne False""" #parametra di in dj predstavljata spremembo koordinate i in koordinate j #npr. če je di==1 in dj==1, se pomikamo po diagonali proti desnemu spodnjemu #robu plošče in pre...
128cf01f8947a30d8c0e4f39d4fd54308892a103
28,575
def _do_filter(items, scores, filter_out, return_scores, n): """Filter items out of the recommendations. Given a list of items to filter out, remove them from recommended items and scores. """ # Zip items/scores up best = zip(items, scores) return _recommend_items_and_maybe_scores( ...
644cdbe1072dfa397e58f9d51a21fc515d569afe
28,576
def userlogout(request): """ Log out a client from the application. This funtion uses django's authentication system to clear the session, etc. The view will redirect the user to the index page after logging out. Parameters: request -- An HttpRequest Returns: An HttpRespon...
e12bb923268592841f0c98613ab0226f56c8cbf6
28,577
import os def shard_filename(path, prefix, lang_pair, tag, shard_num, total_shards): """Create filename for data shard.""" return os.path.join( path, "%s-%s-%s-%.5d-of-%.5d" % (prefix, lang_pair, tag, shard_num, total_shards))
4e380d2f1314c2f222bcff75f8be9f74b09d29ba
28,578
def get_builder_plugin(): """ Get the builder plugin name default. If not provided by CLI opt, start with user pref in gitconfig, Look for hint in cirrus conf or just resort to a guess based on what python cirrus is using """ # TODO look up in git config config = load_configuration...
e533ea56949b4c626280c790d7a7cdd5f9073449
28,579
def regularize(dn, a0, method): """Regularization (amplitude limitation) of radial filters. Amplitude limitation of radial filter coefficients, methods according to (cf. Rettberg, Spors : DAGA 2014) Parameters ---------- dn : numpy.ndarray Values to be regularized a0 : float ...
fe4722a273060dc59b5489c0447e6e8a79a3046f
28,580
from typing import Optional def get_fields_by_queue(client: Client, queue: Optional[list]) -> list: """ Creating a list of all queue ids that are in the system. Args: client: Client for the api. Returns: list of queue ids. """ if queue: queues_id = queue else: ...
a6ee562e50ec749ec9132bf39ca0e39b0336bdbc
28,581
def emitter_20(): """Interval, emit from center, velocity fixed speed around 360 degrees""" e = arcade.Emitter( center_xy=CENTER_POS, emit_controller=arcade.EmitterIntervalWithTime(DEFAULT_EMIT_INTERVAL, DEFAULT_EMIT_DURATION), particle_factory=lambda emitter: arcade.LifetimeParticle( ...
6a7d6689299cab15fbe6ab95e6bb62164ae09657
28,582
def add_mask_rncc_losses(model, blob_mask): """Add Mask R-CNN specific losses""" loss_mask = model.net.SigmoidCrossEntropyLoss( [blob_mask, 'masks_init32'], 'loss_mask', scale=model.GetLossScale() * cfg.MRCNN.WEIGHT_LOSS_MASK ) loss_gradients = blob_utils.get_loss_gradients(model...
e8ae0e80e2ca3ce6f7782173872f4d3e01c916c1
28,583
def fixed_discount(order: Order): """ 5k fixed amount discount """ return Decimal("5000")
867a98049e19aea03d421c37141dbc7acd651fc9
28,584
def index(): """ The index page. Just welcomes the user and asks them to start a quiz. """ return render_template('index.html')
13e70c6fd82c11f3cd6aed94b043fd1110e65c3c
28,585
from typing import BinaryIO def parse_element(stream: BinaryIO): """Parse the content of the UPF file to determine the element. :param stream: a filelike object with the binary content of the file. :return: the symbol of the element following the IUPAC naming standard. """ lines = stream.read().d...
2911d7ee97df77fd02bbd688a5044c8ba6f5434e
28,586
from typing import Optional from typing import List from typing import Any from typing import Type def mention_subclass( class_name: str, cardinality: Optional[int] = None, values: Optional[List[Any]] = None, table_name: Optional[str] = None, ) -> Type[Mention]: """Create new mention. Creates...
1639f19609b3b815a25e22729b3b0379caf13ac2
28,587
def undupe_column_names(df, template="{} ({})"): """ rename df column names so there are no duplicates (in place) e.g. if there are two columns named "dog", the second column will be reformatted to "dog (2)" Parameters ---------- df : pandas.DataFrame dataframe whose column names shoul...
51d13bad25571bc60edd78026bb145ff99281e2d
28,588
import os def p(*args): """ Convenience function to join the temporary directory path with the provided arguments. """ return os.path.join(temp_dir, *args)
29a00fab7cb9f76bb7adc3adf52aa50f49c9ccc3
28,589
def get_example_data(dataset_name): """ This is a smart package loader that locates text files inside our package :param dataset_name: :return: """ provider = get_provider('ebu_tt_live') manager = ResourceManager() source = provider.get_resource_string(manager, 'examples/'+dataset_name)...
5f5f3fd3485f63a4be2b85c2fed45a76e2d53f7c
28,590
def js(data): """ JSをミニファイ """ # 今のところは何もしない return data
2ee82b81dcb3cfb9d133ed218ba1c67b5d16f691
28,591
def _has_endpoint_name_flag(flags): """ Detect if the given flags contain any that use ``{endpoint_name}``. """ return '{endpoint_name}' in ''.join(flags)
e8827da778c97d3be05ec82ef3367686616d3a88
28,592
def convert_example(example, tokenizer, max_seq_len=512, max_response_len=128, max_knowledge_len=256, mode='train'): """Convert all examples into necessary features.""" goal = example['goal'] knowledge = exam...
5ebce39468cda942f2d4e73cd18f8fa4dd837f0a
28,593
def mag2Jy(info_dict, Mag): """Converts a magnitude into flux density in Jy Parameters ----------- info_dict: dictionary Mag: array or float AB or vega magnitude Returns ------- fluxJy: array or float flux density in Jy """ fluxJy=info_dict['Fl...
db8a56e1ca0529cd49abd68dea65ce6aeff7fd22
28,594
def load_array(data_arrays, batch_size, is_train=True): """Construct a PyTorch data iterator. Defined in :numref:`sec_utils`""" dataset = ArrayData(data_arrays) data_column_size = len(data_arrays) dataset = ds.GeneratorDataset(source=dataset, column_names=[str(i) for i in range(data_column_size)], s...
804da2b88eceaeb84e2d5d6a3961aa12df958da3
28,595
def do_get_batched_targets(parser, token): """ Retrieves the list of broadcasters for an action and stores them in a context variable which has ``broadcasters`` property. Example usage:: {% get_batched_targets action_id_list parent_action_id as batched_targets %} """ bits = token.conte...
b4847c5acc480b88c0a9cd7b44467f307eed0d65
28,596
def task_success_slack_alert(context): """ Callback task that can be used in DAG to alert of successful task completion Args: context (dict): Context variable passed in from Airflow Returns: None: Calls the SlackWebhookOperator execute method internally """ slack_webhook_token...
596694b089f758a683eac677d7ca237a253a2bd2
28,597
import base64 def return_img_stream(img_local_path): """ 工具函数: 获取本地图片流 :param img_local_path:文件单张图片的本地绝对路径 :return: 图片流 """ img_stream = '' with open(img_local_path, 'rb') as img_f: img_stream = img_f.read() img_stream = base64.b64encode(img_stream) return img_strea...
7ddee56650fcfabf951ca9b5844a08c7ae5fb2b7
28,598
from typing import Optional from typing import Dict from typing import Union from typing import Any def filter_log_on_max_no_activities(log: EventLog, max_no_activities : int = 25, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> EventLog: """ Filter a log on a maximum number of activities ...
b09d376a758a10f784fd2b9f7036cc6e0d58be05
28,599