content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def euler2rot_symbolic(angle1='ϕ', angle2='θ', angle3='ψ', order='X-Y-Z', ertype='extrinsic'): """returns symbolic expression for the composition of elementary rotation matrices Parameters ---------- angle1 : string or sympy.Symbol angle representing first rotation angle2 : string or sym...
07069fc6c543acb9960f8203130cabcd04a762f4
3,642,963
import ctypes def k4a_playback_get_next_imu_sample(playback_handle, imu_sample): """ K4ARECORD_EXPORT k4a_stream_result_t k4a_playback_get_next_imu_sample(k4a_playback_t playback_handle, k4a_imu_sample_t *imu_sample); """ _k4a_playback_get_next_imu_sample = record_dll.k4a_playback_get_next_imu_sa...
faa127b8788163de209863adee1419c349852827
3,642,964
def knapsack_iterative_numpy(items, maxweight): """ Iterative knapsack method maximize \sum_{i \in T} v_i subject to \sum_{i \in T} w_i \leq W Notes: dpmat is the dynamic programming memoization matrix. dpmat[i, w] is the total value of the items with weight at most W T is ...
7ef8ab10b91e72b7625fdfc9445501c4ae8e5554
3,642,965
import torch def gram_matrix(image: torch.Tensor): """https://pytorch.org/tutorials/ advanced/neural_style_tutorial.html#style-loss""" n, c, h, w = image.shape x = image.view(n * c, w * h) gram_m = torch.mm(x, x.t()).div(n * c * w * h) return gram_m
5912cfec026cba26a77131c3b52a8e751c0f575e
3,642,966
def photos_of_user(request, user_id): """Displaying user's photo gallery and adding new photos to user's gellery view. """ template = 'accounts/profile/photos_gallery.html' user_acc = get_object_or_404(TLAccount, id=user_id) photos = user_acc.photos_of_user.all() # Custom related name con...
3fd3cdfac7f1af4de13c464a3fe2bea26f72e6c2
3,642,967
def sw_update_opts_w_name_db_model_to_dict(sw_update_opts, subcloud_name): """Convert sw update options db model plus subcloud name to dictionary.""" result = {"id": sw_update_opts.id, "name": subcloud_name, "subcloud-id": sw_update_opts.subcloud_id, "storage-apply-type...
c9c1703d9e4d0b69920d3ab06e5bf19fbb622103
3,642,968
def imf_binary_primary(m, imf, binary_fraction=constants.BIN_FRACTION): """ Initial mass function for primary stars of binary systems Integrated between m' and m'' using Newton-Cotes Returns 0 unless m is in (1.5, 16) """ m_inf = max(constants.B_MIN, m) m_sup = min(constants.B_MAX, 2 * m) ...
ae49a298d66a7ee844b252b5e736ea1c1846c31b
3,642,969
import torch def compute_scene_graph_similarity(ade20k_split, threshold=None, recall_funct=compute_recall_johnson_feiefei): """ :param ade20k_split: :param threshold: :param recall_funct: :return: """ model = get_scene_graph_encoder...
061435209baa2c8d03af93ce09d00fcaf02adf8a
3,642,970
import importlib_resources def load_cmudict(): """Loads the CMU Pronouncing Dictionary""" dict_ref = importlib_resources.files("tacotron").joinpath("cmudict-0.7b.txt") with open(dict_ref, encoding="ISO-8859-1") as file: cmudict = (line.strip().split(" ") for line in islice(file, 126, 133905)) ...
76f3ed592cb3709d4f073c42ee7229ac0142b77a
3,642,971
def evalasm(d, text, r0 = 0, defines = defines, address = pad, thumb = False): """Compile and remotely execute an assembly snippet. 32-bit ARM instruction set by default. Saves and restores r2-r12 and lr. Returns (r0, r1). """ if thumb: # In Thumb mode, we still use ARM cod...
c5bf3f5728fc9e85dbfd2540083ae7b2b87cd452
3,642,972
import multiprocessing def _get_thread_count(): """Gets a thread_count based on the multiprocessing.cpu_count().""" try: thread_count = multiprocessing.cpu_count() # cpu_count only gets the physical core count. There doesn't appear to be a # simple way of determining whether a CPU supports simultaneou...
f7c4959734e49a70412d87ebc1f03b811b600600
3,642,973
def weighted_avg(x, weights): # used in lego_reader.py """ x = batch * len * d weights = batch * len """ return weights.unsqueeze(1).bmm(x).squeeze(1)
efa08d9719ccbcc727cb7349888f0a26140521e9
3,642,975
def CYR(df, N=5, M=5): """ 市场强弱 :param df: :param M: :return: """ VOL = df['volume'] AMOUNT = df['amount'] DIVE = 0.01 * EMA(AMOUNT, N) / EMA(VOL, N) CRY = (DIVE / REF(DIVE, 1) - 1) * 100 MACYR = MA(CRY, M) return pd.DataFrame({ 'CRY': CRY, 'MACYR': MACYR })
7d5f31064d8eb3e4aaed8f6694226760a656f4d7
3,642,976
def packCode(code): """Packs the given code by passing it to the compression engine""" if code in packCache: return packCache[code] packed = compressor.compress(parse(code)) packCache[code] = packed return packed
b20714a022e73cbec38819d515c1cb89b8157d8c
3,642,977
def langpack_submission_allowed(user, parsed_addon_data): """Language packs can only be submitted by people with the right permission. See https://github.com/mozilla/addons-server/issues/11788 and https://github.com/mozilla/addons-server/issues/11793 """ return ( not parsed_addon_data.g...
5d26aaff3089a4e4ba6b2325f25d7ad5d759bcd9
3,642,979
import re def process_derived_core_properties(derived_core_properties): """Parse DerivedCoreProperties.txt and returns its version, and set of characters with ID_Start and ID_Continue. """ id_start = set() id_continue = set() m = re.match('# DerivedCoreProperties-([0-9\.]+).txt', derived_core_pro...
cb15993eb84e3d1e7a1f65528f2f677e1e596668
3,642,982
def error_500(error): """Route function for handling 500 error pages """ return flask.templating.render_template("errors/500.html.j2"), 500
8d93367e21e855c672de50901de9793a326867e6
3,642,983
def poormax(X : np.ndarray, feature_axis = 1) -> np.ndarray: """ 对数据进行极差化 \n :param feature_axis: 各特征所在的维度 \n feature_axis = 1 表示每列是不同的特征 \n """ if not feature_axis: X = X.T _min = np.min(X, axis = 0) _max = np.max(X, axis = 0) across = _max - _min X = (X - _min) / across if not feature_axis: X = ...
8d2c45b225d05f36951eb6fac2fc19214b6e3f31
3,642,984
def login_form(request): """ The request must be get """ menu = MenuService.visitor_menu() requestContext = RequestContext(request, {'menu':menu, 'page_title': 'Login'} ) return render_to_response('login.html', requestContext)
596273f8925a4d6aa39584f94262fc0f1d53657d
3,642,985
def tz_from_dd(points): """Get the timezone for a coordinate pair Args: points: (lat, lon) | [(lat, lon),] | pd.DataFrame w/lat and lon as columns Returns: np.array """ if isinstance(points, pd.DataFrame): points = points.values.tolist() if not isinstance(points, list)...
5a6b05f1bf88c3a016cc5beae024a99873715904
3,642,986
def find_touching_pixels(label_img, distance=1, selem=None): """ Returns a mask indicating touching regions. Either provide a diameter for a disk shape distance or a selem mask. :param label_img: a label image with integer labels :param distance: =1: touching pixels, >1 pixels labels distance appart...
a69b2b89be2df9660f1016c008c266de7932bb90
3,642,988
def draw_boxes_on_image(img, boxes, labels_index, labelmap_dict, **kwargs): """Short summary. Parameters ---------- img : ndarray Input image. boxes : ndarray-like It must has shape (n ,4) where n is the number of bounding boxes. labels_index : nd...
1ee1d7b4e04e8646dd4e986e1a7e72d42d3f9685
3,642,989
def guess_locations(location): """Convenience function to guess where other Strongholds are located.""" location = Point(*location) return (location, rotate(location, CLOCKWISE), rotate(location, COUNTERCLOCKWISE))
34c6824d63dbd99e4b09c6bb588298add404d87a
3,642,990
def get_centroid(mol, conformer=-1): """ Returns the centroid of the molecule. Parameters --------- conformer : :class:`int`, optional The id of the conformer to use. Returns ------- :class:`numpy.array` A numpy array holding the position of the centroid. """ cen...
393b5e27a5fa1779f98c2455c88d36027036e5f2
3,642,991
import torch def idct(X, norm=None): """ The inverse to DCT-II, which is a scaled Discrete Cosine Transform, Type III Our definition of idct is that idct(dct(x)) == x For the meaning of the parameter `norm`, see: https://docs.scipy.org/doc/ scipy.fftpack.dct.html :param X: the input signal ...
f0b86dbbe80fe9b2e4b442f55ea67b82f7eaa019
3,642,992
def div25(): """ Returns the divider 44444444444444444444444 :return: divider25 """ return divider25
6bb38e50a6cd7fe80c9aef5dbb2d829c0c5a6fb5
3,642,993
def comp_periodicity(self, wind_mat=None): """Computes the winding matrix (anti-)periodicity Parameters ---------- self : Winding A Winding object wind_mat : ndarray Winding connection matrix Returns ------- per_a: int Number of spatial periods of the winding ...
f1c7074cdc55be6af3c5511a071a1df0835e666e
3,642,994
def _is_valid_target(target, target_name, target_ports, is_pair): """Return True if the specified target is valid, False otherwise.""" if is_pair: return (target[:utils.PORT_ID_LENGTH] in target_ports and target_name == _PAIR_TARGET_NAME) if (target[:utils.PORT_ID_LENGTH] not in targ...
58a7c2ceb7b3206777c01122b0c3ef01a5887b65
3,642,995
def _get_span_name(servicer_context): """Generates a span name based off of the gRPC server rpc_request_info""" method_name = servicer_context._rpc_event.call_details.method[1:] if isinstance(method_name, bytes): method_name = method_name.decode('utf-8') method_name = method_name.replace('/', '....
5527820fa766fe29009e6fe060e76c01a75e3c37
3,642,996
def calculateNDFairnessPara(_ranking, _protected_group, _cut_point, _gf_measure, _normalizer, items_n, proItems_n ): """ Calculate group fairness value of the whole ranking. Calls function 'calculateFairness' in the calculation. :param _ranking: A permutation of N numbers (0..N-1) that repre...
b1c0dfa53d1842f8d93a6ed6d2ae2ddd9ebafd7b
3,642,997
import json import requests def change_server(name: str = None, description: str = None, repo_url: str = None, main_status: int = None, components: dict = None, password: str = None): """Change server according to arguments (using package config). This will automatically change the config so it has the right...
f7a5334da8ef011969c8ffb5c31c1b4f477ed2a5
3,642,999
def tokenize(lines, token='word'): """Split text lines into word or character tokens.""" if token == 'word': return [line.split() for line in lines] elif token == 'char': return [list(line) for line in lines] else: print('ERROR: unknown token type: ' + token)
c30c8b3f1ea5d5752e17bc9fd514acaf097cba18
3,643,000
def gravatar(environ): """ Generate a gravatar link. """ email = environ.get('tank.user_info', {}).get('email', '') return GRAVATAR % md5(email.lower()).hexdigest()
0464d409f4e0c1fef251927930618236146ac3f1
3,643,002
def keyrep(kspec, enc="utf-8"): """ Instantiate a Key given a set of key/word arguments :param kspec: Key specification, arguments to the Key initialization :param enc: The encoding of the strings. If it's JSON which is the default the encoding is utf-8. :return: Key instance """ if en...
25524953376a83562859b33a91ba10ae85c2c25d
3,643,003
import math def aa2matrix(axis, angle, radians=True, random=False): """ Given an axis and an angle, return a 3x3 rotation matrix. Based on: https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle Args: axis: a vector about which to perform a rotation angle: the angle of rotat...
d41460663edd36e5da1255636514468180e20511
3,643,004
def expand_value_range(value_range_expression): """Expand the value range expression. Args: value_range_expression: Value range or expression to expand. Return: iterable. """ if type(value_range_expression) is str: # Grid search if value_range_expression.startswith('...
bddfc2fd4ed65101ecb3d8ca2bc5d11de58374bd
3,643,005
def date_range(df): """Takes the dataframe returns date range. Example here: http://pandas.pydata.org/pandas-docs/stable/timeseries.html Returns as Days """ start_date = df.tail(1)['date'] start = pd.Timestamp.date(list(start_date.to_dict().values())[0]) end_date = df.head(1)['date'...
1b577b29ccc7ed6751e8162f11b076042178c590
3,643,006
from datetime import datetime def last_hit_timestamp(hit_count_rules, month): """ Get list of last hit timestamp to rule :param hit_count_rules: dictionary which contain json response with all hit count rules :param month: number of month elapsed since the rule was ...
048d63e9ad77bf19974b4506aedb66d98fb84403
3,643,007
def url(should_be=None): """Like the default ``url()``, but can be called without arguments, in which case it returns the current url. """ if should_be is None: return get_browser().get_url() else: return twill.commands.url(should_be)
a9faa937ffe994136d16e5c86082f22600368431
3,643,008
def remove_outliers(X_train,y_train): """ This function deletes outliers on the given numpy arrays, and returns clean version of them. Parameters ---------- X_train: dataset to remove outliers with k features y_train: dataset to remove outliers with k f...
35c86ba50ca6398ec70e95c07091bb1ffc6811d2
3,643,009
import tqdm def query_data(regions, filepath_nl, filepath_lc, filepath_pop): """ Query raster layer for each shape in regions. """ shapes = [] csv_data = [] for region in tqdm(regions): geom = shape(region['geometry']) population = get_population(geom, filepath_pop) ...
a4ecd234d04fc1cf677d276afe11c716a1c3b854
3,643,010
from bs4 import BeautifulSoup import re def scrape_urls(html_text, pattern): """Extract URLs from raw html based on regex pattern""" soup = BeautifulSoup(html_text,"html.parser") anchors = soup.find_all("a") urls = [a.get("href") for a in anchors] return [url for url in urls if re.match(pattern, u...
dfba40df7894db91575b51a82d89fef0f824d362
3,643,011
from typing import List def get_num_weight_from_name(model: nn.Module, names: List[str]) -> List[int]: """Get list of number of weights from list of name of modules.""" numels = [] for n in names: module = multi_getattr(model, n) num_weights = module.weight.numel() numels.append(nu...
ae6c3bfb5abe3522ff6d276cde052a5270e5741e
3,643,012
from typing import OrderedDict def _categories_level(keys): """use the Ordered dict to implement a simple ordered set return each level of each category [[key_1_level_1,key_2_level_1],[key_1_level_2,key_2_level_2]] """ res = [] for i in zip(*(keys)): tuplefied = _tuplify(i) res...
35f62244c3d3b893008d7ba7b8a9f651528c198e
3,643,013
def to_usd(my_price): """ Converts a numeric value to usd-formatted string, for printing and display purposes. Param: my_price (int or float) like 4000.444444 Example: to_usd(4000.444444) Returns: $4,000.44 """ return f"${my_price:,.2f}"
a8959cdca7f011a435e35b4a4a5d2d43911a55da
3,643,014
def computeNodeDerivativeHermiteLagrange(cache, coordinates, node1, derivative1, scale1, node2, scale2): """ Computes the derivative at node2 from quadratic Hermite-Lagrange interpolation of node1 value and derivative1 to node2 value. :param cache: Field cache to evaluate in. :param coordinates: Coo...
7eb98502341e94e277b4d7b98b68293ff28f395b
3,643,015
def _step5(state): """ Construct a series of alternating primed and starred zeros as follows. Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote the starred zero in the column of Z0 (if any). Let Z2 denote the primed zero in the row of Z1 (there will always be one). Contin...
4d6e50164724b6fdaa42fa41423677dd80500a3e
3,643,016
def encode_ascii_xml_array(data): """Encode an array-like container of strings as fixed-length 7-bit ASCII with XML-encoding for characters outside of 7-bit ASCII. """ if isinstance(data, np.ndarray) and \ data.dtype.char == STR_DTYPE_CHAR and \ data.dtype.itemsize > 0: return data...
a9baf0ca562b78ce36c49e1d64c8f8a9015df097
3,643,017
from typing import Union from pathlib import Path from typing import Optional from typing import List import queue def download_dataset( period: str, output_dir: Union[Path, str], fewer_threads: bool, datasets_path: Optional[Union[Path, str]] = None ) -> List[Path]: """Download files from the given dataset wi...
0c98956bb54f6f948a31097e47ba6008e91ebefc
3,643,018
def monospaced(fields, context): """ Make text monospaced. In HTML: use tags In Markdown: use backticks In Text: use Unicode characters """ content = fields[0] target = context['target'] if target == 'md': return wrapper('`')([content], context) if target == 'html': ...
eed91b414ce8cb486b115d0d203db4e7ed81e5d5
3,643,019
def indexview(request): """ initial page shows all the domains in columns """ domdb = Domain.objects if not request.user.has_perm('editapp.see_all'): # only see mine domdb = domdb.filter(owner__username=request.user.username) domains = [ d.domain for d in domdb.order_by('domain') ] ...
b99e8b3499f7d7a282b5a93606dddf7527a5e93b
3,643,020
def MC_swap(alloy, N, E, T): """ Randomly selects an atom and one of its neighbours in a matrix and calculates the change in energy if the two atoms were swapped. The following assignment is used to represent the neighbouring directions: 1 = up 2 = right 3 = down 4 = left """ ...
aea84cd605389e480d89e78fcca9806bc68e0c83
3,643,021
def _try_type(value, dtype): """ Examples -------- >>> _try_type("1", int) 1 >>> _try_type(1.0, int) 1 >>> _try_type("ab", float) 'ab' """ try: return dtype(value) except ValueError: return value
4a188e57dfafca96e6cd8a815dbbb162c74df01b
3,643,022
from datetime import datetime def get_all_codes(date=None): """ 获取某个交易日的所有股票代码列表,如果没有指定日期,则从当前日期一直向前找,直到找到有 数据的一天,返回的即是那个交易日的股票代码列表 :param date: 日期 :return: 股票代码列表 """ datetime_obj = datetime.now() if date is None: date = datetime_obj.strftime('%Y-%m-%d') codes = [] ...
b5d861f1991763e8196f1f336faffefc00b58df4
3,643,023
def cluster_config(request_data, op_ctx: ctx.OperationContext): """Request handler for cluster config operation. Required data: cluster_name Optional data and default values: org_name=None, ovdc_name=None (data validation handled in broker) :return: Dict """ _raise_error_if_pks_not_enable...
985e9633d54c0b7ccfc235f6c34bb4d4c5086ebf
3,643,024
from .pyazureutils_errors import PyazureutilsError def iotcentral_cli_handler(args): """ CLI entry point for command: iotcentral """ logger = getLogger(__name__) try: if args.action == "register-device": status = _action_register_device(args) except PyazureutilsError as exc...
e5c78f24c459ff45ab8a88198697eae0a9bb7abe
3,643,026
def kelly_kapowski(s, g, w, its=45, r=0.025, m=1.5, **kwargs): """ Compute cortical thickness using the DiReCT algorithm. Diffeomorphic registration-based cortical thickness based on probabilistic segmentation of an image. This is an optimization algorithm. Arguments --------- s : ANTsim...
809d119d5691e64504671a4915525a109d0ae375
3,643,027
def get_word_count(frame, pattern_list, group_by_name): """ Compute word count and return a dataframe :param frame: :param pattern_list: :param column_name: :return: frame with count or None if pattern_list is empty """ if not pattern_list or len(pattern_list) == 0: return None ...
06a1c82b387bfc2194e3d4ee0a4526e5b4e3f800
3,643,028
def parse(text, from_timezone=None): """ :rtype: TimeeDT """ timee_dt = None if from_timezone: timee_dt = parse_with_maya(text, timezone=from_timezone) return timee_dt else: for parse_method in parsing_methods(): result = parse_method(text) i...
c7a8b7819031ee7f97c54c9903f19d4b24112c4a
3,643,029
import collections def _command_line_objc_copts(objc_fragment): """Returns copts that should be passed to `clang` from the `objc` fragment. Args: objc_fragment: The `objc` configuration fragment. Returns: A list of `clang` copts, each of which is preceded by `-Xcc` so that they can be pa...
8c55d1297b0aa116b9f6dc859cad1dfda1901f00
3,643,030
import logging import urllib def handle_incoming_mail(addr=None): """Handle an incoming email by making a task to examine it. This code checks some basic properties of the incoming message to make sure that it is worth examining. Then it puts all the relevent fields into a dict and makes a new Cloud Task wh...
9bef81cf818d433cc833e64b5291b5c371605424
3,643,031
def split(df, partition, column): """ :param df: The dataframe to split :param partition: The partition to split :param column: The column along which to split : returns: A tuple containing a split of the original partition """ dfp = df[column][partition] if column in ca...
8d87d025695a0a2dde681e1abbbf0f5acccdc914
3,643,032
def get_gaussian_kernel(l=5, sig=1.): """ creates gaussian kernel with side length l and a sigma of sig """ ax = np.linspace(-(l - 1) / 2., (l - 1) / 2., l) xx, yy = np.meshgrid(ax, ax) kernel = np.exp(-0.5 * (np.square(xx) + np.square(yy)) / np.square(sig)) return kernel / np.sum(kernel)
71982928ee89d3ac98ae8d74dcc079dd2c4ca0d8
3,643,033
def get_data_tbl(path, tblname): """Wrapper function around @merge_json """ files = get_annon_db_file(path, tblname) log.info("files: {}".format(files)) K,V = common.merge_json(files) return K,V
55381098b1a702a5497a965169b0588192e0a439
3,643,034
def costes_coloc(im_1, im_2, psf_width=3, n_scramble=1000, thresh_r=0.0, roi=None, roi_method='all', do_manders=True): """ Perform Costes colocalization analysis on a pair of images. Parameters ---------- im_1: array_like Intensity image for colocalization. Must be the ...
34776cc4e8845e696f61750718736feae6105dee
3,643,035
def get_induced_dipole_count(efpobj): """Gets the number of polarization induced dipoles in `efpobj` computation. Returns ------- int Total number of polarization induced dipoles. """ (res, ndip) = efpobj._efp_get_induced_dipole_count() _result_to_error(res) return ndip
1c7bbd25c17e0a1326e48319c00ad8298174a4b7
3,643,036
def _gen_parabola(phase: float, start: float, mid: float, end: float) -> float: """Gets a point on a parabola y = a x^2 + b x + c. The Parabola is determined by three points (0, start), (0.5, mid), (1, end) in the plane. Args: phase: Normalized to [0, 1]. A point on the x-axis of the parabola. start...
bdd808339e808a26dd1a4bf22552a1d32244bb02
3,643,037
import uuid def grant_perms(obj: element, mast: element, read_only: bool, meta): """ Grants another user permissions to access a Jaseci object Param 1 - target element Param 2 - master to be granted permission Param 3 - Boolean read_only flag Return - Sorted list """ mast = meta['h']....
3a73baf583214d95c31011e8dfc427ea364edb4a
3,643,038
def pkgdir(tmpdir, monkeypatch): """ temp directory fixture containing a readable/writable ./debian/changelog. """ cfile = tmpdir.mkdir('debian').join('changelog') text = """ testpkg (1.1.0-1) stable; urgency=medium * update to 1.1.0 * other rad packaging updates * even more cool packaging up...
0717aba1d5181e48eb11fa1e91b72933cda1af14
3,643,040
import configparser def read_plot_config(filename): """Read in plotting config file. Args: filename (str): Full path and name of config file. Returns: dict: Contents of config file. """ config = configparser.ConfigParser() config.read(filename) out = {} for section in...
876a84b2976807d2ef02c79806c9c2d14874997a
3,643,041
def parse(file_path, prec=15): """ Simple helper - file_path: Path to the OpenQASM file - prec: Precision for the returned string """ qasm = Qasm(file_path) return qasm.parse().qasm(prec)
5303753da86780854f1b2b9abff18ad9531e1ea8
3,643,042
def sinusoid(amplitude=1.0, frequency=1.0, phase=0.0, duration=60.0, samplerate=100.0): """Generate a sinusoid""" t = np.arange(0, duration, 1.0/samplerate) d = np.sin(2.0 * np.pi * frequency * t) return t, d
ea55aec9519321221946e74504732209771b0b23
3,643,043
def get_model(): """ Returns a compiled convolutional neural network model. Assume that the `input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`. The output layer should have `NUM_CATEGORIES` units, one for each category. """ model = tf.keras.models.Sequential() model.add( ...
d6d5ad41ec6ba61ebcf7d2dfb962f18a24b7a8a1
3,643,044
def check_datetime_str(datetime_str): """ Tries to parse the datetime string to a datetime object. If it fails, it will return False :param str datetime_str: :return: returns True or False depending on the validity of the datetime string :rtype: bool """ try: parse_datetime_str(...
8129a3ef87d377bc488bfbd151012241f673e07d
3,643,045
def _df_pitch(df: pd.DataFrame, xcol: str = 'x', ycol: str = 'y', zcol: str = 'z'): """Find angular pitch for each row in an accelerometer dataframe. Args: df (pd.DataFrame): accelerometer dataframe xcol, ycol, zcol (str): column names for x, y, and z acceleration Returns: ...
50c6e40e535b5cd7acead652edf1a9420125fee8
3,643,046
def gan_masked_generate_face(generator_fun, face_img: np.array): """ Generated a face from the seed one considering a generator_fun which should output alpha mask and bgr results :param generator_fun: takes an image and returns alpha mask concatenated with bgr results :param face_img: img to feed to the...
9b6ce882f509851b0a9c52364bb602909db45cb6
3,643,047
def feat_row_sum_inv_normalize(x): """ :param x: np.ndarray, raw features. :return: np.ndarray, normalized features """ x_feat = x.astype(dtype=np.float64) inv_x_rowsum = np.power(x_feat.sum(axis=1), -1).flatten() inv_x_rowsum[np.isinf(inv_x_rowsum)] = 0. x_diag_mat = np.diag(inv_x_rows...
ea55c7826054ca13f810852a24cf315f268dfd6a
3,643,049
def cross3(v1, v2): """ cross3 """ return (v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0])
f3bb2b82acf54d929ffc14177fde120970617886
3,643,050
import copy def api_request(request, viewset, method, url_kwargs={}, get_params={}): """ Call an API route on behalf of the user request. Examples: data = api_request(request, CaseDocumentViewSet, 'list', get_params={'q': 'foo'}).data data = api_request(request, CaseDocumentViewSet...
c3d118d1a9857e9522f3e518a77da6e51e443ef7
3,643,051
def ca_restart(slot): """ :param slot: """ LOG.info("CA_Restart: attempting to restart") ret = CA_Restart(CK_ULONG(slot)) LOG.info("CA_Restart: Ret Value: %s", ret) return ret
1192f371c14bdf8f773b1402f77e66d24d3aee94
3,643,052
def db_query_map(db_or_el, query, func_match, func_not) -> tuple: """ Helper function to find elems from query and transform them, to generate 2 lists of matching/not-matching elements. """ expr = parse_query_expr(query) elems1, elems2 = [], [] for el in _db_or_elems(db_or_el): m = e...
d7b56e8d62d0c80c4bfdb026879d5a848b7d3b8f
3,643,056
import inspect def route(pattern, method = HTTP_METHOD.GET): """ Decorator to declare the routing rule of handler methods. """ def decorator(func): frm = inspect.stack()[1] class_name = frm[3] module_name = frm[0].f_back.f_globals["__name__"] full_class_name = module_na...
28d107abbce1d36611fa5313b0d52491000a1f73
3,643,057
from operator import invert def div_q(a: ElementModPOrQorInt, b: ElementModPOrQorInt) -> ElementModQ: """Compute a/b mod q.""" b = _get_mpz(b) inverse = invert(b, _get_mpz(get_small_prime())) return mult_q(a, inverse)
285a8aa161748d8c7aaa38bd04f81fe7c22e5e43
3,643,058
import pyarrow def pyarrow_to_r_schema( obj: 'pyarrow.lib.Schema' ): """Create an R `arrow::Schema` object from a pyarrow Schema. This is sharing the C/C++ object between the two languages. The returned object depends on the active conversion rule in rpy2. By default it will be an `rpy2.robje...
0eb461451ea805b3ac888084b4f46ca9cbbd7c00
3,643,060
import calendar def validate_days(year, month, day): """validate no of days in given month and year >>> validate_days(2012, 8, 31) 31 >>> validate_days(2012, 8, 32) 31 """ total_days = calendar.monthrange(year, month) return (total_days[1] if (day > total_days[1]) else day)
7499dc9654ec9ffd7f534cf27444a3236dd82e81
3,643,062
import json def save_to_s3(bucket_name, file_name, data): """ Saves data to a file in the bucket bucket_name - - The name of the bucket you're saving to file_name - - The name of the file dat - - data to be saved """ s3 = boto3.resource('s3') obj = s3.Object(bucket_name, file_name)...
520599136418d635cfbaf67c7bffbb2da105985c
3,643,063
def linsearch_fun_BiCM_exp(xx, args): """Linsearch function for BiCM newton and quasinewton methods. This is the linesearch function in the exponential mode. The function returns the step's size, alpha. Alpha determines how much to move on the descending direction found by the algorithm. :param ...
c88f974c76ceec84a12a67ef9c6f71ae357f472b
3,643,064
def getCountryName(countryID): """ Pull out the country name from a country id. If there's no "name" property in the object, returns null """ try: countryObj = getCountry(countryID) return(countryObj['name']) except: pass
72b90de7e49911983fe60e18b00cc577f423785d
3,643,065
def get_placeholder(default_tensor=None, shape=None, name=None): """Return a placeholder_wirh_default if default_tensor given, otherwise a new placeholder is created and return""" if default_tensor is not None: return default_tensor else: if shape is None: raise ValueError('One o...
e62fe4ca8244ae45ac853a0398754375454626dc
3,643,067
def get_targets(args): """ Gets the list of targets for cmake and kernel/build.sh :param args: The args variable generated by parse_parameters :return: A string of targets suitable for cmake or kernel/build.sh """ if args.targets: targets = args.targets elif args.full_toolchain: ...
81eb31fe416303bc7e881ec2c10cfeeea4fdab05
3,643,068
def _format_warning(message, category, filename, lineno, line=None): # noqa: U100, E501 """ Simple format for warnings issued by ProPlot. See the `internal warning call signature \ <https://docs.python.org/3/library/warnings.html#warnings.showwarning>`__ and the `default warning source code \ <https://...
f5709df0a84d9479d6b895dccb3eae8292791f74
3,643,069
def piocheCarte(liste_pioche, x): """ Cette fonction renvoie le nombre x de cartes de la pioche. Args: x (int): Nombre de cartes à retourner. Returns: list: Cartes retournées avec le nombre x. """ liste_carte = [] for i in range(x): liste_carte.append(liste_pioche[i]) ...
ed31c47d699447870207a4066a3da9c35333ada8
3,643,070
def cost_logistic(p, x, y): """ Sum of absolute deviations of obs and logistic function :math:`L/(1+exp(-k(x-x0)))` Parameters ---------- p : iterable of floats parameters (`len(p)=3`) - `p[0]` = L = Maximum of logistic function - `p[1]` = k = Steepness of logistic...
4985d19ff792bf2df8fe5692330cb9c32d329cab
3,643,072
import requests def get_price(token: str, sellAmount=1000000000000000000): """ get_price uses the 0x api to get the most accurate eth price for the token :param token: token ticker or token address :param buyToken: token to denominate price in, default is WETH :param sellAmount: token amount to s...
b1dae25571eccb28433b9bfe7c3be6f006f05184
3,643,073
def _get_all_errors_if_unrecognized_properties(model: dict, props: list) -> iter: """Get error messages if the model has unrecognized properties.""" def get_error_if_property_is_unrecognized(key): if key not in props: return f"unrecognized field named '{key}' found in model '{model}'" ...
e7c380b750606adc466f335a2411619eab11312f
3,643,075
def get_get_single_endpoint_schema(class_name, id_field_where_type, response_schema): """ :param class_name: :param id_field_where_type: :param response_schema: """ return { "tags": [class_name], "description": f"Get a {class_name} model representation", "parameters": [...
98daaaa20e5e52c2480ce6aa1805ee3da6b163d7
3,643,078
from typing import Optional def overlapping_template_matching( sequence, template_size: Optional[int] = None, blocksize: Optional[int] = None, matches_ceil: Optional[int] = None, ): """Overlapping matches to template per block is compared to expected result The sequence is split into blocks, ...
035ce0c333c69bdf437f1e6f93071c9342154e92
3,643,079
def _extract_options(config, options, *args): """Extract options values from a configparser, optparse pair. Options given on command line take precedence over options read in the configuration file. Args: config (dict): option values read from a config file through configparser ...
3d74857b3dcdd242950a35b84d3bcaae557a390b
3,643,080
def _calc_fans(shape): """ :param shape: tuple with the shape(4D - for example, filters, depth, width, height) :return: (fan_in, fan_out) """ if len(shape) == 2: # Fully connected layer (units, input) fan_in = shape[1] fan_out = shape[0] elif len(shape) in {3, 4, 5}: ...
70535fd002f08bbaadf1a0af4ec980851e52ad92
3,643,081
def statRobustness(compromised, status): """produce data for robustness stats""" rob = {0:{"empty":0, "login based":0, "top 10 common":0, "company name":0}, 1:{"top 1000 common":0, "login extrapolation":0, "company context related":0, "4 char or less":0}, 2:{"top 1M common":0, "6 char or...
46920b466b96fa37a94888e788104c1d901a9227
3,643,083