content
stringlengths
22
815k
id
int64
0
4.91M
def test_simple(): # type: () -> None """Simplest output.""" assert efm8.to_frames([0], False, False) == [ [36, 4, 49, 165, 241, 0], [36, 4, 50, 0, 0, 255], [36, 4, 51, 0, 0, 0], ]
76,800
def oval_entity_is_extvar(elem): """Check if OVAL entity represented by XML element is OVAL <external_variable> element Return: True if <external_variable>, False otherwise""" return elem.tag == '{%s}external_variable' % oval_ns
76,801
def dispatch_file(file: File): """ Dispatch file by extension. """ if file.extension in ["jpg", "png", "svg", "gif"]: return _prepare_image(file) return """ <div class='panel panel-default'> <div class='panel-body'> <p>{}</p> <a class='btn...
76,802
def next_day(date, dayOfWeek): """ :rtype: Column >>> from pysparkling import Context, Row >>> from pysparkling.sql.session import SparkSession >>> spark = SparkSession(Context()) >>> spark.range(1, 10).select(next_day(concat(lit("2019-11-0"), col("id")), "Mon")).show() +-------------------...
76,803
def test_lv_present_with_same_size(lv01): """ Test to specify the same volume size as parameter """ name = "testlv01" vgname = "testvg01" comt = "Logical Volume {} already present".format(name) ret = {"name": name, "changes": {}, "result": True, "comment": comt} mock = MagicMock(return_...
76,804
def save_pyobj(filename, pyobj): """save pyobj""" mkfilepath(filename) the_s = pprint.pformat(pyobj, indent=2, width=120, compact=True) with open(filename, 'w', encoding='utf8') as fid: fid.write(the_s)
76,805
def check_sqlalchemy_results_are_equal(results1, results2): """Compare two lists of SQLAlchemy results to see if they are equal""" list1 = [sqlalchemy_obj_to_dict(item) for item in results1] list2 = [sqlalchemy_obj_to_dict(item) for item in results2] return list1 == list2
76,806
def dp_longest_palindrome(dp, S, i, j): """ Recursive function for finding the longest palindromic subsequence from a string using a modified version of the algorithm above """ if i == j: return S[i] if (i, j) in dp: return dp[(i, j)] if S[i] == S[j]: if i + 1 == j: dp[([i, j])] = 2 *...
76,807
def prediction_measurement_significance(measurement, \ measurement_statistical_error, \ measurement_systematic_error, \ prediction, \ prediction_statistical_err...
76,808
def queues(ctx): """List all available queues""" click.echo( "{0:25} | {1:^15} | {2:^15} | {3:^15} | {4:^15} | {5:^15}".format( "Queue Name", "Node Max Task", "Node Max Thread", "Node Max Memory", "Max Task", "Available Task", ...
76,809
def add(x, y): """ add :param x: :param y: :return: """ return x + y
76,810
def index(): """ Get the index page """ return render_template("index.html"), 200
76,811
def delivery_report(err, msg): """ Reports the failure or success of a message delivery. Args: err (KafkaError): The error that occurred on None on success. msg (Message): The message that was produced or failed. Note: In the delivery report callback the Message.key() and Message.value() ...
76,812
def generate_xml(target_dir, image_name, image_width, image_height, detections): """ generate xml file Args: target_dir (str): target xml dir image_name (str): the name of image image_width (int): the width of image image_height (int): the height of image det...
76,813
def extract_structure_from_csv(csv_file): """ Load csv file that contains folder structure information and return it as pandas.datafram. Parameters ---------- csv_file: str The file to be loaded. Returns ------- pandas.dataframe A dataframe containing the essential ...
76,814
def createadmin(): """Create a admin, requires username, email and password.""" db.create_tables() username = prompt('admin username') email = prompt('admin email') confirm_email = prompt('confirm admin email') if not EMAIL_REGEX.match(email): sys.exit('\n kindly provide a valid email a...
76,815
def get_available_devices(): """Return CPU and, if present, GPU device. Returns: [torch.device]: Available devices for `torch`. """ devices = [torch.device("cpu")] if torch.cuda.is_available(): devices.append(torch.device("cuda")) return devices
76,816
def file_exist(file_path): """check file is exist :type file_path: file abs path :return bool file not exist return False else return True """ count = 0 while 1: if os.path.exists(file_path): return True if count >= 300: return False count += 1 ...
76,817
def disruptive_uniform_crossover(dna1, dna2): """disruptive uniform crossover uniformly crossover genes between dna1 and dna2, with children guaranteed to be different from parents, if the number of differences between parents is larger than 1 """ differences = sum(1 for i, j in zip(dna1, dna2)...
76,818
def main(): """ Generate the files """ portability_metrics = get_flow_graph(limit=1000, period=86400) # generate TSV files with open('output/portability_metrics.tsv', 'wt') as handler: handler.write('# Portability metrics\n') handler.writelines(format_tsv_lines(portability_metri...
76,819
def getSplicingEntropy(gene_data): """ Calculates splicing entropy and frequency for a given gene Arguments: tp_data = DataFrame of splicing mutations in given gene Returns: splicingEntropy fi = highest splicing entropy """ sp_data = getSplicingData(gene_data) [splic...
76,820
def download_data(file_type="mongodb"): """ Fetch data from Openfoodfacts server. Options mongodb, csv, rdf. The file is downloded in the current directory. """ if file_type not in FILE_TYPE_MAP: raise ValueError("File type not recognized!") filename = FILE_TYPE_MAP[file_type] file...
76,821
def _run_fabric(data): """ Runs fabric commands on a 'remote' host. """ host = data.get('host') if not host: app.app.logger.warning("No 'host' specified in request") data['status'] = 'failed' data['warnings'] = "No 'host' specified in request" return False data[...
76,822
def getbitlen(bint): """ Returns the number of bits encoding an integer """ return bint.bit_length()
76,823
def test_load_auth_with_invalid_auth(cloud_hass, mock_read, mock_cognito): """Test calling load_auth when auth is no longer valid.""" mock_cognito.get_user.side_effect = aws_error('SomeError') auth = auth_api.load_auth(cloud_hass) assert auth.cognito is None
76,824
async def remove_org_user(root: Root, org_name: str, user_name: str) -> None: """ Remove user access from the org. """ await root.client._admin.delete_org_user(org_name, user_name) if not root.quiet: root.print( f"Removed [bold]{rich_escape(user_name)}[/bold] from org " ...
76,825
def test_lfw_no_shuffle(): """ Feature: LFW Description: test dataset of LFW Expectation: the dataset is as expected """ logger.info("Test Case noShuffle") # define parameters. repeat_count = 2 # apply dataset operations. data1 = ds.LFWDataset(DATA_DIR, shuffle=False) data1 ...
76,826
def lookstr(table, limit=0, **kwargs): """Like :func:`petl.util.vis.look` but use str() rather than repr() for data values. """ kwargs['vrepr'] = str return look(table, limit=limit, **kwargs)
76,827
def do_breaks(probes, segments, min_probes=1): """List the targeted genes in which a copy number breakpoint occurs.""" intervals = get_gene_intervals(probes) bpoints = get_breakpoints(intervals, segments, min_probes) return pd.DataFrame.from_records(bpoints, columns=...
76,828
def convert_dcc_translation(translation): """ Converts given tpDcc translation into a translation that DCC can manage NOTE: tpDcc uses Y up coordinate axes as the base reference axis :param translation: list(float, float, float) :return: list(float, float, float) """ if get_up_axis_name().l...
76,829
def parse_log(log_line, watch_duration=10): """Parse a log line and extract interesting sections :param str log_line: W3C formated log line :param int watch_duration: Watch duration in seconds :return: Log fields as :class:`dict` """ logger.debug("Line: {}".format(log_line[0:-1])) match = p...
76,830
def test_parse_kpoints_mesh(kpoints_parser): """Load a reference KPOINTS parser. We check that it parses and provides the correct content for mesh mode. """ # The kpoints for KPOINTS parser should have the key `kpoints-kpoints` result = kpoints_parser.get_quantity('kpoints-kpoints') result_re...
76,831
def fetch_filenames(filenames: Union[List[str], str], data_home=None) -> List[str]: """ Fetch images fully qualified filenames for given filenames or direcoty name. Parameters ---------- filenames A list of image names or, a single image file name or, a directory nam...
76,832
def rex_stacks(rex_dir, chisq, internal, thesis, png, n_test): """Generate plots from TRExFitter result.""" import tdub.rex import tdub.config outdir = PosixPath(rex_dir) / "matplotlib" outdir.mkdir(exist_ok=True) tdub.config.init_meta_table() tdub.config.init_meta_logy() if thesis: ...
76,833
def flatten(stan, ctx=None): """Given the stan and the optional context, return a string containing the representation of the tree in the given context. """ if ctx is None: from nevow.context import RequestContext, PageContext from nevow.testutil import FakeRequest ctx = PageCont...
76,834
def tenant_is_valid(request): """Function will return either True or False depending if a subdomain exists or not.""" return JsonResponse({ 'access-granted':True })
76,835
def fp_type02_1(cxt: DecoderContext, fmt: FormatF): """ CVTF.{LD, LS, ULD, ULS} | NEGF.{D,S} | RECIPF.{D,S} | TRNCF.{DL, DUL, DUW, DW, SL, SUL, SUW, SW} """ # 11 27 4 0 20 16 # 0 0 00001 10010 CVTF.LD # 0 w 00001 00010 CVTF.LS # 0 0 10001 10010 CVTF.ULD # 0 w 10001 00010 ...
76,836
def create(url, username, course_name, target_dir): """ Create a new scraper with a url and name """ # ignore = ignore.split(",") scraper_source = f""" import sys from iliasScraper import scraper if len(sys.argv) == 2: skip = sys.argv[1] user = '{username}' sc = scraper.Scraper(url='{url}', nam...
76,837
def coors_in_cylinder(x, y, z, centre, axis, radius, length, inside=True): """ Select coordinates in a cylinder given by centre, axis and length. """ vec = nm.vstack((x, y, z)) - centre drv = nm.cross(axis, vec, axisb=0) dr = nm.sqrt(nm.sum(drv * drv, 1)) dl = nm.dot(axis, vec) if ...
76,838
def check_elasticity_parameters( parameterDict ): """ Check the elasticity parameters to make sure they are allowable. :param dict parameterDict: A dictionary of parameters """ #Create a list of constraint equations constraintEquations = [ le_pce.evaluate_g1, le_pce.evaluate_g2, le_pce....
76,839
def random_walk_z(N, y, W1, W2): """ A random walk method for sampling the inactive variables from a polytope. **See Also** domains.sample_z """ m, n = W1.shape s = np.dot(W1, y).reshape((m, 1)) # linear program to get starting z0 if np.all(np.zeros((m, 1)) <= 1-s) and np.all(np.z...
76,840
def solid_example_3(*, example_param_1: float = 4.0): """ :param example_param_1: :return: """ pass
76,841
def text_to_button(self, display, text, color, button_x, button_y, button_width, button_height, size="s"): """Writes text over an already created button via button(). Args: self (game_loop.App): Game loop class App. display (pygame.Surface): Pygame game surface. text ...
76,842
def PyImport_ExecCodeModule(space, name, w_code): """Given a module name (possibly of the form package.module) and a code object read from a Python bytecode file or obtained from the built-in function compile(), load the module. Return a new reference to the module object, or NULL with an exception set...
76,843
def calc_turb_vol(radar, radius=DEFAULT_RADIUS, split_cut=False, xran=MAX_INT, yran=MAX_INT, verbose=False, name_dz=DEFAULT_DZ, name_sw=DEFAULT_SW, turb_name=DEFAULT_TURB, max_split_cut=SPLIT_CUT_MAX, use_ntda=True, beamwidth=DEFAULT_BEAMWIDTH, ...
76,844
def create(title: str, head: str, base: str, dry_run: bool): """ Create a new pull request """ hb: Optional[TrackedBranchRef] = get_tracked_branch_ref(head) if not hb: fatal(f'head branch "{head}" is not a valid remote tracking branch') return log.info('HEAD branch: %s from %s', hb.branc...
76,845
def get_delay_val(clock_diff,poly_diff,seconds_ref_clock,seconds_ref_poly,seconds,seconds_offset,v=0,diff_pol=1): """ Compute delays at seconds_offset+seconds, considering the offsets for each polynomial (seconds_ref_clock and seconds_ref_poly). Parameters ---------- clock_diff : list of float...
76,846
def merge_defaultdicts_list(dicts): """ Merge one or several default dictionaries that have list as their values into a single one """ keys = [key for d in dicts for key in d.keys()] res_dict = defaultdict(list) for key in set(keys): res_dict[key] = merge_length_list([d[key] fo...
76,847
def calc_word_value(word): """given a word calculate its value using LETTER_SCORES""" word_value = 0 for letter in word: word_value += LETTER_SCORES[letter.upper()] return word_value
76,848
def calc_word_value(word, score=0): """Calculate the value of the word entered into function using imported constant mapping LETTER_SCORES""" for w in word: if not w.isalpha(): continue score += LETTER_SCORES[w.upper()] return score
76,849
def debugfsinfo(ui, path="."): """show information detected about current filesystem""" ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no')) ui.write(('fstype: %s\n') % (util.getfstype(path) or '(unknown)')) ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no')) ui.wri...
76,850
def _resolve_any_to_text(name, ns, dom): """Shell out to dig instead of using RPC because of RPC rate-limiting.""" ret = [] cmdline = ("dig +noadditional +noquestion +nocmd " "+nostats +nocomment %s any @%s | grep ^%s" % (name, ns, name)) for line in os.popen(cmdline, "r"):...
76,851
def bi2bt(num): """将无符号整数转换为字节序""" MSBin = b'' while num > 0: # if six.PY2: # MSBin = chr(num % 256) + MSBin # elif six.PY3: MSBin = six.int2byte(num % 256) + MSBin num >>= 8 return MSBin
76,852
def delete_blob(client, container, name, timeout=None): # type: (azure.storage.blob.BaseBlobService, str, str, int) -> None """Delete blob, including all associated snapshots :param azure.storage.blob.BaseBlobService client: blob client :param str container: container :param str name: blob name ...
76,853
def cache_init(force_update): """Create the 'tooltips.sqlite' database for quick access to tooltips. As parsing the whole bunch of XML files to find the requested content each time a tooltip is shown is quite inefficient as well as preserving the whole content int RAM all the time the xml documents are...
76,854
def test_scrape(): """ Test realistic scrape across company/date. :return: """ # Get case list case_list = get_case_list(dates=(datetime.date(2010, 1, 1), datetime.date(2010, 2, 1)), company="Acme") assert_equal(len(case_list), 5) for case in case_list: case_info = get_case(case[...
76,855
def load_dataset_hierarchical(maxlen, max_sentence_len): """ """ train_data = 'data/delicious/train-data.dat' train_labels = 'data/delicious/train-label.dat' val_data = 'data/delicious/valid-data.dat' val_labels = 'data/delicious/valid-label.dat' test_data = 'data/delicious/test-data.dat' test_labels = 'data/d...
76,856
def job(): """ Jobs - RESTful controller """ def prep(r): # @todo: for assigments, filter person_id to persons not # currently assigned to this job # @todo: for assigments, set default to current user if # not assigned to this job yet if r.method == "data...
76,857
def get_display_name(entity): """ Gets the display name for the given :tl:`User`, :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise. """ if isinstance(entity, types.User): if entity.last_name and entity.first_name: return '{} {}'.format(entity.first_name, entity.last...
76,858
def plot_quadrants(input_filename, output_filename, n, labels, show): """Plots tags on arousal-valence space""" df = pd.read_csv(input_filename) if n is not None: df = df[:n] plt.scatter(df.valence, df.arousal, df['count'].astype(float) / 15, alpha=0.7) if labels: for i, tag in en...
76,859
def calc_max_cpu(records): """ Returns the CPU usage at the max temperature, ever :param records: a list of records of min, max temp and associated CPU avg load :return: a record with the highest recorded temperature, and the associated list of CPU loads """ max_temp = 0 cpu_loads = [] for ...
76,860
def integer_or_decimal(entropy, signed): """Returns integer or non-integer decimal; 50% probability of each.""" if random.choice([False, True]): # Represent it as a decimal so that arithmetic operations are supported: return display.Decimal(integer(entropy, signed)) else: return non_integer_decimal(en...
76,861
def save_data(df, database_filename): """ - Saves cleaned data to an SQL database Args: df pandas_dataframe: Cleaned data returned from clean_data() function database_file_name str: File path of SQL Database into which the cleaned\ data is to be saved """ engine = create_engine('sqlit...
76,862
def test_initialize_with_taylormode(any_order): """Make sure that the values are close(ish) to the truth.""" r2b_jax = diffeq_zoo.threebody_jax() ode_dim = 4 expected = statespace.Integrator._convert_derivwise_to_coordwise( THREEBODY_INITS[: ode_dim * (any_order + 1)], ordint=any_order, ...
76,863
def index(request): # 定义请求需要跳转到的网页 """学习笔记的主页""" return render(request, 'learning_logs/index.html')
76,864
def run_e_raid(): """Run e_raid from cli.""" parser = ArgumentParser() parser.add_argument('-n', '--name', action='store', help='Provides name of MD RAID Array') print(e_raid(parser.parse_args().name))
76,865
def get_auth_token(): """Use the heroku auth:token command to fetch the user's API token. By using the heroku CLI itself we remove the requirement to set up an environment variable for the token. """ r = sarge.capture_stdout('heroku auth:token') if r.returncode == 0: return r.stdout.te...
76,866
def get_version(): """ Extract the __version__ from a file without importing it. :return: The version that was extracted. :rtype: :py:obj:`str` :raises AssertionError: When a version cannot be determined. """ path = os.path.dirname(os.path.abspath(__file__)) filepath = os.path.join(path...
76,867
def test_completeTask2(): """Checks complete_task returns error if task_id is not an ObjectId""" tq.complete_task(task_id=123456)
76,868
def sort_by_deg(G: nx) -> List[tuple]: """ Returns sorted list of nodes by degree """ return sorted(nx.degree(G), key=lambda vk: vk[1])
76,869
def split(root): """Split the datasets for different sequences""" train_lists = defaultdict(list) tbar = tqdm(sorted(os.listdir(os.path.join(root, 'annots')))) for name in tbar: annot = np.load(os.path.join(root, 'annots', name)).item() flag = defaultdict(bool) for obj_id ...
76,870
def resnet_qc_101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNetQC(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model_ft = models.resnet101(pretrained=True) mo...
76,871
def mse(pred: ndarray, label: ndarray) -> ndarray: """Returns the mean squared errors between the predicted values and the actual values. Args: pred (ndarray): the array of predicted values. label (ndarray): the array of ground truths. Returns: (ndarray): mean squared errors. ...
76,872
def test_keyboard_interrupt(prompt_session_init: MagicMock): """Should handle keyboard interrupt gracefully.""" ps = MagicMock() ps.prompt.side_effect = KeyboardInterrupt prompt_session_init.return_value = ps context = MagicMock() shell = interactivity.Shell(context) shell.run() assert...
76,873
def runall(regions_runs, count_retentions, sim_type, max_del=5): """ run and create a figure for each region, string in d """ deletion_lengths=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] png_template = "data/" + op.splitext(op.basename(regions_runs))[0] \ + ".%s" % (...
76,874
def ROI_def(xylnht): """ :param xylnht: X, Y, length, height in arcsec :return: Array containing [x0, xf, y0, yf] """ if xylnht[2] < 0: raise ValueError("Please input positive length and/or height") import astropy.units as u x = xylnht[0] * u.arcsec y = xylnht[1] * u.arcsec ...
76,875
async def status(): """ Return the service status - Route: `/status` - Method: `GET` - Response example: ```json { app: { up_since: "2021-02-05 17:42:13", version: "0.1.7" }, projects: [ "quotes" ] } ``` """ ...
76,876
def create_batch_file(application_exe_pyw_file_path=""): """ Creates .bat file for the given application / exe or even .pyw BOT developed by you. This is required in Task Scheduler. """ global batch_file_path try: if not application_exe_pyw_file_path: appli...
76,877
def setplot(plotdata): #-------------------------- """ Specify what is to be plotted at each frame. Input: plotdata, an instance of clawpack.visclaw.data.ClawPlotData. Output: a modified version of plotdata. """ slice_number = 3 os.chdir(plotdata.outdir) for filename in os.listdir('.'...
76,878
def is_norm(layer, exclude=None): """Check if a layer is a normalization layer. Args: layer (nn.Module): The layer to be checked. exclude (type | tuple[type]): Types to be excluded. Returns: bool: Whether the layer is a norm layer. """ if exclude is not None: if not...
76,879
def save_model(bst) -> None: """ Save the given booster model. :param bst: Computed booster. """ dummy = "" model_path: str = f"./models{dummy}/" os.makedirs(model_path, exist_ok=True) now_str: str = datetime.now().strftime('%Y%m%d_%H%M%S') file_path = os.path.join(model_path, f"xgb...
76,880
def train_gru_on(filename, target_indices, save_as, sep=',', skip_first_line=True): """ Trains a GRU RNN on a given data file filename: The name of a CSV file containing the training data target_indices: A list of integers indicating the columns with target variables save_as: F...
76,881
def validate_mp_config(config): """Validate the configuration dictionary for model parallelism. Args: config (dict): Dictionary holding configuration keys and values. Raises: ValueError: If any of the keys have incorrect values. """ if "partitions" not in config: raise Valu...
76,882
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ # Database setup common_db_configure(settings) # Add some default settings (would be nicer to do this programatically) f = "route_url = pyramid_jinja2.filters:route_url_filter" settings['jinja2.fi...
76,883
def wsgi_server(config_path): """create wsgi server given a config path""" with open(config_path) as fp: config = yaml.load(fp) tile_server = create_tileserver_from_config(config) return tile_server
76,884
def all_task_types_for_sequence(sequence, client=default): """ return the list of task_tyes for given asset and current user. """ sequence = normalize_model_parameter(sequence) path = "user/sequences/%s/task-types" % sequence["id"] task_types = raw.fetch_all(path, client=client) return sort_...
76,885
def find_most_probable_dates(text): """ Find in text the patterns that are the most probable to be the date of the documents and return them as a list match objects, along with the code that characterize the date. text : the text to be analyzed Return : (match_list, code) match_list : the list o...
76,886
def test_NocaseList_remove(testcase, nclist, args, exp_nclist): """ Test function for NocaseList.remove() """ # Don't change the testcase data, but a copy nclist_copy = NocaseList(nclist) # The code to be tested # pylint: disable=assignment-from-no-return result = nclist_copy.remove(*a...
76,887
def gensettings(T, Z=300, EED=1e-6, n=5e19, yMax=5): """ Generate appropriate DREAM settings. T: Electron temperature. Z: Effective charge of plasma. EEc: Electric field (in units of critical electric field). n: Electron density. yMax: Maximum momentum (normalized to thermal momen...
76,888
def get_fitness(individual, hash_table, environment, rerun=0): """ Gets fitness from hash table if possible, otherwise gets it from simulation rerun = 0 means never rerun rerun = 1 means rerun with diminishing probability rerun = 2 means rerun always """ values = hash_table.find(individual) ...
76,889
def grid_params(dict): """ Generate all possible combinations (cartesian product) of the hyperparameter values Returns: A new dictionary with a grid of all the possible hyperparameter combinations """ keys = dict.keys() val_arr = [] for key in keys: val_arr.append(dict[key]) p...
76,890
def main(model=None, output_dir=None, n_iter=15): """Load the model, set up the pipeline and train the parser.""" if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: nlp = spacy.blank("en") # create blank Language class...
76,891
def datetime_to_str(dt): """ Convert default datetime format to str & remove digits after int part of seconds """ result = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-7] return result
76,892
def longest_substring_using_nested_for_loop(s: str) -> int: """ Given a string s, find the length of the longest substring without repeating characters. https://leetcode.com/problems/longest-substring-without-repeating-characters/ 3946 ms 14.2 MB >>> longest_substring_using_nested_for_loop("abcabcb...
76,893
def check_valid( T, t, mu, U, ignoreLowT, verbose): """ This function is used to enforce the validity limits of the HTSE. Near half filling we have that T/t should be > 1.5, but away from half filling this does not matter so much. When running the LDA in our small beam waist setup the local val...
76,894
def neighborhood_values(image: np.ndarray, r: int, c: int, mode: str): """ Get values of pixels in the neighborhood of the current position """ assert mode in {'forward', 'reverse', 'search', 'forward4'} neighborhood = [] for (supp_r, supp_c) in neighborhood_idxs(image, r, c, mode): if...
76,895
def get_fit3_treatment(): """ Returns fit file for unit tests. """ info_path = InfoPath( path='temp_data', dir_name="a04_height3_treatment", sub_dir_name=InfoPath.DO_NOT_CREATE ) iters = get_iters() data = get_data3_tr...
76,896
def register_metrics(app, app_version=None, app_config=None): """ Register metrics middlewares Use in your application factory (i.e. create_app): register_middlewares(app, settings["version"], settings["config"]) Flask application can register more than one before_request/after_request. Beware...
76,897
def convertFile(inputpath, outputpath): """Reference: http://imageio.readthedocs.io/en/latest/examples.html#convert-a-movie""" reader = imageio.get_reader(inputpath) fps = reader.get_meta_data()['fps'] writer = imageio.get_writer(outputpath, fps=fps) for i,im in enumerate(reader): if i%10 =...
76,898
def _get_string_value(dictionary, key, default=None): """Return the valid string value for key in dictionary or default.""" if isinstance(dictionary, dict) and isinstance(key, str): value = dictionary.get(key) if _is_valid(value): return value return default
76,899