content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def asscalar(a):
"""
Convert an array of size 1 to its scalar equivalent.
Parameters
----------
a : ndarray
Input array.
Returns
-------
out : scalar
Scalar of size 1 array.
Examples
--------
>>> np.asscalar(np.array([24]))
>>> 24
"""
return a.... | 2cb363f5172a9466287970e83190926cde3ca58d | 617,649 |
def before_send(event, hint):
"""Don't log django.DisallowedHost errors in Sentry."""
if "log_record" in hint:
if hint["log_record"].name == "django.security.DisallowedHost":
return None
return event | 30d8cde0ebd7bac5e934e6665d3858d2e2f4306c | 617,650 |
import torch
def siamese_collate(batch):
"""
This collator is used in Jigsaw approach.
Input:
batch: Example
batch = [
{"data": [img1,], "label": [lbl1, ]}, #img1
{"data": [img2,], "label": [lbl2, ]}, #img2
.... | da4eeebed1c7dce8dcad4c72c6f324b7b5a4a4c9 | 617,652 |
def get_PerformanceCode(doc, trialid, code=True):
"""
Returns the performance of the monkey in the given trial either as code or
abbreviation.
Args:
doc (odml.doc.BaseDocument):
odML Document of reach-to-grasp project
trialid (int):
ID of wanted trial
cod... | 7158ff316ca0649315bb08e8e73abb1bb3f40b5c | 617,653 |
def seconds_to_string(seconds):
"""
Convert run seconds into string representation
:param seconds: Number of seconds
:type seconds: int
:return: String in the format of 'Xd Xh Xm Xs' based on the provided elapsed time
:rtype: string
"""
day = int(seconds // (24 * 3600))
time_mod = se... | fb76dbbf1643b7cf94cd102b71eaa6633c017392 | 617,654 |
def combine_text_columns(data_frame, to_drop):
"""
Helper function to convert all text rows of data_frame to single vector
"""
to_drop = set(to_drop) & set(data_frame.columns.tolist())
text_data = data_frame.drop(to_drop, axis=1)
text_data.fillna(' ', inplace=True)
return text_da... | fb7a62f9ae30d17acd1f7c03308778157e5329e3 | 617,660 |
def format_manufacturer(manufacturer):
"""Format a manufacturer for tweeting"""
if manufacturer.twitter_handle:
return f'@{manufacturer.twitter_handle}'
return manufacturer.name | 3e652c978d5f646edc779126a8075cd5397a3c2e | 617,666 |
def merge_dicts(*dicts,
filler = 0):
"""
=================================================================================================
merge_dicts(*dicts, filler)
This function takes an arbitrary number of dictionaries and merges them together. If a key is not
found in one o... | 3fbea382542a8bbe6dec74ba23dc52a4ae3281b1 | 617,667 |
def date_format_to_human(value):
"""
Convert Python format date to human.
Example:
>>> date_format_to_human('%Y-%m-%d')
YYYY-MM-DD
:param value: Date format example: %Y-%m
"""
maps = {
'%y': 'YY',
'%Y': 'YYYY',
'%m': 'MM',
'%d': 'DD',
}
f... | 4f646763016db1e5b161334dbc39ab06ae76e5f7 | 617,668 |
def get_property(data, key):
"""
Get a property, either from a JSON response dictionary or a dataclass.
"""
if isinstance(data, dict):
return data[key]
return getattr(data, key) | 32fc7264f39a25fe7febe53d9d3d7b998a80b15c | 617,675 |
def _code_range_to_set(code_range):
"""Converts a code range output by _parse_code_ranges to a set."""
characters = set()
for first, last, _ in code_range:
characters.update(range(first, last+1))
return characters | 3cb7c2771bec698241ae4d2ae103e4827493e40d | 617,676 |
def train_decorator(actor, *args, **kwargs):
"""Wrapping decorator for the train method."""
return actor.train(*args, **kwargs) | 3c67eef803239e5f54c3b8280e4654a4a8d39847 | 617,677 |
def get_grant_project_image_upload_path(instance, filename):
"""
Construct the upload path for an image for a ProjectGrant object.
"""
return str("grant-projects/{0}/{1}").format(instance.name, filename) | 7a829ab49319d27c447ba7344a7b43f77530b68e | 617,680 |
def _is_valid_image(image):
""" This function returns whether the given image contains a valid url.
"""
return image.url is not None | d0350b837bc4a08b61e86f0739e0e57ccd852b47 | 617,681 |
import re
def segment_data(data, regexp):
"""Splits the data string into segments that either match or do not match
the regular expression 'regexp'. Other than re.split() (or "".split()),
which leave out the separation string, the segments matching 'regexp'
are included in the result.
Args:
... | 2cd35292276d720f56e11d52e7089e79671d9e7d | 617,685 |
def toString(s):
"""
Formats a 2D list Sudoku puzzle into one line of integers
for easy writing to a file
"""
output = ""
for i in range(9):
for j in range(9):
output += str(s[i][j])
return output + "\n" | 359a1c2d49cceba5eef2ac9d9ec6907da4fedaed | 617,686 |
from typing import Dict
from typing import Any
from typing import Iterable
def filter_dict(d: Dict[str, Any], exclude: Iterable[str]) -> Dict[str, Any]:
"""Return a new dict with specified keys excluded from the original dict
Args:
d (dict): original dict
exclude (list): The keys that are exc... | 234b45d70eb8e0a9a1d66398aa541b2f874c49f5 | 617,687 |
def sign_to_int(signs):
"""
Convert a list to an integer.
[-1, 1, 1, -1], -> 0b0110 -> 6
"""
return int("".join('0' if x == -1 else '1' for x in signs),2) | 4810061e6d0494c541b2d6ca81b8ae574b860343 | 617,696 |
def int2hex(number):
"""Returns a string representation of the number as hex.
"""
return "%04X" % number | fe43dfa07cf955a671e0be6ca82abee42e236482 | 617,700 |
def get_prior_genes(fname):
"""Get the list of prior genes."""
with open(fname, 'rt') as fh:
genes = fh.read().strip().split('\n')
return genes | 3c723d98a7c992cb2b3cafd60d9fa1e0642dd0d2 | 617,701 |
import math
def LogBinomialCoef(n, k):
"""Computes the log of the binomial coefficient.
http://math.stackexchange.com/questions/64716/
approximating-the-logarithm-of-the-binomial-coefficient
n: number of trials
k: number of successes
Returns: float
"""
return n * math.log(n) - k * m... | 7b1074d3626e3eb58bb0ab2e4013c9a0a09b3940 | 617,704 |
import torch
def relative_to_abs(rel_traj, start_pos):
"""
Convert relative coordinates in 'natural' coordinates
Inputs:
- rel_traj: pytorch tensor of shape (seq_len, batch, 2)
- start_pos: pytorch tensor of shape (batch, 2)
Outputs:
- abs_traj: pytorch tensor of shape (seq_len, batch, 2)... | 35dbbc36384e4c68e8d40d35e0978d5776580c83 | 617,707 |
def pal_draw_condition_1(x_start, x_stop, y_start, y_stop):
"""
First draw condition of polygonal audience lines. Stop values are bigger
or equal to the start values
Parameters
----------
x_start : float
Start point on x-axis.
x_stop : float
Stop point on x-axis.
y_start... | 73c3b517e06e49e91e106f7bec22c4c36b56492c | 617,709 |
def parse_coco_categories(categories):
"""Parses the COCO categories list.
The returned ``classes`` contains all class IDs from ``[0, max_id]``,
inclusive.
Args:
categories: a dict of the form::
[
...
{
"id": 2,
... | c428161bfcf2ad36286ab2697f0ee078ae04d81d | 617,710 |
def reverse_words(s):
"""
Reverses order or words in string s.
"""
words = s.split()
words_reversed = words[::-1]
return ' '.join(words_reversed) | c8f9c0770b5bb29f621118f2be2bc1dd69d3b760 | 617,712 |
import requests
def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict:
"""
Given an 'isbn/0140328726', return book data from Open Library as a Python dict.
Given an '/authors/OL34184A', return authors data as a Python dict.
This code must work for olids with or without a leading slash ('/').... | cec0507cc91017aa65a17d1a421371c7721c2e68 | 617,713 |
def findInfectInFamily(tx, query, id):
"""
Method that executes the query to find the infected member of a family
:param tx: is the transaction
:param query: is the query to execute
:param id: is the id of the positive Person
"""
result = tx.run(query, id=id).data()
return result | d4eea3256b686ffeb120652869ba82ef74d3b306 | 617,716 |
def compute_max_firing_rate(spiketrains, runtime):
"""
Compute maximum firing rate
:param spiketrains: spike trains of neurins
:param runtime: simulation runtime
:return: float
"""
rates = list()
for spiketrain in spiketrains:
rates.append(len(spiketrain) * (1000 / runtime))
... | cbbe6958877dcf7d756ab4796ef9dc351fd1dd3a | 617,717 |
def refresh_time_stats(bot):
"""
Returns formatted stats on the last refresh.
"""
stats = bot.memory['ratbot']['stats'].get('starsystem_refresh')
if not stats:
return "No starsystem refresh stats are available."
return (
"Refresh took {total:.2f} seconds. (Load: {load:.2f}, Prun... | 17e1900d2c2979e94631dd796ed4b1e9b8c0504f | 617,718 |
from typing import List
def split_changes_into_list(changes: str) -> List[str]:
"""
Given a string of chord alterations (e.g., suspensions or added tones),
split them into a list of individual alterations.
Parameters
----------
changes : str
A string representing a chord alterations, ... | 43bc545c46d6e3e78c32a6b5ed5f23299af6870f | 617,724 |
def autoNorm1(dataSet):
"""
归一化特征值,消除属性之间量级不同导致的影响
归一化公式:
Y = (X-Xmin)/(Xmax-Xmin)
其中的 min 和 max 分别是数据集中的最小特征值和最大特征值。该函数可以自动将数字特征值转化为0到1的区间。
"""
# 计算每种属性的最大值、最小值、极差
minVals = dataSet.min(0)
maxVals = dataSet.max(0)
ranges = maxVals - minVals
normDataSet = (dataSet - m... | 8558de4ee922ffe2af9114859774ad8f704cc2d3 | 617,726 |
import operator
from typing import OrderedDict
def build_node_id_mapping(nodes):
"""
Build the mapping from tree node to array index
>>> nodes = [('funny', None, None, 3), (',', None, None, 2), ('.', None, None, 2), ('engaging', None, None, 4), ('film', None, None, 2), ('warm', None, None, 3), ('A', ... | beed799bfc05732c08ed448fbdb06cf534098eb3 | 617,727 |
from typing import Dict
import pkg_resources
def get_versions() -> Dict[str, str]:
"""Returns version info for all Open Mafia (sub-)packages."""
prefix = "open-mafia"
z = sorted(
[
(p.key, p.version)
for p in pkg_resources.working_set
if p.key.startswith(prefix... | 3e4499ad7e5cb63daff88e5a5106d3e016a82372 | 617,728 |
import re
def pull_stats(summary: list) -> dict:
"""
Convert stats to a dictionary.
Each line in the summary table in the log file needs to be parsed by first
converting the table to a comma-separated list for easy parsing, then
taking the first column as the statistical category and placing the
... | df56c1b8871e6217e9cd6a6465a6e98c207958e3 | 617,729 |
def merge_dicts(*args):
"""Merge multiple dictionaries in a new one
treating None as an empty dictionary.
merge_dicts(dict1, [dict2 [...]]) -> dict1.update(dict2);dict1.update ...
Parameters
----------
*args : dict-like
Returns
-------
dict
Example
-------
>>> d1 = d... | 23f9745616bf5b96d6bea92c9f91c28ea48b8b05 | 617,730 |
import re
def should_ignore_line(line):
"""
Determine whether or not a line should be ignored for now.
"""
patterns_to_ingore = [
re.compile('#!/usr/bin/env python'),
re.compile('from __future__ import .+'),
re.compile('^#[\s\S]*'),
re.compile('^\s+$')
]
return ... | 9f26ce49a52003183537cdb51dd1241d1bde4264 | 617,737 |
def decode_ports(ports, filter_proto):
"""Given a string like '901-902/tcp,30/udp', return a list of ports."""
if not ports:
return []
results = []
for protoport in ports.split(','):
port, proto = protoport.split('/')
if proto != filter_proto:
continue
# Expa... | 7239d6367370b36371911f46a6f396d8bc97480c | 617,740 |
import json
def read_json_filter(path):
"""Reads a json filter from a file.
For example:
[">", 3.14, ["field", "000002"]]
"""
with open(path) as json_data:
return json.load(json_data) | 3718686224f3683a6dd4917945c5a227aa0d6692 | 617,751 |
def get_reverse_list(ori_shape, transforms):
"""
get reverse list of transform.
Args:
ori_shape (list): Origin shape of image.
transforms (list): List of transform.
Returns:
list: List of tuple, there are two format:
('resize', (h, w)) The image shape before resize,... | 723a12c4635f154c1194f46874aba17a08e5abb9 | 617,753 |
def ask(prompt: str='', default: str='') -> str:
"""Print the ``prompt``, get user's answer, return it -- or a default."""
if prompt:
if default:
prompt = prompt + ' [' + default + ']'
prompt = prompt + ' '
answer = None
while not answer:
answer = input(prompt)
... | bedc4efb74f97b9103082225f804f6765cc98326 | 617,755 |
import re
def parse_ldd_output(output):
"""Parses the output from a run of 'ldd' on a binary.
Returns a dictionary of {path: address} for
each library required by the specified binary.
Arguments:
output(bytes, str): The output to parse
Example:
>>> sorted(parse_ldd_output('''
... | c7b05ac7036adc567ce60f280bbbe49c62ac76fd | 617,757 |
def _is_line_important(line_content, frames):
"""Check if the line contains a frame; it means the line is
important."""
for frame in frames:
if frame in line_content:
return True
return False | a7f8fc44c9cb20c12c59dd01b0892c7534bc7c60 | 617,760 |
def string_to_list(a):
"""Transform a string with coma separated values to a list of values."""
return a if isinstance(a, list) or a is None else a.split(",") | d227356d6b9c4695b90b6871ed6e75dff96e4020 | 617,761 |
def _sort_resources(resources):
"""
Sorts a stack's resources by LogicalResourceId
Parameters
----------
resources : list
Resources to sort
Returns
-------
list
List of resources, sorted
"""
if resources is None:
return []
return sorted(resources, ke... | e52541f03cdc9b27a61b918becb51e5d5e3b22cb | 617,763 |
def fix_checkbox(params):
"""
Replace param_checkbox with param-indexed.
"""
pol_params = {}
# drop checkbox parameters.
for param, data in params.items():
if param.endswith("checkbox"):
base_param = param.split("_checkbox")[0]
pol_params[f"{base_param}-indexed"] ... | 92d7490d191a7708160802cf8ec565da8c6718f1 | 617,765 |
def mode(var, k=1):
"""
Returns the `k`th most probable value of the random variable `var`.
"""
pairs = sorted(var._dist.keys(), key=lambda val: var[val], reverse=True)
return pairs[k - 1] | 3aad812d9a928af24c537e4c4ecb226bd121233e | 617,769 |
def change_extension(filename, new_ext):
"""
Change file extension
"""
fn = '.'.join(filename.split('.')[:-1] + [new_ext])
return fn | 7c9108ba0fd3f997d2a766d5e42ec8ecfc9290d8 | 617,771 |
from typing import Dict
def generate_userlist(users: Dict[str, str]) -> str:
"""Generate valid userlist.txt from the given dictionary of usernames:passwords.
Args:
users: a dictionary of usernames and passwords
Returns:
A multiline string, containing each pair of usernames and passwords i... | 4a645ad18dae364b12a3e1b0bbcf6320d8880a50 | 617,775 |
def make_id_response(id):
"""
Usually used for requests that create single resources.
:param id: ID of of the created resource.
:return: Single ID response.
"""
return {'id': id} | 049d8697c0ffc7db1d44c156eb47ba45d73cec54 | 617,776 |
def PySequence_GetSlice(space, w_obj, start, end):
"""Return the slice of sequence object o between i1 and i2, or NULL on
failure. This is the equivalent of the Python expression o[i1:i2]."""
return space.getslice(w_obj, space.newint(start), space.newint(end)) | 639e890930dee2a20cbe1b9f5be6bd3b89a82c8a | 617,778 |
def specify_grid(grid):
"""Specify the grid to search on (`F` for use of xorca_brokenline).
Parameters
----------
grid : str
Name of the grid (T, U, V, F).
Returns
-------
S : str
Name of the dummy variable living on the specified grid.
"""
# make sure the letter d... | 2ef322b4fe37832098a875c4f32284f803851163 | 617,783 |
def _instance_tags(hostname, role, tags=None):
"""Return instance tags (common tags + instance name and role).
"""
if tags is None:
tags = []
return [{
'ResourceType': 'instance',
'Tags': tags + [
{'Key': 'Name', 'Value': hostname.lower()},
{'Key': 'Role'... | b569940bd51ae984de8c3ab5cc2b549028fdf7d4 | 617,784 |
import torch
def mbcuda(t: torch.Tensor) -> torch.Tensor:
"""Short for "maybe cuda" this moves a tensor (or model) to cuda if available
"""
if torch.cuda.is_available():
return t.cuda()
else:
return t | 0592f22465e58ff56b3ed30e0d850b05ccb259d3 | 617,788 |
def get_subgraph(G, nodes):
"""
NetworkX subgraph method wrapper
"""
return G.subgraph(nodes) | 69b51f9dfa57c97b446a66fd94d0a4005b57dd18 | 617,793 |
import types
def is_generator(val):
"""
Checks whether a variable is a generator.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True is the variable is a generator. Otherwise False.
"""
return isinstance(val, types.GeneratorType) | ec14a50048d6800738566148b4c87059c051c293 | 617,795 |
def vecDistanceSquared(inPtA, inPtB):
"""calculate the square of the distance between two points"""
ddx = inPtA[0] - inPtB[0]
ddy = inPtA[1] - inPtB[1]
ddz = inPtA[2] - inPtB[2]
return ddx*ddx + ddy*ddy + ddz*ddz | dd054e1a2e6fde7d56bd0febd18847c09e900e8c | 617,796 |
def count_daily_prefixes(pfx_raw_data):
"""
Count how many prefixes have been announced by each AS in input.
Note: input should contain data for only one day.
:param pfx_raw_data: generator that yields dictionaries containing BGP announces for one day
(from jarvis)
... | 1cdd3238c6d364595a94bf066cc3ed568f05c40c | 617,799 |
def flatten_errors(errors, path=''):
"""Flatten Cerberus errors into the JSONAPI structure."""
flat_errors = []
for key, values in errors.items():
for value in values:
if isinstance(value, dict):
flat_errors.extend(flatten_errors(value, path='{0}/{1}'.format(path, key)))
... | d562877969548a80e31d5903c1e1639b21ec4978 | 617,802 |
from typing import Any
import inspect
def safe_is_sub(sub: Any, parent: Any) -> bool:
"""Is this a subclass of parent."""
is_class = inspect.isclass(sub)
return is_class and issubclass(sub, parent) | d54346eecc111b60be5fe62782957d07f4a30e67 | 617,804 |
import torch
def encode_boxes_to_anchors(boxes, anchors, eps=1e-8):
""" Create anchors regression target based on anchors
Args:
boxes: ground truth boxes.
anchors: anchor boxes on all feature levels.
eps: small number for stability
Returns:
outputs: anchors w.r.t. ground tr... | 62facae75a1290dbd64e1dfdbe98a5d6eeb60ca1 | 617,812 |
def get_headers_dict(base_headers: list[str]):
"""Set headers for the request"""
headers_dict = {}
for line in base_headers:
parts = line.split(':')
headers_dict[parts[0]] = parts[1].strip()
return headers_dict | a22a5f1cd5a6c47115ccd89a7d0165a9b262eda3 | 617,814 |
from datetime import datetime
def unisoformat(s):
"""Turn result of .isoformat() back into datetime."""
return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') | 5fed85538997b9b5c71f0e254922ac6f045f0233 | 617,815 |
def binary_search(a, x, left=0, right=-1):
"""
Returns the index of x if it exists in a.
Otherwise returns the index of either its left or right neighbor.
right is inclusive.
"""
n = len(a)
if right < 0:
right += n
while left < right:
mid = left + (right - left) // 2
... | 03e3ebc91c9dc97d74e1d0dc782f87fa6bb7ad5c | 617,818 |
def shoulder_to_dict(s):
"""Return a dict of the user defined values/attributes in a Shoulder model"""
return {
'active': s.active,
'crossrefEnabled': s.crossrefEnabled,
'datacenter': s.datacenter,
'date': s.date,
'isArk': s.isArk,
'isCrossref': s.isCrossref,
... | ba161340e7215e616a8fedc5017d37ba36774ec6 | 617,819 |
import collections
def _name_regions(regions, vertex_slice):
"""Convert a list of regions into the correct form for a method expecting
two dictionaries describing the regions.
"""
regions = collections.OrderedDict({
i: r for i, r in enumerate(regions, start=1) if r is not None
})
regio... | 188d8aa071d6921642f785aade485d54bcda39b4 | 617,822 |
import inspect
def get_caller_file_name(skip_frames=1):
"""
Get the file name of the original caller of the calling function.
:param skip_frames: The number of frames to skip to get the caller. If you
want your filename, set to 0, if you want your caller's leave to default or
set to 1, and any nu... | 0b8f8c35d1fca51c61f0389946fd8fedf8f3e8d1 | 617,824 |
import re
def is_aws_ecr(registry):
"""Checks whether registry is an AWS ECR registry."""
return re.match(r"[0-9]+\.dkr\.ecr\.[^.]+\.amazonaws\.com",
registry) is not None | 0a558f255a65d2c8ce093bc65c6ffc8c1b2d8438 | 617,828 |
import re
def parse_unit(line, unit_type):
"""Parse line to unit representation with unit_type."""
regex = r'''(\d+) # number of units
[\w\s]+?
(\d+) # hit points
[\w\s]+?
(\([\w;,\s]+\))? # immunity and weaknesses
... | f34eab12db581d142d134d06627fecc194d58e0b | 617,843 |
def equiangular_dimension_unpack(nodes, ratio):
"""Calculate the two underlying dimensions
from the total number of nodes
Args:
nodes (int): combined dimensions
ratio (float): ratio between the two dimensions
Returns:
int, int: separated dimensions
"""
dim1 = int((nodes... | 77d9666705d56706d064b6ed8e92e2d896467aaf | 617,846 |
def count_ports(port_mask):
"""Return the number of ports of given portmask"""
ports_in_binary = format(int(port_mask, 16), 'b')
nof_ports = ports_in_binary.count('1')
return nof_ports | f3ad69fcb90ce34d26c391f2aa56d9d7e1d08a77 | 617,849 |
import functools
def _positional(max_pos_args):
"""A decorator to declare that only the first N arguments may be positional.
Note that for methods, n includes 'self'.
"""
def positional_decorator(wrapped):
@functools.wraps(wrapped)
def positional_wrapper(*args, **kwds):
if len(args) > max_pos_a... | a155d77797311c7eb2645ad67581d444ac528e82 | 617,857 |
def convert_example_test(example,
tokenizer,
max_seq_length=512,
pad_to_max_seq_len=False):
"""
Builds model inputs from a sequence.
A BERT sequence has the following format:
- single sequence: ``[CLS] X [SEP]``
Ar... | b31bc525ee105cebbdd2abc3d837cc7792935908 | 617,859 |
import random
def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789',
repetitions=False):
"""
Returns a random string, based on the provided arguments.
It returns capital letters and numbers by default.
Ambiguous characters are left out, repetitions will b... | 5e84b60ae73afac4ea728ac64dd99d72cfc64e92 | 617,860 |
def file_get_contents(filepath):
"""Get file contents"""
with open(filepath) as f:
return f.read() | d4569fec8cd2440267c901d71c34fd464610690f | 617,861 |
from typing import Union
def convert_to_set(convert_this: Union[list, set, str, tuple]) -> set:
""" Convert a string, a tuple, or a list into a set
(i.e. no duplicates, unordered)"""
if isinstance(convert_this, set):
# functions using this expect a set, so everything
# else just captu... | 702e942a9980d511728a2bfbfd6943247765311a | 617,865 |
def get_word_string(word, guesses):
"""
This function will return a string of the word with the correct guesses.
"""
# Initialize the string.
string = ""
# Loop through the word.
for letter in word:
# Check if the letter has been guessed.
if letter in guesses:
# Add the letter to the string.
string +=... | b841de4ed8c619370e18696e43c631a486c6c871 | 617,868 |
def get_resource_names_output(resources):
"""
Creates the output dict with the names of all resources to be created.
"""
names = [resource['name'] for resource in resources]
return {'name': 'resources', 'value': names} | 0311f21892cb522007289b3d65a9a88e9bce60a7 | 617,869 |
import torch
def batch_lstsq(B, A):
"""Compute the least-squares solution.
Finds ``x`` that minimizes ``Ax - B``
Parameters
----------
input : torch.Tensor
(b, m, k)
A : torch.Tensor
(b, m, n)
Returns
-------
torch.Tensor
(b, n, k) least squares solution.... | ae038e306bf470e0b30b47e60f384fce422f42e0 | 617,870 |
import six
def php_serialize(value):
"""
Serialize a value for use with PHP's deserialize() function. This function
can serialize bytes, strings, integers, floats, booleans, None, lists,
dicts and custom objects implementing __php__().
Args:
value: The value to serialize.
Returns:
... | 5d55c303c1571f0a8a525ff61cf43c8ba0b019ae | 617,874 |
def dict_from_file(filename, key_type=str):
"""Load a text file and parse the content as a dict.
Each line of the text file will be two or more columns splited by
whitespaces or tabs. The first column will be parsed as dict keys, and
the following columns will be parsed as dict values.
Args:
... | 8d12620ca12c65c9cc8769262eba253d26581a72 | 617,877 |
def unite_characteristics(species):
"""
This function unites the characteristics of all the given species
Parameters:
species (list of species or ParallelSpecies object)
"""
characteristics = set()
if species is not None:
for spe in species:
characterist... | 421e9c7f82f035c05f08837be45169d3ef83d575 | 617,879 |
def layer_is_in_mark(layer, mark):
"""
Whether the given layer is in the given mark.
"""
return layer["mark"] == mark or ("type" in layer["mark"]
and layer["mark"]["type"] == mark) | 8a235dc575e4da63324941a92f6fae8b24fc527e | 617,880 |
def rescale(n, after=[0,1], before=[]):
"""
Helper function to rescale a vector between specified range of values
:param numpy array n: a vector of numbers to be rescale
:param list after: range of values to which to scale n
:param list before: range of values in which n is contained
"""
... | 152857cc48253e7a252428da74c0967b1cc5c76c | 617,884 |
import itertools
def _merge(d, keys):
""" Merge multiple lists from a dictionary into one iterator.
e.g. _merge({'a': [1, 2], 'b': [3]}, ['a', 'b']) ->
iter(1, 2, 3)
:param d: dictionary
:type d: dict
:param keys: keys to merge
:type keys: [hashable]
:returns: iterator
... | 3335e8feb1bfbea449709c4791643034abcc6952 | 617,885 |
def add_nipsa_action(index, annotation):
"""Return an Elasticsearch action for adding NIPSA to the annotation."""
return {
"_op_type": "update",
"_index": index,
"_type": "annotation",
"_id": annotation["_id"],
"doc": {"nipsa": True}
} | b666582e1b257dfebe91789b0b1cc3401bb3fbe5 | 617,886 |
def player_listing(table):
""" Returns the list of seats with players and stacks, for the hand history. """
_str = ''
for i, s in enumerate(table.seats):
if s.player is None:
_str += 'Seat #{}:\n'.format(i)
else:
_str += 'Seat #{}: {}(${})\n'.format(i, str(s.player), ... | 221a18b0c2989510e657ec6afbf7882bee170531 | 617,888 |
def det_prob_query(p1: float, k: int, l: int) -> float:
"""
Compute the probability of finding point q < cR
Parameters
----------
p1
P_1 as determined with Union[floky.stats.collision_prob_cosine, floky.stats.collision_prob_l2]
k
Number of hash digits.
l
Number of ha... | f62c5ef83c77ac971f40a4c11a641fcc74777071 | 617,889 |
def dual_filter(cond, seq):
"""filter `seq` on `cond`; return two lists: (matches, non_matches)"""
pos,neg = [],[]
for x in seq:
(pos if cond(x) else neg).append(x)
return pos,neg | 82942531b9be7b32f724100f7b3a7c4c901b90ff | 617,892 |
from typing import List
def quantile(xs: List[float], p: float) -> float:
"""Returns the pth-percentile value in x"""
p_index = int(p * len(xs))
return sorted(xs)[p_index] | 35dbf0ca4fc6929786cf08908806a8092be6fe1c | 617,893 |
import re
def explode_ltr_model_definition(definition):
"""
Parse a string describing a ltr featureset or model
(featureset|model):name[@storename]
Parameters
----------
definition: string
the model/featureset definition
Returns
-------
list: 3 elements list: type, na... | 6f377c86c8895280b4866a46ae3d6e58c16e9d79 | 617,899 |
def first(xs):
"""Grab the first item from a list-like thing."""
return xs[0] | 6c6427c04d3456b56823b57491db4eb368d64fa5 | 617,902 |
def model_trapezoidal_pulses(pileup_time, energy1, energy2, cfg):
"""
Models the pileup energy based on a trapezoidal filter. We have 4 scenarios for the pileup.
The final energy depends on when the pileup signal peaks:
1. fully inside the gap of the first signal,
2. between the gap and the ... | dc8b906c96233d6d8e8d9e15560d97f6ccfdaf16 | 617,904 |
def print_files(arguments):
"""Prints the current location of raw database files."""
print ("Files for database '%s':" % arguments.name)
for k in arguments.files:
print(k)
return 0 | 111c96a8529470e5333fb7c3a1a94bdaa8f90ab7 | 617,906 |
def factorial_r(n):
"""
Input: a number.
Output: find the factorial of the input number using recursion.
"""
if n == 0:
return 0
if n == 1:
return 1
else:
return (n * factorial_r(n-1)) | 61f08ab0b3c7fde4ad5b6336945d8b9e63ad63db | 617,907 |
import torch
def mixup_criterion(preds, target):
"""Implements loss for Mixup for EEG data. See [1]_.
Implementation based on [2]_.
Parameters
----------
preds : torch.Tensor
Predictions from the model.
target : torch.Tensor | list of torch.Tensor
For predictions without mixu... | eec54f9d18f44d7808abd3d5614d2870c9d86963 | 617,908 |
from pathlib import Path
def is_file(file_obj):
"""Check a file exists on the system.
Examples
--------
::
>>> from pyutil.sys_checks import is_file
>>> if is_file('path/to/file'):
>>> pass
"""
p = Path(file_obj)
return p.is_file() | a2acf2c6d53c6de91a033bcb16629219e438e5db | 617,910 |
from typing import Iterable
from typing import Tuple
def make_in_list_sql_clause(
database_engine, column: str, iterable: Iterable
) -> Tuple[str, list]:
"""Returns an SQL clause that checks the given column is in the iterable.
On SQLite this expands to `column IN (?, ?, ...)`, whereas on Postgres
it... | 2f288df554ab64d6f25a84ea54b6c62e8ba87e80 | 617,921 |
def filter_cannonical(df):
"""Retains only cannonical chromosomes in bed-like df."""
df = df[df.loc[:, 0].str.match("chr[0-9|X|Y]+[a|b]?$")]
return df | 46023600c667967973a451d0b32c4f721e612cd9 | 617,923 |
import typing
def type_hints(f):
"""Same as `typing.get_type_hints` but returns `{}` if not allowed type."""
allowed_types = typing._allowed_types # type:ignore
return typing.get_type_hints(f) if isinstance(f, allowed_types) else {} | 1ef7a2b1e119d7260a6848f5ed7bc9b575052f2f | 617,925 |
def get_function(name, entries):
"""Generates lookup function with given name and lookup table entries."""
contents = """
absl::optional<tensorflow::gtl::FlatSet<int>> {name}(
const tensorflow::string &op_name) {{
static std::array<OpIndexInfo, {count}> a = {{{{
""".format(
name=name, count=len(entries) +... | a059a6b42bacd067e577d0ecf221a0895c3696e3 | 617,927 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.