content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def piano_roll_to_midi(piece): """ piece is a an array of shape (T, 4) for some T. The (i,j)th entry of the array is the midi pitch of the jth voice at time i. It's an integer in range(128). outputs a mido object mid that you can convert to a midi file by called its .save() method """ piece = np.concatenate...
740174c67319e0bb0f8dca581cb4d301eed331cf
69,010
def choose_coords(): """ Choose a random latitude and longitude within certain ranges. Returns: tuple(float, float) """ for i in range(10): lat, lon = random_coords() if is_land(lat, lon, ZOOM): logger.info( f"Took {i + 1} attempt(s) to find land ({round(l...
c1878dd3c3fc67ccfa363e2ef6d81483fc80befa
69,011
def get_id_or_about(element): """Return the ID or the about associated with an element""" return element.attrib.get(nselem('rdf', 'ID')) or \ element.attrib.get(nselem('rdf', 'about'))
8f2ac9cdbd22b8f03982baccda781d6a782a8d4a
69,012
def custom_jwt_validation(token, leeway=0, exclude=None): """ perform custom jwt validation leeway number of seconds of skew that is allowed exclude is a list of claims to exclude from validation. jose jwt defaults to: defaults = { 'verify_signature': True, ...
353f12bf5e73765f65b247afa1b63f217ad63163
69,014
def fluidsynth(sequence, sample_rate, sf2_path=None): """Synthesizes audio from a music_pb2.NoteSequence using FluidSynth. This uses the pretty_midi `fluidsynth` method. In order to use this synth, you must have FluidSynth and pyFluidSynth installed. Args: sequence: A music_pb2.NoteSequence to synthesize....
8ed386fa76e2ba3387fdfaea4e9c370b2a9c9886
69,015
def parse(place_id): """ Accepts a place_id and returns the data expected by our target forms """ place_name = place_id[3:].upper() place_id = LOOKUP_BY_NAME[place_name] return { 'name': place_name, 'id': place_id, }
6d251a8e26c8cdd8c499d341f76d38fa7de793b0
69,016
def get_query_list(): """ Form a query list for all the queries above """ query_list = [] for index in range(1, 11): eval("query_list.append(query_" + str(index) + ")") # end for return query_list pass
ee0d19d8dc04bb8b7b48c0a3dcf35689a5adba23
69,017
def _call_sampler(sample_n_fn, sample_shape, name=None): """Reshapes vector of samples.""" with tf.name_scope(name, "call_sampler", values=[sample_shape]): sample_shape = tf.convert_to_tensor( sample_shape, dtype=tf.int32, name="sample_shape") # Ensure sample_shape is a vector (vs just a scalar). ...
0ae9e0c2b5e4193335e7bd4567db88a609c194d2
69,018
def getS3bands( in_file, coords, band_names, errorfile, s3_instrument, slstr_res ): """Extract data from Sentinel-3 bands. Read the input S3 file and extract data from a list of given bands for the coordinates (in a provided list) located within the scene. Args: in_file (str): Path to a S3...
96a7ccdedb805be03e5e9ebd8bc0373f3e6bb2f2
69,019
def Radius(cosx, cosy, cosz, psi0, r, q, qp1by2om2): """ >>>Radius(-1., 0., 0., 5454., 0.14, 56., 57./2) """ logger.log(9, "start") code = """ double x, y, z, rc2, rc, rx, rx3, psi, dpsi, dpsidx, dpsidy, dpsidz, dpsidr, dr; #line 100 //std::cout << sizeof(r) << std::endl; #line 110 ...
008d667c6224ce9f57964c31f677e3a72b2118dc
69,020
import re def get_volname_from_vmdk_path(vmdk_path): """Returns the volume name from a full vmdk path. """ match = re.search(DATASTORE_PATH_REGEXP, vmdk_path) _, path = match.groups() vmdk = path.split("/")[-1] return strip_vmdk_extension(vmdk)
5c11f9855309f6e07a4a05df5a1e8742f17425c6
69,021
def convert_constraints_to_rosmsg(constraints, header): """Convert COMPAS FAB constraints into ROS Messages.""" if not constraints: return None ros_constraints = Constraints() for c in constraints: if c.type == c.JOINT: ros_constraints.joint_constraints.append( ...
c713679eadcf8535524e798a7067ba8dbe2fb010
69,022
def defined(interp, name): """ Checks whether a given named constant exists""" return interp.space.newbool(_lookup_constant(interp, name) is not None)
83e256f4aa10f503c75f3bdbdfa37e57bac738e9
69,023
def line( df, x=None, y="value", order=None, legend=None, title=True, color=None, marker=None, linestyle=None, fill_between=None, final_ranges=None, rm_legend_label=[], ax=None, cmap=None, **kwargs, ): """Plot data as lines with or without markers. Pa...
3ef4e7e561757dfd4eb4f9702192c11bb10ae94e
69,025
def _load_fit_file(fname): """ Returns values as `name: list of values` pairs and dict of `name: unit name` for the FIT file with the given filename. Parameters ---------- fname : str Fully resolved filename of the FIT file to load. Returns ------- values : dict Dic...
bbe9f525568cbf44c9e6590c577647a2c723836e
69,027
def poissonModel(gamma, mesh=None, nx=36, ny=36, width=1): """ `gamma` is scaling parameter for left boundary condition `n_x` and `n_y` are the number of elements for the horizontal/vertical axes of the mesh """ # Create mesh and define function space if mesh is None: mesh = fin.RectangleMesh(fi...
a1679d72733edfcb6f5298c83d79b9aceadaa787
69,028
def cross_corr(image_1, image_2, hybridizer=0, normal=True): """ Normalized Correlation, allowing for hybridization with cross correlation being the default output if no hybridization parameter is given Parameters ---------- image_1: ndarray First image image_2: ndarra...
782791186165bc222722c9cbd7d21a788f258d3d
69,029
def calc_image_entropy_HLS(image): """ :param image: :return: """ image_HLS = cv2.cvtColor(image, cv2.COLOR_BGR2HLS) size = image_HLS.shape result = [] for i in range(size[len(size) - 1]): hist = cv2.calcHist([image_HLS], [i], None, [256], [0, 256]) hist = hist[hist > 0] ...
54a81e768b825bf8250345104881a7322acad6a6
69,030
def batch_check_user_perm(dataset_list, object_type, request, action_type="query_data"): """批量校验用户与对象权限""" username = request.user.username object_type = "{}.{}".format(object_type, action_type) permissions_list = [ {"user_id": username, "action_id": object_type, "object_id": each_dataset} for e...
2a6c86321eaeec3695fa3a756c31a8361f0ee368
69,031
from typing import List from typing import Tuple def get_ops_and_inputs_by_name_or_regex( var_names: List[str], graph: tf_compat.Graph = None, ) -> List[Tuple[tf_compat.Operation, tf_compat.Tensor]]: """ Get tuples of operations and the inputs for inputs of operations that match a regex pattern in...
912083e1625299ce90d9b3801cc44cf7ebc2e312
69,032
def random_binomial() -> float: """ Creates a random number between -1 and 1 where the numbers close to 0 are more likely to appear Returns: rand_num: random number between -1 and 1 """ rand_num = np.random.rand() - np.random.rand() return rand_num
b5491cc6ac931940bd9eb84ff4c3a17bb2c6efba
69,033
def image_upload_view(request): """Process images uploaded by users""" if request.method == "POST": form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # Get the current instance object to display in the template img_obj = form.instan...
aad28e1cca467eed830cb3fe399c6c74ff2dea7b
69,034
import requests import random from bs4 import BeautifulSoup import time def cms_detct(url, proxy_list): """ This method detect the cms of the url :param url: the pre-process url, a String. example: www.shore-lines.co.uk :return: A string, One of the following: "Magento", "WordPress", "PrestaShop" ...
11d267621b449c201cf368d0aac7ff26b67cd7d6
69,035
def get_iteration_syslist(system_node_list, system_name_list): """ Takes a list of system nodes and system names and returns. 1. List of system names with iter=yes 2. List of system nodes with iter=yes """ iteration_sysnamelist = [] iteration_sysnodelist = [] for i in range(0, len(s...
9745e52151224aa84c5310592d49db3a980045e9
69,036
def _icrsFromAppGeo(ra, dec, epoch=2000.0, mjd=None): """ Convert the apparent geocentric position in (RA, Dec) to the mean position in the International Celestial Reference System (ICRS) This method undoes the effects of precession, annual aberration, and nutation. It is meant for mapping poi...
b87b0c13864d51fdef8a6dcdeeeae656d26c0d40
69,037
def check_age(observation): """ Validates that observation contains valid age value Returns: - assertion value: True if age is valid, False otherwise - error message: empty if age is valid, False otherwise """ age = observation.get("SubjectAge") if...
4705cf9c2dca40a67c1944a12e832d503dcf7f92
69,038
def getseason_pm5(dat, ystart, yend, season): """ Pick out seasons +/- 5 days """ dpm = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] mondaystr = dat.indexes['time'].strftime('%Y-%m-%d') nyears = yend - ystart + 1 if (season == 'DJF'): ndays = dpm[11]+dpm[0]+dpm[1]+10 indices...
555572cf5e052823cde17417e8a92cd3043bd11a
69,039
import logging def kurtosis(channelLabel, coefs, logger): """ """ logger = logging.getLogger(__name__) coefsNoise = [] for coef in coefs: numCoef = coef.shape[-1] std = np.std(coef) mean = np.mean(coef) kurt = np.sum((coef - mean)**4) / (numCoef * std**4) - 3 t...
0818657c79bfa1fa8caf5975d68cba17fad74cf5
69,040
def open4csv(fname, mode): """ Open filename `fname` for CSV IO in read or write `mode` Parameters ---------- fname : str filename to open mode : {'r', 'w'} Mode to open file. Don't specify binary or text modes; we need to chose these according to python version. Retur...
0dd7628458fdb56351c690d6ac7de20e175b7fa5
69,041
def h1(*text, **kwargs): """Return a header 1""" return tydoc().h1(*text, **kwargs)
7ee90c0fe832c8ca9e0d0285d7e5cad4b28cf3f5
69,043
def _has_initializers_setter(value, owning_component=None, context=None): """ Assign has_initializers status to Component and any of its owners up the hierarchy. """ if value: # only update owner's attribute if setting to True, because there may be # other children that have initializers...
3dbbcf441016a3b7f4c75b946cb5683ad732b45f
69,044
def _initialize_referenced(model_class, attribute): """ Adds a property to the target of a reference field that returns the list of associated objects. """ # this should be a descriptor def _related_objects(self): return (model_class.objects .filter(**{attribute.attname: ...
d30c6b929bff136b8175ddf82da645bafa0537b0
69,045
import hashlib def sha1(data): """ Return the sha1 of "data". Arguments: data (bytes): Data. Returns: str: Hex encoded. """ return _checksum(hashlib.sha1, data)
88a5373cc20f26e93557160d305ba170357cc059
69,046
def utc_to_server(dt): """Convert the given UTC datetime to the server's TZ.""" server_tz = get_timezone(config.DEFAULT_TIMEZONE) return dt.astimezone(server_tz)
867572d80ee9759d56454b92f4e82859ab0fedc6
69,047
def nearst_planck(dt: float, dx: float, rho: np.ndarray, phi: np.ndarray, coefs: Params) -> np.ndarray: """ solve the Nearst-Planck equation one step """ q = np.copy(rho) for idx in range(1, len(rho)-1): dif = (rho[idx+1] + rho[idx-1] - 2 * rho[idx]) * dt / dx**2 adv = coefs.beta * 0.25 * (p...
2c35581112e7d023dfadcf7130265b9ae54b21a2
69,049
import json async def beacon_post_region(request): """Find datasets using POST endpoint.""" db_pool = request.app['pool'] method, processed_request = await parse_request_object(request) LOG.info(f"This is the {method} processed request: {processed_request}") if not processed_request.get("end"): ...
35d41c84ae2fdccf665667400afd3c4699817dc0
69,050
def getInt(node, prop): """Get an int property.""" propertyName = '{node}.{prop}'.format(node=node, prop=prop) return rv.commands.getIntProperty(propertyName, 0, 1)[0]
83f452905e8c2d5e216e4677cf44de923727ff39
69,052
def _promote_vec(v): """Promote vectors to their quaternion representation.""" return np.concatenate((np.zeros(v.shape[:-1] + (1,)), v), axis=-1)
6f5950d3e9da070c88e17305903a2d05558a44c1
69,053
def get_pg_data(cursor, table): """Return data from table in postgresql database.""" col_str = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE " col_str += "TABLE_NAME = '" + table + "';" cursor.execute(col_str) col_names = pd.DataFrame(cursor.fetchall()) sql_str = "SELECT * FROM " + ...
ad47316059659f97617e8a2e78772cfeda27164e
69,054
def expected_value(beta, B): """Return the (symbolic) expected value of the phase-type distribution. Args: beta (SymPy dx1-matrix): initial distribution vector B (SymPy dxd-matrix): transition rate matrix Returns: SymPy expression: expected value of PH(:math:`\\bet...
c4bc6d7e302aa62674b92e21a45834e05646ec97
69,055
from typing import Any def is_dynamo_value(value: Any) -> bool: """Returns True if the value is a Dynamo-formatted value""" if not isinstance(value, dict) or len(value) != 1: return False subkey = next(iter(value.keys())) return subkey in TYPES_REV
e3d29ace6666c59d36a307755a48d7bb5b21513a
69,056
def move_by_month(month, offset): """Get the month with given offset raletive to current month.""" return (((month - 1) + offset) % 12) + 1
38229d5a45b4643dfeb64e0e311949b9e26625ef
69,057
def last(element): """ A wrapper around element[-1]. params: element: an element that implements __getitem__ """ return element[-1]
b299c503a00c45463c4db2e0f0f9afba0cfd2727
69,058
def is_image_file(filename): """Checks if a file is an image. Arguments: filename {str} -- File path. Returns: bool -- True if the path is PNG or JPG image. """ return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg"])
d2971a57cd4fda456384f1e2f839dc32b3c897a6
69,059
def c_ctrl_rr(c_ctrl_params): """DASSH RoddedRegion object for conceptual control asm""" flowrate = 1.0 rr = make_rodded_region_fixture('ctrl_rr', c_ctrl_params[0], c_ctrl_params[1], flowrate) return activate_rodded_region(rr, 623.15)
f06dcc94646124678cee851cd05e9d67fb4620e2
69,060
def cu2ho(cu): """ Cubochoric vector to homochoric vector. References ---------- D. Roşca et al., Modelling and Simulation in Materials Science and Engineering 22:075013, 2014 https://doi.org/10.1088/0965-0393/22/7/075013 """ with np.errstate(invalid='ignore',divide='ignore'): ...
00511889e5bc0838dd425d8d9b1b6477021e941c
69,061
def delete_singleton_axis( mv, vid=None ): """If mv depends on an axis with just one value, create a copy of mv without that axis, and without the corresponding data dimension. Normally this happens when time has been averaged out, but there is still a one-valued time axis left (thus one would normally use...
8d9d180578e5e2aa9db8f2746b1bf1a8697f5210
69,062
import json def process_car_control_msg(message): """Process the car control msg. Args: message (str): The message to process for car control. Raises: GenericNonFatalException: If processing message has some problem, it's not fatal and we ignore it and c...
67609a1b5714600c2e820e3638d57b705136dfce
69,064
def solve_0dfd9992(x): """ Main function to solve the task. Explanation same as in description I/P : Problem grid (2D Numpy array) O/P : Solved grid with required values """ # Creating a copy of input grid to work on it sol = x.copy() # Creating a transpose grid to work on colum...
3b02fc394bc8f4a93dca4a1404343809a1e2a3e6
69,065
async def area_list( db=Depends(get_db), name:str = None, ): """ Get all areas """ areas = await search_area(db,name) return areas
6a78d95e03176a301df04cf0bb64e18fe4a2afec
69,066
def make_00a8(pc): """キャラクターマップ通知""" return pack_int(pc.map_id)
e0d8fa6974cdd96f2e30e110b16829ce81f491c0
69,067
def lmAssociation(X, localLandmarks): """ Return two lists of new and re-observed landmarks. Landmarks are associated using a nearest-neighbor approach. localLandmarks is the list of landmarks observed. X is a StateMatrix object. """ newLandmarkds, reobservedLandmark = [], [] count = 0 ...
e0dbcc6634d98d2dc4d27cb34380944f8875e9ec
69,068
def get_bucket_credentials(bucket_id): """Get S3 credentials for bucket id.""" if bucket_id not in settings.S3_BUCKETS: raise MarketAccessException(f'Bucket "{bucket_id}" not configured.') return settings.S3_BUCKETS[bucket_id]
8b469e9aea1719ccee7c3d7e1379b222cec06c8b
69,070
def get_comment_history(comment): """ This method creates a dictionary of an edit history for a comment or comment reply """ edit_history_list = [] history = comment.edit_history.all() now = timezone.now() current_time = now.strftime("%d-%m-%y %H:%M:%S") for edit in list(history): ...
74382e2cca7d01d313d5700ae09e827696adc38b
69,072
def BER(original_img_bin,decoded_img_bin): """ Computes Bit-Error-Rate (BER) by comparing 2 binary images. The ratio of bit errors over total number of bits is returned. """ if not original_img_bin.shape == decoded_img_bin.shape: raise ValueError('Original and decoded images\' sha...
51b962fdab63d0a087229b4f0f4dfdd0e94412de
69,074
from typing import List def snake_case(word: str) -> str: """Converts given word to snake case. >>> snake_case("someWord") "some_word" """ underscore = "_" no_underscore_words = word.split(underscore) no_underscore_cases: List[str] = [] for w in no_underscore_words: cases = f...
138d9f48f3902c48cc09c281233ab937f8d3e29d
69,075
import codecs def split_dictionary(train_path, valid_path=None, test_path=None): """Split source dictionary to train, validation and test sets. """ with codecs.open(train_path, "r", "utf-8") as f: source_dic = f.readlines() train_dic, valid_dic, test_dic = [], [], [] if valid_path: with codecs.open(...
8a21e2695e6ebb29f71b10d199a237494491e0e3
69,076
def similarity_mapper(pair): """ this method receives a pair that the key is User X, and the users who follow user X. (X, [Y1, .....Yn, -F1, ..., -Fi]) where Fi is a list of direct relation to the user X. This method calculates all pairs (Yi, Yj) and (Yj, Yi) where i ∈ [1, k], j ∈ [1, k] and i != j, and...
aea4a6363f6537a43928822e575f4ff8cce79904
69,077
from typing import Optional from datetime import datetime def run_information(point_in_time: Optional[datetime]=None): """Return information about current run. There is also the run that covers point_in_time. """ _verify_instance() recorder_runs = get_model('RecorderRuns') if point_in_time i...
5c6b9dbee7af36a328d264633a915c636b94124b
69,078
def show_open_dialog(directory=HOME): """Show the user a dialog asking for a file to open. :param directory: The initial directory displayed in the dialog. :type directory: pathlib.Path or str :return: The filename of the user-selected file, or None if the dialog was cancelled. """ return _plat...
929d5518f6f59891ed9001c1a428d6f62bbe39ef
69,079
import itertools def _some2(predicate, iterable): """Alternative implementation of :func:`some`.""" result = False for _ in itertools.dropwhile(complement(predicate), iterable): result = True return result
a4441f723fd58c40325bbc9334bf95f441e63b7e
69,080
import math def asin(x): """ x est un nombre ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Retourne un angle en radians dont le sinus vaut x. """ return math.asin(x)
b980a538fbf51679bff8d08a84cd9cdb1a486153
69,081
def latent_heat_of_vaporization(temp): """ Calculate the latent heat of vaporization. Parameters ---------- temp : numeric Air temperature (K). Returns ------- lat_heat_vap : numeric Latent heat of vaporization (J kg-1). """ return c.LATENT_HEAT_OF_VAPORIZATION ...
1f877a1747875a2ec72557d300b1687985a6d788
69,082
def check_imdb_dataset(method): """A wrapper that wraps a parameter checker around the original IMDBDataset.""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shard...
4c9cadf092ef88ffed25da4049b99073013e1349
69,083
from typing import Union from typing import Iterable from typing import Dict from typing import Any def tensors_batch_size(tensors: Union[Tensor, Iterable[Tensor], Dict[Any, Tensor]]): """ Default function for getting the batch size from a tensor or collection of tensors. Returns the batch size (zeroth in...
76f430f49002968b10536e437c813c0adffde427
69,084
def get_image_file(uuid, image_file_path): """GetImageFile (GET /images/:uuid/file) Return the image file. """ encoded_md5 = get_image_file_md5(uuid, image_file_path) if NGINX_ENABLED: res = make_response('') res.headers['Content-Type'] = 'application/octet-stream' res.head...
4275e8f503a7f02c0d5e6d6561a71b81e8c0c35c
69,085
def build_character( base_info, background, characteristics, fellow_investigators, hit_points, inventory, luck, magic, sanity, skills, weapons, ): """Builds a character object. Args: base_info (dict): The base character information. background (dict):...
8504ee61d9702eebeb4000d021ab975c0f777033
69,086
def average_arc_weight(graph): """ average_arc_weight(graph) -> average_arc_weight """ weights = [] arcs = graph.get_arcs() for arc in arcs: weights.append(arc.info) return average(weights)
c33ac23a5a6db451ab18d63dec471736359c758f
69,088
def removeUser(name): """Unregisters a user from this computer. Returns true if the user was removed, false if they weren't registered in the first place. The user will lose all access to this computer. When the last user is removed from the user list, the computer becomes accessible to all players.""" retu...
7cc414ed6f7d9e23e4f0993f53366a42c850b5b0
69,089
import scipy import six def istft_noDiv(stft_matrix, hop_length=None, win_length=None, window=None, center=True, dtype=np.float32): """ #Copied from librosa's spectrum.py file, removing division by squared window, which shouldn't be necessary and can cause problems in recon. Inverse sh...
916320e97e71df1f876454c2b43f0ebb1d3bb937
69,090
import click import six def get_client(config): """Construct a new wrapped client based on the specified config file.""" # Passing the config file unconditionally here since if the user hasn't # specified one it'll be None and the config loader will use the default # locations. loader = warthog.ap...
28e6b2039a54b622d5f5dc57398f013a37176306
69,091
from typing import List def build_key_row_0(size: KeyboardSize) -> List[Key]: """ space bar row """ r = [ LeftCtrlKey().set_is_left_hand(), LeftOsKey().set_is_left_hand(), LeftAltKey().set_is_left_hand(), SpaceKey().set_is_left_hand(), RightAltKey().set_is_right...
41e828bc6a5abee604dd78f9d34bde5f11b46f6a
69,092
def ensure_bytes(obj, encoding=None): """ Convert ``obj`` to a byte string, if it isn't one already. The conversion method is as follows: 1. If ``obj`` is a byte string, return it unchanged. 2. If ``obj`` is an unicode string, encode it using ``encoding``. 3. Otherwise, cast ``obj`` to unicode...
4dfff3df2c60d10e6cfce79004a54b597d3d8040
69,093
def eval_acc_all(test_fn, all_examples): """ Evaluate accuracy n_exampleson `all_examples`. """ acc = 0 n_examples = 0 prediction = [] for x1, mask1, x2, mask2, x3, mask3, x4, x5, x6, x7, x8, x9, x10, y in all_examples: # print(x1.shape) # print(x2.shape) # print(...
ec166338d70d5f06cb5999cbf63da8485fd48b9d
69,095
def bound_length(input_paths, tokenizers, shortest, longest): """ Return an np.array which flags whether all parallel segments comply with length constraints and count the number of tokens in each stream (considering valid sequences only). :param input_paths: paths (list/tuple) to each part of the para...
1af2e94f276e62c81c14e94309ce6b74b0cf8790
69,096
def validate_payload(validator: dict, params: dict, required: list = None) -> bool: """ Validates parameters and body payloads sent to the API """ # Repurposed with permission from https://github.com/yaleman/crowdstrike_api # __ # ...
fb3d09b0711df2cc77a54f014af614c853b2df8b
69,097
def getClass( typeName ): """returns the class of a concrete uno exception, struct or interface """ return pyuno.getClass(typeName)
cf7d704bcbcc9d80a192f77ddee9d82528f0826b
69,098
def sharpe_ratio(r, rf_rate, periods_per_year): """ Computes annualized sharpe ratio of a set of returns """ rf_per_period = (1 + rf_rate) ** (1 / periods_per_year) - 1 excess_return = r - rf_per_period ann_excess_return = annualize_ret(excess_return, periods_per_year) ann_vol = annualize_vo...
59fd6f6ca1b76fcd35380ec2005272777f5b85a9
69,100
def NetInvIncTax(e00300, e00600, e02000, e26270, c01000, c00100, NIIT_thd, MARS, NIIT_PT_taxed, NIIT_rt, niit): """ Computes Net Investment Income Tax (NIIT) amount assuming that all annuity income is excluded from net investment income. """ modAGI = c00100 # no foreign earned inco...
992946090d5894042f2e0909a325ea3225c8a49f
69,101
def merge_dicts(*dict_args): """ Efficiently merges arbitrary number of dicts, giving precedence to latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
9170784049bc1b70e07672301bed020f584a4a4b
69,102
def make_pi_dict(**kwargs): """ Make a dict of pi components suitable for passing to Surface. """ return { i: np.array([kwargs.get(i, 0.)]) for i in ['xx', 'yy', 'xy', 'xz', 'yz'] }
c6c2df7c758f14eb415d8fefe38ebaca6847aac8
69,103
import numpy def get_COMs_celllist(cell, M): """ Calculate Center of Mass (COM) for celllist """ Mx = M[0] My = M[1] Mz = M[2] Lx = numpy.linalg.norm(cell[0, :]) Ly = numpy.linalg.norm(cell[1, :]) Lz = numpy.linalg.norm(cell[2, :]) NEW_P = [] vec_x = cell[:][0, :].copy() n_x = ...
329a4ef25951aea6b38fee9dc0dafb19200621a4
69,105
def lowest_cost_search(start, successors, is_goal, action_cost): """Return the lowest cost path, starting from start state, and considering successors(state) => {state:action,...}, that ends in a state for which is_goal(state) is true, where the cost of a path is the sum of action costs, which are g...
13ca96b3563660b7645023a0bf3be601ddd575a8
69,106
def provider_amazon_de(section): """Provider for Amazon """ try: amazon = AmazonAPI(section['amazon_access_key'], section['amazon_secret_key'], section['amazon_assoc_tag'], region="DE") product = amazon.lookup(ItemId=section['asin']) return product.price_and_currency[0] except: return None
d9a0201f17cf925ce717038cb060f3859e7ab9ea
69,107
def get_dynamic_projection_info_delay(): """Get information about the current dynamic projection data. """ descriptor = [ {'name':'N_time_bins', 'type':'uint', 'value':None }, {'name':'N_counts', 'type':'long', 'value':None }, ...
c072fe29671ddd7333735965fd2c23c7b4cc09fa
69,108
def get_supported_technologies(): """Runs 'kallisto bus --list' to fetch a list of supported technologies. :return: list of technologies :rtype: list """ p = run_executable([get_kallisto_binary_path(), 'bus', '--list'], quiet=True, returncode=1) ret...
e35427a14f3b1d509bc6abf9a55848c1fbfbfb4b
69,109
def get_bprop_assign_add(self): """Grad definition for `AssignAdd` operation.""" def bprop(x, y, out, dout): return zeros_like(x), zeros_like(y) return bprop
7d1878e9d0a72883316a1bb51c57775977a90fad
69,110
def break_up_sink_info(sink_info:str) -> dict: """Break up the info into a dictionary. Parameters ---------- sink_info: str The sink info from pulsemixer. Returns ------- dict A dictionary of sink information. """ pieces = sink_info.split(",") if "\t" in pieces[...
790c757500528af28a6a01bc0cea2b7772d2ea55
69,111
def project_content_url(project, **kwargs): """ Get the URL for a file path within a project. This can significantly reduce the number of queries instead of fetching the project and account for every file in a list which happens when using `{{ file.download_url }}`. """ return project.conte...
91a6a927b3fa88f4b9e976093965a1176657532e
69,113
def mavlink_latlon(degrees): """Converts a MAVLink packet lat/lon degree format to decimal degrees.""" return float(degrees) / 1e7
20d883e45f99cca3c99eeb9d7c5fae96db03fd5a
69,114
def get_pym_string_single(source): """get_pym_string_single(source) -> python_code_string Translate MATLAB single statement string into a functionally equivalent Python compatible statement that relies on features of OMPClib's mobject. This string can be further passed to Python's built-in compile...
4670fac6f0b58f833c559c9b25965297dc59cba0
69,116
def getQLClothInMesh(target): """ Get the input mesh of a Qualoth cloth object. :param target: `PyNode` qualoth cloth object (inmesh, qlClothShape, outmesh) :return: `PyNode` """ clothNode = getQLClothNode(target) if not clothNode: return None qlConverter = clothNode.inputGeometry.conne...
76dfb9a5d6eadcda5d53b31709997d02241998dd
69,117
def decode_token(token): """ Top-level method to decode a JWT. Takes either a compact-encoded JWT with a single signature, or a multi-sig JWT in the JSON-serialized format. Returns the deserialized token, as a dict. The signatures will still be base64-encoded """ if isinstance(token, (u...
1100dbfc970cf394a34ee127b362f3e994d60ba7
69,118
def load_smart_meters(cursor=None, schema: str = "public", name: str = "smart_meters"): """ --------------------------------------------------------------------------- Ingests the smart meters dataset into the Vertica database. This dataset is ideal for time series and regression models. If a table with the same na...
3cdb7f82bd6100cb2c5803bde27ba091c5935e05
69,119
def is_whitespace(c): """ static boolean isWhitespace(int codepoint) """ # try to hit the most common ASCII ones first, then the nonbreaking # spaces that Java brokenly leaves out of isWhitespace. # u202F is the BOM, see # http://www.unicode.org/faq/utf_bom.html#BOM # we just accept it...
f2160386120da49cb42eb0cefd80a65a2345832b
69,121
def vertical(samples, classes): """ Return vertcial array of shape (samples, classes). """ X = np.zeros((samples*classes, 2)) y = np.zeros(samples*classes, dtype='uint8') for class_number in range(classes): ix = range(samples*class_number, samples*(class_number+1)) X[ix] = np.c_[...
be70fecd50b3b866902373040107f3c020d0b4a6
69,122
import itertools def _merge_dicts(first, second): """Merge two dicts into a new one Args: first (dict): Primary dict; if a key is present in both, the value from this dict is used. second (dict): Other dict to merge. Returns: dict: Union of provided dicts, with value fr...
85b3377d25d730b32c9bf925bfde375db5c49450
69,123
def bbox2result(bboxes, labels, num_classes): """Convert detection results to a list of numpy arrays. Args: bboxes (Tensor): shape (n, 5) labels (Tensor): shape (n, ) num_classes (int): class number, including background class Returns: list(ndarray): bbox results of each cl...
cdee80469e8af546e105d7cfb9e1b70267dbe560
69,124
def compare_inputs(in1, in2, shape, hist_len): """ Return a matplotlib image with the inputs as 2 rows of `hist_len` images side-by-side """ images1, images2 = [], [] img_size = np.prod(shape) for i in range(hist_len): images1.append(in1[img_size*i:img_size*(i+1)].reshape(shape)) ...
90dbf8ab603eb26abce8b936ade9d85781876fce
69,125
def create_clidriver(): """ CLIDriver Builder. :rtype: CLIDriver :return: CLIDriver instance. """ return CLIDriver()
d1b51f284be7e4a0617dbdbb592cfbf708124bfc
69,126