content
stringlengths
22
815k
id
int64
0
4.91M
def _bq_harness_with_result(sql, do_batch): """ Handles all the boilerplate for running a BQ job """ client = bigquery.Client() job_config = bigquery.QueryJobConfig() if do_batch: job_config.priority = bigquery.QueryPriority.BATCH location = 'US' # API request - starts the quer...
51,200
def create_workflow(name=None, namespace=None, bucket=None, **kwargs): """ Args: name: Name to give to the workflow. This can also be used to name things associated with the workflow. """ builder = Builder(name=name, namespace=namespace, bucket=bucket, **kwargs) return builder...
51,201
def GenerateParseTreeVisitor(concrete_classes): """Generates parse_tree_visitor.h contents containing ParseTreeVisitor class. Args: concrete_classes: a list of classes for which to generate visit methods Yields: A string part of the output code. """ yield textwrap.dedent('''\ #ifndef STORAGE_Z...
51,202
def validadeInequalityFilter(inequality_filters, entity): """Check if a entity attends all the inequality filters inputed""" check = True # Iterated on every the inequality filter informed for f in inequality_filters: if hasattr(entity, f["field"]): # Check if the entity has the attribute ...
51,203
def _make_reader(event_buffer_len=65536, delay=0.1): """Read a large amount of events into the given queue. event_buffer_len determines how much to attempt to read at once """ logger.debug("Create reader buffer={} delay={}" .format(event_buffer_len, delay)) def _read(): glo...
51,204
def flops_metric_map(end_points, mean_metric, total_name='Total Flops'): """Assembles flops-count metrics into a map for use in tf.contrib.metrics.""" metric_map = {} total_flops = tf.to_float(end_points['flops']) flops_map = moments_metric_map(total_flops, total_name, mean_metric, delimiter='/', do_shift...
51,205
def _is_false2(x): """Non-vectorized helper function""" return (x in ("False", "false", "0") or not bool(x)) and not _is_na2(x)
51,206
def process_document(document, context_size, dictionary, fixed_dictionary=False): """ Given a dictionary, extract the tuples of words of length equal to context_size. Each word is represented by a unique integer number. If fixed_dictionary is True, only take consecutive tuples of words being (all o...
51,207
def list_buckets(): """ Lists available buckets. :return: list of available buckets Amazon (2019) s3-python-example-list-buckets.py Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. """ # create s3 client s3 = boto3.client('s3') # call client and get lis...
51,208
def site_time_zone(request, registry, settings): """Expose website URL from ``tm.site_time_zone`` config variable to templates. By best practices, all dates and times should be stored in the database using :term:`UTC` time. This setting allows quickly convert dates and times to your local time. Exampl...
51,209
def qubic_spline_coeff(x_nodes, y_nodes): """Here underscored variables are related to the matrix equation, whereas normal ones stand for the spline coefficients """ polynomials_num = len(x_nodes) - 1 coeffs = np.zeros((polynomials_num, 3)) hs = (x_nodes - np.roll(x_nodes, 1))[1:] ys = (y_no...
51,210
def test_entity_mixin() -> None: """Testing our mixin entity variety.""" ent = EntityTestMixin() assert static_type_equals(ent.isubval2, int) assert ent.isubval2 == 3453
51,211
def load_C2O(xml_file): """Load a C2O decision model. See http://www.jku.at/isse/content/e139529/e126342/e126343 for information about the C2O (Configurator 2.0) tool. Arguments: xml_file: Path to a C2O XML file. Returns: A tuple with two elements `var_domains` and `constraints` ...
51,212
def contact_infectivity_asymptomatic_40x50(): """ Real Name: b'contact infectivity asymptomatic 40x50' Original Eqn: b'contacts per person normal 40x50*infectivity per contact' Units: b'1/Day' Limits: (None, None) Type: component b'' """ return contacts_per_person_normal_40x50() * i...
51,213
def test_continuous_discr(): """ Ensure correct discretization in continuous state spaces """ # NOTE - if possible, test a domain with mixed discr/continuous domain = InfiniteTrackCartPole.InfTrackCartPole() #2 continuous dims rep = IndependentDiscretization(domain, discretization=20) assert rep.fea...
51,214
def freezeclass(cls): """ Decorator to freeze a class.""" cls.__frozen = False def frozensetattr(self, key, value): if self.__frozen and not hasattr(self, key): print("Class {} is frozen. Cannot set {} = {}" .format(cls.__name__, key, value)) else: ...
51,215
def gsc_url_keyword(prop, start, end, query, url): """Return position, clicks & impressions from GSC for keyword for URL.""" #API Not adapted to Pipulate yet request = { "startDate": start, "endDate": end, "dimensions": [ "query", "page" ], "dimensionFilterGrou...
51,216
def click_agency(name: str) -> None: """select one of the agencies, for example, National Science Foundation """ logger.info(ctx_message(f'click on {name}')) locator = f'partial link:{name}' lib.click_element(locator)
51,217
def zerofill_net(input_size=(640, None, 1), **dummy_kwargs): """A net that performs a simple zero-filled reconstruction Parameters: input_size (tuple): the size of your input kspace Returns: keras.models.Model: the zerofill net model, compiled """ # shapes mask_shape = input_size[:-1] ...
51,218
def __useless_contour(shape, detected, last_cont,center,angle): """ Erase the useless contours, center, and angle. Contours, center, and angle are erased if the shape type is ALL, PARTIAL or UNKNOWN. Parameters ---------- shape : Shape The shape we want to detect detected : Shape ...
51,219
def plot_agn_rel_cddf(snap): """Load and make a plot of the difference between both simulations with and without AGN""" basen = myname.get_name(0) base = dp.PrettyBox(basen, snap, nslice=10) cddf_base = base.column_density_function() basen = myname.get_name(4) other = dp.PrettyBox(basen, snap, n...
51,220
def test_cog_translate_to_memfile(runner): """Create COG in memory and using in memory or in disk temp files.""" with runner.isolated_filesystem(): with rasterio.open(raster_path_rgb) as dataset: with MemoryFile() as memfile: cog_translate(dataset, memfile.name, deflate_profi...
51,221
def add_b(_rb): """ Add for Baselines """ def add(e): for i in range(e["obs"].shape[0]): _rb.add(obs_t=e["obs"][i], action=e["act"][i], reward=e["rew"][i], obs_tp1=e["next_obs"][i], done=e["done"][i]) ret...
51,222
def get_ncfile(fname='cmip5.CSIRO-Mk3-6-0.nc'): """ Return one netCDF file """ return join(get_datadir(),fname)
51,223
def test_get_environment_factor_no_subcategory(): """get_environment_factor() should raise a KeyError if passed an unknown subcategory ID.""" with pytest.raises(KeyError): _pi_e = relay.get_environment_factor(12, 1, 1)
51,224
def generate_complete_path(filename:str, main_folder="./temp/", subfolders='', file_extension = ".png", save_files=True): """ Function to create the full path of a plot based on `name`. It creates all the subfolders required to save the final file. If `save_files=False` returns `None`, useful to control fro...
51,225
def start_webview(): """This method gets called once the new thread is created. It starts the webview and Javascript API. Returns: None """ api = Api() webview.create_window("Example", html=html, js_api=api) webview.start(gui="qt")
51,226
async def sue(event, *, target=""): """Sue somebody! **Example usage** * `sue` * `sue a person` """ conjunctions = " because | for | over " parts = [part.strip() for part in re.split(conjunctions, target, 1, re.I)] if len(parts) > 1 and parts[1]: conjunction = re.search(conjunc...
51,227
def realm_from_principal(principal): """ Attempt to retrieve a realm name from a principal, if the principal is fully qualified. :param principal: A principal name: user@DOMAIN.COM :type: principal: str :return: realm if present, else None :rtype: str """ if '@' not in principal: ...
51,228
def patch_batchnorm(module: nn.Module) -> List: """Patch all batchnorm instances (1d, 2d, 3d, sync_bn, etc.) of a module so that they don't track running stats when torch.no_grad() is enabled. This is important in activation checkpointing to ensure stats are tracked correctly as if there were ...
51,229
def decode_uids(uids, *, return_sids_iids:bool=False, return_sids_pids:bool=False, experimental_noinfo_id:int=-1, experimental_dataset_spec:DatasetSpec=None, experimental_correct_range:bool=False): """ Given the universal ids `uids` according to the hierarchical format described in...
51,230
def _joined_names_column(df): """ Join data from all name columns into a single column. """ return df.apply( lambda row: ','.join(set([ six.text_type(n) for n in [row['main_name'], row['asciiname'], row['alternatenames']] if n and n is not np.nan ])), ...
51,231
def skip( num_input_channels=2, num_output_channels=3, num_channels_down=[16, 32, 64, 128, 128], num_channels_up=[16, 32, 64, 128, 128], num_channels_skip=[4, 4, 4, 4, 4], filter_size_down=3, filter_size_up=3, filter_skip_size=1, need_sigmoid=True, need_bias=True, pad='zero', ups...
51,232
def generate_constructor_for_class(cl: ClassIR, fn: FuncDecl, init_fn: Optional[FuncIR], setup_name: str, vtable_name: str, emitter: Emitter) -> ...
51,233
def run_analysis(args): """Builds an analysis files for training.""" # Read the schema and input feature types schema_list = json.loads( file_io.read_file_to_string(args.schema_file)) run_numerical_categorical_analysis(args, schema_list) # Also save a copy of the schema in the output folder. file_i...
51,234
def validate_kml(possible_files): """Validate uploaded KML file and a possible image companion file KML files that specify vectorial data typers are uploaded standalone. However, if the KML specifies a GroundOverlay type (raster) they are uploaded together with a raster file. """ kml_file = [ ...
51,235
def mailform(): """Sample form for sending email via Microsoft Graph.""" # read user profile data user_profile = MSGRAPH.get('me/', headers=request_headers()).data user_name = user_profile['displayName'] # get profile photo photo_data, _, profile_pic = profile_photo(client=MSGRAPH, save_as='me...
51,236
def set_for_repo(repo, **kwargs): """Sets configuration settings for a particular repository. When used with get_for_repo, has the effect of overriding global settings.""" set(str(repo), **kwargs)
51,237
def _global_query_(included_interviews=None, included_globals=None, client_as_numeric=True, exclude_reliability=True): """ Constructs the globals query for session-level datasets :param included_interviews: iterable of str specifying names of interviews to include :param included_globals: :param cli...
51,238
def basic_detokenizer(tokens): """Reverse the process of the basic tokenizer below.""" result = [] previous_nospace = True for t in tokens: if is_char(t): result.append(t[_CHAR_MARKER_LEN:]) previous_nospace = True elif t == _SPACE: result.append(" ") previous_nospace = True ...
51,239
def _validate_kwgs(kwgs): """Private helper method to validate kwargs arguments.""" if not isinstance(kwgs, (type(None), dict)): err = "kwgs must be None or a dictionary of keyword arguments" raise ValueError(err)
51,240
def page_not_found(error): """Generic 404 error page. :param error: An exception from the error. :returns: The rendered 404 error template. """ app.logger.debug('Rendering 404 page') return render_template('404.html'), 404
51,241
def test_add_noise(test_file, snr): """ Test adding noise function. """ add_noise(test_file, snr) # check result fname = "%s_augmented_%s_noisy.wav" % (test_file.split(".wav")[0], str(snr)) time.sleep(1) assert_file_exists(fname)
51,242
def get_task_state(exit_code): """Interprets the exit_code and return the corresponding task status string Parameters ---------- exit_code: int An integer that represents the return code of the task. Returns ------- A task status string corresponding to the exit code. """ i...
51,243
def filtertime(timestamp, interval): """Check if timestamp is between timestamp_range - (time1,time2) Args: timestamp --> UNIX timestamp value. interval --> `Tuple` of 2 UNIX timestamp values. Returns: `bool` --> True/False """ T0, T1 = interval if (timestamp <= T1) an...
51,244
def is_dataframe(value): """ Check if an object is a Spark DataFrame :param value: :return: """ return isinstance(value, DataFrame)
51,245
def reverse_enum(enum_to_reverse: Type[SMOOTHIE_GCODE]) -> Dict: """ Returns dictionary with keys and values switched from passed Enum :param enum_to_reverse: The Enum that you want to reverse :return: Reversed dictionary """ # I don't know what is going on with mypy, it is complaining # abo...
51,246
def extract_zip(self: Task, folderId: str, itemId: str): """ Discovery logic: * Find all folders that have at least one child file (potential datasets) * Exclude folders which are sub-folders of previously discovered folders because datasets cannot be nested in other datasets """ context: ...
51,247
def findDiff(dict1, dict2, path=""): """ Recursively compare key / value pairs for two dictionaries """ for key in dict1.keys(): if not dict2.has_key(key): print("{}:".format(path)) print("{} as key not in dict2\n".format(key)) else: if isinstance(dict1[key], dict): if path == ...
51,248
def test_predict_labels(): """A unittest for predict labels. This function mocks out the embedding service and the MLPWorker. """ model = repo_specific_model.RepoSpecificLabelModel() model._mlp_predictor = mock.MagicMock(spec=mlp.MLPWrapper) model._mlp_predictor.predict_probabilities.return_value = [[.2, ...
51,249
def install_npm(path=None, build_dir=None, source_dir=None, build_cmd='build', force=False): """Return a Command for managing an npm installation. Note: The command is skipped if the `--skip-npm` flag is used. Parameters ---------- path: str, optional The base path of the node package. De...
51,250
def cli_ads_update(args): """Command-line interface for ads-update call.""" update_keys = args.update == 'arxiv' am.update(update_keys=update_keys)
51,251
def group_Counter(trip: Iterable[Leg]) -> List[Tuple[int, int]]: """Group legs into bins with distances 5 nm or less. >>> trip = [ ('s1', 'e1', 1), ('s4', 'e4', 4.9), ('s5', 'e5', 5), ('s6', 'e6', 6)] >>> group_Counter(trip) [(0, 2), (5, 2)] """ quantized = (int(5*(dist//5)) for start, stop, di...
51,252
def run_deduper(deduper, data_frame, settings_file, training_file, recall_weight = 1): """ Given a deduper object and a dataset, this function trains the model and predicts which records are duplicates. depends: dedupe as dd pandas as pd time params: deduper: a Dedu...
51,253
def convert_inertial(x): """Convert from Inertial Parameters used in Meijaard to those used by Dale Peterson's inertial model parameters. """
51,254
def _get_file_preferred_suffix() -> tuple: """Based on ontologia/core.lkg.yml + env variable LANGUAGE, build preferred user language Returns: tuple: the result of file sufisex """ userpref_suffix = [] core_suffix = CORE_LKG['fs']['hdp']['base'] userlangs_upper = get_language_user_...
51,255
def propagate_groundtracks(): """Periodic groundtracks propagation """ logger.info('>>> Populating groundtracks') try: gt_models.GroundTrack.objects.propagate() except Exception as ex: logger.exception( '>>> Exception populating groundtracks, ex = ' + str(ex), ex ...
51,256
def fatorial(n, show=False): """ -> Call :param n: :param show: :return: """ f = 1 for c in range (n, 0, -1): if show: print(c, end='') if c>1: print(' x ', end='') else: #print(f'{c} X ') print(' = '...
51,257
def _CreateIncompleteService(service_pb2): """Provides a servicer backend that fails to implement methods and its stub. The servicer is just the implementation of the actual servicer passed to the face player of the python RPC implementation; the two are detached. Args: service_pb2: The service_pb2 modul...
51,258
def integrate_whole(payload, org, out_uuid, group): """integrates payload into whole of profile, returns dict""" if group: in_uuid = str(uuid.uuid4()) nested = {"PayloadContent": payload, "PayloadEnabled": True, "PayloadIdentifier": 'SparkleDisabler', ...
51,259
def search_hospitals(request_input: RequestInput, db_session) -> List[dict]: """ Search hospitals based on requested items. Sort them by nearest location :param request_input: RequestInput :param db_session: DB session :return: List of Hospital dictionaries """ # Search hospitals which has r...
51,260
def get_inverse_metric(): """Computes and returns the inverse metric Sets the inverse metric variable, so that DendroSym knows how to compute various derived variables. This should be done early on in the generating script. It requires the metric to already be defined. Returns ------- symp...
51,261
def add_towers_4G_km2_sheet(ws, cols, lnth): """ """ for col in cols: cell = "{}1".format(col) ws[cell] = "=Towers!{}".format(cell) for col in cols[:2]: for i in range(1, lnth): cell = "{}{}".format(col, i) ws[cell] = "=Towers!{}".format(cell) for c...
51,262
def create_vocabulary(source_path, vocabulary_path, max_vocabulary_size, tokenizer=japanese_tokenizer): """Create vocabulary file. Please see comments in head for file format Args: source_path: source file path vocabulary_path: Path to write vocabulary max_vocabulary_size: Max vocabulary size...
51,263
def get_all_netting_channel_events( chain: BlockChainService, token_network_address: Address, netting_channel_identifier: ChannelID, contract_manager: ContractManager, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ) -> Lis...
51,264
def custom_extractors( eval_shared_model: tfma.MaybeMultipleEvalSharedModels, eval_config: tfma.EvalConfig, tensor_adapter_config: tensor_adapter.TensorAdapterConfig, ) -> List[tfma.extractors.Extractor]: """Returns default extractors plus a custom prediction extractor.""" predict_extractor = make_xgboo...
51,265
def custom_detrending(flc): """Wrapper""" f = flc.flux[np.isfinite(flc.flux)] if np.abs(f[0]-f[-1])/np.median(f) > .2: print("Do a coarse spline interpolation to remove trends.") flc = fit_spline(flc, spline_coarseness=12) flc.flux[:] = flc.detrended_flux[:] # Iterativel...
51,266
def Install(vm): """Installs the psping package on the VM.""" zip_path = ntpath.join(vm.temp_dir, PSPING_ZIP) vm.DownloadFile(PSPING_URL, zip_path) vm.UnzipFile(zip_path, vm.temp_dir)
51,267
def summon_blocks(board): """Place 1-8 circles in random places on the speed board""" for _ in range(random.randint(1, 8)): x = random.randint(0, 4) y = random.randint(0, 4) while board[x][y] != 'g': x = random.randint(0, 4) y = random.randint(0, 4) board[x][y] = 'b' return board
51,268
def main(): """ Main entry point of the app """ # Type conversion a = "a" b = 10 c = "1001" print(bin(b)) print(oct(b)) print(hex(b)) print(ord(a)) # The int() function takes second argument as the base of the number to be converted print(int(c,2)) print(int(c,10)) ...
51,269
def cache_data(cache_dir, input_dir): """将输入图片计算一个分类,然后缓存起来 cache_dir: 缓存目录 input_dir: 图片输入目录 """ image_paths = glob(os.path.join(input_dir, "*.jpg")) create_graph_helper() with tf.Session() as sess: for path in image_paths: print("cache {}...".format(os.path.basename(pa...
51,270
def three_sum_brute_force(array: List[int], target: int) -> Tuple[int, int, int]: """ args: array: target: returns: idxs >>> s = [-1, 0, 1, 2, -1, -4] >>> three_sum_brute_force(s, 0) (0, 1, 2) O(N^3) """ for i, u in enumerate(array): for j, v in enumerat...
51,271
def duplicates(work, golden=None, purge=False): """ Finds duplicates and purges them based on the flags @param work: work path where duplicates will be searched and purged if purge flag is set @param golden: path where duplicates will be searched, however never deleted @param purge: delete duplicates, k...
51,272
def add_logging_values_to_args( args:argparse.Namespace, log_file:str=_DEFAULT_LOG_FILE, log_stdout:bool=False, no_log_stderr:bool=False, logging_level:str=_DEFAULT_LOGGING_LEVEL, file_logging_level:str=_DEFAULT_SPECIFIC_LOGGING_LEVEL, stdout_logging_level:str=_DE...
51,273
def on_cooldown(user): """Shortcut: Get remaining cooldown of a user.""" return Parent.GetUserCooldownDuration(ScriptName, settings["command"], user)
51,274
def is_json(response): """This function will validate whether the header has the content-type as json""" assert 'application/json' in response.headers.get('content-type'), "The response is not json value"
51,275
def get_ieconstraints(unknowns, segment): """ Runs the mission if the inequality constraint values are needed, these are specific to a climb Assumptions: Time only goes forward CL is less than a specified limit CL is greater than zero All altitudes are greater than zero ...
51,276
def check_file_name(file_name, file_type="", extension=""): """ check_file_name(file_name, file_type="", extension="") Checks file_name for file_type or extension """ file_name = check_string(file_name, -1, '.', extension) file_name = check_string(file_name, -1, '_', file_type) return file_name
51,277
def render_experiments( driver: Driver = None, collab_id: str = "", project_id: str = "", form_type: str = "display", show_details: bool = True ): """ Renders out retrieved experiment metadata in a custom form Args: driver (Driver): A connected Synergos driver to communicate with...
51,278
def dns_logs(ctx: Configuration): """Home Assistant DNS logs.""" _handle(ctx, 'dns/logs')
51,279
def hasvalue_returns_false_for_these_symbols(self): """hasvalue returns false for these symbols.""" assert self.dic.hasvalue('eggs') is False
51,280
def test_normal_peek(): """Test chunk with peeking at iterable.""" # chunk with multiple but peek makes it non-multiple data = iter('ABCDEFGH') res = chunk(data, 2) assert next(res) == ('A', 'B') assert next(data) == 'C' assert list(res) == [('D', 'E'), ('F', 'G'), ('H',)] assert list(da...
51,281
def tag_lookup(request): """JSON endpoint that returns a list of potential tags. Used for upload template autocomplete. """ tag = request.GET['tag'] tagSlug = slugify(tag.strip()) tagCandidates = Tag.objects.values('word').filter(slug__startswith=tagSlug) tags = json.dumps([candidate['word...
51,282
def scope_to_list(scope): """Convert a space separated string to a list of scopes.""" if isinstance(scope, list) or scope is None: return scope else: return scope.split(" ")
51,283
def test_get_relative_path_from_config_file_to_data_base_file_path_from_within_ge_directory_and_absolute_data_path( monkeypatch, simulated_project_directories ): """ This test simulates using the CLI from within the great_expectations directory and using an absolute path. /projects/pipeline1/great_...
51,284
def import_migration_script(filepath: Path) -> ModuleType: """ Import migration script as if it were a module. """ spec = importlib.util.spec_from_file_location(filepath.stem, filepath) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # type: ignore return modu...
51,285
def numargs(func: Callable) -> int: """Get number of arguments.""" return len(inspect.signature(func).parameters)
51,286
def _embed(x, order=3, delay=1): """Time-delay embedding. Parameters ---------- x : 1d-array, shape (n_times) Time series order : int Embedding dimension (order) delay : int Delay. Returns ------- embedded : ndarray, shape (n_times - (order - 1) * delay, order...
51,287
def counts_normalization(counts, max_t): """This functions acts over the counts matrices and vectors in order to normalize their elements into a probabilities. Parameters ---------- counts: array_like, shape(n,n,nlags) the counts of the coincident spikes considering lag times. Returns ...
51,288
def init_logger(level='DEBUG', name='ska'): """Initialise stdout logger for the ska.sdp logger. :param level: Logging level, default: 'DEBUG' :param name: Logger name to initialise. default: 'ska.sdp'. """ log = logging.getLogger(name) log.propagate = False # make sure there are no duplica...
51,289
def form_baseline_intro(current_law): """ Form final sentance of introduction paragraph """ if not current_law: return f"{date()}" else: return ( f"{date()}, along with some modifications. A summary of these " "modifications can be found in the \"Summary of Ba...
51,290
def check_access_financing(token: str, staff: bool, account_id: str, statement): """Extra check on account access to a financing statement.""" if staff or (account_id and statement.registration[0].account_id == account_id): return account_name = get_account_name(token, account_id) access = Fals...
51,291
def serialise(entry: Directive) -> Any: """Serialise an entry.""" if not entry: return None ret = entry._asdict() ret["type"] = entry.__class__.__name__ if isinstance(entry, Transaction): ret["payee"] = entry.payee or "" if entry.tags: ret["narration"] += " " + " ...
51,292
def MeanValueCoordinateMapping(dpoint, uv, physical_points): """MVC mapping from parametric uv to physical 3D inputs: dpoint: [list, tuple or 1D array of floats] desired uv point uv: [2D array] of parametric uv points of polygon vertices physic...
51,293
def models(verbose_exceptions=False, output_dir='models', group_name='test', overwrite=True, n_models=1, n_species=10, n_reactions=None, in_dist='random', out_dist='random', joint_dist=None, in_range=None, out_range=None, joint_range=None, min_freq=1.0, mass_violating_reactions=True, edge_type='...
51,294
def _handle_discogs(url): """https://*discogs.com/*""" apiurl = 'https://api.discogs.com/' headers = {'user-agent': 'pyfibot-urltitle'} title_formats = { 'release': '{0[artists][0][name]} - {0[title]} - ({0[year]}) - {0[labels][0][catno]}', 'artist': '{0[name]}', 'label': '{0[n...
51,295
def get_api_all_item(): """Get map of class name to class for all ApiItem subclasses. Returns: :obj:`dict` """ return {c.__name__: c for c in ApiItem.__subclasses__()}
51,296
def get_image_url(soup_object: object) -> str: """Return book image url.""" image_url = soup_object.find("img")["src"] return image_url.replace("../..", "https://books.toscrape.com/")
51,297
def load_dir(path): """ loads all images in a directory Inputs - path (string): folder containing images """ files = [os.path.join(path, p) for p in os.listdir(path)] images = [] for f in files: # frame number # frame = f[] image = cv2.imread(f) imag...
51,298
def tracking(velocity_x, velocity_y, velocity_z, duration): """ Move vehicle in direction based on specified velocity vectors. """ msg = vehicle.message_factory.set_position_target_global_int_encode( 0, # time_boot_ms (not used) 0, 0, # target system, target component ma...
51,299