content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def resnet101(pretrained=True, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'...
1073c8104c7f3064bbf4a180f03153e82ccaf314
3,621,609
def fraction_input(x,y): """ Takes two inputs and returns it as a fraction Parameters ___________ :param x: int/float: a number :param y: int/float: a number Returns ___________ :return: Returns the fraction """ # Try creating a Fraction using the two numbers inputted ...
9b8be454352a253085291bef34ab7858ef176136
3,621,610
def format_datetime(obj, constant_hour=False, hour=("00", "00")): """Will format a datetime object into a string.""" if not constant_hour: return "{}{}{}{}{}".format( obj.year, "{:02d}".format(obj.month), "{:02d}".format(obj.day), "{:02d}".format(obj.hour)...
0d8d3d35e9ad3168a0e264f6b4e77248406bf7c6
3,621,611
def select_modalities(combs, modalities_flag): """ :param combs: example [[1, 1, 1], [1, 1, 0], [0, 1, 1], [1, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]] :param modalities_flag: e.g [1,1,0] :return: e.g [ [1, 1, 0], [1, 0, 0], [0, 1, 0]] """ combs = [[a * b for a, b in zip(c, modalities_flag)] fo...
3942423468fc8f29a4d135d0503a59472e1a0943
3,621,612
def test_component_inherited_factory_value(): """https://github.com/larq/zookeeper/issues/123.""" @factory class IntFactory: def build(self) -> int: return 5 @component class Child: x: int = ComponentField() @component class Parent: child: Child = Compo...
40cbb10c967095c87f8a85e55b4c80c10287ba37
3,621,613
def GuessVCS(options, path, file_list): """Helper to guess the version control system. NOTE: Very similar to upload.GuessVCS. Doesn't look for hg since we don't support it yet. This examines the path directory, guesses which SCM we're using, and returns an instance of the appropriate class. Exit with an er...
aff738ad9a55cd68efd12db58a613a0832dd94e7
3,621,614
def tactic_application_to_string(t_app: deephol_pb2.TacticApplication) -> Text: """Generate tactic strings. Args: t_app: TacticApplication proto Returns: tactic string; to be parsed by third_party/hol_light/parse_tactic.ml Raises: ProofFailedError: When invariants of the tactic application are no...
14c39b09adf90a5da6cfe5f0f53a6506ec7ed884
3,621,615
import collections def accumulatable_wer_stats(refs, hyps, stats=collections.Counter()): """Computes word error rate and the related counts for a batch. Can also be used to accumulate the counts over many batches, by passing the output back to the function in the call for the next batch. Arguments ...
6d2b698ae162abcda8c120ae5bd3408a074d1874
3,621,616
def waterfall(stack, profile, yaxis="rel_time", cmap="inferno", ax=None, **kwargs): """_summary_ Parameters ---------- stack : _type_ _description_ profile : _type_ _description_ yaxis : str, optional _description_, by default "rel_time" cmap : str, optional ...
f0dc359a53d67e36d2dcd132fc786fd2cc0e7c41
3,621,617
import urllib import json def parse_sport_parionssport(sport): """ Get ParionsSport odds from sport """ sports_alias = { "football" : "FOOT", "basketball" : "BASK", "tennis" : "TENN", "handball" : "HAND", "rugby" :...
725e63405d6259d150e7b8581018dd521e19822e
3,621,618
def conf_to_ccs(conformers, infodf): """Converts list of conformer indexes (from a 50x50 matrix) to Boltzmann weighted CCS average and Lowest Energy CCS. Args: conformers (np.array): Array of conformer indexes selected from a 50x50 rmsd matrix as returned in the SDS() datafra...
a403b167b22153805665b99fb5f29cd198177b35
3,621,619
from typing import List def list_datasets() -> List[str]: """Returns list of available datasets names Returns: List[str]: list of dataset names as string >>> import src >>> src.list_datasets() ['emodb'] """ return sorted(__dataset_mapper__.keys())
502dbeb3b61ee6887ad9d8bb4180cad7aff310f0
3,621,620
from typing import Optional def get_nat_address(instance_id: Optional[str] = None, nat_address_id: Optional[str] = None, organization_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNatAddressResult: """ Gets the...
1a8665a6a977ea7d4a65c6fb60459685d40506e6
3,621,621
def roc(values, period): """ ROC ใ‚’่จˆ็ฎ—ใ™ใ‚‹ใฎใงใ™ใ€‚ * values: ่ชฟๆ•ดๅพŒ็ต‚ๅ€คใ‚’ๆŒ‡ๅฎšใ™ใ‚‹ใฎใงใ™ใ€‚ * period: ๆœŸ้–“ใชใฎใงใ™ใ€‚ * return: ็ต‚ๅ€คใƒ™ใƒผใ‚นใฎ ROC ใ‚’่ฟ”ใ™ใฎใงใ™ใ€‚ """ _values = DataFrame(values) pasts = _values.shift(period) return (_values - pasts) / _values
6332a65f147626675e2c75ab09081f05873cf40b
3,621,624
def compute_density(start, end, length, time_unit='us'): """ Computes a grid density given the edges and number of samples. Handles datetime grids correctly by computing timedeltas and computing a density for the given time_unit. """ if isinstance(start, int): start = float(start) if isinsta...
821c984b2787d91f6af475da1e974e5262eab129
3,621,625
def intersection_pt(triangle_left, triangle_right): """ get intersection point of two output triangles""" a, b, c = triangle_left[0], triangle_left[1], triangle_left[2] d, e, f = triangle_right[0], triangle_right[1], triangle_right[2] x = (c * (b - c) - d * (e - d)) / (b - c - e + d) y = (e - d) * (...
051137af7eaa57edae25ff814593deb1a134ea14
3,621,626
def pitch(freq): """finds the closest pitch to the frequency freq""" return _ftop[closest(_fs, freq)]
cbcc64605ce4c74a0f39a8db37bbdf9f946a431c
3,621,627
import math def algorithm(feature): """ Content-Based Algorithm+ ๊ธฐ์กด์˜ Content-Based์—์„œ Youflix ์‹œ์Šคํ…œ์„ ์œ„ํ•ด ํŠœ๋‹์ด ๋œ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž…๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž๊ฐ€ ํ‰๊ฐ€ํ•œ ๊ฒฐ๊ณผ๋ฅผ ํ† ๋Œ€๋กœ ๋” ๋†’์€ ์ ์ˆ˜๋ฅผ ๋ฐ›์€ ์˜ํ™”๋Š” ๊ฐ€์ค‘์น˜๋ฅผ ๋†’๊ฒŒ์ค˜์„œ ๋น„์Šทํ•œ ์˜ํ™”๊ฐ€ ๋งŽ์ด ์ถ”์ฒœ ๋˜๋„๋ก ํ•˜๊ณ , ๋ฐ˜๋Œ€๋กœ ๋‚ฎ์€ ์ ์ˆ˜์˜ ์˜ํ™”์™€ ์œ ์‚ฌํ•œ ์˜ํ™”๋Š” ์ถ”์ฒœ๋˜์ง€ ์•Š๋„๋ก ํ•˜์—ฌ ์‚ฌ์šฉ์ž์—๊ฒŒ ์˜๋ฏธ์žˆ๋Š” ๊ฒฐ๊ณผ๋ฅผ ๋‚ด๋„๋ก ํ•˜์˜€์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€์ ์œผ๋กœ ์˜ํ™”๊ฐ๋…์ด๋‚˜ ์˜ํ™”๋ฐฐ์šฐ๋“ค์„ ๊ธฐ...
d62bcc2c9a60525b9ddfe8a0615503e8be31c9af
3,621,628
def get_volume_page_score_for_input_fields(result_record, hypothesis): """ :param result_record: :param hypothesis: :return: """ input_fields = hypothesis.get_detail('input_fields') evidences = Evidences() exist = bool('volume' in input_fields) + bool('page' in input_fields) ads_...
4f18544a46754ff4abeb39c556672f3998ec9cb1
3,621,629
def array_to_dist_graph(point_set, point_weight=1, metric='sqeuclidean'): """take a set of points P and create the complete graph with vertex set P and weights equal to the distance between pairs""" link_idx = triu_indices(len(point_set), k=1) g = nx.Graph(data=list(zip(link_idx[0], ...
9802cba1ae75e239e75cdfde306e03b1b7646a3f
3,621,630
import torch def adaptive_scaling_loss(logits: Tensor, targets: Tensor, positive_idx: Tensor, mask: Tensor = None, beta: float = 1.0, reduction='none', weight_trainable: bool = False): """ :param logits: (batch, num_label) :param targets: (batch, ) ...
214362eba1b32c996b079ff66a830f4de8386d90
3,621,631
def mp_wms_130_nometadata(monkeypatch): """Monkeypatch the call to the remote GetCapabilities request of WMS version 1.3.0, not containing MetadataURLs. Parameters ---------- monkeypatch : pytest.fixture PyTest monkeypatch fixture. """ def read(*args, **kwargs): with open('...
6556af96fbb4c14ed1a1db44c8940470f0378b34
3,621,633
from Acquire.Service import start_profile, end_profile def _handle(ctx=None, function=None, additional_function=None, args=None): """This function routes calls to sub-functions, thereby allowing a single identity function to stay hot for longer. If you want to add additional functions then add them ...
d2cce59835273eddb4ab9ef4af7ad948e53c8b91
3,621,634
import torch def _learn(x, logw, loss, optim_kwargs, schedule_kwargs, n_steps, init_x, optim_class_name='Adam', scheduler_class_name='StepLR'): """ Combine solve_for_state and transport_from_potentials in a "reweighting scheme" :param x: torch.Tensor[N, D] The input :param w: torch....
68e2922c6a3ec595a0c9a682cb819567a975f272
3,621,635
from typing import Sequence from typing import cast async def create_tcp_message_payload_connection( queue: "Queue[bytes]", loop: AbstractEventLoop | None, readers: Sequence[MeterReaderBase] | None, *args, **kwargs, ) -> MeterTransportProtocol: """ Create TCP connection using SmartMeterMes...
f0e5a3dc857cb7278f062e6bb5150c9e0c073cc8
3,621,636
import numpy def _numpy_repr(array, prefix="", suffix=""): """Wrapper for showing Numpy array in custom class""" max_line_width = numpy.get_printoptions()["linewidth"] array_str = numpy.array2string( array, separator=", ", prefix=prefix, suffix="," if suffix else None, ...
e0edcf8eadceadccbf9f615c3e685ea40126764f
3,621,637
def parse_collect_msg(orig_msg): """ Parse "collect" message received from backend """ # collect response and message have the same message format return parse_message_msg(orig_msg)
b998102967e907d12b0aab14ede92ca71fa7e9e6
3,621,638
from typing import Iterator from pathlib import Path import tqdm def read_chessboards(images: Iterator[Path]): """ Charuco base pose estimation. """ logger.info("Pose Estimation Starts:") allCorners = [] allIds = [] decimator = 0 # SUB PIXEL CORNER DETECTION CRITERION criteria = (c...
7c5316e24f4a6c52d60cd424856a0787b1e95a83
3,621,639
def populate_sd_dict(herbivore_list): """Create and populate the stocking density dictionary, giving the stocking density of each herbivore type.""" stocking_density_dict = {} for herb_class in herbivore_list: stocking_density_dict[herb_class.label] = herb_class.stocking_density return stoc...
87a0b9375a5a419557443506522ab2cf8d34c308
3,621,640
from rfpipe import source def read_segment(st, segment, cfile, vys_timeout): """ Wrapper for source.read_segment that secedes from worker thread pool """ logger.info("Reading datasetId {0}, segment {1} locally." .format(st.metadata.scanId, segment)) with distributed.worker_clien...
2be4453f349ba180fe53339b3d382cfd27161277
3,621,642
def require_self(f): """Require the logged-in user to be the user that is currently being edited""" @wraps(f) def fn(*args, **kwargs): try: username = kwargs["username"] except KeyError: abort( 500, "The require_self decorator only wor...
e1b48c6b4f80d2ba6293dda6dc7aa5f334fdb28e
3,621,643
def _estimate_score_file_format(filename, ncolumns=None): """Estimates the score file format from the given score file. If ``ncolumns`` is in ``(4,5)``, then ``ncolumns`` is returned instead. """ if ncolumns in (4, 5): return ncolumns f = open_file(filename, "rb") try: line = f....
fae8d90e3e1ba8cc1009d80c3b289bb8d3f56983
3,621,644
def spec_chain_zero_truncated(chain, ln_proba=None, ar=None): """ Return the Markov chain with the dimension: walkers x steps* x parameters, where steps* is the last step before having 0 (not yet constructed chain). Parameters ---------- chain: numpy.array The MCMC chain. ln_pro...
348a0e42845b8a9ab384708fdc464f856f3a4c85
3,621,645
def precision_recall_f1(y, y_pred, average='macro'): """ average: str {'macro', 'micro'} """ cm = confusion_matrix(y, y_pred) if y.ndim == 1: # binary classification pr = (cm.diagonal()/cm.sum(axis=0))[1] rc = (cm.diagonal()/cm.sum(axis=1))[1] f1 = 2*pr*rc / (pr+rc) ...
a342c5e0e1d1e14c598c64a54da968ded4c00c4d
3,621,646
from typing import List import pathlib def get_files( catalog: str, recursive: bool, suffix_markup: str, extension: str ) -> List[str]: """ ะžััƒั‰ะตัั‚ะฒะปัะตั‚ ะฟะพะธัะบ ะฒ ะบะฐั‚ะฐะปะพะณะต ะธ ะฒั‹ะดะฐะตั‚ ัะฟะธัะพะบ ะฟัƒั‚ะตะน ะฝะฐะนะดะตะฝะฝั‹ั… ั„ะฐะนะปะพะฒ. ะŸะพ-ัƒะผะพะปั‡ะฐะฝะธัŽ, recursive = False, ะธั‰ะตั‚ ั„ะฐะนะปั‹ ั‚ะพะปัŒะบะพ ะฒ ะบะฐั‚ะฐะปะพะณะต. extension ะธ suffix_marku...
99f6d591b0548aafb654d05b94271a6d9ae243b6
3,621,647
def CppTypedefString(scope, type_defn): """Gets the representation of a type when used in a C++ typedef. Args: scope: a Definition for the scope in which the expression will be written. type_defn: a Definition for the type. Returns: a (string, boolean) pair, the first element being the representatio...
693d4fa235d970769a1bf1eb3ae1a2d1dc3cc11d
3,621,648
import collections def get_acl(device, acl_name, seq_number): """Retrieves ACL configuration Args: device (Device): This is the device object of an NX-API enabled device using the Device class from pycsco acl_name (str): Case-sensitive name of the ACL seq_number (str): Num...
2f53d6340ae76c2b6a4899be770fc84055d7d19c
3,621,649
def output_tensor(interpreter): """Returns dequantized output tensor.""" output_details = interpreter.get_output_details()[0] output_data = np.squeeze(interpreter.tensor(output_details['index'])()) scale, zero_point = output_details['quantization'] return scale * (output_data - zero_point)
c2ac664328307f2722842a1ff0a49fa604e29ac3
3,621,650
from pathlib import Path def normalize_features(feature: np.ndarray, variable: str) -> np.ndarray: """Normalize features using global pre-computed statistics. Parameters ---------- feature : np.ndarray Data to normalize variable : str One of ['inputs', 'output'], where `inputs` me...
61efd55545e321dfc755059b70fc8bae064132ca
3,621,652
def lonlat2xyz(lon,lat,r=1): """ """ x = r*np.cos(lon*c)*np.cos(lat*c) y = r*np.sin(lon*c)*np.cos(lat*c) z = r*np.sin(lat*c) return x,y,z
3ca8b879256a35593bb0b4ff2c23961183c62aad
3,621,653
def train_switcher(**params): """ function to call the correct train function depending on the dataset. s.t. parallel training easily works altough different fuctions need to be called :param params: all params needed by the train function, as passed by parallel_training :return: functio...
1caa78fbb9bea335225b6c34fc9efaa8b980515a
3,621,654
def get_stock_price(symbol, start, end): """get stock price of a company over a time range Args: symbol (str): ticker symbol of a stock start (datetime.datetime): start time end (datetime.datetime): end time Returns: pd.DataFrame: stock price of a company over a time range ...
69f7150cb1c266360ab4e6a5175b5453f35a0618
3,621,656
import socket def ip6_from_bytes(data: bytes) -> str: """Converts ip4 address from bytes to string representation. Keyword arguments: data -- address bytes to convert """ return socket.inet_ntop(socket.AF_INET6, data)
694384d872b6fe27baa3fd97cba9dbfa7c35f8a9
3,621,657
import typing def unletterbox(image) -> typing.Optional[ typing.Tuple[typing.Tuple[int, int], typing.Tuple[int, int]]]: """Return bounds of non-trivial region of image or None. Unletterboxing is cropping an image such that trivial edge regions are removed. Trivial in this context means that the m...
cb0813dd52e0edd9a94ad72f831c8b6fc976335d
3,621,658
def hash_side_effect(value): """Side effect value.""" if "mail_none.gif" in value: return "633d7356947eec543c50b76a1852f92427f4dca9" else: return "133d7356947fec542c50b76b1856f92427f5dca9"
cc791ad289b4a198a0e66916467aae6c015f5676
3,621,659
def cbow_context(source, window, empty, name=None): """Generates `Continuous bag-of-words` contexts for inference from batched list of tokens. Args: source: `2-D` string `Tensor` or `RaggedTensor`, batched lists of tokens [sentences, tokens]. window: `int`, size of context before and after targ...
017bcf470956011dc0d002c58f8f0548f00ecb0a
3,621,660
def CombineParallelDense(min_num_branches=3): """Combine multiple dense operators into one. For example: data / \ dense (2,2) dense (2,2) | | elemwise/bcast (2,2) elemwise/bcast (2,2) Would become: data ...
a77c2f25a99839269ef6e5cd52cb19bb24e3398f
3,621,661
def layer_norm__ncnn(ctx, *args): """Register default symbolic function for `layer_norm`. Add support to layer_norm to ONNX. """ return layer_norm(*args)
23cdae45587c43d6ee57f3148fc36012bd0fe48e
3,621,662
def new_locale(language: str = None, country: str = None, variant: str = None, use_locale_module: bool = False) -> Locale: """ Instantiates a new Locale :param language: The language code :type language: str :param country: The country code :type country: str :param variant: T...
cd85965284404084ac73e445467504853b6e881b
3,621,663
def plot_variance_explained(model, bar_kwargs=None, ax=None): """ Parameters ---------- model : ``sklearn.decomposition.PCA`` The fitted model. bar_kwargs : dict-like, optional Additional keyword arguments passed through to ``ax.bar()``. ax : axes, optional The axes on ...
99082357bc288fa591123c6244bd450b287dee03
3,621,664
from typing import Optional import json import urllib def get_latest_news_metadata(local: Optional[bool] = False): """ Get latest news metadata file from S3 bucket """ if local: with open(LOCAL_NEWS, 'rb') as f: news = json.loads(f.read().decode('utf-8')) # {"datetime":...
2fd562c90b40b00c593b5feb46a2cb249cf47f21
3,621,665
from typing import Tuple def get_direction(ch: str) -> Tuple[int, int]: """Coordinates point for direction Args: ch: str - direction as a single letter UDLR or NEWS Returns: tuple (x, y) - direction coordinates. E.g.: N -> (0, 1) # north S -> (0, -1) # s...
763b973f62f0fc4606fb9b504f93a3afc604e608
3,621,666
import tqdm def run_batched_rollout(num_episodes, batched_env, agent): """ This function will generate a series of rollouts in a batched manner. """ num_envs = batched_env.num_envs # This part can be left as is observations = batched_env.batch_reset() rewards = [0.0 for _ in range(num_en...
7356a27dcd75e555727384afeba1c4425cf15fea
3,621,667
import torch def model_params_stats(model, param_dims=None): """Returns the model sparsity, weights count, and the count of weights in the sparse model. Returns: model_sparsity - the model weights sparsity (in percent) params_cnt - the number of weights in the entire model (incl. zeros) ...
567454901c506f67dd6171bfce344db694a9467b
3,621,668
from typing import Dict from typing import Any import json def get_connect_dict() -> Dict[str, Any]: """Read in database connection settings and return values as a dictionary. """ with open("config.json", "r") as config_file: config_dict = json.load(config_file) if "database" in config...
4d292d02e959aa091e2124f9c10b0876417ffba9
3,621,669
def peak_transform_sd(data, tm): """ Using multiplier of standard-deviation. data: N x L matrix, N profiles of length L l = codon density signal profile sequence tm = threshold multipler. Returns individual profiles peak values (st) (Series object) """ N, L = data.shape peak_mat...
d447d0affd268ec5cf6437347f1acd38661aee5a
3,621,670
def unless(predicate, function, value): """Tests the final argument by passing it to the given predicate function. If the predicate is not satisfied, the function will return the result of calling the whenFalseFn function with the same argument. If the predicate is satisfied, the argument is returned as...
9a883fb57b99f5dbc4e8b357dfeb9b88682ef621
3,621,671
import logging def getLogger(): """Helper for retrieve the logger object """ return logging.getLogger(__name__)
470424ea4b3f6b18225db6994b6b43439f2fd425
3,621,672
def pnchunk(darray, maxsize_4d=1000**2, sample_var="u", round_func=round, **kwargs): """ Chunk `darray` in time while keeping each chunk's size roughly around `maxsize_4d`. The default `maxsize_4d=1000**2` comes from xarray's rule of thumb for chunking: http://xarray.pydata.org/en/stable/dask.html#chun...
770bc7465168d89bf85800e01d1fcbb8fa0af663
3,621,673
def _RecursiveAssembleBD(disk, owner, as_primary): """Activate a block device for an instance. This is run on the primary and secondary nodes for an instance. @note: this function is called recursively. @type disk: L{objects.Disk} @param disk: the disk we try to assemble @type owner: str @param owner: ...
ad393f5572a8565d01c4f0672297525ff9491d33
3,621,675
def reformat_raw_matrices(raw_matrix_files): """ Convert txt format to sparse matrix format. Use csr format (compressed sparse row; triplet format). :param raw_matrix_files: [txt] raw Hi-C matrices """ chr_raw_matrix_col_0 = np.array(raw_matrix_files[:, 0]) chr_raw_matrix_col_1 = np.array(raw_m...
818f3cdb4596beb0bf7ab579efaa9a3820fe6708
3,621,676
def get_all_folder_ids(service, parent_id=None, drive_id=False): """ Returns the id of the destination folder name in Google Drive """ parent_ids = [] # build query string if parent_id: query = 'mimeType = \'application/vnd.google-apps.folder\'' \ f' and \'{parent_id}\' in pa...
56f1ae373533efcf991572aab9816540620fd949
3,621,677
import math def estimate_wrapped_gaussian_stddev(values, clip_lower, clip_upper): """Estimate the stddev of values assuming a wrapped normal distribution. This function takes an input tensor `values` and estimates the sample standard deviation of its values with the following assumptions: 1. The values are...
58e3f1a476482f39168acca7ad4c83f8c184e257
3,621,678
import errno def _convert_errno_parm(code_should_be): """ Convert the code_should_be value to an integer If code_should_be isn't an integer, then try to use the code_should_be value as a errno "name" and extract the errno value from the errno module. """ try: code = int(code_should_be)...
949c9f17539d885a0fc4a51f3358fc3695c42e22
3,621,679
def unknownwordftb(word, loc, _lexicon): """Model 2 for French of the Stanford parser.""" sig = UNK if ADVSUFFIX.search(word): sig += "-ADV" elif VERBSUFFIX.search(word): sig += "-VB" elif NOUNSUFFIX.search(word): sig += "-NN" if ADJSUFFIX.search(word): sig += "-ADV" if HASDIGIT.search(word): sig += ...
56a371ec67f16121a4ee286823c778b41c3e6e8b
3,621,681
def patch_src_utils_logger_create_logger(mocker) -> MagicMock: """Patch the `src.utils.logger.create_logger` function.""" return mocker.patch("src.utils.logger.create_logger")
a855ce570f9a122c56304e7420368f3aa396ba15
3,621,682
import torch def rectangleMesh(x_range=(0,1), y_range=(0,1), h=0.25): """ Input: - x's range, (x_min, x_max) - y's range, (y_min, y_max) - h, mesh size, can be a tuple Return the element matrix (NT, 3) of the mesh a torch.meshgrid """ try: hx, hy = h[0], h[1] except:...
3af1e2a514ff878b058830b63a2e53a96b2a9363
3,621,683
from typing import List def group_notes_to_chords(notes: List[MidiNote], kernel=None) -> List[List[MidiNote]]: """ Groups the list of `MidiNote`s by time. The return value maps time to a list of `MidiNote`s for that time. """ if kernel is None: kernel = kernel_default # Degenerate ca...
6379402d1ea4e3b19f3a1c93b97423aa19ac6230
3,621,684
def readVGIline(line,l1dic,l2dic,l3dic): """reads and interpretes one line of a VGI file.""" if line.startswith("{"): #new level 1 heading if level1 != "": l2dic[level2] = l3dic l1dic[level1] = l2dic level1 = line.lstrip("{").rstrip("}\n") level2 = "" ...
597b87944785588d20ee77f369862f9c950036ff
3,621,686
def garch_fit_and_predict(series, ticker, horizon=1, p=1, q=1, o=1, print_series_name=False): #p=1,q=1, o=1 #series=returns_df['spy'] #horizon=1 """ This function takes a series of returns, and get back the GJR-GARCH time series fit for the conditional volatility, using one shock, and a t-stud...
4ec226eec64c804be93e589919db4c92c89f7109
3,621,687
import re def find_all_starts_regex(seq): """ Find the starting index of all start codons in a lowercase seq """ regex_start = re.compile('atg') # Find the indices of all start codons starts = [] for match in regex_start.finditer(seq): starts.append(match.start()) return tuple(starts...
5dd16b36352bbf41005fdf008606e503a050a175
3,621,688
def get(isamAppliance, error_page, check_mode=False, force=False): """ Retrieving an error page """ return isamAppliance.invoke_get("Retrieving an error page", "{0}{1}".format(module_uri, error_page), requires_modules=requires_modules, requires_version=requires_versio...
be2176a344273c0fceab446cbfcac651b6d02845
3,621,689
def edit_category(category_id): """ Edit category for database. Inject all existing data from the category document into the form. """ the_category = mongo.db.categories.find_one({"_id": ObjectId(category_id)}) return render_template('editcategory.html', cate...
691c78bea14fdf8e489a5f7cbb2cc3e7c653600b
3,621,691
def update_blurs(blur_o, blur_d, routing): """Signal when all the input fields are full (or at least visited?) and a routing option has been picked.""" if routing == 'slope': c = 0 elif routing == 'balance': c = 1 else: c = 2 if (not blur_o) or (not blur_d): return 0 ...
092ad87e42d682a1369dca41ddc1dab491bd7525
3,621,693
def index(): """Basic home page.""" return render_template('hi.html')
f7d256c658f29d500388bfbb500c022511c8bb4f
3,621,694
def create_tag_query(session, collection=None, document_ids=None, tag_buffer=TAG_BUFFER_SIZE): """ returns a query for tags with specified parameters :param session: session to execute query on :param collection: filter by collection :param document_ids: filter by ids :param tag_buffer: yield pe...
8a85d058d357225d9ab430d563cd885b9167b962
3,621,695
def _add(x): """ Add all elements of a list. :param x: List to sum :return: Sum of all elements in the input list """ return sum(x)
19d42b51dbd07a992f3256b8b0d69c1f4043fa89
3,621,697
import torch def make_data_loader(dataset, batch_size=cfg.batch_size, shuffle=True, sampler=None): """Make dataloader from dataset.""" data_loader = torch.utils.data.DataLoader( dataset=dataset, batch_size=batch_size, shuffle=shuffle if sampler is None else False, ...
8297d89c6e89b867dad34807e8584067cab3085e
3,621,698
import math def to_yaw_angle_quat(qxyzw): """ :param qxyzw: a list or numpy array :return: a float angle [-pi, pi) """ qxyzw = qxyzw / np.linalg.norm(qxyzw) if qxyzw[2] < 0: theta = math.acos(-qxyzw[3])*2 else: theta = math.acos(qxyzw[3])*2 if theta > math.pi: theta -= 2*math.pi return ...
8f8a19edbb6bd2b8b95fddd52adfba31c265ce43
3,621,699
async def serverinfo(msg): """ Show information about the Server / Guild this Command was used on. :param msg: The Message invoking the Command :return: The Bot's response """ guild_info = f'**Name**: {msg.guild.name}\n' \ f'**Region**: {msg.guild.region}\n' \ ...
e5ff17a360c098206b1a6706a159c7e7aea7cdab
3,621,701
def _assign_link_resids(res_link, match): """ Given a link at residue level (`res_link`) and a dict (`match`) specifying to which resids the res_link nodes map, create a correspondence dict that maps the higher resolution nodes to the resids specified in` match`. Each `res_link` node by defi...
cfb315a15ebba6e086f340dc7e6db27eadee1d2b
3,621,704
def can_split_pairs(card_one, card_two): """ :param card_one: str - first card in hand. :param card_two: str - second card in hand. :return: bool - if the hand can be split into two pairs (i.e. cards are of the same value). """ if card_one == 'A' or card_two == 'A': split_pairs = card_...
71d4ef9463f5f0dc7a43e48be8ae0c660cda7327
3,621,705
def _get_pos_neg_loss(cls_loss, labels): """get pos neg loss""" # cls_loss: [N, num_anchors, num_class] # labels: [N, num_anchors] batch_size = cls_loss.shape[0] if cls_loss.shape[-1] == 1 or len(cls_loss.shape) == 2: cls_pos_loss = (labels > 0).astype(cls_loss.dtype) * cls_loss.view(batch_s...
1e7c9444c8604e4c0e438f3d80826a2142a5398b
3,621,706
def parse_args(): """ Helper function parsing the command line options @retval ArgumentParser """ parser = ArgumentParser(description="PyTorch distributed training launch " "helper utilty that will spawn up " "multiple d...
606a10c6954e89b94a47d278c534a4b8b295a3c6
3,621,707
import copy def invert(image: Image) -> Image: """Return an inverted copy of image; that is, an image that is a colour negative of the original image. >>> image = load_image(choose_file()) >>> inverted = invert(image) >>> show(inverted) """ new_image = copy(image) # Invert t...
286d6a3de666d356797f1d287b6a4582da30945e
3,621,709
def load(quantum_circuit_object, format: str): """Load external quantum assembly and quantum circuits from supported frameworks into PennyLane templates. .. note:: For more details on which formats are supported please consult the corresponding plugin documentation: https://pennyla...
2b71157b2d870f266e7521705d25e9b749bb34e4
3,621,710
def make_batched_features_dataset(file_pattern, batch_size, features, reader=core_readers.TFRecordDataset, label_key=None, reader_args=None, ...
60edb2837b45e45b05688be8f3876591270782d6
3,621,712
def batch_update(docs, commit_each_doc=True): """ docs Format: [ "Contract (DocType)": { "create": [ { "fieldname": value, "fieldname": value, "fieldname": value } ],...
ccc30566a015d572f731402e2b155f7a5f296af0
3,621,713
import ctypes def disk_util(directory): """" <Purpose> Gets information about disk utilization, and free space. <Arguments> directory: The directory to be queried. This can be a folder, or a drive root. If set to None, then the current directory will be used. <Exceptions> Environ...
96a3dec573aa333eceba970b98e84477c2829a0b
3,621,714
def calculateMinimumTemperature(frd, maj_met, min_met, time, psolid, psolidmap): """ Minimum nodal temperature for a given PSOLID. """ minTemp = None for element in psolidmap[psolid]: temp = frd.results[maj_met][time][min_met][element] if temp < minTemp or minTemp is None: minTem...
c6065c0fee4f97a80fbdd765551987dc9eac1b41
3,621,715
def test_agegroup_pop(df): """ Compare the age group populations with manually computed sums from the Excel files """ def assert_pop(df, sex, state_name, year, age_group): return(df[sex][(df.StateName == state_name) & (df.Year == year) & (df.AgeG...
a9e4d5a30eef670b916ea13cf5ef328234863cf6
3,621,717
def checkrows(sudoku): """ Checks if each row contains each value only once """ size = len(sudoku) row_num = 0 for row in sudoku: numbercontained = [False for x in range(size)] for value in row: # if placeholder, ignore it if value in range(size): ...
3266eb936b0f3f1e22bd16cd40fbf61753876ce1
3,621,718
def list_is_unique(ls): """Check if every element in a list is unique Parameters ---------- ls: list Returns ------- bool """ return len(ls) == len(set(ls))
a0bc92c2e00b48d80af39020622f31059845fc94
3,621,719
import json def bandit( historical_info, type=BANDIT_BLA_ROUTE_NAME, rest_host=DEFAULT_HOST, rest_port=DEFAULT_PORT, testapp=None, **kwargs ): """Hit the rest endpoint for allocating arms of a bandit given arms already sampled (historical info).""" endpo...
05d2b879c3b3acdd255710bbb07475cff9bffef9
3,621,722
def mark_branch(tree, target_leafs): """Mark in the tree the common ancestor of the species in target_leafs""" tree = deepcopy(tree) targets_in_tree = [ target for target in target_leafs if target in [leaf.name for leaf in tree.get_terminals()] ] if len(targets_in_tree) == 1:...
2e94fccb9faf46f74513736c05f2b92ce1537ec4
3,621,723
def GetEigenVectorCentr(*args): """ GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4, int const & MaxIter=100) Parameters: Graph: PUNGraph const & NIdEigenH: TIntFltH & Eps: double const & MaxIter: int const & GetEigenVectorCentr(P...
7d39b1bf777868911da02fa54fad769b73ae686b
3,621,724
def run_random(connection, test_case, all_preds, nr_sums, timeout_s): """ Run simple random generation baseline. Args: connection: connection to database test_case: summarize for this test case all_preds: all available predicates nr_sums: generate so many summaries t...
d4f7c39f7e30f9fd46bed1fed61db308da550a6c
3,621,725
def load_cifar_10_data(data_dir, nparts=6, negatives=False): """ Return train_data, train_filenames, train_labels, test_data, test_filenames, test_labels """ # training data cifar_train_data = None cifar_train_filenames = [] cifar_train_labels = [] for i in range(1, nparts+1): ...
e15b2931d63afa1d726a99c2cf03776e51769c16
3,621,726
import csv def read_queue(project): """Read queue csv file Args: project (string): project, i.e. CMIP5/CMIP6 Returns: rows (dict): - prsenting each record stored in the file dids (set): dataset_ids stored in the file """ rows={} dids=set() # open csv file and read...
6e6fe3a08d22e5984c962eaba3cf446456e3cb59
3,621,727
def normalise_json_testdata(obj, ignore): """ Various normalisations of the JSON sourced test data: - make it immutable to avoid accidental manipulation of baseline values - remove any keys we want to ignore - lowercase any values with a key of "id" (since we always lowercase the external IDs in the...
079b12083a20214cf900afc8f933149b83fbb55c
3,621,728