content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def call_assign_job(job_id, mex_id): """ Function to send an update to the MEx Sentinel to assign a Job to an MEx. """ try: rospy.wait_for_service('/mex_sentinel/assign_job_to_mex', rospy.Duration(1)) try: assign_job = rospy.ServiceProxy('mex_sentinel/assign_job_to_mex', AssignJobToM...
9c5b2aa27e8d04949fbb4c5a2c9eb2ac86ccd9a7
17,090
def full( coords, nodata=np.nan, dtype=np.float32, name=None, attrs={}, crs=None, lazy=False ): """Return a full DataArray based on a geospatial coords dictionary. Arguments --------- coords: sequence or dict of array_like, optional Coordinates (tick labels) to use for indexing along each d...
41bb4fce22a8dd280dee0d4891ff81bd88d263b5
17,091
from typing import Union from typing import List from typing import Tuple from typing import Dict def add_weight_decay( model: nn.Module, weight_decay: float = 1e-5, skip_list: Union[List, Tuple] = () ) -> List[Dict]: """Helper function to not decay weights in BatchNorm layers Source: https://discuss.pyto...
27efae02eaaf0bdc94f3763c1069165c47e08acb
17,093
def find_bands_hdu(hdu_list, hdu): """Discover the extension name of the BANDS HDU. Parameters ---------- hdu_list : `~astropy.io.fits.HDUList` hdu : `~astropy.io.fits.BinTableHDU` or `~astropy.io.fits.ImageHDU` Returns ------- hduname : str Extension name of the BANDS HDU. N...
3b170109d199482c651861764b0ec21a44aa7933
17,094
def read_raw_binary_file(file_path): """can actually be any file""" with open(file_path, 'rb') as f: return f.read()
b03bc1d4c00f9463ded0ea022023e66fd298a7ad
17,095
def encode_cl_value(entity: CLValue) -> dict: """Encodes a CL value. """ def _encode_parsed(type_info: CLType) -> str: if type_info.typeof in TYPES_NUMERIC: return str(int(entity.parsed)) elif type_info.typeof == CLTypeKey.BYTE_ARRAY: return entity.parsed.hex() ...
09d75f9552347e4fd121dcd1a57f26ac46756870
17,096
def escape(string): """ Escape a passed string so that we can send it to the regular expressions engine. """ ret = None def replfunc(m): if ( m[0] == "\\" ): return("\\\\\\\\") else: return("\\\\" + m[0]) # @note - I had an issue getting replfunc to be ca...
c2682757fec2ddaefb32bb792fee44dd63c539fd
17,097
def batch_apply(fn, inputs): """Folds time into the batch dimension, runs fn() and unfolds the result. Args: fn: Function that takes as input the n tensors of the tf.nest structure, with shape [time*batch, <remaining shape>], and returns a tf.nest structure of batched tensors. inputs: tf.nest s...
4cc220a7891f236dc6741e9c203862c5ee33e978
17,098
def grab_haul_list(creep: Creep, roomName, totalStructures, add_storage=False): """ 위에 허울러가 에너지를 채울 목록 확인. :param creep: :param roomName: 방이름. :param totalStructures: 본문 all_structures 와 동일 :param add_storage: 스토리지를 포함할 것인가? priority == 0 인 상황 아니면 포함할일이 없음. :return: 허울러의 에너지 채울 대상목록 """...
d1d944c221089363a7e546bdc03dd51cd178fc35
17,099
def target(x, seed, instance): """A target function for dummy testing of TA perform x^2 for easy result calculations in checks. """ # Return x[i] (with brackets) so we pass the value, not the # np array element return x[0] ** 2, {'key': seed, 'instance': instance}
131560778f51ebd250a3077833859f7e5addeb6e
17,101
def generate(fspec, count, _fuel=None): """Generate <count> number of random passwords/passphrases. The passphrases are formated according to <fspec>. Returned value is (list, json_data), where list is a <count>-element sequence of pair of (password, reading hint for password). json_da...
aad44a80a648d192c696ebdd44ceefadd21d88cd
17,102
def convert_to_valid_einsum_chars(einsum_str): """Convert the str ``einsum_str`` to contain only the alphabetic characters valid for numpy einsum. """ # partition into valid and invalid sets valid, invalid = set(), set() for x in einsum_str: (valid if is_valid_einsum_char(x) else invalid...
2cdd67bc967a12bd3dcb80f323f093cd9eff7213
17,103
def prop_GAC(csp, newVar=None): """ Do GAC propagation. If newVar is None we do initial GAC enforce processing all constraints. Otherwise we do GAC enforce with constraints containing newVar on GAC Queue """ constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons() pruned...
a1c576cfd9920a51eb9b9884bd49b4e8f4194d02
17,104
def submit_only_kwargs(kwargs): """Strip out kwargs that are not used in submit""" kwargs = kwargs.copy() for key in ['patience', 'min_freq', 'max_freq', 'validation', "max_epochs", "epoch_boost", "train_size", "valid_size"]: _ = kwargs.pop(key, None) return kwargs
e93a4b8921c5b80bb487caa6057c1ff7c1701305
17,106
def make_simple_boundary(outline_edge_group: UniqueEdgeList, all_edges: UniqueEdgeList): """ Step 3 recursive :param outline_edge_group: A list of edges, grouped by connectivity between edges. :param all_edges: :return: ??? """ while len(all_edges.edge_list) > 0: current_edge = all_e...
fd3dfd40302d2f01126032c9420fd7b990d30cc6
17,107
async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" job = HassJob(action) if config[CONF_TYPE] == "turn_on": entity_id = config[CONF_ENTITY_ID] @callback ...
5cf362c7dc0b82f562164141ccf76f30dd1a0169
17,110
import pathlib def imread(image_path, as_uint8=True): """Read an image as numpy array. Args: image_path (str or pathlib.Path): File path (including extension) to read image. as_uint8 (bool): Read an image in uint8 format. Returns: :class:`numpy.ndarray`: ...
30050f63e43d862cf512994f0e9d21c187b1ac0a
17,111
def pk(obj): """ A helper that gets the primary key of a model instance if one is passed in. If not, this returns the parameter itself. This allows functions to have parameters that accept either a primary key or model instance. For example: ``` python def get_translations(target_locale): ...
431f518fe6d53e979543e4588a1d7389d7100d69
17,112
import requests import json def get_dataset(id): """Query for existence of dataset by ID.""" uu = UrlUtils() es_url = uu.rest_url #es_index = "{}_{}_s1-ifg".format(uu.grq_index_prefix, version) es_index = "grq" # query query = { "query": { "wildcard": { "_id": id ...
cfb31da0e23b7e197af1919fa34fa3f2d4fa1dfe
17,113
def bags_with_gold( parents_of, _ ): """ Starting from leaf = 'gold', find recursively its parents upto the root and add them to a set Number of bags that could contain gold = length of the set """ contains_gold = set() def find_roots( bag ): for outer_bag in parents_of[ bag ]: ...
3fd2b1c260d41867a5787a14f0c50a9b5d1a2f08
17,114
def process_file(file_path): """ This function processes the submitted file :return: A dictionary of errors found in the file. If there are no errors, then only the error report headers will in the results. """ enc = detect_bom_encoding(file_path) if enc is None: with open(file_path...
29b25b9a1ac950b2b0d051a6748ebc78b31bad10
17,115
import requests def get_request_body(text, api_key, *args): """ send a request and return the response body parsed as dictionary @param text: target text that you want to detect its language @type text: str @type api_key: str @param api_key: your private API key """ if not api_key: ...
e21e8733eec00bc78616b18a8d93c18dc2b20449
17,116
def generate_sample_task(project): """ Generate task example for upload and check it with serializer validation :param project: project with label config :return: task dict """ task = generate_sample_task_without_check(project.label_config) # check generated task '''if project: try...
1e3259b320e46a938139b0dde8ed5b999290d6cd
17,117
def serializable_value(self, field_name): """ Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly. Used to seri...
839d59e92c4249359367d07700bd55f80eafe98b
17,118
import pandas def fetch_fi2010(normalization=None) -> pandas.DataFrame: """ Load the FI2010 dataset with no auction. Benchmark Dataset for Mid-Price Forecasting of Limit Order Book Data with Machine Learning Methods. A Ntakaris, M Magris, J Kanniainen, M Gabbouj, A Iosifidis. arXiv:1705.03233 [cs...
bb6e6e484d6d3d3d1d831a9194fe4f629b820db8
17,119
def get_netcdf_filename(batch_idx: int) -> str: """Generate full filename, excluding path.""" assert 0 <= batch_idx < 1e6 return f"{batch_idx:06d}.nc"
5d916c4969eb96653ea9f0a21ab8bec93ebcfafa
17,120
def area_calc(radius, point_in, total_points): """Calculates the partial area of ball :param radius: radius of ball :param point_in: points of the total points to include :param total_points: number of sampled points :return: area """ return (4 * pi * radius ** 2) * (point_in / total_points)
a660776a4f4a1d2d04a28255b7ee0892ddc5d136
17,122
import gettext import math def results_framework_export(request, program): """Returns .XLSX containing program's results framework""" program = Program.rf_aware_objects.get(pk=program) wb = openpyxl.Workbook() wb.remove(wb.active) ws = wb.create_sheet(gettext("Results Framework")) get_font = l...
79cf9f84243f089dd463909f9f64d13a1bb39444
17,123
import copy def generate_subwindow(pc, sample_bb, scale, offset=2, oriented=True): """ generating the search area using the sample_bb :param pc: :param sample_bb: :param scale: :param offset: :param oriented: use oriented or axis-aligned cropping :return: """ rot_mat = np.tran...
af86fdd4409f98ccd503a9587a6e4b19b0763a31
17,124
def tsfigure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, subplotpars=None, FigureClass=TSFigure): """ Creates a new :class:`TimeSeriesFigure` object. Parameters ---------- num : {None, int}, optional Number of the figure. ...
578b8299ea8b7b8eb05a1f0e68ce4b1f1dca4682
17,125
import zipfile import json def load_predict_result(predict_filename): """Loads the file to be predicted""" predict_result = {} ret_code = SUCCESS try: predict_file_zip = zipfile.ZipFile(predict_filename) except: ret_code = FILE_ERROR return predict_result, ret_code for ...
c26cc24fcdcaa774d05ed6963f66cae346617f46
17,126
def convert_post_to_VERB(request, verb): """ Force Django to process the VERB. """ if request.method == verb: if hasattr(request, '_post'): del(request._post) del(request._files) try: request.method = "POST" request._load_post_and_files() ...
3c304d07ab04950ac65f58405acc3103a3b64dcf
17,128
def close(x, y, rtol, atol): """Returns True if x and y are sufficiently close. Parameters ---------- rtol The relative tolerance. atol The absolute tolerance. """ # assumes finite weights return abs(x-y) <= atol + rtol * abs(y)
bd2597c0c94f2edf686d0dc9772288312cb36d83
17,129
import warnings def plot_precip_field( precip, ptype="intensity", ax=None, geodata=None, units="mm/h", bbox=None, colorscale="pysteps", probthr=None, title=None, colorbar=True, axis="on", cax=None, map_kwargs=None, **kwargs, ): """ Function to plot a pre...
7e9429310ffdfdb38ac2b6e03b4c846d017060f5
17,130
def get_for_repo(repo, name, default=None): """Gets a configuration setting for a particular repository. Looks for a setting specific to the repository, then falls back to a global setting.""" NOT_FOUND = [] # a unique sentinel distinct from None value = get(name, NOT_FOUND, repo) if value is NOT_...
5848e4da859f26788ab02b733bc61135c1ea3b80
17,131
from typing import AnyStr def new_user(tenant: AnyStr, password: AnyStr) -> bool: """Return a boolean containing weither a new tenant is created or no.""" if not query.get_tenant_id(tenant): return True return False
ac1bc45213c76712d1ec3553a8545fac5ab67f3a
17,132
def home(): """ Home page control code :return Rendered page: """ error = request.args.get("error", None) state, code = request.args.get("state", None), request.args.get("code", None) if code and not has_user() and 'state' in session and session['state'] == state: tok = reddit_get_access_t...
280f17feff363fa73decfa15bc615aa0c320d3d9
17,133
def is_even(val): """ Confirms if a value if even. :param val: Value to be tested. :type val: int, float :return: True if the number is even, otherwise false. :rtype: bool Examples: -------------------------- .. code-block:: python >>> even_numbers = list(filter(is_even, ran...
1ef0716e1e86ff77b3234bbd664c6b973352c3ea
17,135
def min_spacing(mylist): """ Find the minimum spacing in the list. Args: mylist (list): A list of integer/float. Returns: int/float: Minimum spacing within the list. """ # Set the maximum of the minimum spacing. min_space = max(mylist) - min(mylist) # Iteratively find ...
b8ce0a46bacb7015c9e59b6573bc2fec0252505d
17,137
def sign(x): """Return the mathematical sign of the particle.""" if x.imag: return x / sqrt(x.imag ** 2 + x.real ** 2) return 0 if x == 0 else -1 if x < 0 else 1
0dca727afbc9c805a858c027a8a4e38d59d9d218
17,139
def wrap_strings(lines: [str], line_width: int): """Return a list of strings, wrapped to the specified length.""" i = 0 while i < len(lines): # if a line is over the limit if len(lines[i]) > line_width: # (try to) find the rightmost occurrence of a space in the first 80 chars ...
0a6fa989fd6d27276d2e7d8c91cf8be37f6a3aff
17,140
def has_even_parity(message: int) -> bool: """ Return true if message has even parity.""" parity_is_even: bool = True while message: parity_is_even = not parity_is_even message = message & (message - 1) return parity_is_even
8982302840318f223e9c1ab08c407d585a725f97
17,141
def is_primitive(structure): """ Checks if a structure is primitive or not, :param structure: AiiDA StructureData :return: True if the structure can not be anymore refined. prints False if the structure can be futher refined. """ refined_cell = find_primitive_cell(structure) prim = Fals...
9f7034bb92d3fdd0505a56bc7d53d1528846ef76
17,142
def mock_mkdir(monkeypatch): """Mock the mkdir function.""" def mocked_mkdir(path, mode=0o755): return True monkeypatch.setattr("charms.layer.git_deploy.os.mkdir", mocked_mkdir)
e4e78ece1b8e60719fe11eb6808f0f2b99a933c3
17,143
def saferepr(obj, maxsize=240): """return a size-limited safe repr-string for the given object. Failing __repr__ functions of user instances will be represented with a short exception info and 'saferepr' generally takes care to never raise exceptions itself. This function is a wrapper around the Re...
d02f68581867e64a6586548ab627b6893328c42a
17,145
from typing import Callable from re import A def filter(pred : Callable[[A], bool], stream : Stream[A]) -> Stream[A]: """Filter a stream of type `A`. :param pred: A predicate on type `A`. :type pred: `A -> bool` :param stream: A stream of type `A` to be filtered. :type stream: `Stream[A]` :r...
93b3d4c30d4295b2be73200451436c6a4e9ab5cd
17,146
def _get_kernel_size_numel(kernel_size): """Determine number of pixels/voxels. ``kernel_size`` must be an ``N``-tuple.""" if not isinstance(kernel_size, tuple): raise ValueError(f"kernel_size must be a tuple. Got {kernel_size}.") return _get_numel_from_shape(kernel_size)
fb004817950ece275fc10b4824ee83a1d1b9a6a9
17,147
import uuid def random(): """Get a random UUID.""" return str(uuid.uuid4())
411aeb5254775473b43d3ac4153a27a2f15014cb
17,148
def reautorank(reaumur): """ This function converts Reaumur to rankine, with Reaumur as parameter.""" rankine = (reaumur * 2.25) + 491.67 return rankine
aec2299999e9798530272939125cb42476f095c3
17,149
def list_pets(): """Shows list of all pets in db""" pets = Pet.query.all() return render_template('list.html', pets=pets)
60df575932d98ab04e949d6ef6f1fdfa6734ba92
17,150
import glob def get_lif_list(path): """ Returns a list of files ending in *.lif in provided folder :param: path :return: list -- filenames """ path += '/*.lif' return glob.glob(path)
8a26d65fc2c69b1007a40ded82225038ead67783
17,152
def compute_distance_matrix(users, basestations): """Distances between all users and basestations is calculated. Args: users: (obj) list of users! basestations: (obj) list of basestations! Returns: (list of) numpy arrays containing the distance between a user and all basestations ...
07b6175047d7602288436d163f838077e54054fc
17,154
from .core import resolver def __getattr__(name): """Lazy load the global resolver to avoid circular dependencies with plugins.""" if name in _SPECIAL_ATTRS: res = resolver.Resolver() res.load_plugins_from_environment() _set_default_resolver(res) return globals()[name] e...
20dd678be2b9d3f08513912a40098dc8b436ac81
17,155
def img_newt(N, xran=(-3, 3), yran=(-3, 3), tol=1e-5, niter=100): """ Add colors to a matrix according to the fixed point of the given equation. """ sol = [-(np.sqrt(3.0)*1j - 1.0)/2.0, (np.sqrt(3.0)*1j + 1.0)/2.0, -1.0] col_newt = np.zeros((N, N, 3)) Y, X = np.mgrid[yr...
166aa3c5e144972f7ec825f973885f9b528047f0
17,156
def pack_block_header(hdr: block.BlockHeader, abbrev: bool = False, pretty: bool = False, ) -> str: """Pack blockchain to JSON string with b64 for bytes.""" f = get_b2s(abbrev) hdr_ = {'timestamp': f(hdr['timestamp']), 'previous_h...
a6df547918ab82bc990ca915d956730cb6a62b87
17,157
def get_datasets(recipe): """Get dataset instances from the recipe. Parameters ---------- recipe : dict of dict The specifications of the core datasets. Returns ------- datasets : dict of datasets A dictionary of dataset instances, compatible with torch's DataLoader...
f525cf379f13069a1f5255798d963af3389dd5ed
17,158
import re def is_sedol(value): """Checks whether a string is a valid SEDOL identifier. Regex from here: https://en.wikipedia.org/wiki/SEDOL :param value: A string to evaluate. :returns: True if string is in the form of a valid SEDOL identifier.""" return re.match(r'^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}...
207ff94a4df99e7a546440cef1242f9a48435118
17,159
def create_substrate(dim): """ The function to create two-sheets substrate configuration with specified dimensions of each sheet. Arguments: dim: The dimensions accross X, Y axis of the sheet """ # Building sheet configurations of inputs and outputs inputs = create_sheet_space(-1,...
9a47bf213d796aecec4b6f630ae30b04dc035d63
17,160
def remove_artefacts(signal: np.array, low_limit: int = 40, high_limit: int = 210) -> np.array: """ Replace artefacts [ultra-low and ultra-high values] with zero Args: signal: (np.array) 1D signal low_limit: (int) filter values below it high_limit: (int) filter valu...
0b85e929588bd5895a9a84c5d03fce88c4f9f7cb
17,161
def normalizedBGR(im, display=True): """ Generate Opponent color space. O3 is just the intensity """ im = img.norm(im) B, G, R = np.dsplit(im, 3) b = (B - np.mean(B)) / np.std(B) g = (G - np.mean(G)) / np.std(G) r = (R - np.mean(R)) / np.std(R) out = cv2.merge((np.uint8(img.normUnity(b) * 25...
810b4a1ee4d9b5d7f68072c72379fa182b7f34fe
17,162
def feeds(url): """ Tries to find feeds for a given URL. """ url = _full_url(url) data = _get(url) # Check if the url is a feed. if _is_feed(url): return [url] # Try to get feed links from markup. try: feed_links = [link for link in _get_feed_links(data, url) i...
dd16dc751f34fbbf496c9b0142fa5d58372538b2
17,163
def getlog(name): """Create logger object with predefined stream handler & formatting Parameters ---------- name : str module __name__ Returns ------- logging.logger Examples -------- >>> from smseventlog import getlog >>> log = getlog(__name__) """ name = ...
cd5e0dd4589757e3c8d05614f117b7ce46fe4fb9
17,164
import numpy as np def replace_nan(x): """ Replaces NaNs in 1D array with nearest finite value. Usage: y = replace_nan(x) Returns filled array y without altering input array x. Assumes input is numpy array. 3/2015 BWB """ # x2 = np.zeros(len(x)) np.copyto(x2,x) # ...
9100a33dcb7d00b38e7a6a53132db8d13682e499
17,166
def handson_table(request, query_sets, fields): """function to render the scoresheets as part of the template""" return excel.make_response_from_query_sets(query_sets, fields, 'handsontable.html') # content = excel.pe.save_as(source=query_sets, # dest_file_type='handsontable....
93c1471c142917f5b0492ddb27fdd6c278e9976d
17,167
from functools import reduce def is_periodic(G): """ https://stackoverflow.com/questions/54030163/periodic-and-aperiodic-directed-graphs Own function to test, whether a given Graph is aperiodic: """ if not nx.is_strongly_connected(G): print("G is not strongly connected, periodicity not def...
6671a1bf57ef6ec973c7d283cb447d890cbd93e2
17,168
def Sphere(individual): """Sphere test objective function. F(x) = sum_{i=1}^d xi^2 d=1,2,3,... Range: [-100,100] Minima: 0 """ #print(individual) return sum(x**2 for x in individual)
349b732e931fc5acf8a52213d9ddf88335479b90
17,169
def find_names_for_google(df_birth_names): """ :param df_birth_names: 所有的birth data from the data given by Lu :return 1: df_country_found, 返回一个dataframe 里面有国家了 先通过country list过滤,有些国家可能有问题(如有好几个名字的(e.g. 荷兰),有些含有特殊符号,如刚果布,刚果金,朝鲜,南朝鲜北朝鲜是三个“国家”, 再比如说南奥塞梯,一些太平洋岛国归属有问题,还就是香港台湾这样的。。。。暂时算是国家) 而后看看...
6358fd692784389530ebf4c3a2059c3923104d2f
17,170
def make_address_mask(universe, sub=0, net=0, is_simplified=True): """Returns the address bytes for a given universe, subnet and net. Args: universe - Universe to listen sub - Subnet to listen net - Net to listen is_simplified - Whether to use nets and subnet or universe only, see User Guid...
d360dde7ecc4ecc99e32df53f2f0806d5d396f1f
17,171
def get_img_size(src_size, dest_size): """ Возвращает размеры изображения в пропорции с оригиналом исходя из того, как направлено изображение (вертикально или горизонтально) :param src_size: размер оригинала :type src_size: list / tuple :param dest_size: конечные размеры :type dest_size: lis...
133dab529cd528373a1c7c6456a34cf8fd22dac9
17,173
def laxnodeset(v): """\ Return a nodeset with elements from the argument. If the argument is already a nodeset, it self will be returned. Otherwise it will be converted to a nodeset, that can be mutable or immutable depending on what happens to be most effectively implemented.""" if not isinstance(v, Node...
3210f8d1c1d47c8871d0ba82c793b6cd85069566
17,174
def load_config(): """ Loads the configuration file. Returns: - (json) : The configuration file. """ return load_json_file('config.json')
05099118414d371ebc521e498503be1798c39066
17,175
from bs4 import BeautifulSoup def text_from_html(body): """ Gets all raw text from html, removing all tags. :param body: html :return: str """ soup = BeautifulSoup(body, "html.parser") texts = soup.findAll(text=True) visible_texts = filter(tag_visible, texts) return " ".join(t.str...
313a5f404120c17290b726cb00b05e2276a07895
17,178
def alert_history(): """ Alert History: RESTful CRUD controller """ return s3_rest_controller(rheader = s3db.cap_history_rheader)
34a2b6bf90ab0b73eae3b64c83ffebc918e2f1a3
17,179
def chat(): """ Chat room. The user's name and room must be stored in the session. """ if 'avatar' not in session: session['avatar'] = avatars.get_avatar() data = { 'user_name': session.get('user_name', ''), 'avatar': session.get('avatar'), 'room_key': session.get...
d7024960ac8a03082deb696e0c0e6009dfe8e349
17,180
def _get_split_idx(N, blocksize, pad=0): """ Returns a list of indexes dividing an array into blocks of size blocksize with optional padding. Padding takes into account that the resultant block must fit within the original array. Parameters ---------- N : Nonnegative integer Total ...
21935190de4c42fa5d7854f6608387dd2f004fbc
17,181
def buydown_loan(amount, nrate, grace=0, dispoints=0, orgpoints=0, prepmt=None): """ In this loan, the periodic payments are recalculated when there are changes in the value of the interest rate. Args: amount (float): Loan amount. nrate (float, pandas.Series): nominal interest rate per ...
46eb6bbaaa940b5cf1abd702ee5d9e2e20c6dab3
17,182
from typing import Optional def ffill(array: np.ndarray, value: Optional[int] = 0) -> np.ndarray: """Forward fills an array. Args: array: 1-D or 2-D array. value: Value to be filled. Default is 0. Returns: ndarray: Forward-filled array. Examples: >>> x = np.array([0,...
f5774c3e50ddbf2ffa9cf84df5cb57b135d1549a
17,183
def svn_stringbuf_from_file(*args): """svn_stringbuf_from_file(char const * filename, apr_pool_t pool) -> svn_error_t""" return _core.svn_stringbuf_from_file(*args)
b375a43bf8e050aa5191f387d930077680e9b019
17,184
def poly4(x, b, b0): """ Defines a function with polynom 4 to fit the curve Parameters ---------- x: numpy.ndarray: x of f(x) b: float Parameter to fit b0 : int y-intercept of the curve Returns ------- f : numpy.ndarray Result of f(x) """ ...
aed3603640400488219f2cca82e57268f32de000
17,185
from teospy.tests.tester import Tester def chkiapws06table6(printresult=True,chktol=_CHKTOL): """Check accuracy against IAPWS 2006 table 6. Evaluate the functions in this module and compare to reference values of thermodynamic properties (e.g. heat capacity, lapse rate) in IAPWS 2006, table 6. ...
c0fce67d3a268ec0b67ff845f5671c67aa394846
17,186
def flat(arr): """ Finds flat things (could be zeros) ___________________________ """ arr = np.array(arr) if arr.size == 0: return False mean = np.repeat(np.mean(arr), arr.size) nonzero_residuals = np.nonzero(arr - mean)[0] return nonzero_residuals.size < arr.size/100
ce2697d95165b46cec477265df6ccb337cb89af1
17,187
def sensitive_fields(*paths, **typed_paths): """ paths must be a path like "password" or "vmInfo.password" """ def ret(old_init): def __init__(self, *args, **kwargs): if paths: ps = ["obj['" + p.replace(".", "']['") + "']" for p in paths] setattr(s...
e174519c253d4676ae7c07c1b11eb18e532d5f61
17,188
from datetime import datetime import time def get_timestamp_diff(diff): """获取前后diff天对应的时间戳(毫秒)""" tmp_str = (datetime.today() + timedelta(diff)).strftime("%Y-%m-%d %H:%M:%S") tmp_array = time.strptime(tmp_str, "%Y-%m-%d %H:%M:%S") return int(time.mktime(tmp_array)) * 1000
61ca093471103376ee44d940552db6337a4e65f5
17,189
def can_delete(account, bike): """ Check if an account can delete a bike. Account must be a team member and bike not borrowed in the future. """ return (team_control.is_member(account, bike.team) and not has_future_borrows(bike))
f962e465b6a5eb62feea2683cdd8328b5591fb43
17,190
def get_node_types(nodes, return_shape_type = True): """ Get the maya node types for the nodes supplied. Returns: dict: dict[node_type_name] node dict of matching nodes """ found_type = {} for node in nodes: node_type = cmds.nodeType(node) if node_...
7867f97f7228ac77ae44fda04672a8224aa7c1f4
17,192
import csv from typing import OrderedDict def updateDistances(fileName): """ Calculate and update the distance on the given CSV file. Parameters ---------- fileName: str Path and name of the CSV file to process. Returns ------- ret: bool Response indicating if the upd...
c19e0adcf731f9fd1af87f5dfe3a61889d395457
17,193
def hr(*args, **kwargs): """ The HTML <hr> element represents a thematic break between paragraph-level elements (for example, a change of scene in a story, or a shift of topic with a section). In previous versions of HTML, it represented a horizontal rule. It may still be displayed as a horizont...
959106dc2c71334b5a88045f8a26a9f42a2d2fdb
17,194
def as_linker_option(p): """Return as an ld library path argument""" if p: return '-Wl,' + p return ''
452c06034be5c3c2525eb2bfad011e468daef02b
17,195
def split_backbone(options): """ Split backbone fasta file into chunks. Returns dictionary of backbone -> id. """ backbone_to_id = {} id_counter = 0 # Write all backbone files to their own fasta file. pf = ParseFasta(options.backbone_filename) tuple = pf.getRecord() while tup...
6446e90a1aa2e38ca01ebb8a86b8cd1dbd3abd75
17,196
import pkg_resources def _get_highest_tag(tags): """Find the highest tag from a list. Pass in a list of tag strings and this will return the highest (latest) as sorted by the pkg_resources version parser. """ return max(tags, key=pkg_resources.parse_version)
8d2580f6f6fbb54108ee14d6d4834d376a65c501
17,197
def add_comment(request, pk): """ Adds comment to the image - POST. Checks the user and assigns it to the comment.posted_by """ form = PhotoCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.save() else:...
4488a183ca7786c65d355991cec38fed01864ab1
17,198
import warnings def disable_warnings_temporarily(func): """Helper to disable warnings for specific functions (used mainly during testing of old functions).""" def inner(*args, **kwargs): warnings.filterwarnings("ignore") func(*args, **kwargs) warnings.filterw...
5e19b8f51ca092709a1e1a5d6ff0b2543a41e5e1
17,200
def progress_bar(progress): """ Generates a light bar matrix to display volume / brightness level. :param progress: value between 0..1 """ dots = list(" " * 81) num_dots = ceil(round(progress, 3) * 9) while num_dots > 0: dots[81 - ((num_dots - 1) * 9 + 5)] = "*" num_dots -= ...
88986ecc505cf786e197d8ad55cd70b21fa3aa27
17,201
def get_context_command_parameter_converters(func): """ Parses the given `func`'s parameters. Parameters ---------- func : `async-callable` The function used by a ``SlasherApplicationCommand``. Returns ------- func : `async-callable` The converted function. ...
294706230f95745dbd50681cafc066a5d226880d
17,202
def norm(x): """Normalize 1D tensor to unit norm""" mu = x.mean() std = x.std() y = (x - mu)/std return y
ea8546da2ea478edb0727614323bba69f6af288d
17,203
def honest_propose(validator, known_items): """ Returns an honest `SignedBeaconBlock` as soon as the slot where the validator is supposed to propose starts. Checks whether a block was proposed for the same slot to avoid slashing. Args: validator: Validator known_items (Dict): Kn...
c6b0403b15154e3e3b19547770a162e2ac05501b
17,204
import re def formatKwargsKey(key): """ 'fooBar_baz' -> 'foo-bar-baz' """ key = re.sub(r'_', '-', key) return key
24c79b37fdd1cd6d73ab41b0d2234b1ed2ffb448
17,205
import dateutil def mktimestamp(dt): """ Prepares a datetime for sending to HipChat. """ if dt.tzinfo is None: dt = dt.replace(tzinfo=dateutil.tz.tzutc()) return dt.isoformat(), dt.tzinfo.tzname(dt)
2f444d0ea27a3afbed68742bade8833a49e191e4
17,206
def build_accuracy(logits, labels, name_scope='accuracy'): """ Builds a graph node to compute accuracy given 'logits' a probability distribution over the output and 'labels' a one-hot vector. """ with tf.name_scope(name_scope): correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(la...
53f5f78a8c07c691e20d14c416c1fe21a2547bc6
17,208
def compute_mp_av(mp, index, m, df, k): """ Given a matrix profile, a matrix profile index, the window size and the DataFrame that contains the timeseries. Create a matrix profile object and add the corrected matrix profile after applying the complexity av. Uses an extended version of the apply_av funct...
cc89d34dd145339c99d1ded8ced9af853c061124
17,210