content
stringlengths
22
815k
id
int64
0
4.91M
def promote(lhs, rhs, promote_option=True): """Promote two scalar dshapes to a possibly larger, but compatible type. Examples -------- >>> from datashape import int32, int64, Option >>> x = Option(int32) >>> y = int64 >>> promote(x, y) Option(ty=ctype("int64")) >>> promote(int64, in...
300
def calc_derFreq(in_tped, out_derFreq_tsv): """Calculate the derived allele frequency for each SNP in one population""" with open(in_tped) as tped, open(out_derFreq_tsv, 'w') as out: out.write('\t'.join(['chrom', 'snpId', 'pos', 'derFreq']) + '\n') for line in tped: chrom, snpId, gen...
301
def validate_esc(esc): """Validate esc options\n Give an error if the characters aren't '*?[]' """ esc = esc.replace("]", "[") argset = set(esc) charset = {"*", "?", "["} if argset.difference(charset): err = "input character is not '*?[]'" raise argparse.ArgumentTypeError(err...
302
def reset(): """Reset the radio device""" #extern void radio_reset(void); radio_reset_fn()
303
def test_profile_valid(resource_type): """Resource types are valid.""" assert resource_type == mapbox.Analytics( access_token='pk.test')._validate_resource_type(resource_type)
304
def calc_amp_pop(eigenvecs, wave_func, nstates): """Calculates amplitudes and population from wave function, eigenvectors""" pop = np.zeros(nstates) amp = np.zeros((nstates), dtype=np.complex128) for j in range(nstates): amp[j] = np.dot(eigenvecs[:, j], wave_func) pop[j] = np.real(bra_k...
305
def reflect(cls, *args, **kwargs): """ Construct a funsor, populate ``._ast_values``, and cons hash. This is the only interpretation allowed to construct funsors. """ if len(args) > len(cls._ast_fields): # handle varargs new_args = tuple(args[:len(cls._ast_fields) - 1]) + (args[len(c...
306
def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description='Semantic Segmentation') # Data parameters. parser.add_argument('--batch_size', type=int, default=1, help='Number of ima...
307
def make_strictly_feasible(x, lb, ub, rstep=1e-10): """Shift a point to the interior of a feasible region. Each element of the returned vector is at least at a relative distance `rstep` from the closest bound. If ``rstep=0`` then `np.nextafter` is used. """ x_new = x.clone() active = find_activ...
308
def main(): """ General test method """ from . import spectra as sp p_dict = {'Bfield':700,'rb85frac':1,'Btheta':88*np.pi/180,'Bphi':0*np.pi/180,'lcell':75e-3,'T':84,'Dline':'D2','Elem':'Cs'} chiL,chiR,chiZ = sp.calc_chi(np.linspace(-3500,3500,10),p_dict) #print 'ez: ',chiZ + 1 # ez / e0 #print 'ex: ',0.5*(2+chi...
309
def SearchPageGenerator(query, step=None, total=None, namespaces=None, site=None): """ Provides a list of results using the internal MediaWiki search engine """ if site is None: site = pywikibot.Site() for page in site.search(query, step=step, total=total, namespaces=namespaces): yie...
310
def add_emails(request): """ Args: request: Http Request (ignored in this function) Returns: Add operation status wrapped on response's object """ error_messages = [] success_messages = [] status = HTTP_200_OK success, message = queries.add_emails(request.data) if success: success_messages.append(messag...
311
def deposit(amount, account): """Deposit STEEM to market in exchange for STEEMP.""" stm = shared_blockchain_instance() if stm.rpc is not None: stm.rpc.rpcconnect() if not stm.is_steem: print("Please set a Steem node") return if not account: account = stm.conf...
312
def tanD(angle): """ angle est la mesure d'un angle en degrés ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Retourne la tangente de angle. """ return math.tan(math.radians(angle))
313
def test_complex_df(complex_dataframe): """ Get a dataframe from a complex mapped dataframe """ df = complex_dataframe mapper = DataFrameMapper( [('target', None), ('feat1', None), ('feat2', None)], df_out=True) transformed = mapper.fit_transform(df) assert len(transformed) =...
314
def main(verbose: bool = False, log_path: Optional[str] = None): """Launches Noteserver. Noteserver is a LSP server that works with most editors in order to help make taking notes easier! This program expects to receive LSP RPCs from stdin and will produce LSP RPCs to stdout. Args: verbose: Include for ...
315
def step_i_get_a_task_from_the_entity_using_the_service_api( context, service_name, tasks_service_name, filename ): """ :type context: behave.runner.Context :type service_name: str :type tasks_service_name: str :type filename: str """ location = context.json_location headers = read_j...
316
def parse_all_headers(): """ Call parse_header() on all of Allegro's public include files. """ p = options.source includes = " -I " + p + "/include -I " + os.path.join(options.build, "include") includes += " -I " + p + "/addons/acodec" headers = [p + "/include/allegro5/allegro.h", ...
317
def offset_zero_by_one(feature): """Sets the start coordinate to 1 if it is actually 0. Required for the flanking to work properly in those cases. """ if feature.start == 0: feature.start += 1 return feature
318
def smilesToMolecule(smiles): """ Convert a SMILES string to a CDK Molecule object. Returns: the Molecule object """ mol = None try: smilesParser = cdk.smiles.SmilesParser(silentChemObjectBuilder) mol = smilesParser.parseSmiles(smiles) except cdk.exception.InvalidSmilesExcep...
319
def build_pathmatcher(name, defaultServiceUrl): """ This builds and returns a full pathMatcher entry, for appending to an existing URL map. Parameters: name: The name of the pathMatcher. defaultServiceUrl: Denotes the URL requests should go to if none of the path patterns match. """ matcher ...
320
def gaussian1D_smoothing(input_array, sigma, window_size): """ Function to smooth input array using 1D gaussian smoothing Args: input_array (numpy.array): input array of values sigma (float): sigma value for gaussian smoothing wi...
321
async def test_enabling_webhook(hass, hass_ws_client, setup_api, mock_cloud_login): """Test we call right code to enable webhooks.""" client = await hass_ws_client(hass) with patch( "hass_nabucasa.cloudhooks.Cloudhooks.async_create", return_value={} ) as mock_enable: await client.send_js...
322
def add_whitespace(c_fn): """ Add two spaces between all tokens of a C function """ tok = re.compile(r'[a-zA-Z0-9_]+|\*|\(|\)|\,|\[|\]') return ' ' + ' '.join(tok.findall(c_fn)) + ' '
323
def readFlow(fn): """ Read .flo file in Middlebury format""" with open(fn, 'rb') as f: magic = np.fromfile(f, np.float32, count=1) if 202021.25 != magic: print('Magic number incorrect. Invalid .flo file') return None else: w = np.fromfile(f, np.int32, ...
324
def test_method_attr(): """Test the value of the method attribute.""" assert_equal(m.method, "multidim_parameter_study")
325
def plot_umap_list(adata, title, color_groups): """ Plots UMAPS based with different coloring groups :param adata: Adata Object containing a latent space embedding :param title: Figure title :param color_groups: Column name in adata.obs used for coloring the UMAP :return: """ try: ...
326
def page_with_subject_page_generator( generator: Iterable[pywikibot.Page], return_subject_only=False ) -> Generator[pywikibot.Page, None, None]: """ Yield pages and associated subject pages from another generator. Only yields subject pages if the original generator yields a non- subject page, and d...
327
def _delete_block_structure_on_course_delete(sender, course_key, **kwargs): # pylint: disable=unused-argument """ Catches the signal that a course has been deleted from the module store and invalidates the corresponding cache entry if one exists. """ clear_course_from_cache(course_key)
328
def _filename(url, headers): """Given the URL and the HTTP headers received while fetching it, generate a reasonable name for the file. If no suitable name can be found, return None. (Either uses the Content-Disposition explicit filename or a filename from the URL.) """ filename = None # Tr...
329
def MatrixCrossProduct(Mat1, Mat2): """ Returns the cross products of Mat1 and Mat2. :param: - Mat1 & Mat2 - Required : 5D matrix with shape (3,1,nz,ny,nx). :return: - Mat3 : 5D matrix with shape (3,1,nz,ny,nx). """ Mat3 = np.zeros_like(Mat1) Mat3[0] = ...
330
def partition_preds_by_scrape_type(verify_predictions, evidence_predictions, val_examples): """Partition predictions by which scrape_type they come from. The validation fold contains four sets of evidence: drqa, lucene, ukp_pred, and ukp_wiki....
331
def apply_delay_turbulence(signal, delay, fs): """Apply phase delay due to turbulence. :param signal: Signal :param delay: Delay :param fs: Sample frequency """ k_r = np.arange(0, len(signal), 1) # Create vector of indices k = k_r - delay * fs # Create vector ...
332
def binaryContext(): """Return the registered context for the binary functions. Return Value: Ctor() for the binary function context """ return bin_func_class
333
def validate_vm_file(file_name: Path, nx: int, ny: int, nz: int): """ Validates that a velocity model file has the correct size, and no 0 values in a sample of the layers :param file_name: A Path object representing the file to test :param nx, ny, nz: The size of the VM in grid spaces (nx*ny*nz) :re...
334
def format_assignment_html(recording, debug=False): """Given a single recording, format it into an HTML file. Each recording will only have one student. Returns a {content: str, student: str, type: str, assignment: str} dict. """ try: files = format_files_list(recording.get('files', {})) ...
335
def plot_PSD_amps(df, ch_titles, out_dir, channel): """ Plots PSD using pwelch method. """ %matplotlib qt sr = df["samplerate"].values[0] df_0 = df.loc[df['amplitude_ma'] == df['amplitude_ma'].unique()[0]] df_1 = df.loc[df['amplitude_ma'] == df['amplitude_ma'].unique()[1]] df_2 = df.loc[df[...
336
def test_createTask1(): """Checks for newly created task its status and urgency""" i_task = tq.create_task("immediate") assert i_task.status == "pending" and i_task.urgency == 3
337
def adapted_chu_liu_edmonds(length: int, score_matrix: numpy.ndarray, coreference: List[int], current_nodes: List[bool], final_edges: Dict[int, int], old_input: numpy.ndarray, ...
338
def compute_xlabel_confusion_matrix(y_true, y_pred, labels_train=None, labels_test=None, normalize=True, sample_weight=None): """Computes confusion matrix when the labels used to train the classifier are different than those of the test set. Args: y_true: Ground...
339
def write_build_file(build_gn_path, package_name, name_with_version, language_version, deps, dart_sources): """ writes BUILD.gn file for Dart package with dependencies """ with open(build_gn_path, 'w', encoding='utf-8') as build_gn: build_gn.write('''# This file is generated by importer.py for %s impor...
340
def generate_synthetic_data(n=50): #n is the number of generated random training points from normal distribution """Create two sets of points from bivariate normal distributions.""" points = np.concatenate((ss.norm(0,1).rvs((n,2)),ss.norm(1,1).rvs((n,2))), axis=0) #norm(mean, standard deviation) #'.rvs' ...
341
def show_qr_detection(img, pts): """Draw both the lines and corners based on the array of vertices of the found QR code""" pts = np.int32(pts).reshape(-1, 2) for j in range(pts.shape[0]): cv2.line(img, tuple(pts[j]), tuple(pts[(j + 1) % pts.shape[0]]), (255, 0, 0), 5) for j in range(pts.shape...
342
def upload_download_test(**kwargs): """Run upload and/or download test with generated test files""" cwm_worker_tests.upload_download_test.main(**kwargs)
343
def mask_array(array, idx, n_behind, n_ahead): """[summary] Args: array ([type]): [description] idx ([type]): [description] n_behind ([type]): [description] n_ahead ([type]): [description] Returns: [type]: [description] """ first = max(0, idx - n_behind) ...
344
def test_atomic_language_length_2_nistxml_sv_iv_atomic_language_length_3_5(mode, save_output, output_format): """ Type atomic/language is restricted by facet length with value 10. """ assert_bindings( schema="nistData/atomic/language/Schema+Instance/NISTSchema-SV-IV-atomic-language-length-3.xsd"...
345
def pip_main(): """Entry point for pip-packaged binary Required because the pip-packaged binary calls the entry method without arguments """ main([' '.join(sys.argv[1:])])
346
def get_nfs_acl(path: str, user: str) -> str: """ Retrieve the complete list of access control permissions assigned to a file or directory. """ raw = command(["/usr/bin/nfs4_getfacl", path], output=True).stdout.decode("utf-8") allowed: Set[str] = set() denied: Set[str] = set() for line in ra...
347
def PolyMult(p1, p2, debug=False): """ Multiply two numbers in the GF(2^8) finite field defined See http://stackoverflow.com/questions/13202758/multiplying-two-polynomials For info """ binP2 = bin(p2)[2:].zfill(8) mult = 0 if p1 == 0 or p2 == 0: return 0 for i in range(8): ...
348
def run_hdbscan(X_df, X_tsne, output_dir, transparent): """Cluster using density estimation Parameters ---------- X_df: DataFrame X_tsne: array-like, [n_samples, 2] output_dir: str, path transparent: bool Returns ------- clusterer: HDBSCAN object assignments: numpy array of...
349
async def test_http_error400(aresponses): """Test HTTP 404 response handling.""" aresponses.add( "pvoutput.org", "/service/r2/test", "GET", aresponses.Response(text="OMG PUPPIES!", status=404), ) async with aiohttp.ClientSession() as session: pvoutput = PVOutput(...
350
def check_min_sample_periods(X, time_column, min_sample_periods): """ Check if all periods contained in a dataframe for a certain time_column contain at least min_sample_periods examples. """ return (X[time_column].value_counts() >= min_sample_periods).prod()
351
def _insert(partition, bat): """ 用于向hbase中插入数据, 每个数据表字段不同需要单独写put语句 :param partition: 【partition】 :param bat: 【batch】 :return: """ for row in partition: # bat.put(str(row.datasetA.movie_id).encode(), # {"similar:{}".format(row.datasetB.movie_id).encode(): b"%0.4f" % (...
352
def main(): """ Run ftfy as a command-line utility. (Requires Python 2.7 or later, or the 'argparse' module.) """ import argparse parser = argparse.ArgumentParser() parser.add_argument('filename', help='file to transcode') args = parser.parse_args() file = open(args.filename) ...
353
def test_profit(performance): """The profit property should return the profit earned on a win bet for the performance""" expected_value = -1.0 if performance['result'] == 1: expected_value += performance['starting_price'] assert performance.profit == expected_value
354
def get_quest_stat(cards): # pylint: disable=R0912,R0915 """ Get quest statistics. """ res = {} encounter_sets = set() keywords = set() card_types = {} for card in cards: if card.get(lotr.CARD_KEYWORDS): keywords = keywords.union( lotr.extract_keywords(c...
355
def build_command_names(): """ Use the list of commands available to build the COOMAND_NAMES dict. """ for cmd in COMMANDS: doc = cmd.__doc__.strip() if cmd.__doc__ is not None else 'Unknown' doc = doc.split('\n')[0] COMMAND_NAMES[cmd.__name__] = {'name': doc, 'function': cmd}
356
def bind_type(python_value): """Return a Gibica type derived from a Python type.""" binding_table = {'bool': Bool, 'int': Int, 'float': Float} if python_value is None: return NoneType() python_type = type(python_value) gibica_type = binding_table.get(python_type.__name__) if gibica_t...
357
def delete_server(hostname, instance_id): """ Deletes a server by hostname and instance_id. """ host = get_host_by_hostname(hostname) if not host or not instance_id: return None try: r = requests.delete("%s/servers/%i" % (host['uri'], instance_id), au...
358
def quote_ident(val): """ This method returns a new string replacing " with "", and adding a " at the start and end of the string. """ return '"' + val.replace('"', '""') + '"'
359
def TFC_TDF(in_channels, num_layers, gr, kt, kf, f, bn_factor=16, bias=False): """ Wrapper Function: -> TDC_TIF in_channels: number of input channels num_layers: number of densely connected conv layers gr: growth rate kt: kernel size of the temporal axis. kf: kernel size of the freq. axis ...
360
def barplot_data(gene_values, gene_names, cluster_name, x_label, title=None): """ Converts data for top genes into a json for building the bar plot. Output should be formatted in a way that can be plugged into Plotly. Args: gene_values (list): list of tuples (gene_id, gene_value) ...
361
def save_animate(data, data_root, quantity, kwargs_plot={}, kwargs_animate={}): """ Save the frames and animate the quantity of interest Args: data: the flow field defined by the class SimFramework data_root: file path to an empty folder to save frames to quantity: what we are animat...
362
def main(): """main function""" field = { 'minLngE6': 116298171, 'minLatE6': 39986831, 'maxLngE6': 116311303, 'maxLatE6': 39990941, } with open('cookies') as cookies: cookies = cookies.read().strip() intel = ingrex.Intel(cookies, field) result = intel.fe...
363
def logic_not(operand: ValueOrExpression) -> Expression: """ Constructs a logical negation expression. """ return Not(operators.NotOperator.NOT, ensure_expr(operand))
364
def webpage_attribute_getter(attr): """ Helper function for defining getters for web_page attributes, e.g. ``get_foo_enabled = webpage_attribute_getter("foo")`` returns a value of ``webpage.foo`` attribute. """ def _getter(self): return getattr(self.web_page, attr) return _getter
365
def diff_with_step(a:np.ndarray, step:int=1, **kwargs) -> np.ndarray: """ finished, checked, compute a[n+step] - a[n] for all valid n Parameters ---------- a: ndarray, the input data step: int, default 1, the step to compute the difference kwargs: dict, Returns ---...
366
def main(): """ Driver to download all of the ancillary data files """ # Get data from World Ocean (WOA) 2013 version 2 # get_WOA13_data() # Get data from NODC (Levitus) World Ocean Atlas 1994 # get_WOA94_data() # Get data from NODC World Ocean Atlas 2001 # get_WOA01_data() # GEBCO’...
367
def save_temp_data(data, filename, directory='temp'): """save temp data to disk""" if not os.path.exists(directory): os.makedirs(directory) with open(directory + '/'+ filename + '.temp', 'wb') as f: pickle.dump(data, f) f.close() print("Data saved to", filename + ".temp in worki...
368
def rmse(y_true: np.ndarray, y_pred: np.ndarray): """ Returns the root mean squared error between y_true and y_pred. :param y_true: NumPy.ndarray with the ground truth values. :param y_pred: NumPy.ndarray with the ground predicted values. :return: root mean squared error (float). """ return...
369
def party_name_from_key(party_key): """returns the relevant party name""" relevant_parties = {0: 'Alternativet', 1: 'Dansk Folkeparti', 2: 'Det Konservative Folkeparti', 3: 'Enhedslisten - De Rød-Grønne', 4: 'Liberal...
370
def GetOutDirectory(): """Returns the Chromium build output directory. NOTE: This is determined in the following way: - From a previous call to SetOutputDirectory() - Otherwise, from the CHROMIUM_OUTPUT_DIR env variable, if it is defined. - Otherwise, from the current Chromium source directory, and a p...
371
def __imul__(self,n) : """Concatenate the bitstring to itself |n| times, bitreversed if n < 0""" if not isint(n) : raise TypeError("Can't multiply bitstring by non int"); if n <= 0 : if n : n = -n; l = self._l; for i in xrange(l//2) : self[i],self[l-1-i] = self[l-1-i],se...
372
def FlushAllCaches(): """Removes any cached data from datastore/memache.""" chart_data_keys = ChartData.query().fetch(keys_only=True) ndb.delete_multi(chart_data_keys) project_list_keys = Projects.query().fetch(keys_only=True) ndb.delete_multi(project_list_keys)
373
def test_integration_format_configuring_conf_json_no_interactive_positive(tmp_path: PosixPath, source_path: str, destination_path: str, ...
374
def update_cache(force=False, cache_file=None): """ Load a build cache, updating it if necessary. A cache is considered outdated if any of its inputs have changed. Arguments force -- Consider a cache outdated regardless of whether its inputs have been modified. """ if not cach...
375
def create_uniform_masses_lengths_randomizer_qq(frac_halfspan: float): """ Get a uniform randomizer that applies to all masses and lengths of the Quanser Qube according to a fraction of their nominal parameter values :param frac_halfspan: fraction of the nominal parameter value :return: `DomainRand...
376
def compress_table(tbl, condition, blen=None, storage=None, create='table', **kwargs): """Return selected rows of a table.""" # setup storage = _util.get_storage(storage) names, columns = _util.check_table_like(tbl) blen = _util.get_blen_table(tbl, blen) _util.check_equal_len...
377
def validate_schedule(): """Helper routine to report issues with the schedule""" all_items = prefetch_schedule_items() errors = [] for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS: for item in validator(all_items): errors.append('%s: %s' % (msg, item)) all_slots = prefetch_...
378
def train_gridsearchcv_model(base_model: Any, X: np.array, y: np.array, cv_splitter, hyperparameter_grid: Dict[str, Any], scoring: Union[str, Callable[[Any, np.array, np.ar...
379
def set_resolmatrix(nspec,nwave): """ Generate a Resolution Matrix Args: nspec: int nwave: int Returns: Rdata: np.array """ sigma = np.linspace(2,10,nwave*nspec) ndiag = 21 xx = np.linspace(-ndiag/2.0, +ndiag/2.0, ndiag) Rdata = np.zeros( (nspec, len(xx), nwave)...
380
def assembleR(X, W, fct): """ """ M = W * fct(X) return M
381
def generate_dictionary_variable_types( dict_name, key_name, search_dict, indent_level=0 ): """Generate a dictionary from config with values from either function, variable, or static""" out_str = [] # Don't escape these: types_used = ["None", "True", "False", None, True, False] if len(search_d...
382
def make_uuid(value): """Converts a value into a python uuid object.""" if isinstance(value, uuid.UUID): return value return uuid.UUID(value)
383
def test_twospin_v_coo(): """Tests to see if sparse.tensordot works with COO arrays instead. This test passes for sparse <=0.10.0, but fails for >=0.11.0, and generates the same nmrsim error that was observed when sparse was upgraded. """ v, J = spin2() Lz = np.array( [[[0.5 + 0.j, 0. +...
384
def create_config(config_data, aliases=False, prefix=False, multiple_displays=False, look_info=None, custom_output_info=None, custom_lut_dir=None): """ Create the *OCIO* config based on the configuration ...
385
def parse_json_with_comments(pathlike): """ Parse a JSON file after removing any comments. Comments can use either ``//`` for single-line comments or or ``/* ... */`` for multi-line comments. The input filepath can be a string or ``pathlib.Path``. Parameters ---------- filename : str o...
386
def main(): """ Main entry point """ parser = argparse.ArgumentParser() parser.add_argument("-b", "--betatest", dest="betatest", action="store_true", help="If used, then do not update the symlinks with this version's entry points") parser.add_argument("--python", dest="python...
387
def _unpack_available_edges(avail, weight=None, G=None): """Helper to separate avail into edges and corresponding weights""" if weight is None: weight = "weight" if isinstance(avail, dict): avail_uv = list(avail.keys()) avail_w = list(avail.values()) else: def _try_getit...
388
def triple_str_to_dict(clause): """ converts a triple (for a where_clause) in the form <<#subj, pred_text, #obj/obj_text>> to dictionary form. it assumed that one of the three entries is replaced by a "?" if the obj memid is fixed (as opposed to the obj_text), use a "#" in front of the memid...
389
def test_check_auth(session): # pylint:disable=unused-argument """Assert that check_auth is working as expected.""" user = factory_user_model() org = factory_org_model() factory_membership_model(user.id, org.id) entity = factory_entity_model() factory_affiliation_model(entity.id, org.id) #...
390
def test_add_edge_1(): """ Test normal usage. """ gfa_graph = mod.GFAGraph() gfa_graph.add_node('node1', 4, 'ACTG', tags={}, labels={}) gfa_graph.add_node('node2', 1000, '*', tags={}, labels={}) edge_name = 'edge1' source, source_orient = 'node1', '+' sink, sink_orient = 'node2', ...
391
def reddit_data(subreddit, time_request = -9999): """ @brief function to retrieve the metadata of a gutenberg book given its ID :param subreddit: the name of the subreddit :param time_request: unix timestamp of when requested subreddit was generated :return: a list of reddit objects with the data of...
392
def main(): """ COMMANDS MANAGER / SWITCH PANEL """ args: dict = demisto.args() params: dict = demisto.params() self_deployed: bool = params.get('self_deployed', False) tenant_id: str = params.get('tenant_id', '') auth_and_token_url: str = params.get('auth_id', '') enc_key: str = params.get(...
393
def rename_var(fname): """ Rename defined variables in HDF5 file. """ with h5py.File(fname) as f: f['bs'] = f['bs_ice1'] f['lew'] = f['lew_ice2'] f['tes'] = f['tes_ice2'] del f['bs_ice1'] del f['lew_ice2'] del f['tes_ice2']
394
def write_velocity_files(U_25_RHS_str, U_50_RHS_str, U_100_RHS_str, U_125_RHS_str, U_150_RHS_str, U_25_LHS_str, U_50_LHS_str, U_100_LHS_str, U_125_LHS_str, U_150_LHS_str, path_0_100, path_0_125, path_0_150, path_0_25, path_0_50): """Create the details file for the surrounding cases, and write the velocities in lin...
395
def traceback_to_server(client): """ Send all traceback children of Exception to sentry """ def excepthook(exctype, value, traceback): if issubclass(exctype, Exception): client.captureException(exc_info=(exctype, value, traceback)) sys.__excepthook__(exctype, value, trac...
396
def _verify_input_args(x, y, input_fn, feed_fn, batch_size): """Verifies validity of co-existance of input arguments.""" if input_fn is None: if x is None: raise ValueError('Either x or input_fn must be provided.') if contrib_framework.is_tensor(x) or (y is not None and ...
397
def datetime_to_bytes(value): """Return bytes representing UTC time in microseconds.""" return pack('>Q', int(value.timestamp() * 1e6))
398
def test_tfenv_run_no_version_file( cd_tmp_path: Path, caplog: LogCaptureFixture ) -> None: """Test ``runway tfenv run -- --help`` no version file.""" caplog.set_level(logging.ERROR, logger="runway") runner = CliRunner() result = runner.invoke(cli, ["tfenv", "run", "--", "--help"]) assert result...
399