content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def valida_cnpj(cnpj):
"""
Valida CNPJs, retornando apenas a string de números válida.
# CNPJs errados
>>> validar_cnpj('abcdefghijklmn')
False
>>> validar_cnpj('123')
False
>>> validar_cnpj('')
False
>>> validar_cnpj(None)
False
>>> validar_cnpj('12345678901... | 4b3d2591e6f196cccdd8d68089e36f22ba1d1a98 | 1,723 |
def km_miles(kilometers):
"""Usage: Convert kilometers to miles"""
return kilometers/1.609 | 5480c065f904dfc1959691e158653fd0e6bb67e6 | 1,724 |
def is_enterprise_learner(user):
"""
Check if the given user belongs to an enterprise. Cache the value if an enterprise learner is found.
Arguments:
user (User): Django User object.
Returns:
(bool): True if given user is an enterprise learner.
"""
cached_is_enterprise_key = get... | 76bbf24dafec3ec26ec23504b8d064fbe5c21c52 | 1,725 |
def point_cloud(depth, colors):
"""Transform a depth image into a point cloud with one point for each
pixel in the image, using the camera transform for a camera
centred at cx, cy with field of view fx, fy.
depth is a 2-D ndarray with shape (rows, cols) containing
depths from 1 to 254 inclusive. Th... | 75aa681fa817b29e23ed76beb8504ef1bbaa5d67 | 1,726 |
import tqdm
def structural_email(data, pos_parser=True, bytedata_parser_threshold=50, reference_parser_match_type=2):
"""
This is a parser pipeline, parser order matters.
1. string => structure email to separate => header, body, others
2. body => remove typo and some irrelevant words => body
3. bo... | b68227f10ae6e78f6e12ab174e2360c0828e2038 | 1,727 |
import six
def build_batches(data, conf, turn_cut_type='tail', term_cut_type='tail'):
"""
Build batches
"""
_turns_batches = []
_tt_turns_len_batches = []
_every_turn_len_batches = []
_response_batches = []
_response_len_batches = []
_label_batches = []
batch_len = len(data[... | e82411d5b51171c9590bd5f150dfeca666b3a3a6 | 1,728 |
def is_notebook():
"""Check if pyaedt is running in Jupyter or not.
Returns
-------
bool
"""
try:
shell = get_ipython().__class__.__name__
if shell == "ZMQInteractiveShell":
return True # Jupyter notebook or qtconsole
else:
return False
excep... | 51c0806ba17cbaef5732379a5e9c68d8eb171d31 | 1,729 |
def strategy(history, memory):
"""
Tit-for-tat, except we punish them N times in a row if this is the Nth time they've
initiated a defection.
memory: (initiatedDefections, remainingPunitiveDefections)
"""
if memory is not None and memory[1] > 0:
choice = 0
memory = (memory[0], m... | bf8d09417c246f9f88a721dfcc4408f49195fd1a | 1,730 |
def get_primitives(name=None, primitive_type=None, primitive_subtype=None):
"""Get a list of the available primitives.
Optionally filter by primitive type: ``transformation`` or ``aggregation``.
Args:
primitive_type (str):
Filter by primitive type. ``transformation`` or ``aggregation``... | c833a2b1d52dc135a4518aa6fa7147ae58b73b9a | 1,731 |
def _unpack_batch_channel(data, old_shape):
"""Unpack the data channel dimension.
"""
data = nnvm.sym.transpose(data, axes=(0, 4, 1, 5, 2, 3))
data = nnvm.sym.reshape(data, shape=old_shape)
return data | 1b59f6fbceabef3a28b4180a5bc808621e11c6b7 | 1,732 |
def get_branch_user(branch):
"""Get user name for given branch."""
with Command('git', 'log', '--pretty=tformat:%an', '-1', branch) as cmd:
for line in cmd:
return line | 0845dc69cbd949c1f739ca877c0b182740fa7bdb | 1,733 |
from .qtmultimedia import find_system_cameras
from electrum_cintamani import qrscanner
def find_system_cameras() -> Mapping[str, str]:
"""Returns a camera_description -> camera_path map."""
if sys.platform == 'darwin' or sys.platform in ('windows', 'win32'):
try:
except ImportError as e:
... | adefb85f99494f71e1c55e74f8b4e589d96daacf | 1,734 |
def _shape_list(x):
"""Return list of dims, statically where possible."""
static = x.get_shape().as_list()
shape = tf.shape(x)
ret = []
for i, static_dim in enumerate(static):
dim = static_dim or shape[i]
ret.append(dim)
return ret | 0add2ba771dd99817654ce48c745db5c5f09d3aa | 1,735 |
import packaging
def upgrade_common(ctx, config, deploy_style):
"""
Common code for upgrading
"""
remotes = upgrade_remote_to_config(ctx, config)
project = config.get('project', 'ceph')
extra_pkgs = config.get('extra_packages', [])
log.info('extra packages: {packages}'.format(packages=ext... | 13840203bceb6b6ae069d47fa03a278dac3b0bc6 | 1,736 |
def convert2define(name):
"""
returns the name of the define used according to 'name' which is the name of the file
"""
header = toupper(toalphanum(name))
return "__" + header + "__" | 9f48181310db2732a26b846cb8270eb44bd06004 | 1,737 |
def url_exists(url):
"""
Checks if a url exists
:param url:
:return:
"""
p = urlparse(url)
conn = httplib.HTTPConnection(p.netloc)
conn.request('HEAD', p.path)
resp = conn.getresponse()
return resp.status == 301 or resp.status == 200 | 3ef7d71fed0c85d4e75e910e5354b817c656c0d7 | 1,738 |
def add_header(cmd):
"""
:param cmd: the command with its values
:return: adds a header and returns it, ready to be send
"""
# get the length of the length of the cmd (for how many spaces needed)
header = str(len(cmd))
for i in range(get_digits(len(cmd)), HEADERSIZE):
header = heade... | 91a23eaee6ddd01ce5b5d62b3d43221b25bcd541 | 1,739 |
def stat_selector(player, stat, in_path, year):
"""
Selects stat for player in game year selected
Parameters
----------
player
The player being assessed (str)
stat
The stat being assessed (str)
in_path
The path to the folder containing player data (str)
year
... | 7f04086e4e3baee273baa1b90e1e0735856091d5 | 1,740 |
import torch
def get_cali_samples(train_data_loader, num_samples, no_label=True):
"""Generate sub-dataset for calibration.
Args:
train_data_loader (torch.utils.data.DataLoader):
num_samples (int):
no_label (bool, optional): If the dataloader has no labels. Defaults to True.
Ret... | 297ea0384b1e7f0a6ea51fc37325e57eb1cb8afa | 1,741 |
from typing import List
from typing import Tuple
import requests
import json
def fetch_available_litteraturbanken_books() -> List[Tuple[str, str]]:
"""Fetch available books from Litteraturbanken."""
url = "https://litteraturbanken.se/api/list_all/etext?exclude=text,parts,sourcedesc,pages,errata&filter_and=%7B... | ff14af499335c6229d1f8d995c343c62fff7db74 | 1,742 |
def soup_from_psf(psf):
"""
Returns a Soup from a .psf file
"""
soup = pdbatoms.Soup()
curr_res_num = None
is_header = True
for line in open(psf):
if is_header:
if "NATOM" in line:
n_atom = int(line.split()[0])
is_header = False
continue
words = line.split()
atom_nu... | 6b84e9428bec66e65b0d06dd81b238370f1602a8 | 1,743 |
def check_api():
"""
复核货品入库
post req: withlock
{
erp_order_code,
lines: [{
barcode, location, lpn, qty
},]
w_user_code,
w_user_name
}
"""
w_user_code = request.json.pop('w_user_code', None)
w_user_name = request.json.pop('w_user_na... | 7c91f2c9068f762cb6681210f52ffe7d1a6ca259 | 1,744 |
def quadratic_form(u, Q, v, workers=1, **kwargs):
"""
Compute the quadratic form uQv, with broadcasting
Parameters
----------
u : (..., M) array
The u vectors of the quadratic form uQv
Q : (..., M, N) array
The Q matrices of the quadratic form uQv
v : (..., N) array
... | 6cd0abdf3d49ce38ba61ba6da9ee107663b1a8b9 | 1,745 |
def reorg(dat):
"""This function grabs the data from the dictionary of data types
(organized by ID), and combines them into the
:class:`dolfyn.ADPdata` object.
"""
outdat = apb.ADPdata()
cfg = outdat['config'] = db.config(_type='Nortek AD2CP')
cfh = cfg['filehead config'] = dat['filehead con... | 2389be25e7052016a6a710803b7b661a7eb1606c | 1,746 |
def get_oauth2_service_account_keys():
"""A getter that returns the required OAuth2 service account keys.
Returns:
A tuple containing the required keys as strs.
"""
return _OAUTH2_SERVICE_ACCOUNT_KEYS | bcded81a6884dc40b9f2ccb32e8b14df450b6fd6 | 1,748 |
def grammar_info(df, col):
"""return three separate attributes with
clean abstract, flesh score and sentence count"""
df['clean_abstract'] = clean_text(df[col])
df['flesch_score'] = df[col].apply(flesch_score)
df['sentence_count'] = sentence_count(df[col])
return df | 7606121f68434a760255cca10e75840ca058c50c | 1,751 |
def landing():
"""Landing page"""
return render_template('public/index.html') | 462b8f4451008832c6883be64dc23712bc76c907 | 1,753 |
def uniform_decay(distance_array, scale):
"""
Transform a measurement array using a uniform distribution.
The output is 1 below the scale parameter and 0 above it.
Some sample values. Measurements are in multiple of ``scale``; decay value are in fractions of
the maximum value:
+--------------... | e643e7e962d3b6e29c2c23c0aa682e77a539d04b | 1,754 |
def pid_to_service(pid):
"""
Check if a PID belongs to a systemd service and return its name.
Return None if the PID does not belong to a service.
Uses DBUS if available.
"""
if dbus:
return _pid_to_service_dbus(pid)
else:
return _pid_to_service_systemctl(pid) | 925f67611d83b3304db673e5e3d0c0a7dafd8211 | 1,755 |
def Frequencies(bands, src):
"""
Count the number of scalars in each band.
:param: bands - the bands.
:param: src - the vtkPolyData source.
:return: The frequencies of the scalars in each band.
"""
freq = dict()
for i in range(len(bands)):
freq[i] = 0;
tuples = src.GetPoint... | 081e37f0d2d9d5a70266b24372d75d94d86fcbb0 | 1,756 |
from typing import Callable
import torch
from typing import Dict
def get_loss_fn(loss: str) -> Callable[..., torch.Tensor]:
"""
Get loss function as a PyTorch functional loss based on the name of the loss function.
Choices include 'cross_entropy', 'nll_loss', and 'kl_div'.
Args:
loss: a stri... | ebbb20dba1b7573c615c35d683a59c9a5151b0e9 | 1,757 |
def FormatAddress(chainIDAlias: str, hrp: str, addr: bytes) -> str:
"""FormatAddress takes in a chain prefix, HRP, and byte slice to produce a string for an address."""
addr_str = FormatBech32(hrp, addr)
return f"{chainIDAlias}{addressSep}{addr_str}" | 4004e2367e13abb890d22b653b4ac849bf615d1a | 1,758 |
from typing import List
from operator import or_
async def get_journal_scopes(
db_session: Session, user_id: str, user_group_id_list: List[str], journal_id: UUID
) -> List[JournalPermissions]:
"""
Returns list of all permissions (group user belongs to and user) for provided user and journal.
"""
j... | 2f3fcc3cbfdc124a10ee04a716c76f7e2144e0de | 1,759 |
import re
def clean_script_title(script_title):
"""Cleans up a TV/movie title to save it as a file name.
"""
clean_title = re.sub(r'\s+', ' ', script_title).strip()
clean_title = clean_title.replace('\\', BACKSLASH)
clean_title = clean_title.replace('/', SLASH)
clean_title = clean_title.replace(':', COLON... | 6dcee3b05e9654e65e0f8eb78be9383d349adff2 | 1,760 |
def _calc_cumsum_matrix_jit(X, w_list, p_ar, open_begin):
"""Fast implementation by numba.jit."""
len_x, len_y = X.shape
# cumsum matrix
D = np.ones((len_x, len_y), dtype=np.float64) * np.inf
if open_begin:
X = np.vstack((np.zeros((1, X.shape[1])), X))
D = np.vstack((np.zeros((1, D.... | a282f68ca5789c97582f9535b5a255066bba44d9 | 1,762 |
def create_field_texture_coordinates(fieldmodule: Fieldmodule, name="texture coordinates", components_count=3,
managed=False) -> FieldFiniteElement:
"""
Create texture coordinates finite element field of supplied name with
number of components 1, 2, or 3 and the componen... | e19e964e0828006beae3c9e71f30fb0c846de1de | 1,763 |
import uuid
def get_cert_sha1_by_openssl(certraw: str) -> str:
"""calc the sha1 of a certificate, return openssl result str"""
res: str = None
tmpname = None
try:
tmpname = tmppath / f"{uuid.uuid1()}.crt"
while tmpname.exists():
tmpname = tmppath / f"{uuid.uuid1()}.crt"
... | 4b92531473e8488a87d14c8ecc8c88d4d0adef0d | 1,764 |
from typing import Union
def get_dderivative_skewness(uni_ts: Union[pd.Series, np.ndarray], step_size: int = 1) -> np.float64:
"""
:return: The skewness of the difference derivative of univariate time series within the
function we use step_size to find derivative (default value of step_size is 1)... | 11688b0cbd5dde2539cc3d5cfa8c5dccb9432f55 | 1,766 |
def extract_query(e: Event, f, woi, data):
"""
create a query array from the the event
:param data:
:param e:
:param doi:
"""
assert woi[0] > 0 and woi[1] > 0
e_start_index = resolve_esi(e, data)
st = int(e_start_index - woi[0] * f)
ed = int(e_start_index + woi[0] * f)
return... | 7109e28a265ff49054036e4e4c16ace0fc5eebda | 1,767 |
import ctypes
def getForegroundClassNameUnicode(hwnd=None):
"""
Returns a unicode string containing the class name of the specified
application window.
If hwnd parameter is None, frontmost window will be queried.
"""
if hwnd is None:
hwnd = win32gui.GetForegroundWindow()
# Maximu... | 82147d3da4c9374078bbeba64ef6968982dc2550 | 1,768 |
def read_mapping_from_csv(bind):
"""
Calls read_csv() and parses the loaded array into a dictionary. The dictionary is defined as follows:
{
"teams": {
*team-name*: {
"ldap": []
},
....
},
"folders: {
*folder-id*: {
"name": *folder-name*... | 8ffe1b5f489bb3428cb0b2dd3cc7f9eafe9ecf27 | 1,769 |
from typing import Sequence
from typing import Tuple
def primal_update(
agent_id: int,
A: np.ndarray,
W: np.ndarray,
x: np.ndarray,
z: np.ndarray,
lam: np.ndarray,
prev_x: np.ndarray,
prev_z: np.ndarray,
objective_grad: np.ndarray,
feasible_set: CCS,
alpha: float,
tau: ... | 6a13bb9147b74c3803482f53273ebc831ca1662b | 1,770 |
def norm_cmap(values, cmap, normalize, cm, mn, mx):
""" Normalize and set colormap
Parameters
----------
values
Series or array to be normalized
cmap
matplotlib Colormap
normalize
matplotlib.colors.Normalize
cm
matplotl... | 25515df37fe6b7060acf681287156af2c58d4c03 | 1,771 |
def _cpx(odss_tuple, nterm, ncond):
"""
This function transforms the raw data for electric parameters (voltage, current...) in a suitable complex array
:param odss_tuple: tuple of nphases*2 floats (returned by odsswr as couples of real, imag components, for each phase
of each terminal)
:type od... | f5931915550bb7ec9e713689c3d79997973eb252 | 1,772 |
def get_l2_distance_arad(X1, X2, Z1, Z2, \
width=0.2, cut_distance=6.0, r_width=1.0, c_width=0.5):
""" Calculates the Gaussian distance matrix D for atomic ARAD for two
sets of molecules
K is calculated using an OpenMP parallel Fortran routine.
Arguments:
==============
... | 77a4656a6f0014453991b8619ea4c53c6eec2c78 | 1,773 |
def _swap_endian(val, length):
"""
Swap the endianness of a number
"""
if length <= 8:
return val
if length <= 16:
return (val & 0xFF00) >> 8 | (val & 0xFF) << 8
if length <= 32:
return ((val & 0xFF000000) >> 24 |
(val & 0x00FF0000) >> 8 |
... | 4b3b879ad04e43e9454b904ba65420a8d477b629 | 1,774 |
def get_analysis(output, topology, traj):
"""
Calls analysis fixture with the right arguments depending on the trajectory type.
Parameters
-----------
output : str
Path to simulation 'output' folder.
topology : str
Path to the topology file.
traj : str
Trajectory typ... | 0382f4e672aba3ab754de7d26d27c7921239951f | 1,775 |
def get_callback_class(module_name, subtype):
""" Can return None. If no class implementation exists for the given subtype, the module is
searched for a BASE_CALLBACKS_CLASS implemention which is used if found. """
module = _get_module_from_name(module_name)
if subtype is None:
return _get_c... | cf04ddcc28c43b82db44d8be96419efbc166330f | 1,776 |
def index():
"""Toon de metingen"""
return render_template('index.html', metingen=Meting.query.all()) | 3d92b912c0af513b6d20a094799f7dfb60220a75 | 1,777 |
def about(template):
"""
Attach a template to a step which can be used to generate
documentation about the step.
"""
def decorator(step_function):
step_function._about_template = template
return step_function
return decorator | 7c00256e39481247857b34dcd5b7783a39b0a8bd | 1,778 |
import torch
def _extend_batch_dim(t: torch.Tensor, new_batch_dim: int) -> torch.Tensor:
"""
Given a tensor `t` of shape [B x D1 x D2 x ...] we output the same tensor repeated
along the batch dimension ([new_batch_dim x D1 x D2 x ...]).
"""
num_non_batch_dims = len(t.shape[1:])
repeat_shape = ... | 7ee1d0930f843a9d31bcc4934d675109f3b2df9b | 1,779 |
def get_client(config):
"""
get_client returns a feature client configured using data found in the
settings of the current application.
"""
storage = _features_from_settings(config.registry.settings)
return Client(storage) | 650f0d294514a4d13afd9ab010d6d4bdd4045c43 | 1,781 |
from datetime import datetime
def fra_months(z): # Apologies, this function is verbose--function modeled after SSA regulations
"""A function that returns the number of months from date of birth to FRA based on SSA chart"""
# Declare global variable
global months_to_fra
# If date of birth is 1/1/1938... | 70ba416f6415fd5db08244ae7543db0573f74b2d | 1,783 |
def set_global_format_spec(formats: SpecDict):
"""Set the global default format specifiers.
Parameters
----------
formats: dict[type, str]
Class-based format identifiers.
Returns
-------
old_spec : MultiFormatSpec
The previous globally-set formatters.
Example
-----... | 1494a6ff2ad71aa9ed0d20bc0620a124d404e5da | 1,784 |
def gen_base_pass(length=15):
"""
Generate base password.
- A new password will be generated on each call.
:param length: <int> password length.
:return: <str> base password.
"""
generator = PassGen()
return generator.make_password(length=length) | 571683589e13b8dcbd74573b31e5fc7644360bfe | 1,785 |
def split_component_chars(address_parts):
"""
:param address_parts: list of the form [(<address_part_1>, <address_part_1_label>), .... ]
returns [(<char_0>, <address_comp_for_char_0), (<char_1>, <address_comp_for_char_1),.., (<char_n-1>, <address_comp_for_char_n-1)]
"""
char_arr = []
for addres... | f4f3dd59378a689e9048cee96b8d6f12e9d8fe21 | 1,786 |
import json
def report_metrics(topic, message):
"""
将metric数据通过datamanage上报到存储中
:param topic: 需要上报的topic
:param message: 需要上报的打点数据
:return: 上报结果
"""
try:
res = DataManageApi.metrics.report({"kafka_topic": topic, MESSAGE: message, TAGS: [DEFAULT_GEOG_AREA_TAG]})
logger.info(... | 28f0bf1671b4116b26b8dba3f0c0a34174a0597a | 1,787 |
def wg_completion_scripts_cb(data, completion_item, buffer, completion):
""" Complete with known script names, for command '/weeget'. """
global wg_scripts
wg_read_scripts(download_list=False)
if len(wg_scripts) > 0:
for id, script in wg_scripts.items():
weechat.hook_completion_list_... | b9dc0d5e736cfeb1dc98d09b8e12c6a52696d89d | 1,788 |
def getG(source):
""" Read the Graph from a textfile """
G = {}
Grev = {}
for i in range(1,N+1):
G[i] = []
Grev[i] = []
fin = open(source)
for line in fin:
v1 = int(line.split()[0])
v2 = int(line.split()[1])
G[v1].append(v2)
Grev[v2].append(v... | 6e9a8a5c69267403ee3c624670c60af547d37a46 | 1,789 |
import re
def remove_version(code):
""" Remove any version directive """
pattern = '\#\s*version[^\r\n]*\n'
regex = re.compile(pattern, re.MULTILINE|re.DOTALL)
return regex.sub('\n', code) | 101ada9490137a879ea287076989a732942368f8 | 1,790 |
def unlabeled_balls_in_labeled_boxes(balls, box_sizes):
"""
OVERVIEW
This function returns a generator that produces all distinct distributions of
indistinguishable balls among labeled boxes with specified box sizes
(capacities). This is a generalization of the most common formulation of the
problem,... | 6390226744c2d4b756b43e880707accc333893d5 | 1,791 |
def beginning_next_non_empty_line(bdata, i):
""" doc
"""
while bdata[i] not in EOL:
i += 1
while bdata[i] in EOL:
i += 1
return i | 0a372729a7ad794a9385d87be39d62b1e6831b71 | 1,792 |
import collections
def VisualizeBoxes(image,
boxes,
classes,
scores,
class_id_to_name,
min_score_thresh=.25,
line_thickness=4,
groundtruth_box_visualization_color='black',
... | b02216a5a2e7fa7029dd0fea298efd1d593bab88 | 1,793 |
def cal_softplus(x):
"""Calculate softplus."""
return np.log(np.exp(x) + 1) | a966826f1e508ca1a197e63396ae9e2f779bcf96 | 1,795 |
def prepare_spark_conversion(df: pd.DataFrame) -> pd.DataFrame:
"""Pandas does not distinguish NULL and NaN values. Everything null-like
is converted to NaN. However, spark does distinguish NULL and NaN for
example. To enable correct spark dataframe creation with NULL and NaN
values, the `PANDAS_NULL` c... | f18ddfc3e77809908bf8fa365c1acf8a8d5069c6 | 1,797 |
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 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 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 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.