content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_num_adain_params(model): """ input: - model: nn.module output: - num_adain_params: int """ # return the number of AdaIN parameters needed by the model num_adain_params = 0 for m in model.modules(): if m.__class__.__name__ == "AdaptiveInstanceNorm1d": num_...
1ba52ef9284415dfad1cb0d6808447a71614e318
47,607
def matmul(lhs, rhs, transa=False, transb=False): """Create an extern op that compute matrix mult of A and rhs with rocBLAS Parameters ---------- lhs : Tensor The left matrix operand rhs : Tensor The right matrix operand transa : bool Whether transpose lhs transb : b...
72bf4944bc081ecc56e2b13c5d69cb57fda7e4f9
47,609
import typing def call(func: typing.Callable[..., typing.Any], args: typing.Optional[typing.Sequence[str]] = None, prog: typing.Optional[str] = None, doc_parser: DocParserType = google_doc_parser, param_parser: ParamParserType = basic_param_parser) -> typing.Any: """Call functi...
a929b536243dca0fc061109a83220717157a7f6e
47,610
from typing import Iterable from typing import List def clone(clone_specs: Iterable[CloneSpec]) -> List[CloneSpec]: """Clone all repos asynchronously. Args: clone_specs: Clone specifications for repos to clone. cwd: Working directory. Defaults to the current directory. Returns: S...
eae1655b1a43b270e60f1be3c6d0c4d58e172837
47,611
def corrAFM(s): """ Compute the correlator for this pattern: ↑ ↓ ↓ ↑ and symmetry-equivalent patterns """ res = 0.0 L = s.shape[-1] for i in range(L-1): for j in range(L-1): res += s[0, i, j] * s[1, i+1, j] * s[1, i, j+1] * s[0, i+1, j+1] ...
ee86dac73f96a68511441ae39a78ab640922019f
47,612
def RPL_SERVLISTEND(sender, receipient, message): """ Reply Code 235 """ return "<" + sender + ">: " + message
e30e2316f55569a48990cdbf2979bf6ee26bb438
47,613
def fix_missing_locations2(node): """ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, ...
6fd941e47540ad13b13e051e0e84a335003ec78c
47,614
def downsample(scan, is_mask=False, ori_space=None, trgt_space=None, ori_sz=None, trgt_sz=None, order=1, labels=None): """ :param labels: used for advanced downsample when order = 1 for is_mask :param is_mask: mask have smooth upsampling :param scan: shape(z,y,x,chn) :param ori_space: shape(z,y,x) ...
ad2346e5abd272ea2cc47d0f42eb279bb1817bae
47,615
def calc_limits_sorted(data, crop, extend=False, interpolate=False): """ Crops given data by applying specified range to first data and optionally extends data by adding adjacent points and finally calculates minimum and maximum for each data. Note that this method assumes the first data item to be ...
69659af8d6fec86abc5a2855ccc71480539db278
47,616
def GetSweepParamList(core): """ スイープパラメータ値リストの生成 [in] core PDIコアデータ 戻り値 -> スイープパラメータ値リスト """ if not core or not core.pd: return None spl = [] for p in core.pd.plist: if not p.disable and p.calcCaseNum() > 1: spl.append(p) continue # end of for(p) ...
9f50c4475ae5414681e15f1f43e7900575a8d500
47,617
def get_repository_action_counts(repo, start_date): """ Returns the daily aggregated action counts for the given repository, starting at the given start date. """ return RepositoryActionCount.select().where( RepositoryActionCount.repository == repo, RepositoryActionCount.date >= start_date )
4f4fef8087e06a898b2f606eb76f95315d732f6b
47,618
def generate_object_example(properties, definitions): """ Generates an object example from the properties and definitions obtained from the JSON schema. :param properties: A `dict` that defines the properties of the object. :param definitions: A `dict` that defined the schema of certain properties in-c...
4588fb4711c35c4c48e043f5b68945aa3a8f904e
47,619
def attention_block(input_features, context_features, bottleneck_dimension, output_dimension, attention_temperature, valid_mask, is_training): """Generic attention block. Args: input_features: A float Tensor of shape [batch_size, input_size, num_input_features]. ...
c0f8027648f2f02b438918a3443713bc7701db40
47,620
def get_tag_counts(): """return counts of all tags""" query = DB.session.query(Tag.name, DB.func.count(Resource.identifier)).join( Resource.tags).group_by(Tag.id) return dict(query)
2a3bf6baaceeab2ab06d53de43590cf3a03630b7
47,621
def rolling_window(a: np.ndarray, window: int) -> np.ndarray: """Create a rolling window over the provided array. Args: a: array on which to perform the rolling window window: the size of the rolling window Returns: An array of the rolling window. """ shape = a.shape[:-1] +...
3b2e7e1ad9e196614ad286d355a55e51b3be970e
47,622
def map_range(x, in_min, in_max, out_min, out_max): """re-maps a number from one range to another.""" mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min if out_min <= out_max: return max(min(mapped, out_max), out_min) return min(max(mapped, out_max), out_min)
f33b53a5221c9396c4802637c200de7a70812b70
47,623
def extract_faces_from_image(image_array, face_boxes, required_size=(160, 160), convert_2_numpy=True): """ Extract face region from image array Args: image_array (array): Image pixels in numpy format face_boxes (list): list of face bounding boxes required_size (tuple, optional):...
aa6838c1b21e1a5173862efa060fab83f86988e0
47,625
def activity_stream(context, stream_type, *args, **kwargs): """ Renders an activity stream as a list into the template's context. Streams loaded by stream_type can be the default ones (eg user, actor, etc.) or a user defined stream. Extra args/kwargs are passed into the stream call. :: {% ...
879a077267d95b9b41414b44868f5dcf1f4cc95e
47,626
def dilated_residual_2d(inputs, filters, kernel_size=3, rate_mult=2, dropout=0, repeat=1, symmetric=True, **kwargs): """Construct a residual dilated convolution block. """ # flow through variable current current = inputs # initialize dilation rate dilation_rate = 1.0 for ri in range(repeat): re...
e7924d923f65cb4c85a0d52a51c513678b771e63
47,627
def deep_model(model: str = 'vggvox-v2', quantized: bool = False, **kwargs): """ Load Speaker2Vec model. Parameters ---------- model : str, optional (default='speakernet') Model architecture supported. Allowed values: * ``'vggvox-v1'`` - VGGVox V1, embedding size 1024, exported fro...
e9d6ea283e274f615c5c7c7959d59f76118d109f
47,629
def conv3x3(in_planes, out_planes, stride=1,pad=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=pad, bias=False)
de6a83e51dcf46595c56a1585bdf771ba909d5c5
47,630
import copy def EDA_classify_and_return_cols_by_type(df1, nlp_char_limit=20): """ EDA stands for Exploratory data analysis. This function performs EDA - hence the name ######################################################################################## This handy function classifies your columns i...
477385cc13cdd4b414e92b128bc3691deb7a663c
47,632
def log_error(err_code): """ Take an error code from the tracker and log an error for the user. """ error = constants.Errors(err_code) if error != constants.Errors.SUCCESS and error != constants.Errors.NO_ERROR: logger.error(f'ERROR: {error}') return True return False
df4e4af64474a5f609c1ea8c508849b10e1139df
47,633
import torch def rodrigues(theta): """Convert axis-angle representation to rotation matrix. Args: theta: size = [B, 3] Returns: Rotation matrix corresponding to the quaternion -- size = [B, 3, 3] """ l1norm = torch.norm(theta + 1e-8, p = 2, dim = 1) angle = torch.unsqueeze(l1no...
c4a3ecf4cfd72769fb6cd802d8d4b5a0a26f5e1a
47,634
def hairball_plot( g, color_list=None, display=False, node_size=1, text_color="black", node_sizes=None, # for custom sizes layout_parameters=None, legend=None, scale_by_size=True, layout_algorithm="force", edge_width=0.01, ...
9d111daaa2f69f13c4aae7008863e5fc720fe476
47,635
def p_boolean_sliding_window(texts, segmented_topics, dictionary, window_size, processes=1): """Perform the boolean sliding window probability estimation. Parameters ---------- texts : iterable of iterable of str Input text segmented_topics: list of (int, int) Each tuple (word_id_se...
39922ca69804d5f074480106c888ad70baad52a4
47,636
from typing import Iterable def get_relme() -> Iterable[models.TRelMe]: """Get all relme records""" return models.TRelMe.objects.all()
71368c52599dac09f315105e70855281fe2f3078
47,637
import numpy def rand_index(l): """ Return an index of the list with the probability given in the list. Example: prob_index([0.5,0.25,0.25]) should return 0 50% of the time, 1 25% of the time and 2 25% of the time. """ r = numpy.random.uniform(0., sum(l)) s = l[0] for i,p in enum...
2dc37eb292034284053b4d91c42bcfcada8376cd
47,638
from web import Open_URL from BeautifulSoup import BeautifulSoup def Table_Convert(url, contents={}, table=0): """ Open a web page which a table and pull out the contents of that table into a list of dictionaries with your own custom keys. CODE: Table_Convert(url, contents, table) AVAILABLE PARAMS: url ...
b47cb0493b6db5d72c090a75dbd67834737f7fdd
47,639
def _var_to_series(s): """return a pandas Series from a list of lists (arranged vertically)""" if not isinstance(s, (list, tuple)): raise TypeError("Expected a list of lists") keys, values = [], [] for row in s: if not isinstance(row, (list, tuple)): raise TypeError("Expecte...
6a0f8b5cb009bad518a77161f109172260ad8b1b
47,640
def process_line(line: str) -> str or None: """ Pre-processes a line by removing comments and whitespaces. Return a line as an array. If a line does not have valid instructions, it will return None. """ # Remove comments if '#' in line: cut: int = line.find('#') line: str = l...
dfc13898907ea068909eb6d26ea74e32e6e7b18d
47,641
def get_known_corrects(pos: str, wordform: str, input_word: str): """ Get list of known correct outputs of `input_word` with given `pos`, converted to `wordform`. """ try: lemma = agid[pos]["to_lemma"][input_word] except KeyError: return [] # Check if we are converting to t...
564fbb6c87e763af0fb9e3b803890c19d2ac490f
47,642
def smartypants(text): """ Transforms sequences of characters into HTML entities. =================================== ===================== ========= Markdown HTML Result =================================== ===================== ========= ``'s``...
9d6fb4e6a308d263cc7a4afb9d14e893b9a8db39
47,643
def transform_gcp_subnets(subnet_res): """ Add additional fields to the subnet object to make it easier to process in `load_gcp_subnets()`. :param subnet_res: The response object returned from compute.subnetworks.list() :return: A transformed subnet_res """ # The `id` in the response object has ...
ec89d9ce6fc0892093d33eda87fbffeb4081bf31
47,644
def get_chessboard_lines (corners, image): """ Function: get_chessboard_lines ------------------------------ given a list of corners represented as tuples, this returns (horizontal_lines, vertical_lines) represented as (a, b, c) pairs """ #=====[ Step 1: get lines via Hough transform on corners ]===== c...
cc06959fb77228bd438f56c60089cfae708963ca
47,645
def _dg_is_sink_source( dg, v ): """ Returns True iff the digraph dg has a sink or a source at vertex v. INPUT: - ``dg`` -- a digraph - ``v`` -- a vertex of dg EXAMPLES:: sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _dg_is_sink_source sage: from sage....
cc7ed0fc150f593594b4286ffdd111d684291555
47,646
def get_uvs_fingerprinting_algo_desc(): """ Return a string mentioning the current fingerprinting algorithm in use by the system. """ log.cmv("get_uvs_fingerprinting_algo_desc() called. ") if sdef.REPO_HASH_CHOICE == sdef.HashAlgo.SHA512: return "SHA512_HMAC" if sdef.REPO_HASH_CHOICE == sdef...
dabca9857dcd2d9bed24c98f9821981fe90f2961
47,647
def get_smaller_channel(channel, channel_range): """ get channels which is smaller than inputs :param channel:input channel :param channel_range:list,channel range :return:list,channels which is larger than inputs """ return list(filter(lambda x: x < channel, channel_range))
4b9f862756663f12d8f9a8208239ca16fc88042b
47,648
def poch(a,n): """ Returns the Pochhammer symbol (a)_n. """ # First, check if 'a' is a real number (this is currently only working for reals). assert type(a) is not type(1+1j), "a must be real: %r" % a isInteger(n) # Compute the Pochhammer symbol. if n == 0: return 1.0 else...
4d793f7b825e408d313504c9208839838340c14a
47,649
def flatten(game_data): """Flatten the game data into a vector. Parameters ---------- game_data : ndarray An ndarray of shape (# games, 2, 11, 52). 2 teams, 10 players + 1 team aggregate statistic, and 52 features. Returns ------- flattened_data : ndarray An ndarray...
f71316e87d54fdefde52074e1ef58c87cbabb212
47,650
def to_base36(number): """Converts an integer to a base36 string.""" alphabet = digits + uppercase base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <= number < len(alphabet): return sign + alphabet[number] while number != 0: number, i = ...
5dc5504b33b4e91d71ec9fb75396f0d4ee5b16c8
47,651
import chardet def smart_decoder(raw_content, default_encoding_list=("utf-8", "gb18030")): """ 将字符串解码成unicode :type default_encoding_list: list of str :rtype: str :type raw_content: bytes """ encoding = chardet.detect(raw_content).get("encoding", "utf-8") try: return raw_conte...
ddc279db912260c82f7a55627d28ddfaef20fc31
47,653
import torch def sample_sequence(personality, history, tokenizer, model, args, current_output=None): """A function to sample the network. Taken from `interact.py`""" special_tokens_ids = tokenizer.convert_tokens_to_ids(SPECIAL_TOKENS) if current_output is None: current_output = [] for i in ra...
3564aeea115fd0f9bc6b8940a072d0a32376c392
47,654
def clique_merge(contigsof, threshold=0.5): """Merges all maximal cliques of clusters. Inputs: contigsof: A {clustername: set(contignames)} dict threshold [0.5]: Minimum fraction of overlapping contigs to create edge Output: A {clustername: set(contignames)} dict """ # Calculate a...
9f0e685891450b946834d16c01ddeb92f1287a63
47,655
def get_annotmatch_rowids_from_aid( ibs, aid_list, eager=True, nInput=None, force_method=None ): """ Undirected version Returns a list of the aids that were reviewed as candidate matches to the input aid aid_list = ibs.get_valid_aids() CommandLine: python -m wbia.annotmatch_funcs --exec...
68d056afd7c149a8947fcaddd6918fc5acbcd4f4
47,656
def Standard_ErrorHandler_IsInTryBlock(*args): """ * Test if the code is currently running in a try block :rtype: bool """ return _Standard.Standard_ErrorHandler_IsInTryBlock(*args)
e77e0cb3843e04b6db80891514941faf08e4e124
47,657
def quantity(name): """ """ quantity = None if name.lower() not in quants: for k, v in quants.items(): if v['name'].lower() == name.lower(): quantity = v break else: quantity = quants[name] return quantity
94ad20af9cfeb0d0bac73618296fe3ddd9d16165
47,658
from typing import Dict from typing import Any from typing import Tuple from pathlib import Path import urllib import socket import re def get_remote_filesystem_and_path( protocol: str, uri: str, path: str, **storage_options: Dict[str, Any] ) -> Tuple[AbstractFileSystem, str]: """ For a given protocol, ro...
f39ea7c25cb0456fa92c014cd070634fe64a52dc
47,660
def test_token(current_user: User = Depends(get_current_user)): """ Test access token """ return current_user
7f42d411f39cd78142f02522fe1fadd35b1c4c43
47,661
def image_ref(conn, id_, required=True): """Create reference dict for Image identified by ID `id_`. Use OpenStack SDK connection `conn` to fetch the info. If `required`, ensure the fetch is successful. Returns: the ref dict, or None if not found and not `required` Raises: openstack's ResourceNotFo...
faf04bf8a9ae8229695ff34e6567b5d96005f153
47,662
import socket def get_host_ip(): # https://www.cnblogs.com/z-x-y/p/9529930.html """查询本机ip地址 用于快速获取主机的IP地址 Returns: 一个字符串,表示IP地址 例如: 127.0.0.1 """ s = None try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) ...
4f1d4a1d709c467a70a3a91ad985ff0954e6c492
47,663
from typing import cast def get_test_nuplan_db_path() -> str: """Get a single nuPlan DB path to be used in testing.""" paths = discover_log_dbs(NUPLAN_DB_FILES) return cast(str, paths[DEFAULT_TEST_DB_INDEX])
2d44d686bcdc87fb7c60178377f1a984748bc2bb
47,664
def optimize_unnamed_groups(exp): """return an equivalent expression tree but without unnamed groups WARNING: has side-effect """ optimize_unnamed_groups_recursive(exp) return skip_empty_group(exp)
aa9f29f1a8863e6be2f715edbe0b20c32aaabbae
47,665
import warnings import struct def parse(handle, pdbid, verbose=False): """Creates :class:`pdb_eda.ccp4.DensityMatrix` object. :param handle: an I/O handle for .ccp4 file. :type handle: :class:`io.IOBase` :param pdbid: PDB entry ID. :type pdbid: :py:class:`str` :param verbose: verbose mode, de...
0505f1400aea7b7ac3a6f7664e532f0586e30127
47,666
import random def plot_set_3d(set_data, show_vertices=False, show_points=False, show_shape=True, full_page=False, scale=0.7, show_axes=True, only_hull_points=True): """ This function plots a three dimensional convex set. :param set_data: The set to illustrate. :param show_vertices: Sh...
ab12a9bbf08971c42a095ccb1235410cb43ecea1
47,667
def include_container(container, args): """ Return truthy if container should be removed. """ inspect_data = inspect_container(container, args) status = inspect_data["State"]["Status"] # Note that while a timedelta of zero is a valid value for the created/exited/dead fields, # it evaluates ...
d14172acc6787d8a53dd5bd94ca1d3b7537745d5
47,668
def split_line(is_splitline_show=True, **kwargs): """ :param is_splitline_show: 是否显示分割线 :param kwargs: :return: """ _split_line = { "show": is_splitline_show, "lineStyle": line_style(**kwargs) } return _split_line
76e2865a1c6d4c7a5085816846e9587871302588
47,669
def strToNMSLIBVect(text): """Converts to a string that can be fed to NMSLIB""" return toksToStr(unique(getTokenIds(text)))
fe56a3d8e62e61a051e9b33af154fcafa5f64cf8
47,670
import json def load_json(filepath): """Return parsed json file as dictionary.""" with open(filepath) as json_file: try: json_data = json.load(json_file) except json.JSONDecodeError: return None return json_data
daa1d93aaf0602c0e4771e78b5f36ac3d04e4891
47,671
def lighten(color, scale=1.0): """ Lighten a color. - color is a tuple (r, g, b, a) - scale can be any number, if < 1, color will be darken """ return tuple(map( lambda x: int(min(max(x * scale, 0), 255)), color[:3] )) + color[3:]
4c520c00ca3509b3e09090b7d72790db2a80f63c
47,672
def fwhm(sigma=1.0): """ Get the Full-width-half-maximum value from the sigma value (~2.3548) :param sigma: float, the sigma, default value is 1.0 (normalised gaussian) :return: 2 * sqrt(2 * log(2)) * sigma = 2.3548200450309493 * sigma """ return 2 * np.sqrt(2 * np.log(2)) * sigma
1e99cfd747608edcac5b7187bc7a7637bd38cbf2
47,673
def AB2Jy(ABmag): """Convert AB magnitudes to Jansky""" return 10.**(-0.4*(ABmag+48.60))/1e-23
a55b70df44f56461d935c8e5aa8aff50df26a982
47,674
def course_details(request, course_id=None): """ Details about a course """ context = {} # pylint: disable=E1101 course_detail = Course.objects.get(id=course_id) course_user_list = (CourseUser.objects.filter(course=course_id) .values_list('user', flat=True)) user_...
47bdda78f148728747f3c7843d3adc8694a06bfc
47,675
def all_valid(formsets): """Validate every formset and return True if all are valid.""" # List comprehension ensures is_valid() is called for all formsets. return all([formset.is_valid() for formset in formsets])
3cffd9879143e4879794e86bbb65e49f4f2fd975
47,676
import requests from bs4 import BeautifulSoup def get_links(): """ Scrapes the links from the DATASET_LIST_URL and returns a list of them. """ res = requests.get(DATASET_LIST_URL) soup = BeautifulSoup(res.content, 'html.parser') links = soup.find_all('a', text='CSV') return ...
4d6f0ed01b81b02f7d2b48f8f7b15cc65585d42c
47,677
def horizontal_link_count(shape): """Number of horizontal links.""" assert len(shape) == 2 return shape[0] * (shape[1] - 1)
e4d997cd668a75410e3fb208e7a200cbba3fb6bf
47,678
def greedy_value(I: list, w: list, v: list, K: int) -> tuple: """ Solve knapsack problem with value greedness. Takes most valuable first. Parameters: ----------- - I : items - w : items' weights - v : items' value - K : knapsack size Result: ...
767d43b283cd2bab6bedb8d583c0e31450e2edd8
47,679
def data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_put(uuid, tapi_common_bandwidth_profile=None): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_put creates or updates tapi.common.BandwidthProfile...
5be1ea034269879fa179ef69afffdde6aae8703f
47,680
from datetime import datetime def convert_datetime_decimal_day(dt_list): """ returns the decimal day number for each datetime object in dt_list :param dt_list: list of datetime objects to evaluate :return: numpy array of the decimal day for each datetime """ timestamp = np.zeros(len(dt_list)) ...
f9f8774828ff6764d00f1bb211a36775278125a3
47,681
def build_err_payload(aggregator, import_): """ Builds a JSON error response to return as a WS client notification. """ # flatten errors & warnings into a single list to send to the UI. Each ImportErrorSummary # may optionally contain multiple related errors grouped by subcategory errs = [] ...
1fae5be0308ea5086ac7a3a62be96779162bb2cd
47,682
from typing import Optional def subscriber(pytestconfig) -> Optional[str]: """Subscriber of USS making UTM API calls""" if pytestconfig.getoption(OPT_RID_AUTH): session = make_session(pytestconfig, BASE_URL_RID, OPT_RID_AUTH) session.get('/status', scope=rid.SCOPE_READ) rid_sub = session.auth_adapter....
7b726dca5620b5fec1ffdfce1fb6034901e1cbdd
47,683
def create_bus(net, vn_kv, name=None, index=None, geodata=None, type="b", zone=None, in_service=True, max_vm_pu=nan, min_vm_pu=nan, coords=None, **kwargs): """ Adds one bus in table net["bus"]. Busses are the nodes of the network that all other elements connect to. INPUT:...
6547f73733077c2c73ed038eeb75d2d9ee45ba95
47,684
def m(x0: float, x1: float, y0: float, y1: float) -> float: """ Simple gradient function. Parameters ---------- x0 : float x co-ordinate at time 0. x1 : float x co-ordinate at time 1. y0 : float y co-ordinate at time 0. y1 : float y co-ordinate at time...
d138dfedd1e381a575ff6f5108b8841470febbd7
47,685
def normalize(track_complex): """ Normalizes training data to use only amplitudes """ magnitude = np.abs(track_complex) magnitude = np.reshape(magnitude, magnitude.shape + (1,)) return magnitude
415bfe6c14cd80081429250c60976c34ccb08509
47,686
def get_child_watcher(): """Equivalent to calling get_event_loop_policy().get_child_watcher().""" return get_event_loop_policy().get_child_watcher()
e8dfad4c324c1da7456c7ccde837e38e98f223a0
47,687
def ping_video_url(url): """ Ping url """ try: vs = cv2.VideoCapture(url) flag, _ = vs.read() except Exception as e: logger.info("Exception in ping url: {}".format(e)) return flag
10d603b82232ac88c7cb84717a04fa882f8b426f
47,688
def md_alignment(alignment): """Given alignment option, return corresponding markdown""" if alignment == "<": return ":", "-" elif alignment == ">": return "-", ":" else: return "-", "-"
7e111bdf4e6b83ca5754aeba98ee49a80e1a555c
47,689
def password_from_sentence(sentence): """ Create a phrase-based password. Remember the sentence to remember the password. The first letters of each word are added to the password, numbers and special characters are kept as is. Arguments: sentence -- The sentence for create the passord (str)...
f4c0f5cf75fa0c790b461ce586d2cd51f15173ca
47,690
import itertools def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None): """ Returns a dict containing the humanized data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, only the name...
932c2d86f95f40055c8f81b7a19039ca421e34b7
47,692
def save_model(model, model_name: str) -> str: """ Serves for saving pre-trained models to disk. Takes <model, model_name> as input (the name of the saved model - can be with or without file extension). Raises Exception if the model cannot be saved to disk. """ model_path = get_model_path(model_...
85c4b7fbe3a92334e0e4ac51a0e8ef70c375d25c
47,693
def _refresh(fn): """Decorator to refresh the attributes of this object from the cluster""" def wrapper(self, *args, **kwargs): self.Refresh() fn(self, *args, **kwargs) self.Refresh() return wrapper
5db0f25fc3042aec25f1af8f5a65edf8436cacdc
47,694
def define_haystack_units() -> UnitRegistry: """ Missing units found in project-haystack Added to the registry """ unit_ureg = UnitRegistry(on_redefinition='ignore') unit_ureg.define('% = [] = percent') unit_ureg.define('pixel = [] = px = dot = picture_element = pel') unit_ureg.define('d...
4916c62b689ed422e3364ddb3b3ff7a0c9fa0687
47,695
def singlediode_voc(effective_irradiance, temp_cell, module_parameters): """ Calculate voc using the singlediode model. Parameters ---------- effective_irradiance temp_cell module_parameters Returns ------- """ photocurrent, saturation_current, resistance_series, resistan...
b2de1329e0a921bbdbe88cdcaa4c129f5ee63d3b
47,696
from pathlib import Path def scans_generator(scans_train_directory_path: Path, scans_val_directory_path: Path, batch_size=16, target_size=(256, 256), shuffle=True, backbone="efficientnetb0"): """ Tensorflow dataset generator. :param scans_train_directory_path: It should contain one su...
052f69b7d6d6d21d5b4900e8826eda406a5e7b20
47,697
def Nabla_discrete(k_space,s_space=None,kfield=None): """ This function returns the difference operator represented in Fourier space. """ if(about.hermitianize.status): print 'It is not recommended to calculate derivatives in' print 'Fourier space while hermitianize is o...
7263602dc204bcd7eb484fc687124b7a38785aca
47,698
def _usa(): """Returns a data frame of cumulative daily infections per state.""" df = pd.read_csv('../data/usa.csv', usecols=['date', 'state', 'positive'], parse_dates=['date']) df = df.rename(columns=dict(state='region', positive='cumulative')) return df.dropna(subset=['cumulative'...
cd5bb880c699aada8d210ece38072310c349099f
47,699
import time def getDateRange(dt): """ 获取时间戳范围 参数 -------------- dt: str url请求中传递过来的date参数 返回值 -------------- turple 返回一对 (起始时间戳,终止时间戳) """ if dt == 'weekend': startDT = "2017-03-25 00:00:00" endDT = "2017-03-27 00:00:00" elif dt == 'weekday': ...
1265df8cb736a8ac13515220b68296c7517771ad
47,700
import random def generate_random_color(): """ Generate random color. """ r = random.random() g = random.random() b = random.random() return (r, g, b)
11416e6714a08bfbea8c6939774d1f0e54664ac4
47,701
def get_highest_in_hierarchy(nodes): """Return highest nodes in the hierarchy that are in the `nodes` list. The "highest in hierarchy" are the nodes closest to world: top-most level. Args: nodes (list): The nodes in which find the highest in hierarchies. Returns: list: The highest nod...
ddd3f061fd381989a8a2f5cd8f9525371400ed1a
47,702
def get_host_finding_detail_command(client, args): """ Retrieve information about particular host finding based on host finding id. :param client: object of client :param args: Demisto arguments provided by the user :return: command output """ client_detail = get_client_detail_from_context(...
9254d00c7dae7a136061a7f78c239998bb8bed31
47,703
def MPC_GetRxGainExternalRx() -> int: """Gets current reception gain Returns ------- int Reception gain (raw value) """ gain = c_uint32() CTS3Exception._check_error(_MPuLib.MPC_GetRxGainExternalRx( c_uint8(0), byref(gain))) return gain.value
2fdfc6b89458ce9d758eb9493d2d280d86036f32
47,704
import copy def tiwary_mmvt_model(tmpdir_factory, tiwary_mmvt_model_persistent): """ Create a copy of the model that is not persistent. But this at least doesn't require us to generate an entirely new model """ tiwary_mmvt_model = copy.deepcopy(tiwary_mmvt_model_persistent) return tiwary_mmvt_...
381dd449c8cbcfbdf43ed9a3e8b71fff09f9a2c9
47,705
def _get_disposable_app_filename(clientInfo): """ Get name of file used to store creds. """ return clientInfo.get('file', clientInfo['name'] + '.client_data.json')
7d6a67443cd8815ddfde3f69aae450d59f59a437
47,706
def _timestamp_from_record_tuple(record): """Extract timestamp from HBase tuple record """ return record[0]['timestamp']
de0ff6f12e14093a236cab651d4baae2299d2124
47,708
def concretize_backward_bound(backward_linexp: LinearExpression, act_bound: Bound) -> Bound: """Compute the value of a backward bound. Args: backward_linexp: Coefficients of linear functions defined over a layer. act_bound: Bound on the activations of that layer. Returns: ...
d95d9c01acebf126490f706ce4c6d29fd509e923
47,709
def order_sell_stop_loss(symbol,quantity,stopPrice,timeInForce='gtc'): """Submits a stop order to be turned into a market order once a certain stop price is reached. :param symbol: The stock ticker of the stock to sell. :type symbol: str :param quantity: The number of stocks to sell. :type quantity...
08273662492940766dc22494c724cc40a92f9278
47,710
import functools def downloadable(orderby=None, limitby=None): """Return list of downloadable books. Args: orderby: orderby expression, see select() limitby: limitby expression, see seelct() Returns: Records instance representing list of Creator instances. """ db = curren...
abb316f1ddcc40969de57dbc8784ede6cddf0997
47,711
def kube_upgrade_download_images(token): """ Ask System Inventory to kube upgrade download images """ return _patch_kube_upgrade_state(token, "downloading-images")
67c94ddb2acb250bc4003fb08bbe822bd172b3a4
47,712
import cmath def builtin_precision(n): """ Count the digits in an integer. Count the significant figures of a floating point number. """ if isinstance(n, BInt): ds = str(n).lstrip('-') return BInt(len(ds)) elif isinstance(n, BFloat): if cmath.isinf(n.value) or cmath.isnan(n.value): return BInt(0) ds ...
fa2397e984c29f7305322d4ad081ef91f150f653
47,713
import random from datetime import datetime import logging def main(): """ Handler for the main (index) page """ if _SINGLE_PAGE_UI: # Redirect to the single page UI return redirect(url_for("page")) user = current_user() # Initial tab to show, if any tab = request.args.get("tab"...
7ea4e33eeacd5cef0604433ec7d394184b248795
47,714