content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_exploration_components_from_dir(dir_path): """Gets the (yaml, assets) from the contents of an exploration data dir. Args: dir_path: str. a full path to the exploration root directory. Returns: *. A 2-tuple, the first element of which is a yaml string, and the se...
945690e496846e9cf6c0443ff8cc57ff18d5d056
11,700
import time def time_this_function(func): """ Time the function. use as a decorator. Examples --------- :: @time_this_function def func(x): return x a= func(1) Parameters ---------- func: Callable function Returns ------- ...
6ee2d12dc2301e1c3efe2ca02548297aa83d316f
11,701
def power_plot(data, sfreq, toffset, log_scale, zscale, title): """Plot the computed power of the iq data.""" print("power") t_axis = np.arange(0, len(data)) / sfreq + toffset if log_scale: lrxpwr = 10 * np.log10(data + 1e-12) else: lrxpwr = data zscale_low, zscale_high = zsca...
06d7fab09c027ec2dbf7a11fa78f3b6fcd97e2d7
11,702
import torchvision import torch def load_dataset(dataset): """ Loads a dataset and returns train, val and test partitions. """ dataset_to_class = { 'mnist': torchvision.datasets.MNIST, 'cifar10': torchvision.datasets.CIFAR10, 'fa-mnist': torchvision.datasets.FashionMNIST } assert dataset in dataset_to_cla...
e17dcec84603a742cb6eec0fa18ad40af2454461
11,703
def compareTo(s1, s2): """Compares two strings to check if they are the same length and whether one is longer than the other""" move_slice1 = 0 move_slice2 = 1 if s1[move_slice1:move_slice2] == '' and s2[move_slice1:move_slice2] == '': return 0 # return 0 if same length elif s1[move_...
4700360d10561227a6d4995c66953993dce1cea3
11,704
def is_unique(x): # A set cannot contain any duplicate, so we just check that the length of the list is the same as the length of the corresponding set """Check that the given list x has no duplicate Returns: boolean: tells if there are only unique values or not Args: x (list): elemen...
12b4513a71fc1b423366de3f48dd9e21db79e73a
11,705
def str2format(fmt, ignore_types=None): """Convert a string to a list of formats.""" ignore_types = ignore_types if ignore_types else () token_to_format = { "s": "", "S": "", "d": "g", "f": "f", "e": "e", } base_fmt = "{{:{}}}" out = [] for i, token ...
9cbe719abe6b37a0adcd52af250dfe768f850ffa
11,706
from pathlib import Path def _read_concordance(filename: Path, Sample_IDs: pd.Index) -> pd.DataFrame: """Create a flag of known replicates that show low concordance. Given a set of samples that are known to be from the same Subject. Flag samples that show low concordance with one or more replicates. ...
2c7049ff5b521927ffbf863471fc23e073bce531
11,707
def load_image(name): """ Get and cache an enaml Image for the given icon name. """ path = icon_path(name) global _IMAGE_CACHE if path not in _IMAGE_CACHE: with open(path, 'rb') as f: data = f.read() _IMAGE_CACHE[path] = Image(data=data) return _IMAGE_CACHE[path]
6ce56c1a9d4d9e80d25a19aca239f43ebd119840
11,708
def add_shipment_comment( tracking_id: str, body: CreateComment = Body(...), client: VBR_Api = Depends(vbr_admin_client), ): """Add a Comment to a Shipment. Requires: **VBR_WRITE_PUBLIC**""" tracking_id = sanitize_identifier_string(tracking_id) shipment = client.get_shipment_by_tracking_id(...
d115d230bbf47a8f1cf625f0ab66e855f382244c
11,709
import os def train_faster_rcnn_alternating(base_model_file_name, debug_output=False): """ 4-Step Alternating Training scheme from the Faster R-CNN paper: # Create initial network, only rpn, without detection network # --> train only the rpn (and conv3_1 and up for VGG16) # buffer region prop...
cb0b255198f60da9415282f047396c8b501a43aa
11,710
def _mp2_energy(output_str): """ Reads the MP2 energy from the output file string. Returns the energy in Hartrees. :param output_str: string of the program's output file :type output_str: str :rtype: float """ ene = ar.energy.read( output_str, app.one_of_the...
febd9f4c5759cb6150ff16bda2e9050199c48c5f
11,711
def fastlcs(a,b,Dmax=None): """ return the length of the longest common substring or 0 if the maximum number of difference Dmax cannot be respected Implementation: see the excellent paper "An O(ND) Difference Algorithm and Its Variations" by EUGENE W. MYERS, 1986 NOTE: let D be the minim...
d8a88c7ffaae892e48a292b7a045da9f5dc58173
11,712
from typing import Optional from typing import Mapping def FeaturesExtractor( # pylint: disable=invalid-name eval_config: config_pb2.EvalConfig, tensor_representations: Optional[Mapping[ Text, schema_pb2.TensorRepresentation]] = None) -> extractor.Extractor: """Creates an extractor for extracting f...
86e58783fca3ebb23de1e6b7ac9cdd4030e99c38
11,713
def assert__(engine, obj, condition, message=u'Assertion failed'): """:yaql:assert Evaluates condition against object. If it evaluates to true returns the object, otherwise throws an exception with provided message. :signature: obj.assert(condition, message => "Assertion failed") :arg obj: object ...
c29e073bf6673ce0c89ed339c27f2287d6952991
11,714
def create_review(request, item_id, template_name="reviewclone/create_review.html"): """ Current user can create a new review. Find the item with `item_id` then make sure the current user does not already have a review. If a review is found `review_exist` will be True. If the cur...
fe1806017cbce5e95be183be48c9e35a63a10e26
11,715
from typing import Iterable from typing import List def build_level_codes(incoming_column_name: str, levels: Iterable) -> List[str]: """ Pick level names for a set of levels. :param incoming_column_name: :param levels: :return: """ levels = [str(lev) for lev in levels] levels = [incom...
994ccc0673bd27dcce30709a97372c29d75a8e67
11,716
def get_all(isamAppliance, check_mode=False, force=False): """ Get all rsyslog objects """ return isamAppliance.invoke_get("Get all rsyslog objects", "/core/rsp_rsyslog_objs")
55ff144577a9ef25b555ca3a37db65bfdb0f0af4
11,717
def genomic_dup1_37_loc(): """Create test fixture GRCh37 duplication subject""" return { "_id": "ga4gh:VSL.CXcLL6RUPkro3dLXN0miGEzlzPYiqw2q", "sequence_id": "ga4gh:SQ.VNBualIltAyi2AI_uXcKU7M9XUOuA7MS", "interval": { "type": "SequenceInterval", "start": {"value": 4...
470af80795c649bc0f4dd29393d1093c45c9f0da
11,718
def parse(f, _bytes): """ Parse function will take a parser combinator and parse some set of bytes """ if type(_bytes) == Parser: return f(_bytes) else: s = Parser(_bytes, 0) return f(s)
7f824c46477a384ce97f66806813f4b42412d6d8
11,719
def spiral_tm(wg_width=0.5, length=2): """ sample of component cutback """ c = spiral_inner_io_euler(wg_width=wg_width, length=length, dx=10, dy=10, N=5) cc = add_gratings_and_loop_back( component=c, grating_coupler=pp.c.grating_coupler_elliptical_tm, bend_factory=pp.c.bend_circular,...
e7fcec9e61984d8f89558d7479cc942db389ba3a
11,720
import time import sys def get_url_until_success(url): """Continuously tries to open a url until it succeeds or times out.""" time_spent = 0 while (time_spent < RECEIVE_TIMEOUT): try: helps = urllib2.urlopen(url) break except: time.sleep(RETRY_INTERVAL) time_spent += RETRY_INTERV...
04c47d158393c1f8b809240b84d2aecc6fcbf8de
11,721
from typing import List from typing import Tuple def _chunk(fst: pynini.Fst) -> List[Tuple[str, str]]: """Chunks a string transducer into tuples. This function is given a string transducer of the form: il1 il2 il3 il4 il5 il6 ol1 eps eps ol2 eps ol3 And returns the list: [(il1 ...
fa50e13062267e8929df5f538ab9a924822bc265
11,722
def auth_token_required(func): """Your auth here""" return func
e65b94d40c914c57ff8d894409b664cf97aa790d
11,723
def base_convert_money(amount, currency_from, currency_to): """ Convert 'amount' from 'currency_from' to 'currency_to' """ source = get_rate_source() # Get rate for currency_from. if source.base_currency != currency_from: rate_from = get_rate(currency_from) else: # If curren...
5417ba7a9d757bafc835df8f55a1d4e6de72cb2f
11,724
import confluent_kafka as ck from elasticsearch import Elasticsearch import sys def init_dask_workers(worker, config, obj_dict=None): """ Initalize for all dask workers :param worker: Dask worker :type worker: object :param config: Configuration which contains source and sink details :type con...
34fb468e5a5f2acf3ea4c18065c7c0efde750a04
11,725
async def contestant() -> dict: """Create a mock contestant object.""" return { "id": "290e70d5-0933-4af0-bb53-1d705ba7eb95", "first_name": "Cont E.", "last_name": "Stant", "birth_date": date(1970, 1, 1).isoformat(), "gender": "M", "ageclass": "G 12 år", "...
261fd560107489b58c645efb1bb9c19a396e0dce
11,726
import requests import http def GetApitoolsTransport(timeout='unset', enable_resource_quota=True, response_encoding=None, ca_certs=None, allow_account_impersonation=True, use_google_auth=None, ...
21fc8d521703580a51c753811b7f0d401f68bba5
11,727
def user_requested_anomaly7(): """ Checks if the user requested an anomaly, and returns True/False accordingly. """ digit = 0 res = False if is_nonzero_file7(summon_filename): lines = [] with open(get_full_path(summon_filename)) as f: lines = f.readlines() if len(line...
bed54831c00deb6c11ce81c731fe37f35ef070b7
11,728
def mat_to_r(_line, _mat_object : MatlabObject, _r_object : RObject = RObject()): """Move variables from Matlab to R Parameters ---------- _line : str, Iterable[str] If str, one of the following: 1. '#! m[at[lab]] -> <vars>' 2. '<vars>' where <vars> is a comma separated list of Matlab variable names I...
22f78c06bcf47a71596563debf6115c954d89e21
11,729
import os def read_keys(): """ read aws credentials from file, then stick into global variables... """ with open('%s/.aws/credentials' % os.getenv('HOME'), 'rt') as infile: for line in infile: if 'aws_access_key_id' in line: aws_access_key_id = line.split('=')[-1].strip() ...
c79752cb52045c3d369516dc16343ec766aa9e09
11,730
def RecalculatedEdgeDegreeAttack(G, remove_fraction = 1.0): """ Recalculated Edge Degree Attack """ n = G.number_of_nodes() m = int(G.number_of_edges() * (remove_fraction+0.0) ) tot_ND = [0] * (m + 1) tot_T = [0] * (m + 1) ND, ND_lambda = ECT.get_number_of_driver_nodes(G) tot_ND[0] = ND...
ff88430f172a1ca319af9d637c292091cab2bf6f
11,731
def get(url, params=None, headers=None): """Return the contents from a URL Params: - url (str): Target website URL - params (dict, optional): Param payload to add to the GET request - headers (dict, optional): Headers to add to the GET request Example: ``` get('https://httpbin.org/an...
edb0fe25728fe1bd11d9e74509a630f2d3823af1
11,732
def get_param_num(model): """ get the number of parameters Args: model: Returns: """ return sum(p.numel() for p in model.parameters())
19d98a1bcbdcb827be4a657f82cda2ff09f119e4
11,733
import os def get_branch_name(): """Get the name of the current branch returns: The name of the current branch """ HEAD = data.get_ref('HEAD', deref=False) if not HEAD.symbolic: return None HEAD = HEAD.value assert HEAD.startswith('refs/heads/') return os.path.relpath(H...
631b08be509503f50826b5e5f7c1ceca95b8f4af
11,734
from typing import Union def format_tensor_to_ndarray(x: Union[ms.Tensor, np.ndarray]) -> np.ndarray: """Unify `mindspore.Tensor` and `np.ndarray` to `np.ndarray`. """ if isinstance(x, ms.Tensor): x = x.asnumpy() if not isinstance(x, np.ndarray): raise TypeError('input should be one of [m...
6e64a40bbafe2b2f89f5afd200077be369adcfe7
11,735
from typing import Pattern import re def hunt_csv(regex: Pattern, body: str) -> list: """ finds chunk of csv in a larger string defined as regex, splits it, and returns as list. really useful only for single lines. worse than StringIO -> numpy or pandas csv reader in other cases. """ csv_strin...
9c5574f059ef05e6f99e468a9272f42393d79030
11,736
import re def time_key(file_name): """ provides a time-based sorting key """ splits = file_name.split('/') [date] = re.findall(r'(\d{4}_\d{2}_\d{2})', splits[-2]) date_id = [int(token) for token in date.split('_')] recording_id = natural_key(splits[-1]) session_id = session_key(splits[-2]) ...
07a5448b7b39b00780f53080b316981198d54c91
11,737
import subprocess def silent_popen(args, **kwargs): """Wrapper for subprocess.Popen with suppressed output. STERR is redirected to STDOUT which is piped back to the calling process and returned as the result. """ return subprocess.Popen(args, stderr=subprocess.STDOUT, ...
5075a3ea1891ad3c237d5b05b474f563005ff48f
11,738
def sizeRange(contourList, low, high): """Only keeps contours that are in range for size""" newList = [] for i in contourList: if (low <= cv2.contourArea(i) <= high): newList.append(i) return newList
ac83b09acfd8d8e23a03965b52c5c4cc0361710d
11,739
def number_field_choices(field): """ Given a field, returns the number of choices. """ try: return len(field.get_flat_choices()) except AttributeError: return 0
b8776e813e9eb7471a480df9d6e49bfeb48a0eb6
11,740
def _is_an_unambiguous_user_argument(argument: str) -> bool: """Check if the provided argument is a user mention, user id, or username (name#discrim).""" has_id_or_mention = bool(commands.IDConverter()._get_id_match(argument) or RE_USER_MENTION.match(argument)) # Check to see if the author passed a usernam...
adecc093a0597d43292171f867ebcf5a64edc7d8
11,741
def resize_image(image, size): """ Resize the image to fit in the specified size. :param image: Original image. :param size: Tuple of (width, height). :return: Resized image. :rtype: :py:class: `~PIL.Image.Image` """ image.thumbnail(size) return image
67db04eac8a92d27ebd3ec46c4946b7662f9c03f
11,742
def one_hot_vector(val, lst): """Converts a value to a one-hot vector based on options in lst""" if val not in lst: val = lst[-1] return map(lambda x: x == val, lst)
401ff1d6666c392b3a217659929a4f7832c52522
11,743
def follow(request, username): """ Add user with username to current user's following list """ request.user.followers.add(User.objects.get(username=username)) return redirect('accounts:followers')
72530b32cfcb2282045cd2ef112df62a19e03239
11,744
def sesteva_stolpce(seznam_seznamov_stolpcev): """sešteje vse 'stolpce' v posameznem podseznamu """ matrika_stolpcev = [] for i in range(len(seznam_seznamov_stolpcev)): sez = seznam_seznamov_stolpcev[i] stolpec11 = sez[0] while len(sez) > 1: i = 0 stolpec22 = ...
fe69368a79b60e549983a07e140ec3b5e532868e
11,745
def create_response(data={}, status=200, message=''): """ Wraps response in a consistent format throughout the API Format inspired by https://medium.com/@shazow/how-i-design-json-api-responses-71900f00f2db Modifications included: - make success a boolean since there's only 2 values - make messag...
51346e3a92bdf93085b12eaccc99511b66a34bcf
11,746
def do_sizes_match(imgs): """Returns if sizes match for all images in list.""" return len([*filter(lambda x: x.size != x.size[0], imgs)]) > 0
7da30972ecfd4d3cac3d21ff380255865ec3b5c8
11,747
def gaussian_sampling(len_x, len_y, num_samples, spread_factor=5, origin_ball=1): """ Create a gaussian sampling pattern where each point is sampled from a bivariate, concatenated normal distribution. Args: len_x (int): Size of output mask in x direction (width) len_y (int): ...
fce7396b02778aa832c5d24028fb1f55f1013b15
11,748
import json def from_cx_jsons(graph_json_str: str) -> BELGraph: """Read a BEL graph from a CX JSON string.""" return from_cx(json.loads(graph_json_str))
c61e415199ce0bfc610c1a4277aa8ba1b74a070a
11,749
from typing import Tuple def _calculate_dimensions(image: Image) -> Tuple[int, int]: """ Returns the width and height of the given pixel data. The height of the image is the number of rows in the list, while the width of the image is determined by the number of pixels on the first row. It is assu...
7e74f181839b70e45cb64ca8b8517ef663c7caf8
11,750
def cli(ctx, invocation_id): """Get a summary of an invocation, stating the number of jobs which succeed, which are paused and which have errored. Output: The invocation summary. For example:: {'states': {'paused': 4, 'error': 2, 'ok': 2}, 'model': 'WorkflowInvocation', ...
94197a9c55c0d37b311585fdfce9d615c6986cb5
11,751
import numpy as np def remove_observations_mean(data,data_obs,lats,lons): """ Removes observations to calculate model biases """ ### Import modules ### Remove observational data databias = data - data_obs[np.newaxis,np.newaxis,:,:,:] return databias
8f0cf60137660878f57dc35caa8c23896944d6ab
11,752
import logging def joint_extraction_model_fn(features, labels, mode, params): """Runs the node-level sequence labeling model.""" logging.info("joint_extraction_model_fn") inputs = features # Arg "features" is the overall inputs. # Read vocabs and inputs. dropout = params["dropout"] if params["circle_fea...
1e6eb2028c8924733329bc4fc3079ca12af12d94
11,753
def jp2yy (sent): """take a Japanese sentence in UTF8 convert to YY-mode using mecab""" ### (id, start, end, [link,] path+, form [surface], ipos, lrule+[, {pos p}+]) ### set ipos as lemma (just for fun) ### fixme: do the full lattice yid = 0 start = 0 cfrom = 0 cto = 0 yy = list() ...
d59a047f95761aacdd1b371bc6f03072d708e505
11,754
def make_ss_matrices(sigma_x, dt): """ To make Q full-rank for inversion (so the mle makes sense), use: Q = [ dt**2 dt/2 dt/2 1 ] to approximate Q = (dt 1)(dt 1)' System: x = [p_x p_y v_x v_y] y = [p_x' p_y'] :param sigma_x: :param dt: :return: sigma_0:...
551a1d46ee67360e159ab966c0b3f30dd77254c8
11,755
def get_icp_val(tmr): """Read input capture value""" return peek(tmr + ICRx) | (peek(tmr + ICRx + 1) << 8)
0aef45e0c6edeb3c6540a51ae44013ded03c7be7
11,756
import torch def validate(segmenter, val_loader, epoch, num_classes=-1): """Validate segmenter Args: segmenter (nn.Module) : segmentation network val_loader (DataLoader) : training data iterator epoch (int) : current epoch num_classes (int) : number of classes to consider Returns...
716f1eda3a283c2707fa8ffd6e8073c351bda560
11,757
def detect_forward(CoreStateMachine, PostConditionStateMachine): """A 'forward ambiguity' denotes a case where the post condition implementation fails. This happens if an iteration in the core pattern is a valid path in the post- condition pattern. In this case no decision can be made about where to res...
4d6c1952a201f3505b0770f12f42609847728a54
11,758
def price_sensitivity(results): """ Calculate the price sensitivity of a strategy results results dataframe or any dataframe with the columns open, high, low, close, profit returns the percentage of returns sensitive to open price Note ----- Price sensitivity is calc...
02ab811bf689e760e011db6d091dcb7c3079f0d1
11,759
def wrap_zone(tz, key=KEY_SENTINEL, _cache={}): """Wrap an existing time zone object in a shim class. This is likely to be useful if you would like to work internally with non-``pytz`` zones, but you expose an interface to callers relying on ``pytz``'s interface. It may also be useful for passing non-`...
7776153859b30ee758b16498b1122d0af294d371
11,760
async def async_browse_media( hass, media_content_type, media_content_id, *, can_play_artist=True ): """Browse Spotify media.""" info = list(hass.data[DOMAIN].values())[0] return await async_browse_media_internal( hass, info[DATA_SPOTIFY_CLIENT], info[DATA_SPOTIFY_ME], me...
d3f912ecbd8949a637d461a453a4b9a9ea73a20c
11,761
from typing import Tuple import json def bounds(url: str) -> Tuple[str, str, str]: """Handle bounds requests.""" info = main.bounds(url) return ("OK", "application/json", json.dumps(info))
2da1ec2db8b2c0c3a3d28854dc2f68b71aa96bf1
11,762
import email def make_message_id(): """ Generates rfc message id. The returned message id includes the angle brackets. """ return email.utils.make_msgid('sndlatr')
7030efe1d61f4e54d833bb5c808f582689c626c6
11,763
def _understand_err_col(colnames): """Get which column names are error columns Examples -------- >>> colnames = ['a', 'a_err', 'b', 'b_perr', 'b_nerr'] >>> serr, terr = _understand_err_col(colnames) >>> np.allclose(serr, [1]) True >>> np.allclose(terr, [2]) True >>> serr, terr =...
2fab9346a3ea8fa6e84e406856eef8ad14ad9f66
11,764
def unpivot(frame): """ Example: >>> df date variable value 0 2000-01-03 A 0.895557 1 2000-01-04 A 0.779718 2 2000-01-05 A 0.738892 3 2000-01-03 B -1.513487 4 2000-01-04 B -0.543134 5 2000-01-05 B 0.902733 6 20...
6cda1c29e7e7c9b4176e83b6a0e1d907458721b2
11,765
import type def find_viable_generators_aux (target_type, prop_set): """ Returns generators which can be used to construct target of specified type with specified properties. Uses the following algorithm: - iterates over requested target_type and all it's bases (in the order returned bt t...
40764a16b17b54c28495e08623d616d0927451d1
11,766
def analyze(model, Y, print_to_console=True): """ Perform variance-based sensitivty analysis for each process. Parameters ---------- model : object The model defined in the sammpy Y : numpy.array A NumPy array containing the model outputs print_to_console : bool Prin...
119c00becb1c3b507e35cbcecd98762fcb924521
11,767
import copy def GetMorganFingerprint(mol, atomId=-1, radius=2, fpType='bv', nBits=2048, useFeatures=False, **kwargs): """ Calculates the Morgan fingerprint with the environments of atomId removed. Parameters: mol -- the molecule of interest radius -- the maximum radius ...
9fd8077c4f35c83e8996a53981f99baa0e4510a6
11,768
import math def _rgb2lab(rgb): """Convert an RGB integer to Lab tuple""" def xyzHelper(value): """Helper function for XYZ colourspace conversion""" c = value / 255 if c > 0.0445: c = (c + 0.055) / 1.055 c = math.pow(c, 2.4) else: c /= 12.92 ...
a663370e3908daa9ba795bb0dc2ecb945653221e
11,769
import os def _resolve_dir(env_name, dflt_dir): """Resolve a directory given the override env var and its default directory. And if '~' is used to indicate the home directory, then expand that.""" folder = os.environ.get(env_name, dflt_dir) if folder is not None: return os.path.expanduser(...
677c9b3bab970c56f1b3ea0ac8cff75d083e5328
11,770
import torch def biband_mask(n: int, kernel_size: int, device: torch.device, v=-1e9): """compute mask for local attention with kernel size. Args: n (torch.Tensor): the input length. kernel_size (int): The local attention kernel size. device (torch.device): transformer mask to the devi...
ab3a5f25f9fe0f83579d0492caa2913a13daa2d7
11,771
def containsIfElse(node): """ Checks whether the given node contains another if-else-statement """ if node.type == "if" and hasattr(node, "elsePart"): return True for child in node: if child is None: pass # Blocks reset this if-else problem so we ignore them # ...
255f58fdf4abe69f10e9b433562ade12cb0bc215
11,772
import os def lstm_create_dataset(data_home, batch_size, repeat_num=1, training=True): """Data operations.""" ds.config.set_seed(1) data_dir = os.path.join(data_home, "aclImdb_train.mindrecord0") if not training: data_dir = os.path.join(data_home, "aclImdb_test.mindrecord0") data_set = ds...
c0cfe9e37edbae523e580e0e218f9cfe4c0ff835
11,773
def get_gitlab_scripts(data): """GitLab is nice, as far as I can tell its files have a flat hierarchy with many small job entities""" def flatten_nested_string_lists(data): """helper function""" if isinstance(data, str): return data elif isinstance(data, list): ...
ad73c1ea6d4edcbce51eea18de317d7ab2d5e536
11,774
import new def method(cls): """Adds the function as a method to the given class.""" def _wrap(f): cls.__dict__[f.func_name] = new.instancemethod(f,None,cls) return None return _wrap
0f746420bf9870dec5d8a5e69bcec414530fc1cb
11,775
def maps_from_echse(conf): """Produces time series of rainfall maps from ECHSE input data and catchment shapefiles. """ # Read sub-catchment rainfall from file fromfile = np.loadtxt(conf["f_data"], dtype="string", delimiter="\t") if len(fromfile)==2: rowix = 1 elif len(fromfile)>2: ...
31e09c5bed2f7fe3e0d750a59137c05ef987dc2e
11,776
def utility_assn(tfr_dfs): """Harvest a Utility-Date-State Association Table.""" # These aren't really "data" tables, and should not be searched for associations non_data_dfs = [ "balancing_authority_eia861", "service_territory_eia861", ] # The dataframes from which to compile BA-Uti...
6b0357f1d7024bcfddac6981d968e67e5dbeba51
11,777
def is_smtp_enabled(backend=None): """ Check if the current backend is SMTP based. """ if backend is None: backend = get_mail_backend() return backend not in settings.SENTRY_SMTP_DISABLED_BACKENDS
988d2173923dc53cd3179cf0866c702ab9fe69d4
11,778
import requests def get_presentation_requests_received(tenant: str, state: str = ''): """ state: must be in ['propsal-sent', 'proposal-received', 'request-sent', 'request-received', 'presentation-sent', 'presentation-received', 'done', 'abondoned'] """ possible_states = ['', 'propsal-sent', 'proposal-...
1157712b8e4df1b269892a2d3ec15dae366d8d71
11,779
def generate_round(): """ Генерируем раунд. Returns: question: Вопрос пользователю result: Правильный ответ на вопрос """ total_num, random_num = generate_numbers() question = " ".join(total_num) answer = str(random_num) return question, answer
d4b535016e6ca6c6d673c1a6a2ee2c20eca87bc1
11,780
from datetime import datetime def get_basic_activity(): """ A basic set of activity records for a 'Cohort 1' and CoreParticipant participant. """ return [ {'timestamp': datetime(2018, 3, 6, 0, 0), 'group': 'Profile', 'group_id': 1, 'event': p_event.EHRFirstReceived}, {'timesta...
4ee13cf35326d6c09fb4174f0e4217b17a34a545
11,781
def bad_multi_examples_per_input_estimator_misaligned_input_refs( export_path, eval_export_path): """Like the above (good) estimator, but the input_refs is misaligned.""" estimator = tf.estimator.Estimator(model_fn=_model_fn) estimator.train(input_fn=_train_input_fn, steps=1) return util.export_model_and_e...
c08fac8d0ae8679db56128dc8d4a36a5492a6737
11,782
import os def page_is_dir(path) -> bool: """ Tests whether a path corresponds to a directory arguments: path -- a path to a file returns: True if the path represents a directory else False """ return os.path.isdir(path)
bb52f6f09110e085fbb4cd8aeb9d03b36fe07b84
11,783
import logging import yaml def read_configuration(dirname_f: str) -> dict: """ :param dirname_f: path to the project ending with .../cameras_robonomics :type dirname_f: str :return: dictionary containing all the configurations :rtype: dict Reading config, containing all the required data, suc...
784c45095d1dd5530c65e9000b0e9d7f95662b20
11,784
def caption_example(image): """Convert image caption data into an Example proto. Args: image: A ImageMetadata instance. Returns: example: An Example proto with serialized tensor data. """ # Collect image object information from metadata. image_features, positions = read_object(image.objects, image...
f989774a0d3321717cbb09f6342a6c86f5433c54
11,785
def GetAttributeTableByFid(fileshp, layername=0, fid=0): """ GetAttributeTableByFid """ res = {} dataset = ogr.OpenShared(fileshp) if dataset: layer = dataset.GetLayer(layername) feature = layer.GetFeature(fid) geom = feature.GetGeometryRef() res["geometry"] = geo...
42b845ae5b1a3c9976262cc37f5854b80aa7b290
11,786
def get_root_folder_id(db, tree_identifier, linked_to, link_id): """Get id of the root folder for given data category and profile or user group Args: db (object): The db object tree_identifier (str): The identifier of the tree linked_to (str): ['profile'|'group'] link_id (int): ...
7378ec4852d90913282109dcce5d8168613c835e
11,787
def str_cell(cell): """Get a nice string of given Cell statistics.""" result = f"-----Cell ({cell.x}, {cell.y})-----\n" result += f"sugar: {cell.sugar}\n" result += f"max sugar: {cell.capacity}\n" result += f"height/level: {cell.level}\n" result += f"Occupied by Agent {cell.agent.id if cell.agen...
d62801290321d5d2b8404dbe6243f2f0ae03ecef
11,788
def get_idx_pair(mu): """get perturbation position""" idx = np.where(mu != 0)[0] idx = [idx[0], idx[-1]] return idx
eed8b77f3f21af93c28c84d6f325dd2161740e6f
11,789
def zeeman_transitions(ju, jl, type): """ Find possible mu and ml for valid ju and jl for a given transistion polarization Parameters: ju (scalar): Upper level J jl (scalar): Lower level J type (string): "Pi", "S+", or "S-" for relevant polarization type Returns: tu...
446d9683da6cc027003b2ec755d8828ccb01db5d
11,790
def get_reachable_nodes(node): """ returns a list with all the nodes from the tree with root *node* """ ret = [] stack = [node] while len(stack) > 0: cur = stack.pop() ret.append(cur) for c in cur.get_children(): stack.append(c) return ret
c9ffaca113a5f85484433f214015bf93eea602d1
11,791
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc(): """separate rgb embeddings.""" hparams = imagetransformer_sep_channels_12l_16h_imagenet_large() hparams.num_hidden_layers = 16 hparams.local_attention = True hparams.batch_size = 1 hparams.block_length = 256 return hparams
1d428cae33a6a34a7844171c72c7821a44fc3e97
11,792
def torsion_coordinate_names(zma): """ z-matrix torsional coordinate names (currently assumes torsional coordinates generated through x2z) """ name_dct = standard_names(zma) inv_name_dct = dict(map(reversed, name_dct.items())) geo = automol.geom.without_dummy_atoms(geometry(zma)) tors_names...
a7820e1619d4a73260ec4d9255b78cdec2263a55
11,793
from typing import List from typing import Dict def extract_other_creditors_d( page: pdfplumber.pdf.Page, markers: List[Dict], creditors: List ) -> None: """Crop and extract address, key and acct # from the PDf :param page: PDF page :param markers: The top and bottom markers :return: Address, key...
cb66185c68c7ab3febeee611e4384b839b42417e
11,794
from typing import List from pathlib import Path def get_dicdirs(mecab_config: str = "mecab-config") -> List[Path]: """Get MeCab dictionary directories. Parameters ---------- mecab_config : str Executable path of mecab-config, by default "mecab-config". Returns ------- List[Path]...
26d7969c072a9aa0668db31c296ee930b567049f
11,795
def new_instance(settings): """ MAKE A PYTHON INSTANCE `settings` HAS ALL THE `kwargs`, PLUS `class` ATTRIBUTE TO INDICATE THE CLASS TO CREATE """ settings = set_default({}, settings) if not settings["class"]: Log.error("Expecting 'class' attribute with fully qualified class name") ...
bf32bd41105052816a9a54efb71143f2a250502f
11,796
from sys import path def find_entry(entries, fn): """Find an entry that matches the given filename fn more or less.""" entry = get_entry_by_filename(entries, curr_file) if entry is not None: return entry key = lambda fn: path.splitext(fn)[0] entry = get_entry_by_filename(entries, curr_fi...
0552d61bea835b5eb3975a388287062fcb733b33
11,797
def get_type(k): """Takes a dict. Returns undefined if not keyed, otherwise returns the key type.""" try: v = { 'score': '#text', 'applicant': 'str', 'applicant_sort': 'str', 'author': 'str', 'author_sort': 'str', 'brief': 'boo...
fec3b7e04531dd202c46366f096f687160c68320
11,798
def al(p): """ Given a quaternion p, return the 4x4 matrix A_L(p) which when multiplied with a column vector q gives the quaternion product pq. Parameters ---------- p : numpy.ndarray 4 elements, represents quaternion Returns ------- numpy.ndarray 4x4 matrix des...
1e4803bffd75fb841b723d504261c51019d5d45e
11,799