content
stringlengths
22
815k
id
int64
0
4.91M
def _build_jinja2_expr_tmp(jinja2_exprs): """Build a template to evaluate jinja2 expressions.""" exprs = [] tmpls = [] for var, expr in jinja2_exprs.items(): tmpl = f"{var}: >-\n {{{{ {var} }}}}" if tmpl not in tmpls: tmpls.append(tmpl) if expr.strip() not in exprs: ...
5,318,600
def create_blueprint(app): """Register blueprint routes on app.""" routes = app.config.get("APP_ROUTES") blueprint = Blueprint( "{{cookiecutter.package_name}}_records", __name__, template_folder="../templates", ) # TODO: register your record views here. # Register temp...
5,318,601
def test_rule_with_templates(rules): """ Test that all rules have at least one corresponding template """ # Retrieve all serverless rule IDs rule_ids = set([r.id for r in rules if r.id[1] == "S"]) # Retrieve all rule IDs for tests test_rule_ids = set([t[1] for t in templates]) assert ...
5,318,602
def normal(x, mu=0, sig=1): """ Normal distribution log-likelihood. :param x: *int, float, np.array.* :param mu: (optional) *int, float, np.array.* Location parameter of the normal distribution. Defaults to 0. :param sig: (optional) *int, float.* Standard deviatio...
5,318,603
def parse_args(args): """ Parse arguments """ parser = optparse.OptionParser() parser.add_option('--os', default=platform.system().lower(), help='Set the target os (default %default)') parser.add_option('--cc', default='gcc', help='Set the target comp...
5,318,604
def download_file_sftp(child, filepath, download_path="~/Downloads"): """Download a file from a device using SFTP. Developer Note: SFTP must be installed. :param pexpect.spawn child: The connection in a child application object. :param str filepath: The file to download. :param str download_path: ...
5,318,605
def BitmapFromImage(image): """ A compatibility wrapper for the wx.Bitmap(wx.Image) constructor """ return Bitmap(image)
5,318,606
def load_coco_name(path): """Load labels from coco.name """ coco = {} with open(path, 'rt') as file: for index, label in enumerate(file): coco[index] = label.strip() return coco
5,318,607
def qsat(T, p) : """ Saturation vapour pressure. Derived variable name: qsat Parameters ---------- T : numpy array or xarray DataArray Temperature. (K) p : numpy array or xarray DataArray Pressure (Pa). Returns ------- qs : numpy array or xarray DataArray ...
5,318,608
def set_xy_labels_and_ticksize(units, kpc_per_arcsec, xlabelsize, ylabelsize, xyticksize): """Set the x and y labels of the figure, and set the fontsize of those labels. The x and y labels are always the distance scales, thus the labels are either arc-seconds or kpc and depend on the \ units the figure is ...
5,318,609
def create_group_ae(cse_uri, group_name, uri_list): """ Method description: Creates an AE that groups various other specifies AEs in the OneM2M framework/tree under the specified DATA CON Parameters: uri : [str] URI for the parent DATA CON appended by "la" or "ol" fm...
5,318,610
def extract_features(df, action): """ 提取特征 :param df: DataFrame 样本(训练和测试) :param action: str action :return: x: DataFrame 特征 y: Series 标签 """ # 特征-训练每个任务都需要初始化 DENSE_FEATURE_COLUMNS = ['videoplayseconds'] # 1,特征处理 # dense df.fillna(value={f: 0.0 for f in DEN...
5,318,611
def test_clumper_docstrings(m): """ Take the docstring of every method on the `Clumper` class. The test passes if the usage examples causes no errors. """ check_docstring(m)
5,318,612
def quick_sort(input_list): """Quick sort.""" if not isinstance(input_list, (list, tuple)): raise ValueError('input takes list/tuple only') if isinstance(input_list, (tuple)): input_list = list(input_list) if not all(isinstance(val, (int, float)) for val in input_list): raise V...
5,318,613
def validate_execution_order(relations: List[RelationDescription], keep_going=False): """ Make sure we can build an execution order. We'll catch an exception and set a flag if the keep_going option is true. """ try: ordered_relations = etl.relation.order_by_dependencies(relations) excep...
5,318,614
def now(): """Returns a java.util.Date object that represents the current time according to the local system clock. Returns: Date: A new date, set to the current date and time. """ return Date()
5,318,615
def create_session_factory(session_id_store, backend_store, *, loop=None): """Creates new session factory. Create new session factory from two storage: session_id_store and backend_store. """ return _SessionFactory(session_id_store=session_id_store, backend_store=backend_...
5,318,616
def fixture_context(*fixtures: Fixture, copy_context=True) -> Dict[str, Fixture]: """ Enter a new fixture context. Any fixtures created within the `with` block will not be available outside of it. :param fixtures: Any fixtures which should be included in the context. If a fixture ...
5,318,617
async def get_mnemonic(strict=False): """Attempt to gather a mnemonic from one of the available sources First, if a mnemonic is defined in the env, use that. Next, check the config file for the secret If no mnemonic can be found, optionally raise an Exception Args: strict (bool, optio...
5,318,618
def process(callable_, *args, **kwargs): """ Submit a callable to a background process. Return an proxy object for the future return value. NOTE: Use only, if you really need control over the type of background execution. """ return _submit(callable_, 'cpu', *args, **kwargs)
5,318,619
async def test_setlist(): """Basic sanity check for setlist data.""" async with httpx.AsyncClient(timeout=CLIENT_TIMEOUT) as client: setlists = await pyvitals.async_get_setlists_url(client, keep_none=False, trim_none=False) setlists_len = [len(x) for x in setlists.values()] assert setlists_len...
5,318,620
def encode_entities(string): """ Encodes HTML entities in the given string ("<" => "&lt;"). For example, to display "<em>hello</em>" in a browser, we need to pass "&lt;em&gt;hello&lt;/em&gt;" (otherwise "hello" in italic is displayed). """ if isinstance(string, basestring): string = ...
5,318,621
def load_node_handle(fname, mode="r"): """ Read a conduit file node handle. Does not read into memory. """ if os.path.exists(fname): options = conduit.Node() options["mode"] = mode handle = conduit.relay.io.IOHandle() handle.open(fname, options=options) return han...
5,318,622
async def upload_data_generation_file( background_tasks: BackgroundTasks, doc: UploadFile = File(...), current_user: User = Depends(auth.get_current_user_and_bot) ): """ Uploads document for training data generation and triggers event for intent creation """ TrainingDataGenerationProcessor.i...
5,318,623
def histogram(name, tensor, max_bins): """ 转换直方图数据到potobuf格式 """ values = make_np(tensor) sum_sq, bucket_limit, bucket = make_histogram(values.astype(float), max_bins) hist = HistogramProto(min=values.min(), max=values.max(), num=len(values.reshape(-1)), sum=values.sum(), ...
5,318,624
def max_pool_1d(input_tensor, pool_sizes=(2), stride_sizes=(1), paddings='same', names=None): """[summary] Arguments: input_tensor {[float, double, int32, int64, uint8, int16, or int8]} -- [A Tensor representing prelayer values] Keyword Arguments: pool_size {tuple} -- [Size of kern...
5,318,625
def test_process_coa_filing(app, session): """Assert that an AR filling can be applied to the model correctly.""" from entity_filer.worker import process_filing from legal_api.models import Business, Filing # vars payment_id = str(random.SystemRandom().getrandbits(0x58)) identifier = 'CP1234567...
5,318,626
def validate_inputs(scenario_id, subscenarios, subproblem, stage, conn): """ Get inputs from database and validate the inputs :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database connection :return: """ pass # V...
5,318,627
def decompress_metadata_string_to_dict(input_string): # pylint: disable=invalid-name """ Convert compact string format (dumped, gzipped, base64 encoded) from IonQ API metadata back into a dict relevant to building the results object on a returned job. Parameters: input_string (str): compre...
5,318,628
def call_ck(i): """ Input: { Input for CK } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 (stdout) - stdout, if available ...
5,318,629
def inet_atoni(ip): """Like inet_aton() but returns an integer.""" return struct.unpack('>I', socket.inet_aton(ip))[0]
5,318,630
def predict_age_and_gender(): """Predict the gender of the faces showing in the image""" # create a new cam object cap = cv2.VideoCapture(0) while True: _, img = cap.read() # Take a copy of the initial image and resize it frame = img.copy() # resize if higher th...
5,318,631
def add_2d_bbox(bbox, axis, linewidth=0.5, color="b"): """Add bounding box to the image. Parameters ---------- bbox : tuple Tuple of the form (row, col, height, width). axis : axis object linewidth : float thickness of the overlay lines color : str matplotlib support...
5,318,632
def test_bash1(bash1, job_id1, log, tasks_json_tmpfile): """a bash task should execute properly """ # queue task enqueue(bash1, job_id1) validate_one_queued_task(bash1, job_id1) # run failing task run_code( log, tasks_json_tmpfile, bash1, '--bash_cmd thiscommandshouldfail') validate_...
5,318,633
def align_method_FRAME( left, right, axis, flex: Optional[bool] = False, level: Level = None ): """ Convert rhs to meet lhs dims if input is list, tuple or np.ndarray. Parameters ---------- left : DataFrame right : Any axis: int, str, or None flex: bool or None, default False ...
5,318,634
def send_mail(self: MonitoredTask, message: dict[Any, Any], email_stage_pk: Optional[int] = None): """Send Email for Email Stage. Retries are scheduled automatically.""" self.save_on_success = False message_id = make_msgid(domain=DNS_NAME) self.set_uid(slugify(message_id.replace(".", "_").replace("@", "...
5,318,635
def rep_unicode_in_code(code): """ Replace unicode to str in the code like '\u003D' to '=' :param code: type str :return: type str """ pattern = re.compile('(\\\\u[0-9a-zA-Z]{4})') m = pattern.findall(code) for item in set(m): code = code.replace(item, chr(int(item[2:], 16))) ...
5,318,636
def delete_bucket_on_project(current_session, project_name, bucket_name): """ Remove a bucket from a project, both on the userdatamodel and on the storage associated with that bucket. Returns a dictionary. """ response = pj.delete_bucket_on_project(current_session, project_name, bucket_name) ...
5,318,637
def redir(url, text=None, target='_blank'): """Links to a redirect page """ text = text or url html = '<a href="%(url)s" target="%(target)s">%(text)s</a>' % { 'url' : redir_url(url), 'text' : text, 'target' : target, } html = mark_safe(html) return html
5,318,638
def notifier_limit_over_checker(username, language_code, hard_limit): """ Function that takes a username and checks if they're above a hard monthly limit. This is currently UNUSED. True if they're over the limit, False otherwise. :param username: The username of the person. :param language_code: Th...
5,318,639
def lateral_steering_transform(steering, camera_position): """ Transform the steering of the lateral cameras (left, right) Parameters: steering (numpy.float): Original steering Returns: out (numpy.float): New steering """ if (camera_position == LEFT): steering += ...
5,318,640
def fv_creator(fp, df, F, int_fwm): """ Cretes frequency grid such that the estimated MI-FWM bands will be on the grid and extends this such that to avoid fft boundary problems. Inputs:: lamp: wavelength of the pump (float) lamda_c: wavelength of the zero dispersion wavelength(ZDW) (...
5,318,641
def gcs_upload_object(python_object: Any, gcs_path: str, overwrite: bool = False, verbose: bool = True) -> None: """Upload a Python object to Google Cloud Storage (using pickle to serialize the object). :param python_object: The Python object to upload (e.g. a Pandas DataFrame) :param gcs_path: The Google ...
5,318,642
def test_jobs_create(mock_url, replay_session): """Create should return JSON of the created Job.""" job_payload = {'id': 'app1'} resp_json = {'id': 'response'} exp_method = 'POST' exp_url = 'https://localhost:443/service/metronome/v1/jobs' replay_session.queue([MockResponse(resp_json, 201)]) ...
5,318,643
def analyse_104_with_line_graph(): """ This plots a line graph of experiment 104, as well as using some data from experiment 107. The x-axis will be level size and the y-axis the metrics, specifically time and maybe some others. """ data = load_compressed_pickle(get_latest_folder('../result...
5,318,644
def trento_events(): """ Random trento events. """ fig, axes = plt.subplots( nrows=3, sharex='col', figsize=figsize(.38, aspect=2.7) ) xymax = 8. xyr = [-xymax, xymax] with tempfile.NamedTemporaryFile(suffix='.hdf') as t: subprocess.run(( 'trento Pb...
5,318,645
def calc_F1_score(scores, changepoints, tolerance_delay, tuned_threshold=None, div=500, both=True): """ Calculate F1 score. If tuned_threshold is None, return the tuned threshold. Args: scores: the change scores or change sign scores changepoints: changepoints or starting points of gradual ...
5,318,646
def mul_pt_exn(pt, curve, k): """Computes point kP given point P, curve and k using Montgomery Ladder. Args: pt (tuple(int, int)): Point P. curve (tuple(int, int, int)): Curve. k (int): Multiplier. Raises: InverseNotFound: Thrown when point kP is the point at infinity. ...
5,318,647
def get_enter_room_url(): """ swagger-doc: 'schedule' required: [] req: course_schedule_id: description: '课节id' type: 'string' res: url: description: '访问地址' type: '' """ course_schedule_id = request.json['course_schedule_id'] with session_scop...
5,318,648
def get_scene_nodes(): """ Returns al nodes in current scene as GamEX nodes :return: list<gx.dcc.DCCNode> """ node_list = list() _append_children(get_root(), node_list) return node_list, len(node_list)
5,318,649
def interpolate(src_codes, dst_codes, step=5): """Interpolates two sets of latent codes linearly. Args: src_codes: Source codes, with shape [num, *code_shape]. dst_codes: Target codes, with shape [num, *code_shape]. step: Number of interplolation steps, with source and target included. For ...
5,318,650
def get_flavored_transforms(penalty, kind): """ Gets the tranformation functions for all flavored penalties. Parameters ---------- penalty: PenaltyConfig, PenaltyTuner The penalty configs/tuner whose flavored penalties we want. kind: str Which kind of flavor we want; ['adaptive...
5,318,651
def f(spam, eggs): """ :type spam: list of string :type eggs: (bool, int, unicode) """ return spam, eggs
5,318,652
def setDesignFromModel(D, m, blnSetNoneOtherwise=True): """Set the elements of a Design according to variables. Chooses between setDesignFromYik and setDesignFromYi. See those functions for more information. Args: D (Design): Design that matches the Canvas that the model was constr...
5,318,653
def GetAllowedGitilesConfigs(): """Returns the set of valid gitiles configurations. The returned structure contains the tree of valid hosts, projects, and refs. Please note that the hosts in the config are gitiles hosts instead of gerrit hosts, such as: 'chromium.googlesource.com'. Example config: { ...
5,318,654
def usage(progname): """ Print usage message and exit """ sys.stderr.write("Usage: " +progname + " [-rcv] " " <query_id> <tabsearch.outputfile>\n") sys.stderr.write(' -c class level not fold level evaluation\n') sys.stderr.write(' -r higher scores are better (for MSVN...
5,318,655
def add_effective_dates(apps, schema_editor): """ Adds effective dates to the organization addresses """ db_alias = schema_editor.connection.alias organization_address = apps.get_model('api', 'OrganizationAddress') organization_address.objects.using(db_alias).update( effective_date="20...
5,318,656
def cbsodatav3_to_gcs(id, third_party=False, schema="cbs", credentials=None, GCP=None, paths=None): """Load CBS odata v3 into Google Cloud Storage as Parquet. For given dataset id, following tables are uploaded into schema (taking `cbs` as default and `83583NED` as example): - ``cbs.83583NED_DataProper...
5,318,657
def process_chunk_of_genes(packed_args): """ Control flow of compute coverage of pangenome per species and write results """ species_id, chunk_id = packed_args[:2] if chunk_id == -1: global semaphore_for_species num_of_genes_chunks = packed_args[2] tsprint(f" MIDAS2::process_chun...
5,318,658
def test_parse_publish_qos(): """ A publish with QoS of 1 is successfully parsed. """ data = bytearray() data.extend( binascii.unhexlify(b'321700047465737400037b2274657374223a2274657374227d') ) msgs = [] c = _parsing.parse(data, msgs) assert len(data) == c assert len(msgs...
5,318,659
def plot_acf(x, lag_range, out_path, acf_function, reverse=True, figsize=(12, 5), title_fontsize=15, xlabel_fontsize=16, ylabel_fontsize=16): """ plot autocorrelation of series x :param x: series that we will perform the lag :type x: pd.Series :param lag_range: range of lag...
5,318,660
def get_Up(N=16, dt=0.1): """ INPUTS N (int): is the length of the preview horizon; dt (float): time step size; OUTPUTS Up: size [N, N] matrix; """ Up = np.tril(np.ones((N, N)), 0) * (1 / 6) for i in range(N): Up += np.diag(np.ones(N - i) * i, k=-i) / 2 Up += np.dia...
5,318,661
def forecasts_mp(configs): """ Iterate over the forecast settings for each scenario, yielding tuples that can be serialised and sent to other Python processes. Each process can then retrieve the associated :class:`Forecasts` value by calling :func:`get_forecasts_mp`. :param configs: The forecas...
5,318,662
def print_person(first, last, middle=None): """Prints out person's names This funciton prints out a person's name. It's not too useful Args: first (str): This person's first name last (str): This person's last name middle (str): Optional. This person's middle name """ middl...
5,318,663
def musica(): """[Função que toca a musica] """ try: AudioPlayer("./Interface Grafica/Tree/tree_lofi/lofi.mp3").play(True, True) except FileNotFoundError: print("A musica não pode ser reproduzida, pois ouve um erro")
5,318,664
def get_governing_regions(strict=True): """! Creates a sorted list of governing regions which may simply be federal states or intermediate regions which themselves are a real subset of a federal state and to which a certain number of counties is attributed. Governing regions are generally denoted b...
5,318,665
def _chomp_element(base, index, value): """Implementation of perl = and chomp on an array element""" if value is None: value = '' base[index] = value.rstrip("\n") return len(value) - len(base[index])
5,318,666
def write_primitive(group, name, data, ds_kwargs): """Note: No dataset chunk options (like compression) for scalar""" data_type = type(data) # Write dataset if data_type == np.ndarray: ds = group.create_dataset(name, data=data, **ds_kwargs) # enable compression for nonscalar numpy array el...
5,318,667
def measurecrime(gps, radius): """Measures crime around a given location""" latitude, longitude = gps minlat = latitude - radius maxlat = latitude + radius minlong = longitude - radius maxlong = longitude + radius baseurl = (DATABASE + WHERE + LAT + GT + str(minlat) + AND + LAT + LT + ...
5,318,668
def _weights(name, shape, mean=0.0, stddev=0.02): """ Helper to create an initialized Variable Args: name: name of the variable shape: list of ints mean: mean of a Gaussian stddev: standard deviation of a Gaussian Returns: A trainable variable """ var = tf.get_variable( name, shape, ...
5,318,669
def packed_function(function): """returns a function with a single input""" # needed in python 3.x since lambda functions are not automatically unpacked # as they were in python 2.7 if hasattr(function, '__code__'): if function.__code__.co_argcount > 1: return pack(function) retu...
5,318,670
async def read_ratings(session, archive_url, archive_timestamp, archive_content): """ Extract a movie rating from its imdb page :raise: A ScrapeError if the rating could not be extracted :return: """ try: soup = BeautifulSoup(archive_content, 'html.parser') ratings_element = sou...
5,318,671
def species_json(request, species_id): """ Return information about a species. """ raise Http404
5,318,672
def test_feathr_online_store_databricks(): """ Test FeathrClient() online_get_features and batch_get can get data correctly. """ runner = CliRunner() with runner.isolated_filesystem(): runner.invoke(init, []) os.chdir('feathr_user_workspace') client = FeathrClient() j...
5,318,673
def authorize( verbose: int, api_token: str, network_id: str, member_id: str, name: Optional[str], description: Optional[str] ) -> None: """Authorize Zerotier network member to the network.""" obj = setup_shared_network_options( verbose, api_token, network...
5,318,674
def generate_nonce(): """ Generates nonce for signature Returns: nonce (int) : timestamp epoch """ return int(time.time() + 100)
5,318,675
def test_add_increases_count(db_multiple_experiments, tmpdir): """Test DataBase.add() affect on DataBase.count().""" # GIVEN a db with 9 experiments # WHEN another experiment is added db = db_multiple_experiments current_count = db.count() code_dir = tmpdir.mkdir("new_exp") db.add(Experiment...
5,318,676
def dense(x, inp_dim, out_dim, name = 'dense'): """ Used to create a dense layer. :param x: input tensor to the dense layer :param inp_dim: no. of input neurons :param out_dim: no. of output neurons :param name: name of the entire dense layer.i.e, variable scope name. :return: tensor with sh...
5,318,677
def test_component_normalisation(my_component): """Tests the normalisations of all densities evaluated for a component """ ssps, cube, gc1 = my_component v_edg = np.linspace(-900, 900, 20) dv = v_edg[1] - v_edg[0] na = np.newaxis # check p_t a = gc1.get_p_t(density=False, light_weighted...
5,318,678
def read_observation_time_range(observation_id): """Get the time range of values for a observation. Parameters ---------- observation_id: string UUID of associated observation. Returns ------- dict With `min_timestamp` and `max_timestamp` keys that are either dt.dat...
5,318,679
def test_regression_issue_163(tmpdir): """https://github.com/emcconville/wand/issues/163""" unicode_char = b'\xce\xa6'.decode('utf-8') with Drawing() as draw: with Image(width=500, height=500) as image: draw.font_size = 20 draw.gravity = 'south_west' draw.text(0, ...
5,318,680
def compute_mean_image(batches): """Computes the mean image given a list of batches of images. Args: batches (List[ObjectID]): A list of batches of images. Returns: ndarray: The mean image """ if len(batches) == 0: raise Exception("No images were passed into `compute_mean_image`.") sum_image_i...
5,318,681
def get_sevt(r: Request, resp: Response): """ SEVT web server route for GET request. :param r Request object, provides access to method, headers & cookies: :param resp Response Object used for modification of status code: :return returns the content of the internal resources response...
5,318,682
def mse(actual, predicted): """ https://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html#cost-function MSE = the mean of (actual_outcome - predicted_outcome) squared """ return np.mean(np.power(actual - predicted, 2))
5,318,683
def cleanup(worker=global_worker): """Disconnect the driver, and terminate any processes started in init. This will automatically run at the end when a Python process that uses Ray exits. It is ok to run this twice in a row. Note that we manually call services.cleanup() in the tests because we need to start an...
5,318,684
def get_type_hints(fn): """Gets the type hint associated with an arbitrary object fn. Always returns a valid IOTypeHints object, creating one if necessary. """ # pylint: disable=protected-access if not hasattr(fn, '_type_hints'): try: fn._type_hints = IOTypeHints() except (AttributeError, TypeE...
5,318,685
def setJointsTrajectoryFromPoints(phase, q, dq, ddq, timeline, overwrite=True): """ Define the joints position, velocity and acceleration trajectories as a linear interpolation between each points Also set the initial / final values for q, dq and ddq to match the ones in the trajectory :param phase: ...
5,318,686
def test_levenshtein_roman(): """Test Levenshtein - roman.""" cfg.glob.logger.debug(cfg.glob.LOGGER_START) # ------------------------------------------------------------------------- upper_limit: int = 1200 upper_limit_roman: str = roman.toRoman(upper_limit) for prev in range(upper_limit): ...
5,318,687
def notebook_to_md(notebook): """Convert a notebook to its Markdown representation, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(ipynb_writes(notebook).encode('utf-8')) tmp_file.close() pandoc(u'--from ipynb --to markdown -s --atx-headers --wrap=preserve --pre...
5,318,688
def is_windows() -> bool: # pragma: no cover """ Returns True if the host operating system is Windows. """ return os.name == "nt"
5,318,689
def topsorted(outputs): """ Topological sort via non-recursive depth-first search """ assert isinstance(outputs, (list, tuple)) marks = {} out = [] stack = [] # pylint: disable=W0621 # i: node # jidx = number of children visited so far from that node # marks: state of each node,...
5,318,690
def open_resource(resource, mode='r'): """Find the resource file (see find_resource), open it, and return a file handle. Parameters ---------- resource : str Resource path; can be path relative to CWD, path relative to PISA_RESOURCES environment variable (if defined), or a package ...
5,318,691
def merge_small_enclosed_subcavs(subcavs, minsize_subcavs = 50, min_contacts = 0.667, v = False): """ The watershed algorithm tends to overspan a bit, even when optimizing seeds. This function aims at identifying small pockets (< minsize_subcavs) that are heavily in contact with other subcavs (> min_contacts) Thes...
5,318,692
def is_py3(file_path): """Check if code is Python3 compatible.""" # https://stackoverflow.com/a/40886697 code_data = open(file_path, "rb").read() try: ast.parse(code_data) except SyntaxError: return False return True
5,318,693
def test_set_agencies_singlesub(): """ Test that we can properly derive agency info from the metadata and add it to the XML if there is a subagency. """ agencies_info = [ { 'name': 'Justice Department', 'parent_id': None, 'url': ('https://www.federalregister.gov/...
5,318,694
def getDate(): """获得时间""" return time.localtime()
5,318,695
def modify_rsp(rsp_entries, other_rel_path, modify_after_num): """Create a modified rsp file for use in bisection. Returns a new list from rsp. For each file in rsp after the first modify_after_num files, prepend other_rel_path. """ ret = [] for r in rsp_entries: if is_path(r): if modify_after_...
5,318,696
def wordEncrypt(word): """ Encrypt a word into list of keys using the cipher in file_cipher. Definition ---------- def wordEncrypt(word): Input ----- word string Output ------ list with numeric keys Examples ...
5,318,697
def test_types(mocker: MockerFixture) -> None: """ Test that native Python types can be used in queries. """ requests = mocker.patch("datajunction.sql.dbapi.cursor.requests") requests.post().headers.get.return_value = "application/json" url = URL("http://localhost:8000/") headers = { ...
5,318,698
def stop_service(name): """ Start service with given name. """ subprocess.run(["systemctl", "stop", name], check=True)
5,318,699