content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import fnmatch def filename_match(filename, patterns, default=True): """Check if patterns contains a pattern that matches filename. If patterns is not specified, this always returns True. """ if not patterns: return default return any(fnmatch.fnmatch(filename, pattern) for pattern in patt...
42572c4d9c4b1e21f751be87dfab53fec87b891e
669,917
from itertools import tee def binary_reflected_graycodes_reduce(codes, on=lambda p, r: r, off=lambda p, r: r, redux=None, full_tuple=False): """ An *opera...
f2ad655e4bc3811e02e46f1e58a01cb05a63cb5b
669,918
import sys import subprocess def get_mpi_env(envs): """get the mpirun command for setting the envornment support both openmpi and mpich2 """ cmd = '' # windows hack: we will use msmpi if sys.platform == 'win32': for k, v in envs.items(): cmd += ' -env %s %s' % (k, str(v)) ...
a5f86fbbce0c5fac744133642589f045e7b6c165
669,919
import pandas def checkFile(path): """ Checks if the input 'path' is an excel file an can be correctly read, returns a boolean """ #data = pandas.ExcelFile(path, engine='openpyxl') #print(data) try: data = pandas.ExcelFile(path, engine='openpyxl') return True except: ...
b191e193a2a640ed96a5f760332af878c1c75bdb
669,920
import math def truncate_floor(number, decimals): """Truncates decimals to floor based on given parameter Arguments: number {float} -- number to truncate decimals {int} -- number of decimals Returns: float -- truncated number """ return math.floor(number * 10 ** decimals)...
3f172b9947635662b59f2c5f31abb2cc13e31882
669,921
import random def convkey(x, left=False, right=False): """Turns a numerical salary value into a string preserving comparison.""" assert not (left and right) if left: appendix = '0' elif right: appendix = '9' else: appendix = '5' appendix += ''.join(chr(random.randrange(...
20b70b136caeed484ddbaa3d0b7f7691b8f38318
669,924
def _return_features(data, features): """Select specific raw features from the data :param data: The data set to manipulate. :param features: A list of ISXC 2012 IDS specific features. :return: List of data with just the chosen features in the order they were requested. """ process...
921ca5eaa514e19a0d97a3522f70b3c9297a440f
669,925
def get_version(): """Get the current version number for the library Returns ------- String Of the form "<major>.<minor>.<micro>", in which "major", "minor" and "micro" are numbers""" with open("hyperparameter_hunter/VERSION") as f: return f.read().strip()
f2b212f09839af98c4a3a912416413ba0649d3a1
669,926
def return_module(module): """Mock for importlib.reload(). Returns argument.""" return module
b132269774d6faa0924fec264f756cd67b0b9c1b
669,927
def predict_proba_model(model, X_score): """Uses a trained scikit-learn model to predict class probabilities for the scoring data""" return model.predict_proba(X_score)[:, 1]
e1cde41ac300e49814b747749064bbc1d1c3a5a6
669,928
import struct def lcs32(b: bytes, s: int): """Shift 32-bit quantity `b` `s` bytes to the left.""" u = struct.unpack(">I", b)[0] return struct.pack(">I", ((u << (s*8)) | (u >> (32 - s*8))) & 0xffffffff)
3468295dde4f4acc27b02c779c3490c81c388688
669,930
def is_node(node, name): """Return the node name""" if node is None: return False return node.__class__.__name__ == name
bec69d48157bb6b0a57bde345d6b7c0d098a0244
669,931
import pytz def localize_date(date, city): """ Localize date into city Date: datetime City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'.. """ local = pytz.timezone(city) local_dt = local.localize(date, is_dst=None) return local_dt
1b07cbe5abfe6f391d9c981002227e68120c43ac
669,932
def serialize_utf8(value, partition_key): """A serializer accepting bytes or str arguments and returning utf-8 encoded bytes Can be used as `pykafka.producer.Producer(serializer=serialize_utf8)` """ if value is not None and type(value) != bytes: # allow UnicodeError to be raised here if the enc...
4281fe898797eb453b549296a6113d7056d8cbc3
669,933
def _module_name_safe(string): """Returns a transformation of `string` that is safe for module names.""" result = "" saw_non_identifier_char = False for ch in string.elems(): if ch.isalnum() or ch == "_": # If we're seeing an identifier character after a sequence of # non...
a0f5659e7ec3bed0443d88f1e8fe8ec9fe27ee85
669,935
def set_common_keys(dict_target, dict_source): """ Set a dictionary using another one, missing keys in source dictionary are reported""" keys_missing=[] for k in dict_target.keys(): if k in dict_source.keys(): dict_target[k]=dict_source[k] else: keys_missing.append(k)...
5bd4e6f53c1b6991b458c6140ed927be4866a93e
669,936
import torch def accuracy(logits, labels): """ Compute accuracy of given forward pass through network. Parameters: - - - - - logits: torch tensor output of single network forward pass labels: torch tensor ground truth class of each sample Returns: - - - - float s...
a9a5e4e298a1f20ae065dda3deb873fd3b77ca42
669,938
import collections def _GetResourceIdentifierString(resource_type, resource_identifier): """Returns a human readable string representation of a resource identifier. Args: resource_type: the type of resource identified by `resource_identifier`. resource_identifier: an ordered mapping representing a fully ...
7413d26d67532418f5c0ed09a7fa6df4042a3844
669,939
import subprocess def bedtools_getfasta( bed_path, genome_path, output_path, strand=True, bedtools_exe="bedtools" ): """Extract DNA sequences from a fasta file based on feature coordinates. Wrapper around `bedtools getfasta`. This function was made to work with bedtools version 2.27.1. It is not guara...
fa4ce1516a13d21be08abca7df2dd8965a157ef5
669,940
import random def duplicate(row, n=5): """ Duplicates (augments) the row by modifying the sale price :param row: pandas series :param n: how many duplicates to return :return: duplicates in list """ price = row['sales.price'] lower, higher = price * 0.9, price * 1.1 dupe_list = [] ...
ea80b5ae5c308e1260c153eb46b9c17bae376e80
669,941
def get_gtf_chromosomes(gtf_fn): """Return a set of chromosomes in gtf""" chrs = set() with open(gtf_fn, 'r') as reader: for line in reader: if line.startswith('#') or len(line.strip()) == 0: continue else: chrs.add(line.split('\t')[0]) ret...
23ca548068d29ed2c6d98f38f3a7be857582445d
669,942
def _adjmatType(adjMat): """(helper function) retruns <class 'int'> if the adjacency matrix is a (0,1)-matrix, and returns <class 'list'> if the adjacency matrix contains edge weights, and returns None if neither of the cases occurs. Args: adjMat (2D - nested - list): the adjacency matrix. ...
f57e3a97c6d759a564bcf0e546c67ee975caf4c7
669,943
import os def get_default_config_file(name): """Get the default config file. Args: name (str): daos component name, e.g. server, agent, control Returns: str: the default config file """ file_name = "".join(["daos_", name, ".yml"]) return os.path.join(os.sep, "etc", "daos", f...
90d56018c4adc02c7e4b6f73fd27ff8ef363e341
669,944
import re def delBlock( Text ) : """ removed task and function block """ Text = re.sub(r'\Wtask\W[\W\w]*?\Wendtask\W','\n',Text) Text = re.sub(r'\Wfunction\W[\W\w]*?\Wendfunction\W','\n',Text) return Text
204ebb483230b541bd319cd6b92b1c8468f84963
669,945
def get_user_article_choice() -> int: """ Get user's choice on which article they want to view. :precondition: User's input must be an integer :postcondition: Successfully return user's input as an integer :return: User's choice of article number as an integer """ # Loop until there is val...
7f04ce42b7a673019f0ebd48fec426b443e8295a
669,946
from typing import List from typing import Optional import bisect def get_bucket(seq_len: int, buckets: List[int]) -> Optional[int]: """ Given sequence length and a list of buckets, return corresponding bucket. :param seq_len: Sequence length. :param buckets: List of buckets. :return: Chosen buck...
8a5db6dda3b87e015a0abdb1b4a380ed22df38b9
669,947
def valid_data_string(request, valid_delimiter): """ Fixture that yields valid data strings. """ return request.param.format(delimiter=valid_delimiter)
ca4d2995943a19b9b3733edde889cea5b2642d8c
669,948
import os def resolve_relative_path(self, relative_path, extra_path = None): """ Resolves the relative path as an absolute path. The resolution takes into account an extra path that may be added to the resolved path. :type relative_path: String :param relative_path: The relative path to be us...
d32e73e9f3ec7397c3eb3f3da6f8748c2a71a732
669,950
def jenkins_folder_xml(): """XML used to create folder on Jenkins. for now just hardcode the XML. :return str """ return """<?xml version="1.0" encoding="utf-8"?> <com.cloudbees.hudson.plugins.folder.Folder plugin="cloudbees-folder"> <actions/> <icon class="com.cloudbees.hu...
30d3ac6d2691396fbf2e640760f7e2238e564b17
669,951
def Quantity(number, singular, plural=None): """A quantity, with the correctly-pluralized form of a word. E.g., '3 hours', or '1 minute'. Args: number: The number used to decide whether to pluralize. (Basically: we will, unless it's 1.) singular: The singular form of the term....
b206fca427a5674cd09d8fc334e1a00c54aa2cdd
669,952
def conv_dt(dt): """ Scale dt (time diff between SAR and ALT) by std. Computed with: with h5py.File('aggregate_ALT.h5', 'r') as fs: dd = np.hstack([fs['dx'][:].reshape(-1,1), fs['dt'][:].reshape(-1,1)]) print(dd.std(axis=0)) """ return dt / 36.70367443
b9f41638cba6c6ed254d05fd2c866eafd74c9c28
669,953
from typing import List def smart_join(elements: List[str], sep: str) -> str: """ Uses regular join after filtering null elements from the initial list Parameters ---------- elements : List[str] list of /possibly null/ strings to join sep : str joining delimiter Returns ...
26e8ec7bea41ae6292fce7730003907643dec17a
669,954
import glob import os def get_latest_model_file(folder): """ returns the location of the newest file in the provided foler path note: folder path NEEDS to end on a / returns None if no files were found in given location """ files = glob.glob(folder + 'model*.pt') if files == []: ...
638a49b938ffec78a11e605c36d30176e7b61a77
669,955
import os import pickle def try_to_load_as_pickled_object_or_None(filepath): """ This is a defensive way to write pickle.load, allowing for very large files on all platforms """ max_bytes = 2**31 - 1 try: input_size = os.path.getsize(filepath) bytes_in = bytearray(0) with o...
75d706ab53e3dc8fae677072ff8a167e7076325d
669,956
def obscure_string(input_string): """ Obscures the input string by replacing all but the last 4 characters in the string with the character '*'. Useful for obscuring, security credentials, credit card numbers etc. Args: input_string A string of characters Returns: A new string where all but the l...
fd49f289fe6ae3fd1f7be73fcacdc968f5c47cf3
669,958
def read_json(jsondata): """Read names of sensors from JSON file.""" readlist = ["'" + jsondata[sensor]['name'] + "'" for sensor in jsondata] return(eval("""{{'r': [{}] }}""".format(', '.join(readlist))))
ea0c90a6fde4a8d2699a201104b38b43e89010bf
669,959
def WignerHsize(mp_max, ell_max=-2): """Total size of array of wedges of width mp_max up to ell_max Parameters ---------- ell_max : int mp_max : int, optional If None, it is assumed to be at least ell See Also -------- WignerHrange : Array of (ℓ, m', m) indices corresponding to...
0a2fd8618dd2099c09cbf1045aa2f5b52deb9ca1
669,960
def word_count(string: str) -> int: """Count the words in a string. Might not be 100% correct. Args: string (str): The string to analyze. Returns: int: The word count. """ return string.count(" ") + string.replace("\n\n", "\n").count("\n") + 1
866ae7cc71aac90875be62d3c780630b4878a44a
669,961
def convert_spreadsheet_to_unix(val): """ This function converts a date from an Excel spreadsheet (which is an integer) into the number of seconds since the Unix epoch (which is also an integer). """ # Return answer .. return 86400 * (val - 25569)
134baa086389f7b4f76c4cbfb2f5037f83e08793
669,963
def compute_distribution_bounds(history, parameter, alpha, run): """Returns distribution bounds from pyabc posterior distribution. Parameters ---------- history : pyabc.smc An object created by :func:`pyabc.abc.run()` or :func:`respyabc.respyabc()`. parameter : str Paramete...
af4726d07210108340cea7c6335ec99a0c40cdb1
669,964
def balanced_eq(x, z, y): """Gradient of the max operator with tie breaking. Args: x: The left value z: The maximum of x and y y: The right value Returns: The gradient of the left value i.e. 1 if it is the maximum, 0.5 if they are equal and 0 if it was not the maximum. """ return (x == z...
896ce734e43dafd3c5084bc623b329bbc5a3b1f9
669,965
def _d4(E, f, d3): """ Solve Eq. 23 """ return -f[0] / (f[1] + 0.5 * d3 * f[2] + (d3**2) * f[3] / 6.)
db9d6782380e3463b50d13fb526637821ae4025c
669,966
def get_region_names_of_lausanne_2008_atlas(): """ Get the ordered region names of the Lausanne 2008 atlas as in standard papers. It corresponds to the Desikan atlas in the cortex, without the corpus callosum along with 7 subcortical regions. Returns ------- atlas_names: list of str ...
adda8b874a84e1836dfbc91f9cc5f536ee2952cd
669,967
import os import json import sys def load_config(config_file): """ Load configuration from file (output: dict) """ if os.path.isfile(config_file): try: with open(config_file, 'rU') as f: config = json.load(f) except ValueError: print('Wrong JSON ...
9a35b962e169e2d266e92f957635a2d7f2bc20f5
669,969
def create_mock_coro(mocker, monkeypatch): """Fixture to mock coroutines. Reference: https://github.com/econchick/mayhem/blob/master/part-5/test_mayhem_3.py """ def _create_mock_patch_coro(to_patch=None): mock = mocker.Mock() async def _coro(*args, **kwargs): return mock(*a...
02d4b279245f5dfd10282999f68228aa07ec7301
669,970
def unwrap(url): """Transform a string like '<URL:scheme://host/path>' into 'scheme://host/path'. The string is returned unchanged if it's not a wrapped URL. """ url = str(url).strip() if url[:1] == '<' and url[-1:] == '>': url = url[1:-1].strip() if url[:4] == 'URL:': url = url...
84510be907f933212b5f6747cc8d6635b72ad38b
669,971
import os import shutil def tmpDir(): """A temporary folder for the test session. This folder is presistent after the tests have run so that the status of generated files can be checked. The folder is instead cleared before a new test session. """ testDir = os.path.dirname(__file__) theDir...
90599f02f49f1d94dddcf636a94ed0ef99bdf607
669,972
def repr_dict(dict_obj): """Human readable repr for a dictonary object. Turns a dict into a newline delimited string. Intended use is for loading up sample specifications into the starting buffer of an editor :param dict_obj: type dict dictionary to format""" res = '' for k, v in dict_obj.iteritems...
085dabfde3c19712049a157cbea38ec64302ab93
669,974
from bs4 import BeautifulSoup import requests def fetch(session, url): """ Fetch a URL and parse it with Beautiful Soup for scraping. """ return BeautifulSoup(requests.get(url, stream=False).text, "html.parser")
7fb0c0dc01dcc021c50e7e7648febcf3d522fcec
669,975
import torch def get_simple_trajopt_cost(x_dim, u_dim, alpha_dim, dtype): """ Returns a set of tensors that represent the a simple cost for a trajectory optimization problem. This is useful to write tests for example @return Q, R, Z, q, r, z, Qt, Rt, Zt, qt, rt, zt where min ∑(.5 xᵀ[n] Q ...
fcbff16048c0d39d2cae71c15347ab2fedea1b11
669,976
def _range_representer(representer, node: range): """Represents a Python range object using the ``!range`` YAML tag. Args: representer (ruamel.yaml.representer): The representer module node (range): The node, i.e. a range instance Returns: a yaml sequence that is able to recreate a...
ac1cb8481d3eb3251303d87681de7ca5ebb12513
669,978
import platform def edgetpu_lib_name(): """Returns the library name of EdgeTPU in the current platform.""" return { 'Darwin': 'libedgetpu.1.dylib', 'Linux': 'libedgetpu.so.1', 'Windows': 'edgetpu.dll', }.get(platform.system(), None)
2aac0dde023a4dbe567c93261bd83b1c7d7e7b3d
669,980
import pathlib import tempfile import zipfile def extract_archvie(archive_path: pathlib.Path) -> pathlib.Path: """ Extract a user data archive to a temporary directory. If the user supplied a path to an already unzipped archive, this is a no-op and will return the same path. Otherwise, the archive is...
b122f47225f25a644295011fdf6d46730acd07be
669,981
def v(): """ Actual vk API version """ return '5.80'
f0d7c9771a34ceed1f4639e555271ff9c692bb99
669,984
def update_ares(line_list, spectrum, out, options): """Driver for ARES""" default_options = options for key, value in default_options.items(): if key not in options.keys(): options[key] = value def rejt_from_snr(snr): """Calculate rejt from SNR""" return 1.0-(1.0/fl...
4f3adba33c1af9a3ff7459dc2b2c1a5378137ffb
669,985
def return_characters(data: bytes) -> bytes: """ Characters that are used for telegram control are replaced with others so that it is easier to parse the message over the wire. Final character is never replaced. This function returns them to their original form. '\x1b\x0e' -> '\x0d' '\x1b\x...
20e633f6a9757595f3b19ac82d2d51feac95ffa9
669,987
def calculate_separate_operator_conditionals(expression: str) -> int: """Return the evaluation of the given infix arithmetic expression Note: integer division should truncate toward zero. Args: expression: A valid infix arithmetic expression containing only digits and operators in '+', '-'...
ffd3a75247d128eeb16c0b9cffef28597d014d80
669,988
def input_to_yaml(i, prefix, array, record): """ Transcribe inputs for the yaml file """ yaml = "" if record : if i.type == "text" or i.type == "integer" or i.type == "float" or i.type == "boolean" or i.type == "select": yaml += str(i.name) + ": " + prefix + "." + str(i.name) ...
ac952a91c799092f1ca12b0576c89cc687e4be2d
669,989
def get_final_ranks(rank_probs): """Orders final rank probabilities into a list and trims decimal places. """ ranks = [] for team, prob_dict in sorted(rank_probs.items(), key=lambda x: -sum([i*p for i,p in enumerate(x[1].values())])): ranks.append({"team": team, "prob...
887da4da34574c3c966545d0781aca8cfb8131bd
669,990
def createOpponentCol(x,name): """helper function""" if (x['winner_name'] == name): return x['loser_name'] else: return x['winner_name']
21d2edb42ca23d421892704b3e19c2549dabbb49
669,991
def _sort_by_fitness(parameters, fitness): """Given a parameters and fitness array, returns the same arrays but sorted in ascending order of the fitness. Args: fitness (numpy array): As a numpy array, the values for the fitness. parameters (numpy array): As a numpy array, the values for the...
521c2b3425d39e4f23ff7902f94c0456bb60e930
669,992
from pathlib import Path import yaml def load_game_reource(game_tag: str, filename: str) -> dict: """Return specific game resource from `{filename}.yml` file.""" path = Path(f"incarn/resources/games/{game_tag}/{filename}.yml").read_text("utf8") return yaml.load(path, Loader=yaml.FullLoader)
74ec91e0a48f1f6b6ad2bcf44879ed77cb32eaa5
669,993
def _index_story(stories, title): """Returns index of title in story list returns -1 if not found Arguments: stories [Story] -- List of stories (Story) title str -- Story title to look for in list """ for i, story in enumerate(stories): if story == title: ret...
a924a600fae37b7de08eb7f6acc991b3401a5791
669,994
import math def principal_value(angle_in_radians: float) -> float: """ Ensures the angle is within [-pi, pi). :param angle_in_radians: Angle in radians. :return: Scaled angle in radians. """ interval_min = -math.pi two_pi = 2 * math.pi scaled_angle = (angle_in_radians - interval_min) ...
6fc57322bbe9c44b838bfdb4d9eb191d3c07faed
669,996
def desc_sort_list(list, key): """desc sort list of dicts for a given key.""" return sorted(list, key=lambda kev: kev[key], reverse=True)
ad89fe00334ffb15d3b2cc50893f207ab64dfaf7
669,997
from typing import List def _get_number_range(left: str, right: str) -> List[int]: """Get the number range list @type left: str @param left: The left string of the division mark @type right: str @param right: The right string of the division mark @returns List[int]: The list with the range ...
05a6cd572c3cc66f3e54cca8fbfc8a2d2e95e1e1
669,998
import os def get_latest_ecmf_file(): """Return the file name of the latest ecmf file""" basedir = '/var/lib/odindata/ECMWF' def is_digit_dir(name): if not os.path.isdir(os.path.join(basedir, name)): return False if not name.isdigit(): return False return T...
0d4d92d4379e0692d234aa3596fdf8e1cd1c7381
669,999
import torch def to_onehot(target: torch.Tensor, num_classes: int) -> torch.Tensor: """ Convert given target tensor to onehot format :param target: `LongTensor` of `BxCx(optional dimensions)` :param num_classes: number of classes :return: """ size = list(target.size()) size.insert(1, num...
de12f78d4d1f29ea351da701bde10c7c5fb63592
670,000
def f(x): """ Args: x (object): """ return 42
4254244a006411c17592bdd840f91ffa4ec9cdef
670,001
import torch def dihedral( x0: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, x3: torch.Tensor ) -> torch.Tensor: """Dihedral between four points. Reference --------- Closely follows implementation in Yutong Zhao's timemachine: https://github.com/proteneer/timemachine/blob/1a0ab45e605d...
50bce697366bf11dc4df23e45f18519d7f28cc6f
670,002
def conv2d(obj, filt): """ 2-D spatial convolution of an `Image` or `ImageCollection`. Parameters ---------- obj: `Image` or `ImageCollection` Object to convolve over filt: `Kernel` object Kernel object to convolve Example ------- >>> from descarteslabs.workflows im...
d24494baec44ada81f2bc5276e8c08b48baeaadc
670,003
import torch def create_mask(batchsize, max_length, episode_length, length): """Given the length create a mask given a padded tensor""" tensor_mask = torch.zeros(batchsize, max_length) for idx, row in enumerate(tensor_mask): row[:max(episode_length,length[idx])] = 1 return tensor_mask
c4e5fec27c09ed883a110fc5499e15b68d4841ea
670,004
from typing import Callable from typing import Any def to_string_gen(gen) -> Callable[[Any], str]: """ Accepts a string or a function that returns a string and returns a function that returns a string :param gen: either the string to be returned or a generator that accepts an element and returns a string...
411ab7a0c53dbdbe0489be1929d188692ae9bfab
670,005
def switchAndTranslate(gm1, gm2, v1, v2, wrapModulo): """ Transforms [v1,v2] and returns it such that it is in the same order and has the same middle interval as [gm1, gm2] """ assert(v1 < v2) # keep the same middle of the interval if (wrapModulo): gmMiddle = float(gm1 + gm2) / 2...
dd9ad5823d7e99a1ec22e55c46d8ec0040b5268b
670,006
def form_intro(pol_areas, description=None): """ Form the introduction line Parameters ---------- pol_areas: list of all the policy areas included in the reform used to create a description of the reform description: user provided description of the reform """ # these are all of...
79fbb4e30dcf3ffc31f1fb8924fa94db442e30ab
670,007
import importlib def find_model_using_name(model_name): """Import the module "models/[model_name]_model.py". In the file, the class called DatasetNameModel() will be instantiated. It has to be a subclass of BaseModel, and it is case-insensitive. """ model_filename = "models." + model_name + "...
d946c43098eaffff99c142a25588722f664b3074
670,008
import struct def get_vbmeta_size(vbmeta_bytes): """Returns the total size of a AvbVBMeta image.""" # Keep in sync with |AvbVBMetaImageHeader|. AVB_MAGIC = b'AVB0' # pylint: disable=C0103 AVB_VBMETA_IMAGE_HEADER_SIZE = 256 # pylint: disable=C0103 FORMAT_STRING = ( ...
a863c4ca5e96d78deb401c962563c2de41187ae9
670,009
import copy def isnested(A, B, namespace=None): """ Is factor B nested within factor A or vice versa: a very crude test which depends on the namespace. If they are nested, returns (True, F) where F is the finest level of the relationship. Otherwise, returns (False, None) """ if namespac...
c767ba2253aafb0a8c59ae09160fe702006f7d10
670,011
from datetime import datetime def get_current_month_name(month=None): """ get the current month name. if month is given then get the name of that month otherwise get this month name """ current_date = datetime.now() if month is not None: current_date = datetime(current_date.ye...
2bd07616aa517fe3c86b41c09e0dc469023900a6
670,012
def _compute_delta_t( data: dict, nodeid: str, event1: str, event1_pos: int, event2: str, event2_pos: int) -> float: """Compute time delta between two events :param dict data: data :param str nodeid: node id :param str event1: event1 :param int event1_pos: event1 position in stream ...
b8496b63c9dc93e3e9070c3c4ec89ca445a88dee
670,013
def isCat_95in10(col): """ hardcoded rule for identifying (integer/string) categorical column """ return col.value_counts().head(10).sum() / float(col.count()) > .95
1f125b6409a6d4864bc81aa2a4c0452c087e9f4d
670,014
def add_qual_hardcoded(obj_dict, ref_csv,flat=True, thinness=True, proportion=True): #10% of obj dim """ # Add hardcoded qualitative sizes as small, medium, etc returns: object dictionary with hardcoded values """ for i,row in enumerate(ref_csv): if i ==0: continue obj_name = row[0]....
0fcee05ad047c76f89ddf00588b9cc0292928aac
670,015
def interpolate(a0, a1, w): """ Interpolate between the two points, with weight 0<w<1 """ # return (a1 - a0) * w + a0 # Can make this smoother later return (a1 - a0) * ((w * (w * 6.0 - 15.0) + 10.0) * w * w * w) + a0
7de0195079fa95fdb4b9a8001f2076edc63cda2e
670,016
def gctor2newc(name, args): """Create a new container object based on generator-constructor name.""" if name == "construct_yaml_set": return set() if name == "construct_yaml_map": return {} if name == "construct_yaml_object": return args[0].__new__(args[0]) return []
68d0f025ea2ee224e9edb6e91230051103e8deef
670,017
def time2str(time): """ returns utc time as hh:mm string """ minute = '0'+str(time.minute) if time.minute < 10 else str(time.minute) return str(time.hour)+':'+minute
382d73bb2b6d8951331e1396f30e0452eed6fe2b
670,018
def solve2(cmds): """calculate the depth and position by applying the given commands logic: up/down change the aim; forward changes position AND depth Args: cmds (list): list of a command and one value: e.g. forward 5 Returns: int: magic number for AOC """ depth,pos,aim=0,0,0 ...
f658574af409eeea3fcddd442f36e7b15f02d089
670,019
import torch def argmin(x): """Deterministic argmin. Different from torch.argmin, which may have undetermined result if the are multiple elements equal to the min, this argmin is guaranteed to return the index of the first element equal to the min in each row. Args: x (Tensor): only supp...
6ff5546b96b964c93d92a1b2d507e5ada703c2fc
670,020
import json def buildJson(self, fields, values): """ Builds json :param fields: fields for json :param values: values for fields in json :return: json """ i = 0 data = {} for field in fields: data[field] = values[i] i += 1 json_data = json.dumps(data) retur...
6be7c05665b83eb6155ddc2eeb5a14179a0dc31a
670,022
import numbers import warnings def result(un,label=None): """ Create an uncertain number to represent an intermediate result :arg un: :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex` or :class:`.UncertainArray` :arg label: str or a sequence of str :rtype: :class:`~lib.UncertainReal` ...
5663ad4499747c61a1b2ee1dc99886a4dbdcb601
670,023
def restore_field_information_state(func): """ A decorator that takes a function with the API of (self, grid, field) and ensures that after the function is called, the field_parameters will be returned to normal. """ def save_state(self, grid, field=None, *args, **kwargs): old_params = g...
d22c99d3b6aa6e7634f18c200a4c00585dbd5352
670,024
import os import fnmatch def get_recursive_mtime(directory, ignores=[]): """Get the latest mtime recursivly on a directory. Args: directory (string): complete path of a directory to scan. ignores (list of strings): list of shell-style wildcards to define which filenames/dirnames t...
5062248881be80a127ddebcff2e40f8dc6f22cf9
670,025
def get_list_subsets(object_list, subset_size): """ Breaks a larger list apart into a list of smaller subsets. :param object_list: The initial list to be broken up :param subset_size: The maximum size of the smaller subsets :return: A list of subsets whose size are equal to subset_size. The last sub...
09030c6fa6a8948ab809cea93261c67f8b77ccd4
670,026
import math def keypoint_rot90(keypoint, factor, rows, cols, **params): """Rotates a keypoint by 90 degrees CCW (see np.rot90) Args: keypoint (tuple): A keypoint `(x, y, angle, scale)`. factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image heigh...
f95f28fdca73f453ffe84e382f70fd5df619c1b5
670,027
import os def get_opposite_os_directory_sep(): """ @return: @rtype: """ if os.sep == '/': return '\\' else: return '/'
664cb27bfc85e88686f5d1b0a3a62eaf8acdba40
670,028
def class_to_fqn(cls): """Returns the fully qualified name for cls""" return '%s.%s' % (cls.__module__, cls.__name__)
f7868a8c1cff11be01636a87914aa49c799f013a
670,029
def dump_mapbox_location( cls, name, zoom=15, width=400, height=300, token="pk.eyJ1IjoibW91c2lraXRvcyIsImEiOiJja2k2bGw2bnkzMXZ2MnJtcHlyejFrNXd4" "In0.JIyrV6sWjehsRHKVMBDFaw", ): """ Free `Tyf.ifd.Ifd.url_load_location` use case. [Use your own Mapbox token](https://docs.mapbox.com/api/overv...
17bc64e38da9690393ce3c574eeb13256a0e3132
670,030
def unpack_result(res): """Turn a document hit from ES into a more traditional JSON object.""" error = res.get('error') if error is not None: raise RuntimeError("Query error: %r" % error) if res.get('found') is False: return data = res.get('_source', {}) data['id'] = str(res.get(...
f071a2068122ac8a39481af0cc24c7d62247e938
670,031
import click def min_far_option(far_name="FAR", dflt=1e-4, **kwargs): """Get option to get min far value""" def custom_min_far_option(func): def callback(ctx, param, value): if value is not None and (value > 1 or value < 0): raise click.BadParameter( "{...
5cc140cd5a8d89d196836a67c86650d260b8b793
670,032
def array2dataset(dataset_cls, obs, array, weights=None): """ dataset_cls: only used to get the class in which array/weights will be converted. """ if hasattr(dataset_cls, "from_numpy"): return dataset_cls.from_numpy(obs=obs, array=array, weights=weights) else: return dataset_cl...
aefc768d08c639a838e47cd9e1e95b3c8436e39e
670,033
def word_article_count_list_to_dict(word_counts): """ Converts list of tuples of words and counts of articles these occur in into list of dictionaries of lists of words and counts. List is of form: [("word, word, ...", count), ...] Dictionary is of form: { "words": [<WOR...
9ff1229baad64af60d9529bce53f5b995e202368
670,034