content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _all(itr): """Similar to Python's all, but returns the first value that doesn't match.""" any_iterations = False val = None for val in itr: any_iterations = True if not val: return val return val if any_iterations else True
bb1145abaaaa1c6910371178ca5ebe68600bb287
49,738
def list_plot3d_array_of_arrays(v, interpolation_type, texture, **kwds): """ A 3-dimensional plot of a surface defined by a list of lists ``v`` defining points in 3-dimensional space. This is done by making the list of lists into a matrix and passing back to :func:`list_plot3d`. See :func:`list_plo...
d3099b55a37f57a9df111b3f8b55033732b1ebcc
49,739
import six def volume(input, copyFrom=None, rescale=True, voltype=None): """ Read an existing geoprobe volue or make a new one based on input data Input: input: Either the path to a geoprobe volume file or data to create a geoprobe object from (either a numpy array or ...
c04a5d5060a0afd25d9b3f12b5d6a207582739ea
49,740
def view_related_developers(request, tag, slug): """ Tutorial > View Related Developers """ namespace = CacheHelper.ns('tutorial:views:view_related_developers', tag=tag, slug=slug) response_data = CacheHelper.io.get(namespace) if response_data is None: response_data, tutorial = RelatedH...
f36355eb0635dd29edd1fe548ff88f22ec51ffdb
49,741
def compute_neuron_head_importance(task_name, model, data_loader, num_layers, num_heads, loss_fct=nn.loss.CrossEntropyLoss(), ...
be0d52c34539db4650aba53c0bb41a958af17ab9
49,742
def no_init(_data, weights): """ Return the entered weights. Parameters ---------- _data: ndarray Data to pick to initialize weights. weights: ndarray Previous weight values. Returns ------- weights: ndarray New weight values Notes ----- Useful ...
f120b49ab26fa1051360b4e4ae85dd07025ae5cc
49,743
def primeFactors(someInt): """ return a list of the prime factors of someInt. e.g. primeFactors(24)=[2,2,2,3] primeFactors(23)=[23] primeFactors(25)=[5,5] """ return "stub"
4afe8491585721852571ecda89c7cd33fb05d1f7
49,744
def create_local_gateway_route(client, local_cidr, **route_kwargs): """[summary] Arguments: client {[type]} -- [description] local_cidr {[type]} -- [description] Keyword Arguments: gateway {[type]} -- [description] (default: {None}) Returns: OperationResult """ ...
e7f07f133be40d7eb71a6c40ec610f3ceba3e6c8
49,745
def validate_ui(self, value): """Validate EngineUI objects.""" if not isinstance(value, EngineUI): reason = 'not an EngineUI object' raise ValueError(self.msg.format(reason)) return value
dbe3eb7377164a2c98dd875f1e5715a84d613176
49,746
import uuid def is_valid_uuid(val): """ Check if a string is a valid uuid :param val: uuid String :return: Returns true if is a string is a valid uuid else False """ try: uuid.UUID(str(val)) return True except ValueError: return False
d04f658d3ae2fa85377e110b0a6716bc34ee9df0
49,747
def generate_stat_string(stat_distribution, name): """generates the gear rating string based on the count of the stat""" count = stat_distribution.count(name) extra_line = "\n" if name == "versatility" else "" return "gear_{0}_rating={1}{2}".format(name, count * config["stats"]["steps"], extra_line)
bab062276be57fbc134bc49c70eda1d96513de86
49,748
from typing import Tuple from typing import List def pad_dialog( dialog: Dialog, max_dialog_size: int, max_utterance_size: int ) -> Tuple[List[List[int]], List[List[int]], List[List[int]], List[List[int]]]: """Pads utterances in a dialog up to max dialog sizes.""" dialog_usr_input, dialog_usr_mask, dialog_sy...
2456716cd0ffc9b0d8613adb04ff206c250cc0c8
49,749
from pathlib import Path import warnings import shlex def _make_sbatch_string( command: str, folder: tp.Union[str, Path], job_name: str = "submitit", partition: tp.Optional[str] = None, time: int = 5, nodes: int = 1, ntasks_per_node: tp.Optional[int] = None, cpus_per_task: tp.Optional[...
bde05036f280d2cf9b88e2b768bb2b93806682dd
49,750
import warnings import urllib def parse_redis_url(url): """ Given a url like redis://localhost:6379/0, return a dict with host, port, and db members. """ warnings.warn( "Use redis.StrictRedis.from_url instead", DeprecationWarning, stacklevel=2) parsed = urllib.parse.urlsplit(ur...
6d24b885feadf58a6f9a17486ba71e4473bce100
49,751
import numpy def Torque(cc1,cc2,ccp,g,mass=1.0): """ cc1: origin of axis, cc2 head of axis ccp: point g: Gradients in Cartasian coordinate, [dx,dy,dz] """ torque=0.0 x21=cc2[0]-cc1[0]; y21=cc2[1]-cc1[1]; z21=cc2[2]-cc1[2] xp1=ccp[0]-cc1[0]; yp1=ccp[1]-cc1[1]; zp1=ccp[2]-cc1[2] dnom...
d4974f3e5997e44530ad7a1988fe36800d3dad4b
49,752
import io import tarfile def write_tar_from_contents(contents, filter=None): """Writes a tar file from a dict of archive names to bytes that represent the contents of each file. """ digest = io.BytesIO() with tarfile.TarFile(mode="w", fileobj=digest) as tar: for filename, content in conten...
c7918a131ca0038647f0de24198609b1f1e28363
49,753
def eliminate(values, s, d): """Eliminate d from values[s]; propagate when values or places <= 2. Return values, except return False if a contradiction is detected.""" global counttotalsearches # DGTEMP counttotalsearches += 1 # DGTEMP if d not in values[s]: return values ## Already elim...
7df68c13c1088933a8601eecbcb3b8bd9aba5d03
49,754
def non_zero_uniform(shape): """Samples in open range (0, 1). This avoids the value 0, which can be returned by tf.random.uniform, by replacing all 0 values with 0.5. Args: shape: a list or tuple of integers. Returns: A Tensor of the given shape, a dtype of float32, and all values in the open i...
c3c50d26d6c1e87e2c1049c5d2931e73f4c7dd86
49,755
def _format_moving_cutoff_predictions(y_preds, cutoffs): """Format moving-cutoff predictions""" if not isinstance(y_preds, list): raise ValueError(f"`y_preds` must be a list, but found: {type(y_preds)}") if len(y_preds[0]) == 1: # return series for single step ahead predictions retu...
f52d70c72a00a84bcbb35eacf952eaee1e7dbb44
49,757
import re def get_possible_modes(): """Get the set of possible modes.""" modes = set() with open("web/src/helpers/constants.js", encoding="utf-8") as file_: # The call to `eval` is a hack to parse the `modeOrder` array from the # JavaScript source file. for mode in eval(re.search(r...
062159e1dffd24296264792fd8cf6e53441fb141
49,760
def convert_to_hexadecimal(bits, padding): """ Converts bits to a hexadecimal character with padding. E.g. Converts [False, False, False, True], 0 to "1". Converts [True, False, False, False], 2 to "08" Args: bits: List of boolean values. padding: Integer of number of ...
b8cd1647a24072278aca65f7734934acd93d8f12
49,761
import fastapi from typing import List async def read_patron_list( session: aio_session.AsyncSession = fastapi.Depends( dependencies.get_session), offset: int = 0, limit: int = fastapi.Query(default=100, le=100), current_patron: patron_model.Patron = fastapi.Depends( # pylint: disable=unused-...
522407fd8b448564d80957b66df58feef3252f99
49,762
def beta_table(stocks_weights, start, end): """ Returns an attribution table for portfolio beta :param stocks_weights: table of the name of equities in one column, weights in another :param start: start date :param end: end date :return: table """ # Due to the nature of the percentchange...
9cfb5f6658dc1a3d4960bc7451be06c9e48ac9fb
49,763
def sepconv_relu_sepconv(inputs, filter_size, output_size, first_kernel_size=(1, 1), second_kernel_size=(1, 1), padding="LEFT", nonpadding_mask=None, ...
a7f94ec286df89e252262d6ada7031a92d133342
49,764
import wheel def convert(context, base_path, rule): """ Convert the python representation of a targets file into a python representation of a buck file. """ converters = [ discard.DiscardingConverter(context, 'cpp_binary_external'), discard.DiscardingConverter(context, 'haskell_ge...
dcaa320255dc4286b73ab3750d465898060a4008
49,765
import json def set_review_filters(request): """Sets review filters given by passed request. """ review_filters = request.session.get("review-filters", {}) if request.POST.get("name", "") != "": review_filters["name"] = request.POST.get("name") else: if review_filters.get("name"):...
9d9f7e1544e3eea9767f0f85677bcb2b23cdd81c
49,766
import string def _sanitize_title(title): """ Remove all non alphanumeric characters from title and lowercase """ alphanumeric = string.ascii_lowercase + string.digits + ' ' title = title.lower() title = "".join(filter(lambda x: x in alphanumeric, title)) return title
6f0d1818140bc2a50b160f73b8b4590be8f31891
49,767
def IsBefore(version, major, minor, revision): """Decide if a given version is strictly before a given version. @param version: (major, minor, revision) or None, with None being before all versions @type version: (int, int, int) or None @param major: major version @type major: int @param minor: minor...
3fe9f995b90d7406d0b0366b0bbe5a940f975893
49,768
def generateRules(L, supportData, minConf=0.7): """ 生成关联规则 Args: L 频繁项集列表 supportData 频繁项集支持度的字典 minConf 最小置信度 Returns: bigRuleList 可信度规则列表(关于 (A->B+置信度) 3个字段的组合) """ bigRuleList = [] for i in range(1, len(L)): # 获取频繁项集中每个组合的所有元素 for freqSet in...
2ab2c23450cfff8c80f6b2bd9783e73186f1d064
49,771
def domain_check(f, symbol, p): """Returns False if point p is infinite or any subexpression of f is infinite or becomes so after replacing symbol with p. If none of these conditions is met then True will be returned. Examples ======== >>> from sympy import Mul, oo >>> from sympy.abc impor...
057665c5de32747a92b09f83831db36665f127c3
49,772
import math def makePyramid(elem, graph, levels=4, scale=0.5): """ Create a pyramid of num images based upon elem, which becomes the first child of the new pyramid """ p = elem.getparent() minDim = round(levels / scale) width = max(int(elem.get(swidth, str(minDim))), minDim) height = m...
822f54fcb78673101390d8aaa7bb8aefb022d90c
49,773
def parse_negline(neg_line): """ Parse the THIRD line of the .mmo file, where the negations are stored. Why does it not do this per-phrase? Mystery. We connect the negated-CUI to its appearance in the text using the ConceptPositionalInfo which _appears_ to correspond to the PosInfo field which ...
a412add79370a58f6bd00c0139a9fe334e808432
49,775
import json def validate_cohort_project_allowed(): """ Returns true if a valid project is provided. Remote call is set up in static/js/cohortUpload.js. """ project = request.args.get('project') valid = project in db.get_mw_projects() return json.dumps(valid)
79e568d2a8ec8f5541aa5c6ea97aac5d42d80bb5
49,776
def depthwise_2d_fast(feat, weights): """ """ feat = tf.convert_to_tensor(feat) weights = tf.convert_to_tensor(weights) kernel_size = weights.shape.as_list()[0] return graphics_tf_module.depthwise_conv_fast(feat, weights, kernel_size)
f3aa9989a7c7f4559a1184f19d303187d2d2e594
49,777
def handle_trace_length(state_trace_length): """ transform format of trace length :return: """ trace_length_record = [] for length in state_trace_length: for sub_length in range(0, int(length)): trace_length_record.append(sub_length + 1) return trace_length_record
39631247d10dbaa024a0e8d553024718150ccc51
49,778
from time import time from scipy.signal import fftconvolve def compute_ts_map(counts, background, exposure, kernel, mask=None, flux=None, method='root brentq', optimizer='Brent', parallel=True, threshold=None): """ Compute TS map using different optimization methods. ...
ebfc3dada9e0e39ba8bea0c3e36948f5d6ffe134
49,779
import sound def audio_duration(filename): """ duration of a audio file (usually mp3) Parameters ---------- filename : str must be a valid audio file (usually mp3) Returns ------- duration in seconds : float Note ---- Only supported on Windows and Pythonista. On ...
6d51619957c6a6dc96eb1b3647bfe2176ae080fd
49,781
def is_moderator(request, view): """ Helper function to check if a user is a moderator Args: request (HTTPRequest): django request object view (APIView): a DRF view object Returns: bool: True if user is moderator on the channel """ user_api = request.channel_api cha...
31c8b53c28b3972a731b87b13177b3c01c45ade4
49,782
def monkeypatch(monkeypatch): """Adapt pytest's monkeypatch to support stdlib's pathlib.""" class Monkeypatcher: """Middle man for chdir.""" def _chdir(self, value): """Change dir, but converting to str first. This is because Py35 monkeypatch doesn't support stdlib's p...
d7da33204cd0a2f07f51b47b95f106e053c28c1f
49,783
def binom(n, k): """ Obtain the binomial coefficient, using a definition that is mathematically equivalent but numerically stable to avoid arithmetic overflow. The result of this method is "n choose k", the number of ways choose an (unordered) subset of k elements from a fixed set of n elements. ...
b322712d1757df543ccdc92ffc7f883504804346
49,784
def no_auth(request): """ Use this if no auth is desired """ return request
5871518399aee8204d2ece4c8bad575527270627
49,785
def bilstm_layer_cudnn(input_data, num_layers, rnn_size, keep_prob=1.): """Multi-layer BiLSTM cudnn version, faster Args: input_data: float32 Tensor of shape [seq_length, batch_size, dim]. num_layers: int64 scalar, number of layers. rnn_size: int64 scalar, hidden size for undirectional L...
6f55275787e7e5f68004cb5b5173008ab34ae6f1
49,786
from typing import Tuple def calculate_smoothed_trends( case_counts: np.ndarray, death_counts: np.ndarray, hosp_counts: np.ndarray, smoothing_window: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Calculates the smoothed trends with the given smoothing window :param case_counts: Cases per day :par...
c8fc0ef3a071bb04c86bbed1e27d04a505b094ea
49,787
def generate_swagger_params(crown: ViewCrown, swagger_params: dict) -> dict: """ assemble params for swagger_auto_schema by crown """ default_params = {} if crown.body_in: default_params = {"request_body": crown.get_in_serializer_instance()} elif crown.query_in: default_params = ...
dc91db1a6e9317a4b45346e6829df1d4d195a18c
49,788
def total_size(metainfo): """ Compute sum of all files' size """ if metainfo.has_key('files'): total = 0 for infile in metainfo['files']: if infile.has_key('length'): total += infile['length'] return total else: return None
84deea16534e35f2c3c86c9674a8e83f880bd5a5
49,789
def diffmap(adata, **kwargs): """\ Scatter plot in diffmap basis. Parameters ---------- {scatter} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. """ return scatter(adata, basis="diffmap", **kwargs)
f304e66f76fa143ff7102eec5388749c6e6014fe
49,790
import random import string def makeHTMLword(body, fontsize): """take words and fontsize, and create an HTML word in that fontsize.""" #num = str(random.randint(0,255)) # return random color for every tags color = 'rgb(%s, %s, %s)' % (str(random.randint(0, 255)), str(random.randint(0, 255)), str(rando...
00bb65217f4b75344a38100cee88c1e928aa0698
49,791
def sigma_x_rk_new( thickness, radius, length, f_y_k, fab_quality=None, flex_kapa=None ): """ Meridional characteristic buckling stress. Calculates the characteristic meridional buckling stress for a cylindrical shell according to EN1993-1-6 [1]. Paramet...
fc79d852b8878757d7e5e2eb794a1507986bb0cb
49,792
def ts_grismc_sim(pixels): """ Simple analytic wavelength calibration for Simulated GRISMC data """ disp = 0.0010035 ## microns per pixel (toward positive X in raw detector pixels, used in pynrc) undevWav = 4.0 ## undeviated wavelength undevPx = 1638.33 wavelengths = (pixels - undevPx) ...
f3491fea1fa1e8833384711076e6187f0f6cb42b
49,794
from typing import Callable def get_admin_principal_by(authentication_manager: AuthenticationManager) -> Callable[[Request], PrincipalService]: """ admin only """ return get_principal_by(authentication_manager, [UserRole.ADMIN])
8737f6a271d766560cb2f5c17e271d297c520195
49,795
def get_profile_avatar_upload_to(instance, filename): """ Returns a valid upload path for the avatar associated with a forum profile. """ return instance.get_avatar_upload_to(filename)
840e7482b225c0a456dbc8cd967203aa542945f8
49,796
from typing import Optional def calc_r(alphas: np.ndarray, colvars: np.ndarray, calc_jac: bool) -> tuple[np.ndarray, Optional[np.ndarray]]: """ Calculate linear combination of reaction coordinates given a weights vector and colvars matrix. Also returns the jacobian with respect to the alphas if...
2e14ddd98c296eb0250ff59cc84597594873c383
49,797
def discretized_exponential(lamb, up_bound, steps): """ Exponential distribution on discretized interval [0, up_bound] """ return discretized_state(lambda x: stats.expon.pdf(x, scale=1 / lamb), 0, up_bound, steps)
8ed948c7e7652fa15aefd41f02470864dfd5d1df
49,798
def timedelta_to_string(dt): """ Return hh:min:sec from a timedelta64. There doesn't seem to be a standard pandas or numpy function to do this strangely. """ total_sec = dt / np.timedelta64(1, 's') hours = int(total_sec // 3600) minutes = int((total_sec // 60) % 60) seconds = int(to...
2615dc0f54272183325ddc441d8f489f323c1cfb
49,799
def funex(c): """ Compile a function by 'exec' :param c: function to compile :type c: string :return: the function 'f' declared in the input string :rtype: function """ dc = {} exec(c, dc) return dc['f']
79fac0aad493d47fc9fecbf30bfe4bc09a2f9908
49,800
import threading import time def get_fingerprint_batch(input_list, default_port=443, delay_time=0.5, max_threads=100): """ This is a parallel version of the TLS fingerprint primitive. Params: input_list- the input is a list of host:ports. default_port- default port to ...
6276e23290b35762eeeddb98a6d60e97135d29c2
49,801
def even_fib(ceiling): """ Returns the sum of all even Fibonacci numbers not exceeding ceiling. """ total = 0 fg = Fibonacci() n = next(fg) while n <= ceiling: if n % 2 == 0: total += n n = next(fg) return total
ad9163d34bc57767336fef5171d26e2cd3339a08
49,802
import json def get_table_columns(etcd_client, db, tbl): """ Get primary key column for table db.tbl. :param etcd_client: Etcd client. :param db: database name. :param tbl: table name. :return: Primary key column. :rtype: ColumnSet :raise ProgrammingError: if table or database doesn't...
091fe315cc7ad83af93e710cdf18526640fd6ed2
49,803
def _flatten_multiplicand_list(kernels): """Flatten a list of kernels which may contain _ProductKernel instances. Args: kernels: Python list of `PositiveSemidefiniteKernel` instances Returns: Python list containing the elements of kernels, with any _ProductKernel instances replaced by their `kernels...
d5a2700795b634fb2861998bc842df653456258b
49,804
def parse_bool_token(token): """ Parses a string token to convert it to its equivalent boolean value ignoring the case of the string token or leaves the token intact if it cannot. :param token: String to convert to ``True`` or ``False``. :type token: ``str`` :return: ``T...
bd9de30ee85921ba72a46e83eb96a0af104f998d
49,805
from typing import Union import abc def dictionary_writable( model: Union[type, abc.Dictionary] ) -> abc.DictionaryHooks: """ Retrieve a metadata instance. If the instance currently inherits its metadata from a class or superclass, this function will copy that metadata and assign it directly to th...
e0f60c42ae8d9a2eabc3b2ec4fb24bef52fcf8b3
49,806
import torch def log_prb_1l_per_smpl(x, ls): """ x=log(P) is a list of log probability tensors, and it has shape (batch_size, number_of_classes + 1, other dimensions like time, ...) ls is a list of labels with the same length as x. Each sample has one label in range [0, number_of_classes) ...
ad71c0fca4dea7e830db343acba296123e8e277d
49,807
def func_PS_Level(HA_Open, HA_Close, PS_pct_level=[0.35, 0.5, 0.95, 0.97], combine=False): """ 0. This function is for calculating the HA bars' bar size level, or called Price Status(PS). 1. This function has 4 arguments and return 2 arrays as output. 2. Input arguments including: (1) HA_Open: D...
3a2f9a9d200e800b0e314df7f01e4a3affa155d7
49,808
def angle(x0, x1): """Compute the angle between two vectors x0, x1 using the dot product""" mx0 = np.dot(x0, x0) mx1 = np.dot(x1, x1) return np.arccos(np.dot(x0,x1)/np.sqrt(mx0*mx1))
18b43c43e41d3ffb27c985f7338ea635f4f80cd8
49,809
import scipy def grubbs(timeseries, end_timestamp, full_duration): """ A timeseries is anomalous if the Z score is greater than the Grubb's score. """ try: series = scipy.array([x[1] for x in timeseries]) stdDev = scipy.std(series) # Issue #27 - Handle z_score agent.py Runtim...
14d05c35e65880ff7bdee9afc571ba173a814741
49,811
def _spatial_proximity(data, group_pop_var, total_pop_var, alpha=0.6, beta=0.5): """Calculate Spatial Proximity index. Parameters ---------- data : a geopandas DataFrame with a geometry column. group_pop_var : string The name of variable in data that contains the popula...
ba365819e1eef61c1042587a0e9370989752354b
49,812
def video_content_to_dict(vid_info_list): """Convert YouTube metadata list to dictionary.""" video_dict = {} for video in vid_info_list: if not video: continue title = video["title"] video_dict[title] = {"id": video["id"], "duration": video["duration"]} return video_d...
e56b211e9879ce783a8b145f267778dcaa0550b9
49,813
import requests def getwcs(dataset, applyomega=True, service="https://hla.stsci.edu/cgi-bin/fitscut.cgi"): """Return dictionary with WCS information for an image. Parameters ---------- dataset : str dataset name applyomega : bool, optional Apply HSC correction? Default value = Tr...
43d22dba3e8d882961deff5856361900f9ec8e68
49,814
import six def get_redis_from_settings(settings): """Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_...
03c555612aa67be6c3197cfd4c51a7145184436e
49,815
import wget async def download(uri): """ Guarda en el disco duro un archivo indicado por una URI Parámetro: > uri (str, por ejemplo 'http://www.inspyration.org/logo.png') Retorno: > contenido de un archivo (bytes, archivo de texto o binario) """ content = wget(uri) if content is ...
a2668b3182267bf2264bac382013f7fd9c0d4294
49,816
def print_symbol_table_node_to_dot(node, cur_id): """ Print the node of a symbol table as html table :param node: symbol table :param cur_id: current node id :return: dot string """ dot = "\t{} [\n\t shape=plaintext \n \tlabel=< <table border=\'0\' cellborder=\'1\' cellspacing=\'0\'\n\t>".fo...
d4a1b2dcb8bbc971d8100e74f2c887ce452cd1b9
49,817
def create_getter(var_name): """ Given the string name of a variable, creates a getter function for that variable and returns it. Args: var_name the name of the variable for which a getter should be created. """ def getter(self): """ The getter function to be returned.""" return geta...
7091280d2a804d818247ffcfa9e55c0d98bfe761
49,818
def James_Stein_estimator(data, std_noise): """ See Large-scale inference: empirical Bayes methods for estimation, testing, and prediction (Efron, 2010, page 6) """ mean_data = np.mean(data) dev = sum((data - mean_data) ** 2) return mean_data + (1 - (len(data) - 3) * (std_noise ** 2) / dev) * (d...
69db35bbeb65047b4c301bce673d11f7ddf51759
49,819
def predict_by_moving_avg_growth(stock, s, **_): """Returns predicted value of a stock Predicts the next price of a stock by extrapolating the moving average and its growth. Parameters ---------- stock : :obj:`stock` Stock to be predicted. s : int Number of data points used to...
c8e02b9c55bd339ff6f1793b697ba46647331326
49,820
from typing import Union import types def get_admin_log(peer: Union[int, str] = None) -> list: """ Get a list of logs from the admin-logs. This method gets 'Join' and 'Leave' events by default, but you can uncomment the commented items and add them to your result list. :param peer: Union: [id, usern...
704a277eb9e1fde3cd119d5e3b7f73ffcc4e578a
49,822
def from_networkx(G): """ Convert a NetworkX graph into a Zen graph object. In creating the object, the NetworkX node object and node/edge data will be copied over (a shallow copy). **Returns**: The return type depends on the input type. * :py:class:`zen.Graph` if the input graph was a :py:class:`network...
e320a20749be2b9b99d90a1f8164706073f0593b
49,823
def find_subpixel_peak_position(corr, subpixel_method='gaussian'): """ Find subpixel approximation of the correlation peak. This function returns a subpixels approximation of the correlation peak by using one of the several methods available. If requested, the function also returns the signal ...
b915e6a2e1c71aa36d8423bb31ce2b625878ae38
49,824
def _vec_to_triu(vec): """Take vec and forms strictly upper triangular matrix. Parameters ---------- vec : array_like, shape[..., n] Returns ------- tril : array_like, shape=[..., k, k] where k is (1 + sqrt(1 + 8 * n)) / 2 """ n = vec.shape[-1] triu_shape = vec.shape + ...
8c5af1ad5089614280c048a84c572c04a958369e
49,826
import zlib import base64 def _compress(s: bytes): """ Compresses bytes for the payload. """ co = zlib.compressobj(wbits=-zlib.MAX_WBITS) b = co.compress(s) + co.flush() return base64.b64encode(''.join(map(chr, b)).encode())
6c6f1b04670c55f0417991fd3f9ab19ad42fefec
49,827
def render_Board_members_list_overlay(self, h, comp, *args): """Overlay to list all members""" h << h.h2(_('All members')) with h.form: with h.div(class_="members"): h << [m.on_answer(self.handle_event, comp).render(h) for m in self.all_members] return h.root
b818413dd28bac3043e1b83b83b1d7abf07416f3
49,828
def _token_to_int(t, token_list, token_cache, size_limit=float('inf')): """Return the int which represents a token, with caching. Throws a ValueError if token t is not in the token_list. There MUST be a _UNK token at the beginning of your vocab, or this may not halt. """ if t not in token_cache: ...
d2a46135197c38ff6ab08336fba9a4970fe6952f
49,829
def select_data(df, countries_list, regions_list, ages_list, genders_list): """Extracts from the dataset the data corresponding to many criterias. Parameters: ----------- df : Pandas DataFrame dataset countries_list : list of str countries to be selected regions_list : ...
de6e24966f3060728657a4cc6685c8203bfa85e7
49,831
def revescape(text): """Any text. Escapes all "special" characters, except @. Forward slashes are escaped twice to prevent web servers from prematurely unescaping them. For example, "@foo bar/baz" becomes "@foo%20bar%252Fbaz". """ return urlreq.quote(text, safe=b'/@').replace(b'/', b'%252F')
227f420bb6f6c625f5f3b9be2d8142240a2c726d
49,832
from typing import cast def intersect1d(pda1 : pdarray, pda2 : pdarray, assume_unique : bool=False) -> pdarray: """ Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ---------- pda1 : pda...
8062173a51ecbec1933787de94e451c9f668165f
49,833
import re import io def _remove_unicode_encoding(xml_file): """ attempts to remove the "encoding='unicode'" from an xml file as lxml does not support that on a windows node currently see issue #38100 (Search.adml) For some reason this file is encoded 'utf-16' """ with salt.utils.files.fo...
b40cf886dca7932ccfeb75738d4ced2db6909bea
49,834
def add_data_reference(enc_key, enc_data): """Add DataReference to ``enc_data`` in ReferenceList of ``enc_key``. ``enc_data`` should be an EncryptedData node; ``enc_key`` an EncryptedKey node. Add a wsu:Id attribute to the EncryptedData if it doesn't already have one, so the EncryptedKey's URI att...
7d3d9cfabe9a645782ec58224a7824f7ec159fa8
49,835
from typing import Sequence from typing import Any from typing import List from typing import Dict def _get_items_as_rows(items_to_add: Sequence[Any], batch_number: int, result: str, operation: str, timestamp: str) -> List[Dict[str, Any]]: """Adds Content API results to...
70bc2976b0c47f7a66dea472599ba54a60702268
49,836
from ba import _error def get_available_purchase_count(tab: str = None) -> int: """(internal)""" try: if _ba.get_account_state() != 'signed_in': return 0 count = 0 our_tickets = _ba.get_account_ticket_count() store_data = get_store_layout() if tab is not Non...
1b0d6afc0b9ba6a5d7ace211082d63dccefe8cae
49,838
def textops_rawtexttolines(text, linedelimiter="\n"): """ <Purpose> Converts raw text (a string) into lines that can be processed by the functions in this module. <Arguments> text: The text to convert into lines (basically, a sequence of strings). linedelimiter (optional, defaults to...
e146180f3dc02a036e84cbb04b5a4fd90b85abe8
49,839
import re def get_display_name(skill_name: str): """Splits camelcase and removes leading/trailing "skill".""" skill_name = skill_name.replace("_", " ").replace("-", " ") skill_name = re.sub(r'(^[Ss]kill|[Ss]kill$)', '', skill_name) return camel_case_split(skill_name).title().strip()
8e0cbfde49b6b6d7568084711bea31b7c75af05f
49,840
import pathlib from typing import Tuple def generate_images(*, path: pathlib.Path) -> Tuple[files.File, ...]: """ Get the assets images to create. Args: path: the destination path for the images. Returns: A tuple of the images to create. """ images = assets.get_images() r...
72ca85feaf1dbe1fdb6128b194683d7e46f0a260
49,841
from datetime import datetime def timestamp2datetime(value): """ 将一个时间戳值转换为系统所在时区的日期时间实例 """ return timezone.make_aware(datetime.fromtimestamp(value))
e4fd2eaf7c8404ee0d1c9f817ebbcc0c2367d22e
49,842
from typing import List def generate_eagle_track( conductivity: np.ndarray, potential: np.ndarray, start_loc: List[int], dirn_restrict: int, nu_par: float ): """ Generate an eagle track """ num_rows, num_cols = conductivity.shape burnin = 200 max_moves = num_ro...
47a82e40ca85031c93b37999fdf75558fbb6eb0e
49,843
def _expm_vjp(exp_matrix, matrix): """ Construct the left-multiplying vector jacobian product function for the matrix exponential. Intuition: `dfinal_dexpm` is the jacobian of `final` with respect to each element `expmij` of `exp_matrix`. `final` is the output of the first function in the b...
f2e75e92aa0877bab8788015f079d58ba07e5fa0
49,844
def precook(s, n=4, out=False): """ Takes a string as input and returns an object that can be given to either cook_refs or cook_test. This is optional: cook_refs and cook_test can take string arguments as well. :param s: string : sentence to be converted into ngrams :param n: int : number of ...
72d75158a21ae84b9c76ef09663a1db866821c9e
49,845
def motorcycle_data(): """ The motorcycle dataset where the targets are normalised to zero mean and unit variance. Returns a tuple of input features with shape [N, 1] and corresponding targets with shape [N, 1]. """ df = pd.read_csv("./data/motor.csv", index_col=0) X, Y = df["times"].values.resh...
07312be5992029aa5bdd8951ba257944ce4b6f45
49,846
def get_class_distribution(y): """Calculate number of samples per class.""" # y_cls can be one of [OH label, index of class, class label name string] # convert OH to index of class y_cls = flatten_y_if_onehot(y) # y_cls can be one of [index of class, class label name] classset = sorted(list(set(...
2005c17361d971dbb5f04e767fe6896c7cea1d0e
49,847
from re import S def gamma_at_2_coefficient(k): """Reference: https://dlmf.nist.gov/5.7#E3""" if k == 0: return S(0) elif k == 1: return S(1 + digamma(1)) else: return ((-1)**k*(zeta(k) - 1)/k)
4779e30a55ea0a90a501b8f6db1df141e7fe3f2f
49,848
def unverified_user(error): """Displays the front page with an error that the user must verify their email before accessing data. """ messages = { "Email Unverified": [ "Please complete the sign up process by verifying your " "email account. You should receive a verificat...
a1127547f0d7bcf08a63f67f42c07170a04c8ecf
49,850
import torch def initialize_sampler_lp_(g, batch_size, args, target_idx, evaluate_panrep =False): """ When lp is used different loader is required """ full_node_list = torch.arange(g.number_of_nodes()) target_uns = torch.arange(g.number_of_nodes()) val_pct = 0.1 use_cuda = args.gpu >= 0 and torch...
15c86f3057b1099195dd873e6fecbe4fd840fae7
49,851