content
stringlengths
22
815k
id
int64
0
4.91M
def get_all(log): """get all documents""" return log.all()
72,400
def train(): """ Takes No Parameter trains the LUIS Model """ print "Training the LUIS Model" try: conn = httplib.HTTPSConnection("api.projectoxford.ai") conn.request("POST", "/luis/v1.0/prog/apps/{0}/train".format(configData["appID"]), None, headers)...
72,401
def lag_to_z(x,lag,xunit='ang',avgbad=True): """ this converts an integer pixel lag for a given x-axis into a redshift currently the only supported unit for the x-axis is angstroms avgbad replaces undeterminable velocities with the average of the others, else they are set to 0 ""...
72,402
def trainA3C(file_name="A3C", env=GridworldEnv(1), update_global_iter=10, gamma=0.999, is_plot=False, num_episodes=500, max_num_steps_per_episode=1000, learning_rate=0.0001 ): """ A3C training routine. Retuns rewards and durations logs. Plot environment screen """ ns = env....
72,403
def search_artist(query): """Search artists by query. Returns an ArtistSearch object. Use get_next_page() to retrieve sequences of results.""" return ArtistSearch(query)
72,404
def key_expansion(k): """AES key expansion for 128/256-bit keys.""" w = list(map(list, zip(*k))) Nk = len(w) # Nk is 4 or 8 Nr = 10 if Nk == 4 else 14 for i in range(Nk, 4 * (Nr + 1)): t = w[-1] if i % Nk in {0, 4}: t = [sbox(x) for x in t] if i % Nk == 0: ...
72,405
def _find_tcl_tk_dir(): """ Get a platform-agnostic 2-tuple of the absolute paths of the top-level external data directories for both Tcl and Tk, respectively. Returns ------- list 2-tuple that contains the values of `${TCL_LIBRARY}` and `${TK_LIBRARY}`, respectively. """ # Pyth...
72,406
def test_config_downgrade(run_cli_command, config_with_profile_factory): """Test `verdi config downgrade`""" config_with_profile_factory() options = ['config', 'downgrade', '1'] result = run_cli_command(cmd_verdi.verdi, options) assert 'Success: Downgraded' in result.output.strip()
72,407
def process_invitation_response(request, invitation_response_formset): """ Process an invitation response. Helper function to view: project_home """ user = request.user invitation_id = int(request.POST['invitation_response']) for invitation_response_form in invitation_response_formset: ...
72,408
def addParams(params, subparser): """Add params to the given subparser""" if (params is not None): for param in params: flags = ["--{}".format(param.name)] if (param.alt is not None): flags.append("-{}".format(param.alt)) if param.choices: ...
72,409
def getShaders(objects): """ DEPRECATED, use getMaterials(objects) instead """ return getMaterials(objects)
72,410
def upsample(x, factor): """Reverse decimation by polyphase upsampling by the given (integer) factor""" return scipy.signal.resample_poly(x, factor, 1)
72,411
def process_is_crawler(pid): """This is really checking if proc is the current process. """ try: pid = int(pid) except ValueError: raise TypeError('pid has to be an integer') try: proc = psutil.Process(pid) cmdline = (proc.cmdline() if hasattr(proc.cmdline, '__call__...
72,412
def _load_local_tzinfo(): """Load zoneinfo from local disk.""" tzdir = os.environ.get("TZDIR", "/usr/share/zoneinfo/posix") localtzdata = {} for dirpath, _, filenames in os.walk(tzdir): for filename in filenames: filepath = os.path.join(dirpath, filename) name = os.path.relpath(filepath, tzdir)...
72,413
def balance_conversion_plus_primary_constraint_rule( backend_model, node, tech, timestep ): """ Balance energy carrier consumption and production for carrier_in and carrier_out .. container:: scrolling-wrapper .. math:: \\sum_{loc::tech::carrier \\in loc::tech::carriers_{out}} ...
72,414
def create_objectness_label(anchor_center, resolution=0.5, x=90, y=100, z=10, scale=4): """Create Objectness label""" print(type(x[1] - x[0])) obj_maps = np.zeros((int((x[1] - x[0]) / (resolution * scale)), int((y[1] - y[0]) / (resolution * scale)), ...
72,415
def weighted_rating(clean_anime, quantile, mean): """ :var term: gets the total users who rated each anime. """ term = clean_anime['members'] / (quantile + clean_anime['members']) return clean_anime['rating'] * term + (1 - term) * mean
72,416
def cmd_train(context): """Main command do train the network. :param context: this is a dictionary with all data from the configuration file: - 'command': run the specified command (e.g. train, test) - 'gpu': ID of the used GPU ...
72,417
def create_file_if_not_exists( file_path: str, file_contents: str = "{}" ) -> None: """Creates file if it does not exist. Args: file_path: Local path in filesystem. file_contents: Contents of file. """ # if not fileio.exists(file_path): # fileio.(file_path, file_contents) ...
72,418
def start_omniboard(experiment_name): """ 1) creates an omniboard directory, if it doesnt exist, to hold a DB config file. 2) Sets OMNIBOARD_CONFIG environment to be able to find the the config file. 3) Starts omniboard 4) resets OMNIBOARD_CONFIG """ if state.verbose: logger.info("...
72,419
def tree(directoryPathlib): """ Parâmetro: params directoryPathlib: (pathlib.Path()) O próximo exemplo define uma função, tree() que imprimirá uma árvore visual representando a hierarquia de arquivos, com raiz em um determinado diretório. Aqui, queremos list...
72,420
def test_pick_channels_mixin(): """Test channel-picking functionality """ evoked = read_evokeds(fname, condition=0, proj=True) ch_names = evoked.ch_names[:3] ch_names_orig = evoked.ch_names dummy = evoked.pick_channels(ch_names, copy=True) assert_equal(ch_names, dummy.ch_names) assert_e...
72,421
def mjd2doyyr(mjd): """ Convert mjd to (decimal) day-of-year and year Mathew Owens, 16/10/20 """ #convert to datetime and extract the necessary info dt=mjd2datetime(mjd) year=np.vectorize(lambda x: x.year)(dt) year=year.astype(int) doy=np.vectorize(lambda x: x.timetuple().tm_yday...
72,422
def test_includeinpanel___process(): """ Make sure includeInPanel column is propogated and intergenic region is captured """ expected_beddf = pd.DataFrame(dict( Chromosome=['2', '9', '12', '19'], Start_Position=[69688432, 1111, 53700240, 44080953], End_Position=[69689532, 11...
72,423
def test_atomic_id_max_length_nistxml_sv_iv_atomic_id_max_length_1_3(mode, save_output, output_format): """ Type atomic/ID is restricted by facet maxLength with value 1. """ assert_bindings( schema="nistData/atomic/ID/Schema+Instance/NISTSchema-SV-IV-atomic-ID-maxLength-1.xsd", instance=...
72,424
def execute(*cmd): """ Execute command. Returns output and error. Raises CommandException on error """ with subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) as proc: ou...
72,425
def git_fetch(path='', output=False, debug=False, timeout=None, exception=True, show=False): """Perform `git fetch --all --prune` - path: path to git repo, if not using current working directory - output: if True, return output of `git fetch --all --prune` - debug: if True, insert breakpo...
72,426
def parse_markdown_to_structure(markdown, replacements): """Convert a parsed Markdown document into a folder structure""" file_contents, file_replacements = process_markdown_definitions( markdown, replacements ) replaced_file_contents = replace_file_contents( replacements, file_contents...
72,427
def map_remove_by_rank_range(bin_name, rank_start, remove_amt, return_type, inverted=False): """Creates a map_remove_by_rank_range operation to be used with operate or operate_ordered The operation removes `remove_amt` items beginning with the item with the specified rank from the map. Args: bin_n...
72,428
def export_view_json(request): """ Custom view function to export full results for this game as JSON file """ def create_odict_from_object(obj, fieldnames): """ Small helper function to create an OrderedDict from an object <obj> using <fieldnames> as attributes. ...
72,429
def _parse_sklearn_api(topology, model, inputs): """ This is a delegate function adding the model to the input topology. It does nothing but invokes the correct parsing function according to the input model's type. Args: topology: The ``hummingbitd.ml._topology.Topology`` object where the model...
72,430
def verify_mr_information( pulled_mrs: int, project_id: int, snowflake_engine: Engine, start: str, end: str ) -> None: """ Gets number of MRs present from gitlab_db for the same timeframe. If that number doesn't match the number passed in, a warning is logged. """ count_query = f""" SELE...
72,431
def test_detect_nan(): """ Test the code snippet example that detects NaN values. """ nan_detected = [False] def detect_nan(i, node, fn): for output in fn.outputs: if numpy.isnan(output[0]).any(): print '*** NaN detected ***' theano.printing.debug...
72,432
def get_image_stream(stream, class_mapping_dict, ip, port, model_name, thresh): """Function that gets the image stream with bounding box information Arguments: stream (iterable): input image image stream class_mapping_dict (dict): with key as int and value as class name ip (str): tensor...
72,433
def even_value_doubler(array_to_double = [1,2,3,5,6,7,9,10,12]): """ This function allegedly takes an list array of numbers and doubles the value of every even value in the list. """ length = len(array_to_double) for i in range(0, length): if arr[i] % 2 == 0: arr[i] *= 2 return arr
72,434
def _print_card(card: Any) -> str: """helper for ``_validate_msg``""" try: return card.write_card(size=8) except RuntimeError: return ''
72,435
def untar(tarfile, outdir): """Returns True if untar content differs from pre-existing outdir content.""" tmpdir = tempfile.mkdtemp() try: untared = _open_archive(tarfile, tmpdir) files = [f for f in untared if os.path.isfile(os.path.join(tmpdir, f))] dirs = [d for d in untared if os.path.isdir(os.pat...
72,436
def getImageHash(img): """ Calculates md5 hash for a given Pillow image. """ md5hash = hashlib.md5(img.tobytes()) return md5hash.hexdigest()
72,437
def fssurf_to_gifti(surf, fn=None): """ Converts FreeSurfer `surf` surface file to GIFTI format Parameters ---------- obj : str or os.PathLike FreeSurfer surface file to be converted fn : str or os.PathLike, None Output filename. If not supplied uses input `surf` filename (with ...
72,438
def dihedral_ranking_score(structure, residues, sec_struct_column="sec_struct_3state", original=True): """ Assess quality of structure model by twist of predicted alpha-helices and beta-sheets. This function re-implements the functionality of make_alpha_beta_score_table....
72,439
def kernel(request): """Console kernel fixture""" # Get kernel instance kernel = get_kernel() kernel.namespace_view_settings = {'check_all': False, 'exclude_private': True, 'exclude_uppercase': True, ...
72,440
def character_replacement(s: str, k: int) -> int: """https://leetcode.com/problems/longest-repeating-character-replacement""" counter = Counter() left = 0 max_length = 0 current_max_frequency = 0 for right, char in enumerate(s): counter[char] += 1 current_max_frequency = max(cur...
72,441
def build_sampler(tparams, options, use_noise, trng, sampling=True): """ Builds a sampler used for generating from the model Parameters ---------- See build_model function above Returns ------- f_init : theano function Input: annotation, Output: initial lstm state and memory ...
72,442
def test_dist_agg(pipeline, clean_db): """ Test dist_agg, dist_merge_agg, dist_cdf, dist_quantile """ q = """ SELECT k::integer, dist_agg(x::int) AS t FROM test_tdigest_stream GROUP BY k """ desc = ('k', 'x') pipeline.create_stream('test_tdigest_stream', k='int', x='int') pipeline.create_cv('test_td...
72,443
def check_image_labels(dirname, prm=DATASET_INFO): """Create/Check that ESP-Game labels are in HDF5 format Note ---- Be careful launching multiple-process dumping source files """ filename = os.path.join(dirname, 'label_train.h5') if not os.path.isfile(filename): ds.espgame_dump_la...
72,444
def text_match(vobject_item, filter_, child_name, ns, attrib_name=None): """Check whether the ``item`` matches the text-match ``filter_``. See rfc4791-9.7.5. """ # TODO: collations are not supported, but the default ones needed # for DAV servers are actually pretty useless. Texts are lowered to ...
72,445
def generate_tag_version(): """ Generates a new unique identifier for tag version.""" hash_value = hashlib.md5("{0}{1}{2}".format( randrange(0, MAX_TAG_KEY), get_thread_id(), time.time() ).encode('utf8')).hexdigest() return hash_value
72,446
def new_session(session): """ Create a new tmux session""" sessions = connections.check_output_as_list('tmux list-sessions -F "#S"') if session in sessions: print("Session '{}' already exists!".format(session)) sys.exit(posix.EX_USAGE) command = "tmux new-session -d -s '{}'".format(sess...
72,447
def _stem_words_list(list_words): """Stem words using a nltk stemmer :param list_words: A list of strings representing words to stem :rtype: A list of strings representing stemmed words """ stemmer = snowball.SnowballStemmer('english') list_words_stemmed = {_stem(stemmer, word) for word in list...
72,448
def read_data(location, type): """ This helps us read various filetypes directly into pyspark datframes. This is an allround solution. """ ftype = { 'avro' : "com.databricks.spark.avro", 'parquet' : "parquet", 'csv' : "com.databricks.spark.csv", 'json' : "json" } ...
72,449
def get_app_user_assignments(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppUserAssignmentsResult: """ Use this data source to retrieve the list of users assigned to the given Okta application (by ID). ## Example Usage ```python ...
72,450
def clean_hotel_location(string): """ """ if string is not None: r = HTMLParser.HTMLParser().unescape(string) r = commons.limpieza_barras_por_espacios(r) if r.find('(') >= 0: r = r[:r.find('(')] if r.find('&bull;') >= 0: r = r[:r.find('&bull;')] if r.find('Chatl') >= 0: r='El Chalten' r=decutf_...
72,451
def from_shapely(data): """Converts shapely based data formats to spatialpandas.GeoDataFrame. Args: data: A list of shapely objects or dictionaries containing shapely objects Returns: A GeoDataFrame containing the shapely geometry data. """ from spatialpandas import ...
72,452
def handle(req): """handle a request to the function Args: req (str): request body """ ret_str = 'Hello OpenFaas. I received the following text:\n' return ret_str + req
72,453
def rlmErr(ols, w, spDcache): """ Robust LM error test. Implemented as presented in eq. (8) of Anselin et al. (1996) [Anselin1996a]_ NOTE: eq. (8) has an errata, the power -1 in the denominator should be inside the square bracket. ... Attributes ---------- ols : OLS_dev ...
72,454
def max_ts(timeseries, nodata=-9999): """Maximum value of the time series. :param timeseries: Time series. :type timeseries: numpy.ndarray :param nodata: nodata of the time series. Default is -9999. :type nodata: int :returns: Maximum value of time series. """ ts = fixseries(timeserie...
72,455
async def on_prepare(msg): """ 直播结束时触发此方法,结束录制 :param msg: 事件内容 :return: None """ log.info("********************【直播结束】********************") monitor.isStreaming = False # 结束录制线程 recorder_thread.stop()
72,456
def get_hole_declarations(program_vars): """Helper function for creating hole declaration with a grammar blow.""" grammar_spec = """ ( (Start Int ( (Variable Int) (+ Start Start) )) ) """ grammar = templates.load_gramar_from_SYGUS_spec(grammar_spec...
72,457
def unit_scalar_to_str(value, n_digits=6): """ Convert a UnitScalar to a string representation to display in text box. """ dimless_labels = [None, 'dimensionless', '1'] if value is None: return "" elif isinstance(value, UnitScalar): number = value.tolist() if isinstance(numbe...
72,458
def test_gmtime_epoch(): """Test that time.gmtime() is based upon the UNIX epoch.""" epoch_st = time.struct_time([1970, 1, 1, 0, 0, 0, 3, 1, 0]) st = time.gmtime(0) assert st == epoch_st
72,459
def dump_db(session): # pragma: no cover """ Purely debug function, shunts db contents into file for examination. """ fname = os.path.join(tempfile.gettempdir(), 'dbdump_' + os.environ.get('COG_TOKEN', 'dev')) print("Dumping db contents to:", fname) with open(fname, 'w') as fout: for cl...
72,460
def find_paths(iterable, searchfor, max_=0, searchtype='key', **kwargs): """Returns paths to 'searchfor'. If 'max_' is 0 all matches will be found""" return objects.FindPath(iterable, searchfor, max_, searchtype, **kwargs).paths
72,461
def process_overlap_files(inputfiles, header): """ :param inputfiles: :param header: :return: """ cage_cov = {'+': dict(), '-': dict()} feat_count = col.Counter() skip_partial = 0 for inpf in inputfiles: with open(inpf, 'r', newline='') as infile: rows = csv.DictR...
72,462
def where(cond, true_vals, false_vals=None): """ Use `true_vals` where `cond` is True, `false_vals` where `cond` is False to build a merged dataset. The result will be empty where `cond` is empty. `false_vals` are optional and if not provided, this will behave nearly the same as `true_vals.filter(c...
72,463
def create_ssl_context(verify=True, cafile=None, capath=None): """Set up the SSL context. """ # This is somewhat tricky to do it right and still keep it # compatible across various Python versions. try: # The easiest and most secure way. # Requires either Python 2.7.9 or 3.4...
72,464
def extract_domain(url): """Extract domain name from URL string""" o = urlparse(url) if o.scheme == '' and o.netloc == '': o = urlparse("//" + url.lstrip("/")) return o.netloc
72,465
def diamond_graph(create_using=None): """Return the Diamond graph. """ description=[ "adjacencylist", "Diamond Graph", 4, [[2,3],[1,3,4],[1,2,4],[2,3]] ] G=make_small_undirected_graph(description, create_using) return G
72,466
def tensor_setitem_by_tuple_with_tensor(data, tuple_index, value): """Assigns the tensor by tuple with tensor value.""" op_name = const_utils.TENSOR_SETITEM tuple_index = _transform_ellipsis_to_slice(data, tuple_index, op_name) tuple_index, not_expanded_dim = remove_expanded_dims(tuple_index, F.shape(da...
72,467
def test_query_ksm_balances(rotkehlchen_api_server): """Test query the KSM balances when multiple accounts are set up works as expected. """ async_query = random.choice([False, True]) setup = setup_balances( rotki=rotkehlchen_api_server.rest_api.rotkehlchen, ethereum_accounts=None, ...
72,468
def arpls(y, lam, ratio=1e-6, niter=1000, progressCallback=None): """ Return the baseline computed by asymmetric reweighted penalized least squares smoothing, arPLS. Ref: Baseline correction using asymmetrically reweighted penalized least squares smoothing Sung-June Baek, Aaron Park, Young-Jin Ahn a...
72,469
def compressnumbers(s): """Take a string that's got a lot of numbers and try to make something that represents that number. Tries to make unique strings from things like usb-0000:00:14.0-2 """ n = '' currentnum = '' for i in s: if i in '0123456789': #Exclude...
72,470
def test_get_image_link_re(): """get_image_link_re""" re_link = get_image_link_re() all_links = re_link.findall(text) assert len(all_links) == 6 fn = "output.jpg" re_link = get_image_link_re(fn) res = re_link.finditer(text) assert len(list(res)) == 2 res = re_link.finditer(text) ...
72,471
def test_message_silent(capsys): """ Test sending message with silent flag """ script = Script() message = 'Test message with silent flag' script.__silent__ = True script.message(message) captured = capsys.readouterr() assert captured.err == ''
72,472
async def plot_index_bar_chart(tag_dict): """ Plots the index bar chart. """ x = np.array(list(tag_dict.keys())) y = np.array(list(tag_dict.values())) plt.clf() plt.bar(x, y, color="green") plt.xticks(fontsize=7) plt.xlabel("Index", fontsize=7) plt.ylabel("Number", fontsize=7) ...
72,473
def cli_id_contigs( sep, genbank_id_map, seq_fasta, min_homology, min_alignment_len, m8file, outfile): """ID contigs based on the species that have the most homology to each.""" click.echo('Identifying Contigs') tbl = assign_contigs( m8file, genfile=genbank_id_map, se...
72,474
def test_splunk_app_cim_fiction(testdir): """Make sure that pytest accepts our fixture.""" testdir.makepyfile( """ from pytest_splunk_addon.standard_lib.addon_basic import Basic class Test_App(Basic): def empty_method(): pass """ ) shutil.copytr...
72,475
def _get_tile_output_shape(shape, multiples): """compute output shape of tile""" if multiples is None: return shape if not isinstance(shape, (list, tuple)): raise TypeError("Input shape of Tile must be of type list or tuple") if not isinstance(multiples, (list, tuple)): raise Ty...
72,476
def get_clinical_strat(params: Parameters, stratified_adjusters: Dict[str, Dict[str, float]]) -> Stratification: """ Stratify the infectious compartments of the covid model by "clinical" status, into the following five groups: NON_SYMPT = "non_sympt" Asymptomatic persons SYMPT_NON_H...
72,477
def service_is_ready(): """ Used to show the "Haystack is loading..." message """ url = API_QUERY_ENDPOINT try: if requests.get(url).status_code < 400: return True except Exception as e: logging.exception(e) sleep(2) # To avoid spamming a non-existing endpoin...
72,478
def medianfilt(img, kernel_shape): """[summary] Aplies a median filter to an image, but adds the necessary padding to mantain the aspect ratio. Args: img (numpy array): Image array. kernel_shape (tuple): Tuple indicating kernel shape. Returns: output (numpy array): processed...
72,479
def cik(apikey: str, cik_id: str) -> typing.List[typing.Dict]: """ Query FMP /cik/ API. FORM 13F get company name by cik :param apikey: Your API key. :param cik_id: CIK value :return: A list of dictionaries. """ path = f"cik/{cik_id}" query_vars = {"apikey": apikey} return __ret...
72,480
def trim(fn, grn=5, path=""): """ function: Put the trimmed photos into result dir :param path: The directory to save the result :param fn: file name :param grn: The graininess of trimmer. range is (0, 5), the graininess larger, the trimmed photos larger(Maybe). :return: No return. But pri...
72,481
def dec_indicator(encoded): """decode a Fudge Indicator. Returns: A Singleton INDICATOR object""" return INDICATOR
72,482
def parse(path): """Parse a config file for running a model. Arguments --------- path : str Path to the YAML-formatted config file to parse. Returns ------- config : dict A `dict` containing the information from the config file at `path`. """ with open(path, 'r') a...
72,483
def main(): """Coin changer puzzle for junior interview candidates, in Python 3. Generates the optimal set of change for a given sum of money, using the obvious "greedy algorithm". This only works, in terms of producing optimal results, for "canonical" coin systems where each coin is at least doubl...
72,484
def unordered_inverse(matrix): """ Takes in a matrix of values and maps each distinct row to a unique value ex [[1 2 3] becomes [1,2,1] [4 5 6] [1 2 3]] """ num_rows = matrix.shape[0] result = np.zeros((num_rows,)) state_map = dict() state_count = 0 for index,row in enumerate(matrix): row = row....
72,485
def _build_predict_signature(input_tensor, output_tensor_x, output_tensor_y): """Helper function for building a predict SignatureDef.""" input_tensor_info = tf.saved_model.utils.build_tensor_info(input_tensor) signature_inputs = {"input": input_tensor_info} output_tensor_info_x = tf.saved_model.utils.build_ten...
72,486
def filter_error_nodes(nodes): """Filter out ERROR nodes from the given node list. :param nodes: candidate nodes for filter. :return: a tuple containing the chosen nodes' IDs and the undecided (good) nodes. """ good = [] bad = [] not_created = [] for n in nodes: if ...
72,487
def pad_sequences(x, n_padded, center_padded=True): """TODO(rpeloff) return the padded sequences and their original lengths.""" padded_x = np.zeros((len(x), n_padded, x[0].shape[1]), dtype=_globals.NP_FLOAT) lengths = [] for i_data, cur_x in enumerate(x): length = cur_x.shape[0] if cente...
72,488
def ds_cnn_params(): """Parameters for toy "depthwise convolutional neural network" stride model.""" params = Params() params.model_name = 'ds_cnn' params.cnn1_kernel_size = '(3,2)' params.cnn1_dilation_rate = '(1,1)' params.cnn1_strides = '(2,1)' params.cnn1_padding = 'same' params.cnn1_filters = 4 p...
72,489
def LoadVNSIM(nsim_csv): """Returns dictionary with degraded file key and mean nsim value. The CSV should have three values: reference path, degraded path, nsim value Args: nsim_csv: Path to CSV file with NSIM values, format described above. Returns: Dictionary with degraded file key and NSIM value. ...
72,490
def getCharOverlapCount(from1, to1, from2, to2): """Calculates the number of overlapping characters of the two given areas.""" #order such that from1 is always prior from2 if from1 > from2: tmp = from1 from1 = from2 from2 = tmp tmp = to1 to1 = to2 t...
72,491
def getPressure(): """ Method to get the angular position of the rocket. This method is only activated when the route /getAng is accessed. Data collected here is to be directly displayed as numbers on ReactApp. """ pressure = {'PTop':PT1,'PBottom':PT2,'P3':PT3} f = open("./AvionicsData/pressure.txt","a+") f...
72,492
def test_malformed_fasta(): """ Test if output is correct with mal-formed input. """ MALFORMED_FASTA = f"{FASTA_FILE}.malformed.fasta" CONVERTED_FASTA = f"{FASTA_FILE}.malformed-test.fasta" with open(FASTA_FILE, "r") as f_in, open(MALFORMED_FASTA, "w") as f_out: f_out.write(f_in...
72,493
def pg_notify(dburi_or_sqlaengine_or_dbapiconnection, channel, payload): """Send PostgreSQL notifications to channel with a payload""" connection = get_dbapi_connection(dburi_or_sqlaengine_or_dbapiconnection) try: with connection: with connection.cursor() as cursor: curso...
72,494
def label_color(label): """ Return a color from a set of predefined colors. Contains 80 colors in total. Args label: The label to get the color for. Returns A list of three values representing a RGB color. If no color is defined for a certain label, the color green is returned and...
72,495
def file_path(cfg): """ Return the directory containing the description files as an absolute path. Returns None if the configuration does not define this. """ try: desc_path = Path(cfg['descriptions_dir']) except KeyError: raise ConfigKeyMissingError('description_dir') # if...
72,496
def rename_to_text(file_path): """ Appends a .txt to all files run since some output files do not have an extension :param file_path: input file path :return: .txt appended to end of file name """ import os file = file_path.split('/')[-1] if file.endswith('.txt') is False: new_f...
72,497
def angle_average(galactic_frame_func): """ @returns Angle-averaged function """ @np.vectorize def angle_averaged(v_galactic_frame): """ @returns Angle-averaged evaluation of function """ v = v_galactic_frame * np.ones_like(COS_THETA) integrand = galactic_fram...
72,498
def _kkr2cif(structure, lattice="direct", fmt="cif", outputfilename="structure.cif", include_Vc=True): """make a cif file. if outputfilename == None, print to stdout Args: struc (Structure): pymatgen.core.Structure lattice (str, optional): lattice conversion. Defaults to "dire...
72,499