content
stringlengths
22
815k
id
int64
0
4.91M
def _apply_sobel(img_matrix): """ Input: img_matrix(height, width) with type float32 Convolves the image with sobel mask and returns the magnitude """ dx = sobel(img_matrix, 1) dy = sobel(img_matrix, 0) grad_mag = np.hypot(dx, dy) # Calculates sqrt(dx^2 + dy^2) grad_mag *= 255 ...
20,700
def isDeleted(doc_ref): """ Checks if document is logically deleted, i.e. has a deleted timestamp. Returns: boolean """ return exists(doc_ref) and 'ts_deleted' in get_doc(doc_ref)
20,701
def log_sql_result(count, time): """Print the given string to the console with "[SQL] " prefixed Parameters: statement (String): The statement to log """ print(str(datetime.now().strftime(fmt)) + CYAN + ' [SQL] ' + RESET + str(count) + ' Rows(s) affected in ' + str(round(time,3)) + ' s')
20,702
def test_list_byte_length_1_nistxml_sv_iv_list_byte_length_2_4(mode, save_output, output_format): """ Type list/byte is restricted by facet length with value 6. """ assert_bindings( schema="nistData/list/byte/Schema+Instance/NISTSchema-SV-IV-list-byte-length-2.xsd", instance="nistData/li...
20,703
def GenerateSysroot(sysroot_path, board, build_tests, unpack_only=False): """Create a sysroot using only binary packages from local binhost. Args: sysroot_path: Where we want to place the sysroot. board: Board we want to build for. build_tests: If we should include autotest packages. unpack_only: I...
20,704
def postprocess_summary(summary, name, result_dict, result_keys): """ Save the result_keys performances in the result_dict. """ for key in result_keys: if key in summary.keys(): result_dict[key][name] = summary[key]
20,705
def sys_wait_for_event( mask: int, k: Optional[Key], m: Optional[Mouse], flush: bool ) -> int: """Wait for an event then return. If flush is True then the buffer will be cleared before waiting. Otherwise each available event will be returned in the order they're recieved. Args: mask (int):...
20,706
def func_module_subcmd(args): """Entry point for "buildtest module" subcommand. :param args: command line arguments passed to buildtest :type args: dict, required """ if args.diff_trees: diff_trees(args.diff_trees) if args.easybuild: check_easybuild_module() if args.spack...
20,707
def get_test(): """ Return test data. """ context = {} context['test'] = 'this is a test message' return flask.jsonify(**context)
20,708
def num_poisson_events(rate, period, rng=None): """ Returns the number of events that have occurred in a Poisson process of ``rate`` over ``period``. """ if rng is None: rng = GLOBAL_RNG events = 0 while period > 0: time_to_next = rng.expovariate(1.0/rate) if time_to_...
20,709
def findmatch(members,classprefix): """Find match for class member.""" lst = [n for (n,c) in members] return fnmatch.filter(lst,classprefix)
20,710
def create_fields_provided_instances(apps, schema_editor): """ creates new instances of the FieldsProvided model for each submission. This helps track which form fields were filled in (or edited/removed) when users submit activity reports or staff edits. Each submission should have one related instance...
20,711
def find_cheapest_price(price_data, timeframe, power): """Return start time and end time where the electricity price is the cheapest. :param price_data: Price data, key is start hour in unix time, value is price :type price_data: Dict[int, float] :param timeframe: time span for which we want to consume...
20,712
def main(args, unit_test=False): """ Runs fluxing steps """ import os import numpy as np from pypeit import fluxspec from pypeit.core import flux from pypeit.par import pypeitpar # Load the file spectrograph, config_lines, flux_dict = read_fluxfile(args.flux_file) # Parameter...
20,713
def drop_database(dbname,engine): """ Warning, drops the specified database! Args: dbname (str): Name of database to drop. engine (obj): Database engine. """ msg = """ --------------------------------------------------------- \n Warning, you are about to delete the followi...
20,714
def is_narcissistic(number): """Must return True if number is narcissistic""" return sum([pow(int(x), len(str(number))) for x in str(number)]) == number
20,715
def Plot1DFields(r,h,phi_n_bar,g_s,g_b): """ Generates a nice plot of the 1D fields with 2 axes and a legend. Note: The sizing works well in a jupyter notebook but probably should be adjusted for a paper. """ fig,ax1 = plt.subplots(figsize=(6.7,4)) fig.subplots_adjust(right=0.8) ax2 = a...
20,716
def get_yesterday(): """ :return: """ return _get_passed_one_day_from_now(days=1).date()
20,717
def classroom_mc(): """ Corresponds to the 2nd line of Table 4 in https://doi.org/10.1101/2021.10.14.21264988 """ concentration_mc = mc.ConcentrationModel( room=models.Room(volume=160, inside_temp=models.PiecewiseConstant((0., 24.), (293,)), humidity=0.3), ventilation=models.MultipleVent...
20,718
def teardown_module(): """Remove test data and scripts from .retriever directories.""" for test in tests: shutil.rmtree(os.path.join(HOME_DIR, "raw_data", test['name'])) os.remove(os.path.join(HOME_DIR, "scripts", test['name'] + '.json')) subprocess.call(['rm', '-r', test['name']])
20,719
def reset_params(): """Reset all global (or module) parameters. """ Z3_global_param_reset_all()
20,720
def smart_eval(stmt, _globals, _locals, filename=None, *, ast_transformer=None): """ Automatically exec/eval stmt. Returns the result if eval, or NoResult if it was an exec. Or raises if the stmt is a syntax error or raises an exception. If stmt is multiple statements ending in an expression, the s...
20,721
def parse_toml(path_string: Optional[str]) -> Dict[str, Any]: """Parse toml""" if not path_string: path = pathlib.Path(os.getcwd()) else: path = pathlib.Path(path_string) toml_path = path / "pyproject.toml" if not toml_path.exists(): return {} with open(toml_path, encodin...
20,722
def run_authorization_flow(): """Run authorization flow where the user must authorize Pardal to access their Twitter account.""" start_server() logger.info('Starting not logged user flow...') say('Please wait while an access token is retrieved from Twitter.') # FIXME if Linux copy the address ...
20,723
def mtxv(m1, vin): """ Multiplies the transpose of a 3x3 matrix on the left with a vector on the right. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxv_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of floats :param vin: 3-dimensional double precisi...
20,724
def cmip_recipe_basics(func): """A decorator for starting a cmip recipe """ def parse_and_run(*args, **kwargs): set_verbose(_logger, kwargs.get('verbose')) opts = parse_recipe_options(kwargs.get('options'), add_cmip_collection_args_to_parser) # Recipe is run. returnval = func...
20,725
def optimize_concrete_function( concrete_function: function.ConcreteFunction, strip_control_dependencies: bool) -> wrap_function.WrappedFunction: """Returns optimized function with same signature as `concrete_function`.""" wrapped_fn = wrap_function.WrappedFunction( concrete_function.graph, vari...
20,726
def serialize_cupcake(cupcake): """Serialize a cupcake SQLAlchemy obj to dictionary.""" return { "id": cupcake.id, "flavor": cupcake.flavor, "size": cupcake.size, "rating": cupcake.rating, "image": cupcake.image, }
20,727
def compute_accuracy(labels, logits): """Compute accuracy for a single batch of data, given the precomputed logits and expected labels. The returned accuracy is normalized by the batch size. """ current_batch_size = tf.cast(labels.shape[0], tf.float32) # logits is the percent chance; this gives the category...
20,728
def enable_daily_notification(update: Update, context: CallbackContext) -> None: """Enable daily notifications for clean time at user specified time.""" update, context, user = bot_helper.get_user(update, context) user_job = bot_helper.get_daily_notification(context, user["UserID"]) if user_job: ...
20,729
def jvc(ctx): """Current–voltage characteristic + graphs""" extension = "ocw" jvc_template_out = ["+V [V]", "+J [mA/cm2]", "-V [V]", "-J [mA/cm2]", "+P [W/cm2]", "-P [W/cm2]"] jvc_result_template = ["Scan", "Power max", "Voc [V]","Jsc [mA/cm2]", "FF", "PCE (%)"] jvc_summary = [] jvc_mask_area = click.prompt( ...
20,730
def generate_sosreport_in_node( nodeip: str, uname: str, pword: str, directory: str, results: list ) -> None: """Generate sosreport in the given node and copy report to directory provided Args: nodeip host Ip address uname Username for accessing host pword ...
20,731
def get_data(generic_iterator): """Code to get minibatch from data iterator Inputs: - generic_iterator; iterator for dataset Outputs: - data; minibatch of data from iterator """ data = next(generic_iterator) if torch.cuda.is_available(): data = data.cuda() return data
20,732
def aug_transform(crop, base_transform, cfg, extra_t=[]): """ augmentation transform generated from config """ return T.Compose( [ T.RandomApply( [T.ColorJitter(cfg.cj0, cfg.cj1, cfg.cj2, cfg.cj3)], p=cfg.cj_p ), T.RandomGrayscale(p=cfg.gs_p), ...
20,733
def _check_definition_contains_or(definition_dict, key, values): """need docstring""" out = False for value in values: if (np.array(list(definition_dict[key])) == value).any(): out = True break return out
20,734
def write_conf(config): """ """ try: with open('./data/config.json', 'w') as outfile: print(timestamp(), "\tConfig written: ", config) json.dump(config, outfile) except IOError: print(timestamp(), "\tIOError opening config.json for writing") return
20,735
def concurrent_map(func, data): """ Similar to the bultin function map(). But spawn a thread for each argument and apply `func` concurrently. Note: unlike map(), we cannot take an iterable argument. `data` should be an indexable sequence. WARNING : this function doesn't limit the number of thr...
20,736
def star_hexagon(xy, radius=5, **kwargs): """ |\ c | \ b |__\ a """ x,y = xy r = radius a = 1/4*r b = a*2 c = a*3**(1/2) return plt.Polygon(xy=( (x, y-2*c), (x+a, y-c), (x+a+b, y-c), (x+b, y), (x+a+b, y+c), (x+a, y+c), (x, y+2*c),...
20,737
def initialize(*args, **kwargs): """Instance creation""" global TSI TSI = TestServerInterface(*args, **kwargs) TSI.startFifo()
20,738
def calibrate(leveled_arcs, sat_biases, stn_biases): """ ??? """ calibrated_arcs = [] for arc in leveled_arcs: if arc.sat[0] == 'G': sat_bias = sat_biases['GPS'][int(arc.sat[1:])][0] * NS_TO_TECU stn_bias = stn_biases['GPS'][arc.stn.upper()][0] * NS_TO_TECU el...
20,739
def test_google_bigquery_destination(sdc_builder, sdc_executor, gcp): """ Send data to Google BigQuery from Dev Raw Data Source and confirm that Google BigQuery destination successfully recieves them using Google BigQuery client. This is achieved by using a deduplicator which assures that there is only...
20,740
def negSamplingCostAndGradient(predicted, target, outputVectors, dataset, K=10): """ Implements the negative sampling cost function and gradients for word2vec :param predicted: ndarray, the predicted (center) word vector(v_c) :param target: integer, the index of the target word :param outputVectors...
20,741
def isotime(timestamp): """ISO 8601 formatted date in UTC from unix timestamp""" return datetime.fromtimestamp(timestamp, pytz.utc).isoformat()
20,742
def initializeSeam(): """ This function defines the seams of a baseball. It is based, in large extant, on the work from http://www.darenscotwilson.com/spec/bbseam/bbseam.html """ n = 109 #number of points were calculating on the seam line alpha = np.linspace(0,np.pi*2,n) x = np.zeros(len...
20,743
def check_model_consistency(model, grounding_dict, pos_labels): """Check that serialized model is consistent with associated json files. """ groundings = {grounding for grounding_map in grounding_dict.values() for grounding in grounding_map.values()} model_labels = set(model.estimator....
20,744
def get_submission_info(tile_grid, collections, tile_indices, period_start, period_end, period_freq): """ Return information about tracked order submissions """ return { 'submitted': dt.datetime.today().isoformat(), 'collections': collections, 'tile_grid': til...
20,745
def load_obj(path): """Load an object from a Python file. path is relative to the data dir. The file is executed and the obj local is returned. """ localdict = {} with open(_DATADIR / path) as file: exec(file.read(), localdict, localdict) return localdict['obj']
20,746
def dp_policy_evaluation(env, pi, v=None, gamma=1, tol=1e-3, iter_max=100, verbose=True): """Evaluates state-value function by performing iterative policy evaluation via Bellman expectation equation (in-place) Based on Sutton/Barto, Reinforcement Learning, 2nd ed. p. 75 Args: env: Envi...
20,747
async def test_cut_video_aio(): """ 测试视频缩放 :return: """ print('') h264_obj = H264Video(constval.VIDEO, constval.OUTPUT_DIR, aio=True) start_time = random.random() * 100 last_time = random.randint(int(start_time)+1, 1000) print('current work dir', os.path.abspath(os.getcwd())) pri...
20,748
def gpst2utc(tgps, leaps_=-18): """ calculate UTC-time from gps-time """ tutc = timeadd(tgps, leaps_) return tutc
20,749
def create_shell(username, session_id, key): """Instantiates a CapturingSocket and SwiftShell and hooks them up. After you call this, the returned CapturingSocket should capture all IPython display messages. """ socket = CapturingSocket() session = Session(username=username, session=session...
20,750
def _get_index_sort_str(env, name): """ Returns a string by which an object with the given name shall be sorted in indices. """ ignored_prefixes = env.config.cmake_index_common_prefix for prefix in ignored_prefixes: if name.startswith(prefix) and name != prefix: return n...
20,751
def giveError(message: str) -> None: """Display error message and exits program""" print(colored(f"Error: {message}", 'red')) exit()
20,752
def utcnow(): """Gets current time. :returns: current time from utc :rtype: :py:obj:`datetime.datetime` """ return datetime.datetime.utcnow()
20,753
def elem2full(elem: str) -> str: """Retrieves full element name for short element name.""" for element_name, element_ids, element_short in PERIODIC_TABLE: if elem == element_short: print(element_name) return element_name else: raise ValueError(f"Index {elem} does not ...
20,754
def fixture_path(relapath=''): """:return: absolute path into the fixture directory :param relapath: relative path into the fixtures directory, or '' to obtain the fixture directory itself""" return os.path.join(os.path.dirname(__file__), 'fixtures', relapath)
20,755
def create_random_totp_secret(secret_length: int = 72) -> bytes: """ Generate a random TOTP secret :param int secret_length: How long should the secret be? :rtype: bytes :returns: A random secret """ random = SystemRandom() return bytes(random.getrandbits(8) for _ in range(secret_length...
20,756
def _get_roles_can_update(community_id): """Get the full list of roles that current identity can update.""" return _filter_roles("members_update", {"user", "group"}, community_id)
20,757
def register_external_compiler(op_name, fexternal=None, level=10): """Register the external compiler for an op. Parameters ---------- op_name : str The name of the operator. fexternal : function (attrs: Attrs, args: List[Expr], compiler: str) -> new_expr: Expr The fun...
20,758
def kl_divergence_from_logits_bm(logits_a, logits_b): """Gets KL divergence from logits parameterizing categorical distributions. Args: logits_a: A tensor of logits parameterizing the first distribution. logits_b: A tensor of logits parameterizing the second distribution. Returns: ...
20,759
def get_stats_fuzzy(stats, img, var_img, roi_set, suffix="", ignore_nan=True, ignore_inf=True, ignore_zerovar=True, mask=None, pv_threshold=0.): """ Get a set of statistics for a set of 'fuzzy' ROIs :param img: 3D Numpy array :param roi_set: 4D Numpy array with same dimensions as img and each volume ...
20,760
def if_stopped_or_playing(speaker, action, args, soco_function, use_local_speaker_list): """Perform the action only if the speaker is currently in the desired playback state""" state = speaker.get_current_transport_info()["current_transport_state"] logging.info( "Condition: '{}': Speaker '{}' is in ...
20,761
def test_quorum_slices_to_definition(): """Test quorum_slices_to_definition()""" assert quorum_slices_to_definition([{'A', 'B'}, {'C'}]) == { 'threshold': 1, 'nodes': set(), 'children_definitions': [{ 'threshold': 2, 'nodes': {'A', 'B'}, 'children_defi...
20,762
def compute_src_graph(hive_holder, common_table): """ computes just the src part of the full version graph. Side effect: updates requirements of blocks to actually point to real dep versions """ graph = BlockVersionGraph() versions = hive_holder.versions graph.add_nodes(versions.itervalues()) ...
20,763
def get_uv(seed=0, nrm=False, vector=False): """Dataset with random univariate data Parameters ---------- seed : None | int Seed the numpy random state before generating random data. nrm : bool Add a nested random-effects variable (default False). vector : bool Add a 3d ...
20,764
def private_names_for(cls, names): """ Returns: Iterable of private names using privateNameFor()""" if not isinstance(names, Iterable): raise TypeError('names must be an interable') return (private_name_for(item, cls) for item in names)
20,765
def check_xpbs_install() -> None: """Try to get the install path of third party tool Xpbs (https://github.com/FranckLejzerowicz/Xpbs). If it exists, nothing happens and the code proceeds. Otherwise, the code ends and tells what to do. """ ret_code, ret_path = subprocess.getstatusoutput('which Xp...
20,766
def find_vcs_root(location="", dirs=(".git", ".hg", ".svn"), default=None) -> str: """Return current repository root directory.""" if not location: location = os.getcwd() prev, location = None, os.path.abspath(location) while prev != location: if any(os.path.isdir(os.path.join(location, ...
20,767
def invert_trimat(A, lower=False, right_inv=False, return_logdet=False, return_inv=False): """Inversion of triangular matrices. Returns lambda function f that multiplies the inverse of A times a vector. Args: A: Triangular matrix. lower: if True A is lower triangular, else A is upper triangu...
20,768
def category_input_field_delete(request, structure_slug, category_slug, module_id, field_id, structure): """ Deletes a field from a category input module :type structure_slug: String :type category_slug: String :type module_id: Integer...
20,769
def cat_to_num(att_df): """ Changes categorical variables in a dataframe to numerical """ att_df_encode = att_df.copy(deep=True) for att in att_df_encode.columns: if att_df_encode[att].dtype != float: att_df_encode[att] = pd.Categorical(att_df_encode[att]) att_df_enco...
20,770
async def handle_get(request): """Handle GET request, can be display at http://localhost:8080""" text = (f'Server is running at {request.url}.\n' f'Try `curl -X POST --data "text=test" {request.url}example`\n') return web.Response(text=text)
20,771
def values_target(size: tuple, value: float, cuda: False) -> Variable: """ returns tensor filled with value of given size """ result = Variable(full(size=size, fill_value=value)) if cuda: result = result.cuda() return result
20,772
def get_new_perpendicular_point_with_custom_distance_to_every_line_segment( line_segments: np.ndarray, distance_from_the_line: np.ndarray ): """ :param line_segments: array of shape [number_of_line_segments, 2, 2] :param distance_from_the_line: how far the new point to create from the reference :ret...
20,773
def test_files_safen_path(mongodb_settings, filename, fuuid): """Verify that regular and url-encoded paths are equivalent """ base = FileStore(mongodb_settings) doc = FileRecord({'name': filename}) resp = base.add_update_document(doc) assert resp['uuid'] == fuuid
20,774
def tmdb_find_movie(movie: str, tmdb_api_token: str): """ Search the tmdb api for movies by title Args: movie (str): the title of a movie tmdb_api_token (str): your tmdb v3 api token Returns: dict """ url = 'https://api.themoviedb.org/3/search/movie?' params = {'que...
20,775
def bus_routes(): """ Gets all the bus routes from the LTA API and store them in bus_routes.txt Each row in bus_routes.txt will have a bus service number, direction, bus stop code, bus stop name, first and last bus timings for weekdays, Saturday and Sunday """ os.remove('bus_routes.txt') bus...
20,776
def is_missing_artifact_error(err: WandbError): """ Check if a specific W&B error is caused by a 404 on the artifact we're looking for. """ # This is brittle, but at least we have a test for it. return "does not contain artifact" in err.message
20,777
def robust_makedirs(path): """ create a directory in a robust race safe manner if not already existing. Good for multiprocessing / threading or cases where multiple actors might create a directory """ if not os.path.isdir(path): try: os.makedirs(path) exce...
20,778
def activate_locale(locale=None, app=None): """Active an app or a locale.""" prefixer = old_prefix = get_url_prefix() old_app = old_prefix.app old_locale = translation.get_language() if locale: rf = RequestFactory() prefixer = Prefixer(rf.get('/%s/' % (locale,))) translation....
20,779
def create_reforecast_valid_times(start_year=2000): """Inits from year 2000 to 2019 for the same days as in 2020.""" reforecasts_inits = [] inits_2020 = create_forecast_valid_times().forecast_time.to_index() for year in range(start_year, reforecast_end_year + 1): # dates_year = pd.date_range(sta...
20,780
def _checkerror(fulloutput): """ Function to check the full output for known strings and plausible fixes to the error. Future: add items to `edict` where the key is a unique string contained in the offending output, and the data is the reccomended solution to resolve the problem """ edict = {'mu...
20,781
def create_pre_process_block(net, ref_layer_name, means, scales=None): """ Generates the pre-process block for the IR XML Args: net: root XML element ref_layer_name: name of the layer where it is referenced to means: tuple of values scales: tuple of values Returns: ...
20,782
def tabWidget_func(value, main_window): """Connect main tabWidget.""" main_window.scene.current_tab_idx = value fill_listWidget_with_data(main_window.scene.project_data, main_window.listWidget, value) set_selected_id_in_listWidget(main_window.scene, 0)
20,783
def GetSystemFaultsFromState(state, spot_wrapper): """Maps system fault data from robot state proto to ROS SystemFaultState message Args: data: Robot State proto spot_wrapper: A SpotWrapper object Returns: SystemFaultState message """ system_fault_state_msg = SystemFaultStat...
20,784
def findAnEven(L): """ :Assumes L is a list of integers: :Returns the first even number in L: :Raises ValueError if L does not contain an even number: """ for num in L: if num % 2 == 0: return num raise ValueError
20,785
def get_points(wire): """ get all points (including starting point), where the wire bends >>> get_points(["R75","D30","R83","U83","L12","D49","R71","U7","L72"]) [((0, 0), (75, 0)), ((75, 0), (75, -30)), ((75, -30), (158, -30)), ((158, -30), (158, 53)), ((158, 53), (146, 53)), ((146, 53), (146, 4)), ((14...
20,786
def getcutscheckerboard(rho): """ :param rho: :return: cell centers and values along horizontal, vertical, diag cut """ ny, nx = rho.shape assert nx == ny n = ny horizontal = rho[6 * n // 7, :] vertical = rho[:, n // 7] if np.abs(horizontal[0]) < 1e-15: horizontal = hor...
20,787
def errorString(node, error): """ Format error messages for node errors returned by checkLinkoStructure. inputs: node - the node for the error. error - a (backset, foreset) tuple, where backset is the set of missing backlinks and foreset is the set of missing forelinks. returns: string ...
20,788
def test_2(): """ query : compare average sales of A and B in date range 2000 to 2010 here the oversight is not detected as the 2 companies don't differ in experience time """ table = pandas.DataFrame() table['Company'] = pandas.Series(['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B']) ...
20,789
def deep_update(target, source): """ Deep merge two dicts """ if isinstance(source, dict): for key, item in source.items(): if key in target: target[key] = deep_update(target[key], item) else: target[key] = source[key] return target
20,790
def verify_iou_value(issued_currency_value: str) -> None: """ Validates the format of an issued currency amount value. Raises if value is invalid. Args: issued_currency_value: A string representing the "value" field of an issued currency amount. Returns: ...
20,791
def md5_hash_file(path): """ Return a md5 hashdigest for a file or None if path could not be read. """ hasher = hashlib.md5() try: with open(path, 'rb') as afile: buf = afile.read() hasher.update(buf) return hasher.hexdigest() except IOError: #...
20,792
def Constant(value): """ Produce an object suitable for use as a source in the 'connect' function that evaluates to the given 'value' :param value: Constant value to provide to a connected target :return: Output instance port of an instance of a Block that produces the given constant when evaluated...
20,793
def _Backward3a_T_Ps(P, s): """Backward equation for region 3a, T=f(P,s) Parameters ---------- P : float Pressure [MPa] s : float Specific entropy [kJ/kgK] Returns ------- T : float Temperature [K] References ---------- IAPWS, Revised Supplementary ...
20,794
def calculate_width_and_height(url_parts, options): """Appends width and height information to url""" width = options.get("width", 0) has_width = width height = options.get("height", 0) has_height = height flip = options.get("flip", False) flop = options.get("flop", False) if flip: ...
20,795
def db_handler(args): """db_handler.""" if args.type == 'create': if args.db is None: db.init_db() return if not _setup_db(args.db): return if args.type == 'status': current_rev = db_revision.current_db_revision() print('current_rev', current_rev) ...
20,796
def expandvars(s): """Expand environment variables of form %var%. Unknown variables are left unchanged. """ global _env_rx if '%' not in s: return s if _env_rx is None: import re _env_rx = re.compile(r'%([^|<>=^%]+)%') return _env_rx.sub(_substenv, s)
20,797
def main(): """ Parse command line parameters """ parser = argparse.ArgumentParser(add_help=False, description="Don't worry loves, cavalry's here!") subparsers = parser.add_subparsers(dest='command') parser_config = subparsers.add_parser('config', description='Configure gene...
20,798
def run_queries(q, file): """Run Twitter username queires against Twitter API. Args: q (tuple): A tuple of query strings. file (str): A str filepath to a save results. """ data = csv(cd(file)) # modified to point to Data dir. seen = set(col(0, data)) for q in reversed(q): ...
20,799