content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def random_type(): """Return type of monster.""" types = ( ('Slime'), ('Skeleton'), ('Zombie'), ('Blue Wizard'), ('Red Wizard'), ('Bear'), ('Wolf'), ('Barbarian'), ('Minotaur'), ('Goblin'), ('Ogre'), ) return choice(...
c3801b9446bfae34d09952904c31641beed87bec
54,370
def get_ip(server, net_type, ip_version): """Return the server's IP of the given type and version.""" if net_type in server.addresses: for ip in server.addresses[net_type]: if ip['version'] == ip_version: return ip['addr']
a8b983fb27ed01f5a76aab3f0e8a345f0273e153
54,371
import random import torch def random_crop(image, boxes, labels): """ Performs a random crop operation with multiple possibilities as in the paper. Helpful when detecting bigger objects(windows, doors, buildings). Ref: https://github.com/amdegroot/ssd.pytorch/blob/master/utils/augmentations.py ""...
a6afd940af21206cae367b4b96a95ce1a0992874
54,372
from sklearn.impute import IterativeImputer from sklearn.ensemble import RandomForestRegressor from sklearn.preprocessing import LabelEncoder from sklearn.neighbors import KNeighborsRegressor def impute_missing_values(data, verbose: int, estimator): """Imputation of missing values using the IterativeImputer metho...
7fd741a258073cae3e6b2b2676dd11a774dcc0ec
54,373
def service_http_delete(request, application_id, service_http_id): """ Delete service model """ service = get_object_or_404(HTTPCodeService, pk=service_http_id) service.service.delete() return redirect(reverse('project', args=[application_id]))
bc820603161a537a7e0d2444249ceab65e3869dd
54,374
from app.shortener import shortener def create_app(config): """ Flask application factory to create the app object. """ app = Flask(__name__) app.config.from_object(config) db.init_app(app) app.register_blueprint(shortener) return app
8464e6bce15bc929ab10e8f3a6534fcc669b32f6
54,375
from bs4 import BeautifulSoup import re import pytz from datetime import datetime def ilmaandmed_veebist(dt_utc): """ Tagastab etteantud ajahetke (dt_utc) viimase möödunud täistunni ilmaandmed ilmateenistus.ee veebilehelt """ jaam = 'Valga' cols = ['airtemperature', 'relativehumidi...
182615fb52a067d8daa14e0255c0784fa64b29bb
54,377
def set_value(obj, value): """ 设置固定数值 :param value: 数值 :return: 数值 """ return value
1ecb69bebb841a8a36d752544560f87d95f07c5f
54,378
def AddSliceTag(slicename, key, value, node, nodegroup): """ AddSliceTag() calls s.api.AddSliceTag() with the correct set of arguments. Args: slicename - string slicename i.e. "iupui_ndt" key - the slice tag name, i.e. "vsys" value - the value for the slice tag, i.e. "web...
3c7884724d6b4a14ab4b488113d7d65e2bde89d4
54,379
def initialize_all(y0, t0, t1, n): """ An initialization routine for the different ODE solving methods in the lab. This initializes Y, T, and h. """ if isinstance(y0, np.ndarray): Y = np.empty((n, y0.size),dtype=complex).squeeze() else: Y = np.empty(n,dtype=complex) Y[0] = y0 T = np.linspace(t0, t1, n) h =...
2a14fa5a8eceae1504a5d2cc69b57306d6703b4b
54,380
import random import string def generate_points(num_points): """ :param num_points: an integer, the number of data points :return: """ points = [Point() for _ in range(num_points)] vmin, vmax = 100, 0 for p in points: vector = np.random.choice(list(range(1000)), 2) word = '...
f2e220ebc3b2d651009b6c93758172596ad358f6
54,381
def camel_shuffle(sequence): """ Inspired by https://stackoverflow.com/q/42549212/610569 >>> list(range(12)) # Linear. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> camel_shuffle(list(range(12))) # M-shape. [0, 4, 8, 9, 5, 1, 2, 6, 10, 11, 7, 3] >>> camel_shuffle(list(rev...
710e8b1fd626019e2af8cac1f2ecdb295dbef022
54,382
def random_date(start, end, prop): """ get random date between start and end """ return str_time_prop(start, end, '%Y-%m-%d %I:%M:%S', prop)
423815406e9b5522e971bbaefcada3596c99b5bf
54,383
def calc_distances(x, targets): """ within and between class distances """ def c_s(l): l.sort() s, r = 0, 0 n = len(l) for i in range(n - 1): s += l[i] r += 2 * (n - i - 1) * l[i] s += l[-1] return (n - 1) * s - r within_class = 0 for y, inclass_x ...
079c7085bb275b905b7342cfca98db074f801c53
54,384
def check_symmetry_and_dim(number, dim=3): """ check if it is a valid number for the given symmetry Args: number: int dim: 0, 1, 2, 3 """ valid = True msg = 'This is a valid group number' numbers = [56, 75, 80, 230] if dim not in [0, 1, 2, 3]: msg = "invalid...
1097eb78dbd58f0e164ae5f10fdc9f88a3c00ccc
54,385
import _json def merge_layers(input_layer, merge_layer, merge_attributes=None, output_name=None, gis=None, context=None, future=False): """ .. image:: _static/images/merge_layers/merge_layers.png ...
459db54a89fd30694e3ba248b0b52ce396f61b7e
54,386
def anonymous_required(redirect_url): """For views that allow only unauthenticated users to access view. Usage: @anonymous_required(redirect_url='company_info') def homepage(request): return render(request, 'homepage.html') """ def _wrapped(view_func, *args, **kwargs): def check...
b2cf7fe55cf16da320e1baa7ae9570ef708bb724
54,387
import collections def get_buffers(layer_instance, include_sublayer=True): """ Returns Variable buffers of decorated layers. If set `include_sublayer` True, the Variable buffers created in sub layers will be added. """ buffers = collections.OrderedDict() if layer_instance is not None: ...
01500c4692280e0db24aac442d274b66b8f08129
54,388
def user(): """ exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://.....
10c394bd3bd325ab2d7b9e996524d0f1a120de15
54,389
def pagerank(A, p=0.85, personalize=None, reverse=False): """ Calculates PageRank given a csr graph Inputs: ------- G: a csr graph. p: damping factor personlize: if not None, should be an array with the size of the nodes containing probability distributions. It wi...
7400dc7a85871ed90671621158f7c662b4bb2e67
54,390
def create_transforms(input_config): """Create transforms from configuration Parameters ---------- input_config : dict Dictionary containing the configuration options for input pre-processing. Returns ------- train_transforms : list List of transforms to be applied to the i...
5e5e40d3df048c9d8f9701c5b413af431497273b
54,391
from typing import Optional from typing import List from typing import Literal from typing import Dict from typing import Callable import inspect def pulse_diagram_plotly( schedule: Schedule, port_list: Optional[List[str]] = None, fig_ch_height: float = 300, fig_width: float = 1000, modulation: Li...
6e977f8a6be9e527f68ccdf0263df349fa251247
54,392
def unbiased_std_factor(n): """ Returns 1/c4(n) """ if is_arraylike(n): wh = n < 343 ans = np.ones(np.shape(n)) * (4. * n - 3.) / (4. * n - 4.) n = n[wh] ans[wh] = spec.gamma((n - 1) / 2) / np.sqrt(2 / (n - 1)) / spec.gamma(n / 2) return ans else: ans...
dea4e8670ebefe8f9e3139ee84061def8a8354ae
54,393
def _ion_number_density(field, data): """ Creates the function for a derived field for following the number_density of an ion over a dataset given that the specified ion's ion_fraction field exists in the dataset. """ if isinstance(field.name, tuple): ftype = field.name[0] field_...
e049c55c92df3afa65f5554f05cfd4241751ee62
54,395
def normalize_by_population(tidy_df): """ Normalize by population the column "value" of a dataframe with lines being the country ISO """ pop = get_populations() normalized_values = (tidy_df.set_index('iso')['value'] / pop.set_index('ISO3')['Population']) # NAs appea...
3257178aa4071820946715593bb84524c398f2bf
54,396
def _hex_to_int(input: str) -> int: """Given a hex string representing bytes, returns an int.""" valid_bytes = input[1:] if (len(input) % 2 != 0 and input[0] == "0") else input hex_bytes = bytes.fromhex(valid_bytes) return int.from_bytes(hex_bytes, BYTE_ORDER)
79c5d5505a72c825722996458f43f503438bfb62
54,397
async def update_objects_by_id(model, conn, obj_id_list, data: dict) -> int: """Массовое обновление объектов в БД. Args: model (Table): обновляемая модель (таблица) в БД. conn (SAConnection): открытое соединение с БД. obj_id_list (list of int or int): список идентификаторов ...
e433f17b700770a2fee0927ce7c8c5e170d13e23
54,399
def annotate_heatmap(im, data=None, valfmt="{x:.2f}", textcolors=["white", "white"], threshold=None, **textkw): """ A function to annotate a heatmap. Arguments: im : The AxesImage to be labeled. Optional arguments: data : Data used...
36febdab90f9a243bab02739ad2ad62cee3d1d21
54,400
def build_attention_mask_3d_causal(source_mask, target_mask): """ Returns a 3D joint attention mask for Megatron given two 2D masks :param source_mask - True for non-masked, else masked [batch, src length] :param target_mask - True for non-masked, else masked [batch, tgt length] """ causal_mask ...
145014389519267eac49f287c260cac5c920d3c7
54,401
def get_run_list(filter_=None, page=1, page_size=25): """Get a list of runs The `filter` parameter takes a list of filters to apply in the form of: {name}{operator}{value} where: - `name` is any valid column in the database - `operator` is one of `=`, `!`, `>`, `<`, `)`, `(`, `~`, `*...
2178112de82e527d77ab31c6965b95cdcec68ef5
54,402
def split_timesteps(inputs): """Split the input matrix from (batch, timesteps, input_dim) to a step list ([[batch, input_dim], ..., ]).""" timesteps = inputs.get_shape()[1].value feature_dims = inputs.get_shape()[2].value inputs = tf.transpose(inputs, [1, 0, 2]) inputs = tf.reshape(inputs, [-1, feat...
bfe26243aa1b9443e39c6e377cb5dec2cdf17560
54,403
import torch def get_all_dists(x, y): """Get L2 distance of x from each item in y.""" return torch.sqrt(torch.sum(torch.pow(x - y, 2), 1))
9c54cdd1887b71e872b240e87cf12cc5df9abb1e
54,404
def get_xml_tail(full_xml_ordered_dict): """Get xml tail""" xml_tail = get_rpc_tail(full_xml_ordered_dict) return xml_tail
6edc992eac813117275d223385f777b80016c3d1
54,405
def IPRange(Range, range_temp, language): """ IP range string to IPNetwork type Args: Range: IP range string range_temp: range_temp filename language: language Returns: an array of IP range in IPNetwork type """ myranges_now = open(range_temp).read().rsplit() ...
e01ecbdb3a8701d8fd70d3e5a37dafd45fcfd5dd
54,406
def api_get_user_modelling_units_results(userModellingUnitId, period, divider): """ { "doc": { "title": "user modelling units results help", "body": "<p> Obtain the user modelling units results </p>" }, "GET": { "label": "Obtain the user modelling unit...
04e7e57b3946a0e7a420fef9b23a4878b1f378ff
54,407
def test_writer_precision_nano_fail(): """if writer is not set to nano, supplying this timestamp should be truncated""" ts, pkt = (Decimal('1454725786.010203045'), b'foo') writer.writepkt(pkt, ts=ts) # noqa return [(1454725786.010203, pkt)]
3b170e10b1b49f9c56a4ce7f4716777aafd32dc0
54,408
def _get_suggestions_index(name): """Returns suggestions index name for a regular index name.""" return f'df_suggestions_{name}'
4cd2294e89f05dfbefe65ff4604c43818880d6c9
54,409
def draw_rois( im, notebook_url="localhost:8888", table_height=100, crosshair_tool_alpha=0.5, color="white", fill_alpha=0.1, vertex_color="red", vertex_size=10, cmap=None, frame_height=400, frame_width=None, length_units="pixels", interpixel_distance=1.0, x_range=...
3b054e5b0e6fc4449029d8cb7fe56dd823301c57
54,411
def boxplot(data1, data2=None, width=0.75, whiskers=1.5, axesAdjust=True, axes=None): """ boxplot(*args, width=0.75, whiskers=1.5, axesAdjust=True, axes=None) Create a box and whisker plot and returns a BoxPlot wobject that can be used to change the appearance of the boxes (such as color). If ...
9e5b3ef14fcf78ec6e8ef1001b9f5b29e9c8586c
54,412
import json def add_config(request): """ 新增配置 :param request: :return: """ account = request.session["now_account"] if request.is_ajax(): testconfig_info = json.loads(request.body.decode('utf-8')) msg = config_info_logic(**testconfig_info) return HttpResponse(get_aj...
719318e36a9b3f398470dae39b9127fcd88b20c4
54,414
def get_scene_index(glTF, name): """ Return the scene index in the glTF array. """ if glTF.get('scenes') is None: return -1 index = 0 for scene in glTF['scenes']: if scene['name'] == name: return index index += 1 return -1
357365ea60ea89630d942b13d0c3a26b49889488
54,415
def wifi_toggle_state(ad, new_state=None): """Toggles the state of wifi. Args: ad: An AndroidDevice object. new_state: Wifi state to set to. If None, opposite of the current state. Returns: True if the toggle was successful, False otherwise. """ # Check if the new_state is ...
0aa2ce4a02be1ad78707dd165d8bfa5652063eb7
54,416
def _preprocess_include(include): """ A utility function for processing the `include` input Parameters ---------- include : numpy.ndarray A list of (zero-based) indices corresponding to the dimensions in `T` that must be included in the constrained multidimensional motif search. ...
81498282d06e156569559705ca54131a2ce22f78
54,417
def get_storage(path=None, options=None): """ Get the specified storage configured with options. :param path: Path in Python dot style to module containing the storage class. If empty settings.DBBACKUP_STORAGE will be used. :type path: ``str`` :param options: Parameters for config...
4f91d193c53aaff49d95e5ae2fd2c1cb386bda60
54,418
def _ord_to_str(ordinal, weights): """Reverse function of _str_to_ord.""" chars = [] for weight in weights: if ordinal == 0: return "".join(chars) ordinal -= 1 index, ordinal = divmod(ordinal, weight) chars.append(_ALPHABET[index]) return "".join(chars)
33283d4e09ddaccbf1bff3f92904313d6c18de6c
54,421
def aws(flox: Flox, args, **kwargs): """awscli command wrapper with session credentials provider""" command_name = next(iter(args), None) if command_name == "console": args = list(args) with EmptyContext(flox, console, args[1:], allow_interspersed_args=True, ignore_unknown_options=True) as ...
eba7e1151c69be603d56930b35b392f1205f9864
54,422
def is_inactive_link(node_status_at_link): """Find links that are inactive. A link is inactive if it connects two boundary nodes or one of its nodes is closed. Parameters ---------- node_status_at_link : ndarray of int, shape `(n_links, 2)` Node status a link tail and head. Return...
fcf9a318029968da714c76adc6f1a981b99479dc
54,423
def found_value(gpio_value): """checks if the gpio value entered in command line is supported and return the corresponding value""" if gpio_value in common.gpio_supported_values: if common.gpio_supported_values[gpio_value] == 0 or common.gpio_supported_values[gpio_value] == 1: return common....
533f25138a724bc7ab355f30d365524b5f4db4e2
54,425
def scrape_html_table(bs_table, f = lambda tags_list, index : list( map(lambda tag: tag.string, tags_list) )): """ Returns a nested list based on the contents of the table html = \"\"\"<table class="formulario"> <tr> <td class="very important stuff">Hotel</td> <td>Trivago</t...
3639a9691f25333c59ec2a4613123ad3b568d7bd
54,426
def calculate_immediate_post_dominators(nodes, _pdom, _spdom): """ Calculate immediate post dominators for all nodes. Do this by choosing n from spdom(x) such that pdom(n) == spdom(x). """ _ipdom = {} for node in nodes: if _spdom[node]: for x in _spdom[node]: i...
17fb44a47a440c8c93f58262132ab0f65a9566a5
54,427
from typing import Dict def validate_runner_claims(claims: Dict): """ Validate claims required for runner to function""" runner_metadata_schema = RunnerMetadataSchema(unknown=EXCLUDE) return runner_metadata_schema.load(claims)
e02a3101cc03a0858716dff71a87d21c416d918b
54,429
def repay_margin(order_id, amount): """ :param order_id: :param amount: :return: """ params = {"order-id": order_id, "amount": amount} url = "/v1/margin/orders/{0}/repay".format(order_id) return api_key_post(params, url)
da47b9d24d5ea8d713afa8149c05fa500b655067
54,430
def clinvar_track(build, chrom): """Return a dictionary consisting in the clinVar snvs track Accepts: build(str): "37" or "38" chrom(str) Returns: clinvar_track(dict) """ clinvar_track = { "name": "ClinVar", "type": "annotation", "sourceType": "file...
fb7d090fce2a4c9f23f0347ddb59d613e9c41876
54,431
import random def calc_batch_loss(batch, teacher_forcing=1): """ Calculate the loss for given batch of data :param batch: batch of data. :param teacher_forcing: (float, default=1) rate of teacher forcing :return: loss tensor """ x, x_len = batch.text data = x[:-1].clone() target = ...
2d3d7d4b946c59bef9720e814a827db65836234d
54,432
import click def attach(config, model): """ Attach to model and show creation logs. MODEL may be specified by name or ID, but ID is preferred. """ models = config.trainml.run(config.trainml.client.models.list()) found = search_by_id_name(model, models) if None is found: raise cli...
075f76a5bdbfd102f7d83d80837d72c8ca78202f
54,433
import torch def cg_solve(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10, x_init=None): """ Goal: Solve Ax=b equivalent to minimizing f(x) = 1/2 x^T A x - x^T b Assumption: A is PSD, no damping term is used here (must be damped externally in f_Ax) Algorithm template from wikipe...
89cbff54d1107abb02ddfb5c095d12af7744f2bb
54,434
def parang (hourangle, declination, latitude): """Calculate the parallactic angle of a sky position. This computes the parallactic angle of a sky position expressed in terms of an hour angle and declination. Arguments: hourangle The hour angle of the location on the sky. declination Th...
09c4df4119e1b91dfa25372d9746e5fc0b7561fa
54,435
def dataset(params): """ The input batch generator. """ with tf.name_scope("dataset"): def sample(): input_mean = tf.constant(params.input_mean, dtype=tf.float32) input_stddev = tf.constant(params.input_stddev, dtype=tf.float32) count = len(params.input_mean) ...
c2a9c20261fd82bc5498bddb7b843394428eeddf
54,436
def frac_diff_ffd(data: pd.Series, d: float, threshold=1e-5, parallel=False): """ Fractionally Differentiated Features Fixed Window :param data: data :param d: difference coefficient :param threshold: threshold :param parallel: run in parallel """ if isinstance(data.index, pd.MultiIndex)...
31f0f796547a1447d1545255ffe32202ca25927a
54,437
def SetIamPolicy(taxonomy_id, policy): """Sets IAM policy, for a given taxonomy. Args: taxonomy_id: Id of the taxonomy. policy: An IamPolicy message. Returns: An IamPolicy message. """ messages = utils.GetMessagesModule() return _GetService().SetIamPolicy( messages.DatapolTaxonomyStoresD...
6f4e82d009700c008a71e4c2fc40dd3524e41743
54,439
def format_committer(input_row: dict) -> tuple: """Format a committer row form commit input_row.""" return format_contributor(input_row, CONTRIBUTOR_TYPE_COMMITTER)
a091492fab2a0305972eb9d19e69b7ad46be601d
54,440
async def about(request): """Renders the About page.""" return templates.TemplateResponse("about.html", {"request": request})
af066e26770c1b08f63254ba9122e1fa633d84e5
54,441
def investigateTreesAndAlignments(d, srcSIndex, tgtSIndex): """ Return the parse trees and word alignments for this pair of source sentence and target sentence indices """ src = d.sentence(srcSIndex) tgt = d.highlight(tgtSIndex) # get matchList, and trim so it is only leaf nodes ma...
f70b935ee5c97259f7e62a9196df829871e8219a
54,442
def build_faces(structure, template, vertex_list, target, fill_uncompleted='border'): """ Creates the faces :param structure: row[]: column[]; cell[]: vertex: int - inner mesh structure :param template: RFTemplate - template :param vertex_list: VertexData[] - created vertex :param target: RFTarg...
484bcb29c94213b00716be7e93e519d13952441b
54,443
import struct def read(filename, include_fourcc=False): """Reads a LAB container and returns all stored files. :param filename: Path to the LAB to read :return: List of LAB entry tuples [(str, bytes), ..., ] where the tuple represents (name, data) of the entry """ # Utility function for reading n...
316b115a47e6acbf39a8d21edac3320e27f5b12c
54,444
def gf_sub_const(f, a, p): """Returns f - a where f in GF(p)[x] and a in GF(p). """ if not f: a = -a % p else: a = (f[-1] - a) % p if len(f) > 1: return f[:-1] + [a] if not a: return [] else: return [a]
93d4c8611aac77d1cf1da891ca8e72db5612b28a
54,445
def replace_jax_res_net_block_vars_to_tf( jax_initial_vars: NestedMap) -> NestedMap: """Replaces the JAX ResNetBlock vars to TF compatible vars. Args: jax_initial_vars: JAX ResNetBlock vars. Returns: tf_initial_vars which is TF compatible with ResNetBlock. """ tf_initial_vars = jax_initial_vars....
20c8cfec6cad1aa3639902af5cee43f6453f4e34
54,446
import re def install_transproteomic_pipeline(env): """ """ ## version should be of form X.X.X-codename default_version = "4.6.1-occupy" version = env.get("tool_version", default_version) version_parts = re.match("(\d\.\d)\.(\d)-(.*)", version) major_version = version_parts.group(1) re...
27146ce5105ef9da4d95c6f63112fcdfff813c6d
54,447
def assemble_SHCNN_blocks(inputs, config, dropout_prob, hw, mw, lw, hw2, mw2, lw2, h2m, m2l): """ Definition of all the layers according to config :param inputs: dictionary of inputs with keys [points, neighbors, pools, upsamples, features, batches, labels] :param config: :param dropout_prob: :r...
9cc79ee44e4f3adc4bd0bbff2a4066531fc7f789
54,449
import torch def sample_with_temperature(logits, sampling_temp, keep_topk, keep_topp): """Select next tokens randomly from the top k possible next tokens. Samples from a categorical distribution over the ``keep_topk`` words using the category probabilities ``logits / sampling_temp``. Args: l...
aa2dcf6e6584923a7e1ac8c091d5c832c6bf7b5e
54,450
import torch def get_mask_from_lengths(lengths): """Constructs binary mask from a 1D torch tensor of input lengths Args: lengths (torch.tensor): 1D tensor Returns: mask (torch.tensor): num_sequences x max_length x 1 binary tensor """ max_len = torch.max(lengths).item() ids = t...
508f7425b03fc3a0b52be45bcb5632150b809bfb
54,451
def fixed_ro_bci_edge_small_angle(ascentlat, lat_fixed_ro_ann=None, burg_num=None, ross_num=None, delta_v=None, height=HEIGHT_TROPO, grav=GRAV_EARTH, rot_rate=ROT_RATE_EARTH, radius=RAD_EARTH): """Small-angle solut...
6873656f5f88a51ac0ba6108aa0ffe3c429a0cf3
54,453
def veclength(vec): """Returns the length of the given vector(s). Multiple vectors may be passed in, with a shape of ``(n, 3)``. """ vec = np.array(vec, copy=False).reshape(-1, 3) return np.sqrt(np.einsum('ij,ij->i', vec, vec))
cfad654c1364217a5620ae360817cd97d697f6d0
54,454
from typing import List def get_guardian(day: date, holiday_list: List[List[date]]) -> str: """Get the guardian for a day, according to the holidays.""" if is_father_day(day): return "B" if is_mother_day(day): return "L" if day_is_holiday(day, holiday_list): return get_guardian...
d99debe9dbfad6ed3e3a6036c7885e0f00684a16
54,455
def add_two_polynomials(polynomial_1: list, polynomial_2: list) -> list: """ This function expects two `polynomials` and returns a `polynomial` that contains their `sum`. :param polynomial_1: First polynomial :param polynomial_2: Second polynomial :return: A polynomial representing the sum of t...
e2fed8be5f35f1c306b78b69c608f90668aeb2f1
54,456
import torch def mediane(x, y=None): """ Computes the median """ if (isinstance(x, np.ndarray)): x = torch.from_numpy(x) if (isinstance(y, np.ndarray)): y = torch.from_numpy(y) dxx = distances(x) if y == None: return dxx.median() dyy = distances(y) dxy...
d622d9fd54e26abb124b3f675e510f779c5b6ea0
54,457
import torch def train_loop(model, epochs, loss_fn, train_dl, valid_dl, use_gpu=False, lr=0.01): """ Loop between training and validation cycles through n epochs :param model: pytorch model :param epochs: number of epochs :param loss_fn: loss function :param train_dl: pytorch dataloder on top ...
fafaa8ee5cccffe07b237bcc64efc1b5ac29d7af
54,458
import functools def ajax_required(fn): """ Placed on a view, this decorator will raise :class:`django.http.Http404` if the incoming request is not an HTTP POST or if the header `HTTP_X_REQUESTED_WITH` is not set. """ @functools.wraps(fn) def wrapper(request, *args, **kwargs): if ...
9171a146fa499414ca3fceed2e3ee3c022aaae3a
54,459
from typing import List from typing import Tuple import torch from typing import Dict import time import itertools import tqdm def read_images(data_packs: List[matchzoo.DataPack], fat_pth_file: str, max_len_images: int, side, image_dim: int = 2048) -> Tuple[torch.Tensor, Dict, Dict]: """ - Pru...
a91048ad9f81d3e645d8b220148f42cd4496e391
54,460
import torch def mmd_gaussian(samples1, samples2, sigma=10.0): """ MMD constraint with Gaussian Kernel support matching in BEAR This code was stolen from: https://github.com/aviralkumar2907/BEAR/blob/master/algos.py sigma is set to 10.0 for hopper, cheetah and 20 for walker/ant """ # Batch x ...
9b81c1e4d2999e89521d935d5950121bb2d4608f
54,462
def DefaultKeyWriter(key_name): """This key writer rewrites keys as lower camel case. Expects that the input is formed by '_' delimited words. Args: key_name: Name of the key to serialize. Returns: Key name in lower camel-cased form. """ return ToLowerCamelCase(key_name)
c7ed1bda0ce5ccc1e061ce4b1e39fe06c59ed53f
54,463
def get_random_orthonormal_vector(base_vector: ParameterVector) -> ParameterVector: """Helper function to generate a random orthogonal vector with respect to a provided base vector.""" random_vector = np.random.normal(size=base_vector.shape) new_vector = ( random_vector - np.dot(random_v...
cf111f088d13a14f4cabc9eeb0e16a62bdc26aaf
54,465
def PUtilVisCompare (in1UV, in2UV, err): """ Compares the visibilites in *in1UV* with those in *in2UV*. * return: RMS ( real, imaginary differences / amplitude of *inUV2* ) * in1UV = Numerator Python UV object. Possible infoList parameter printRat scalar float if given and >0.0 then tell a...
de362477189c9760185972e693199bf9684febac
54,466
def normalize(vec: DSList): """ Normalize the input vector. :param vec: DSList :return: DSList """ norm_ = norm(vec) return smul(1/norm_, vec)
1011bd68f91d780ecd984e7bfd6ba0e9c786415a
54,467
def distro_name_errors(distro_name): """Returns a list of errors in the distro name. Empty list means distro name is valid.""" errors = [] if len(distro_name) == 0: errors.append( "distro name cannot be zero length") if distro_name.startswith(defaults['catalog_prev_distro_pref...
905da831ac82605295db81f3a54e41d2a76800a7
54,469
from math import sqrt def prime_def(num): """ Поиск максимального простого делителея числа :param num: :return: """ prime_set = set(range(1, num + 1)) #print(prime_set) for i in range (2, int(sqrt(num))): if i in prime_set: prime_set -= set(range(2*i, num + 1, i)) ...
619a4310dd9540e8354143fa2871ceddb78b4237
54,470
def dict_from_two_lists(keys: list, values: list): """Creates a dictionary from a list of keys and a list of values. Examples: >>> keys = ('bztar', 'gztar', 'tar', 'xztar', 'zip')\n >>> values = ('.tbz2', '.tgz', '.tar', '.txz', '.zip')\n >>> newdict = dict_from_two_lists(keys, values)\...
3865a8e5a890dc00e69ea3feafc161f8617697ff
54,471
def hashable_index(tuple_idx): """Return an hashable representation of a tuple of slice object We add this because the slice object in python is not hashable. Parameters ---------- tuple_idx : tuple A tuple of slice/int objects Returns ------- ret : tuple A hashable re...
e83d4db426053cc64f9ffda3b938bb85395e4741
54,472
def add_new_entry(): """ Add IP details for the current user in Airtable :return: True """ table.create(build_data_new()) return True
54ab17dfaeaf8c1dc46885341d1db67e8c2981a3
54,473
def encode_single_dataframe(dataframe: pd.DataFrame, f, types: dict=None, column_order: list=None, bigendian: bool=False, properties: dict=None): """ :param dataframe: A pandas dataframe to encode :param f: A file-like object to write the encoded data to :param columns: A dic...
23e96b89b67f4cbad9e2e1eb6a55c32eb9f46d3f
54,475
from typing import Dict def rms_combine(signals, weights = None, days = 1024, max_leverage = 5, join = 'outer', method = 'ffill'): """ >>> dt1 = drange(2000,2020, '1b') >>> sig1 = pd.DataFrame(ewmxo(np.random.normal(0,1,(len(dt1),10)), 18, 54, vol = 30) , dt1) >>> sig2 = pd.DataFrame(ewmxo(np.random.n...
34b2dd5819dcd28c99cb4b5716b3a455747e8014
54,476
def get_output_type(name: str) -> OutputType: """Fetches a previously registered OutputType by name""" if name in OUTPUT_TYPES: return OUTPUT_TYPES[name] else: raise ValueError('The output type %s is unknown' % name)
65f4f91fb28c39576241f72bb385442301a89407
54,477
def prepare_for_parsing(multinet): """ Compute layout for a hairball visualization Args: param1 (obj): multilayer object Returns: tuple: (names, prepared network) """ layers = defaultdict(list) for node in multinet.nodes(data=True): try: layers[node[0...
b0e97223bcd832c69d1e76ee722e934a8d27f852
54,478
import typing def peek(nbytes=0) -> typing.Generator[_Action, Buffer, bytes]: """Read output without consuming it. Read but **does not** consume data from the protocol input. This is a *non-blocking* primitive, if less data than requested is available, less data is returned. It is meant to be used i...
c3112858d8f37122d2c81f5f3c2cbafb853056a7
54,479
def get_func_prototype_from_man(func): """ Parse "man func" output and return the function prototype. :param func: function name :returns the function prototype as a string. If not found, returns empty string. """ if func in g_prototype_db: return g_prototype_db[func] man_output = ge...
f79888d6d79332b536007ab1c9c9a6939819fe7b
54,481
from typing import Tuple from typing import List from typing import Dict from typing import Any import torch def train_gcn( dgl_tuple: Tuple[List[DGLHeteroGraph], dict], params: Dict[str, Any] ) -> Model: """ Trains a GCN model """ epochs: int = params["epochs"] hidden_features: int = params["...
4b52af7666f2fffd73e4c495002bea5183027b6d
54,482
from typing import List from typing import Union from typing import Any from typing import Type def check_tied_units( all_t2_units: List[T2Compute], first_pass_config: Union[FirstPassConfig, dict[str,Any]] ) -> None: """ :raises: ValueError if tied t2 units are present in t2_units but the requred t2 units ar...
4b10b864e120a4f91e4c43b486a1a37f40f16b91
54,483
def create_procgen_env(config, instance_seed, instance): """ Creates a procgen environment and applies recommended wrappers. """ procgen_args = {k[8:]: v for k, v in vars(config).items() if k.startswith('procgen_')} procgen_args['start_level'] += 300_000*instance env = gym.make(f'procgen:procgen-{config...
d1bef874fe6b39ef4ae1495594329d6dbdab1705
54,485
def dedupe(items: list, only_neighbors: bool = False) -> list: """ Deduplicate a list while keeping order If only_neighbors is True, dedupe will only check neighboring values """ ret = [] for item in items: if (only_neighbors and ret and ret[-1] != item) or item not in ret: ...
2313667f10f1480cb82e63dcfd33f986ccabfd75
54,486
from typing import Union from typing import Tuple from typing import Optional def major7( base: Union[int, str, Tone, Note], duration: Union[Tuple[int, int], Signature, None] = None, velocity: Optional[float] = None ) -> Tuple[Note, Note, Note, Note]: """ Generates Major Seventh chord....
73c98ee43960e9815eee25f20c0e98c662a940f6
54,488