content
stringlengths
22
815k
id
int64
0
4.91M
def cli(ctx, path, max_depth=1): """List files available from a remote repository for a local path as a tree Output: None """ return ctx.gi.file.tree(path, max_depth=max_depth)
5,329,200
def warp_p(binary_img): """ Warps binary_image using hard coded source and destination vertices. Returns warped binary image, warp matrix and inverse matrix. """ src = np.float32([[580, 450], [180, 720], [1120, 720], [700, ...
5,329,201
async def _async_setup_entity( config, async_add_entities, config_entry=None, discovery_data=None ): """Set up the MQTT number.""" async_add_entities([MqttNumber(config, config_entry, discovery_data)])
5,329,202
def _get_xml_sps(document): """ Download XML file and instantiate a `SPS_Package` Parameters ---------- document : opac_schema.v1.models.Article Returns ------- dsm.data.sps_package.SPS_Package """ # download XML file content = reqs.requests_get_content(document.xml) x...
5,329,203
def moving_pairs(iterable: Iterable) -> Iterator: """ Generate moving pair elements over iterable. e.g. (1, 2), (2, 3) from iterable 1, 2, 3. :param iterable: :yields: moving pair on iterable """ iterator = iter(iterable) try: previous = next(iterator) except StopIteration: ...
5,329,204
def plot_confusion_matrix(ax, y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ From scikit-learn example: https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html ...
5,329,205
def _in_docker(): """ Returns: True if running in a Docker container, else False """ with open('/proc/1/cgroup', 'rt') as ifh: if 'docker' in ifh.read(): print('in docker, skipping benchmark') return True return False
5,329,206
def asPosition(flags): """ Translate a directional flag from an actions into a tuple indicating the targeted tile. If no directional flag is found in the inputs, returns (0, 0). """ if flags & NORTH: return 0, 1 elif flags & SOUTH: return 0, -1 elif flags & EAST: ...
5,329,207
def write(file_name, data): """Write data as JSON to file. Args: file_name (str): file name data: data as serializable object """ filex.write(file_name, json.dumps(data, indent=2))
5,329,208
def pickvol(filenames, fileidx, which): """Retrieve index of named volume Parameters ---------- filenames: list of 4D file names fileidx: which 4D file to look at which: 'first' or 'middle' Returns ------- idx: index of first or middle volume """ from nibabel import load ...
5,329,209
def update_tmp_lineage_collection(): """ Creates a lineage field in the temporary collection, and assigns it the value of True or False based on the corresponding record in the pangolin collection. Modifies the lineage_tmp collection as a side-effect """ print("Updating lineage values for sequen...
5,329,210
def merge(d, **kwargs): """Recursively merges given kwargs int to a dict - only if the values are not None. """ for key, value in kwargs.items(): if isinstance(value, dict): d[key] = merge(d.get(key, {}), **value) elif value is not None: d[key] = value return ...
5,329,211
def test_search_orgs_for_affiliation(client, jwt, session, keycloak_mock): # pylint:disable=unused-argument """Assert that search org with affiliation works.""" headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.passcode) client.post('/api/v1/entities', data=json.dumps(TestEntityInfo.entity_lear_m...
5,329,212
def post_process(config_file): """Show first level groups keys and attributes on a hdf5 file. Parameters ---------- hdf5_path : Path Hdf5 file to be investigated. Returns ------- List of str Keys of first level groups. List of str Attributes names of first level...
5,329,213
def init_config_flow(hass): """Init a configuration flow.""" flow = config_flow.VelbusConfigFlow() flow.hass = hass return flow
5,329,214
def test_variant_allele_index_extractor(genotype, expected): """ Tests the extraction of the variant allele index from the vcf """ idx = VariantAlleleIndexExtractor.extract(genotype) assert idx == expected
5,329,215
def validate_project_name(): """ This validator is used to ensure that `project_name` is valid. Valid inputs starts with the lowercase letter. Followed by any lowercase letters, numbers or underscores. Valid example: `school_project3`. """ if not re.match(MODULE_REGEX, MODULE_NAME): ...
5,329,216
def read_service_ids_by_date(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find all service identifiers by date""" feed = load_raw_feed(path) return _service_ids_by_date(feed)
5,329,217
def get_all_services(org_id: str) -> tuple: """ **public_services_api** returns a service governed by organization_id and service_id :param org_id: :return: """ return services_view.return_services(organization_id=org_id)
5,329,218
def test_values(): """Test the values function.""" table = (('foo', 'bar', 'baz'), ('a', 1, True), ('b', 2), ('b', 7, False)) actual = values(table, 'foo') expect = ('a', 'b', 'b') ieq(expect, actual) ieq(expect, actual) actual ...
5,329,219
def get_initializer(initializer_range=0.02): """Creates a `tf.initializers.truncated_normal` with the given range. Args: initializer_range: float, initializer range for stddev. Returns: TruncatedNormal initializer with stddev = `initializer_range`. """ return tf.keras.initializers...
5,329,220
def test_file_created(): """Test if csv file was created""" aux = [['16', 'Kinect Adventures!', 'X360', '2010', 'Misc' , 'Microsoft Game Studios', '14.97', '4.94', '0.24', '1.67', '21.82']] CsvOperations.create_file(aux) file_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)...
5,329,221
async def character_info(message: types.Message): """ Responds to the /char <name> command :param message: :return: """ character = message.text find = ' '.join(character.split(' ')[1:]) logger.info(f"{message.from_user.full_name} send /char {find}") variables = {"query": find} ...
5,329,222
def findh_s0(h_max, h_min, q): """ Znajduje siłę naciągu metodą numeryczną (wykorzystana metoda bisekcji), należy podać granice górną i dolną dla metody bisekcji :param h_max: Górna granica dla szukania siły naciągu :param h_min: Dolna granica dla szukania siły naciągu :param q: całkowite obcią...
5,329,223
async def test_no_clients(hass): """Test the update_clients function when no clients are found.""" await setup_unifi_integration( hass, ENTRY_CONFIG, options={}, clients_response={}, devices_response={}, clients_all_response={}, ) assert len(hass.states.a...
5,329,224
def velocity_dependent_covariance(vel): """ This function computes the noise in the velocity channel. The noise generated is gaussian centered around 0, with sd = a + b*v; where a = 0.01; b = 0.05 (Vul, Frank, Tenenbaum, Alvarez 2009) :param vel: :return: covariance """ cov = [] for...
5,329,225
def get_db_path(): """Return the path to Dropbox's info.json file with user-settings.""" if os.name == 'posix': # OSX-specific home_path = os.path.expanduser('~') dbox_db_path = os.path.join(home_path, '.dropbox', 'info.json') elif os.name == 'nt': # Windows-specific home_path = o...
5,329,226
def msd_Correlation(allX): """Autocorrelation part of MSD.""" M = allX.shape[0] # numpy with MKL (i.e. intelpython distribution), the fft wont be # accelerated unless axis along 0 or -1 # perform FT along n_frame axis # (n_frams, n_particles, n_dim) -> (n_frames_Ft, n_particles, n_dim) allFX...
5,329,227
def convert_table_value(fuel_usage_value): """ The graph is a little skewed, so this prepares the data for that. 0 = 0 1 = 25% 2 = 50% 3 = 100% 4 = 200% 5 = 400% 6 = 800% 7 = 1600% (not shown) Intermediate values scale between those values. (5.5 is 600%) """ if fuel...
5,329,228
def FindMSBuildInstallation(msvs_version = 'auto'): """Returns path to MSBuild for msvs_version or latest available. Looks in the registry to find install location of MSBuild. MSBuild before v4.0 will not build c++ projects, so only use newer versions. """ import TestWin registry = TestWin.Registry() ms...
5,329,229
def create_toc_xhtml(metadata: WorkMetadata, spine: list[Matter]) -> str: """ Load the default `toc.xhtml` file, and generate the required terms for the creative work. Return xhtml as a string. Parameters ---------- metadata: WorkMetadata All the terms for updating the work, not all com...
5,329,230
def convertSLToNumzero(sl, min_sl=1e-3): """ Converts a (neg or pos) significance level to a count of significant zeroes. Parameters ---------- sl: float Returns ------- float """ if np.isnan(sl): return 0 if sl < 0: sl = min(sl, -min_sl) num_zero = np.log10(-sl) elif sl > 0: ...
5,329,231
def test_get_migrations_path(): """ gets the application migrations path. """ root_path = application_services.get_application_main_package_path() migrations_path = os.path.abspath(os.path.join(root_path, 'migrations')) assert application_services.get_migrations_path() == migrations_path
5,329,232
def downloadKeggInfo(args): """ Download necessary information from Kegg Database for parsing. Arguments: :param geneKeggAnnot: Gene to KEGG ID Link file :type geneKeggAnnot: file :param metKeggAnnot: Metabolite to KEGG ID Link file :type metKeggAnnot: file Returns: ...
5,329,233
def calibrate_time_domain(power_spectrum, data_pkt): """ Return a list of the calibrated time domain data :param list power_spectrum: spectral data of the time domain data :param data_pkt: a RTSA VRT data packet :type data_pkt: pyrf.vrt.DataPacket :returns: a list containing the calibrated tim...
5,329,234
def func(x): """ :param x: [b, 2] :return: """ z = tf.math.sin(x[...,0]) + tf.math.sin(x[...,1]) return z
5,329,235
def parse_handler_input(handler_input: HandlerInput, ) -> Tuple[UserMessage, Dict[str, Any]]: """Parses the ASK-SDK HandlerInput into Slowbro UserMessage. Returns the UserMessage object and serialized SessionAttributes. """ request_envelope = handler_input.request_envelope ...
5,329,236
def _validate_show_for_invoking_user_only(show_for_invoking_user_only): """ Validates the given `show_for_invoking_user_only` value. Parameters ---------- show_for_invoking_user_only : `None` or `bool` The `show_for_invoking_user_only` value to validate. Returns ------- show_fo...
5,329,237
def process_frame(df, country_map, reg_func, formula, model_num): """Processes one frame. df: DataFrame country_map: map from code to Country reg_func: function used to compute regression formula: string Patsy formula model_num: which model we're running """ grouped = df.groupby('cn...
5,329,238
def dismiss_get_app_offer(browser, logger): """ Dismiss 'Get the Instagram App' page after a fresh login """ offer_elem = read_xpath(dismiss_get_app_offer.__name__, "offer_elem") dismiss_elem = read_xpath(dismiss_get_app_offer.__name__, "dismiss_elem") # wait a bit and see if the 'Get App' offer rises ...
5,329,239
def test_db_transaction_n1(monkeypatch): """Raise _DB_TRANSACTION_ATTEMPTS OperationalErrors to force a reconnection. A cursor for each SQL statement should be returned in the order the statement were submitted. 0. The first statement execution produce no results _DB_TRANSACTION_ATTEMPTS times (Operat...
5,329,240
def fetch_status(): """ 解析サイト<https://redive.estertion.win> からクラバト情報を取ってくる return ---- ``` { "cb_start": datetime, "cb_end": datetime, "cb_days": int } ``` """ # クラバト開催情報取得 r = requests.get( "https://redive.estertion.win/ver_log_redive/?page=1...
5,329,241
def data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_post(uuid, tapi_path_computation_routing_constraint=None): # noqa: E501 """data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_post creates tapi.path.computation.RoutingConstraint # noqa: E501 :p...
5,329,242
def date_range(start, end, step): """ Generator that yields a tuple of datetime-like objects which are `step` apart until the final `end` date is reached. """ curr = start while curr < end: next_ = curr + step # next step is bigger than end date # yield last (shorter)...
5,329,243
def A004086(i: int) -> int: """Digit reversal of i.""" result = 0 while i > 0: unit = i % 10 result = result * 10 + unit i = i // 10 return result
5,329,244
def should_raise_sequencingerror(wait, nrep, jump_to, goto, num_elms): """ Function to tell us whether a SequencingError should be raised """ if wait not in [0, 1]: return True if nrep not in range(0, 16384): return True if jump_to not in range(-1, num_elms+1): return Tru...
5,329,245
def add_task_with_sentinels( task_name: str, num_sentinels: Optional[int] = 1): """Adds sentinels to the inputs/outputs of a task. Adds num_sentinels sentinels to the end of 'inputs' and at the beginning of 'targets'. This is known to help fine-tuning span corruption models, especially on smaller datas...
5,329,246
def to_routing_header(params): """Returns a routing header string for the given request parameters. Args: params (Mapping[str, Any]): A dictionary containing the request parameters used for routing. Returns: str: The routing header string. """ if sys.version_info[0] < 3...
5,329,247
def mk_llfdi(data_id, data): # measurement group 10 """ transforms a k-llfdi.json form into the triples used by insertMeasurementGroup to store each measurement that is in the form :param data_id: unique id from the json form :param data: data array from the json...
5,329,248
def valid_distro(x): """ Validates that arg is a Distro type, and has :param x: :return: """ if not isinstance(x, Distro): return False result = True for required in ["arch", "variant"]: val = getattr(x, required) if not isinstance(val, str): result =...
5,329,249
def stop_stream_to_online(feature_table: str): """ Start stream to online sync job. """ import feast.pyspark.aws.jobs feast.pyspark.aws.jobs.stop_stream_to_online(feature_table)
5,329,250
def validate(dataloader, model, criterion, total_batches, debug_steps=100, local_logger=None, master_logger=None, save='./'): """Validation for the whole dataset Args: dataloader: paddle.io.DataLoader, dataloader ...
5,329,251
def encode(message): """ Кодирует строку в соответсвие с таблицей азбуки Морзе >>> encode('MAI-PYTHON-2020') # doctest: +SKIP '-- .- .. -....- .--. -.-- - .... --- -. -....- ..--- ----- ..--- -----' >>> encode('SOS') '... --- ...' >>> encode('МАИ-ПИТОН-2020') # doctest: +ELLI...
5,329,252
def get_group_to_elasticsearch_processor(): """ This processor adds users from xform submissions that come in to the User Index if they don't exist in HQ """ return ElasticProcessor( elasticsearch=get_es_new(), index_info=GROUP_INDEX_INFO, )
5,329,253
def main(): """Main""" # Skip manual check if len(sys.argv) > 1: if sys.argv[1] == 'manualcheck': print 'Manual check: skipping' exit(0) # Check OS version and skip if too old if getOsVersion() < 12: print 'Skipping iBridge check, OS does not suppo...
5,329,254
def loss_function(recon_x, x, mu, logvar, flattened_image_size = 1024): """ from https://github.com/pytorch/examples/blob/master/vae/main.py """ BCE = nn.functional.binary_cross_entropy(recon_x, x.view(-1, flattened_image_size), reduction='sum') # see Appendix B from VAE paper: # Kingma an...
5,329,255
def remove_poly(values, poly_fit=0): """ Calculates best fit polynomial and removes it from the record """ x = np.linspace(0, 1.0, len(values)) cofs = np.polyfit(x, values, poly_fit) y_cor = 0 * x for co in range(len(cofs)): mods = x ** (poly_fit - co) y_cor += cofs[co] * mo...
5,329,256
def generate_per_host_enqueue_ops_fn_for_host( ctx, input_fn, inputs_structure_recorder, batch_axis, device, host_id): """Generates infeed enqueue ops for per-host input_fn on a single host.""" captured_infeed_queue = _CapturedObject() hooks = [] with ops.device(device): user_context = tpu_context.TPU...
5,329,257
def download(): """ curl -o haproxy.tar.gz https://www.haproxy.org/download/1.9/src/haproxy-1.9.0.tar.gz tar xzf haproxy.tar.gz """ with cd("/usr/src"), settings(warn_only=True): for line in download.__doc__.split("\n"): sudo(line)
5,329,258
def test_rename_columns(dupcols): """Test renaming columns in a data frame with duplicate column names.""" # Rename the first column d1 = rename(dupcols, columns='Name', names='Person') assert d1.columns[0] == 'Person' assert dupcols.columns[0] == 'Name' assert d1.columns[1] == 'A' assert d1...
5,329,259
def by_location(aoi, year, lon, lat, chipsize=512, extend=512, tms=['Google'], axis=True, debug=False): """Download the background image with parcels polygon overlay by selected location. This function will get an image from the center of the polygon. Examples: from cbm.view import ...
5,329,260
def from_path(path, vars=None, *args, **kwargs): """Read a scenario configuration and construct a new scenario instance. Args: path (basestring): Path to a configuration file. `path` may be a directory containing a single configuration file. *args: Arguments passed to Scenario __init__. **kwargs:...
5,329,261
def test_get_next_payment_date(controller: Controller): """Check that client can get next_payment_date attribute for subscriptions in subscription list""" subscriptions_list = controller.get_subscriptions_list() assert type(subscriptions_list[0]) == Subscription for subs in subscriptions_list: a...
5,329,262
def SogouNews(*args, **kwargs): """ Defines SogouNews datasets. The labels includes: - 0 : Sports - 1 : Finance - 2 : Entertainment - 3 : Automobile - 4 : Technology Create supervised learning dataset: SogouNews Separately returns the tra...
5,329,263
def test_unasigned_unknowns_are_kept(): """Test that existing unasigned unknown variables are kept empty.""" set_dotenv( """ UNKNOWN_VARIABLE """ ) dotenver.parse_files([TEMPLATE_FILE.name], override=False) expected = """ STATIC_VARIABLE=static export FALSE_VARIABLE=False TRUE_VARIABLE=Tru...
5,329,264
async def async_iter(iterator): """Returns an async generator""" for item in iterator: yield item
5,329,265
def add_volume (activity_cluster_df, activity_counts): """Scales log of session counts of each activity and merges into activities dataframe Parameters ---------- activity_cluster_df : dataframe Pandas dataframe of activities, skipgrams features, and cluster la...
5,329,266
def handle_message(message): """ Where `message` is a string that has already been stripped and lower-cased, tokenize it and find the corresponding Hand in the database. (Also: return some helpful examples if requested, or an error message if the input cannot be parsed.) """ if 'example' in mes...
5,329,267
def MemoizedSingleCall(functor): """Decorator for simple functor targets, caching the results The functor must accept no arguments beyond either a class or self (depending on if this is used in a classmethod/instancemethod context). Results of the wrapped method will be written to the class/instance namespace...
5,329,268
def polyadd(c1, c2): """ Add one polynomial to another. Returns the sum of two polynomials `c1` + `c2`. The arguments are sequences of coefficients from lowest order term to highest, i.e., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``. Parameters ---------- c1, c2 : array_lik...
5,329,269
def weighted_categorical_crossentropy(target, output, n_classes = 3, axis = None, from_logits=False): """Categorical crossentropy between an output tensor and a target tensor. Automatically computes the class weights from the target image and uses them to weight the cross entropy # Arguments target: A tensor of ...
5,329,270
def config(): """List the path to the Cards db.""" with cards_db() as db: print(db.path())
5,329,271
def get_config(key, default): """ Get the dictionary "IMPROVED_PERMISSIONS_SETTINGS" from the settings module. Return "default" if "key" is not present in the dictionary. """ from django.conf import settings config_dict = getattr(settings, 'IMPROVED_PERMISSIONS_SETTINGS', None) if c...
5,329,272
def fetch_protein_interaction(data_home=None): """Fetch the protein-interaction dataset Constant features were removed =========================== =================================== Domain drug-protein interaction network Features Biologic...
5,329,273
def prefetched_iterator(query, chunk_size=2000): """ This is a prefetch_related-safe version of what iterator() should do. It will sort and batch on the default django primary key Args: query (QuerySet): the django queryset to iterate chunk_size (int): the size of each chunk to fetch ...
5,329,274
def mousePressed(): """ mousePressed """ pass
5,329,275
def get_dir(foldername, path): """ Get directory relative to current file - if it doesn't exist create it. """ file_dir = os.path.join(path, foldername) if not os.path.isdir(file_dir): os.mkdir(os.path.join(path, foldername)) return file_dir
5,329,276
def add_img_to_frame(img, frame, offset): """put a smaller matrix into a larger frame, starting at a specific offset""" img = img.reshape((orig_size, orig_size)) for x in xrange(orig_size): frame[x + offset[0]][offset[1]: offset[1] + orig_size] = img[x]
5,329,277
def dicom_strfname( names: tuple) -> str: """ doe john s -> dicome name (DOE^JOHN^S) """ return "^".join(names)
5,329,278
def plot_new_data(logger): """ Plots mixing ratio data, creating plot files and queueing the files for upload. This will plot data, regardless of if there's any new data since it's not run continously. :param logger: logging logger to record to :return: bool, True if ran corrected, False if exit o...
5,329,279
def plot_graphs(graphs=compute_graphs()): """ Affiche les graphes avec la bibliothèque networkx """ GF, Gf = graphs pos = {1: (2, 1), 2: (4, 1), 3: (5, 2), 4: (4, 3), 5: (1, 3), 6: (1, 2), 7: (3, 4)} plt.figure(1) nx.draw_networkx_nodes(GF, pos, node_size=500) nx.draw_networkx_labels(GF, pos)...
5,329,280
def get_polygon_name(polygon): """Returns the name for a given polygon. Since not all plygons store their name in the same field, we have to figure out what type of polygon it is first, then reference the right field. Args: polygon: The polygon object to get the name from. Returns: The name for t...
5,329,281
def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return redirect("/login") # E...
5,329,282
def new(name): """ Create blueprint. """ g_blueprint(name)
5,329,283
def read_option(file_path, section, option, fallback=None): """ Parse config file and read out the value of a certain option. """ try: # For details see the notice in the header from . import paval as pv pv.path(file_path, "config", True, True) pv.string(section, "se...
5,329,284
def phietrack(df: pd.DataFrame, phi: list =None, lims: list = None, phi_range :list = [0,0.35], dtick: bool =False, ax=None, fontsize=8, correlation: pd.DataFrame = None, grid_numbers : list = [11,51], ...
5,329,285
def D20_roll(): """calls DX with dice_sides = 20""" roll_result.set(DX(D20_rolls.get(), 20, D20_modifier_var.get()))
5,329,286
def find_theme_file(theme_filename: pathlib.Path) -> pathlib.Path: """Find the real address of a theme file from the given one. First check if the user has the file in his themes. :param theme_file_path: The name of the file to look for. :return: A file path that exists with correct theme. """ ...
5,329,287
def msg_to_json(msg: Msg) -> json.Data: """Convert message to json serializable data""" return {'facility': msg.facility.name, 'severity': msg.severity.name, 'version': msg.version, 'timestamp': msg.timestamp, 'hostname': msg.hostname, 'app_name': msg....
5,329,288
def get_direct_dependencies(definitions_by_node: Definitions, node: Node) -> Nodes: """Get direct dependencies of a node""" dependencies = set([node]) def traverse_definition(definition: Definition): """Traverses a definition and adds them to the dependencies""" for dependency in definition...
5,329,289
def get_timeseries_metadata(request, file_type_id, series_id, resource_mode): """ Gets metadata html for the aggregation type (logical file type) :param request: :param file_type_id: id of the aggregation (logical file) object for which metadata in html format is needed :param series_id: if of ...
5,329,290
def standardize(tag): """Put an order-numbering ID3 tag into our standard form. This function does nothing when applied to a non-order-numbering tag. Args: tag: A mutagen ID3 tag, which is modified in-place. Returns: A 2-tuple with the decoded version of the order string. raises: ...
5,329,291
def test_composite_unit_get_format_name(): """See #1576""" unit1 = u.Unit('nrad/s') unit2 = u.Unit('Hz(1/2)') assert (str(u.CompositeUnit(1, [unit1, unit2], [1, -1])) == 'nrad / (Hz(1/2) s)')
5,329,292
def pop_layer_safe(lv: dict, pop_key: str): """Pops a child from a layer 'safely' in that it maintains the node's size Args: lv (dict): The node to pop a child from pop_key (str): The key to the child that should be popped """ lv.pop(pop_key) lv['size'] -= 1
5,329,293
def _count_objects(osm_pbf): """Count objects of each type in an .osm.pbf file.""" p = run(["osmium", "fileinfo", "-e", osm_pbf], stdout=PIPE, stderr=DEVNULL) fileinfo = p.stdout.decode() n_objects = {"nodes": 0, "ways": 0, "relations": 0} for line in fileinfo.split("\n"): for obj in n_objec...
5,329,294
def combine_multi_uncertainty(unc_lst): """Combines Uncertainty Values From More Than Two Sources""" ur = 0 for i in range(len(unc_lst)): ur += unc_lst[i] ** 2 ur = np.sqrt(float(ur)) return ur
5,329,295
def export_performance_df( dataframe: pd.DataFrame, rule_name: str = None, second_df: pd.DataFrame = None, relationship: str = None ) -> pd.DataFrame: """ Function used to calculate portfolio performance for data after calculating a trading signal/rule and relationship. """ if rule_name is not None:...
5,329,296
def attention(x, scope, n_head, n_timesteps): """ perform multi-head qkv dot-product attention and linear project result """ n_state = x.shape[-1].value with tf.variable_scope(scope): queries = conv1d(x, 'q', n_state) keys = conv1d(x, 'k', n_state) values = conv1d(x, 'v',...
5,329,297
def std_ver_minor_inst_valid_possible(std_ver_minor_uninst_valid_possible): # pylint: disable=redefined-outer-name """Return an instantiated IATI Version Number.""" return iati.Version(std_ver_minor_uninst_valid_possible)
5,329,298
def sequence_loss_by_example(logits, targets, weights, average_across_timesteps=True, softmax_loss_function=None, name=None): """Weighted cross-entropy loss for a sequence of logits (per example). Args: logits: List of 2D Tensors of shape [batch_size x n...
5,329,299