content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cbar_for_line_plot(axis, num_steps, discrete_ticks=True, **kwargs): """ Adds a colorbar next to a line plot axis Parameters ---------- axis : matplotlib.axes.Axes Axis with multiple line objects num_steps : uint Number of steps in the colorbar discrete_ticks : (optional)...
b9d83d93f7b86259a796cc71638a0bef0c81dce7
9,797
from typing import Union def get_config_based_on_config_file(path: str) -> Union[Config, None]: """ load config and check if section exist or not :param path: path to config file :return: None if section [laziest] not exist in Config object updated with params from section if exist """ cfg...
1a537aace82528ff1163deadeea3c48b9289c622
9,798
import typing import asyncio import concurrent def threadpooled( # noqa: F811 func: typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]] = None, *, loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None...
77a91a627569a069728531e2baaa92d8ee5609b3
9,799
def koven_temp_atten(soiltemp, airtemp): """Define thermal attenuation ratios as in Koven et al 2013.""" # read in list of observed lats and lons from Koven paper ex_points = permafrost_koven_sites.site_points # make amplitudes airtemp_ampl = make_monthly_amp(airtemp) soiltemp_ampl = make_month...
a9d0ab18cef1a311ee72fc653089acf96f157cf6
9,800
def clipup(step_size: float, momentum: float = 0.9, max_speed: float = 0.15, fix_gradient_size: bool = True): """Construct optimizer triple for ClipUp.""" step_size = optimizers.make_schedule(step_size) def init(x0): v0 = jnp.zeros_like(x0) return x0, v0 ...
7ab67ba4bfb164c2816b6dc478d0a99b85324b66
9,801
def ramsey_echo_sequence(length, target): """ Generate a gate sequence to measure dephasing time in a two-qubit chip including a flip in the middle. This echo reduce effects detrimental to the dephasing measurement. Parameters ---------- length : int Number of Identity gates. Should be ...
0fbe66b915e94b568b5c051c5982ee4e8aeaf945
9,802
import sympy def gauss_elimination(matrix) -> np.array: """ This function compute Gauss elimination process :param matrix: generic matrix :return: matrix after the Gauss elimination """ return np.array(sympy.Matrix(matrix).rref()[0])
e25cb59808ac189bd858d3fc564aec034d7fc841
9,803
def prune(value, is_removable_function=is_removable): """ Deletes ``None`` and empty lists and dicts, recursively. """ if isinstance(value, list): for i, v in enumerate(value): if is_removable_function(value, i, v): del value[i] else: prun...
1e254cf2df988f4c7e782b7dace82222e7f09910
9,804
import math def n_permutations(n, r=None): """Number of permutations (unique by position) :param n: population length :param r: sample length :return: int """ if r is None: r = n if n < 0 or r < 0: raise ValueError("n and r must be positive") if n == 0 or r > n: ...
441081c534c07bb98b6a32cce4c87d64b030a5a7
9,806
def parse_s3_event(event): """Decode the S3 `event` message generated by message write operations. See S3 docs: https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html See also the callers of this function. Returns bucket_name, ipppssoot """ log.verbose("S3 Ev...
bf9530d49191f29d1132188507da55c7568e26a6
9,807
def clip_2d_liang_barsky(xmin, ymin, xmax, ymax, x0, y0, x1, y1): """Clips the two-dimensional line segment by the algorithm of Liang and Barsky. Adapted from James D. Foley, ed., __Computer Graphics: Principles and Practice__ (Reading, Mass. [u.a.]: Addison-wesley, 1998), 122. Parameters --------...
d38dc2fcda72fe186d95befd1e0e2ef2c688297e
9,808
import re def _(pattern, key_path: str, case_ignored=False) -> bool: """Called when the concerned Key is defined as a re.Pattern, and case_ignored flag is neglected.""" return re.fullmatch(pattern, key_path) is not None
c5759a7940dcb9babc791322cac1397a640dc94d
9,809
def sophos_firewall_web_filter_update_command(client: Client, params: dict) -> CommandResults: """Update an existing object Args: client (Client): Sophos XG Firewall Client params (dict): params to update the object with Returns: CommandResults: Command results object """ r...
f8306dcce60de64dea3114137f0a27813f455a56
9,810
def transition_with_random_block(block_randomizer): """ Build a block transition with randomized data. Provide optional sub-transitions to advance some number of epochs or slots before applying the random block. """ return { "block_producer": block_randomizer, }
acf0d285a7633b40ffb46853831412dafa6617e5
9,811
def vmobj_to_list(o): """Converts TVM objects returned by VM execution to Python List. Parameters ---------- o : Obj VM Object as output from VM runtime executor. Returns ------- result : list Numpy objects as list with equivalent values to the input object. """ i...
8ecc9e22b47072adea98f1fc23f00a696619d0a4
9,812
import logging def fetch_run(workspace: Workspace, run_recovery_id: str) -> Run: """ Finds an existing run in an experiment, based on a recovery ID that contains the experiment ID and the actual RunId. The run can be specified either in the experiment_name:run_id format, or just the run_id. :param...
91255f02888ef1186d18e21e42c4343713bb3b29
9,813
def get_wl_band(radar_frequency): """Returns integer corresponding to radar frequency. Args: radar_frequency (float): Radar frequency (GHz). Returns: int: 0=35GHz radar, 1=94Ghz radar. """ return 0 if (30 < radar_frequency < 40) else 1
cf2eaa12f111f7ad6751fb31f58e0bc01666494a
9,814
def get_topology_node(name: str, topology: ServiceTopology) -> TopologyNode: """ Fetch a topology node by name :param name: node name :param topology: service topology with all nodes :return: TopologyNode """ node = topology.__dict__.get(name) if not node: raise ValueError(f"{nam...
996e6cc1e69a44eb1ce8e4e041d7af84d592e894
9,815
import hashlib def md5hash(string): """ Return the MD5 hex digest of the given string. """ return hashlib.md5(string).hexdigest()
cfc0d44c3c84fb08d277d7b397a5aca453025d96
9,816
def userlist(request): """Shows a user list.""" return common_userlist(request, locale=request.view_lang)
bdfd4477d352d62076d644e045d746a5912993e6
9,817
def return_heartrates(patient_id): """ access database to get heart rate history for a patient :param patient_id: integer ID of patient to get heart rates of :return: json with the heart rate list for patient, or error message """ patient_id = int(patient_id) if heart_server_helpers.valida...
864c3912bcd5be43c43c6ccfc17c0e6f675c7d6d
9,818
def describe_vpn_connections_header(): """generate output header""" return misc.format_line(( "Account", "Region", "VpcId", "VpcCidr", "VpnName", "VpnId", "State", "CutomerGwId", "CutomerGwAddress", "Ty...
5539f2beb017f9c2aaaa4b4a70952f1c17fa5761
9,819
def to_numpy(a): """Convert an object to NumPy. Args: a (object): Object to convert. Returns: `np.ndarray`: `a` as NumPy. """ return convert(a, NPOrNum)
4af733bd61256505d7db49d74d0dc1f96e10701d
9,820
def transpose(self, perm=None, copy=True): """Return a tensor with permuted axes. Parameters ---------- perm : Union[Sequence[int], dragon.Tensor]], optional The output permutation. copy : bool, optional, default=True Return a new tensor or transpose in-place. Returns -----...
be340cf2797555870020d55c163d2765346fd6fa
9,821
def brainrender_vis(regions, colors=None, atlas_name="allen_mouse_25um"): """Visualise regions in atlas using brainrender""" if colors is None: cm = ColorManager(num_colors=len(regions), method="rgb") colors = cm.colors def get_n_random_points_in_region(region, N): """ Gets...
a85fda126f482a5ee1be9b7d129f7b091bc26c79
9,822
def randsel(path, minlen=0, maxlen=None, unit="second"): """Randomly select a portion of audio from path. Parameters ---------- path: str File path to audio. minlen: float, optional Inclusive minimum length of selection in seconds or samples. maxlen: float, optional Excl...
de9e328eb025ab54f6a25bf1b028212470339c8d
9,823
import splunklib from datetime import datetime def parse_datetime(splunk_uri, session_key, time_str): """ Leverage splunkd to do time parseing, :time_str: ISO8601 format, 2011-07-06T21:54:23.000-07:00 """ if not time_str: return None scheme, host, port = tuple(splunk_uri.replace("/"...
bece967102ae37ec0cd1a1eb84e3bfc3eb5bef0f
9,824
def _get_assessment_url(assessment): """Returns string URL for assessment view page.""" return urlparse.urljoin(utils.get_url_root(), utils.view_url_for(assessment))
fd6c7a8dcb4a28a244645dcd93610d18682672b4
9,825
from typing import Set def get_secret_setting_names(settings: dict) -> Set[str]: """guess the setting names that likely contain sensitive values""" return { key for key in settings.keys() if AUTOFIND_SECRET_SETTINGS.match(key) and key not in AUTOFIND_SECRET_SETTINGS_EXCLUDED } | { ...
7cd7c8d90299d0bb3b143d10901ed33a90e85645
9,826
import base64 import requests def main(dict): """ Function that allows to send a get request to twitter API and retrieve the last 3 tweets of a specific account name. The parameter of the account is passed by Watson Assistant throught a context variable. Args: dict (dict): containing ...
5dddf4ad7c4ee45d1bf3a61f308989dffc451cc2
9,827
def build_classifier_model(tfhub_handle_preprocess, tfhub_handle_encoder): """Builds a simple binary classification model with BERT trunk.""" text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text') preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name='preprocessing') ...
03267ac3ab89acf3b6e7381e0149917371e1f29f
9,828
def execute_sql(sql: str, param: list): """ 执行查询sql, 返回列表 :param param: 执行参数 :param sql: 执行的sql语句 :return: 结果列表 """ cursor = connection.cursor() res = cursor.execute(sql, param) return res
cf33a7f4d6b6486def88e6a8256ebbfe8a5a2b0d
9,829
def query_jwt_required(fn): """ A decorator to protect a query resolver. If you decorate an resolver with this, it will ensure that the requester has a valid access token before allowing the resolver to be called. This does not check the freshness of the access token. """ @wraps(fn) def...
74d665dd853deb180554db13cfb40af5815d2858
9,830
def callers_for_code(code): """ Return all users matching the code. :param code: :return: """ return db.session.query(Caller).filter(Caller.code==code).all()
b8b1779c880144e8455e17a6f8c5051daa0839b2
9,831
import numpy import collections import json def WriteJsonFile(filename, params, database): """Write database out as a .dat file. Args: filename: Name of output file to write database to. params: Parameter structure used to generate the database. database: Dictionary of ndarrays of aerodynamic coeffic...
38fe51e463bb099ecb7f1a5beb3c427f471b7611
9,832
def headers(): """ default HTTP headers for all API calls """ return {"Content-type": "application/json"}
e601410c7ba22f28a88e47742349087744495c6b
9,833
import logging def preprocess_confidence(train_df, test_df=None): """ Feature creation that should be done given training data and then merged \ with test data. """ ATTRIBUTION_CATEGORIES = [ # V1 Features # ############### ['ip'], ['app'], ['device'], ['os'], ['channel'], ...
ff157a02ac9253fb1fd2e2306fb207f6c0022317
9,834
def ancestral_state_pair(aln,tree,pos1,pos2,\ ancestral_seqs=None,null_value=gDefaultNullValue): """ """ ancestral_seqs = ancestral_seqs or get_ancestral_seqs(aln,tree) ancestral_names_to_seqs = \ dict(zip(ancestral_seqs.Names,ancestral_seqs.ArraySeqs)) distances = tree.getDistances() ...
f5f1b58231dea83f2d546cc3ffb42ae94b769107
9,835
def get_a(i,j,k): """returns between tad coordinates""" i,j,k = np.sort([i,j,k]) ax,ay=[],[] for x_ in range(i,j+1): for y_ in range(j+1,k+1): ax.append(x_) ay.append(y_) return ax,ay
ed32978045b32d4bf6863919177a726f5ee55d76
9,836
def get_mode(input_list: list): """ Get's the mode of a certain list. If there are few modes, the function returns False. This is a very slow way to accomplish this, but it gets a mode, which can only be 4 things, so it should be OK """ if len(input_list) == 0: return False distinguish...
552620bb68e3922dff7b19f52f5da9dbee813ca3
9,837
def qqe(close, length=None, smooth=None, factor=None, mamode=None, drift=None, offset=None, **kwargs): """Indicator: Quantitative Qualitative Estimation (QQE)""" # Validate arguments length = int(length) if length and length > 0 else 14 smooth = int(smooth) if smooth and smooth > 0 else 5 factor = f...
9f1da38313effb6a585dd4b6a162034b83989557
9,838
def reference_col( tablename, nullable=False, pk_name="id", foreign_key_kwargs=None, column_kwargs=None ): """Column that adds primary key foreign key reference. Usage: :: category_id = reference_col('category') category = relationship('Category', backref='categories') """ foreign_...
a266d81ac1c323dcf6d19e511b147b2b190b3c7e
9,839
def Ei(x, minfloat=1e-7, maxfloat=10000): """Ei integral function.""" minfloat = min(np.abs(x), minfloat) maxfloat = max(np.abs(x), maxfloat) def f(t): return np.exp(t) / t if x > 0: return (quad(f, -maxfloat, -minfloat)[0] + quad(f, minfloat, x)[0]) else: return quad(f, ...
6c6630f4d9a188ccb7a2e7a77b26a8c89a976e65
9,840
def _MaybeMatchCharClassEsc (text, position, include_sce=True): """Attempt to match a U{character class escape <http://www.w3.org/TR/xmlschema-2/#nt-charClassEsc>} expression. @param text: The complete text of the regular expression being translated @param position: The offset of the backslash...
55394c636b94ea2008161e350ba9e9de3250555d
9,841
import urllib import http def request(command, url, headers={}, data=None): """Mini-requests.""" class Dummy: pass parts = urllib.parse.urlparse(url) c = http.client.HTTPConnection(parts.hostname, parts.port) c.request( command, urllib.parse.urlunparse(parts._replace(sche...
a08c0be0549ebe133f42ca56b77c4f113627db2a
9,842
import time def sum_of_n_2(n): """ 迭代求和,仅使用加法。 :param n: 1 到 n 的和 :return: 元组(元素的组合),第一位为值,第二位为所花时间 """ start = time.time() the_sum = 0 for i in range(1, n + 1): the_sum = the_sum + i end = time.time() return the_sum, end - start
45a07d5a8d02f515b8d0730a9a10bf71398092e8
9,844
def TSA_t_g( temperature, temperature_vegetation, vegetation_fraction): """ //Temperature of ground from Tvegetation //Based on two sources pixel split //Chen et al., 2005. IJRS 26(8):1755-1762. //Estimation of daily evapotranspiration using a two-layer remote sensing model. Ground temperature, bare soil TSA_t_g...
c1189f2554e3f7dba13a2c8fd8698f906d343611
9,845
def get_dict_buildin(dict_obj, _type=(int, float, bool, str, list, tuple, set, dict)): """ get a dictionary from value, ignore non-buildin object """ non_buildin = {key for key in dict_obj if not isinstance(dict_obj[key], _type)} return dict_obj if not non_buildin else {key: dict_obj[key] for key in...
14e68e5cc5c35a5e4a440dfb4c842a987c441da6
9,846
def start(timeout=5, backlog_reassign_delay=None): """Create, start, and return the block pipeline.""" pipeline = create_pipeline(timeout=timeout, backlog_reassign_delay=backlog_reassign_delay) pipeline.start() return pipeline
cb157de13af43af5830ffc75654fdba16de4da44
9,848
def preprocess_variable_features(features, interaction_augmentation, normalization): """ Features preprocessing following Khalil et al. (2016) Learning to Branch in Mixed Integer Programming. Parameters ---------- features : 2D np.ndarray The candidate variable features to preprocess. i...
2b8d32a69e4ebe645fc942e7fe57ecea1560f158
9,849
def reverse_inverse_from_cholesky_band_proto(S, l): """ S -> L :param S: sparse subset inverse of banded matrix L :param l: number of subdiagonals in S :return: Ls: reconstructed cholesky decomposition """ # forward pass k = l + 1 # bandwidth n = S.shape[1] # construct vector e ...
90c421fc71a76be0adff7ce49d62bc5b364fdf94
9,851
def fused_bn_grad_5D_run_2(shape, dtype, eps, kernel_name, attrs): """ test bnGrad_2 """ def get_expect(dgamma_red_hw, dbeta_red_hw, var, gamma, eps, data_shape): m = data_shape[0] * data_shape[2] * data_shape[3] neg_m_rec = -1.0 / m eps = np.array([eps], dtype=var.dtype).reshape([1] * 5...
0d792e48be537c7415c9e3ac465f39de5d1c136c
9,852
import numpy def get_best_distance(pdb_file, reference_point, resname="GRW"): """ Finds fragment atom closest to the user-defined reference point. Parameters ---------- pdb_file : str Path to PDB file. reference_point : list[float] Coordinates of the reference point to which t...
5ad05055ddede103e2f24d91adbb6c950f6bf886
9,853
def default_IM_weights(IM_j: IM, IMs: np.ndarray) -> pd.Series: """ Returns the default IM weights based on the conditioning IM If the conditioning IM (IM_j) is spectral acceleration (SA) the weighting is 70% across the SAs and 30% across all other IMs Otherwise a uniform weighting distribution is...
d13dcd0e1022923512e35b798307e27e90aba40f
9,854
from typing import Type import mimetypes def guess_file_type(filename: FileSystemPath) -> Type[PackFile]: """Helper to figure out the most appropriate file type depending on a filename.""" filename = str(filename) if filename.endswith(".json"): return JsonFile elif filename.endswith((".yml", ...
eedb9f90f8caa754334614017f48ccafea6d2a07
9,855
import math def _fcn_mg_joint_pos(t, q_init, q_end, t_strike_end): """Helper function for `create_mg_joint_pos_policy()` to fit the `TimePolicy` scheme""" return ((q_end - q_init) * min(t / t_strike_end, 1) + q_init) / 180 * math.pi
892a494ea5ee2033d2f29efe7400bce8aab30c1c
9,856
def test_circuit_run(default_compilation_configuration): """Test function for `run` method of `Circuit`""" def f(x): return x + 42 x = hnp.EncryptedScalar(hnp.UnsignedInteger(3)) inputset = range(2 ** 3) circuit = hnp.compile_numpy_function(f, {"x": x}, inputset, default_compilation_confi...
068473b1390e9af69ef11d9c4189012ffa2c403e
9,857
def detection(): """ Programmed by: David Williams, Aspen Henry, and Slate Hayes Description: detection is a state where the server tries to find all the faces in a frame, if a face is registered then it looks for fingers held up next to the face. """ #STEP 1: Get and Process frame # print("Detection!") fra...
b5b36a8cceeb38467ae5f63840dfc13c8af9cfe7
9,858
import re def rex_coverage(patterns, example_freqs, dedup=False): """ Given a list of regular expressions and a dictionary of examples and their frequencies, this counts the number of times each pattern matches a an example. If ``dedup`` is set to ``True``, the frequencies are ignored, so that on...
a9ac988348d1fa037508b0a2b6c71e077ca41627
9,859
def build_diamond(validated_letter): """ >:param str validated_letter: A capital letter, that will be used to generate the list of strings needed to print out the diamond. >**Returns:** A list a strings that contains the correct spacing for printing the diamond. build_diamond is used to genera...
bd55281ee275d402d4f35701daacb3be0246812e
9,860
from datetime import datetime def human_timestamp(timestamp, now=datetime.datetime.utcnow): """Turn a :py:class:`datetime.datetime` into a human-friendly string.""" fmt = "%d %B at %H:%M" if timestamp.year < now().year: fmt = "%d %B %Y at %H:%M" return timestamp.strftime(fmt)
37cc6a3918aaa3622945f6650903f64a371e86a9
9,861
from typing import Concatenate def inception_block(x: tf.keras.layers.Layer, nb_filters: int=64, name: str="block1"): """ 3D inception block, as per Itzik et al. (2018) """ conv3d = partial(Conv3D, activation="linear", use_bias=False, padding="same") batchn = partial(BatchNormalization, momentum=...
8cfebd2a147fb1d8b6174df87dd220ab15a56205
9,862
import collections def _flatten_dict(d, parent_key='', sep='/'): """Flattens a dictionary, keeping empty leaves.""" items = [] for k, v in d.items(): path = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(_flatten_dict(v, path, sep=sep).items())...
4bfb4c19209cb7997856a337c7ad66965598571a
9,863
def secret(): """ Authenticated only route @authenticated will flash a message if not authed """ return render_template('secret.html')
4c0708d3e65942d3afbeaa2159f55a735a31a6a9
9,864
def mk_graph(img_dim, num_labels, poly_width = 3, depth = 3, hidd_repr_size = 512): """ The function that creates and returns the graph required to img_dim = image dimensions (Note, that the image needs to be flattened out before feeding here) num_labels = no_of classes to classify into """ ...
a6d63bd967762289f1998af391112a682f89234f
9,865
def createrawtransaction(inputs, outputs, outScriptGenerator=p2pkh): """ Create a transaction with the exact input and output syntax as the bitcoin-cli "createrawtransaction" command. If you use the default outScriptGenerator, this function will return a hex string that exactly matches the output of bit...
05d41c89356513d989eaffdfc3a89fb4e987e0a5
9,868
from typing import List def get_versions() -> List[str]: """ Gets a list of recognized CRSD urns. Returns ------- List[str] """ return list(sorted(urn_mapping.keys()))
e1730f386a4e26197800069a8f93b1a8ff850512
9,869
import math def k2_factor_sq(df=inf,p=95): """Return a squared coverage factor for an elliptical uncertainty region :arg df: the degrees-of-freedom (>=2) :arg p: the coverage probability (%) :type df: float :type p: int or float Evaluates the square of the coverage factor for an elliptical u...
b6c4fbb0eb1bbb5a9c15ab44c791d937bc7bebd2
9,870
def get_cluster_version_path(cluster_id): """ Gives s3 full path of cluster_version file of a given cluster_id """ base_path = s3.get_cluster_info_base_path() return "%s/%s/cluster_version.json"%(base_path, cluster_id)
ef514cde40aa582aa265ac2fd912077e3e1e17c9
9,871
import importlib def import_module_attribute(function_path): """Import and return a module attribute given a full path.""" module, attribute = function_path.rsplit(".", 1) app_module = importlib.import_module(module) return getattr(app_module, attribute)
ce2647bb193c2a6c07949073f7c0d142ee8cd1b5
9,872
def rgb_to_hex(red, green, blue): """Give three color arrays, return a list of hex RGB strings""" pat = "#{0:02X}{1:02X}{2:02X}" return [pat.format(r & 0xff, g & 0xff, b & 0xff) for r, g, b in zip(red, green, blue)]
9126ae9e05d4a005d397f13fd4f0d9400efe5a65
9,873
from typing import Tuple def run_cli(cmd: str, print_output: bool = True, check: bool = False,) -> Tuple[int, str, str]: """Runs the command with `dcos` as the prefix to the shell command and returns a tuple containing exit code, stdout, and stderr. eg. `cmd`= "package install pkg-name" results in: $...
3c6697061dab28fd3f741931d7f2430360f037ae
9,874
def get_initialization(arg, indent_count): """Get the initialization string to use for this argument.""" t = get_base_c_type(arg) if arg.is_array(): if t == "char*": init = '[] = { "String 1", "String 2", "String 0" }' else: if arg.is_dictionary() or arg.is_structure...
cc9867966b40bf9a0ce1a43c13cfd0040a3322db
9,875
import re from datetime import datetime def get_time_source_from_output(output): """ Parse out 'Time Source' value from output Time source output example : 'Time source is NTP, 23:59:38.461 EST Thu Jun 27 2019' 'Time source is NTP, *12:33:45.355 EST Fri Feb 7 2020' ...
aae9c208e06d99ff6eb4ae9699946d0b17e53ca7
9,876
def getStyleFX(): """ Defines and returns the style effects Returns: style effects (list of MNPR_FX) """ # general effects distortionFX = MNPR_FX("distortion", "Substrate distortion", "controlSetB", [[1, 0, 0, 0]], ["distort", "revert"], ["noise"]) gapsOverlapsFX = MNPR_FX("gaps-overlaps", "...
acb9382e041b99c9c76a6baa821b220192176bdd
9,877
def deaths_this_year() -> dict: """Get number of deaths this year.""" return get_metric_of(label='deaths_this_year')
ae6f9ee5d00ebbf7dc7fea0c3702695268a38a17
9,878
def get_cls_dropdown_tree_view_item(object_name): """Get and return class of TreeViewItem Dropdown object according to snapshotability """ base_cls = tree_view_item.CommonDropdownTreeViewItem if object_name in objects.ALL_SNAPSHOTABLE_OBJS: base_cls = tree_view_item.SnapshotsDropdownTreeViewItem return ...
f9ee30bb75b2cd84e381293be1b0e2f6dc7a5d7b
9,879
def make_webhdfs_url(host, user, hdfs_path, op, port=50070): """ Forms the URL for httpfs requests. INPUT ----- host : str The host to connect to for httpfs access to HDFS. (Can be 'localhost'.) user : str The user to use for httpfs connections. hdfs_path : str The full...
c4899d75fd54558c6216889cbc749f5d0fe403df
9,880
def get_slash_mapping(bot: commands.Bot): """Get all the prefix commands groupped by category.""" categories = {} for command in bot.slash_commands: if command: category_name = get_cog_category(command.cog) # categories are organized by cog folders try: ...
dfb7eef9aac5df011ee2801a9976723f8f4f8c7a
9,881
def part_to_text(part): """ Converts an e-mail message part into text. Returns None if the message could not be decoded as ASCII. :param part: E-mail message part. :return: Message text. """ if part.get_content_type() != 'text/plain': return None charset = part.get_content_char...
f6831014a5100e6addaebc5889a5e1c40f74381b
9,883
def icwt(Wx, wavelet='gmw', scales='log-piecewise', nv=None, one_int=True, x_len=None, x_mean=0, padtype='zero', rpadded=False, l1_norm=True): """The inverse Continuous Wavelet Transform of `Wx`, via double or single integral. # Arguments: Wx: np.ndarray CWT computed via `ssque...
dc41ac93ab5e9b71fb6afa34e9e545da4b9e81d5
9,884
def AdvApp2Var_MathBase_msc_(*args): """ :param ndimen: :type ndimen: integer * :param vecte1: :type vecte1: doublereal * :param vecte2: :type vecte2: doublereal * :rtype: doublereal """ return _AdvApp2Var.AdvApp2Var_MathBase_msc_(*args)
e8204854d32b2bcb174a779b4eb5e1617563dd1e
9,885
def chunkify(arr, n): """Breaks a list into n chunks. Last chunk may not be equal in size to other chunks """ return [arr[i : i + n] for i in range(0, len(arr), n)]
10df800440e8c1d5e4070dc48dd8c7ecc12f3c83
9,886
def _run_command(command, targets, options): # type: (str, List[str], List[str]) -> bool """Runs `command` + `targets` + `options` in a subprocess and returns a boolean determined by the process return code. >>> result = run_command('pylint', ['foo.py', 'some_module'], ['-E']) >>> result Tr...
def38e07dd55b5c45d591e6a677937774185962d
9,887
from typing import Counter from typing import List from typing import Dict def find_untranscribed_words( gt: Counter, machine: Counter ) -> List[Dict[str, any]]: """ Finds untranscribed words. That is, we find if there exist words in the GT which never occur in the machine transcription. :param gt: Count...
e120898ce32f98cedcfb6831cd288e1700d14189
9,888
def set_line_length(length): """ set_line_length(int length) Sets the maximum line length for log messages. Messages longer than this amount will be broken up into multiline messages. Parameters ---------- * length : the maximum log message line length in characters ...
4269b8fb1f28f700cb4150e217e3b85f1491b91d
9,890
def get_teams(pbp_json): """ Get teams :param pbp_json: raw play by play json :return: dict with home and away """ return {'Home': shared.get_team(pbp_json['gameData']['teams']['home']['name'].upper()), 'Away': shared.get_team(pbp_json['gameData']['teams']['away']['name'].upper())...
925c079a0a4a04de70154e78d6ccb25bd846071d
9,891
def register(args): """Register a new user using email and password. Return CONFLICT is a user with the same email already exists. """ if db.session.query(User).filter_by(email=args['email']).first(): return conflict("User already exists.") new_user = User(args['email'], args['password']) ...
b7979090683b231f71c319590a120242932229fd
9,892
def _scale_value_to_rpm(value, total): """Scale value to reads per million""" return value * 1 / (total / 1e6)
c3a49c8df8cbb22bd055a2f8076065463041bb72
9,893
import itertools def poly_vals_in_range(minimum, maximum, roots): """Return a list of all results of a given polynomial within a range based on the roots of the polynomial itself. These roots will be selected by a user from the GUI. Arguments: minimum -- the lowest value in the dataset ...
439c56cd04a70a858340712e66ffbe6144c49e04
9,895
def width_angle(rectangle: Polygon): """Returns the length and angle(in degrees) of the longest side of a rotated rectangle """ point_a, point_b, point_c = rectangle.exterior.coords[:3] a = distance(point_a, point_b) b = distance(point_b, point_c) if a > b: angle = line_angle(point_a...
074cd38e90f83af15bd09113bafa58e035960fd5
9,896
def mean_absolute_error(y_true, y_pred, discretise = False): """ requires input arrays to be same np.dtype. returns average, not sum of errors discretising (for classification problems) makes little sense to me, but may be necessary in some obscure scenarios """ if discretise: y_p = tools.round_probabilities(y...
879607b78856cdc6367dbf1f6e4c7cecad48df24
9,897
def population_fit_feature_cal(population, fitFunction, fitFunctionInput, ite): """Parallel population fitness calculation function Args: population (list): Single population fitFunction (function): Fit...
671ddb5acd5d8dee8d8dba660efbb1e86509094c
9,898
def intilise_database2(): """ Initilse the database and make a table instance Returns pymongo object of the table """ myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb=myclient['subreddit'] maintable2 = mydb["posts2"] return maintable2
d70497f837cddcaf0a7383d826a705a77e26dda5
9,899
def first(id_): """The first service of the station.""" return jsonify( [ (n.removeprefix("_"), t) for n, t in r.zrange(f"Station:_{id_}:first", 0, -1, withscores=True) ] )
5de7ef49c1deb0edea3f3d4ddcc30da8c4ae2d3a
9,900
def sample(df, n, shape): """ randomly sample patch images from DataFrame Parameters ---------- df : pd.DataFrame DataFrame containing name of image files n : int number of patches to extract shape : list shape of patches to extract Returns ------- image...
a0f655ad71a7ef47c71ecc23f45365f721bc2085
9,901
def bitsizeof_varint32(value: int) -> int: """ Gets bit size of variable 32-bit signed integer value. :param value: Value to use for bit size calculation. :returns: Bit size of the value. :raises PythonRuntimeException: Throws if given value is out of range for varint32 type. """ return _b...
16fd942d23b6ec26a300119e56fbbad6f37a203d
9,902
import requests import json def slack(channel, message, subject=''): """ Sends a notification to meerkat slack server. Channel is '#deploy' only if in live deployment, otherwise sent privately to the developer via slackbot. Args: channel (str): Required. The channel or username to which the ...
274111901fd3b7545c8e2128ce3e98716eca8406
9,903
def compute_similarity(img_one,img_two): """Performs image resizing just to compute the cosine similarity faster Input: Two images Output: Cosine Similarity """ x = cv2.resize(img_one, dsize=(112, 112), interpolation=cv2.INTER_CUBIC) y = cv2.resize(img_two, dsize=(112, 112), int...
24d02db8c685480572fae2ab02f9648e3798fdf3
9,904
def get_results_from_firebase(firebase): """ The function to download all results from firebase Parameters ---------- firebase : pyrebase firebase object initialized firebase app with admin authentication Returns ------- results : dict The results in a dictionary with t...
ca06c24367d778d4b601eab6fa31009fe6ecb372
9,905