content
stringlengths
22
815k
id
int64
0
4.91M
def calculate_EHF_severity( T, T_p95_file=None, EHF_p85_file=None, T_p95_period=None, T_p95_dim=None, EHF_p85_period=None, EHF_p85_dim=None, rolling_dim="time", T_name="t_ref", ): """ Calculate the severity of the Excess Heat Factor index, defined as: EHF_severity = ...
24,100
def parse_args(): """Parse input arguments Return: parsed arguments struncture """ parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='type') subparsers.required = True parser_file = subparsers.add_parser('file') parser_file.add_argument( "-i", ...
24,101
def arrange_train_data(keypoints: Dict, beg_end_times: List[Tuple], fps: float, MAX_PERSONS: int) -> Dict: """ Arrange data into frames. Add gestures present or not based on time ranges. Generate each frame and also, add dummy when necessary. """ data = {} for key in keypoints.keys(): person...
24,102
def length(list): """Return the number of items in the list.""" if list == (): return 0 else: _, tail = list return 1 + length(tail)
24,103
def buzz(x): """ Takes an input `x` and checks to see if x is a number, and if so, also a multiple of 5. If it is both, return 'Buzz'. Otherwise, return the input. """ return 'Buzz' if isinstance(x, Number) and x % 5 == 0 else x
24,104
def _tuple_of_big_endian_int(bit_groups: Iterable[Any]) -> Tuple[int, ...]: """Returns the big-endian integers specified by groups of bits. Args: bit_groups: Groups of descending bits, each specifying a big endian integer with the 1s bit at the end. Returns: A tuple containing ...
24,105
def gene_signature_wizard_main(loomfile=None, signaturefile=None): """ Parameters ---------- loomfile : (Default value = None) signaturefile : (Default value = None) Returns ------- """ print(loomfile) if loomfile is None: loomfile = click.prompt( ...
24,106
def create_cert( cert_store: CertificateStore, key_store: KeyStore, cert_minter: CertificateMinter, cert_path: str, issuer_key_name: str, issuer_key_password: str, issuer_key_no_password: bool = False, signing_key_name: str = None, signing_key_pass...
24,107
def read_ss(fn): """Read a sequence of serverStatus JSON documents, one per line""" result = collections.defaultdict(list) for i, line in enumerate(open(fn)): j = json.loads(line) _parse(j, result, ('serverStatus',)) if i>0 and i%100==0: yield result result.cl...
24,108
def make_simple_server(service, handler, host="localhost", port=9090): """Return a server of type TSimple Server. Based on thriftpy's make_server(), but return TSimpleServer instead of TThreadedServer. Since TSimpleServer's constructor doesn't accept kwargs...
24,109
def test_random_horizontal_valid_prob_c(): """ Test RandomHorizontalFlip op with c_transforms: valid non-default input, expect to pass """ logger.info("test_random_horizontal_valid_prob_c") original_seed = config_get_set_seed(0) original_num_parallel_workers = config_get_set_num_parallel_workers...
24,110
def morph(clm1, clm2, t, lmax): """Interpolate linearly the two sets of sph harm. coeeficients.""" clm = (1 - t) * clm1 + t * clm2 grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components agrid_reco = grid_reco.to_array() pts = [] for i, longs in enumerate(agrid_reco): ilat =...
24,111
def cal_tsne_embeds_src_tgt(Xs, ys, Xt, yt, n_components=2, text=None, save_path=None, n_samples=1000, names=None): """ Plot embedding for both source and target domain using tSNE :param Xs: :param ys: :param Xt: :param yt: :param n_components: :param text: :param save_path: :ret...
24,112
def read_avg_residuemap(infile): """ Read sequence definition from PSN avg file, returning sequence Map :param infile: File handle pointing to WORDOM avgpsn output file :return: Returns an internal.map.Map object mapping the .pdb residues to WORDOM id's from "Seq" section of the avgpsn-file ...
24,113
def test_metrics_detailed_get_401(orderBy, app, client, session): """Tests API/metrics/<mapper_id> endpoint with invalid data.""" rv = client.get(f"/metrics/1?from=2021-10-10&to=2021-10-31&orderBy={orderBy}") assert rv.status_code == 401
24,114
def get_arguments(): """Run argparse and return arguments.""" try: # Use argparse to handle devices as arguments description = 'htop like application for PostgreSQL replication ' + \ 'activity monitoring.' parser = argparse.ArgumentParser(description=description) ...
24,115
def test_post_and_get(good_dataset_uuid, sample_stats, good_post_data, \ headers, good_job_url, good_dataset_url): """ POST stats with a given job_uuid and check that GET retrieves those stats. """ response = requests.post( url=good_dataset_url, headers=headers, json=good...
24,116
def schedule_remove(retval=None): """ schedule(retval=stackless.current) -- switch to the next runnable tasklet. The return value for this call is retval, with the current tasklet as default. schedule_remove(retval=stackless.current) -- ditto, and remove self. """ _scheduler_remove(getcurren...
24,117
def check_region(read, pair, region): """ determine whether or not reads map to specific region of scaffold """ if region is False: return True for mapping in read, pair: if mapping is False: continue start, length = int(mapping[3]), len(mapping[9]) r = [s...
24,118
def test_modulo_formatting( assert_errors, parse_ast_tree, code, prefix, default_options, ): """Testing that the strings violate the rules.""" tree = parse_ast_tree('x = {0}"{1}"'.format(prefix, code)) visitor = WrongStringVisitor(default_options, tree=tree) visitor.run() asser...
24,119
def create_template_AL_AR(phi, diff_coef, adv_coef, bc_top_type, bc_bot_type, dt, dx, N): """ creates 2 matrices for transport equation AL and AR Args: phi (TYPE): vector of porosity(phi) or 1-phi diff_coef (float): diffusion coefficient adv_coef (float): advec...
24,120
def run(): """ run_watchdog(timeout) -- run tasklets until they are all done, or timeout instructions have passed. Tasklets must provide cooperative schedule() calls. If the timeout is met, the function returns. The calling tasklet is put aside while the tasklets are running. It is inserted ...
24,121
def millisecond_to_clocktime(value): """Convert a millisecond time to internal GStreamer time.""" return value * Gst.MSECOND
24,122
def SE2_exp(v): """ SE2 matrix exponential """ theta, x, y = v if np.abs(theta) < 1e-6: A = 1 - theta**2/6 + theta**4/120 B = theta/2 - theta**3/24 + theta**5/720 else: A = np.sin(theta)/theta B = (1 - np.cos(theta))/theta V = np.array([[A, -B], [B, A]]) R...
24,123
def go_register_toolchains(go_version=DEFAULT_VERSION): """See /go/toolchains.rst#go-register-toolchains for full documentation.""" print("bblu go_register_toolchains 11111111111111111111111111111111111111111") if "go_sdk" not in native.existing_rules(): if go_version in SDK_REPOSITORIES: go_download_sd...
24,124
def _DotControlFlowGraphsFromBytecodeToQueue( bytecode: str, queue: multiprocessing.Queue ) -> None: """Process a bytecode and submit the dot source or the exception.""" try: queue.put(list(opt_util.DotControlFlowGraphsFromBytecode(bytecode))) except Exception as e: queue.put(DotControlFlowGraphsFromByt...
24,125
def evaluate(scores, targets, queries, train_occ, k_list, ci=False, pivotal=True, song_occ=None, metrics_file=None): """ Evaluate continuations induced by `scores` given target `targets`. The arguments are lists, and each item in a list corresponds to one run of the playlist continuation mo...
24,126
def skip_on_hw(func): """Test decorator for skipping tests which should not be run on HW.""" def decorator(f): def decorated(self, *args, **kwargs): if has_ci_ipus(): self.skipTest("Skipping test on HW") return f(self, *args, **kwargs) return decorated return decorator(func)
24,127
def rxns4tag(tag, rdict=None, ver='1.7', wd=None): """ Get a list of all reactions with a given p/l tag Notes ----- - This function is useful, but update to GEOS-Chem flexchem ( in >v11) will make it redundent and therefore this is not being maintained. """ # --- get reaction dictionar...
24,128
def update_daily_report(site_id, result_date, disease_id): """ Update daily testing activity report (without subtotals per demographic) - called when a new individual test result is registered @param site_id: the test station site ID @param result_date: the result date of the test ...
24,129
def DateTime_GetCurrentYear(*args, **kwargs): """DateTime_GetCurrentYear(int cal=Gregorian) -> int""" return _misc_.DateTime_GetCurrentYear(*args, **kwargs)
24,130
def exp_lr_scheduler(optimizer, epoch, init_lr=0.01, lr_decay_epoch=10): """Decay learning rate by a f# model_out_path ="./model/W_epoch_{}.pth".format(epoch) # torch.save(model_W, model_out_path) actor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (0.8**(epoch // lr_decay_epoch)) ...
24,131
def wait(duration): """ Waits the duration, in seconds, you specify. Args: duration (:any:`DoubleValue`): time, in seconds, this function waits. You may specify fractions of seconds. Returns: float: actual seconds waited. This wait is non-blocking, so other tasks will run while th...
24,132
def test_cp_self_2(test_dir: str) -> None: """cp a_file -> . should fail (same file)""" a_file = os.path.join(test_dir, "a_file") sys.argv = ["pycp", a_file, test_dir] with pytest.raises(SystemExit): pycp_main()
24,133
def yesterday_handler(update: Update, context: CallbackContext): """ Diary content upload handler. Uploads incoming messages to db as a note for yesterday. """ # get user timezone user_timezone = Dao.get_user_timezone(update.effective_user) # calculate time at user's user_datetime = update.e...
24,134
def get_lens_pos(sequence): """ Calculate positions of lenses. Returns ------- List of tuples with index and position of OPE in sequence. """ d = 0.0 d_ = [] for idx, ope in enumerate(sequence): if ope.is_lens(): d_.append((idx, d)) else: d +=...
24,135
def test_product_with_rvs1(): """ Test product_distribution() with an rvs specification. """ d = dit.example_dists.Xor() d_iid = dit.product_distribution(d, [[0,1], [2]]) d_truth = dit.uniform_distribution(3, ['01']) d_truth = dit.modify_outcomes(d_truth, lambda x: ''.join(x)) assert d_...
24,136
def disorientation(orientation_matrix, orientation_matrix1, crystal_structure=None): """Compute the disorientation another crystal orientation. Considering all the possible crystal symmetries, the disorientation is defined as the combination of the minimum misorientation angle and the misorientati...
24,137
def response_minify(response): """ minify html response to decrease site traffic """ if not DEBUG and response.content_type == u'text/html; charset=utf-8': response.set_data( minify(response.get_data(as_text=True)) ) return response return response
24,138
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" label_map = {label : i for i, label in enumerate(label_list,1)} features = [] for (ex_index, example) in enumerate(examples): # example : InputExample obj t...
24,139
def to_json_compatible_object(obj): """ This function returns a representation of a UAVCAN structure (message, request, or response), or a DSDL entity (array or primitive), or a UAVCAN transfer, as a structure easily able to be transformed into json or json-like serialization Args: obj: ...
24,140
def rot_box_kalman_filter(initial_state, Q_std, R_std): """ Tracks a 2D rectangular object (e.g. a bounding box) whose state includes position, centroid velocity, dimensions, and rotation angle. Parameters ---------- initial_state : sequence of floats [x, vx, y, vy, w, h, phi] Q_std...
24,141
def validate_schema(path, schema_type): """Validate a single file against its schema""" if schema_type not in _VALID_SCHEMA_TYPES.keys(): raise ValueError(f"No validation schema found for '{schema_type}'") return globals()["validate_" + schema_type](path)
24,142
def setup_test_env(): """Sets up App Engine test environment.""" sys.path.insert(0, APP_DIR) from test_support import test_env test_env.setup_test_env() sys.path.insert(0, THIRD_PARTY) from components import utils utils.fix_protobuf_package()
24,143
def import_vote_internal(vote, principal, file, mimetype): """ Tries to import the given csv, xls or xlsx file. This is the format used by onegov.ballot.Vote.export(). This function is typically called automatically every few minutes during an election day - we use bulk inserts to speed up the import....
24,144
def get_mail_count(imap, mailbox_list): """ Gets the total number of emails on specified account. Args: imap <imaplib.IMAP4_SSL>: the account to check mailbox_list [<str>]: a list of mailboxes Must be surrounded by double quotes Returns: <int>: total emails """ ...
24,145
def get_bdb_path_by_shoulder_model(shoulder_model, root_path=None): """Get the path to a BerkeleyDB minter file in a minter directory hierarchy. The path may or may not exist. The caller may be obtaining the path in which to create a new minter, so the path is not checked. Args: shoulder_model...
24,146
def getDefuzzificationMethod(name): """Get an instance of a defuzzification method with given name. Normally looks into the fuzzy.defuzzify package for a suitable class. """ m = __import__("fuzzy.defuzzify."+name, fromlist=[name]) c = m.__dict__[name] return c()
24,147
def celestial(func): """ Transform a point x from cartesian coordinates to celestial coordinates and returns the function evaluated at the probit point y """ def f_transf(ref, x, *args, **kwargs): y = cartesian_to_celestial(x) return func(ref, y, *args) return f_transf
24,148
def _rescale_to_width( img: Image, target_width: int): """Helper function to rescale image to `target_width`. Parameters ---------- img : PIL.Image Input image object to be rescaled. target_width : int Target width (in pixels) for rescaling. Returns ------- ...
24,149
def make_dpi_aware(): """ https://github.com/PySimpleGUI/PySimpleGUI/issues/1179 """ if int(platform.release()) >= 8: ctypes.windll.shcore.SetProcessDpiAwareness(True)
24,150
def compute_exact_R_P(final_patterns, centones_tab): """ Function tha computes Recall and Precision with exact matches """ true = 0 for tab in final_patterns: for centon in centones_tab[tab]: check = False for p in final_patterns[tab]: if centon == p: ...
24,151
def build_embedding(embedding_matrix, max_len, name): """ Build embedding by lda :param max_len: :param name: :return: """ # build embedding with initial weights topic_emmd = Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1], wei...
24,152
def check_playlist_url(playlist_url): """Check if a playlist URL is well-formated. Parameters ---------- playlist_url : str URL to a YouTube playlist. Returns ------- str If the URL is well-formated, return the playlist ID. Else return `None`. """ match = re.match(...
24,153
def test_PipeJsonRpcSendAsync_2(method, params, result, notification): """ Test of basic functionality. Here we don't test for timeout case (it raises an exception). """ value_nonlocal = None def method_handler1(): nonlocal value_nonlocal value_nonlocal = "function_was_called" ...
24,154
def browse_runs(driver: Driver = None, key: Dict[str, str] = {}): """ Main function that governs the browsing of projects within a specified Synergos network """ st.title("Orchestrator - Browse Existing Run(s)") ######################## # Step 0: Introduction # ########################...
24,155
def pynx(name, author, cwd): """ Function that holds the logic for the 'pynx' command. :param name: Name of the project :param author: Name of the author :param cwd: Current working directory """ folder_name, folder_path = generate_folder_name_and_path(name, cwd) check_and_create_direct...
24,156
def _calculate_accuracy(actual: np.ndarray, predictions: np.ndarray) -> None: """Calculates the accuracy of predictions. """ accuracy = sklearn.metrics.accuracy_score(actual, predictions) print(f' Predicted test labels: {predictions}') print(f' Actual test labels: {actual}') print(f' ...
24,157
def f(t, T): """ returns -1, 0, or 1 based on relationship between t and T throws IndexError """ if(t > 0 and t < float(T/2)): return 1 elif(t == float(T/2)): return 0 elif(t > float(T/2) and t < T): return -1 raise IndexError("Out of function domain")
24,158
def auth0_token(): """ Token for Auth0 API """ auth = settings["auth0"] conn = http.client.HTTPSConnection(auth['domain']) payload = '{' + f"\"client_id\":\"{auth['client']}\"," \ f"\"client_secret\":\"{auth['client-secret']}\"," \ f"\"audience\":\"https:/...
24,159
def get_ami(region, instance_type): """Returns the appropriate AMI to use for a given region + instance type HVM is always used except for instance types which cannot use it. Based on matrix here: http://aws.amazon.com/amazon-linux-ami/instance-type-matrix/ .. note:: :func:`populate_ami_...
24,160
def convert_config(cfg): """ Convert some configuration values to different values Args: cfg (dict): dict of sub-dicts, each sub-dict containing configuration keys and values pertinent to a process or algorithm Returns: dict: configuration dict with some items converted to diff...
24,161
def _signals_exist(names): """ Return true if all of the given signals exist in this version of flask. """ return all(getattr(signals, n, False) for n in names)
24,162
def login(): """Route for logging the user in.""" try: if request.method == 'POST': return do_the_login() if session.get('logged_in'): return redirect(url_for('home')) return render_template('login.html') except Exception as e: abort(500, {'message': s...
24,163
def clean_database(): """ If an instance is removed from the Orthanc server that contains de-identified DICOM images, it must also be removed from the database. This function compared the list of instance IDs in the database with those in Orthanc. """ try: logger.debug('Cleaning the database') ...
24,164
def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for f in os.lis...
24,165
def randomsplit_permuted_non_fixed_rotated_15(): """ Launch training and evaluation with a pretrained base model from rxnfp. """ launch_training_on_all_splits(experiment='repro_randomsplit', splits=RANDOM_SPLIT, base_model='pretrained', dropout=0.7987, learning_rate=0.00009659, n_permutations=15, rando...
24,166
def __screen_info_to_dict(): """ 筛查 :return: """ screen_dict: {str: List[GitLogObject]} = {} for info in git.get_all_commit_info(): if not authors.__contains__(info.name): continue if not info.check_today_time(): continue if screen_dict.__contains...
24,167
def parse_flextext(file_name, log=None): """Iterate over glossed examples contained in a flextext file.""" gloss_db = ET.parse(file_name) for example in separate_examples(gloss_db.getroot(), log): example['example'] = merge_glosses( [extract_gloss(e, log) for e in example['example']]) ...
24,168
def _collapse_edge_by_namespace( graph: BELGraph, victim_namespaces: Strings, survivor_namespaces: str, relations: Strings, ) -> None: """Collapse pairs of nodes with the given namespaces that have the given relationship. :param graph: A BEL Graph :param victim_namespaces: The namespace(s) ...
24,169
def bind_prop_arr( prop_name: str, elem_type: Type[Variable], doc: Optional[str] = None, doc_add_type=True, ) -> property: """Convenience wrapper around bind_prop for array properties :meta private: """ if doc is None: doc = f"Wrapper around `variables['{prop_name}']` of type `V...
24,170
def generate_profile_yaml_file(destination_type: DestinationType, test_root_dir: str) -> Dict[str, Any]: """ Each destination requires different settings to connect to. This step generates the adequate profiles.yml as described here: https://docs.getdbt.com/reference/profiles.yml """ config_generato...
24,171
def plot_altitude(target_list={}, observatory=None, utc_offset=0, obs_time=None, show_sun=True, show_moon=True): """plot the position of science target during observation """ # define the observation time delta_hours = np.linspace(-12, 12, 100)*u.hour obstimes = obs_time + delta_hours - utc_off...
24,172
def get_foreign_trips(db_connection): """ Gets the time series data for all Foreign visitors from the database Args: db_connection (Psycopg.connection): The database connection Returns: Pandas.DataFrame: The time series data for each unique Foreign visitor. It...
24,173
def get_diagonal_sums(square: Square) -> List[int]: """ Returns a list of the sum of each diagonal. """ topleft = 0 bottomleft = 0 # Seems like this could be more compact i = 0 for row in square.rows: topleft += row[i] i += 1 i = 0 for col in square.columns: bottomleft += col[i] i += 1 ...
24,174
def CheckComment(line, filename, linenum, next_line_start, error): """Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. er...
24,175
def int_to_base64(i: int) -> str: """ Returns a 12 char length representation of i in base64 """ return base64.b64encode(i.to_bytes(8, 'big'))
24,176
def payment_provider(provider_base_config): """When it doesn't matter if request is contained within provider the fixture can still be used""" return TurkuPaymentProviderV3(config=provider_base_config)
24,177
def gradle_extract_data(build_gradle): """ Extract the project name and dependencies from a build.gradle file. :param Path build_gradle: The path of the build.gradle file :rtype: dict """ # Content for dependencies content_build_gradle = extract_content(build_gradle) match = re.search(r...
24,178
def start_services(server_argv, portal_argv, doexit=False): """ This calls a threaded loop that launches the Portal and Server and then restarts them when they finish. """ global SERVER, PORTAL processes = Queue.Queue() def server_waiter(queue): try: rc = Popen(server_ar...
24,179
def stack_batch_img( img_tensors: Sequence[torch.Tensor], divisible: int = 0, pad_value: float = 0 ) -> torch.Tensor: """ Args :param img_tensors (Sequence[torch.Tensor]): :param divisible (int): :param pad_value (float): value to pad :return: torch.Tensor. """ assert len(img_te...
24,180
def gen_accessor_declarations(out): """ Generate the declaration of each version independent accessor @param out The file to which to write the decs """ out.write(""" /**************************************************************** * * Unified, per-member accessor function declarations * ****...
24,181
def convert_rel_traj_to_abs_traj(traj): """ Converts a relative pose trajectory to an absolute-pose trajectory. The incoming trajectory is processed elemente-wise. Poses at each timestamp are appended to the absolute pose from the previous timestamp. Args: traj: A PoseTrajecto...
24,182
def remove(handle): """The remove action allows users to remove a roommate.""" user_id = session['user'] roommate = model.roommate.get_roommate(user_id, handle) # Check if roommate exists if not roommate: return abort(404) if request.method == 'POST': model.roommate.delete_roo...
24,183
def delete_conversation(bot_id: str): """ Deletes conversation. """ count = get_db().delete(f'conversation.{bot_id}') logger.info(f'{count} conversation(s) deleted for bot {bot_id}.')
24,184
def maxsubarray(list): """ Find a maximum subarray following this idea: Knowing a maximum subarray of list[0..j] find a maximum subarray of list[0..j+1] which is either (I) the maximum subarray of list[0..j] (II) or is a maximum subarray list[i..j+1] for some 0 <= i <= j ...
24,185
def set_packet_timeout (address, timeout): """ Adjusts the ACL flush timeout for the ACL connection to the specified device. This means that all L2CAP and RFCOMM data being sent to that device will be dropped if not acknowledged in timeout milliseconds (maximum 1280). A timeout of 0 means to never...
24,186
def get_merged_threadlocal(bound_logger: BindableLogger) -> Context: """ Return a copy of the current thread-local context merged with the context from *bound_logger*. .. versionadded:: 21.2.0 """ ctx = _get_context().copy() ctx.update(structlog.get_context(bound_logger)) return ctx
24,187
def sort_cipher_suites(cipher_suites, ordering): """Sorts the given list of CipherSuite instances in a specific order.""" if ordering == 'asc': return cipher_suites.order_by('name') elif ordering == 'desc': return cipher_suites.order_by('-name') else: return cipher_suites
24,188
def make_1D_distributions(lims, n_points, all_shifts, all_errs, norm=None, max_shifts=None, seed=None): """ Generate 1D distributions of chemical shifts from arrays of shifts and errors of each distribution Inputs: - lims Limits of the distributions - n_points Number o...
24,189
def fill_column_values(df, icol=0): """ Fills empty values in the targeted column with the value above it. Parameters ---------- df: pandas.DataFrame icol: int Returns ------- pandas.DataFrame """ v = df.iloc[:,icol].fillna('').values.tolist() vnew = fill_gaps(v) d...
24,190
def reward(static, tour_indices): """ Euclidean distance between all cities / nodes given by tour_indices """ # Convert the indices back into a tour idx = tour_indices.unsqueeze(1).expand(-1, static.size(1), -1) tour = torch.gather(static.data, 2, idx).permute(0, 2, 1) # Ensure we're alway...
24,191
def test_sls_networks_update(cli_runner, rest_mock): """ Test `cray sls networks update` with various params """ runner, cli, opts = cli_runner network_name = 'foobar' url_template = f'/apis/sls/v1/networks/{network_name}' config = opts['default'] hostname = config['hostname'] payload = f"""...
24,192
def valid_review_queue_name(request): """ Given a name for a queue, validates the correctness for our review system :param request: :return: """ queue = request.matchdict.get('queue') if queue in all_queues: request.validated['queue'] = queue return True else: _t...
24,193
def is_valid_cluster_dir(path): """Checks whether a given path is a valid postgres cluster Args: pg_ctl_exe - str, path to pg_ctl executable path - str, path to directory Returns: bool, whether or not a directory is a valid postgres cluster """ pg_controldata_exe = which('p...
24,194
def get_best_straight(possible_straights, hand): """ get list of indices of hands that make the strongest straight if no one makes a straight, return empty list :param possible_straights: ({tuple(str): int}) map tuple of connecting cards --> best straight value they make :param hand: (set(s...
24,195
def stats(request): """ Display statistics for the web site """ from django.shortcuts import render_to_response, RequestContext views = list(View.objects.all().only('internal_url', 'browser')) urls = {} mob_vs_desk = { 'desktop': 0, 'mobile': 0 } for view in views: if is_mo...
24,196
def show_scatter_plot( content_on_x, content_on_y, x_label, y_label, title, color='#1f77b4'): """Plots scatter plot""" plt.figure(1) plt.scatter(content_on_x, content_on_y, s=2, c=color) plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) plt.show()
24,197
def build_argparser(): """ Builds argument parser. :return argparse.ArgumentParser """ banner = "%(prog)s - generate a static file representation of a PEP data repository." additional_description = "\n..." parser = _VersionInHelpParser( description=banner, epilog=a...
24,198
def abc19(): """Solution to exercise C-1.19. Demonstrate how to use Python’s list comprehension syntax to produce the list [ a , b , c , ..., z ], but without having to type all 26 such characters literally. """ a_idx = 97 return [chr(a_idx + x) for x in range(26)]
24,199