content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def loyalty():
"""Пересчитать индекс лояльности"""
articles = Article.objects.all()
if articles.count() == 0:
logger.info('Пока нет статей для пересчёта. Выходим...')
return False
logger.info('Начало пересчёта индекса лояльности')
logger.info(f'Количество материалов: {articles.count(... | 3db3214e1d6d2f2f3d54f9c1d01807ed9558ef6b | 1,800 |
import json
def user_info(request):
"""Returns a JSON object containing the logged-in student's information."""
student = request.user.student
return HttpResponse(json.dumps({
'academic_id': student.academic_id,
'current_semester': int(student.current_semester),
'name': student.nam... | 41c1bcc8f69d97f76acbe7f15c4bc5cbc2ea6b60 | 1,801 |
def extract_brain_activation(brainimg, mask, roilabels, method='mean'):
"""
Extract brain activation from ROI.
Parameters
----------
brainimg : array
A 4D brain image array with the first dimension correspond to pictures and the rest 3D correspond to brain images
mask : array
... | fac20ea1c99696aab84137964dbbfdfa7bd66612 | 1,802 |
def logit(x):
"""
Elementwise logit (inverse logistic sigmoid).
:param x: numpy array
:return: numpy array
"""
return np.log(x / (1.0 - x)) | 4ce2474a9eb97208613268d3005959a4a162dbe0 | 1,803 |
import hashlib
import binascii
def _base58_decode(address: str) -> bool:
"""
SEE https://en.bitcoin.it/wiki/Base58Check_encoding
"""
try:
decoded_address = base58.b58decode(address).hex()
result, checksum = decoded_address[:-8], decoded_address[-8:]
except ValueError:
retu... | e0610e882b64511743376ce7a0370e7600436411 | 1,804 |
def get_average_matrix(shape, matrices):
""" Take the average matrix by a list of matrices of same shape """
return _ImageConvolution().get_average_matrix(shape, matrices) | dfdd4995751bb2894a7bada961d863bb800e79a5 | 1,805 |
def pph_custom_pivot(n, t0):
"""
O algoritmo recebe uma lista n com pares de coordenadas (a, b) e retorna uma lista s, somente com as
coordenadas que juntas tenham uma razão máxima do tipo r = ((a0 + a1 + ... + an) / (b0 + b1 + ... + bn)).
Esse algoritmo tem complexidade de pior caso O(n^2) quando a ra... | 7853aeac0f4acae6270e82b5c1568f6d0858b779 | 1,806 |
def music(hot_music_url, **kwargs):
"""
get hot music result
:return: HotMusic object
"""
result = fetch(hot_music_url, **kwargs)
# process json data
datetime = parse_datetime(result.get('active_time'))
# video_list = result.get('music_list', [])
musics = []
music_list = result.g... | cf49e0648bb84ff9aa033bf49f732260770b47f5 | 1,807 |
def parse_from_docstring(docstring, spec='operation'):
"""Returns path spec from docstring"""
# preprocess lines
lines = docstring.splitlines(True)
parser = _ParseFSM(FSM_MAP, lines, spec)
parser.run()
return parser.spec | 37026d6e0fd0edf476d59cdd33ac7ec2d04eb38d | 1,808 |
def collection_headings(commodities) -> CommodityCollection:
"""Returns a special collection of headings to test header and chapter
parenting rules."""
keys = ["9900_80_0", "9905_10_0", "9905_80_0", "9910_10_0", "9910_80_0"]
return create_collection(commodities, keys) | 545419cd79fbd86d0a16aad78996977ea1ff4605 | 1,809 |
import getpass
def get_ssh_user():
"""Returns ssh username for connecting to cluster workers."""
return getpass.getuser() | 166048aa258bd0b2c926d03478e8492a405b0f7e | 1,810 |
def tryf(body, *handlers, elsef=None, finallyf=None):
"""``try``/``except``/``finally`` as a function.
This allows lambdas to handle exceptions.
``body`` is a thunk (0-argument function) that represents
the body of the ``try`` block.
``handlers`` is ``(excspec, handler), ...``, where
... | bde4282c4422272717e48a546430d2b93e9d0529 | 1,811 |
def obtain_sheet_music(score, most_frequent_dur):
"""
Returns unformated sheet music from score
"""
result = ""
octaves = [3 for i in range(12)]
accidentals = [False for i in range(7)]
for event in score:
for note_indx in range(len(event[0])):
data = notenum2string(event... | 4c216f2cca0d2054af355bc097c22ff2b7662969 | 1,812 |
def adjacency_matrix(edges):
"""
Convert a directed graph to an adjacency matrix.
Note: The distance from a node to itself is 0 and distance from a node to
an unconnected node is defined to be infinite.
Parameters
----------
edges : list of tuples
list of dependencies between n... | b8743a6fa549b39d5cb24ae1f276e911b954ee5a | 1,813 |
def estimate_Cn(P=1013, T=273.15, Ct=1e-4):
"""Use Weng et al to estimate Cn from meteorological data.
Parameters
----------
P : `float`
atmospheric pressure in hPa
T : `float`
temperature in Kelvin
Ct : `float`
atmospheric struction constant of temperature, typically 10... | b74dd0c91197c24f880521a06d6bcd205d749448 | 1,814 |
import ctypes
def sg_get_scsi_status_str(scsi_status):
""" Fetch scsi status string. """
buff = _get_buffer(128)
libsgutils2.sg_get_scsi_status_str(scsi_status, 128, ctypes.byref(buff))
return buff.value.decode('utf-8') | 2bdf7feb455ccbab659961ddbba04a9fa1daeb85 | 1,815 |
import math
def numpy_grid(x, pad=0, nrow=None, uint8=True):
""" thin wrap to make_grid to return frames ready to save to file
args
pad (int [0]) same as utils.make_grid(padding)
nrow (int [None]) # defaults to horizonally biased rectangle closest to square
uint8 (bool [True... | e83452bb2387d79ca307840487bb4bdd24efed87 | 1,816 |
import functools
def if_active(f):
"""decorator for callback methods so that they are only called when active"""
@functools.wraps(f)
def inner(self, loop, *args, **kwargs):
if self.active:
return f(self, loop, *args, **kwargs)
return inner | 83b4eabaafa9602ad0547f87aeae99a63872152a | 1,817 |
def obs_all_node_target_pairs_one_hot(agent_id: int, factory: Factory) -> np.ndarray:
"""One-hot encoding (of length nodes) of the target location for each node. Size of nodes**2"""
num_nodes = len(factory.nodes)
node_pair_target = np.zeros(num_nodes ** 2)
for n in range(num_nodes):
core_target_... | aed5fa19baf28c798f1e064b878b148867d19053 | 1,818 |
from typing import Callable
from typing import List
import math
def repeat_each_position(shape: GuitarShape, length: int = None, repeats: int = 2, order: Callable = asc) -> List[
List[FretPosition]]:
"""
Play each fret in the sequence two or more times
"""
if length is not None:
div_length... | 9783e218134839410e02d4bc5210804d6a945d6d | 1,819 |
import csv
import gzip
from StringIO import StringIO
import pandas
def gz_csv_read(file_path, use_pandas=False):
"""Read a gzipped csv file.
"""
with gzip.open(file_path, 'r') as infile:
if use_pandas:
data = pandas.read_csv(StringIO(infile.read()))
else:
reader = c... | 725132f37454b66b6262236966c96d4b48a81049 | 1,820 |
def init_block(in_channels, out_channels, stride, activation=nn.PReLU):
"""Builds the first block of the MobileFaceNet"""
return nn.Sequential(
nn.BatchNorm2d(3),
nn.Conv2d(in_channels, out_channels, 3, stride, 1, bias=False),
nn.BatchNorm2d(out_channels),
make_activation(activat... | 966ccb1ca1cb7e134db3ac40bb4daf54950743b1 | 1,821 |
def address_working(address, value=None):
"""
Find, insert or delete from database task address
:param address: website address example: https://www.youtube.com/
:param value: True: add , False: remove, default: find
:return:
"""
global db
if value is True:
db.tasks.insert_one({'... | 5879fb6f3d4756aceb8424a5fc22fd232841802c | 1,822 |
def merge_default_values(resource_list, default_values):
"""
Generate a new list where each item of original resource_list will be merged with the default_values.
Args:
resource_list: list with items to be merged
default_values: properties to be merged with each item list. If the item alrea... | c2e98260a34762d17185eacdfc2fb4be1b3a45f3 | 1,823 |
from datetime import datetime
import pytz
def finish_scheduling(request, schedule_item=None, payload=None):
"""
Finalize the creation of a scheduled action. All required data is passed
through the payload.
:param request: Request object received
:param schedule_item: ScheduledAction item being pr... | fa0fb4648ef9d750eca9f19ea435fd57ab433ad8 | 1,824 |
import json
def analyze(results_file, base_path):
"""
Parse and print the results from gosec audit.
"""
# Load gosec json Results File
with open(results_file) as f:
issues = json.load(f)['Issues']
if not issues:
print("Security Check: No Issues Detected!")
return ([], ... | a016f4ba389305103c9bbab1db94706053237e5a | 1,825 |
def _peaks(image,nr,minvar=0):
"""Divide image into nr quadrants and return peak value positions."""
n = np.ceil(np.sqrt(nr))
quadrants = _rects(image.shape,n,n)
peaks = []
for q in quadrants:
q_image = image[q.as_slice()]
q_argmax = q_image.argmax()
q_maxpos = np.unravel_ind... | f7ecc3e5fafd55c38a85b4e3a05a04b25cbd97cf | 1,826 |
def pprint(value):
"""A wrapper around pprint.pprint -- for debugging, really."""
try:
return pformat(value)
except Exception as e:
return "Error in formatting: %s: %s" % (e.__class__.__name__, e) | 1ce07b2f8f3e5e15c5f5cae8f7642ab97201a559 | 1,827 |
def connection_type_validator(type):
"""
Property: ConnectionInput.ConnectionType
"""
valid_types = [
"CUSTOM",
"JDBC",
"KAFKA",
"MARKETPLACE",
"MONGODB",
"NETWORK",
"SFTP",
]
if type not in valid_types:
raise ValueError("% is not a... | cc2ed6096097c719b505356e69a5bb5cdc109495 | 1,828 |
import matplotlib.pyplot as plt
def plot_time_series(meter_data, temperature_data, **kwargs):
""" Plot meter and temperature data in dual-axes time series.
Parameters
----------
meter_data : :any:`pandas.DataFrame`
A :any:`pandas.DatetimeIndex`-indexed DataFrame of meter data with the column ... | 9e77f5e997d86ccb6932b3f192f979b3630d9458 | 1,829 |
import calendar
import time
def render_pretty_time(jd):
"""Convert jd into a pretty string representation"""
year, month, day, hour_frac = sweph.revjul(jd)
_, hours, minutes, seconds = days_frac_to_dhms(hour_frac/24)
time_ = calendar.timegm((year,month,day,hours,minutes,seconds,0,0,0))
return time... | 07c63429ae7881fbdec867e8bebab7578bfaacdd | 1,830 |
import json
def jsonify(obj):
"""Dump an object to JSON and create a Response object from the dump.
Unlike Flask's native implementation, this works on lists.
"""
dump = json.dumps(obj)
return Response(dump, mimetype='application/json') | 72e1fb425507d5905ef96de05a146805f5aa4175 | 1,831 |
def section(stree):
"""
Create sections in a :class:`ScheduleTree`. A section is a sub-tree with
the following properties: ::
* The root is a node of type :class:`NodeSection`;
* The immediate children of the root are nodes of type :class:`NodeIteration`
and have same parent.
... | edd6682d1ff2a637049a801d548181d35e07961a | 1,832 |
def was_csv_updated() -> bool:
""" This function compares the last modified time on the csv file to the
actions folder to check which was last modified.
1. check if csv or files have more actions.
2. if same number of actions, assume the update was made in the csv
"""
csv_actions = get_cas_from... | 7cf78696fa59e8abbe968916191600a265c96305 | 1,833 |
import math
def MakeBands(dR, numberOfBands, nearestInteger):
"""
Divide a range into bands
:param dR: [min, max] the range that is to be covered by the bands.
:param numberOfBands: the number of bands, a positive integer.
:param nearestInteger: if True then [floor(min), ceil(max)] is used.
:... | 104720371d1f83bf2ee2c8fddbf05401ec034560 | 1,834 |
import math
def euler719(n=10**12):
"""Solution for problem 719."""
return sum(i*i
for i in range(2, 1 + int(math.sqrt(n)))
if can_be_split_in_sum(i*i, i)) | 3f814ed837ad58f73f901a81af34ac31b520b372 | 1,835 |
def inner(a, b):
"""
Inner product of two tensors.
Ordinary inner product of vectors for 1-D tensors (without complex
conjugation), in higher dimensions a sum product over the last
axes.
Note:
Numpy argument out is not supported.
On GPU, the supported dtypes are np.float16, and... | b09ee6e22fd6c9bd7c1fd758fa62b38ad8fae1ab | 1,836 |
def stern_warning(warn_msg: str) -> str:
"""Wraps warn_msg so that it prints in red."""
return _reg(colorama.Fore.RED, warn_msg) | 639f0f6aaf3ce1f6ad46ed0f5d852be3457337fb | 1,837 |
def alt2temp_ratio(H, alt_units=default_alt_units):
"""
Return the temperature ratio (temperature / standard temperature for
sea level). The altitude is specified in feet ('ft'), metres ('m'),
statute miles, ('sm') or nautical miles ('nm').
If the units are not specified, the units in defaul... | c46ca3d63169676ccda223f475927a902a82a15e | 1,838 |
def encode_message(key, message):
""" Encodes the message (string) using the key (string) and
pybase64.urlsafe_b64encode functionality """
keycoded = []
if not key:
key = chr(0)
# iterating through the message
for i in range(len(message)):
# assigning a key_character based on ... | ea3a5403878dc58f1faa586c9851863a670c8cd0 | 1,839 |
import argparse
import os
def cfg():
"""Configuration of argument parser."""
parser = argparse.ArgumentParser(
description="Crawl SolarEdge and stores results in InfluxDB",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# TODO: error message when missing env variable
par... | 1aba01ccc8d0b99227d541d56e866fabd62a3941 | 1,840 |
from IPython.core.debugger import Pdb
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
import warnings
def get_debugger():
"""
Returns a debugger instance
"""
try:
pdb = Pdb()
except ImportError:
try:
IPShell(argv=[""])
pdb = Pdb()
... | bfc1600260b62dee8b89145635044ea6f0754064 | 1,841 |
def add_sibling(data, node_path, new_key, new_data, _i=0):
"""
Traversal-safe method to add a siblings data node.
:param data: The data object you're traversing.
:param node_path: List of path segments pointing to the node you're creating a
sibling of. Same as node_path of traverse()
:param new_key: The sibling... | 4bc11315eab686659edc9f7eb8479508d3ca37fb | 1,842 |
def draw_pnl(ax, df):
"""
Draw p&l line on the chart.
"""
ax.clear()
ax.set_title('Performance')
index = df.index.unique()
dt = index.get_level_values(level=0)
pnl = index.get_level_values(level=4)
ax.plot(
dt, pnl, '-',
color='green',
linewidth=1.0,
... | 6210c1861943bf61a7df8dbe2124f8f0f5e77e89 | 1,843 |
def maxRstat(Z, R, i):
"""
Return the maximum statistic for each non-singleton cluster and its
children.
Parameters
----------
Z : array_like
The hierarchical clustering encoded as a matrix. See `linkage` for more
information.
R : array_like
The inconsistency matrix.... | d63c6370e9d896a2e315012fa92fa650d1acaee8 | 1,844 |
import re
def strip_characters(text):
"""Strip characters in text."""
t = re.sub('\(|\)|:|,|;|\.|’|”|“|\?|%|>|<', '', text)
t = re.sub('/', ' ', t)
t = t.replace("'", '')
return t | 763ddc837ef9be19aa067e362c312ebd88632ed7 | 1,845 |
import os
def get_trained_model(datapath, dataset, image_size, nb_labels):
"""Recover model weights stored on the file system, and assign them into
the `model` structure
Parameters
----------
datapath : str
Path of the data on the file system
dataset : str
Name of the dataset
... | 66d685553989a6e03df0b6db4891b5b423a6f937 | 1,846 |
def make_std_secgroup(name, desc="standard security group"):
"""
Returns a standarized resource group with rules for ping and ssh access.
The returned resource can be further configured with additional rules by the
caller.
The name parameter is used to form the name of the ResourceGroup, and al... | b53a65bdc04871c0d7ca56574c1852906b2d9351 | 1,847 |
def parse_plot_args(*args, **options):
"""Parse the args the same way plt.plot does."""
x = None
y = None
style = None
if len(args) == 1:
y = args[0]
elif len(args) == 2:
if isinstance(args[1], str):
y, style = args
else:
x, y = args
elif len(... | 7687ed00785c1ab20fdf2f7bdc969fde3c75840f | 1,848 |
def publications_classification_terms_get(search=None): # noqa: E501
"""List of Classification Terms
List of Classification Terms # noqa: E501
:param search: search term applied
:type search: str
:rtype: ApiOptions
"""
return 'do some magic!' | 6633c91d59a5df7805979bd85a01f8eb1c269946 | 1,849 |
def lu_decompose(tri_diagonal):
"""Decompose a tri-diagonal matrix into LU form.
Parameters
----------
tri_diagonal : TriDiagonal
Represents the matrix to decompose.
"""
# WHR Appendix B: perform LU decomposition
#
# d[0] = hd[0]
# b[i] = hu[i]
#
# Iterative algorith... | 423bb853d96b534055bd00b3c768158c86826b1b | 1,850 |
def _card(item):
"""Handle card entries
Returns: title (append " - Card" to the name,
username (Card brand),
password (card number),
url (none),
notes (including all card info)
"""
notes = item.get('notes', "") or ""
# Add car... | fc7d5e4b960019b05ffe7ca02fd3d1a94d69b303 | 1,851 |
def s3():
"""Boto3 S3 resource."""
return S3().resource | 6402deaafa2ae7d599de1c8e8c67b9e669c06463 | 1,852 |
def SUE(xmean=None,ymean=None,xstdev=None,ystdev=None,rho=None, \
xskew=None,yskew=None,xmin=None,xmax=None,ymin=None,ymax=None, \
Npt=300,xisln=False,yisln=False):
"""
SKEWED UNCERTAINTY ELLIPSES (SUE)
Function to plot uncertainty SUEs (or 1 sigma contour of a bivariate
split-normal di... | 8b298a2d2ba04a3f1262205f19b1993a4701e279 | 1,853 |
def create_label(places, size, corners, resolution=0.50, x=(0, 90), y=(-50, 50), z=(-4.5, 5.5), scale=4, min_value=np.array([0., -50., -4.5])):
"""Create training Labels which satisfy the range of experiment"""
x_logical = np.logical_and((places[:, 0] < x[1]), (places[:, 0] >= x[0]))
y_logical = np.logical_... | 1ae1ed49674fbcee15fb6a8201e69be2c82630f9 | 1,854 |
def usage():
"""Serve the usage page."""
return render_template("meta/access.html") | 909272906678c9980f379342b87c8af6a00ab89c | 1,855 |
def GetCache(name, create=False):
"""Returns the cache given a cache indentfier name.
Args:
name: The cache name to operate on. May be prefixed by "resource://" for
resource cache names or "file://" for persistent file cache names. If
only the prefix is specified then the default cache name for tha... | b8e1796d772506d4abb9f8261df33b4cf6777934 | 1,856 |
def rf_local_divide_int(tile_col, scalar):
"""Divide a Tile by an integral scalar"""
return _apply_scalar_to_tile('rf_local_divide_int', tile_col, scalar) | 0a8c44cafcc44d323fb931fc1b037759ad907d18 | 1,857 |
from typing import Any
from typing import Dict
def or_(*children: Any) -> Dict[str, Any]:
"""Select devices that match at least one of the given selectors.
>>> or_(tag('sports'), tag('business'))
{'or': [{'tag': 'sports'}, {'tag': 'business'}]}
"""
return {"or": [child for child in children]} | 0bda8654ddc0f5dac80c8eb51b0d6d55b57c9e2a | 1,858 |
def get_width_and_height_from_size(x):
""" Obtains width and height from a int or tuple """
if isinstance(x, int): return x, x
if isinstance(x, list) or isinstance(x, tuple): return x
else: raise TypeError() | 581c9f332613dab5de9b786ce2bac3387ee1bd3b | 1,859 |
def remove_stopwords(lista,stopwords):
"""Function to remove stopwords
Args:
lista ([list]): list of texts
stopwords ([list]): [description]
Returns:
[list]: List of texts without stopwords
"""
lista_out = list()
for idx, text in enumerate(lista):
text = ' '.joi... | edca74bb3a041a65a628fcd3f0c71be5ad4858df | 1,860 |
import time
import io
import os
def Skeletonize3D(directory, crop=None, flip='y', dtype=None):
"""Skeletonize TrailMap results.
Parameters
----------
directory : string
Path to directory with segmented data.
crop : dict (optional, default None)
Dictionary with ImageJ-format cr... | 72eaf148cad51df01c9487b12a492a5bd2cd8661 | 1,861 |
def get_users_report(valid_users, ibmcloud_account_users):
"""get_users_report()"""
users_report = []
valid_account_users = []
invalid_account_users = []
# use case 1: find users in account not in valid_users
for account_user in ibmcloud_account_users:
# check if account user is in va... | a96f8835496f82d8b6f8cd4f248ed8a03676795b | 1,862 |
def insert_bn(names):
"""Insert bn layer after each conv.
Args:
names (list): The list of layer names.
Returns:
list: The list of layer names with bn layers.
"""
names_bn = []
for name in names:
names_bn.append(name)
if 'conv' in name:
position = nam... | efe1e6a3218fb33f74c17f90a06e2d18d17442e5 | 1,863 |
def convert_format(parameters):
"""Converts dictionary database type format to serial transmission format"""
values = parameters.copy()
for key, (index, format, value) in values.items():
if type(format) == type(db.Int):
values[key] = (index, 'i', value) # signed 32 bit int (arduino long... | fae756d54cbef6ecc7de07d123513b773ccf1433 | 1,864 |
def prepare(_config):
"""
Preparation of the train and validation datasets for the training and initialization of the padertorch trainer,
using the configuration dict.
Args:
_config: Configuration dict of the experiment
Returns:
3-Tuple of the prepared datasets and the trainer.
... | eab0f93d0682dd8aae8ec8c751b9ff795c9f68e2 | 1,865 |
import warnings
def getproj4(epsg):
"""
Get projection file (.prj) text for given epsg code from
spatialreference.org. See: https://www.epsg-registry.org/
.. deprecated:: 3.2.11
This function will be removed in version 3.3.5. Use
:py:class:`flopy.discretization.structuredgrid.Structur... | 80dccf9722f7dd45cca87dcd78775868cfe545ad | 1,866 |
def vpn_tunnel_inside_cidr(cidr):
"""
Property: VpnTunnelOptionsSpecification.TunnelInsideCidr
"""
reserved_cidrs = [
"169.254.0.0/30",
"169.254.1.0/30",
"169.254.2.0/30",
"169.254.3.0/30",
"169.254.4.0/30",
"169.254.5.0/30",
"169.254.169.252/30",
... | 01807a4db2fc80cf8253b0e000e412b0dce1a528 | 1,867 |
def choose_media_type(accept, resource_types):
"""choose_media_type(accept, resource_types) -> resource type
select a media type for the response
accept is the Accept header from the request. If there is no Accept header, '*/*' is assumed. If the Accept header cannot be parsed, HTTP400BadRequest is rai... | 876ad2ace8af69f5c6dc83d91d598220935987d5 | 1,868 |
import math
def get_border_removal_size(image: Image, border_removal_percentage: float = .04, patch_width: int = 8):
"""
This function will compute the border removal size. When computing the boarder removal the patch size becomes
important the output shape of the image will always be an even factor of th... | f0f236b1d2a13058042269e0e85f52f37fb47b5e | 1,869 |
def get_natural_num(msg):
"""
Get a valid natural number from the user!
:param msg: message asking for a natural number
:return: a positive integer converted from the user enter.
"""
valid_enter = False
while not valid_enter:
given_number = input(msg).strip()
i... | 77bed94bf6d3e5ceb56d58eaf37e3e687e3c94ba | 1,870 |
from typing import Optional
def _decode_panoptic_or_depth_map(map_path: str) -> Optional[str]:
"""Decodes the panoptic or depth map from encoded image file.
Args:
map_path: Path to the panoptic or depth map image file.
Returns:
Panoptic or depth map as an encoded int32 numpy array bytes or None if not... | 1f3b81827ba911614d8979b187b8cde7f10078fe | 1,871 |
def splitstr(s, l=25):
""" split string with max length < l
"(i/n)"
"""
arr = [len(x) for x in s.split()]
out = []
counter = 5
tmp_out = ''
for i in xrange(len(arr)):
if counter + arr[i] > l:
out.append(tmp_out)
tmp_out = ''
counter = 5... | 0d84d7bbf420d1f97993be459764c37fed50f8b3 | 1,872 |
import re
def SplitRequirementSpecifier(requirement_specifier):
"""Splits the package name from the other components of a requirement spec.
Only supports PEP 508 `name_req` requirement specifiers. Does not support
requirement specifiers containing environment markers.
Args:
requirement_specifier: str, a... | d71eee50c162756ac7aae0bd120323d50d3ab255 | 1,873 |
def arctanh(var):
"""
Wrapper function for atanh
"""
return atanh(var) | 955d09821d78703c99fc2e51f70ca0fc47b0c943 | 1,874 |
def predict_sentiment(txt: str, direc: str = 'models/sentiment/saved_models/model50') -> float:
"""
predicts sentiment of string
only use for testing not good for large data because
model is loaded each time
input is a txt string
optional directory change for using different models
returns a... | d7ff2d361792032eb097e0b0e9818da6ce3af1e5 | 1,875 |
import numpy
def logfbank(signal,
samplerate=16000,
winlen=0.025,
winstep=0.01,
nfilt=26,
nfft=512,
lowfreq=0,
highfreq=None,
preemph=0.97,
winfunc=lambda x: numpy.ones((x,))):
"""Compute log Mel-fil... | 670d5faf73fcca6da249d9b5c9fb6965eafab855 | 1,876 |
def get_rmsd( pose, second_pose, overhang = 0):
"""
Get RMSD assuming they are both the same length!
"""
#id_map = get_mask_for_alignment(pose, second_pose, cdr, overhang)
#rms = rms_at_corresponding_atoms_no_super(pose, second_pose, id_map)
start = 1 + overhang
end = pose.total_residue()... | 80af3478fe946243cba5e7f3e45c61a8ea9af1d1 | 1,877 |
def inverse(a: int, n: int):
"""
calc the inverse of a in the case of module n, where a and n must be mutually prime.
a * x = 1 (mod n)
:param a: (int)
:param n: (int)
:return: (int) x
"""
assert greatest_common_divisor(a, n) == 1
return greatest_common_divisor_with_coefficient(a, n)... | 1012c4c69b81dccd2ecfd0c5cddf7a7bd9b2c1f8 | 1,878 |
def create_app():
"""Create the Flask application."""
return app | 7ff5c1e66ab48a5f262beb7abfa21e28680605c9 | 1,879 |
def generate_prime_candidate(length):
""" Genera un integer impar aleatorimanete
param size: tamanio del numero deseado
return:integer
"""
p = big_int(length)
p |= (1 << length - 1) | 1
return p | bdae69644156191a5388b23d7cf1853b8b0273b6 | 1,880 |
def PathPrefix(vm):
"""Determines the prefix for a sysbench command based on the operating system.
Args:
vm: VM on which the sysbench command will be executed.
Returns:
A string representing the sysbench command prefix.
"""
if vm.OS_TYPE == os_types.RHEL:
return INSTALL_DIR
else:
return '... | e0ade1847bce77f3b4efd9f801b36b219917f0b8 | 1,881 |
from typing import Union
import asyncio
def get_next_valid_seq_number(
address: str, client: SyncClient, ledger_index: Union[str, int] = "current"
) -> int:
"""
Query the ledger for the next available sequence number for an account.
Args:
address: the account to query.
client: the net... | cb2a502aabc474ab79ea14bd2305dda5bfe8b479 | 1,882 |
import re
def apps_list(api_filter, partial_name, **kwargs):
"""List all defined applications. If you give an optional command line
argument, the apps are filtered by name using this string."""
params = {}
if api_filter:
params = {"filter": api_filter}
rv = okta_manager.call_okta("/apps", ... | bafb2f1eb65e735b40613e302fcbc85507c25cb8 | 1,883 |
def jacquez(s_coords, t_coords, k, permutations=99):
"""
Jacquez k nearest neighbors test for spatio-temporal interaction.
:cite:`Jacquez:1996`
Parameters
----------
s_coords : array
(n, 2), spatial coordinates.
t_coords : array
(n, ... | dc71d74cc0e0159e1164d659ca3f07f3b9a61dd6 | 1,884 |
def array2tensor(array, device='auto'):
"""Convert ndarray to tensor on ['cpu', 'gpu', 'auto']
"""
assert device in ['cpu', 'gpu', 'auto'], "Invalid device"
if device != 'auto':
return t.tensor(array).float().to(t.device(device))
if device == 'auto':
return t.tensor(array).float().to... | 53826ad5b19a4e030bc3e98857c9b3285094370f | 1,885 |
def to_json(graph):
"""Convert this graph to a Node-Link JSON object.
:param BELGraph graph: A BEL graph
:return: A Node-Link JSON object representing the given graph
:rtype: dict
"""
graph_json_dict = node_link_data(graph)
# Convert annotation list definitions (which are sets) to canonica... | 325053a0838bbf1ab70a4fb61e17f93f27c80dab | 1,886 |
def export(df: pd.DataFrame):
"""
From generated pandas dataframe to xml configuration
:param df: computed pandas dataframe
:return:
"""
return df | 445e91a419746afef8062dcc1e6691572ba9390d | 1,887 |
def has_same_attributes(link1, link2):
"""
Return True if the two links have the same attributes for our purposes,
ie it is OK to merge them together into one link
Parameters:
link1 - Link object
link2 - Link object
Return value:
True iff link1 and link2 have compatible attribu... | e80f62d01ef18e547a2e7718ac2bb1ca3001b84f | 1,888 |
def test_signals_creation(test_df, signal_algorithm):
"""Checks signal algorithms can create a signal in a Pandas dataframe."""
test_df_copy = test_df.copy()
original_columns = test_df.columns
# We check if the test series has the columns needed for the rule to calculate.
required_columns = Api.re... | 5a4515092d778090a77ce5933ad2e79b4d62df36 | 1,889 |
def get_prev_day(d):
"""
Returns the date of the previous day.
"""
curr = date(*map(int, d.split('-')))
prev = curr - timedelta(days=1)
return str(prev) | 9195c0be4fc25a68b0bb94e953bafd407c5931a3 | 1,890 |
import types
def copy_function(old_func, updated_module):
"""Copies a function, updating it's globals to point to updated_module."""
new_func = types.FunctionType(old_func.__code__, updated_module.__dict__,
name=old_func.__name__,
argdefs=old_func._... | e09022f734faa1774a3ac592c0e12b0b007ae8e3 | 1,891 |
import random
def get_random_color():
"""
获得一个随机的bootstrap颜色字符串标识
:return: bootstrap颜色字符串
"""
color_str = [
'primary',
'secondary',
'success',
'danger',
'warning',
'info',
'dark',
]
return random.choice(color_str) | 898814996aa5ada8f4000244887af382b8b9e1bc | 1,892 |
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
Implement a single forward step of the LSTM-cell as described in Figure (4)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
c_prev ... | 1457b7bb53f0658d7c24744c3a06d4cdcdd4096e | 1,893 |
def logged_run(cmd, buffer):
"""Return exit code."""
pid = Popen(cmd, stdout=PIPE, stderr=STDOUT)
pid.wait()
buffer.write(pid.stdout.read())
return pid.returncode | 99a1aa4f8997ef7665a8e994b3df3d4ffe8a844b | 1,894 |
def _decode_and_format_b64_string(b64encoded_string, item_prefix=None,
current_depth=1, current_index=1):
"""Decode string and return displayable content plus list of decoded artifacts."""
# Check if we recognize this as a known file type
(_, f_type) = _is_known_b64_prefix(... | ebf85b6b06319c6b5d8d35b5d419d3ff3b60204a | 1,895 |
import os
import shutil
import time
def buildDMG():
"""
Create DMG containing the rootDir
"""
outdir = os.path.join(WORKDIR, 'diskimage')
if os.path.exists(outdir):
shutil.rmtree(outdir)
imagepath = os.path.join(outdir,
'python-%s-macosx'%(getFullVersion(),))
i... | 8acb9f52219ddc6000bb6cb38d52c04161c17fa3 | 1,896 |
import json
def create_iam_role(iam_client):
"""Create an IAM role for the Redshift cluster to have read only access to
S3.
Arguments:
iam_client (boto3.client) - IAM client
Returns:
role_arn (str) - ARN for the IAM Role
"""
# Create the role if it doesn't already exist.
... | 949026bae3edc1dacc5057427ecf3e21490bd9b8 | 1,897 |
import array
def cone_face_to_span(F):
"""
Compute the span matrix F^S of the face matrix F,
that is, a matrix such that
{F x <= 0} if and only if {x = F^S z, z >= 0}.
"""
b, A = zeros((F.shape[0], 1)), -F
# H-representation: A x + b >= 0
F_cdd = Matrix(hstack([b, A]), number_ty... | ae928e179085116fa8ac48fd01841458bdcd38ec | 1,898 |
def neighborhood(index, npoints, maxdist=1):
"""
Returns the neighbourhood of the current index,
= all points of the grid separated by up to
*maxdist* from current point.
@type index: int
@type npoints: int
@type maxdist int
@rtype: list of int
"""
return [index + i for i in ran... | 98166d810daa6b99862a4c9f6d1629fdfa571bd0 | 1,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.