content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def makeCamera(name, scene):
"""
Retruns a new camera, appropriate for rendering a cube face, linked into
`scene`.
"""
cameraData = bpy.data.cameras.new(name)
cameraData.lens_unit = "FOV"
cameraData.angle = PI_OVER_2
camera = bpy.data.objects.new(name, cameraData)
if BLENDER_LEGACY_V... | a5c0025ba66095a8ed3577206eba51515c22115c | 41,909 |
import re
def path_and_line(req):
"""Return the path and line number of the file from which an
InstallRequirement came.
"""
path, line = (re.match(r'-r (.*) \(line (\d+)\)$',
req.comes_from).groups())
return path, int(line) | 54faa80fb0630f17fab836906e672886eedf3ad9 | 41,910 |
def taupericenter(t, e, f, n):
"""Compute the time of pericenter passage.
Args:
t (float): current time
e (float): eccentricity
f (float): true anomaly
n (float): Keplerian mean motion
Returns:
float: time of pericenter passage
"""
E0 = ... | 811e35b388c80af1250477621c850c9ac70bf1a5 | 41,912 |
import warnings
def get_voronoi_neighbors(atoms, cutoff):
"""
atoms: ase.Atoms object
cutoff: limits the neighbor search to |rj-ri| < cutoff,
used only for faster search, it should be large
enough so that the output doesn't depend on cutoff.
returns: a list of VorNei objects
... | e28325a5c91dc951cf5fe1ff3c03158cdf4d9bfc | 41,913 |
def autoencoder(x_hat, x, dim_img, dim_z, n_hidden, keep_prob):
"""Gateway"""
# encoding
mu, sigma = gaussian_MLP_encoder(x_hat, n_hidden, dim_z, keep_prob)
# sampling by re-parameterization technique
z = mu + sigma * tf.random_normal(tf.shape(mu), 0, 1, dtype=tf.float32)
# decoding
y = b... | f38898f308670e00f608be67dfea994c706a7d10 | 41,915 |
from typing import OrderedDict
import re
def leafelement(element, strip_cdata=False, compact=False, remove_blank_text=True):
"""
This function converts lowest level tree/etree element to dict structure.
:param element: etree leaf-level object,
:param strip_data: bool, whether to parse CDATA as pure te... | 38bba2727c417dacd84c385335f4415cff50a4fb | 41,916 |
def is_in_bbox(x, y, bbox):
"""
Answers True or Folse if the x, y is inside the BBOX.
"""
xMin, yMin, xMax, yMax = bbox
if xMin <= x <= xMax and yMin <= y <= yMax:
return True
return False | 911089af818c5e15e6ba857b1dd46f0182b1ea31 | 41,917 |
def convert_tuple_to_8_int(tuple_date):
""" Converts a date tuple (Y,M,D) to 8-digit integer date (e.g. 20161231).
"""
return int('{0}{1:02}{2:02}'.format(*tuple_date)) | 8584bb9ade995e95d12c9d09c4a6d52f7df44f5d | 41,918 |
def rule_Owner_default(x, world) :
"""We assume that the owner of an object is the first object which
Has some object which in some chain of containment (containment
optional). Returns None if no owner was found."""
poss_owner = world.query_relation(Has(Y, x), var=Y)
if poss_owner :
return ... | 2bd2406679cd997bbc2ce30bd450513de368cc1b | 41,919 |
def gpiod_line_is_requested(line: gpiod_line) -> bool:
"""
@brief Check if the calling user has ownership of this line.
@param line: GPIO line object.
@return True if given line was requested, false otherwise.
"""
return (
line.state == _LINE_REQUESTED_VALUES
or line.state == _... | 9ee9341e1e6cd193bd53258992f1907ffedb766f | 41,920 |
def coord_lister(geom):
"""[summary] when given a geometry pandas geoseries, returns an exterior
list of coordinates for all of the entries, given should
Args:
geom ([type]): [description]
Returns:
[type]: [description]
"""
coords = list(geom.exterior.coords)
return (coords... | b9d28a32241bf8f2b13988ef149eb4cf05ffb315 | 41,921 |
def edgeCannotConnectInputAndOutputOfSameNode(
inputSocket: Socket, outputSocket: Socket
) -> bool:
"""Edge is invalid if it connects the same node"""
if inputSocket.node == outputSocket.node:
printError("Connecting the same node")
return False
return True | c921b32409d1cec60c37a2be0d2bff9e398eddec | 41,922 |
def bcnn(pretrained=False, **kwargs):
"""Constructs a BCNN model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = BCNN(**kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['bcnn']))
return model | cdcdc9258b492865d57cf227521e0c63fe9e2527 | 41,923 |
def get_dataframe_intersection(df, comparator1, comparator2):
"""
Return a dataframe with only the columns found in a comparative dataframe.
Parameters
----------
comparator1: DataFrame
DataFrame to preform comparison on.
comparator2: DataFrame
DataFrame to compare with.
Re... | 0180783601bc1be93b3a74cd5604c5f1cd1bc67b | 41,924 |
import re
def get_sanitized_endpoint(url):
"""
Sanitize an endpoint, as removing unneeded parameters
"""
# sanitize esri
sanitized_url = url.rstrip()
esri_string = '/rest/services'
if esri_string in url:
match = re.search(esri_string, sanitized_url)
sanitized_url = url[0:(m... | 3936efe81970ffb6b54ee308870e70a20c7a4c6c | 41,925 |
def get_request_raw_header(request, name) :
""" Return raw header value of request by header name """
name = name.lower()
for header in request.raw_headers :
if header[0].decode("utf-8").lower() == name:
return header[1].decode("utf-8")
return "" | 37abaac86ae770354bacd6a96326d8b43f54999a | 41,926 |
def sequence_loss(logits, targets, weights,
average_across_timesteps=True, average_across_batch=True,
softmax_loss_function=None, name=None):
"""Weighted cross-entropy loss for a sequence of logits, batch-collapsed.
Args:
logits: List of 2D Tensors of shape [batch_size x num... | 5191deb86377125b67e5742f507b516ff52f9866 | 41,928 |
def scale_values_based_on_eich_peak(lead_list, gamma=0.5):
"""
scale values on the Y-axis
:param lead_list: list of the value
:param gamma: scaling factor
:return: rescaled list
"""
new_lead_list = []
for xy_pair in lead_list:
new_y_value = xy_pair[1] * gamma
... | 34d2c79f07c23e4fe23ab0eee8642ce17e03dbb7 | 41,929 |
def signup():
""" Sign up as a friend, enter card info, etc. """
return jsonify(ok=True) | 9164b983bc7a490bed415e2b16b0da7f5f24d442 | 41,930 |
def _must_find(cls, name):
"""Raises a NotFoundError if the given object doesn't exist in the datbase.
Otherwise returns the object
This is useful for most of the *_delete functions.
Arguments:
cls - the class of the object to query.
name - the name of the object in question.
Must be cal... | 4552b52211ac2a23c10a44bf012ca37ef992545b | 41,931 |
def import_class(class_path):
"""Imports a class using a type string.
:param class_path: Type string of the class.
:type class_path: str
:rtype: type
"""
components = class_path.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
... | bcfeed25c2b5f6672df63e63a031cfa580c0e275 | 41,932 |
def Base_select(self, param):
"""
- name: select 1st
select:
id: element1
by_index: 1
- name: select by value
select:
id: element1
by_value: value1
- name: select by visible text
select:
id: element1
by_text: "text 1"
"""
elem = s... | 4940c25abac8cb1682c2796a5725cd11cf5c5318 | 41,933 |
from typing import Sequence
def peg_time_interval(
twt_vol: xr.DataArray,
depth_surf: xr.DataArray,
twt_surf: xr.DataArray,
mapping_dims: Sequence[str] = ("xline", "iline"),
) -> xr.Dataset:
"""Shifts twt_vol to create such that the depth conversion of `depth_surf` with `twt_vol` matches
`twt_... | ce696048bae93011a44f52170ed0f270e4a8dbf2 | 41,934 |
def plotSeqAndFeatures(seq, X, createFiltAx=False, padBothSides=False, capYLim=1000):
"""plots the time series above the associated feature matrix"""
plt.figure(figsize=(10, 8))
if createFiltAx:
nRows = 4
nCols = 7
axSeq = plt.subplot2grid((nRows,nCols), (0,0), colspan=(nCols-1))
axSim = plt.subplot2grid((nR... | 7c555191292945a5b59b77b644cfa5e2400be609 | 41,935 |
def reconstruction(capsule_mask, num_atoms, capsule_embedding, layer_sizes,
num_pixels, reuse, image, balance_factor):
"""Adds the reconstruction loss and calculates the reconstructed image.
Given the last capsule output layer as input of shape [batch, 10, num_atoms]
add 3 fully connected laye... | 4ef2239adf1155177ef6bde5d85271d842b1b159 | 41,937 |
import requests
from bs4 import BeautifulSoup
def fetch_events_ppe(base_url='https://ppe.sas.upenn.edu/events'):
"""
Fetch events from Philosophy Politics & Economics (PPE)
"""
events = []
html_page = requests.get(urljoin(base_url, '/events'))
page_soup = BeautifulSoup(html_page.content, 'html... | 69eac4ce6dc50d6fefbaaa69811bddea3405c1be | 41,938 |
def convert_to_unicode(text):
"""
Converts `text` to Unicode (if it's not already), assuming utf-8 input.
Args:
text (str|bytes): Text to be converted to unicode.
Returns:
str: converted text.
"""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
... | ea74f2738a23ddad3e429e60679d6fef98860590 | 41,939 |
def create_system_id(os_string, architecture):
"""
Create a system-ID by joining the OS-String and the architecture with a hyphen.
Args:
os_string (str):
The Operating system string.
architecture (str):
The Architecture string.
Returns:
The System-ID str... | 7ae682e2d57784ca771c1e50b7e980b56f631947 | 41,940 |
from typing import Counter
def get_pairs(astring):
"""Takes a string and returns all pairs found in the string"""
adict = Counter()
for i in range(len(astring) - 1):
pair = str(astring[i] + astring[i + 1])
adict[pair] += 1
return adict | 599564b5ec2b253daeb94d832ee001e4867bb72a | 41,941 |
def circular_array_rotation(a, k, queries):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/circular-array-rotation/problem
John Watson knows of an operation called a right circular rotation on an array of integers. One rotation operation
moves the last array element to the first position and ... | 940e193fec0ad1f78c499ee8604e418dd0261109 | 41,942 |
def get_roomUsageSchedule(buildingType, roomType, input_calendar={}):
"""
時刻別のスケジュールを読み込む関数(空調、その他)
"""
if RoomUsageSchedule[buildingType][roomType]["空調運転パターン"] == None: # 非空調であれば
roomScheduleRoom = np.zeros((365,24))
roomScheduleLight = np.zeros((365,24))
roomSchedulePerson =... | 0e60732cc95409a4fb06297403e2cfde93f6906f | 41,943 |
def sim_multi_suj_ephy(modality="meeg", n_subjects=10, **kwargs):
"""Simulate electrophysiological data of multiple subjects.
This function basically use :func:`sim_single_suj_ephy` under the hood to
generate the data of multiple subjects.
Parameters
----------
n_subjects : int | 10
Nu... | c6824ecc7cd3fc81c536457abf4d3bad5f0eaf2a | 41,945 |
def get_all_completed_exp_ids(user_id):
"""Returns a list with the ids of all the explorations completed by the
user.
Args:
user_id: str. The id of the user.
Returns:
list(str). A list of the ids of the explorations completed by the
learner.
"""
completed_activities... | 48c02300cc905f613ce09844ca299fef27ad86d0 | 41,946 |
def problem015():
"""
Starting in the top left corner of a 2×2 grid, and only being able to move
to the right and down, there are exactly 6 routes to the bottom right
corner.
How many such routes are there through a 20×20 grid?
p_015.gif
This is a classic combinatorics problem. To... | 60a6531653deab46d3a968d3dd354cdd585def50 | 41,947 |
import math
def _get_v(b1_height: FloatType, b1_width: FloatType, b2_height: FloatType,
b2_width: FloatType) -> tf.Tensor:
"""Get the consistency measurement of aspect ratio for ciou."""
@tf.custom_gradient
def _get_grad_v(height, width):
"""backpropogate gradient."""
arctan = tf.atan(tf.mat... | 4b0d60d3a5fc6d133aa7f59fb79a0121146d5ce3 | 41,948 |
def on(page, visit_page=False, url_params={}):
"""
Creates PageObject with current instance of the selenium_browser.
Args:
page (PageObject): PageObject class name.
visit_page (boolean): Navigate to page.
url_params (dictionary): url parameter object.
Returns:
... | 70510ea6b0cd5992beb0d38c1534e8fd3e11a836 | 41,949 |
def bold(s):
"""Returns the string bold.
Source: http://stackoverflow.com/a/16264094/2570866
:param s:
:type s: str
:return:
:rtype: str
"""
return r'\textbf{' + s + '}' | b457fe063ef5554ee53df0a79894b3b6f43bccf4 | 41,951 |
def plot_lines(lines, color='#269df2', fig_size=(5,5), title=None):
"""plots lines in complelx plane."""
lines = np.array(lines)
tuple_lines = cmplx_lines_to_tuples(lines)
fig, ax = plt.subplots()
fig.set_size_inches(fig_size)
for line in tuple_lines:
x, y = zip(*line)
ax.plot... | 6cb64a86221510e941dd43c0bd29676ce0961e0a | 41,952 |
import typing
def decode(obj: typing.Any) -> typing.Any:
"""Decodes previously encoded information.
"""
if isinstance(obj, PRIMITIVES):
return obj
if isinstance(obj, tuple):
return tuple(map(decode, obj))
if isinstance(obj, list):
return list(map(decode, obj))
i... | bd8607d2c051628b4c10fdf629f23e24cffe41a9 | 41,953 |
def face_distance(face_encodings, face_to_compare):
"""
计算人脸距离
"""
if len(face_encodings) == 0:
return np.empty((0))
return np.linalg.norm(face_encodings - face_to_compare, axis=1) | 506984373165806da0a5e6cee04c05b128768c81 | 41,954 |
def tri_less_eq(v1, v2):
"""Returns True if the tristate v1 is less than or equal to the tristate
v2, where "n", "m" and "y" are ordered from lowest to highest."""
return TRI_TO_INT[v1] <= TRI_TO_INT[v2] | 2e3a5473b2cbb16ea662454c1db26eca171a2b45 | 41,956 |
import base64
def decode_base64_urlsafe(text):
"""Reverse operation of :func:`encode_base64_urlsafe`.
**中文文档**
将base64字符串解码为原字符串。
"""
return base64.urlsafe_b64decode(text.encode("utf-8")).decode("utf-8") | c90ebb246587a61885ac15e37a071721d87c036b | 41,957 |
def init_figure(height=800):
"""Initialize a 3D figure."""
fig = go.Figure()
fig.update_layout(
height=height,
scene_camera=dict(
eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)),
scene=dict(
xaxis=dict(showbackground=False),
yaxis=dict(showb... | da8ca9f02f66e10f1eba85e56089c88a53c81d09 | 41,958 |
import warnings
def compute_indices(wires, n_block_wires):
"""Generate a list containing the wires for each block.
Args:
wires (Iterable): wires that the template acts on
n_block_wires (int): number of wires per block
Returns:
layers (array): array of wire labels for each block
... | dbbc532ad01f365b9dd1139bd6cfe7b410c4ae80 | 41,959 |
def drop_distant(xy, r=6.0):
"""
Drops pedestrians more than r meters away from primary ped
"""
distance_2 = np.sum(np.square(xy - xy[:, 0:1]), axis=2)
mask = np.nanmin(distance_2, axis=0) < r**2
return xy[:, mask], mask | 33ef5241fe98a07f521a00e3d2ef8e317dacd292 | 41,960 |
from typing import Dict
def normalize_score_dict(input_dict: Dict[str, float], exponent=1) -> Dict[str, float]:
"""Takes a dictionary of scores and applies L1-normalization (dividing each value by the sum).
This is the simplest way of turning a collection of scores into a probability distribution.
The e... | 6a8d65d42d7f356b23a0e814841e8005f7daff30 | 41,961 |
def allreduce_ring_single_shard(xs, devices, reduction_fn_string="SUM"):
"""Compute the reduction of all Tensors and put the result everywhere.
Performance-optimized for a ring of devices.
Args:
xs: a list of n tf.Tensors
devices: a list of strings
reduction_fn_string: "SUM" or "MAX"
Returns:
... | 53079ab91c9a8041a1312905573968a2c72ff790 | 41,962 |
def calcPrecision(data, modelName): #Update name to sensitivity
"""Calculates the prediction of the data using a single str or list of strings in the modelName argument. The modelName corresponds to
the columns to be analyzed.
Sensitivity Formula: True Predictions / All Prediction
"""
if isi... | 428d3a72226c7f675f677f5cb8d245e83c502309 | 41,963 |
def bitwise_not(column):
"""
Computes bitwise NOT.
"""
return _with_expr(exprs.BitwiseNot, column) | 1c231a7241851d259fe7d8a1d8f1217e65002c79 | 41,966 |
def ExecuteDownloadPins(pins, processes):
""" 并发processes个线程下载所有pins """
pool = ThreadPool(processes=processes)
data = pool.map(DownloadPinImg, pins)
pool.close()
pool.join()
return data | ba8a3e675a70c889ff94207b176007209a953915 | 41,967 |
def quaternion_ffn(x, dim, name='', activation=None, reuse=None):
""" Implements quaternion feed-forward layer x is [bsz x features] tensor """
input_dim = x.get_shape().as_list()[1] // 4
with tf.compat.v1.variable_scope('Q{}'.format(name), reuse=reuse) as scope:
kernel = glorot([input_dim, dim], na... | 9c0b438dca8452237a0ef638b60bb1b71e379c72 | 41,969 |
def mfacebookToBasic(url):
"""Reformat a url to load mbasic facebook instead of regular facebook, return the same string if
the url don't contains facebook"""
if "m.facebook.com" in url:
return url.replace("m.facebook.com", "mbasic.facebook.com")
elif "www.facebook.com" in url:
return u... | 26b55c23048bd8febe6ef93f15b0c4bbfd434e36 | 41,970 |
def prepareDataForClassification(dataset, start_test):
"""
generates categorical output column, attach to dataframe
label the categories and split into train and test
"""
features = dataset.columns[0:-1]
X = dataset[features]
y = dataset.UpDown
X_train = X[X.index < start_test]
y_t... | 88b42a8145b1f8da469337a8af214cc57c24848e | 41,973 |
def get_new_skill_id():
"""Returns a new skill id.
Returns:
str. A new skill id.
"""
return skill_models.SkillModel.get_new_id('') | 8d1a61be90f47cc3dd6b0113e89026a2b1e66cdc | 41,974 |
def generate_url_to_event_index(website_url):
"""Given URL to workshop's website, generate a URL to its raw `index.html`
file in GitHub repository."""
template = ('https://raw.githubusercontent.com/{name}/{repo}'
'/gh-pages/index.html')
for regex in [Event.WEBSITE_REGEX, Event.REPO_REGE... | e8eb0974a870f2e8f65d7844d680813753e846e3 | 41,975 |
def tokenize(chars: str) -> ListType[str]:
"""Returns the program as a list of tokens (including parenthesis)."""
return chars.replace("(", " ( ").replace(")", " ) ").split() | 6d3a4e307b0e6215ac74116c9c10817e66509b98 | 41,976 |
def _make_coords(src_data_array, dst_affine, dst_width, dst_height):
"""Generate the coordinates of the new projected `xarray.DataArray`"""
coords = _get_nonspatial_coords(src_data_array)
new_coords = _warp_spatial_coords(src_data_array, dst_affine, dst_width, dst_height)
new_coords.update(coords)
r... | 2e97052c67ee52e39024ad4157bf4d0bbb5b1117 | 41,977 |
def remove_ambiguous_solutions(fn_in, db_lines, strict=True, verbose=True):
""" Removes features with identical solutions.
During solving, some tags may be tightly coupled and solve to the same
solution. In these cases, those solutions must be dropped until
disambiguating information can be found.
... | 59dc2de17c1311b1dc7096661dc6b39d0d8fc373 | 41,978 |
def fill_missing_values(df: pd.DataFrame):
"""Fill missing values with mean
Args:
df (pd.DataFrame): [Pandas DataFrame]
Returns:
[pd.DataFrame]: [Returns processed dataframe]
"""
filled_df = df.fillna(df.mean())
return filled_df | 716bdcfa05d9838fa65a683ee072b96478a5f202 | 41,979 |
async def infer_env_add(self, engine, env1, env2):
"""Infer the return type of primitive `env_add`."""
return AbstractScalar({VALUE: ANYTHING, TYPE: xtype.EnvType}) | 61513621c70d71069a5be43dcb601400d5733db1 | 41,980 |
def residuals(fit, obs):
"""Calculate residuals for fit compared to observed data
:fit: list of discrete fit data points
:obs: list of observed data points
:returns: fit minus observed data points
"""
return fit-obs | 46c5eac3620ab8bce58502822aa7d8824bed0988 | 41,981 |
def expected_traces(P, Γ, Λ, X):
"""The trace matrix for accumulating eligibility traces.
That is, a matrix with the same shape as `X`, but where the i-th row
corresponds to the expected value of the eligibility trace in the
steady-state given that the current state is `i`.
Parameters
---------... | 03f26d41ada49712643b3961c5d1df19adf0a069 | 41,983 |
def test_nationality(root, printerror=False):
"""Verifies if there are problems with the nationalities in the
Lattes CV parsed in the argument root.
Args:
root: the Lattes CV that has been parsed with the ElementTree
language.
flag: if 0, there are languages defined in the Lattes CV.... | b1d3b56ecf70e50b4ff485cf644a6c758eb8283a | 41,984 |
def publish_uploaded_video(resp):
"""Publish a uploaded video.
Vid is pointted to the uploaded vidoe.
<meta>
args:
query:
- access_token
- openid
- title
- tags
- cat
- desc
... | be3656861db65b9a046949ac765ea2d7bb8176be | 41,985 |
def _hashable2val(val):
"""Undo _val2hashable()
"""
if isinstance(val, ReadOnlyDict):
return dict(val)
elif isinstance(val, tuple):
return list(map(_hashable2val, val))
else:
return val | 35afe287e80df0871623b106cb4788d4f700afaa | 41,986 |
import re
def get_method_url_protocol(text):
"""Method to extract the Request Method, URL, and Protocol in a string surrounded by quotes"""
match = re.search(r"\".+?\"", text)
if match:
match_string = match.group()
# Note: match should now be a combination of the Request Method, URL, and Proto... | 2dc2ce2ec8985c19ef01a11c7ada7758bdf8f2d4 | 41,987 |
def Make_Full_Trial_Index(Features, Offset: int, Tr_Length: int, Epoch_Len: int):
"""
Parameters:
-----------
Features: list
Features: list
[Ch]->[Freq]->(Time Samples x Trials)
Offset: int
How much prior or after onset
Tr_Length: int
How many samples to use for ... | 06c86da34d3eaa2f7df07235422b86d036663422 | 41,988 |
def cj_curve_fit(x, y):
"""
Determines least squares fit of parabolic data. This is a vectorized
version of ``sdtoolbox.PostShock.LSQ_CJspeed`` using ``np.linalg.lstsq``.
Parameters
----------
x : np.array
Independent data points for curve fitting
y : np.array
Dependent data... | 0e6d9a85eddf4d173648ba64a1da18f83db9e930 | 41,989 |
import torch
def feature2embedding(model, feature, edge_index, edge_attr, args):
"""
Convert further learned features to node embeddings with pre-trained GCN model.
:param model: an instance of GCN model. Remember to load the trained weights.
:param feature: further learned features.
:param edge_i... | b701c56a6dac1746f2c1d2e2b3ffcba0b29cc0a9 | 41,990 |
def read_outputs():
"""Reads all outputs and returns them as a list"""
out_vals = []
for i in range(len(dfs)):
userid_element = driver.find_element_by_xpath(dfs.iloc[i, 2])
out_vals.append(float(userid_element.text.rstrip("%")))
return out_vals | 14304c4733c473fab143d680dac51e83b64bb16b | 41,992 |
def _get_current_assets():
"""Returns the current set of assets in the request stack.
"""
return getattr(_request_ctx_stack.top, 'current_assets', None) | 1e9ff3e7137273748675be848ad534b6ae5a9b75 | 41,993 |
def send_action(action):
"""Sends `action` while processing func command."""
def decorator(func):
@wraps(func)
def command_func(*args, **kwargs):
bot, update = args
bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)
return func(bot, ... | 69d31d5747d05012e6aa019f12b2584e18719e3b | 41,994 |
def ipaddr_to_bin(num: str, t: int) -> list:
"""
Receives an IP address as a character string,
converts it to a decimal number received as
an argument for each octet, and returns it as a list.
"""
if num.count(".") != 3:
usage("invalid arguments")
ctype = "b" if t == 2 else "x"
... | 14371538a68211595b3133ebbf7ec522f5ec6a6a | 41,995 |
import copy
def make_hash(o):
"""
Makes a hash from a dictionary, list, tuple or set to any level, that
contains only other hashable types (including any lists, tuples, sets, and
dictionaries). In the case where other kinds of objects (like classes) need
to be hashed, pass in a collection of objec... | ea9efe7e87c902a8365024749186490c5dc57ae9 | 41,996 |
from typing import List
def list_ids(group_id: str) -> List[str]:
"""List all person ids in a specified `group_id`.
:param group_id:
ID of the group to be listed. `group_id` is created in `group.create`.
:return:
An array of person ids.
"""
if group_id is None:
raise Value... | 0ab3d8ad921dc50377d6167dc1165d2a34901d35 | 41,998 |
def deEmojify(inputString):
"""
Drop emojis
:param inputString:
:return:
"""
return inputString.encode('ascii', 'ignore').decode('ascii') | f0e2ad0ce597e74a133b37244a6bc047b90b1ecd | 41,999 |
from typing import Dict
from typing import Any
def _validate_email(
value: Text,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> Dict[Text, Any]:
"""Validate email is in ticket system."""
if not value:
return {"1_email": None, "previous_email": None}
... | da3221007ae9c4abf179f85da946a229be12777b | 42,000 |
def build_buy_limit_option_order(symbol, quantity, price):
"""Build Buy Limit: Single Option
Buy to open {quanity} contracts of the {symbol with date and option info}
at a Limit of {price} good for the Day.
Args:
symbol: symbol you want to trade. Includes date e.g., XYZ_032015C49
quan... | b61cbb0464c9d60ed4deea22aef3cd945df2a563 | 42,001 |
import time
def gettime():
"""return timestamp"""
return time.time() | 38ac710463f03780c7289fd7746d137c51d6466e | 42,002 |
def parse_speech_in_segment(nlp, segment: Segment) -> list:
"""
Parses all speeches in a segment.
:param segment: segment
:param nlp: spacy nlp object
:return: list of found speeches and its speakers
"""
speeches = []
for i, line in enumerate(segment.lines):
spoken_line, speaker... | e69c22cf990ae5523689d073a76e813b27faecdc | 42,003 |
def parser_of_trace(data):
""" Given a dict of traceroute measurement, extract timestamps, valide hops and rtts to each hop
Args : data (dict)
{u'af': 4,
u'dst_addr': u'192.228.79.201', u'dst_name': u'192.228.79.201', u'endtime': 1483230652,
u'from': u'103.7.251.180', u'fw': 4740, u'lts': 551, u'... | ce582169e22626f1c59c2032d71e2f8fa1f4b89d | 42,004 |
def perceptron(X, y, max_iter=10):
"""
感知机 算法
"""
X = np.mat(X)
y = np.mat(y).T
n, m = X.shape
w = np.zeros((1, m))
b = 0
h = 0.0001
for k in range(max_iter):
for i in range(n):
xi = X[i]
yi = y[i]
if (-1) * yi * (w * xi.T + b) >= ... | 5294b303410e6b354f5991e867cadcf7a989531b | 42,005 |
def is_s3_bucket_global(session, bucket):
""" Return bool for S3 bucket global accessibility
:param session: AWS session
:param bucket: S3 bucket
"""
s3_client = session.client('s3')
try:
s3_acls = s3_client.get_bucket_acl(Bucket=bucket).get('Grants')
if s3_acls:
for ... | 384b4afe4547a5898ed160fe468b18e05ad33f6c | 42,006 |
def cumulative_integral(
control_points: ArrayLike, t: ArrayLike, *, axis: int = 0
) -> np.ndarray:
"""Estimate the cumulative integral along a curve.
Estimates the cumulative integral of a time-parameterized curve along the
chosen axis. The curve is given by a sequence of control points and their
... | 338226578532cd36e060b15df3cf9519ca7c66cc | 42,007 |
def _sqrt(x):
"""
Return square root of an ndarray.
This sqrt function for ndarrays tries to use the exponentiation operator
if the objects stored do not supply a sqrt method.
"""
x = np.clip(x, a_min=0, a_max=None)
try:
return np.sqrt(x)
except (AttributeError, TypeError):
... | 6ec224a4e2f251875bc6c5c11bb9f350deb176b9 | 42,008 |
def get_keyboard_session():
"""Create a new GET_KEYBOARD_SESSION_MESSAGE."""
return create(protobuf.ProtocolMessage.GET_KEYBOARD_SESSION_MESSAGE) | 44b2f10038c060ddf7cbbe59174579fbe2351d30 | 42,009 |
from typing import Tuple
def equilibrate(a: np.ndarray, b: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
""" Expand the shorter of two array by zero padding
"""
le = max(len(a), len(b))
tempa, tempb = np.zeros((le,)), np.zeros((le,))
tempa[:len(a)] = a
tempb[:len(b)] = b
return tempa, tem... | dd16dc8300170796ca8d5b4f9437d24529f69ee5 | 42,010 |
def countObjects(meshes, skel):
"""
Count the total number of vertex groups and shapes combined, as required
for all specified meshes. If no skeleton rig is attached to the mesh, no
vertex groups for bone weights are required.
"""
nVertexGroups, nShapes = getObjectCounts(meshes)
if skel:
... | f37f11cc6492a69d754d0b472d7cdeb79d541b17 | 42,011 |
from datetime import datetime
def create_container(block_blob_service, account_name, container_name):
"""
This function creates the container if it does not exist
:param block_blob_service: The storage blob service instance
:param account_name: The storage account name
:param container_name: The s... | ef28ef93fc5a91e7e8f8fd19b276dc6bd7588487 | 42,012 |
def abs_of_difference(num1: int, num2: int) -> int:
"""
precondition: parameters must be numbers
calculate difference between num1 and num2 and compute absolute value of the result
>>> abs_of_difference(-4,5)
9
>>> abs_of_difference(1,-3)
4
>>> abs_of_difference(2,2)
0
"""
r... | 6cb2ead6a3ed5899a84280f7356a44d515952c7b | 42,014 |
def snapshot_container(
container_ref: "str", repository: "str", tag: "str" = "latest"
) -> "str":
"""Create a snapshot of a running container.
This will store the container's file system in Glance as a new Image.
You can then specify the Image ID in container create requests.
Args:
contai... | a2807e4c76514b2a75183adfd3ae88f7180c4591 | 42,016 |
from datetime import datetime
import json
def lambda_handler(event, context):
"""
Parse the incoming SNS notification for a Deep Security event
"""
timestamp_format = "%Y-%m-%dT%H:%M:%S.%fZ"
if type(event) == type({}):
if 'Records' in event:
print("Processing {} records".f... | ce29d716fb1615acd30513a485acd5e1442606e3 | 42,017 |
def get_random_training_set(nenv):
"""Create a random training_set array with parameters
And generate four different kinds of hyperparameter sets:
* multi hypper parameters with two bond type and two triplet type
* constrained optimization, with noise parameter optimized
* constrained optimization, ... | 9e742bd518beae34a8d4bad50c0a7e993fb65231 | 42,019 |
def basic_ro(centers):
"""
sort the elements in the left-rigth-top-dowm order given its center
"""
return np.lexsort((centers[:,0],centers[:,1])) | d4f6659318f4e1b530e6d072bdf65a6a4bacd1e5 | 42,020 |
def get_constraints(
m,
foot_angles,
which_current_support,
next_foot_angles,
support_foot_pos,
swing_foot_pos,
stateX,
stateY,
N=16,
dt=0.1,
h=1.0,
g=9.81,
tPf=8,
):
"""
INPUTS
m (int): remaining time steps in current foot step;
foot_angles ([N, 1] ve... | cf021c87582db4a326e35208319c63f207a8cf8f | 42,021 |
import io
def compileHTMLTemplate (template, minimizeBooleanAtts = 0):
""" Reads the templateFile and produces a compiled template.
To use the resulting template object call:
template.expand (context, outputFile)
"""
if (isinstance (template, str)):
# It's a string!
templateFile = io.StringIO (template)
... | c9d7596f8d6679f5d91ae91c17e5c3fccdc1e4bc | 42,022 |
def singleton(cls):
"""Singleton pattern to avoid loading class multiple times
"""
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance | 1aeb8fae2f84000361a77ffef651e7eb14564c3e | 42,023 |
def lookup_tables(request):
"""A view to render tables with all of the lookup values."""
# NOTE - defer spatial fields!
# Management Units
# Strains and Raw Strains
agencies = Agency.objects.all()
lakes = Lake.objects.all()
jurisdictions = Jurisdiction.objects.all()
species = Species.... | 80c101eb6335370ee198e0574f181450fff0fadb | 42,024 |
import types
import smtplib
def send_template_mail(recipient, template, variables, sender=None, html=True, subject=None):
"""
Send an e-mail using a template.
Arguments:
recipient -- the address(es) of the recipient(s)
template -- the template name to use. See below for details.
variables --... | 0fb9e4b7a78407b51e3d97e04910a9d4658daa06 | 42,025 |
def combine_sample_data(gr):
"""Combine data from multiple sequencing runs for the same sample.
Take a pandas groupby object representing multiple data points
corresponding the same sequence and sample, from multiple sequence runs.
Sum the barcode and read counts for the combined result. Use the sequen... | 26efbaa1fb61929bfb8b0acf9453067110776ba8 | 42,026 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.