content
stringlengths
22
815k
id
int64
0
4.91M
def _GetVgInfo( name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo): """Retrieves information about a LVM volume group. """ # TODO: GetVGInfo supports returning information for multiple VGs at once vginfo = info_fn([name], excl_stor) if vginfo: vg_free = int(round(vginfo[0][0], 0)) vg_size = i...
5,292,000
def ca_set_container_policy(h_session, h_containerber, policy_id, policy_val): """Sets a policy on the container. NOTE: With per partition SO this method should generally not be used. Instead ca_set_partition_policies should be used :param int h_session: Session handle :param h_containerber: The c...
5,292,001
def test_apply_filter(test_file, filter_type, low_cutoff_freq, high_cutoff_freq, order): """ Test the Buttenworth filters. """ # apply filter apply_filter(test_file, filter_type, low_cutoff_freq, high_cutoff_freq, order) # check result fname = "{0}_augmented_{1}_pass_filtered.wav".format(te...
5,292,002
def crop_xyz_grid_by_extents(xyzgrid,extents): """ crop grid in xy plane xyzgrid: Dataframe with x,y,z columns or ARRAY with first 3 columns being x,y,z coordinates extents: (xmin,ymin,xmax,ymax) returns: cropped Dataframe """ if type(xyzgrid) == np.array: xyzgridnew = pd.DataFrame(xyzgrid,columns=...
5,292,003
def test_sum_hessian_should_fail(problem): """Test sum_hessian, should fail. Args: problem: test problem """ with raises(ValueError): test_sum_hessian(problem)
5,292,004
def _bytes_through_tmp_image(arr): """Retrieve binary blob for a numpy array image""" mimetype = 'tiff' arr_min = numpy.min(arr) arr_max = numpy.max(arr) # if (arr_max > 1) & (arr_max <= 255): # arr = arr / 255 # numpy.uint8(arr) print "MIN:" print numpy.min(arr) print "MAX:" ...
5,292,005
def _create_machine_onapp(conn, public_key, machine_name, image, size_ram, size_cpu, size_disk_primary, size_disk_swap, boot, build, cpu_priority, cpu_sockets, cpu_threads, port_speed, locat...
5,292,006
def load_game_genres(): """Link genres of games into a middle table.""" print "Game Genres" VgGen.query.delete() with open('seed_data/ign.csv') as csvfile: game_data = reader(csvfile, dialect='excel') next(game_data) for row in game_data: title = row[2] platform = row[4] genres = row[6] genre...
5,292,007
def rand_5() -> int: """ Generates a single, randomly generated 5-digit number. Returns: The generated 5-digit number. """ return random.randrange(100000)
5,292,008
def GVizGetLayoutStr(*args): """ GVizGetLayoutStr(TGVizLayout const & Layout) -> TStr Parameters: Layout: TGVizLayout const & """ return _snap.GVizGetLayoutStr(*args)
5,292,009
def discard_and_merge_types_select_most_common_n(dataset: pd.DataFrame, most_common_n: int = 20) -> pd.DataFrame: """ It is possible that the negative example creation suffers due to a long tail distribution of types. - Can we merge some of the types? - Using name based matching? Eg. ...
5,292,010
def iou(box_group1, box_group2): """ Calculates the intersection over union (aka. Jaccard Index) between two boxes. Boxes are assumed to be in corners format (xmin, ymin, xmax, ymax) Args: - box_group1: boxes in group 1 - box_group2: boxes in group 2 Returns: - A numpy array of shape (len(...
5,292,011
def perform_DQN(agent, episodes, iterations, path, batch_size=4, C=30, randomize_theta=False): """ :param agent: the RL agent :param batch_size: size of minibatch sampled from replay buffer :param C: network update frequency :return: agent, and other information about DQN """ avg_losses = []...
5,292,012
def parse(davartext: str, debug: bool = False) -> arpeggio.NonTerminal: """Parses a text string in davar into a list of davar Statements Parameters ---------- davartext : str A text string written in davar debug : bool, optional If true, prints debug statements as davartext is parse...
5,292,013
def freeze(data): """ :param data: Anything serializable as JSON :return: An immutable and hashable version of `data`. Mappings are replaced by `frozendict` instances, sequences are replaced by tuples, and everything else is returned unchanged. """ if isinstance(data, Mapping): r...
5,292,014
def getattribute(value, arg): """Gets an attribute of an object dynamically from a string name""" assert hasattr(value, str(arg)), "Invalid %s in %s" % (arg, value) return getattr(value, str(arg))
5,292,015
def task_project(): """ RESTful CRUD controller for options.s3json lookups """ if auth.permission.format != "s3json": return "" # Pre-process def prep(r): if r.method != "options": return False return True s3.prep = prep return s3_rest_controller()
5,292,016
def validate_memory(_ctx, _param, value): """Validate memory string.""" if value is None: return if not re.search(r'\d+[KkMmGg]$', value): raise click.BadParameter('Memory format: nnn[K|M|G].') return value
5,292,017
def cmd_arguments(): """ taking CMD arguments and sending them through the argument parser. """ parser = argparse.ArgumentParser() parser.add_argument("-i", "--image", help="Full image path can be optionally supplied.") args = parser.parse_args() return ar...
5,292,018
def get_table_columns( uri: str, extra_params: Dict[str, Any], schema: Optional[str], table: str, ) -> List[Column]: """ Return all columns in a given table. """ engine = create_engine(uri, **extra_params) try: inspector = inspect(engine) column_metadata = inspector.g...
5,292,019
def page (result = ''): """Return the main form""" return CGISH_HTML % {'SHELL_OUTPUT':result}
5,292,020
def mos_niriss_parser(app, data_dir, obs_label=""): """ Attempts to parse all data for a NIRISS dataset in the specified directory, which should include: - *_direct_*_cal.fits : Direct 2D image - *_direct_*_cat.ecsv : Source catalog - *_WFSSR_*_cal.fits : 2D spectra in first orientation - *_...
5,292,021
def forge_formats( token, verbose ): """Retrieve and return the file formats currently supported by the translation processes.""" headers = {'Authorization': 'Bearer ' + token} r = requests.get(url_formats, headers=headers) if verbose: print '\nForge formats call:' print ' Status:', r.status_code ...
5,292,022
def pad_1dconv_input(input, kernel_size, mode="same"): """ This method pads the input for "same" and "full" convolutions. Currently just Same and full padding modes have been implemented :param input: Input Tensor with shape BATCH_SIZE X TIME_STEPS X FEATURES :param mode: :return: Padd...
5,292,023
def hexscale_from_cmap_subchain(cmap, ind): """ NOTE: this is pretty bad, conceptually... Same as hexscale_from_cmap, but patch left and right ends. This is used to color only a substretch of polymer. Parameters: ----------- cmap : see hexscale_from_cmap. Example: plt.cm.viridis ind : ...
5,292,024
def create_dates_list(start_date, end_date): """ Return list of days in range of start and end date for itinerary.""" delta = end_date - start_date dates = [] for d in range(delta.days + 1): dates.append(start_date + timedelta(days = d)) return dates
5,292,025
def jed(exe = 'jed'): """ JED, the lightweight emacsish editor """ install_editor(exe + ' +$line "$file"')
5,292,026
def test_timestamp_to_hour_later(): """ Tests the timestamp output in hours on February second at time zero. """ obs_i = 792.0 exp_i = timestamp_to_hour(pd.Timestamp('2017-02-02T0000')) assert obs_i == exp_i return
5,292,027
def directory_indexing(): """ This function search for indexing in all directories already found and stored in directories. """ global directories global directories_with_indexing global debug global crawl_results global URL global host_name global main_domain global error_...
5,292,028
def clean_install_3_9_4(): """ Install a fresh blank v3.9.4 schema. """ with open(os.path.join(OaConfig.homedir, "sql", "emptyschema_394.sql")) as f: sql = f.read() run_sql(sql) print "Installed v3.9.4 table structure."
5,292,029
def run_name_to_flags(checkpoint_path: Text): """Extracts flag settings from a saved checkpoint path name. TODO: Consider making a single class that converts flags to run names and run names to flags. Or find some existing code that does this. Args: checkpoint_path: Path where checkpoint is saved. Retu...
5,292,030
def main(dir): """ """ logger = logging.getLogger(__name__) LANGUAGE = "en-GB" # make sure you have a 'arelle' directory in the data_path! (This is where the taxonomy is stored) XBRL_DATA_PATH = join('C:\\', 'Users' ,'wjwil', '20_local_data', 'xbrl') XBRL_RESULTS_PATH = join("..", "d...
5,292,031
def viterbi(observations, states, priors, transitions, emissions, probabilistic=False): """Perform HMM smoothing over observations via Viteri algorithm :param list(str) observations: List/sequence of activity states :param numpy.array states: List of unique activity state labels :param numpy...
5,292,032
def test_predicate_search_heuristic_base_classes(): """Cover the abstract methods for _PredicateSearchScoreFunction & subclasses.""" pred_search_score_function = _PredicateSearchScoreFunction( set(), [], {}, []) with pytest.raises(NotImplementedError): pred_search_score_function.evaluate...
5,292,033
def build_analysis_data(analyses): """ Args: analyses: (dict) of analysis Returns: dict: formatted entry context """ entry_context = dict() entry_context['VMRay.Analysis(val.AnalysisID === obj.AnalysisID)'] = [ { 'AnalysisID': analysis.get('analysis_id'), ...
5,292,034
def CurveFilletPoints(curve_id_0, curve_id_1, radius=1.0, base_point_0=None, base_point_1=None, return_points=True): """Find points at which to cut a pair of curves so that a fillet of a specified radius fits. A fillet point is a pair of points (point0, point1) such that there is a circle of radius tange...
5,292,035
def get_today(): """ Returns the datetime.date for today. Needed since tests cannot mock a builtin type: http://stackoverflow.com/a/24005764/4651668 """ return datetime.date.today()
5,292,036
def template_model1(): """ -------------------------------------------------------------------------- template_model1: Variables / RHS / AUX -------------------------------------------------------------------------- """ model_type = 'continuous' # either 'discrete' or 'continuous' model1 = d...
5,292,037
def flags(flags): """Hard-code KZC flags""" def f(test, way): test.way = None test.args += flags return f
5,292,038
def indexColumnPivot(Z, minOrMax, tableaux, _colPivot): # seach the value that'll come to base (index column) """ [seach the index of pivot column. That is a value that'll come to base] Arguments: Z {[list]} -- [list from Z line] minOrMax {[int]} -- [description] tableaux {[matr...
5,292,039
def register_model( name: str, build_function: Callable, model_type=None, convex=None, best_value=None, best_dual=None, opt_value=None, bigM=None) -> None: """ Registers the model in the model library. Parameters ---------- name : str Registry name fo...
5,292,040
def login(phase, cid=None, secret=None, redirect_uri=None): """ Login specific phase, need open auth first cid: Client id get from the sso system, default: 3 secret: Client secret get from the sso system, default: lain-cli_admin redirect_uri: Redirect uri get from the sso system, default: https://e...
5,292,041
def cim_size(estimated: T.FloatTensor, target: T.FloatTensor) -> float: """ Empirically estimated kernel size for CIM taken as the average reconstruction error based on Eq. 25 in https://lcs.ios.ac.cn/~ydshen/ICDM-12.pdf. Parameters: estimated (list): current Q-values target (li...
5,292,042
def main(): """ Simple command-line program for shutting down virtual machines on a system. """ args = GetArgs() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user)) context = ssl._c...
5,292,043
def poll_transloadit(args, upload_url): """ Polls Transloadit's API to determine the status of the upload. Outputs information to stdout (unless suppressed). Raises an exception if there is an error, returns tuple of response information when complete, and None otherwise """ if args.upload_t...
5,292,044
def call_cmd(cmd): """ Call a command line and return the result as a string. """ try: child = Popen(list(str(cmd).split(' ')), stdout=PIPE) string = child.communicate()[0] child.stdout.close() except OSError: message = str("Error while executing " + cmd + "\n" + traceback.f...
5,292,045
def send_message(service, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Sent Messa...
5,292,046
async def cmd_system(message : discord.Message, args : str, isDM : bool): """return statistics about a specified system :param discord.Message message: the discord message calling the command :param str args: string containing a system in the GOF2 starmap :param bool isDM: Whether or not the command is...
5,292,047
def rgb2hex(rgb_string, drop_alpha=False) -> str: """Convert an RGB string to HEX. Args: rgb_string (str): This is the RGB or RGBA string to convert. drop_alpha (bool): ``True`` will **drop the alpha value** from the HEX string. This is useful for colour maps that autom...
5,292,048
def train_cn_consistency(net, train_loader, optimizer, scheduler): """Train for one epoch.""" print('running train_cn_consistency') batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() s_losses = AverageMeter() c_losses = AverageMeter() net.train() end = tim...
5,292,049
def to_kpckms(cluster, ro=8.0, vo=220.0): """Convert stellar positions/velocities, centre of mass, and orbital position and velocity to kpc and km/s Parameters ---------- cluster : class StarCluster ro : float galpy radius scaling parameter vo : float galpy velocity scal...
5,292,050
def getLink(node, attr, destination=False, source=False): """ :param node: :param attr: :return: Linked node :rtype: str/None """ # validate plug plug = getPlug(node, attr) if not cmds.objExists(plug): return # get connections connections = cmds.listConnections( ...
5,292,051
def _reset_pk(query, pk = 'id', num = 0): """ 找出需要重新排列的主键 """ last_diff, changes = 0, [] start, stop = 0, 0 if num > 0: query = query.filter(Expr(pk)>num) for row in query.order_by(pk).iter(pk): id, num = row[pk], num + 1 curr_diff = id - num if curr_diff == 0: ...
5,292,052
def batch(data, batch_size, batch_size_fn=None): """Yield elements from data in chunks of batch_size.""" if batch_size_fn is None: def batch_size_fn(new, count, sofar): return count minibatch, size_so_far = [], 0 for ex in data: minibatch.append(ex) size_so_far = batc...
5,292,053
def interpolate_lightcurve(lc_table=None, lc_array=None): """Returns linear interpolator of epoch lightcurve """ if lc_array is None: if lc_table is None: raise ValueError('Must provide one of [lc_table, lc_array]') else: lc_array = extract_lightcurve_array(lc_table) ...
5,292,054
def get_account_user_id(**kwargs): """ Returns account_user_id from arguments Keyword arguments: :param vm_login_id: user's VM login ID like p100 :param email: user's E-Mail address :returns: account_user_id :rtype: int """ if 'vm_login_id' in kwargs: users = User.all() ...
5,292,055
def lnZ_PEB(time: np.ndarray, flux: np.ndarray, sigma: float, P_orb: float, M_s: float, R_s: float, Teff: float, Z: float, plx: float, contrast_curve_file: str = None, N: int = 1000000): """ Calculates the marginal likelihood of the PEB scenario. Args: time (numpy...
5,292,056
def interval2string_m(i: float) -> str: """Convert a time interval to a string or to NA if it is does not have a value Arguments: i: is a number of seconds Returns: a string of the number of minutes represented or NA if i is not a float """ if type(i) == float: ...
5,292,057
def ldns_sign_public_buffer(*args): """LDNS buffer.""" return _ldns.ldns_sign_public_buffer(*args)
5,292,058
def download_image(url): """Downloads ipg, jpeg fils from given URL""" response = request.urlopen(url) return ContentFile(response.read())
5,292,059
def dir_manager( path: Optional[Union[pathlib.Path, str]] = None ) -> Generator[pathlib.Path, None, None]: """A context manager to deal with a directory, default to a self-destruct temp one.""" if path is None: with tempfile.TemporaryDirectory() as tempdir: d_path = pathlib.Path(tempdir)...
5,292,060
def _evaluate(dataset: tf.data.Dataset, model: tf.keras.Model, loss_fn: tf.keras.losses.Loss) -> Tuple[float, float]: """Evaluates the given model for the whole dataset once.""" loss_sum = 0 correct_item_count = 0 item_count = 0 for (x, y) in dataset: x = tf.cast(x, tf.float64...
5,292,061
def tab(column) -> str: """Emulates the TAB command in BASIC. Returns a string with ASCII codes for setting the cursor to the specified column.""" return f"\r\33[{column}C"
5,292,062
def _make_laplace_numba_2d(grid: CartesianGrid) -> OperatorType: """make a 2d laplace operator using numba compilation Args: grid (:class:`~pde.grids.cartesian.CartesianGrid`): The grid for which the operator is created Returns: A function that can be applied to an array of val...
5,292,063
def main(args: NamedTuple, X: Sequence[str]) -> None: """ X contains a list of input arguments, such as `[--var1=val1]`. These args are sent to RankLib to setup a training run specification. Args ---- args: NamedTuple ranker: str Name of which ranker to use available in Ra...
5,292,064
def preview(slug): """Show the preview of a newly created or edited post. Parameters ---------- slug : str The slug is the part of the URL which identifies a particular post on our blog in an easy to read form. """ post = session['post'] # When I put the post object for the ...
5,292,065
def get_longest_streak_of_all_habits(session): """ :return: the value of the largest value in the streak column. """ try: longest_streak_for_all_habits = (max(session.query(HabitHistory.streak) .all())) except ValueError: raise NoHabitsInHisto...
5,292,066
def create_mds(tsuite): """Initialize MDS resources for testing. Args: tsuite: tsuite runtime.""" #Create the MDS systems for mds in tsuite.sl2objects["mds"]: #Create monolithic reference/replace dict repl_dict = dict(tsuite.src_dirs, **tsuite.build_dirs) repl_dict = dict(repl_dict, **mds...
5,292,067
def nonbond_pairs(pos, rcut_half, neigh_list, nonBondExcls, rcut_ovlp, znums=None): """ """ unitcell_min = pos.min(axis=0) unitcell_max = pos.max(axis=0) box = unitcell_max - unitcell_min + 1.0 # Cell Linked List ndim = np.array(box//rcut_half, dtype=np....
5,292,068
def mysavefig(fig, results_dir='', plot_save_name='test', **kwargs) -> None: """Append today's date to the file path and save with a tight bbox Parameters ---------- fig : plt.Figure results_dir : str plot_save_name : str, default 'test' kwargs keyword arguments to pass to savefig ...
5,292,069
def eye(N, chunks="auto", M=None, k=0, dtype=float): """ Return a 2-D Array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. chunks : int, str How to chunk the array. Must be one of the following forms: - A block...
5,292,070
def calc_num_walls(side_length, room_positions, ap_positions): """ Calculate the number of walls between each room to each AP. This is used to calculated the wall losses as well as the indoor pathloss. Parameters ---------- side_length : float The side length of the square room. ...
5,292,071
def get_version(): """ Get version without importing from elasticapm. This avoids any side effects from importing while installing and/or building the module Once Python 3.8 is the lowest supported version, we could consider hardcoding the version in setup.cfg instead. 3.8 comes with importlib.meta...
5,292,072
def x(h): """Convert a hex string to bytes""" return binascii.unhexlify(h.encode('utf8'))
5,292,073
def get_new_goal(current_pos, current_dest, home_pos, rally_point, batt_level, blocking_time=10, speed=5, energy_consumption=1): """ Function for deciding the new goal All the input coordinates are in the format [LAT, LON] (deg). returns a [int, int] list with [X, Y] coordinates of n...
5,292,074
def is_cuda_consistent(*args): """ See if the cuda states are consistent among variables (of type either tensors or torch.autograd.Variable). For example, import torch from torch.autograd import Variable import torch.nn as nn net = nn.Linear(512, 10) tensor = torch....
5,292,075
def get_policy_arn( iam: boto3.client, rights_msg: str, prefix: str = '/cluster.dev/', policy_name: str = 'cluster.dev-policy', ) -> str: """Get policy ARN if exist. Required "iam:ListPolicies". Args: iam: (boto3.client.IAM) A low-level client representing AWS IAM. rights_m...
5,292,076
def create_nginx_config(server, port): """Create NGINX config in sites-enabled directory""" if config_count() >= config_limit: abort(400) ip = request.remote_addr nginx_config = nginx_sites_enabled + '/' + server temp = sys.stdout sys.stdout = open(nginx_config, 'w') print template...
5,292,077
def batchlobstr(args): """ %prog batchlobstr samples.csv Run lobSTR sequentially on list of samples. Each line contains: sample-name,s3-location """ p = OptionParser(batchlobstr.__doc__) p.add_option("--sep", default=",", help="Separator for building commandline") p.set_home("lobstr", d...
5,292,078
def elbo_batch_loss(model, X, y, inds, samples): """Compute an estimate of the negative ELBO loss from a single batch. Args: X ([N, input_dim] numpy array): Train inputs. y ([N, output_dim] numpy array): Train outputs. inds ([batch_size] torch tensor): Indices for the batch. samp...
5,292,079
def calculate_similarity_bert(entity_1: str, entity_2: str) -> float: """ @param entity_1: @param entity_2: @return: similarity between two entities (in the sense of whether they refer to the same thing TODO make this better than just embeddings? """ embedded_1 = embed_concept_sentence(enti...
5,292,080
def to_epoch(str_time): """Take in string time(yyyy-mm-dd) and convert to epoch time.""" return int(dt.datetime.strptime(str_time, "%Y-%m-%d").timestamp())
5,292,081
def main(restart_step): """ Creates AtariDQN object and runs training according to configs. Parameters: restart_step : int Step to restart training from. Restart_step = 0 gives fresh start. Returns: None """ net_conf = os.path.abspath(os.path.join('...
5,292,082
def untag_resource(resourceArn=None, tagKeys=None): """ Deletes specified tags from a resource. See also: AWS API Documentation Exceptions :example: response = client.untag_resource( resourceArn='string', tagKeys=[ 'string', ] ) :type r...
5,292,083
def _rpn_loss_regr(y_true, y_pred): """ smooth L1 loss y_ture [1][HXWX10][3] (class,regr) y_pred [1][HXWX10][2] (reger) """ sigma = 9.0 cls = y_true[0, :, 0] regr = y_true[0, :, 1:3] regr_keep = tf.where(K.equal(cls, 1))[:, 0] regr_true = tf.gather(regr, regr_keep) regr_pr...
5,292,084
def create_markdown_file_from_filename(markdown_filename:str) -> SuccessErrors: """Creates a markdown file based on incoming filename suggestion If already exists, returns false, If other os.file issue, returns false, If successful, returns true Args: markdown_filename (str), ...
5,292,085
def fit_msm(trajectory, prefix=None, save_path=None): """Function to fit the msm to a given trajectory and save the vizualization Args: trajectory ([type]): Time series to be discretized prefix ([type], optional): Name to save a file. save_path ([type], optional): Wheree to save a fil...
5,292,086
def dataclass( _cls = None, *arg, init = True, repr = True, eq = True, order = False, unsafe_hash = False, ): """ Modification of dataclasses.dataclass that adds the following methods: 1. dataclass.from_tuple(data_tuple: Tuple[Any]) 2. data...
5,292,087
def doPkgConfig(actionArgs, params): """ Do pkg-config """ cfgCtx = params['cfgCtx'] bconf = params['bconf'] taskParams = params['taskParams'] toolname = actionArgs.setdefault('toolname', 'pkg-config') packages = actionArgs.get('packages') if not packages: msg = "...
5,292,088
def get_quiz_info(random_words): """ get examples and random answers for each test word in random_words :param random_words: a list of random test words :return: a list of quiz information """ db_session = DB_Session() allrows = db_session.query(TestWords) quiz_info = [] for word in ...
5,292,089
def parse_dependencies(file_names): """Program logic: read files, verify dependencies. For each input file, read lines and create dependencies. Verify each dependency. :param file_names: files to read dependencies from. :return: The list of dependencies, each verified. """ # type: (List[Text])...
5,292,090
def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(...
5,292,091
def tencent_resolve(url_like): """根据输入的url_like,查询其腾讯安全接口查询结果 :url_like: 可能有几种形式:url: http://www.baidu.com,domain: www.baidu.com,ip: 14.15.15.17,甚至可能是:http://14.15.16.17:80 :returns: {url_like: tencent} """ url = TENCENT_URL payload = { 'dname': url_like } headers = { '...
5,292,092
def host_create(context, values): """Create a host. :param context: context to query under :param values: dictionary of host attributes to create :returns: dictionary-like object containing created host """ return IMPL.host_create(context, values)
5,292,093
def extract_point_coordinates(scraped_points) -> None: """If it's point, extract coordinates(latitude & longitude).""" try: for feature_key in scraped_points["features"]: for geo_key, coordinates in feature_key["geometry"].items(): if isinstance(coordinates, list): ...
5,292,094
def check_trustlines(): """ Create Stellar transaction for deposit transactions marked as pending trust, if a trustline has been created. """ transactions = Transaction.objects.filter(status=Transaction.STATUS.pending_trust) for transaction in transactions: account = Horizon(horizon_uri=...
5,292,095
def __dispatch_remove_command(arguments: list) -> str: """ Dispatches command to remove file/folder Returns command that was run """ command = "" if arguments["file"]: command = "remove-file" library.remove_file(arguments["file"]) elif arguments["folder"]: command = "...
5,292,096
def _wait_for_job(T, job, hide_progress=False): """ Wait for the compliance job to complete """ if ( job is not None and "status" in job and (job["status"] == "failed" or job["status"] == "expired") ): click.echo( click.style( f"Stopped wa...
5,292,097
def adjust_learning_rate(lr, gamma, epoch, step_index, iteration, epoch_size): """Sets the learning rate # Adapted from PyTorch Imagenet example: # https://github.com/pytorch/examples/blob/master/imagenet/main.py """ if epoch < 6: lr = 1e-6 + (lr - 1e-6) * iteration / (epoch_size * 5) el...
5,292,098
def defaulted_config(modules, params=None, yaml=None, filename=None, config=None, validate=True): """Context manager version of :func:`set_default_config()`. Use this with a Python 'with' statement, like >>> config_yaml = ''' ... toplevel: ... param: value ... ''' >>...
5,292,099