content
stringlengths
22
815k
id
int64
0
4.91M
def collect_inference_outputs(inference_output_uri): """ collect information related to output of inference. """ sagemaker_output_file = "unlabeled.manifest.out" prediction_output_uri = inference_output_uri + sagemaker_output_file prediction_output_s3 = S3Ref.from_uri(prediction_output_uri) ...
5,294,800
def run_serial(the_config, compdb): """Executes a serial run, one command after another""" commands = compdb_parser.parse_compdb(compdb) facade_lib.apply_checkers_for_commands(commands, the_config) # TODO The global state of summary is hard to test return summary.get_summary()
5,294,801
def append_new_line(file_name, text_to_append): """Append given text as a new line at the end of file""" with open(file_name, "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) ...
5,294,802
def get_classname(hwnd): """ @return A empty string if failed. """ try: return win32gui.GetClassName(hwnd) except Exception: pass return ''
5,294,803
def xrecons_single_sample(X, read_attn_params, write_attn_params, args): """ Create a single image containing the output canvas at each of the T time steps. Parameters: ----------- X : X is a batch of image canvases. (T, batch_size, H, W, C) read_attn_params: Tuple containing parameters needed to draw rea...
5,294,804
def nanprod(a, axis=None, dtype=None, out=None, keepdims=False): """Returns the product of an array along given axes treating Not a Numbers (NaNs) as zero. Args: a (cupy.ndarray): Array to take product. axis (int or sequence of ints): Axes along which the product is taken. dtype: Da...
5,294,805
def undersc_str2dt(undersc): """Converts the format with underscores to a datetime instance Args: undersc(str): time in underscores-format Returns: `datetime`: datetime instance """ (mydate, mytime) = undersc.split("_") ymd = mydate.split("-") ymd = [int(i) for i in ymd] ...
5,294,806
def test_delta_sigma_consistency(): """This testing function guarantees consistency between the delta_sigma function and the surface_density_in_annulus and surface_density_in_cylinder functions, effectively freezing the internal calculation of delta_sigma. """ num_centers, num_ptcl = 100, 500 wi...
5,294,807
def spectrogram(segments, opt_log10=False, opt_show=True): """ https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html """ x = seg.flatten(segments) fs = segments.frame_rate print(len(x)/fs, len(x), fs) t, f1, t1, Zxx = transform(segments, opt_log10=op...
5,294,808
def console_to_str(s: bytes) -> str: """From pypa/pip project, pip.backwardwardcompat. License MIT.""" try: return s.decode(console_encoding, "ignore") except UnicodeDecodeError: return s.decode("utf_8", "ignore")
5,294,809
def make_animation_all_channels(satellite: Satellite, example_index: int): """ Make animation of all channels An animation is made over time. Subplots show the different satellite channels Args: satellite: satellite data example_index: which example to use Returns: plotly figure ...
5,294,810
def convert_path_extension(path, conversion = '.png'): """Converts a path extension to a different one (as provided).""" # Get the image name and create the final filepath. filename, _ = os.path.splitext(path) save_path = filename + conversion # Append the new path to the return list. return save_pat...
5,294,811
def find_clusters(ClusterTeams): """ Finds the optimal number of clusters using KMeans. :param ClusterTeams: DataFrame. The data to find the number of clusters of. """ from yellowbrick.cluster import KElbowVisualizer from sklearn.cluster import KMeans kmeans = KMeans(random_state =...
5,294,812
def mgmt_lock(timeout=MGMT_LOCK_TIMEOUT, key_args=(), key_kwargs=(), wait_for_release=False, bound_task=False, base_name=None): """ Decorator for runtime task locks. This means that task will run, but will wait in a loop until it acquires a lock or will fail if timeout is reached. """ ...
5,294,813
def common_status_page(userid, status): """ Raise the redirect to the script returned by common_status_check() or render the appropriate site status error page. """ if status == "admin": return errorpage(0, errorcode.admin_mode) elif status == "local": return errorpage(0, errorco...
5,294,814
def get_value(rgb, animated=False): """ Obtains pixel value if it is enabled. Color is not supported yet here. :param rgb: :param animated: It is a WTF from SP1. If I do animation it requires me to invert the values... :return: """ if rgb[0] > 0 or rgb[1] > 0 or rgb[2] > 0: return "...
5,294,815
def get_ldap_conn(host, username, password, reuse=None): """ Returns an LDAP connection """ if reuse: ldap_conn = reuse else: ldap_conn = initialize("ldap://"+host) try: ldap_conn.bind_s(username, password) except Exception as err_msg: return False, 'Error: {}...
5,294,816
def make_profile_middleware( app, global_conf, log_filename='profile.log.tmp', limit=40): """ Wrap the application in a component that will profile each request. The profiling data is then appended to the output of each page. Note that this serializes all requests (i.e., removing c...
5,294,817
def dup_children(my_task, file_info, children, copy_bfid, fcc): """ Create duplicates of package children in FC DB for copy of package file copy_bfid. It is metadata operation, no data copied. Get children of this package identified by file_info Children information is used to create children copies in...
5,294,818
def encode_matrix_fbs(matrix, row_idx=None, col_idx=None): """ Given a 2D DataFrame, ndarray or sparse equivalent, create and return a Matrix flatbuffer. :param matrix: 2D DataFrame, ndarray or sparse equivalent :param row_idx: index for row dimension, Index or ndarray :param col_idx: index for col...
5,294,819
def get_facets(query, params, limit=10, referrer=None): """ High-level API for getting 'facet map' results. Facets are high frequency tags and attribute results that can be used to further refine user queries. When many projects are requested sampling will be enabled to help keep response times low...
5,294,820
def markChangedFiles(db, cs): """ Look for files that have been removed from a trove or restored to a trove, and mark those changes in the database. This is used to record local changes. """ for trvCs in cs.iterNewTroveList(): ver = trvCs.getOldVersion() if ver.onLocalLabel(): ...
5,294,821
def mAP(pred, target, cutoff=.5): """ Computes the Average Precision of the semantic segmentation Arguments: pred: predicted segmentation output by network target: binary segmentation targets cutoff: prediction cutoff for foreground vs background """ with torch.no_grad(): ...
5,294,822
def get_linkage_matrix(run_parameters, linkage_matrix, indicator_matrix): """ read bootstrap temp_h* and temp_p* files, compute and add the linkage_matrix. Args: run_parameters: parameter set dictionary. linkage_matrix: connectivity matrix from initialization or previous call. Returns: ...
5,294,823
def create_User(name, email): """Create a new User. Args: name ([string]): The name of the User email ([string]): An email Raises: exceptions.DatabaseError: if an errors occurs during SQL execution Returns: [User]: A User model """ LOGGER.info("Create a User %...
5,294,824
def log(level, msg, *args, **kwargs): """Log message at the given level. Parameters ---------- level : Union[int,str] The logging level value. msg: str The message. """ level = _logging._checkLevel(level) get_logger().log(level, _detailed_msg(msg), *args, **kwargs)
5,294,825
def load_yaml_config(filepath): """Load Krake base configuration settings from YAML file Args: filepath (os.PathLike, optional): Path to YAML configuration file Raises: FileNotFoundError: If no configuration file can be found Returns: dict: Krake YAML file configuration "...
5,294,826
def test_snake_request_on_timeout(): """ Test SnakeRequest: timeout """ # pylint: disable=no-member, protected-access def kill_child_processes(self, *args, **kwargs): # pylint: disable=unused-argument self.abcd = args def _on_timeout(*args, **kwargs): # pylint: disable=unused-argume...
5,294,827
def insert_pms(payloads, app_name): """Summary Args: payloads (TYPE): Description Returns: TYPE: Description """ responses_list = [] for payload in payloads: print("inserting", payload) response = knackpy.record( payload, obj_k...
5,294,828
def max_cum_build_rule(mod, g, p): """ **Constraint Name**: GenNewLin_Max_Cum_Build_Constraint **Enforced Over**: GEN_NEW_LIN_VNTS_W_MAX_CONSTRAINT Can't build more than certain amount of capacity by period p. """ return mod.GenNewLin_Capacity_MW[g, p] \ <= mod.gen_new_lin_max_cumulativ...
5,294,829
def preprocess2(lowercase, break_hashtags, replacements, line): """ returns lowered line """ try: tweet = json.loads(line) text = tweet['text'] except: tweet = dict() text = line.decode('utf8') # Break hash sign: #hashtag -> # hashtag if break_hashtags: text ...
5,294,830
def get_vrf_description(device, vrf): """Gets description of configured VRF. Args: device (Device): This is the device object of an NX-API enabled device using the Device class within device.py vrf: case-sensitive VRF (because 'show run section $VRF' is being used) Returns: ...
5,294,831
def normalize(tensor, mean=NORMALIZE_MEAN, std=NORMALIZE_STD, inplace=False): """ Normalizes image tensor using VGG mean and std. Assumes image has [0,1] values. Accepts CxHxW or BxCxHxW images. """ from torch import as_tensor if not inplace: tensor = tensor.clone() dtype = ten...
5,294,832
def _scale_factory(scale, axis, *args, **kwargs): """If `scale` is a `~matplotlib.scale.ScaleBase` instance, nothing is done. If it is a registered scale name, that scale is looked up and instantiated.""" if isinstance(scale, mscale.ScaleBase): if args or kwargs: warnings.warn(f'Igno...
5,294,833
def clean_job_task(job_id, db_name=config.PG_JOB_TASK_DB_NAME): """This will directly clean job and related task from db""" deletion_command = f"""DELETE FROM "Task" WHERE "jobId"='{job_id}';DELETE FROM "Job" WHERE "id"='{job_id}';""" client = postgres.PGClass(config.PG_HOST, db_name, config.PG_USER, config...
5,294,834
def setup_read_only_checkbox(checkbox): """Creates checkbox that cannot be modified. Args: checkbox (QtWidgets.QCheckBox): Checkbox UI element. """ checkbox.setAttribute(Qt.WA_TransparentForMouseEvents, True) checkbox.setFocusPolicy(Qt.NoFocus)
5,294,835
def call_qualimap(bamfile: Path, outdir: Path) -> Path: """ Makes a system call to Qualimap with the provided .bam file. Finds and returns the output file (genome_results.txt) :param bamfile: .bam file generated via BBmap.sh :param outdir: output directory for Qualimap output :return: path to Qualim...
5,294,836
def write_merged_bed(probes, bedtools, temp_merged_bed): """Given correctly formatted probes, write the merged bed file""" #First, create merged bed file write_probes=open(temp_merged_bed, 'w') merge_probes_args = [x for x in bedtools.split(' ')]+['bedtools', 'merge', '-i', probes] subprocess.call(m...
5,294,837
def get_fstab_contents(agent_id): """ Get contents of fstab file from a node. (superadmin privilege required) If agent-id is not specified, manager's fstab contents will be returned. """ with Session() as session: try: resp = session.VFolder.get_fstab_contents(agent_id) ...
5,294,838
def _pos_phrases(tokens, preprocess): """Extract phrases from a text using POS Tagging-derived rule-based approach. Args: tokens (list of str): A list of semantically-ordered tokens. preprocess (callable): A function that pre-processes the extracted phrases. Returns: li...
5,294,839
def destroy_result(cli_runner: CliRunner) -> Generator[Result, None, None]: """Execute `runway destroy`.""" yield cli_runner.invoke(cli, ["destroy"], env={"CI": "1"}) # pylint: disable=unexpected-keyword-arg # (CURRENT_DIR / "cdk.out").unlink(missing_ok=True) shutil.rmtree(CURRENT_DIR / "cdk.out", i...
5,294,840
def create_controller(): """ 1. Check the token 2. Call the worker method 3. Show results """ minimum_buffer_min = 3 if views.ds_token_ok(minimum_buffer_min): # 2. Call the worker method args = { 'account_id': session['ds_account_id'], 'base_path': ses...
5,294,841
def reset(self: JObject) -> None: """Reset this object to it's unmodified status. """ if not self.__class__.cdef.jconf.reset_all_fields: raise JSONClassResetNotEnabledError() if self.is_new: raise JSONClassResetError() for k, v in self.previous_values.items(): setattr(self, k...
5,294,842
def writeValidUtf8(in_filename, out_filename, skipOrReplace = 'replace'): """ Read the input file bytes and write it to the output file as UTF-8. When skipOrReplace is skip, drop the invalid bytes, else replace them with U+FFFD. """ # Read the input file into memory as bytes. if not os.path.exists(in_file...
5,294,843
def total_seconds(td): """Since ``timedelta.total_seconds()`` is new in 2.7""" return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
5,294,844
def test_handle_call_with_return( decoy: Decoy, call_stack: CallStack, stub_store: StubStore, subject: CallHandler, ) -> None: """It return a Stub's configured return value.""" spy_call = SpyCall(spy_id=42, spy_name="spy_name", args=(), kwargs={}) behavior = StubBehavior(return_value="hello ...
5,294,845
def review_table(queryset: QuerySet, fields_str: str) -> dict: """ This tag displays a QuerySet of reviews as a table :param queryset: The set of Reviews to display :type queryset: QuerySet :param fields_str: The fields to get for each review :type fields_str: str :r...
5,294,846
def get_sparsity_penalty(nnet, inputs, sparsity, mode="mean", deterministic=False): """ returns the sparsity penalty on network activations combined as a sum """ assert mode in ("mean", "l1") rho = sparsity penalty = 0 eps = 0.0001 # for numerical stability f...
5,294,847
def encode_files(path_to_raw: str, path_to_encoding: str, output_folder: str, initial_file_ending: str = ".py", file_ending: str = "py_enc") -> None: """ This method applies the subword-nmt to any file in a directory. A copy of the directory with the encoded files will be build under output...
5,294,848
def generate_config(context): """ Entry point for the deployment resources. """ properties = context.properties name = properties.get('name', context.env['name']) project_id = properties.get('project', context.env['project']) zone = properties.get('zone') # Network formatting if 'network' ...
5,294,849
def test_quiet(tmp_path): """Test query of global quiet option.""" runner = CliRunner() os.chdir(tmp_path) result = runner.invoke(cli, ["quiet-value"]) assert result.exit_code == 0 assert not bool(int(result.output)) result = runner.invoke(cli, ["-q", "quiet-value"]) assert result.exit_c...
5,294,850
def check_refint(config_folder=None, output=None): """ Check referential integrity. This command scans the graph store to verify that all references to resources within the repository are effectively pointing to existing resources. For repositories set up with the `referential_integrity` option ...
5,294,851
def test_response_two(testserver): """test response one""" cli = JsonWspClient(testserver.url, ['ClacService']) numbers_list = [[1, 2, 3, 4, 5], [10, 20, 5, 7], [12, 4, 32, 6], [40, 2]] for numbers in numbers_list: with cli.sum(numbers=numbers) as res: assert res.result == sum(number...
5,294,852
def tznow(time_zone="Europe/London"): """ # to get the list of time zones: #from dateutil.zoneinfo import get_zonefile_instance #print(list(get_zonefile_instance().zones)) # over 500 timezones """ my_tz = tz.gettz(time_zone) # or =tz.gettz() for local zone of computer return datetime.date...
5,294,853
def create_table(): """Создает пустую таблицу для тестов.""" id_ = base.create_id(ports.USD, ports.USD) return usd.USD(id_)
5,294,854
def assert_allclose(actual: numpy.ndarray, desired: numpy.ndarray, atol: numpy.float64): """ usage.scipy: 81 """ ...
5,294,855
def _prepare_ansible_paths() -> None: """Configure Ansible environment variables.""" library_paths: List[str] = [] roles_path: List[str] = [] if 'ANSIBLE_ROLES_PATH' in os.environ: roles_path = os.environ['ANSIBLE_ROLES_PATH'].split(':') if 'ANSIBLE_LIBRARY' in os.environ: library_p...
5,294,856
def load_yaml(yaml_file_path, logger): """ Read a yaml file from the filesystem and return it as a dict Returns 'None' if the file is not found :param yaml_file_path: string - Location of the yaml file to be read :param logger: Logger - Logger for logging events """ if file_exists(yaml_file...
5,294,857
def available_years() -> List[int]: """List available years with datasets.""" return [2012, 2013, 2014, 2015, 2016, 2017, 2018]
5,294,858
def to_float (a_data,a_cols) : """ Convert column data type to float or numeric Always use [] for a_cols """ a_data[a_cols] = __pd.to_numeric(a_data[a_cols])
5,294,859
def rotational_groups(rxn, key1, key2, dummy=False): """ Obtain the rotational groups for a given rotational axis :param rxn: a hydrogen migration Reaction object :param zma: a z-matrix; if passed in, the linear atoms will be determined from this; otherwise they will be determined heuristically fro...
5,294,860
def kraken2_search_reads(kraken2_exc, genome_dir, reads, outprefix, threads=1, logger=lambda x: None): """Use Kraken2 to make a fast pass report on reads. Write report to outfile.""" reads = abspath(reads) cmd = ( f'{kraken2_exc} ' f'--db {join(genome_dir, KRAKEN2_PATH)} ' f'--thread...
5,294,861
def main(*wtf: Any, **kwwtf: Any) -> Any: """ 入口函数。该函数用于在允许直接运行的同时,兼容 GCP Cloud Function/AWS Lambda 等云函数平台。 :return: 由检测到的平台决定 """ config: Dict[str, Optional[ConfigValue]] = initialize_config(CONFIG_SCHEMA) fill_config(config) # 搭积木;手动建立各个类的实例,并注入依赖 program = Program(ProgramUtils(PureU...
5,294,862
def plot_ecdf_all_states(df_mape): """Function for ECDF plots for all states Args: df_mape (pd.DataFrame): The dataframe with MAPE values for every model, region Returns: mpl.Figure, [mpl.Axes] : The figure and axes objects """ fig, axs = plt.subplots(figsize=(21, 6*15), nrows=15, ...
5,294,863
def delete_products(wishlist_id, product_id): """ Delete an Product """ app.logger.info( "Request to delete product with id: %s from wishlist with id: %s", product_id, wishlist_id) product = Product.find(product_id) if product: product.delete() return make_response("", status...
5,294,864
async def http_call(url, method, data=None, headers=None): """ Performs an http request Args: url (str): The URL to send the request to method (str): The HTTP method to use data (dict): The data to send with the request headers (dict): The headers to send with the request ...
5,294,865
def new_flight(app, init_db, new_airplane): """Fixture to create a new flight""" new_airplane.save() flight = { "id": str(uuid.uuid4()), "airplane_id": new_airplane.id, "flight": 'FL111', "check_in": datetime.datetime(2019, 9, 10, 0, 0), "destination": 'Chicago', ...
5,294,866
def tabulate(start, slots, time_context=None): """Takes a list of slots and converts it into a week schedule table. Args: start: The aware datetime representing the start of the schedule. May be any timezone. slots: The (filled, ordered, annotated) list of timeslots to tabulate. ...
5,294,867
def cached(user_function=None, max_size=None, ttl=None, algorithm=CachingAlgorithmFlag.LRU, thread_safe=True): """ @cached decorator wrapper :param user_function: The decorated function, to be cached :param max_size: The max number of items can be held in the cache :param ttl: Time-To-Live ...
5,294,868
def usage(): """Print setup.py usage. """ print "SYNOPSIS" print " python setup.py <command>" print print "DESCRIPTION" print " mmLib build/install program based on the Python" print " distutils package. This setup.py script has several" print " features not found in most...
5,294,869
def test_atomic_time_max_inclusive_4_nistxml_sv_iv_atomic_time_max_inclusive_5_5(mode, save_output, output_format): """ Type atomic/time is restricted by facet maxInclusive with value 23:59:59. """ assert_bindings( schema="nistData/atomic/time/Schema+Instance/NISTSchema-SV-IV-atomic-time-max...
5,294,870
def add_comment(blog_id, commenter, comment_content): """ add a comment to a blog post :param blog_id: :param commenter: :param comment_content: :return: """ target_post_key = ndb.Key('Post', blog_id) target_post = target_post_key.get() json_comments = target_post.comments c...
5,294,871
def status_handler(func): """Register the status response handler.""" def register_status(instance_func, address): # This registers all messages for a device but only triggers on # status messages if they return within the TIMEOUT period address = Address(address) subscribe_topi...
5,294,872
def check_all_categories(categories) -> Tuple[List, List, List]: """ Check all categories in ``categories``. Parameters ---------- categories: List A list of categories Returns ------- Tuple[List, List, List] A tuple consisting of valid biolink categories, invalid bioli...
5,294,873
def test_has_recursion(): """ Check has_left_recursion """ grammar = ContextFreeGrammar({'a', 'b'}, {'A', 'B', 'C'}, 'A', {'A': ['BC'], 'B': ['C'], 'C': ['']}) assert not grammar.has_left_recursion() simple_grammar = ContextFreeGrammar({}, {'A'}, 'A', {'A': ['A']}) assert simple_grammar.has_...
5,294,874
def get_stat_type(df, stat_type): """ Get statistics from a data frame for the given type if DataFrame contains that column :param df: DataFrame to get stats from :param stat_type: stat type to look for (i.e. Age, Gender) :return: No return """ if stat_type == 'Age': if df.get('Age')...
5,294,875
def typographeur(text, fix_parenthesis=True, fix_colon=True, fix_exclamation=True, fix_interrogation=True, fix_semicolon=True, fix_ellipsis=True, fix_point_space=True, fix_comma_space=True, fix_double_quote=True, fix_a...
5,294,876
def get_triggered(categories): """Returns any of the categories exceeding blocking threshold.""" triggered = [] for x in BLOCKED_CATEGORIES: for category in categories: if category.name.startswith(x) and category.confidence > BLOCKED_CATEGORIES[x]: triggered.append((categ...
5,294,877
def find_best_peak( values: torch.Tensor, ) -> tuple[Optional[PositiveInt], Optional[float]]: """Takes a Tensor of values (with 1 dimension), and finds the index of the best peak If peak finding fails, (None, None) is returned. Parameters ---------- values : torch.Tensor 1-D tensor of v...
5,294,878
def delete_records(request): """Deletes all records of model.""" model_id = request.matchdict['model_id'] try: records = request.db.delete_records(model_id) for record in records: request.notify('RecordDeleted', model_id, record['id']) except ModelNotFound: request.er...
5,294,879
def coordinates_contain_point(coordinates, point): """ This function uses `Crossing number method` (http:#geomalgorithms.com/a03-_inclusion.html) to check whether a polygon contains a point or not. For each segment with the coordinates `pt1` and `pt2`, we check to see if y coordinate of `point` is b...
5,294,880
def handle_other(token: Tok) -> Iterator[str]: """ Return a standard placeholder for the token kind """ yield "[" + TOK.descr[token.kind] + "]"
5,294,881
def obstruction(info_dict): """ Obstruction due to M2 """ # Multiply by 1.05 to take the arms into account info_dict["obstruction"] = ( info_dict["M2_factor"] * info_dict["D_M2"] ) ** 2.0 / info_dict["D_M1"] ** 2.0 return info_dict
5,294,882
def readArduinoData(): """ DOCSTRING: this is the function for reading data from the arduino return : function will return a 3xn matrix containg RGB data and averaged 1D array """ # here finds the port which arduino connected to data = [] PORT = 0 while True: try: ...
5,294,883
def int_sin_m(x: float, m: int) -> float: # pragma: no cover """Computes the integral of sin^m(t) dt from 0 to x recursively""" cosx = cos(x) sinx = sin(x) start = m % 2 res = x if start == 0 else 1 - cosx for p in range(start + 1, m, 2): res = p / (p + 1) * res - cosx * sinx**p / (p + ...
5,294,884
def sendmail(subject, message, to_addr): """Web环境下发送邮件""" #: from_addr建议设置发件人邮箱,否则基本会被拦截或进入垃圾邮箱 from_addr = "picbed@{}".format(request.host) from_name = g.cfg.email_from_name or g.site_name #: 关闭通过本地服务器发送邮件 no_local = g.cfg.email_nolocal if is_true(no_local): res = dict(code=1) e...
5,294,885
def test_stochatreat_only_misfits(probs): """ Tests that overall treatment assignment proportions across all strata are as intended when strata are such that there are only misfits and the number of units is sufficiently large -- relies on the Law of Large Numbers, not deterministic """ N = ...
5,294,886
def test_oscan_correl(): """Test the OscanCorrelTask""" task = bias.OscanCorrelTask() if RUN_TASKS: task.run(superbias=None, **RUN_OPTIONS)
5,294,887
def load(filename): """Load image file in .b16 format as used by PCO CamWare and return image data as numpy array. """ # read image file imgfile = open(filename, 'rb') # read binary buf = imgfile.read() imgfile.close() # read header # 32 bit values (long) header = struct.u...
5,294,888
def stanza_factory(xmlnode, stream = None): """Creates Iq, Message or Presence object for XML stanza `xmlnode`""" if xmlnode.name=="iq": return Iq(xmlnode, stream = stream) if xmlnode.name=="message": return Message(xmlnode, stream = stream) if xmlnode.name=="presence": return Pr...
5,294,889
def _request_sts_credentials(billing_account_id, options): """ Request STS Credentials to get access to the billing account. With the assumed role, this script will be able to traverse over the member accounts in the AWS Organization. Args: billing_account_id (str): The Billing/Root AWS Acc...
5,294,890
def build(c, opts=None, language=None, source=None, target=None, nitpick=False): """ Build the project's Sphinx docs. """ if opts is None: opts = "" source = source or c.sphinx.source target = target or c.sphinx.target if language: ...
5,294,891
def sandbox(): """ just for testing """ x = tf.Variable(3, name='x') y = tf.Variable(4, name='y') f = x * x * y + y + 2 with tf.Session() as sess: init = tf.global_variables_initializer() # node to initialize the rest init.run() # Run the initializer for all variables ...
5,294,892
def read_config_file(given_cfg_file=None): """Return a dict of items read from a config file. If given_cfg_file is None, uses one of the default config file locations. """ cfg_file = None if given_cfg_file: cfg_file = given_cfg_file else: if os.path.exists(DEFAULT_CONFIG_FILE): ...
5,294,893
def get_cache_response_headers( response: Response, *, max_age: int ) -> typing.Dict[str, str]: """Return caching-related headers to add to a response.""" assert max_age >= 0, "Can't have a negative cache max-age" headers = {} if "Expires" not in response.headers: headers["Expires"] = http_...
5,294,894
def parse_response(response): """ :param response: output of boto3 rds client describe_db_instances :return: an array, each element is an 3-element array with DBInstanceIdentifier, Engine, and Endpoint Address Example: [ ['devdb-ldn-test1', 'mysql', 'devdb-ldn-test.cjjimtutptto.eu-we...
5,294,895
def main( steps: List[str], dry_run: bool = False, force: bool = False, private: bool = False, grapher: bool = False, backport: bool = False, exclude: Optional[str] = None, dag_path: Path = paths.DAG_FILE, ) -> None: """ Execute all ETL steps listed in dag.yaml """ if gra...
5,294,896
def is_linear(x, y): """ Returns True if molecule is linear (largest eigenvalue almost equivalent to second largest) """ x = x - np.mean(x,axis=0) y = y - np.mean(y,axis=0) N = x.shape[0] L, Q = sorted_eigh(build_F(x, y)) if L[0]/L[1] < 1.01 and L[0]/L[1] > 0.0: return True ...
5,294,897
def instantiate_me(spectrograph, par, **kwargs): """ Instantiate the FluxSpec subclass appropriate for the provided spectrograph. The class must be subclassed from FluxSpec. See :class:`FluxSpec` for the description of the valid keyword arguments. Args: spectrograph : Spectrograph or str ...
5,294,898
def save_and_next_audio(event): """ Binding the submit button to <Return> key """ save_annotations(CURRENT_INDEX) next_audio_update_index() play_audio(CURRENT_INDEX)
5,294,899