content
stringlengths
22
815k
id
int64
0
4.91M
def bittensor_dtype_to_torch_dtype(bdtype): """ Translates between bittensor.dtype and torch.dtypes. Args: bdtype (bittensor.dtype): bittensor.dtype to translate. Returns: dtype: (torch.dtype): translated torch.dtype. """ if bdtype == bittensor.proto.DataType.FLOAT3...
5,350,400
def read_all(dataset, table): """Read all data from the API, convert to pandas dataframe""" return _read_from_json( CFG.path.replace("data", dataset=dataset, table=table, converter="path") )
5,350,401
def compute_spectrum_welch(sig, fs, avg_type='mean', window='hann', nperseg=None, noverlap=None, f_range=None, outlier_percent=None): """Compute the power spectral density using Welch's method. Parameters ----------- sig : 1d or 2d array Tim...
5,350,402
def _function_set_name(f): """ return the name of a function (not the module) @param f function @return name .. versionadded:: 1.1 """ name = f.__name__ return name.split(".")[-1]
5,350,403
def better_event_loop(max_fps=100): """A simple event loop that schedules draws.""" td = 1 / max_fps while update_glfw_canvasses(): # Determine next time to draw now = perf_counter() tnext = math.ceil(now / td) * td # Process events until it's time to draw while now <...
5,350,404
def measure_step(max_steps, multiplier): """ Measure the performance of STEP :param max_steps: :param multiplier: :return: """ resp = requests.post(f"{API_URL_BASE}/ic", json={"filename": "TEST.scn"}) assert resp.status_code == 200, "Expected the scenario to be loaded" resp = reque...
5,350,405
def _notes_from_paths( paths: Sequence[Path], wiki_name: str, callback: Optional[Callable[[int, int], None]]) -> Set[TwNote]: """ Given an iterable of paths, compile the notes found in all those tiddlers. :param paths: The paths of the tiddlers to generate notes for. :param wiki_name: The n...
5,350,406
def load_matrix(file_matrix, V): """load matrix :param file_matrix: path of pre-trained matrix (output file) :param V: vocab size :return: matrix(list) """ matrix = [[0 for _ in range(V)] for _ in range(V)] with open(file_matrix) as fp: for line in fp: target_id, context...
5,350,407
def add(*args): """Adding list of values""" return sum(args)
5,350,408
def test_ion_fraction_field_is_from_on_disk_fields(): """ Test to add various ion fields to Enzo dataset and slice on them """ ds = load(ISO_GALAXY) add_ion_fields(ds, ['H'], ftype='gas') ad = ds.all_data() # Assure that a sampling of fields are added and can be sliced arr1 = ad['H_p0_io...
5,350,409
def get_chart_dates(df, start_date=None, end_date=None, utc=True, auto_start=None, auto_end=None): """ Get dates for chart functions. More info on date string formats at: https://strftime.org/ Parameters: df : The dataframe for the chart, needed to acertain start and end dates, if non...
5,350,410
def run_benchmark_suite(analyser, suite, verbose, debug, timeout, files, bench): """ Run an analyzer (like Mythril) on a benchmark suite. :param analyser: BaseAnalyser child instance :param suite: Name of test suite :param verbose: Verbosity :param debug: Whether debug is on :param timeout: Test...
5,350,411
def Eip1(name, ospaces, index_key=None): """ Return the tensor representation of a Fermion ionization name (string): name of the tensor ospaces (list): list of occupied spaces """ terms = [] for os in ospaces: i = Idx(0, os) sums = [Sigma(i)] tensors = [Tensor([i], n...
5,350,412
def load_rtma_data(rtma_data, bbox): """ Load relevant RTMA fields and return them :param rtma_data: a dictionary mapping variable names to local paths :param bbox: the bounding box of the data :return: a tuple containing t2, rh, lats, lons """ gf = GribFile(rtma_data['temp'])[1] la...
5,350,413
def print_message(message): """ log the given message to to stdout on any modules that are being used for the current test run. """ for rest_endpoint in _get_rest_endpoints(): thread = pool.apply_async( rest_endpoint.log_message, ({"message": "PYTEST: " + message},) ) ...
5,350,414
def serialize_remote_exception(failure_info, log_failure=True): """Prepares exception data to be sent over rpc. Failure_info should be a sys.exc_info() tuple. """ tb = traceback.format_exception(*failure_info) failure = failure_info[1] if log_failure: LOG.error(_("Returning exception %...
5,350,415
def test_atomic_time_enumeration_nistxml_sv_iv_atomic_time_enumeration_1_5(mode, save_output, output_format): """ Type atomic/time is restricted by facet enumeration. """ assert_bindings( schema="nistData/atomic/time/Schema+Instance/NISTSchema-SV-IV-atomic-time-enumeration-1.xsd", instan...
5,350,416
def combine_arg_list_opts(opt_args): """Helper for processing arguments like impalad_args. The input is a list of strings, each of which is the string passed into one instance of the argument, e.g. for --impalad_args="-foo -bar" --impalad_args="-baz", the input to this function is ["-foo -bar", "-baz"]. This fu...
5,350,417
def in_data(): """Na funçao `in_data` é tratado os dados da matriz lida do arquivo txt.""" points = {} i, j = map(int, file.readline().split(' ')) for l in range(i): line = file.readline().split(' ') if len(line)==j: for colun in range(len(line)): if line[col...
5,350,418
def doom_action_space_extended(): """ This function assumes the following list of available buttons: TURN_LEFT TURN_RIGHT MOVE_FORWARD MOVE_BACKWARD MOVE_LEFT MOVE_RIGHT ATTACK """ space = gym.spaces.Tuple(( Discrete(3), # noop, turn left, turn right Discrete...
5,350,419
def svn_auth_provider_invoke_first_credentials(*args): """ svn_auth_provider_invoke_first_credentials(svn_auth_provider_t _obj, void provider_baton, apr_hash_t parameters, char realmstring, apr_pool_t pool) -> svn_error_t """ return _core.svn_auth_provider_invoke_first_credentials(*args)
5,350,420
def test_vstart_without_rmq_init(request, instance): """ Test error where volttron is started with message bus as rmq but without any certs :param request: pytest request object :parma instance: volttron instance for testing """ try: assert instance.instance_name == os.path.basename(...
5,350,421
def test_led_state() -> None: """Test the state property of an LED.""" led = LED(0, MockLEDDriver()) led.state = True assert led.state
5,350,422
def kill_process(device, process="tcpdump", pid=None, sync=True, port=None): """Kill any active process :param device: lan or wan :type device: Object :param process: process to kill, defaults to tcpdump :type process: String, Optional :param pid: process id to kill, defaults to None :type ...
5,350,423
def get_sentence(soup, ets_series, cache, get_verb=False): """ Given an ETS example `ets_series`, find the corresponding fragment, and retrieve the sentence corresponding to the ETS example. """ frg = load_fragment(soup, ets_series.text_segment_id, cache) sentence = frg.find('s', {'n': ets_serie...
5,350,424
def PreAuiNotebook(*args, **kwargs): """PreAuiNotebook() -> AuiNotebook""" val = _aui.new_PreAuiNotebook(*args, **kwargs) val._setOORInfo(val) return val
5,350,425
def get_nsx_security_group_id(session, cluster, neutron_id): """Return the NSX sec profile uuid for a given neutron sec group. First, look up the Neutron database. If not found, execute a query on NSX platform as the mapping might be missing. NOTE: Security groups are called 'security profiles' on the ...
5,350,426
def customiseGlobalTagForOnlineBeamSpot(process): """Customisation of GlobalTag for Online BeamSpot - edits the GlobalTag ESSource to load the tags used to produce the HLT beamspot - these tags are not available in the Offline GT, which is the GT presently used in HLT+RECO tests - not loading t...
5,350,427
def path_to_filename(username, path_to_file): """ Converts a path formated as path/to/file.txt to a filename, ie. path_to_file.txt """ filename = '{}_{}'.format(username, path_to_file) filename = filename.replace('/','_') print(filename) return filename
5,350,428
def _convert_artist_format(artists: List[str]) -> str: """Returns converted artist format""" formatted = "" for x in artists: formatted += x + ", " return formatted[:-2]
5,350,429
def slerp(val, low, high): """ Spherical interpolation. val has a range of 0 to 1. From Tom White 2016 :param val: interpolation mixture value :param low: first latent vector :param high: second latent vector :return: """ if val <= 0: return low elif val >= 1: ...
5,350,430
async def verify_input_body_is_json( request: web.Request, handler: Handler ) -> web.StreamResponse: """ Middleware to verify that input body is of json format """ if request.can_read_body: try: await request.json() except json.decoder.JSONDecodeError: raise w...
5,350,431
def svn_repos_get_logs4(*args): """ svn_repos_get_logs4(svn_repos_t repos, apr_array_header_t paths, svn_revnum_t start, svn_revnum_t end, int limit, svn_boolean_t discover_changed_paths, svn_boolean_t strict_node_history, svn_boolean_t include_merged_revisions, apr_array...
5,350,432
def _setup_lte(hass, lte_config) -> None: """Set up Huawei LTE router.""" from huawei_lte_api.AuthorizedConnection import AuthorizedConnection from huawei_lte_api.Client import Client url = lte_config[CONF_URL] username = lte_config[CONF_USERNAME] password = lte_config[CONF_PASSWORD] conne...
5,350,433
def linreg_predict(model, X, v=False): """ Prediction with linear regression yhat[i] = E[y|X[i, :]], model] v[i] = Var[y|X[i, :], model] """ if 'preproc' in model: X = preprocessor_apply_to_test(model['preproc'], X) yhat = X.dot(model['w']) return yhat
5,350,434
def create_db_with_tables(): """Creates testing database if it doesn't exist, and then loads in the Mosaiq mimic tables. """ mocks.check_create_test_db(database=DATABASE) create_mimic_tables(DATABASE)
5,350,435
def parse_hostportstr(hostportstr): """ Parse hostportstr like 'xxx.xxx.xxx.xxx:xxx' """ host = hostportstr.split(':')[0] port = int(hostportstr.split(':')[1]) return host, port
5,350,436
def sigmoid_grad_input(x_input, grad_output): """sigmoid nonlinearity gradient. Calculate the partial derivative of the loss with respect to the input of the layer # Arguments x_input: np.array of size `(n_objects, n_in)` grad_output: np.array of size `(n_objects, n_in)` ...
5,350,437
def test_406_gpload_external_schema_merge(): """406 test gpload works with schema test and write as "Test" in config""" TestBase.drop_tables() schema = '"Test"' f = open(TestBase.mkpath('query406.sql'), 'a') f.write("\\! gpload -f "+TestBase.mkpath('config/config_file1')+'\n') f.write("\\! psql ...
5,350,438
def p(draw_p: Turtle) -> None: """Draws a flower.""" r: int = randint(0, 256) g: int = randint(0, 256) b: int = randint(0, 256) x: float = random.uniform(-250, 250) y: float = random.uniform(-250, 250) draw_p.penup() draw_p.goto(x, y) draw_p.pendown() # begins drawing i: int = 0...
5,350,439
def f_is3byte(*args): """f_is3byte(flags_t F, void ?) -> bool""" return _idaapi.f_is3byte(*args)
5,350,440
def make_desired_disp(vertices, DeformType = DispType.random, num_of_vertices = -1): """ DispType.random: Makes a random displacement field. The first 3 degrees of freedom are assumed to be zero in order to fix rotation and translation of the lattice. DispType.isotropic: Every point moves towards the ...
5,350,441
def unix_sort_ranks(corpus: set, tmp_folder_path: str): """ Function that takes a corpus sorts it with the unix sort -n command and generates the global ranks for each value in the corpus. Parameters ---------- corpus: set The corpus (all the unique values from every...
5,350,442
def test_invalid_input(invalid_array): """Validates taht array given is return an error for wrong input datatype.""" with pytest.raises(TypeError): quickSort(invalid_array)
5,350,443
def do_filter(): """Vapoursynth filtering""" opstart_ep10 = 768 ncop = JPBD_NCOP.src_cut ep10 = JPBD_10.src_cut ncop = lvf.rfs(ncop, ep10[opstart_ep10:], [(0, 79), (1035, 1037)]) return ncop
5,350,444
def test_returns_less_than_expected_errors(configured_test_manager): """A function that doesn't return the same number of objects as specified in the stage outputs should throw an OutputSignatureError.""" @stage([], ["test1", "test2"]) def output_stage(record): return "hello world" record = Re...
5,350,445
async def test_emergency_ssl_certificate_when_invalid(hass, tmpdir, caplog): """Test http can startup with an emergency self signed cert when the current one is broken.""" cert_path, key_path = await hass.async_add_executor_job( _setup_broken_ssl_pem_files, tmpdir ) hass.config.safe_mode = Tru...
5,350,446
def test_ending(): """Game ends""" rv, out = getstatusoutput(f'{prg} Lia Humberto -s 1') assert re.search("GAME OVER! Final Scores: {'Lia': 10, 'Humberto': 20}")
5,350,447
def main(): """ エントリポイント """ config.read(CONFIG_FILE) if 'PHPSESSID' not in config['DEFAULT']: phpsessid = get_phpsessionid() if not phpsessid: sys.stderr.write('PHPSESSIDの取得に失敗しました。\n') sys.exit(1) else: phpsessid = config['DEFAULT']['PHPSESSID'] c...
5,350,448
async def test_http_error401(aresponses, status): """Test HTTP 401 response handling.""" aresponses.add( "example.com", "/api/v1/smartmeter", "GET", aresponses.Response(text="Give me energy!", status=status), ) async with aiohttp.ClientSession() as session: clien...
5,350,449
def xgb(validate = True): """ Load XGB language detection model. Parameters ---------- validate: bool, optional (default=True) if True, malaya will check model availability and download if not available. Returns ------- LANGUAGE_DETECTION : malaya._models._sklearn_model.LANGUAGE...
5,350,450
def get_current_data(csv_file): """ Gathers and returns list of lists of current information based in hourly data from NOAA's National Data Buoy Center archived data. Returned list format is [current depths, current speeds, current directions]. Input parameter is any CSV or text file with the same forma...
5,350,451
def _get_batched_jittered_initial_points( model: Model, chains: int, initvals: Optional[Union[StartDict, Sequence[Optional[StartDict]]]], random_seed: int, jitter: bool = True, jitter_max_retries: int = 10, ) -> Union[np.ndarray, List[np.ndarray]]: """Get jittered initial point in format exp...
5,350,452
def load_schema(url, resolver=None, resolve_references=False, resolve_local_refs=False): """ Load a schema from the given URL. Parameters ---------- url : str The path to the schema resolver : callable, optional A callback function used to map URIs to other URIs...
5,350,453
def fastaDecodeHeader(fastaHeader): """Decodes the fasta header """ return fastaHeader.split("|")
5,350,454
def run_sc_test (config) : """ Test model. """ """Load problem.""" if not os.path.exists (config.probfn): raise ValueError ("Problem file not found.") else: p = problem.load_problem (config.probfn) """Load testing data.""" xt = np.load (config.xtest) ""...
5,350,455
def setup_module(module): """ setup any state specific to the execution of the given module.""" child = pexpect.spawn('mlsteam login --address {} --username superuser --data-port {}'.format(API_SERVER_ADDRESS, DATA_PORT)) child....
5,350,456
def test_modulesSimpleFlow(env): """ This simple test ensures that we can load two modules on RLTest and their commands are properly accessible @param env: """ checkSampleModules(env)
5,350,457
def tau_for_x(x, beta): """Rescales tau axis to x -1 ... 1""" if x.min() < -1 or x.max() > 1: raise ValueError("domain of x") return .5 * beta * (x + 1)
5,350,458
def _add_to_dataset( client, urls, name, external=False, force=False, overwrite=False, create=False, sources=(), destination="", ref=None, ): """Add data to a dataset.""" if not client.has_datasets_provenance(): raise errors.OperationError("Dataset provenance is n...
5,350,459
def test_for_404(api, json_response): """Test for 404 handling""" httpretty.enable() body = json.dumps({'message': 'not found'}) httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/info", body=json_response, status=200, content_type="application/json") ...
5,350,460
def load_env(): """Get the path to the .env file and load it.""" env_file = os.path.join(os.path.dirname(__file__), os.pardir, ".env") dotenv.read_dotenv(env_file)
5,350,461
def _generate_element(name: str, text: Optional[str] = None, attributes: Optional[Dict] = None) -> etree.Element: """ generate an ElementTree.Element object :param name: namespace+tag_name of the element :param text: Text of the element. Default is None :...
5,350,462
def CoA_Cropland_URL_helper(*, build_url, config, **_): """ This helper function uses the "build_url" input from flowbyactivity.py, which is a base url for data imports that requires parts of the url text string to be replaced with info specific to the data year. This function does not parse the dat...
5,350,463
def _centered_bias(logits_dimension, head_name=None): """Returns `logits`, optionally with centered bias applied. Args: logits_dimension: Last dimension of `logits`. Must be >= 1. head_name: Optional name of the head. Returns: Centered bias `Variable`. Raises: ValueError: if `logits_dimension...
5,350,464
def get_columns(dataframe: pd.DataFrame, columns: Union[str, List[str]]) -> Union[pd.Series, pd.DataFrame]: """Get the column names, and can rename according to list""" return dataframe[list(columns)].copy(True)
5,350,465
def get_vote_activity(session): """Create a plot showing the inline usage statistics.""" creation_date = func.date_trunc("day", Vote.created_at).label("creation_date") votes = ( session.query(creation_date, func.count(Vote.id).label("count")) .group_by(creation_date) .order_by(creati...
5,350,466
def notebook(ctx): """ Start IPython notebook server. """ with setenv(PYTHONPATH='{root}/core:{root}:{root}/tests'.format(root=ROOT_DIR), JUPYTER_CONFIG_DIR='{root}/notebooks'.format(root=ROOT_DIR)): os.chdir('notebooks') # Need pty=True to let Ctrl-C kill the notebook ...
5,350,467
def viz_graph(obj): """ Generate the visulization of the graph in the JupyterLab Arguments ------- obj: list a list of Python object that defines the nodes Returns ----- nx.DiGraph """ G = nx.DiGraph() # instantiate objects for o in obj: for i in o['input...
5,350,468
def zrand_convolve(labelgrid, neighbors='edges'): """ Calculates the avg and std z-Rand index using kernel over `labelgrid` Kernel is determined by `neighbors`, which can include all entries with touching edges (i.e., 4 neighbors) or corners (i.e., 8 neighbors). Parameters ---------- grid ...
5,350,469
def msg_receiver(): """ 消息已收界面 :return: """ return render_template('sysadmin/sysmsg/sys_msg_received.html', **locals())
5,350,470
def abs_timedelta(delta): """Returns an "absolute" value for a timedelta, always representing a time distance.""" if delta.days < 0: now = datetime.datetime.now() return now - (now + delta) return delta
5,350,471
def is_word_file(file): """ Check to see if the given file is a Word file. @param file (str) The path of the file to check. @return (bool) True if the file is a Word file, False if not. """ typ = subprocess.check_output(["file", file]) return ((b"Microsoft Office Word" in typ) or ...
5,350,472
def make_new_get_user_response(row): """ Returns an object containing only what needs to be sent back to the user. """ return { 'userName': row['userName'], 'categories': row['categories'], 'imageName': row['imageName'], 'refToImage': row['refToImage'], ...
5,350,473
def lock_retention_policy(bucket_name): """Locks the retention policy on a given bucket""" # bucket_name = "my-bucket" storage_client = storage.Client() # get_bucket gets the current metageneration value for the bucket, # required by lock_retention_policy. bucket = storage_client.get_buc...
5,350,474
def upload_bus_data(number: int) -> dict: """Загружает данные по матерям из базы""" logger.debug("Стартует upload_bus_data") try: query = ProfilsCows.select().where( ProfilsCows.number == number ) if query.exists(): bus = ProfilsCows.select().where( ...
5,350,475
def is_feature_enabled(): """ Helper to check Site Configuration for ENABLE_COURSE_ACCESS_GROUPS. :return: bool """ is_enabled = bool(configuration_helpers.get_value('ENABLE_COURSE_ACCESS_GROUPS', default=False)) if is_enabled: # Keep the line below in sync with `util.organizations_hel...
5,350,476
def solve_disp_eq(betbn, betbt, bet, Znak, c, It, Ia, nb, var): """ Решение дисперсионного уравнения. Znak = -1 при преломлении Znak = 1 при отражении """ betb = sqrt(betbn ** 2. + betbt ** 2.) gamb = 1. / sqrt(1. - betb ** 2.) d = c * It / Ia Ab = 1. + (nb ** 2. - 1.) * gamb ** 2. *...
5,350,477
def phistogram(view, a, bins=10, rng=None, normed=False): """Compute the histogram of a remote array a. Parameters ---------- view IPython DirectView instance a : str String name of the remote array bins : int Number of histogram bins ...
5,350,478
async def test_reauth(opp): """Test we get the form.""" await setup.async_setup_component(opp, "persistent_notification", {}) mock_config = MockConfigEntry( domain=DOMAIN, unique_id="test-mac", data={ "host": "1.1.1.1", "hostname": "test-mac", "ssl...
5,350,479
def windowed(it: Iterable[_T], size: int) -> Iterator[tuple[_T, ...]]: """Retrieve overlapped windows from iterable. >>> [*windowed(range(5), 3)] [(0, 1, 2), (1, 2, 3), (2, 3, 4)] """ return zip(*(islice(it_, start, None) for start, it_ in enumerate(tee(it, size))))
5,350,480
def minmax(data): """Solution to exercise R-1.3. Takes a sequence of one or more numbers, and returns the smallest and largest numbers, in the form of a tuple of length two. Do not use the built-in functions min or max in implementing the solution. """ min_idx = 0 max_idx = 0 for idx, n...
5,350,481
def server_func(port): """ 服务端 """ # 1. 创建socket对象 server = socket.socket() # 2. 绑定ip和端口 server.bind(("127.0.0.1", port)) # 3. 监听是否有客户端连接 server.listen(10) print("服务端已经启动%s端口......" % port) # 4. 接收客户端连接 sock_obj, address = server.accept() sock_obj.settimeout(3) ...
5,350,482
def sample_discreate(prob, n_samples): """根据类先验分布对标签值进行采样 M = sample_discreate(prob, n_samples) Input: prob: 类先验分布 shape=(n_classes,) n_samples: 需要采样的数量 shape = (n_samples,) Output: M: 采样得到的样本类别 shape = (n_samples,) 例子: sample_discreate([0.8,0.2],n_sa...
5,350,483
def get_catalyst_pmids(first, middle, last, email, affiliation=None): """ Given an author's identifiers and affiliation information, optional lists of pmids, call the catalyst service to retrieve PMIDS for the author and return a list of PMIDS :param first: author first name :param middle: author mi...
5,350,484
def validar(request, op): """ Método que verifica consistência a partir de um log """ lista_datas = [] # arquivo de log para consistência with open(settings.BASE_DIR + "/log.txt", "r+") as fileobj: for line in fileobj: #pega cada linha do arquivo if "inicio" in line: ...
5,350,485
def upload_categories_to_fyle(workspace_id): """ Upload categories to Fyle """ try: fyle_credentials: FyleCredential = FyleCredential.objects.get(workspace_id=workspace_id) xero_credentials: XeroCredentials = XeroCredentials.objects.get(workspace_id=workspace_id) fyle_connection...
5,350,486
def georegister_px_df(df, im_fname=None, affine_obj=None, crs=None, geom_col='geometry', precision=None): """Convert a dataframe of geometries in pixel coordinates to a geo CRS. Arguments --------- df : :class:`pandas.DataFrame` A :class:`pandas.DataFrame` with polygons in...
5,350,487
def load_ui_type(ui_file): """ Pyside "load_ui_type" command like PyQt4 has one, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. """ parsed = xml.parse(ui_file) widget_class = parsed.find('widget').get(...
5,350,488
def how_did_I_do(MLP, df, samples, expected): """Simple report of expected inputs versus actual outputs.""" predictions = MLP.predict(df[samples].to_list()) _df = pd.DataFrame({"Expected": df[expected], "Predicted": predictions}) _df["Correct"] = _df["Expected"] == _df["Predicted"] print(f'The netwo...
5,350,489
def all_bootstrap_os(): """Return a list of all the OS that can be used to bootstrap Spack""" return list(data()['images'])
5,350,490
def coords_to_volume(coords: np.ndarray, v_size: int, noise_treatment: bool = False) -> np.ndarray: """Converts coordinates to binary voxels.""" # Input is centered on [0,0,0]. return weights_to_volume(coords=coords, weights=1, v_size=v_size, noise_treatment=noise_treatment)
5,350,491
def logo(symbol, external=False, vprint=False): """:return: Google APIs link to the logo for the requested ticker. :param symbol: The ticker or symbol of the stock you would like to request. :type symbol: string, required """ instance = iexCommon('stock', symbol, 'logo', external=external) retu...
5,350,492
def get_dependency_node(element): """ Returns a Maya MFnDependencyNode from the given element :param element: Maya node to return a dependency node class object :type element: string """ # adds the elements into an maya selection list m_selectin_list = OpenMaya.MSelectionList() m_selectin_...
5,350,493
def create_lineal_data(slope=1, bias=0, spread=0.25, data_size=50): """ Helper function to create lineal data. :param slope: slope of the lineal function. :param bias: bias of the lineal function. :param spread: spread of the normal distribution. :param data_size: number of samples to generate....
5,350,494
def parse_station_resp(fid): """ Gather information from a single station IRIS response file *fid*. Return the information as a :class:`RespMap`. """ resp_map = RespMap() # sanity check initialization network = None stn = None location = None # skip initial header comment block ...
5,350,495
def plot_pol(image, figsize=(8,8), print_stats=True, scaled=True, evpa_ticks=True): """Mimics the plot_pol.py script in ipole/scripts""" fig, ax = plt.subplots(2, 2, figsize=figsize) # Total intensity plot_I(ax[0,0], image, xlabel=False) # Quiver on intensity if evpa_ticks: plot_evpa_ti...
5,350,496
def dbrg(ds, T, r): """ Segmentation by density-based region growing (DBRG). Parameters ---------- ds : np.ndarray The mask image. T : float Initial mask threshold. r : int Density connectivity search radius. """ M = _generate_init_mask(ds, T) D = _densit...
5,350,497
def convert_ion_balance_tables(run_file, output_file, elements): """ Convert ascii ion balance tables to hdf5. Parameters ---------- run_file : string Path to the input file ending in .run. output_file : string HDF5 output file name. elements : list List of elements ...
5,350,498
def _ensure_dtype_type(value, dtype: DtypeObj): """ Ensure that the given value is an instance of the given dtype. e.g. if out dtype is np.complex64_, we should have an instance of that as opposed to a python complex object. Parameters ---------- value : object dtype : np.dtype or Exte...
5,350,499