content
stringlengths
22
815k
id
int64
0
4.91M
def replace_heaviside(formula): """Set Heaviside(0) = 0 Differentiating sympy Min and Max is giving Heaviside: Heaviside(x) = 0 if x < 0 and 1 if x > 0, but Heaviside(0) needs to be defined by user. We set Heaviside(0) to 0 because in general there is no sensitivity. This done by setting the ...
5,315,400
def shot_start_frame(shot_node): """ Returns the start frame of the given shot :param shot_node: str :return: int """ raise NotImplementedError()
5,315,401
def check_enrolled_factors(ctx, users): """Check for users that have no MFA factors enrolled""" users_without_mfa = [] msg = ( f"Checking enrolled MFA factors for {len(users)} users. This may take a while to avoid exceeding API " f"rate limits" ) LOGGER.info(msg) index_event(ct...
5,315,402
def entry_cmp(sqlite_file1, sqlite_file2): """ Compare two sqlite file entries in zookeeper to know the ordering """ seq_id1 = _get_journal_seqid(sqlite_file1) seq_id2 = _get_journal_seqid(sqlite_file2) return sequence_cmp(seq_id1, seq_id2)
5,315,403
def fill_cn(bcm, n_metal2, max_search=50, low_first=True, return_n=None, verbose=False): """ NOTE: Most likely broken - still need to extend to polymetallic cases Algorithm to fill the lowest (or highest) coordination sites with 'metal2' Args: bcm (atomgraph.AtomGraph | atomgraph.BCMod...
5,315,404
def curate_submissions(vars,conn,dbName,BLOCK_SIZE = 50): """ Created: 5/24/2015 by Ben Schreck Curates submissions (and indirectly assessments) Args conn: connection to MySQL database \n dbName: name of database \n BLOCK_SIZE: Number of rows to update at once \n """ ...
5,315,405
def _clear_caches_after_call(func): """ Clear caches just before returning a value. """ @functools.wraps(func) def wrapper(*args, **kwds): result = func(*args, **kwds) _clear_caches() return result return wrapper
5,315,406
def is_dicom(filename): """Returns True if the file in question is a DICOM file, else False. """ # Per the DICOM specs, a DICOM file starts with 128 reserved bytes # followed by "DICM". # ref: DICOM spec, Part 10: Media Storage and File Format for Media # Interchange, 7.1 DICOM FILE META INFORMATIO...
5,315,407
def visualize(DATA_FP): """ Creates the visualization data set for a city Args: DATA_FP - path to data directory, e.g. ../data/boston/ """ print("Generating visualization data") subprocess.check_call([ 'python', '-m', 'data.make_preds_viz', '-d', D...
5,315,408
def choices(population, weights=None, cum_weights=None, k=1): """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ n = len(population) if cum_weights is None: ...
5,315,409
def summarize(text: str) -> str: """Summarizes the text (local mode). :param text: The text to summarize. :type text: str :return: The summarized text. :rtype: str """ if _summarizer is None: load_summarizer() assert _summarizer is not None tokenizer = get_summarizer_tok...
5,315,410
def linreg(array, dim=None, coord=None): """ Compute a linear regression using a least-square method Parameters ---------- x : xarray.DataArray The array on which the linear regression is computed dim : str, optional The dimension along which the data will be fitted. If not precised, the first dimension wi...
5,315,411
def _gte(version): """ Return ``True`` if ``pymongo.version`` is greater than or equal to `version`. :param str version: Version string """ return (pkg_resources.parse_version(pymongo.version) >= pkg_resources.parse_version(version))
5,315,412
def assemble(path, addr=0, clean=True, debug=True): """ Assemble and link THUMB assembly code at an address. Args: path (str): Path to assemble. addr (int): Address to link at. If zero no linking is done. clean (bool): Whether to clean intermediate files. Defaults to True. debug...
5,315,413
def read_data(path, format="turtle"): """ Read an RDFLib graph from the given path Arguments: path (str): path to a graph file Keyword Arguments: format (str): RDFLib format string (default="turtle") Returns: rdflib.Graph: a parsed rdflib.Graph """ g = rdflib.Grap...
5,315,414
def exact_change_recursive(amount,coins): """ Return the number of different ways a change of 'amount' can be given using denominations given in the list of 'coins' >>> exact_change_recursive(10,[50,20,10,5,2,1]) 11 >>> exact_change_recursive(100,[100,50,20,10,5,2,1]) 4563 ...
5,315,415
def dt_filelock_locking(): """ Default locking configuration, enabled. >>> old_state = test_config.setup() >>> _ = config.LOCKING_MODE.set("filelock") >>> crds_cache_locking.init_locks() >>> _ = log.set_verbose() >>> crds_cache_locking.status() 'enabled, filelock' >>> crds_cache_loc...
5,315,416
def detectGap(date, gapThres): """ Detects gap in a date vector based on the user defined threshold. Parameters ---------- date: list Dates in UTCDateTime format to detect gaps within. gapThres: float Threshold in seconds over which to detect a gap. Outputs ----...
5,315,417
def del_engine(config, mskengname): """ This module will remove engine from pool""" if config.verbose: click.echo('Verbose mode enabled') click.echo('mskengname = {0}'.format(mskengname)) mskai = aimasking(config, mskengname=mskengname) mskai.del_engine()
5,315,418
def enum(*sequential, **named): """ Enum implementation that supports automatic generation and also supports converting the values of the enum back to names >>> nums = enum('ZERO', 'ONE', THREE='three') >>> nums.ZERO # 0 >>> nums.reverse_mapping['three'] # 'THREE' """ enums = di...
5,315,419
def deterministic_solve( model, exogenous=None, s0=None, m0=None, T=100, ignore_constraints=False, maxit=100, initial_guess=None, verbose=True, solver="ncpsolve", keep_steady_state=False, s1=None, # deprecated shocks=None, # deprecated tol=1e-6, ): """ C...
5,315,420
def find_check_string_output( # type: ignore ctx, class_name, method_name, as_python=True, fuzzy_match=False, pbcopy=True ): """ Find output of `check_string()` in the test running class_name::method_name. E.g., for `TestResultBundle::test_from_config1` return the content of the file `./co...
5,315,421
def index(): """ Dashboard """ if session.error: return dict() mode = session.s3.hrm.mode if mode is not None: redirect(URL(f="person")) # Load Models s3mgr.load("hrm_skill") tablename = "hrm_human_resource" table = db.hrm_human_resource if ADMIN not in roles: ...
5,315,422
def call_movebank_api(params): """ Authenticate with Movebank API and return the Response content """ response = requests.get('https://www.movebank.org/movebank/service/direct-read', params=params, auth=(os.getenv("MBUSER"), os.getenv("MBPASS")) ) if response.status_code == 200: if '📰 License Terms:' i...
5,315,423
def plot_gmm_preds(x, z, with_supervision, plot_id): """Plot GMM predictions on a 2D dataset `x` with labels `z`. Write to the output directory, including `plot_id` in the name, and appending 'ss' if the GMM had supervision. NOTE: You do not need to edit this function. """ plt.figure(figsize=(...
5,315,424
def chars_repeats_csv_calculate(): """ :return: """ text_training = load_from_file(learning_config['large_training_set_path']) text_validation = load_from_file(learning_config['large_validation_set_path']) text_test = load_from_file(learning_config['large_testing_set_path']) text_all = text...
5,315,425
def Vfun(X, deriv = 0, out = None, var = None): """ expected order : r1, r2, R, a1, a2, tau """ x = n2.dfun.X2adf(X, deriv, var) r1 = x[0] r2 = x[1] R = x[2] a1 = x[3] a2 = x[4] tau = x[5] # Define reference values Re = 1.45539378 # Angstroms re = 0.9625247...
5,315,426
def keep_alive(conn): """ :type conn: cloudbot.clients.clients.IrcClient """ keepalive = conn.config.get('keep_alive', False) if keepalive: while True: conn.cmd('PING', conn.nick) yield from asyncio.sleep(60)
5,315,427
def all_events(number=-1, etag=None): """Iterate over public events. .. deprecated:: 1.2.0 Use :meth:`github3.github.GitHub.all_events` instead. :param int number: (optional), number of events to return. Default: -1 returns all available events :param str etag: (optional), ETag from a...
5,315,428
def cli(): """Main command line tool function.""" if len(sys.argv) <= 1 or sys.argv[1] in ['-h', '--help', 'help']: print("%s: %s" % (__program__, 'Usage: var_learning run <cmd>')) else: fire.Fire(CliObject)
5,315,429
def color_splash(image, mask): """Apply color splash effect. image: RGB image [height, width, 3] mask: instance segmentation mask [height, width, instance count] Returns result image. """
5,315,430
def mock_datetime(monkeypatch: MonkeyPatch) -> FakeDatetime: """Mocks dt.datetime Returns: FakeDatetime(2021, 3, 20) """ fake_datetime = FakeDatetime(2021, 3, 20) fake_datetime.set_fake_now(dt.datetime(2021, 3, 20)) monkeypatch.setattr(dt, "datetime", FakeDatetime) return fak...
5,315,431
def plotspectrum(freqArray, spectrumArray): """ Plots the spectra generated by spectrum(). Keywords: freqArray: array of frequencies in GHz spectrumArray: array of flux densities at the corresponding frequencies in Jy """ plt.figure() plt.plot(freqArray, spectrumArray) plt.grid() plt...
5,315,432
def Normalize(v): """ Normalizes vectors so length of vector is 1. Parameters ---------- v : 2D numpy array, floats Returns ------- 2D numpy array, floats Normalized v. """ norm = np.zeros(v.shape[0]) for i, vector in enumerate(v): norm[i] = n...
5,315,433
def get_instance_details(instance_id): """ Returns json detail of specific instance on slate :return: json object of slate instance details """ query = {"token": slate_api_token, "detailed": "true"} instance_detail = requests.get( slate_api_endpoint + "/v1alpha3/instances/" + instance_id...
5,315,434
def test_sybase_does_not_support_offset(): """This unit test case assert the remaining part of test_open_api_definition_without_offset_support""" assert not layabase._database_sqlalchemy._supports_offset("sybase+pyodbc")
5,315,435
def admin_lexers(request): """Form to configure lexers for file extensions.""" formset = AdminLexersFormSet.for_config() if request.method == 'POST': formset = AdminLexersFormSet.for_config(request.POST) if formset.is_valid(): formset.save() messages.success(request...
5,315,436
def ignore_module_import_frame(file_name, name, line_number, line): """ Ignores the frame, where the test file was imported. Parameters ---------- file_name : `str` The frame's respective file's name. name : `str` The frame's respective function's name. line_number : `in...
5,315,437
def validate_args(args): """ Validate parameters (args) passed in input through the CLI. If necessary, perform transformations of parameter values to the simulation space. :param args: [dict] Parsed arguments. :return: [dict] Validated arguments. """ # note: input data types are already c...
5,315,438
def knapsack(val,wt,W,n): """ Consider W=5,n=4 wt = [5, 3, 4, 2] val = [60, 50, 70, 30] So, for any value we'll consider between maximum of taking wt[i] and not taking it at all. taking 0 to W in column 'line 1' taking wt in rows 'line 2' two cases -> * cur_wt<=total wt in that c...
5,315,439
def CNN_model_basic(img_height, img_width,OPTIMIZER): """ This is a customized function for generating a Keras model built-in Keras module with pre-defined parameters and model architecture. Parameters ----------------- img_height,img_width = input image dimensions OPTIMIZER = keras o...
5,315,440
def get_filter_df(df, filter_col, targets, greater_than=True): """ Filter dataframe based on target column Returns dataframe """ if filter_col in ["transactions", "category"]: df_filter = get_filter_indicator_df(df, filter_col, targets) elif filter_col == "rating": if greater_th...
5,315,441
def formatOutputOrigin(originInfo, output_type): """ Formats the output on a given format (json or text) """ if output_type == "json": # Let's print the JSON print(json.dumps(originInfo, indent=2)) if output_type == "text": # Iterate over the dictionary and print the selected inform...
5,315,442
def description_comments(n, shifts, f): """Writes comments to the top of the output file describing what it does. Write comments to the top of the smt2 file describing the proof it contains: the operation, how many bits in the arguments, and how many operations. Args: n: An integer, the number of bits in ...
5,315,443
def filter_graph(graph, n_epochs): """ Filters graph, so that no entry is too low to yield at least one sample during optimization. :param graph: sparse matrix holding the high-dimensional similarities :param n_epochs: int Number of optimization epochs :return: """ graph = graph.copy() g...
5,315,444
def test_MKDADensity_approximate_null(testdata_cbma_full, caplog): """Smoke test for MKDADensity with the "approximate" null_method.""" meta = MKDADensity(null="approximate") res = meta.fit(testdata_cbma_full) corr = FWECorrector(method="montecarlo", voxel_thresh=0.001, n_iters=5, n_cores=1) cres = ...
5,315,445
def show_blade_memory_health(device_id): """ Get and display blade memory health IMPORTANT! - Output formatted for compatibility with WcsCli """ try: result = show_memory_info(device_id) if not check_success(result): print "Command Failed....
5,315,446
def create_file_with_maximum_util(folder_file): """ from a folder with multiple .xls-files, this function creates a file with maximum values for each traffic counter based on all .xls-files (ASFINAG format) :param folder_file: String :return: pandas.DataFrame """ # collect all .xls files as ...
5,315,447
def join_detectionlimit_to_value(df, **kwargs): """Put sign and numeric value together. For example: "<" + "100" = "<100").""" df['Value'] = np.where(df['Value_sign'].isnull(), df['Value_num'], df['Value_sign'] + df['Value_num'].astype(str)) return df
5,315,448
def read_data(datapath, metadatapath, label_key='Schizophrenia'): """read_data :param datapath: path to data file (gene) :param metadatapath: path to meta data file of patients :output x: data of shape n_patient * n_features :output y: label of shape n_patients, label[i] == 1 means that the pat...
5,315,449
def show(tournament, match_id): """Retrieve a single match record for a tournament.""" return api.fetch_and_parse( "GET", "tournaments/%s/matches/%s" % (tournament, match_id))
5,315,450
def get_Frequency(ids): """ Restituisce la frequenze presente sul DB con un ID specifico """ db = Database() db_session = db.session data = db_session.query(db.frequency).filter(db.frequency.id == ids).all() data_dumped = json.dumps(data, cls=AlchemyEncoder) db_session.close() re...
5,315,451
def ycbcr_to_rgb_jpeg(image): """ Converts YCbCr image to RGB JPEG Input: image(tensor): batch x height x width x 3 Outpput: result(tensor): batch x 3 x height x width """ matrix = np.array( [[1., 0., 1.402], [1, -0.344136, -0.714136], [1, 1.772, 0]], dtype=np.float32...
5,315,452
def test_invalid_choices(event, field, glsc): """This test verifies that the form returns a meaningful message if one of the choice fields contains an invalid choice. It takes a parameter that consists of a two element tuple containing the field_id, and the choice key. The choice key is used get the re...
5,315,453
def build_index(in_file, index_file): """Build an index of the MAF file for retrieval. """ indexes = interval_index_file.Indexes() with open(in_file) as in_handle: reader = maf.Reader(in_handle) while 1: pos = reader.file.tell() rec = reader.next() if ...
5,315,454
def gen_dist_train_test(train_df, test_df, pivot_table, gen_se_dist, gen_pro_cli_dist, external_info): """generate dist information on training data, merge the distribution with both training data and test data The Data flow should look like this: train_df ==> pivot_table ==> gen_se_dist ====> get_dist...
5,315,455
def get_global_step(hparams): """Returns the global optimization step.""" step = tf.to_float(tf.train.get_or_create_global_step()) multiplier = hparams.optimizer_multistep_accumulate_steps if not multiplier: return step return step / tf.to_float(multiplier)
5,315,456
def search_file(): """ Fonction effectuant une recherche récursive dans les dossiers de l'utilisateur à l'aide de la commande LINUX 'find' """ if "username" not in session: return redirect("/") if request.method == "POST": search = request.form['sb'] res=[] res2=[...
5,315,457
def getValues(astr, begInd=0): """ Extracts all values (zero or more) for a keyword. Inputs: astr: the string to parse begInd: index of start, must point to "=" if the keyword has any values or ";" if the keyword has no values. Initial whitespace is skipped. Returns a duple consisting of: a tu...
5,315,458
def rev_find(revs, attr, val): """Search from a list of TestedRev""" for i, rev in enumerate(revs): if getattr(rev, attr) == val: return i raise ValueError("Unable to find '{}' value '{}'".format(attr, val))
5,315,459
def test_get_envois(): """Test get_envois with a mock.""" with requests_mock.Mocker() as m: api_response = open("pydelivengo/tests/assets/get_envois_ok.json", "rb", encoding='utf8').read() m.get('https://mydelivengo.laposte.fr/api/v2.4/envois', text=api_response) api = PyDelivengo(api_a...
5,315,460
def enq(queue_name, args): """Enqueue a single task in the named queue.""" task_cls = get_taskclass(queue_name) inst = task_cls() inst.delay(*args)
5,315,461
def untempering(p): """ see https://occasionallycogent.com/inverting_the_mersenne_temper/index.html >>> mt = MersenneTwister(0) >>> mt.tempering(42) 168040107 >>> untempering(168040107) 42 """ e = p ^ (p >> 18) e ^= (e << 15) & 0xEFC6_0000 e ^= (e << 7) & 0x0000_1680 e ^...
5,315,462
def single_run(var='dt', val=1e-1, k=5, serial=True): """ A simple test program to do PFASST runs for the heat equation """ # initialize level parameters level_params = dict() level_params[var] = val # initialize sweeper parameters sweeper_params = dict() sweeper_params['collocatio...
5,315,463
def tofloat(img): """ Convert a uint8 image to float image :param img: numpy image, uint8 :return: float image """ return img.astype(np.float) / 255
5,315,464
def get_session() -> requests_cache.CachedSession: """Convenience function that returns request-cache session singleton.""" if not hasattr(get_session, "session"): get_session.session = requests_cache.CachedSession( cache_name=str(CACHE_PATH), expire_after=518_400 # 6 days ) ...
5,315,465
def parse_html(html): """ Take a string that contains HTML and turn it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored. """ parser = Parser() parser.fe...
5,315,466
def get_atomic_num_one_hot(atom: RDKitAtom, allowable_set: List[int], include_unknown_set: bool = True) -> List[float]: """Get a one-hot feature about atomic number of the given atom. Parameters --------- atom: rdkit.Chem.rdchem.Atom RDKit atom object ...
5,315,467
def ds_to_1Darr(varname,ds,srate='reg',dataw='notrend'): """ var is a string, varibale name from the ds # choose how much data wrangling to do : remove mean or remove mean and trend dataw = 'nomean' or 'notrend' # choose the sampling rate: raw/unchanged or regular 10/9 days srate = reg' or 'ra...
5,315,468
def fs_check(**arguments): """Abstracts common checks over your file system related functions. To reduce the boilerplate of expanding paths, checking for existence or ensuring non empty values. Checks are defined for each argument separately in a form of a set e.g @fs_check(path={'required'...
5,315,469
def old_pgp_edition(editions): """output footnote and source information in a format similar to old pgp metadata editor/editions.""" if editions: # label as translation if edition also supplies translation; # include url if any edition_list = [ "%s%s%s" % ( ...
5,315,470
def ConstructApiDef(api_name, api_version, is_default, base_pkg='googlecloudsdk.third_party.apis'): """Creates and returns the APIDef specified by the given arguments. Args: api_name: str, The API name (or the command surface name, if different). ...
5,315,471
def L2struct_array(L,dtype={'names':('score','col','S_init','tree'),'formats':('f4','S10000','S10000','S10000')}): """ Convert list output from extract_elite to structured Numpy array. Contracts initial conditions string with tree string. Converts column string to int (after removing brackets). Inputs: L: li...
5,315,472
def build_model(x_train_text, x_train_numeric, **kwargs): """Build TF model.""" max_features = 5000 sequence_length = 100 encoder = preprocessing.TextVectorization(max_tokens=max_features, output_sequence_length=sequence_length) encoder.adapt(x_train_text.values) ...
5,315,473
def find_group(name): """Make a special case of finding a group. NB This uses ambiguous name resolution so only use it for a casual match """ return root().find_group(name)
5,315,474
def multiplicar(a, b): """ MULTIPLICAR realiza la multiplicacion de dos numeros Parameters ---------- a : float Valor numerico `a`. b : float Segundo valor numerico `b`. Returns ------- float Retorna la suma de `a` + `b` """ return a*b
5,315,475
def email_vertices(): """Return the email_vertices dataframe Contains the following fields: # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 1005 non-null int64 1 dept 1005 non-null int64 """ stream = pk...
5,315,476
def test_save(session): """Assert that saving an an account bcol id mapping works as expected.""" account_bcol_id = AccountBcolId(account_id='PS12345', bconline_account=200000004) account_bcol_id.save() assert account_bcol_id.id > 0 test_mapping = AccountBcolId.find_by_account_id_bcol_number('PS1234...
5,315,477
def pascal_row(n): """returns the pascal triangle row of the given integer n""" def triangle(n, lst): if lst ==[]: lst = [[1]] if n == 1: return lst else: oldRow = lst[-1] def helpRows(lst1, lst2): if lst1 == [] or lst2 == [...
5,315,478
def rename_project(new_name: str, pid: int) -> None: """ Renames a project. :param new_name: New name of project. :param pid: The project's id (primary key). """ p = get_project_by_id(pid=pid) assert p is not None p.name = new_name p.save()
5,315,479
def _apply_homography(H: np.ndarray, vdata: np.ndarray) -> tuple : """ Apply a homography, H, to pixel data where only v of (u,v,1) is needed. Apply a homography to pixel data where only v of the (u,v,1) vector is given. It is assumed that the u coordinate begins at 0. The resulting vector (x,y,z) is normali...
5,315,480
def asts(repo): """A dict {filename: ast} for all .py files.""" asts = {} for src_fn, src in repo._calc('source_contents').iteritems(): try: ast = pyast.parse(src) except: #if their code does not compile, ignore it #TODO should probably be more strict agai...
5,315,481
def is_matching_layer(layer): """Returns true if the name of the given layer meets the criteria for processing.""" return ( re.match(LAYER_PREFIX_TO_MATCH, layer.name()) and re.match(f'.*{LAYER_SUBSTRING_TO_MATCH}.*', layer.name()) and re.search(SUFFIX_CLEANABLE, layer.name()) and ...
5,315,482
def parse_call_no(field: Field, library: str) -> namedtuple: """ Parses call number data per each system rules Args: field: call number field, instance of pymarc.Field library: library system Returns: """ if library == "bpl": callNo_data...
5,315,483
def ni(num,tem): """ num: density cm^-3 """ b = zeros( Aij.shape[0] + 2 , dtype='float64') b[-1] = 10 # this line is REALLY STUPID, but for some pointless reason linalg experiences # precision errors and thinks that A is singular when it is obviously not. if tem > 30: myni = dot(linalg....
5,315,484
def _parse_example_configuration(config, regexps): """ Parse configuration lines against a set of comment regexps Args: config(_io.TextIOWrapper): Example configuration file to parse regexps(dict[str, list[tuple[re.__Regex, str]]]): Yields: str: Parsed configuration lines "...
5,315,485
def readCosmicRayInformation(lengths, totals): """ Reads in the cosmic ray track information from two input files. Stores the information to a dictionary and returns it. :param lengths: name of the file containing information about the lengths of cosmic rays :type lengths: str :param totals: na...
5,315,486
def testGetMonthlySingleDataInSpesificYearMonthWithWrongParamFormat(): """[NEGATIVE] Test Route /vaccination/monthly/2021/39 [get monthly cases] with wrong format """ testApp = createFlaskTestApp() response = testApp.get('/vaccination/monthly/2021/39') print(response.status_code) decodedJson = json....
5,315,487
def get_package_version(): """get version from top-level package init""" version_file = read('pyshadoz/__init__.py') version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise Runtim...
5,315,488
def setup_default_abundances(filename=None): """ Read default abundance values into global variable. By default, data is read from the following file: https://hesperia.gsfc.nasa.gov/ssw/packages/xray/dbase/chianti/xray_abun_file.genx To load data from a different file, see Notes section. Param...
5,315,489
def resolve_conflicts2_next(pid): """ update page number to db update kapr to db flush related cache in redis """ user = current_user assignment_id = pid + '-' + user.username # find if this project exist assignment = storage_model.get_conflict_project(mongo=mongo, username=user.use...
5,315,490
def load_dataset(datapath): """ Load dataset at given datapath. Datapath is expected to be a list of directories to follow. """ inFN = abspath(join(dirname(__file__), datapath)) return rs.read_mtz(inFN)
5,315,491
def displace_vertices(vertices, directions, length=1., mask=True): """ Displaces vertices by given length along directions where mask is True Parameters ---------- vertices: (n, d) float Mesh vertices directions: (n, d) float Directions of displacement (e.g. the mesh normals...
5,315,492
def point_in_poly(x,y,poly): """" Ray Casting Method: Drawing a line from the point in question and stop drawing it when the line leaves the polygon bounding box. Along the way you count the number of times you crossed the polygon's boundary. If the count is an odd number the point must be inside. ...
5,315,493
def can_comment(request, entry): """Check if current user is allowed to comment on that entry.""" return entry.allow_comments and \ (entry.allow_anonymous_comments or request.user.is_authenticated())
5,315,494
def tianqin_psd(f, L=np.sqrt(3) * 1e5 * u.km, t_obs=None, approximate_R=None, confusion_noise=None): """Calculates the effective TianQin power spectral density sensitivity curve Using Eq. 13 from Huang+20, calculate the effective TianQin PSD for the sensitivity curve Note that this function includes an ex...
5,315,495
def hdf5_paths(ds, indent=0, maxlen=100): """Visit and print name of all element in HDF5 file (from S Hauf)""" for k in list(ds.keys())[:maxlen]: print(" " * indent + k) if isinstance(ds[k], h5py.Group): hdf5_paths(ds[k], indent + 4, maxlen) else: print(" " * ind...
5,315,496
def integration_installed(service_installed): """Prepare honeycomb home path with DEMO_INTEGRATION installed.""" home = service_installed result = CliRunner().invoke(cli, args=args.COMMON_ARGS + [home, defs.INTEGRATION, commands.INSTALL, DEMO_INTEGRATION]) sanity_check(r...
5,315,497
def check_keyup_events(event, ship): """Responde a solturas de tecla.""" if event.key == pygame.K_RIGHT: ship.moving_right = False elif event.key == pygame.K_LEFT: ship.moving_left = False
5,315,498
def __get_request_body(file: BytesIO, file_path: str, repo_url: str) -> dict[str, str]: """Creates request body for GitHub API. Parameters: file_path: path where file is to be uploaded (e.g. /folder1/folder2/file.html) file: File-like object repo_url: url of SuttaCentral editions repo ...
5,315,499