content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def calc_distance(x1, y1, x2, y2):
"""
Calculate the distance between 2 point given the coordinates
:param x1: Point 1 X coordinate
:param y1: Point 1 Y coordinate
:param x2: Point 2 X coordinate
:param y2: Point 2 Y coordinate
:return: Double. Distance between point 1 and poi... | dd143ed5dd088c8a4d205c47363cd463798796d9 | 38,762 |
def list_perceel_adapter(obj, request):
"""
Adapter for rendering a list of
:class: `crabpy.gateway.capakey.Perceel` to json.
"""
return {
'id': obj.id,
'sectie': obj.sectie,
'capakey': obj.capakey,
'percid': obj.percid
} | 7c20a79e492433acdbc31014ed4f9ab8f3d18115 | 38,763 |
def parse_fqdn(session, fqdn):
""" Break an fqdn (string) and get some useful information from it.
Returns a tuple of the shortname (string), and DnsDomain object
"""
if not fqdn:
raise ArgumentError("No fully qualified name specified.")
(short, _, dns_domain) = fqdn.partition(".")
... | 9487d74b411f0d5aebfe857378983df8f69c093a | 38,764 |
def uniform_pdf(x):
""" Uniform Distribution(균등 분포) 확률 밀도 함수 """
return 1 if 0 <= x < 1 else 0 | 8aa049fc5ce2524edbfed892e4c0de1ce439ff58 | 38,765 |
def read_package_data_files():
"""Read package data files and return the text."""
with open(package_data_file(DATA_HTML_BASE),
'rt', encoding='utf-8') as f:
base_html = f.read()
with open(package_data_file(DATA_HTML_LICENSE),
'rt', encoding='utf-8') as f:
lic... | 03a96d7cb8f43f7588a51efa4f0816a3c01030cb | 38,766 |
def unit(value, unit, parenthesis=True):
"""Formats the numeric value of a unit into a string in a consistent way."""
formatted = f"{value:,g} {unit}"
if parenthesis:
formatted = f"({formatted})"
return formatted | fe039ec681a16e4a317f1a500c29ab44615addd1 | 38,767 |
from typing import Callable
from typing import Any
from typing import List
import numpy
def apply_along_axis(
func1d: Callable[[PolyLike], PolyLike],
axis: int,
arr: PolyLike,
*args: Any,
**kwargs: Any,
) -> ndpoly:
"""
Apply a function to 1-D slices along the given axis.
Execute `fun... | 00d537ec6dc12e421344064b236f209d0d8d2846 | 38,768 |
def get_matrix(vocab, token_pairs):
"""Get normalized matrix"""
# Build matrix
vocab_size = len(vocab)
g = np.zeros((vocab_size, vocab_size), dtype='float')
for word1, word2 in token_pairs:
i, j = vocab[word1], vocab[word2]
g[i][j] = 1
# Get Symmetric matrix
g = symmetrize(g... | aaf5737f06438d02c039c6b57e346967bd176967 | 38,769 |
def decode_landm_in_numpy(pre, priors, variances):
"""Decode landm from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
pre (tensor): landm predictions for loc layers,
Shape: [num_priors,10]
priors (tensor): Prior boxes in center-of... | 9e30bae72b3a4e9711a9ff38fa675af95e355235 | 38,770 |
def bulk_add_songs_to_playlist(playlist_id, songs, *args, **kwargs):
"""
"""
playlist = Playlist.objects.get(id=playlist_id)
songs_added = 0
failures = 0
failure_details = []
for song in songs:
try:
platform = get_platform(song.get('platform', 'revibe'))
so... | ae413eca648c41d0421f138d7abd9ae49302389d | 38,771 |
def execute_query(spec, connection_string=None):
"""
Setup a connection to a mongodb server and execute the given query.
:param spec: Mongo query spec.
:returns: Mongo curser.
"""
if connection_string is None:
connection_string = "mongo://localhost:27017/test"
if connection_string:
... | 2f23b2e32cdd004c836b12b6fd32010e224c17e3 | 38,772 |
def untlpydict2xml(untl_filename, untl_dict):
"""Return a UNTL file.
Takes a UNTL filename and a UNTL Python dictionary.
"""
return pydict2xml(untl_filename, untl_dict) | c2e1b1bef7484fc7761a775abfeeee18f1f7ceb4 | 38,773 |
def cityInit(ifInput, cityInput, *txtPath):
"""
随机产生城市矩阵
:param ifInput: 是否输入城市数量 bool
:param cityInput: 如果第一个参数为True, 填任意值, 否则填城市数量 int
:param txtPath: (可选)如果第一个参数为False, 也可以选择文件输入, 文件有三列, 第一列是序号, 第二列是横坐标, 第三列是纵坐标 string
:return: 城市数量 int, 城市坐标 list, 城市之间的距离矩阵 ndarray
city.txt示例:
1 9860 14152
... | 004e68d459f325a141a4ca3865bef874699e030e | 38,774 |
def deduce_left_margin(properties_of_keywords_in_resume, structural_properties_of_resume):
"""Takes the smallest left margin that has more than 2 occurrences in all_caps_properties and
entire_match_properties. If both left_margin matched it returns the left_margin immediately. If not,
it returns the left_ma... | a5abdf66814d00b5edd85f77a262e02da134890b | 38,775 |
def __datetime_representer(dumper, data):
"""
Ensures that datetime objects are represented correctly."""
value = data.isoformat("T")
return dumper.represent_scalar("tag:yaml.org,2002:timestamp", value) | b1a51f29d17b40223595723474c605e430a80aa1 | 38,776 |
def normalize_val_list(val_list):
"""Returns a list of numeric values by the size of their maximum
value."""
max_val = float(max(val_list))
return [ val/max_val if max_val != 0 else 0 for val in val_list ] | f594a6c281253bc181e436d1e1e3e1a83d07b56c | 38,777 |
def policy_threshold(threshold, belief, loc):
"""
chooses whether to switch side based on whether the belief on the current site drops below the threshold
Parameters
----------
threshold (float): the threshold of belief on the current site,
when the belief is lower than the... | 31b50a3093ba60d59e0c23eb11f2f20f76065e81 | 38,778 |
import click
def run(torrent, output_location):
"""Console script for pytorrent.cli.run."""
click.echo("Replace this message by putting your code into " "pytorrent.cli.run")
pt = PyTorrent(torrent)
pt.start()
pt.create_files(output_location)
return 0 | 8529c2eb3e1a59c3945a264f4458e06f981ceafc | 38,779 |
def create_standard_serializer_class(model_cls):
"""Creates serializer class for the Django model specified.
Created serializer will declare all model fields,
will have "url" #HyperlinkedIdentityField pointing at detail view for the entity
and will inherit #OptimizeUrlFieldsSerializer and #JsFriendlyFi... | 59df8920281a38e9651efdeb4be014535c519229 | 38,780 |
import warnings
def choose_representation(adata,
rep=None,
n_pcs=None):
"""Get representation of multivariate data.
Args:
adata (anndata.AnnData): Multidimensional morphological data.
rep (str): Key in .obsm.
n_pcs (int): Number of p... | 85938af3be930ce707a5f9a51992da373686498b | 38,781 |
def sieve(iterable, indicator):
"""Split an iterable into two lists by a boolean indicator function. Unlike
`partition()` in iters.py, this does not clone the iterable twice. Instead,
it run the iterable once and return two lists.
Args:
iterable: iterable of finite items. This function will sca... | 55f64a2aea55af05bd2139328157e3a877b8f339 | 38,782 |
import datasets
import torch
def Flowers_dataloader(root, quat_data, img_size, normalize, batch_size, num_workers=2, eval=False):
"""102 Oxford Flowers dataloader with resized and normalized images."""
name = '102 Oxfrod Flowers'
print('Dataset:', name)
if not eval:
dataset = datasets.ImageFol... | 373c15c4ff23a91309235d6ed8de9e0700ce2939 | 38,783 |
import re
def property_to_snake_case(property_type):
"""Converts a property type to a snake case name.
Parameters
----------
property_type: type of PhysicalProperty of str
The property type to convert.
Returns
-------
str
The property type as a snake case string.
"""
... | fc0aa1c811a2de0bbd77f146a1816e8d7a31e08a | 38,785 |
def standardize(data: np.ndarray) -> list:
"""
Standardize input values
(x - x.mean) / x.standard_deviation
Args:
data (np.ndarray): Input data
Returns:
[type]: Standardized input data
"""
return np.array((data - np.mean(data)) / np.std(data), dtype=np.float32) | d1c7d5571f745c6f426772987be69c08faee88c1 | 38,787 |
def add_component(componentName, entityId, entity_type=entity.EntityType().Game):
"""
Given a component name, finds component TypeId, adds to given entity, and verifies successful add/active state.
:param componentName: String of component name to add.
:param entityId: Entity to add component to.
:r... | 29c53076e2a6eb6a13e6cfc0611f01803d3cbf7c | 38,788 |
def pad_sequence(sequence, max_length, embeddings_dict, pad_token = 'EOS'):
""" Adds EOS tokens until sequence length is max_length. """
n = len(sequence)
padded = sequence.copy()
if n < max_length:
if type(padded) is np.ndarray:
padded = np.append(padded, [embeddings_dict[pad_toke... | 8f31ffa8ba5e9a7d96913564164670196d833b1d | 38,789 |
from typing import Tuple
from typing import List
from operator import concat
def _parse_frequencies(result: Tuple, frequency_ids: List[int], frequencies: List[float], amplitudes: List[float]) -> df:
"""
Parses the list of frequencies from the result of FCombLibrary. The resulting frequencies are simply a list... | 07964a8cc31a0665598b68129d4b64ac8bc873c8 | 38,790 |
def read_binary(filepath):
"""return bytes read from filepath"""
with open(filepath, "rb") as file:
return file.read() | 98587f79b5a2d8b8ff82909cb03957c0b3e2db7d | 38,791 |
def sra_valid_accession(accession):
""" Test whether a string is an SRA accession """
if accession.startswith('SRR') and len(accession) == 10:
return True
return False | 3a4c5f40490f68490620ddacb430a0fcc8dfdd89 | 38,792 |
import pickle
def get_model_names():
"""Helper function that abstracts logic for getting names of all models
associated with the function"""
if 'models' in session:
models = pickle.loads(session.get('models'))
else:
models = {}
return list(models.keys()) | dbcee7582cf5e9118fc63d8c7a5bbb09f66f669a | 38,793 |
def alaska_transform(xy):
"""Transform Alaska's geographical placement so fits on US map"""
x, y = xy
return (0.3*x + 1000000, 0.3*y-1100000) | 3f86caeee7b34295ce0680017dd70d6babea2a62 | 38,794 |
async def mb(bucket: str) -> bool:
""" Make bucket """
async with _create_client() as client:
try:
await client.create_bucket(Bucket=bucket)
logger.info(f'Make bucket "{bucket}".')
except ClientError:
return False
return True | 6b6ff926870204f9028f3c482df94ea44f763480 | 38,795 |
import requests
import json
def get_user_simple_list(access_token, dept_id):
"""
获取部门用户信息
:return:
{
"errcode": 0, # 返回码
"errmsg": "ok", # 对返回码的文本描述内容
"hasMore": false, # 在分页查询时返回,代表是否还有下一页更多数据
"userlist": [
{
"userid": "zhangsan", # 员工id
"name": "张三" #... | 4fe63f8a8554015e02193005023181aa22ec23a5 | 38,796 |
import json
def err_resp(code: int, msg: str, err_subcode=None):
"""
generate error response
:param code: error code
:param msg: error msg
:param err_subcode: specific error details
:return: JsonResponse
"""
return json({
"ok": False,
"code": code,
"msg": msg,
... | 4de735610564989ba5fdd1d581cd3b0525a1778b | 38,797 |
def req(reqrep, address, rep):
"""The REQ socket."""
req, rep = reqrep
req.connect(address)
return req | 3cb4deb9e29256fc591ac59c3a1f756e48ff844b | 38,798 |
def create():
"""
Create a new DeviceModel.
Request:
{
'dm_name': 'Foo',
'df_list': [
{
'df_id': 12, // required
'df_parameter': [{}, ...] // required
'tags': [], // optional
},
... | 8de6c7a749bd2b46f947ce6fa02d0f3d33ecf381 | 38,802 |
def resize_image(img, min_side=800, max_side=1333):
"""
Resize an image such that the size is constrained to min_side and max_side.
Args
min_side: The image's min side will be equal to min_side after resizing.
max_side: If after resizing the image's max side is above max_side, resize until ... | 97e0355af5906132a8a84dbd6beb45e0b33fdaf0 | 38,803 |
def increase_by_1_list_comp(dummy_list):
"""
Increase the value by 1 using list comprehension
Return
------
A new list containing the new values
Parameters
----------
dummy_list: A list containing integers
"""
return [x+1 for x in dummy_list] | 9ad24064a7cf808cba86523e5b84fe675c6c128b | 38,804 |
def registered_root():
"""Return currently registered root"""
return _registered_root["_"] | d11d1e23faa3a63f84d8820b61b6ef8936f937fb | 38,805 |
def _is_conn_refused_exception(exceptionobj):
"""
<Purpose>
Determines if a given error number indicates that the remote
host has actively refused the connection. E.g.
ECONNREFUSED
<Arguments>
An exception object from a network call.
<Returns>
True if the error indicates the connection was... | ef833ce236a5fb697ec2ac35aec19240bd18757c | 38,806 |
import io
def _load_Xy(zipfile, csvfile, sep=',', header=None, engine='python',
na_values={'?'}, **kwargs):
"""Load a zippend csv file with targets in the last column and features in
the rest."""
with ZipFile(zipfile) as z:
with z.open(csvfile) as c:
s = io.StringIO(c.r... | 432f0201b6250bb08d61d0fbf0b0c29f25dda30c | 38,807 |
def pairwise(iterable):
"""
s -> (s0,s1), (s1,s2), (s2, s3), ...
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b) | e54f8d83c49b77f2219ed4a8f000bac07073e1f0 | 38,808 |
from typing import List
def get_pending_transfer_pairs(
transfers_pair: List[MediationPairState],
) -> List[MediationPairState]:
""" Return the transfer pairs that are not at a final state. """
pending_pairs = [
pair
for pair in transfers_pair
if pair.payee_state not in STATE_TRANS... | 660cf390299e614b1a19115005529b9c26a82ea8 | 38,809 |
def split(text: str, max_message_length: int = 4091) -> list:
""" Разделение текста на части
:param text: Разбиваемый текст
:param max_message_length: Максимальная длина разбитой части текста
"""
if len(text) >= max_message_length:
last_index = max(
map(
lambda s... | e54b7730705ed1a2143d7caa82b0f209081d6edf | 38,810 |
def apply_preconfig_to_existing(
self,
preconfig_id: str,
ne_pk: str,
) -> bool:
"""Apply preconfig to existing approved appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - appliancePreconfig
- POST
-... | 453b61b5eb83ea485e741cca9e2cec75d43bae2f | 38,811 |
def convert_quantiles_to_ci(ci, sm_concat, H, error_ci, coef_spline_smoothing=0):
"""
convert the computed quantiles for the normalized errors
into the quantiles of the errors by scaling back
with additional spline smoothing
"""
weights = np.ones((1,H))
weights_W = 1
q = list(set(ci... | 88404e2f43cf25713bffed54a6cdf024e2499ba0 | 38,812 |
def pythagoras(a, b):
"""Compute pythagoras.
Parameters
----------
a : float
length of one side of the triangle
b : float
length of second side
Returns
-------
c : float
length of the hypothenuse
"""
return np.sqrt(a**2 + b**2) | 5cfa96bb995d7bcd0c5b0193b5ba92e8b00c16b7 | 38,813 |
import itertools
def construct_target_sets_method_4(features, labels, ncl, n_samples, n_dim, final_features, dataset_name=None):
""" Construct the target sets: most confusion between classes. """
class_combinations = np.unique(labels)
normals = None
anomalies = None
# investigate each combinati... | 5f6ffdf70131ae11793836952e0dd1745d828cd6 | 38,814 |
def find_low_point_coords(arr: ArrayLike) -> list[list[int]]:
"""Return the low point locations in the input."""
arr_zeros = np.zeros(arr.shape)
# row[i+1] - row[i] > 0 => [row i+1] > row[i]
diff_down = np.diff(arr, 1, axis=0)
# row[i] - row[i+1] > 0 => row[i] > row[i+1]
diff_up = -1 * diff_d... | 8dc7f326ac0561657f8935a49ed46b3e5423cf09 | 38,815 |
import unicodedata
def is_hw(unichr):
"""unichrが半角文字であればTrueを返す。"""
return not unicodedata.east_asian_width(unichr) in ('F', 'W', 'A') | 260d79199c8551b635fb343a72ffeb30e7707958 | 38,817 |
from typing import Optional
def view_experiments(query_id: Optional[int] = None, omic_id: Optional[int] = None):
"""View a list of all analyses, with optional filter by network id."""
experiment_query = manager.session.query(Experiment)
if query_id is not None:
experiment_query = experiment_query... | 9552fb23d31b781c507be71cefb9df4cc62b7d28 | 38,818 |
def cfg_path():
"""Returns a path of the project config file to read."""
if utils.is_local_dev_server() or utils.is_dev():
return 'realms-dev.cfg'
return 'realms.cfg' | 763351450972d379bc6025acef76ab311d5e17cc | 38,820 |
from datetime import datetime
def default_event_end(hour: int = DEFAULT_EVENT_END_HOUR) -> datetime:
"""Return next default start time."""
return next_x_hour(hour, default_event_start()) | 6aa5dc752d67c8ea61293da8e97981aa66b2633b | 38,821 |
def deletedup(xs):
"""Delete duplicates in a playlist."""
result = []
for x in xs:
if x not in result:
result.append(x)
return result | 0f36899c9ce2710564d5d5938b54edbdd64afd81 | 38,822 |
def _cell_version(cellname):
"""Gets the cell based treadmill root."""
admin_cell = admin.Cell(context.GLOBAL.ldap.conn)
cell = admin_cell.get(cellname)
version = cell.get('version')
if version is None:
raise Exception('Version is not defined for cell: %s')
root = cell.get('root')
... | bc112cbd9522802c4dbfc9985498a2ceed28e942 | 38,823 |
from typing import Any
def prettyStringRepr(s: Any, initialIndentationLevel=0, indentationString=" "):
"""
Creates a pretty string representation (using indentations) from the given object/string representation (as generated, for example, via
ToStringMixin). An indentation level is added for every open... | 0c25810f5bd559a8dda09a2ec07bf6ea18956716 | 38,824 |
def create_flow(blocks, name="AnonymousFlow", mode=MODE_CRITICAL, common={}):
"""Auxiliary function to create test flows on the spot."""
return type(name, (TestFlow,), {'mode': mode,
'common': common,
'blocks': blocks}) | 6957c39c1e00f5072674a2815df29eded827a827 | 38,825 |
def format_date_time(date_time: wx.DateTime) -> str:
"""Format the given datetime in a string."""
dt: wx.DateTime = date_time
d, mon, y = dt.GetDay(), dt.GetMonth() + 1, dt.GetYear()
h, m = pad_int_str(dt.GetHour()), pad_int_str(dt.GetMinute())
s = pad_int_str(dt.GetSecond())
str_out = f"{wx.Da... | f0cd93e267a6a5b8663a6b003fb542d5abd20059 | 38,827 |
def parse_cencus_tract_info(rows):
""" Pass in multiple rows for a census tract to create CensusTractInfo
object
Demographics the folowing are derived from 'Visible Minority' section
East Asian (Chinese + South East Asian + Korea + Japanese + Fillipino)
Hispanic (Latin American)
... | 2bb5c173bfdf538234a438f7c5eaa062af8de174 | 38,829 |
from typing import List
from typing import Tuple
def match_points_to_regions(points: List[Tuple[float, float]], shapes_ds: pd.Series,
keep_outside: bool = True, distance_threshold: float = 5.) -> pd.Series:
"""
Match a set of points to regions by identifying in which region each po... | 8f1e368ed6af9d628cf2a96036355f7b90977db7 | 38,830 |
def GridSizer_GetCols3(sizer):
"""
Wrapper for wxGridSizer.GetColws()
With wx3 wxGridSizer.GetRows() and wxGridSizer.GetCols() "returns zero
if the sizer is automatically adjusting the number of rows depending
on number of its children."
@param sizer: Instance of wxGridSizer or a derived class... | a2b353353e424269126321c3ae64e024a8b14f9b | 38,831 |
def roi_align_nchw_ir(data, rois, num_rois, w_pc, pos_pc, pooled_size, spatial_scale, sample_ratio):
"""Hybrid routing fo ROI align operator in NCHW layout.
Parameters
----------
data : tvm.te.Tensor or numpy NDArray
4-D with shape [batch, channel, height, width]
rois : tvm.te.Tensor or nu... | e3ae01444590119174570a7495e7e90a1c29d04b | 38,832 |
def mux(car_state):
"""Returns car_pose to publish, given car_state."""
if car_state == CarState.START: return None
elif car_state == CarState.AUTO: return g['auto_car_pose']
elif car_state == CarState.MANUAL: return g['manual_car_pose'] | 91086eb497eb03afed0f071a8a977e696207d653 | 38,833 |
def get_mapping(d):
"""
Reports fields and types of a dictionary recursively
:param object: dictionary to search
:type object:dict
"""
mapp=dict()
for x in d:
if type(d[x])==list:
mapp[x]=str(type(d[x][0]).__name__)
elif type(d[x])==dict:
mapp[x]=get_m... | 87722f1429a93a934af08cb68519576cfc2cd7b0 | 38,835 |
def tf_top_k_top_p_filtering(logits, top_k=0, top_p=1.0, filter_value=-float("Inf"), min_tokens_to_keep=1):
"""
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (batch size, vocabulary size)
top_k (`int`, *optional*, defaul... | dd83ba9c46eb942e6054c459eac50d459e3f8627 | 38,836 |
def eval_fx(fx, stats):
"""Given fx and stats ('min', 'max', 'mean', 'std') return the result"""
_ = BNF().parseString(fx, parseAll=True)
val = evaluate_stack(exprStack[:], stats)
return val | 273fbafd92b45c0d1c77cc8ee9b1f552f083aacb | 38,837 |
def help(event):
"""Returns some documentation for a given command.
Examples:
!help help
"""
def prepare_doc(doc):
return doc.split('\n')[0]
plugin_manager = event.source_bot.plugin_manager
prendex = 'Available commands: '
if len(event.args) < 1:
return prendex +... | dbc2baed887df46e0d101d48a1a338760329679e | 38,838 |
def wordCount(wordListRDD):
"""Creates a pair RDD with word counts from an RDD of words.
Args:
wordListRDD (RDD of str): An RDD consisting of words.
Returns:
RDD of (str, int): An RDD consisting of (word, count) tuples.
"""
return (wordListRDD.map(lambda x: (x,1)).reduceByKey(lambd... | 1bb52a8d702cca68a91b4a172417224a07dea5d4 | 38,839 |
def parse_size(text):
"""Parse a size string to a structured type"""
match = SIZE_RE.match(text)
if not match:
return None
width = int(match.group('width'))
height = int(match.group('height'))
if 'rate' in match.groupdict():
framerate = float(match.group('rate'))
interlaced =... | 217d24b2a44a1ab4affeb0b3efc8794c4bdb7e19 | 38,840 |
def temporarily_as_user(setenv=True):
"""
Set effective user/group ID to the ordinary user (the one invoking the script).
An optional parameter "setenv=False" will skip setting user-related
environmental variables accordingly.
It can be used either as an ordinary function, or as a context manager
in "with" statem... | 4e230dab862b8a3ff9298137335dd3b1312f82e4 | 38,841 |
def encode_author(author):
"""
:param author:
:return:
"""
author = lxml.html.fromstring(author).text
if isinstance(author, str):
return unidecode.unidecode(remove_control_chars_author(to_unicode(author)))
return author | 58f584d19865ede0624ba674b20045b8e9b97097 | 38,842 |
import posixpath
def create_clowder_collection(session, url, collection, dryrun=False):
"""Create a Clowder collection.
Args:
session: http session
url: Clowder URL
collection: Clowder collection name
dryrun: Boolean. If true, no POST requests are made
Returns:
col... | d2645792a9834bdb853ea011bb23e44e3f95ba43 | 38,843 |
from typing import Optional
from typing import List
from typing import Dict
from typing import Callable
from typing import Type
from typing import Any
from typing import Tuple
def pait(
# param check
at_most_one_of_list: Optional[List[List[str]]] = None,
required_by: Optional[Dict[str, List[str]]] = None,... | 4f60318d06a6ebfff5d9d2040841c44dc9b99ebd | 38,844 |
def alpha_clipping(rectangle, line):
"""
Apply alpha-clipping of `line` according to `rectangle`.
Parameters
----------
rectangle : Rectangle
line : Line
Returns
-------
`None` or Line within rectangle
"""
a_min = 0.0
a_max = 1.0
outcode_p1 = rectangle.get_outcode(l... | 2f8f69ea7834aea91eea4f1b7e65eddbefac96a9 | 38,845 |
def create_spark_session():
"""
Create the entry point to programming Spark with the Dataset and DataFrame API.
The entry point into all functionality in Spark is the SparkSession class.
Instead of having a spark context, hive context, SQL context, now all of it is encapsulated in a Spark session.
S... | 533c611065083f8ebe1a87dd91f7ca7f18f1af2b | 38,846 |
def force_bytes(s, encoding='utf-8', errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first for performance reas... | 2a1f7f17789d472862c77128df90a4af669cade1 | 38,848 |
import random
def single_random_user(ev_room):
"""
Returns a single user name from users in a room
:param ev_room: Room to select users from
:return: A single user tuple
"""
return random.choice(GlobalVars.users_chatting[ev_room]) | aa2d0468091f09095d81ef8adf80b2f6c52f16dc | 38,849 |
def get_bploc_tuples(bp, source_map=None):
""" Returns a list of tuples (file, line) where a breakpoint was resolved. """
if not bp.IsValid():
return []
locs = []
for bploc in bp:
le_tupl = resolve_line_entry(bploc.GetAddress().line_entry, source_map)
if le_tupl[0] and le_tupl[1]... | 3e4e9433f12bcba94b1177d774009ec68058f08c | 38,850 |
def remplace_mot_entre_parentheses(texte: str):
"""
Les mots entre parenthèse représente le petite texte dans Animal Crossing.
Cela n'est pas prononcées.
"""
while '(' in texte and ')' in texte:
debut = texte.index("(")
fin = texte.index(")")
texte = texte[:debut] + "*" * ... | 30b2e86f56be6a4faee2f8c827c58d85ad62eb88 | 38,851 |
def main(token: str) -> int:
"""
Args:
token (str): bot access token
Return:
exit code of main script
NoneZero indicate a failure
"""
client = discord.Client()
@client.event
async def on_error(event, *args, **kwargs):
"""
Safely logout bot on event of... | b8614f88e06158a992384f0cdc83ec0564358197 | 38,852 |
def _threefry(
irb, key_buf, key_offset, counter_buf, counter_offset, out_buf, out_offset, out_shape
):
"""IRBuilder code for running Threefry
Parameters
----------
irb: IRBuilder
IRBuilder that this code will be generated for.
key_buf: BufferVar
Buffer to read the key from.
... | 66a150946bb1b7622321711d50af91babe3599bb | 38,853 |
def ussa_temp(altitude):
""" Compute reference temperature for a given altitude corresponding to the
US Standard Atmosphere.
Parameters
----------
altitude : float
Ambient altitude in kilometers; must lie in the range 0-50 km.
Returns
-------
Temperature at given altitude in K.... | 196902249f4d38bd14e6901c5341c6b7bf98df4f | 38,854 |
def get_scaled_cutout_basic_view(shp, p1, p2, scales):
"""
Like get_scaled_cutout_basic, but returns the view/slice to extract
from an image, instead of the extraction itself
"""
x1, y1 = p1[:2]
x2, y2 = p2[:2]
scale_x, scale_y = scales[:2]
# calculate dimensions of NON-scaled cutout
... | 5286465f2ccfb55f3cc6def7c1530857573861bb | 38,855 |
from typing import List
def check_data_for_invalid(data: List[int], preamble_size: int = 25) -> int:
"""Check the data for a number with an invalid sum.
Args:
data (List[int]): data from the data port
preamble_size (int; optional): the size of the preamble for data;
defaults to 25... | 1387c705e52245b495cf1c83415b35eb3d72fb85 | 38,858 |
def parseWeather(data: list) -> list:
""" take MetOffice weatherdata and return the first four future entries"""
forecast = []
whichday = 0
for day in data:
for entry in day['Rep']:
# The forecast is laggy for the current day, so we need to discard past entries
if ((whichday == 0) & (int(entry['... | 41e37fb4b3608f90417b3cb36ec81c5f6731b021 | 38,859 |
def process_file(filename):
"""
Process FITS file to get desired header info and image statistics
"""
outstr = ""
with fits.open(filename) as hdul:
hdr = hdul[0].header
if hdr['NAXIS'] == 3:
im = np.flipud(hdul[0].data[:, :, 0])
else:
im = hdul[0].data... | b80bc39446a8e0e93736619d82f2884d5bb2e88d | 38,860 |
def knapsack(v, w, n, W):
"""
Function solves 0/1 Knapsack problem
Function to calculate frequency of items to be added
to knapsack to maximise value
such that total weight is less than or equal to W
:param v: set of values of n objects,
:param w: set of weights of n objects,
first eleme... | 07537ab374f006a943a6ab19d90ee4cd580f9abf | 38,861 |
def get_stock_forms_by_case_id(case_ids):
"""Get a dict of form id sets by case id for the given list of case ids
This function loads Couch stock forms (even though they are
technically stored in SQL).
"""
form_ids_by_case_id = defaultdict(set)
for case_id, form_id in (
StockReport.obje... | 3a96fea179de3ce0d2c101e94cf191a378fc4aa9 | 38,862 |
def randint(low=0, high=None, shape=[1], dtype=None, name=None):
"""
:alias_main: paddle.randint
:alias: paddle.randint,paddle.tensor.randint,paddle.tensor.random.randint
This function returns a Tensor filled with random integers from the
"discrete uniform" distribution of the specified data type in the ... | 29763d4ed95401fa060267a3697af7f4986fb127 | 38,863 |
def variable_frequency(DataFrame, variable, sorted=False, ascending=False, limit=None, show_plot=False):
"""
Parameters
----------
DataFrame : pandas.DataFrame
DataFrame
variable : str
Variable to examine the freqeuncy.
sorted : bool, default False
ascending : bool, defa... | 86f622d2b3bccfb5f7966a6f879875441c4d0b24 | 38,864 |
def predict(examples,parameters):
"""
Compute the probability of being y=1 for all the `examples` given `parameters`.
Return a 1D array of probabilities.
"""
z = np.dot(examples,parameters)
return sigmoid(z) | ee122af0fff78959daee25b56dbc8ec7e9c1ce06 | 38,865 |
def less_generators(X):
"""
Reduce the generator matrix of the module defined by ``X``.
This is Algorithm 6.4 in [BC2012]_ and relies on the row syzygies of
the matrix ``X``.
EXAMPLES::
sage: from sage.geometry.hyperplane_arrangement.check_freeness import less_generators
sage: R.<... | b11b6084b9de0c67e101be82f7af858934de6d09 | 38,866 |
def __normalize_request_parameters(post_body, query):
"""
Return a normalized string representing request parameters. This
includes POST parameters as well as query string parameters.
"oauth_signature" is not included.
:param post_body: The body of an HTTP POST request.
:type post_body: strin... | 2cd7e72530a461629dd5034665c09dd240734313 | 38,868 |
def reshape_to_grid(data_flat, coords, shape):
"""Given a flattened array of data with the corresponding Y and X coordinates and the desired grid shape, return the grid of desired shape with the data given. Assumes flattened array has a time dimension as first dimension.
:arg data_flat: 2d array of data. First... | 56072493aad94ee831d9a29a2ae784491c1b77f6 | 38,870 |
import random
def point_mutation(bitstring, mutation_rate):
"""
:param bitstring: '100011...' - 32 bit
:param mutation_rate: 0.08
:return:
"""
child = ""
for bit in bitstring:
if random() < mutation_rate:
child += "0" if bit == "1" else "1"
else:
chi... | ef9710d439ec37a0b250821f06a6499c8530175a | 38,871 |
import re
def remove_punctuation(line):
"""
去除所有半角全角符号,只留字母、数字、中文
:param line:
:return:
"""
rule = re.compile(u"[^a-zA-Z0-9\u4e00-\u9fa5]")
line = rule.sub('', line)
return line | d63f355c5d48ec31db0412dd7b12474bf9d6dd6b | 38,874 |
import time
def CurrentTimeInSec():
"""Returns current time in fractional seconds."""
return time.time() | 3dc3bda89622ffdf0067d489c10f539cb6274e21 | 38,875 |
def pair(global_lut: dict, src: str, trace: Trace) -> str:
"""parsers a key value pair, returns the key"""
kv = src.split(Token.VALUE_SEPARATOR)
if len(kv) > 2:
# warn about assigning a value twice
# key = x = y
# in this case only the last value will be used
warn(Warn.MU... | e9012e524708147960ebd2327d9c10a98f3f110e | 38,876 |
def env_decode(value):
"""
Decodes an environment variable name or value that was returned by
get_env(for_subprocess=True)
:param value:
On Python 3, a unicode string, on Python 2, a byte string
:return:
A unicode string
"""
if not py2:
if not isinstance(value, str... | a317a4746cdae87a53a1d0a1b307b9fa29d6214a | 38,877 |
def disconnect():
"""This handler serves as a global disconnect procedure that will log a
user out no matter which provider they logged in with.
"""
if 'provider' in login_session:
if login_session['provider'] == 'google':
gdisconnect()
del login_session['gplus_id']
... | 0d7eaad5cc647c954655fe3fdb80556478587c8e | 38,878 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.