content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def state_lookup(): """Look up state from given zipcode. Once state is found, redirect to call_senators for forwarding. """ zip_digits = request.values.get('Digits', None) # NB: We don't do any error handling for a missing/erroneous zip code # in this sample application. You, gentle reader, sho...
13219025777e50422ab30902f0f3d35f7b73afed
3,634,829
def vmtkmeshtosurface(mesh, cleanoutput=1): """Convert a mesh to a surface by throwing out volume elements and (optionally) the relative points Args: mesh: Volumetric mesh. cleanoutput (bool): Remove unused points. Returns: vtkPolyData object. """ extractor = vmtkscripts.v...
78b311d8523b495b36be5f64767389bf3c71a13a
3,634,830
def time_delta_calc(contiguous_trajectory,order = 2): """Computes the time derivatives of a contiguous trajectory. INPUT contiguous_trajectory An array of space-time cordinates order The order up to which the time derivatives are calculated. If order=1, the velo...
17352f37f69e9947c0cea8e9fd7cf54ea3ff6e2e
3,634,831
def tasks_page(): """ Tasks and completions page """ return flask.render_template( 'tasks.html', config=g.project.config, project=g.project, version=label_studio.__version__, **find_editor_files() )
56656a8571e33fb40f3790a207faa2fccc7315a0
3,634,832
def outformathtml(pandasdf): """ change a few formating things to prettify and make it match """ pandas_table = pandasdf.to_html() pandas_table = pandas_table.replace(""" border="1" """, " ") pandas_table = pandas_table.replace("""<tr style="text-align: right;">\n <th></th>\n <th></th>...
5f8abf88a2aead4f095f52c1f49ab4ad609c04a5
3,634,833
def list_catalogs(**kwargs): """ Return the available Cone Search catalogs as a list of strings. These can be used for the ``catalog_db`` argument to :func:`conesearch`. Parameters ---------- cache : bool Use caching for VO Service database. Access to actual VO websites refe...
b539746edb4b6aa256bcbac3153b9a323bb41882
3,634,834
def rot_decode(data: str, n: int = 13) -> str: """Decode a ROT-encoded string that was shifted by `n` places.""" if not 1 <= n < 26: raise ValueError('n must be in range [1, 26)') return rot_encode(data, 26 - n)
f001f15684cc77e8ea52cf481626c6bdaf97c071
3,634,835
from datetime import datetime def searchlight(x, y, m=None, groups=None, cv=None, write=False, logger=None, permutations=0, random_state=42, **searchlight_args): """ Wrapper to launch searchlight :param x: Data :param y: labels :param m: mask :param groups: group labels :pa...
799f2496c0609050e6914576cfbdaba972320723
3,634,836
def codegen_reload_data(): """Parameters to codegen used to generate the fn_ioc_parser_v2 package""" reload_params = {"package": u"fn_ioc_parser_v2", "incident_fields": [], "action_fields": [], "function_params": [u"ioc_parser_v2_artifact_id", u"ioc_...
9c279e24b2e05adc5b1573393368216483307071
3,634,837
def Pattern2(s): """ Compute the correlator for this pattern: ↓ ↓ ↑ ↑ and symmetry-equivalent patterns """ res = 0.0 s = np.pad(s, ((0, 0), (2, 2), (2, 2))) L = s.shape[-1] for i in range(L-2): for j in range(L-2): res += s[1, i, j] * s[0, i+1,...
390cf6b8262f00d396235fb8ef5d4acc72d1df9e
3,634,838
import math def gauss(x, x0, sigma): """ This function returns a Gaussian distribution. """ return (1/(sigma*math.sqrt(2 * math.pi))) * np.exp(-(x - x0)**2 / (2 * sigma**2))
c4ebd141e68e59567b21355fb3b813c7f4ff914b
3,634,839
import math def distance(): """ Calculate the distance between two points. return: Distance. """ return lambda a, b: math.sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*+(a.y-b.y)+(a.z-b.z)*(a.z-b.z))
ab3a14e7033afab66db7c283aefda745158bad65
3,634,840
import numpy def rational_sum(numerator, denominator, *argv): """Sum of rational numbers.""" if len(argv) < 2: gcd = numpy.gcd(numerator, denominator) num_out, den_out = numerator//gcd, denominator//gcd else: num_2 = argv[0] den_2 = argv[1] num_3 = numerator*den_2 +...
b34d01ea2bcfd072430501828401d5b492b2bae5
3,634,841
import time def nonce() -> str: """Return a nounce counter (monotonic clock). References: * https://support.kraken.com/hc/en-us/articles/360000906023-What-is-a-nonce- """ # pylint: disable=line-too-long return str(time.monotonic_ns())
fb6221fef4c2c8af66200c4c9da8f6253854b186
3,634,842
def fetch_single_equity(stock_code, start, end): """ 从本地数据库读取股票期间日线交易数据 注 -- 1. 除OHLCV外,还包括涨跌幅、成交额、换手率、流通市值、总市值、流通股本、总股本 2. 添加后复权价格,使用复权价在图中去除间隙断层 3. 使用bcolz格式写入时,由于涨跌幅存在负数,必须剔除该列 Parameters ---------- stock_code : str 要获取数据的股票代码 start_date : datetime-like 自...
04e63665fe9b05dfcca8387519d2a178d117acb5
3,634,843
import string def base62_encode(number): """Encode a number in base62 (all digits + a-z + A-Z).""" base62chars = string.digits + string.ascii_letters l = [] while number > 0: remainder = number % 62 number = number // 62 l.insert(0, base62chars[remainder]) return ''.join(l)...
b1f10fe69b6263d54f2e00a32b8260cbb3c42747
3,634,845
import json def handle_update(config_path): """ handle changes in globalConfig.json Args: config_path : path to globalConfig.json Returns: dictionary : schema_content (globalConfig.json) """ with open(config_path) as config_file: schema_content = json.load(config_file...
f51f52f9353339ba1cf080b10ad8f28691deefe9
3,634,846
from typing import Sequence from typing import Tuple import urllib def encode(s: Sequence[Tuple[str, str]], similar_to: str=None) -> str: """ Takes a list of (key, value) tuples and returns a urlencoded string. If similar_to is passed, the output is formatted similar to the provided urlencoded str...
c0153b77ec03708d54574062d15c7f81df59510b
3,634,847
def gis_ellipse_polygon(origin, a, b, orientation=0.0, complexity=128): """ Generate a polygon of an ellipse suitable for GIS applications. :param origin: the center of the ellipse (expected to be UTM, m) :param a: the a/semi-major axis length (expected to be UTM, m) :param b: the b/semi-minor axis...
48df0adbc7fd04508a6d3a8288c6b46fe9f9bdb0
3,634,848
def activate_lesson(): """ { "id": 51, "active": "A" } """ domain = request.get_json() return lesson_service.activate_lesson(domain)
a4e48ca2c8e65e9ff0e2fb95b61ef776573a9649
3,634,849
def split(labels, n_per_class=20, seed=0): """ Randomly split the training data. Parameters ---------- labels: array-like [n_nodes] The class labels n_per_class : int Number of samples per class seed: int Seed Returns ------- split_train: array-like [n_p...
69c7510f9be494afe7bb0c1492870c1d7c2d6694
3,634,850
from setfilter.setfilter import Setfilter def base(): """test Setfilter """ # build fixture # initialization center = np.array([0, 0, 0, 0.]) body = np.array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) ...
b306d6425a6e1e329e0af006585c06be4585972e
3,634,851
def stack(*cons): """ Combine constraints into a large constaint by intersection. Parameters ---------- cons : [`selection.affine.constraints`_] A sequence of constraints. Returns ------- intersection : `selection.quasi_affine.constraints`_ Notes ----- Res...
8ddc52aa41c2ef4ec784067692efa1f3643a130c
3,634,852
def _create_poi_gdf( tags, polygon=None, north=None, south=None, east=None, west=None, timeout=180, memory=None, custom_settings=None, ): """ Create GeoDataFrame from POIs json returned by Overpass API. Parameters ---------- tags : dict Dict of tags used ...
4d88c0bb60ee836131bf5197c0caad17c0358f5b
3,634,853
def prepare_data(seqs, labels, maxlen=None, x_dim = 3, mapping=None, max_mapping=None): """Create the matrices from the datasets. This pad each sequence to the same length: the length of the longest sequence or maxlen. if maxlen is set, we will cut all sequence to this maximum length. This sw...
e2582ce07fa770b78bcd02dae26b345059c051c0
3,634,854
import types def _get_prediction_tensor( predictions_dict): """Returns prediction Tensor for a specific Estimators. Returns the prediction Tensor for some regression Estimators. Args: predictions_dict: Predictions dictionary. Returns: Predictions tensor, or None if none of the expected keys are...
0bd509d4021e0f0622b0cf685e5bf8682f47daa0
3,634,855
def gen_confirm_code(): """ Generate a new email confirmation code and return it """ return generate_uuid_readable(9)
992844a42886892cfa7eebc44e8efb61aa547725
3,634,856
def update_profile(): """ Update profile page """ form = UpdateProfileForm() # Update profile form if form.validate_on_submit(): # If form is submitted and validated if form.picture.data: # If picture is uploaded picture = save_picture(form.picture.data) # Save picture ...
ad2b427487cc63aa64068b86254c2d5b6b363c2c
3,634,858
def get_version_info(pe): """Return version information""" res = {} for fileinfo in pe.FileInfo: if fileinfo.Key == 'StringFileInfo': for st in fileinfo.StringTable: for entry in st.entries.items(): res[entry[0]] = entry[1] if fileinfo.Key == '...
8a01062de92cd4887f5cc7a292ffb644a701b43c
3,634,859
import torch def data_prepare(coord, feat, label, split='train', voxel_size=0.04, voxel_max=None, transform=None, shuffle_index=False, origin='min'): """ coord, feat, label - an entire cloud """ if transform: coord, feat, label = transform(coord, feat, label) if voxel_size: # voxelize ...
988a7068d0fc383f86c853b0593189633a87a53d
3,634,860
def _right_branching(nodes): """ Parameters ---------- nodes: list[T], where T denotes NonTerminal or Terminal Returns ------- list[T], where T denotes NonTerminal or Terminal """ if len(nodes) == 2: return nodes lhs = nodes[0] # The left-most child node is head ind...
9bfa47daa95be30b7f9a9ada882e1fdceb1295e5
3,634,862
import random def random_swap(o_a, o_b): """ Randomly swap elements of two observation vectors and return new vectors. :param o_a: observation vector a :param o_b: observation vector b :return: shuffled vectors """ X, Y = [], [] tf = [True, False] for x, y in zip(o_a, o_b): ...
f243e91e5b281c682601fdb8df49bd7e6209274c
3,634,863
def parse_multiplicative(index): """Parse multiplicative expression.""" return parse_series( index, parse_unary, {token_kinds.star: expr_nodes.Mult, token_kinds.slash: expr_nodes.Div, token_kinds.mod: expr_nodes.Mod})
e314ca44735db31d00fe55268be8a7f69816db45
3,634,864
def return_factorized_dict(ls): """ ###### Factorize any list of values in a data frame using this neat function if your data has any NaN's it automatically marks it as -1 and returns that for NaN's Returns a dictionary mapping previous values with new values. """ factos = pd.unique(pd.factoriz...
7804f12f953eabcdc7bb398121500c2c8f2e278f
3,634,865
def _strip_asserts(source): """ Remove assert method calls from source code. Using RedBaron, replace some assert calls with print statements that print the actual value given in the asserts. Depending on the calls, the actual value can be the first or second argument. Parameters ----------...
4c484635328e9610bd07004cfba63acc4ae039d1
3,634,866
def _index_clusters(feat_mat, init_mat): """Creates a hierarchical binary tree till the top-level clusters supplied.""" cluster_feat = init_mat.T.dot(feat_mat) cluster_feat = cluster_feat.tocsr() cluster_feat = skprep.normalize(cluster_feat, "l2", axis=1) init_cluster = HierarchicalKMeans.gen( ...
f48e32507e298c4b089c9358c14727c4b8444ee5
3,634,867
from functools import reduce def gcd(numbers): """Return greatest common divisor of integer numbers. Using Euclid's algorithm. Examples -------- >>> gcd([4]) 4 >>> gcd([3, 6]) 3 >>> gcd([6, 7]) 1 """ def _gcd(a, b): """Return greatest common divisor of two i...
da7ae2a24649bc05e233533735baf850a37dcc5a
3,634,868
def normal_attention(tensor_base, tensor_to_attend, mask_for_tensor_base, mask_for_tensor_to_attend, similarity_method='inner', hn=100, use_pooling=False, pooling_method='max', reverse=False, scope=None): """ ...
93df4d084bb76cba4ab227928de6eb72e7f5af76
3,634,869
from bs4 import BeautifulSoup def getPageNum(html): """解析第一页网页,返回该用户的书评页数 """ soup=BeautifulSoup(html,'html.parser') paginator=soup.find('div','paginator') pas=paginator.findAll('a') num=int(pas[-2].text) return num
626a6f580e5634ba741d0794f6fc4c020aecabd0
3,634,870
async def get_user(api_management_name=None,resource_group_name=None,user_id=None,opts=None): """ Use this data source to access information about an existing API Management User. > This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/d/api...
c5bdf6aa7d0c69a59b9b8f6a93f63a9cba9a00cd
3,634,871
def makeCC_allpair(spikes, Begin, End, N_thred): """ 全てのCCをBegin~Endの間で計算する args: spikes: list型 Begin, End: int型 N_thred: 並列計算をするときに与えるスレッド数 return: X: ペアごとに計算したCC. X.shape = (ニューロンのペア数、CCの幅) index: ペアのニューロンの番号. index.shape = (ニューロンのペア数、2). index[i][0]は結合先ニューロン、in...
e9e5b9bd805251b4244ab89e6a1e11316617101d
3,634,872
def move_position(facility, cur_position, direction): """Move position from cur_position in the direction on facility.""" changes = DIRECTIONS[direction] doors = DIRECTION_TO_DOOR[direction] for cell in (doors, ROOM): next_position = [] for coordinate, change in zip(cur_position, changes...
64601f07378da56eaa03d896987491cd6f93182b
3,634,873
from typing import Callable import itertools from typing import OrderedDict import pprint def search_for_improvements( targets : [Exp], wf_solver : ModelCachingSolver, context : Context, examples : [{str:object}], cost_model : CostModel, stop_cal...
374a5a16f6ec4e69e983613aedbb298df1411cca
3,634,874
def down_sample(fft_vec, freq_ratio): """ Downsamples the provided data vector Parameters ---------- fft_vec : 1D complex numpy array Waveform that is already FFT shifted freq_ratio : float new sampling rate / old sampling rate (less than 1) Returns ------- ...
1ddfaa075c1d8bc68f9348d4f49807b61eceb60c
3,634,875
import torch def set_device(cuda: bool) -> int: """Set the device for computation. Args: cuda (bool): Determine whether to use GPU or not (if available). Returns: int: Index of a currently selected device, CPU or GPU. """ device = torch.device("cuda" if (torch.cuda.is_available() a...
f65fc5e38f14b8de78d14ac150ac14e5c8788e26
3,634,877
import torch def hsic_regular(x, y, sigma=None, use_cuda=True, to_numpy=False): """ """ Kxc = kernelmat(x, sigma) Kyc = kernelmat(y, sigma) KtK = torch.mul(Kxc, Kyc.t()) Pxy = torch.mean(KtK) return Pxy
551ed76c2f902b662ffe2c693da4474b6eb3958e
3,634,878
def random_correlation(size, n_factors, random_seed=None): """ Generates a random correlation matrix with 'size' lines and columns and 'n_factors' factors in the underlying structure of correlation. :param size: int. Size of the correlation matrix :param n_factors: int. number of factors in the corr...
92cd98bdf95e0ffef51c016c1c9ef05391c483dd
3,634,879
def eigendecompose(S): """Eigendecompose the input matrix.""" eigvals, V = np.linalg.eig(S) return eigvals, V
0658d3b83d54a7435862b89d0a1fa3e82f4082fd
3,634,881
def _CreateSampleDirectoryCoverageData(builder='linux-code-coverage', modifier_id=0): """Returns a sample directory SummaryCoverageData for testing purpose. Note: only use this method if the exact values don't matter. """ return SummaryCoverageData.Create( server_ho...
3edebb67f0b4dafa837c14b99fd0b2b241da784d
3,634,882
def sched_time(update_time) -> int: """ Return interval between the current time and the update time in seconds """ current_time_ss = hhmm_to_seconds(current_time_hhmm()) update = hhmm_to_seconds(update_time) interval = update-current_time_ss return interval
5a57f591550a9f72dc7e9aa87a75c7aacf624cbe
3,634,883
def http_jsonrpc_post(hostname, port, uri, method, params): """Perform a plain HTTP JSON RPC post (for task farming)""" url = "http://%s:%s%s" % (hostname, port, uri) data = simplejson.dumps({ 'method': method, 'params': params, 'jsonrpc': '2.0', 'id': 1 }) req = urllib2.Request(url, data, {'...
8ac5e836564c4ddc2a277c4aea8bf0ff6b8836c2
3,634,884
def get_user_event(current_user, event_id): """ Query the user to find and return the event specified by the event Id :param event_id: Event Id :param current_user: User :return: """ user_event = User.get_by_id(current_user.id).events.filter_by(event_id=event_id).first() return user_even...
d65e3a65cb4400a9b4173b8ea4d45f6f94e0993c
3,634,885
def get_distances(scr_data_dict, distance_keys, data_centroid=None): """ @param scr_data_dict: @param distance_keys: @param data_centroid: Do not provide if calculating distances for establishing s thresholding @return: """ dataset_keys = scr_data_dict.keys() # Extracting dataset point o...
c0aec2de89bd7c7150d3f5fcbc3161f9f2d441c0
3,634,886
def compare_numeric_abundances(values_in_taxa_list_1, values_in_taxa_list_2): """Retun a Pandas Series with [abundance-in, abundance-out, p-value].""" mean1 = mean_ignore_nans(values_in_taxa_list_1) mean2 = mean_ignore_nans(values_in_taxa_list_2) keyslist1 = list(values_in_taxa_list_1.keys()) keysli...
f2e6e4326b12242a8493b82e37190a47d60b44e6
3,634,887
def parse_folder(folder, start_time=None, grepcmd=None, tmp_folder=None, force_grep=False): """ Args: grepcmd, tmp_folder, force_grep's default value should be the same with parse_single_log_with_pregrep Yields: [[yield], []]: nested yields """ def get_first_last_line(filepath): ...
b8d233ba8ad579d38e3353b841ea03d52bb83962
3,634,888
def search(request): """ search function which reads get data from a requests and uses it to find stuff in elasticsearch """ context = {"table": []} if "subject" in request.GET or "predicate" in request.GET or "object" in request.GET: es = elasticsearch.Elasticsearch(settings.ELASTICSEARCH) ...
85b1daba7d6a815f3e465b23ef369d439834de9c
3,634,889
from typing import Dict def parse_measurement_lines(xml_root: Element) -> Dict[int, LineString]: """Parses the measurement line from the given xml root Args: xml_root (ET.ElementTree): root of the xml file Returns: measurement lines to use in the analysis (id, line) """ measureme...
8e7ff2a75189e8f6c1960f6849c1b63bc1ff4821
3,634,891
from typing import Any from typing import Optional def compute_and_apply_approximate_vocabulary( x: common_types.ConsistentTensorType, default_value: Any = -1, top_k: Optional[int] = None, num_oov_buckets: int = 0, vocab_filename: Optional[str] = None, weights: Optional[tf.Tensor] = None, ...
9662796984852ff255ca923e1048121427debfe6
3,634,892
import io def album_cover(): """Get the current song's album cover.""" cover = app.config["player"].album_cover() image = io.BytesIO(cover) if cover else "static/no_cover.jpg" return send_file(image, mimetype="image/jpeg")
3c2c7b9513bd36e49f27d4b58ca1408932402d72
3,634,893
def create_new_filename(original_filename: str, user_response: str): """ Creates new file name depending on the users response :param original_filename: str :param user_response: str :return: str | new filename """ if user_response == "1": time = str(today.time())[:8].repla...
789bf9f73b4647c534859a2ae97b9ec806b02d1c
3,634,895
from typing import OrderedDict def genertate_info_tree(traces, trace_events, level="module"): """ """ assert level in ["module", "operator", "mixed"] tree = OrderedDict() for trace in traces: path, module = trace # unwrap all of the events, in case model is called multiple times ...
cc885b41df2d2ecf0484c55a07f9b8ef381263d8
3,634,897
def interpolate(x, ratio): """Interpolate data in time domain. This is used to compensate the resolution reduction in downsampling of a CNN. Args: x: (batch_size, time_steps, classes_num) ratio: int, ratio to interpolate Returns: upsampled: (batch_size, time_steps * ratio, classes_num...
54ceb6aee15de3c775d3be93bbc48422dc542641
3,634,898
from astroquery.mast import MastClass def _resolve_object(target): """Ask MAST to resolve an object string to a set of coordinates.""" # Note: `_resolve_object` was renamed `resolve_object` in astroquery 0.3.10 (2019) return MastClass().resolve_object(target)
bf9c0bb3a09fac1622cc107cf3f9532888b3a4f9
3,634,899
import torch def spgr(pd, r1, r2s=None, mt=None, transmit=None, receive=None, gfactor=None, te=0, tr=25e-3, fa=20, sigma=None, device=None): """Simulate data generated by a Spoiled Gradient-Echo (SPGR/FLASH) sequence. Tissue parameters ----------------- pd : tensor_like Proton densit...
78cfa5f7b264fd85603a5e66ec77974558f05d21
3,634,900
def create_subject(request): """ This is a form """ template = loader.get_template('form.html') form = SubjectForm() return HttpResponse(template.render({'form':form, 'redirect': '/subject', 'submit':'Create Subject and add to class'}, request))
8bea2cb4e6ba26a030a9b3008377c126af551491
3,634,902
def text2number(text): """ Convert arabic text into number, for example convert تسعة و عشرون = >29. Example: >>> text2number(u"خمسمئة و ثلاث و عشرون") 523 @param text: input text @return: number extracted from text @rtype: integer """ number_names = WORDS_NUMBERS.copy() ...
9a0b28810549efab956d720695534e82aecf2c4f
3,634,903
def parse_prototype(prototype, additional_definitions={}): """Given a single annotated C function prototypes (see module docstring), for syntax), and an optional dict of non-base type definitions, return the following information that ctypes needs to load and annotate a function: function_name: str ...
93d79407bf0b4175f51dfef0fb39fa288eaa1512
3,634,904
def create_resource(): """QonoS resource factory method.""" return wsgi.Resource(SchedulesController())
caca6c4a6d8b3e67db79eee1937ae0479de1ab05
3,634,905
def compute_heatmap(model, saved_model, image, pred_index, last_conv_layer): """ construct our gradient model by supplying (1) the inputs to our pre-trained model, (2) the output of the (presumably) final 4D layer in the network, and (3) the output of the softmax activations from the model """ ...
c412a1ddb7300434334b2276df257cda51072f96
3,634,906
def get_all_orders(): """Returns a list of ALL the orders for rooms and AGs, with reader and approver specified for each.""" # Get a list of all the orders of access groups of all responsible approvers. ag_relation = ApprovesAgRequest.query \ .join(AccessGroupRequest, AccessGroupRequest.id == ApprovesAgRequest.ag...
798c7347e0db7f3f7ba2f66364cbc55be3a641ed
3,634,907
def isAnomaly(lowBand, highBand, value): """Condition for anomaly on a certain row""" if value < lowBand or value > highBand: return True return False
552513115ec9c98c40cd6487b6a33f497c562c87
3,634,908
def initWeights(positive_count, negative_count, trainingSamples): """ Initialise weights. :param positive_count: Number of positive samples. :param negative_count: Number of negative samples. :param trainingSamples: Training samples. :return: Weights """ positiveSampleInitialWeight ...
640fb32b62fc461b9c638d3a647c53db69424fd9
3,634,909
def get_distance_calculator(name, *args, **kwargs): """returns a pairwise distance calculator name is converted to lower case""" name = name.lower() if "moltype" in kwargs and kwargs.get("moltype") is None: kwargs.pop("moltype") if name not in _calculators: raise ValueError('Unknown...
c8d1d0fca18e7f71742fb8a45829ac4e8f84077b
3,634,910
def compute_escape_peak(spectrum, ratio, params, escape_e=1.73998): """ Calculate the escape peak for given detector. Parameters ---------- spectrum : array original, uncorrected spectrum ratio : float ratio of shadow to full spectrum param : dict ...
c6948547a2bb34f32cb423b5ab0cd8d9f9f695e4
3,634,912
def create_transaction(wallet, purchase): """ creates a transaction of crypto from the PSP wallet to a user who has paid in fiat Note: Ideally this will be done for more than 1 tx at a time.. would have a basket of tx ready to go and then they will all go out in one TX with all the outputs. Then the s...
d6e31bb698782128e58ccf73e8b62e34f8937377
3,634,913
import numpy def _create_globio_lulc_op( lulc_array, potential_vegetation_array, pasture_array, ffqi, globio_nodata, pasture_threshold, primary_threshold): """Construct GLOBIO lulc given relevant biophysical parameters.""" result = numpy.empty_like(lulc_array, dtype=numpy.int16) result[:] ...
1a6ca959e8da30767a264bc529f16ab6f2626851
3,634,914
import random def temperature_dist(): """Random normal variated temperature around RT_MEAN with RT_SIGMA""" return random.normalvariate(RT_MEAN, RT_SIGMA)
971b2296878780e9af568784a454d08dfead0e2c
3,634,915
def pair_keys_to_items(items, key): """ Convert the list of key:value dicts (nics or disks) into a dict. The key for the new dict is one value of the current dict identified by the key parameter. If it does not exist, then the key is the order number in the list. """ new_items = {} for ...
92c66bfbb298e767b3fedbfcfd48ad87ac1162ef
3,634,916
def rotateStructure(structure): """ Rotate a structure randomly """ angle_rad = _np.random.rand(1) * 2 * _np.pi newstructure = _np.array( [ (structure[0, :]) * _np.cos(angle_rad) - (structure[1, :]) * _np.sin(angle_rad), (structure[0, :]) * _np.sin(angle_r...
9df411e82caa5827499ae5648a1ec7d24e27cff5
3,634,918
async def iamalive(name, **params): """ Accept services promotions """ await state.alive_service(name) return OK
82e0e8243dd8eadfc27cab484157c2d1c6db63b1
3,634,919
def add_wind_rotation_info(res: str, ds: xr.Dataset) -> xr.Dataset: """ Add wind rotation information to the dataset Args: res: grid resolution, format as f'c{number cells in tile}' """ rotation = _load_wind_rotation_matrix(res).drop_vars("tile", errors="ignore") common_coords = {"x": ...
242293904998367fe75b112adc1298ead39152a7
3,634,920
def get_human_size(size): """Return a string describing the size in bytes""" if size < 1024: return '{} B'.format(size) if size < 1024 * 1024: return '{:.2f} KB'.format(float(size) / 1024) if size < 1024 * 1024 * 1024: return '{:.2f} MB'.format(float(size) / (1024 * 1024)) if...
48cee8ca55717d6fb48c5c1dc06becff71c58f0e
3,634,921
def prepare_m2m_data(model, ctx_dict, fields, parent_ids): """ Recebe os argumentos e devolve um dicionário com os dados necessários para montar a lista """ #print('in_prepare_m2m_data') name = ctx_dict.get('name') record = ctx_dict.get('record') edit_ok = ctx_dict.get('edit_ok') popup =...
87ec8e992e63ecf53a3e0c878d1254d70c957d11
3,634,923
def empty_when_none(_string=None): """If _string if None, return an empty string, otherwise return string. """ if _string is None: return "" else: return str(_string)
402186ee7b4ba9c3968f81bee23134067d0f260e
3,634,924
def visualizeFrame(x, y, z, translation, size = 0.1): """ Input: x - numpy array (x, y, z) or column vector y - numpy array (x, y, z) or column vector z - numpy array (x, y, z) or column vector translation - numpy array (x, y, z) or column vector ...
2ad8aaf1e16488d4b87d155c5115185a42f68fee
3,634,925
def baseline_dwt( array, max_iter, level=None, wavelet="sym6", background_regions=None, mask=None, mode="constant", axis=-1, ): """ Iterative method of baseline determination, based on the discrete wavelet transform. Parameters ---------- array : `~numpy.ndarray` Data with ba...
41edf5cc884592ee8c480881702fd02206cd55bd
3,634,926
def get_ego_polygon(ego_state: StateSE2, vehicle: VehicleParameters) -> Polygon: """ Return Shapely polygon correspoding to Ego :param ego_state: x, y (center of rear axle) and heading :param vehicle: Parameters of the vehicle :return: Shapely polygon for ego """ ego_rectangle = construct_eg...
eb9d3cee0a6c27fe76bbc5525c06c9e094584850
3,634,927
import hashlib def file_hashes(f, bufsize=16000000): """ computes md5, sha1, sha256 from a file obj. intended for large files. returns 3-tuple of hexstrings """ md5 = hashlib.md5() sha1 = hashlib.sha1() sha256 = hashlib.sha256() while True: buf = f.read(bufsize) if len(buf) == 0: break ...
4e23a0d99cda07325ba3a14675bfb515c12d2950
3,634,928
def paginate_update(update): """ attempts to get next and previous on updates """ time = update.pub_time event = update.event try: next = Update.objects.filter(event=event, pub_time__gt=time).order_by('pub_time').only('title')[0] except: next = None try: previous...
eda885cfdb538f6e609c097d146c3803b17fb1f8
3,634,929
def get_timestep(all_params, stuff_for_time_loop): """ Gets the full VFP + logging timestep :param all_params: (dictionary) contains input parameters for simulation :param stuff_for_time_loop: (dictionary) contains derived parameters for simulation :return: a function with the above values initializ...
0ca048c07b9fe230469c7e16e0a847b9b155fc50
3,634,930
def TDF_ComparisonTool_SourceUnbound(*args): """ * Finds from <aRefDataSet> all the keys not bound into <aRelocationTable> and put them into <aDiffDataSet>. Returns True if the difference contains at least one key. (A key is a source object). <anOption> may take the following values: 1 : labels treatment only; 2...
4f1ad0bbb33ff34f5bbdac37a43bf8ab8c1bd6bd
3,634,932
def sorted_qubits(qbs: Qubits) -> Qubits: """Return a sorted list of unique qubits in canonical order. Qubits can be of different types, so we sort first by type (as a string), then within types. """ return tuple(sorted(list(set(qbs)), key=lambda x: (str(type(x)), x)))
fcff2d13d22875118348566ce6432834c31ba644
3,634,933
def lu(a: np.ndarray, permute_l: bool = False, overwrite_a: bool = False, check_finite: bool = True, is_lapack_piv: bool = True): """ Compute pivoted LU decomposition of a matrix. """ if overwrite_a: pivot, LU = _lu_internal(a, permut...
c417a0ec96c92f6662f2dac78b9369ca7feb18f0
3,634,934
def compute_referendum_result_by_regions(referendum_and_areas): """Return a table with the absolute count for each region. The return DataFrame should be indexed by `code_reg` and have columns: ['name_reg', 'Registered', 'Abstentions', 'Null', 'Choice A', 'Choice B'] """ tempdf = referendum_and_are...
afd55a1c514c59cdac2a507b9f90eb382f2845ee
3,634,935
from typing import List import json def get_edfi_payloads(context, dbt_run_result, table_reference: str) -> List: """ Extract BigQUery table and return the resulting JSON as a dict. """ df = context.resources.warehouse.download_table(table_reference) df_json = df.to_json(orient="records", dat...
c2ad0026ad4e56a256a824a4c1fae0762aaa51b7
3,634,937
from typing import List def deinterleaver(pseudo_rand_array: List[int], array: np.ndarray) -> np.ndarray: """Random permutations for deinterleaving an array according to a pseudo random sequence""" dims = array.shape flat_array = array.flatten() matrix = np.zeros(array.size, int) for index, positi...
8fc1a59921875de3e647f09ba93f6d645d2829c8
3,634,938
def add_rnn_encoder_arguments(group): """Define arguments for RNN encoder.""" group.add_argument( "--elayers", default=4, type=int, help="Number of encoder layers (for shared recognition part " "in multi-speaker asr mode)", ) group.add_argument( "--eunits"...
64a65bd496402dedfe98c4bd0d5bbc516c87a398
3,634,939
def sum_sample(attrfx='merge'): """Returns a mapper that computes the sum sample of a dataset. Parameters ---------- attrfx : 'merge' or callable, optional Callable that is used to determine the sample attributes of the computed sum samples. By default this will be a string representation o...
3a86b1bd169d75a573261313181bb5ca75df3c89
3,634,940
def match_profile_to_preset(profile_lookup, colour_preset_lookup): """Get a list of preset names that match the current profile colour scheme. """ match_list = [] for preset_name, preset_colours in colour_preset_lookup.iteritems(): match = True for colour_name, colour_val in preset_colo...
7ac13ee2d29970f284269c6ca0e32ed6de27e8f7
3,634,941
import json def jsonpify( data, callback ): """ Helper to support JSONP """ try: output = json.dumps( data, sort_keys=True, indent=2 ) if callback: output = '%s(%s)' % ( callback, output ) return output except Exception as e: message = 'exception jsonify...
6b41ca031b45f835aa57bc08e738dbd6c68d59c5
3,634,942