content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_valuation_method(item_code):
"""get valuation method from item or default"""
val_method = frappe.db.get_value('Item', item_code, 'valuation_method')
if not val_method:
val_method = frappe.db.get_value(None, "valuation_method") or "FIFO"
return val_method | 974812dd4fbeb1aac28186347c8aadba5a103391 | 3,607,227 |
def find_layer(model, layer_class):
"""
Find all layers in model that are instances of layer_class
"""
layers = []
for layer in model.layers:
if isinstance(layer, layer_class):
layers.append(layer)
elif hasattr(layer, "layers"):
# search in nested layers
... | d240d916f26e087edb7ccef8006b91b9c539bd76 | 3,607,229 |
from aoikprojectstarter.mediator import main_wrap
def main(args=None):
"""
Program main function.
This function does three things:
- Prepare `sys.path` so that program users do not need set up PYTHONPATH.
- Check whether dependency packages have been installed.
- Call the mediator module t... | f821f35781dd9d18a32eab0d7fb3ddc874ef572e | 3,607,230 |
def create(customer: schema.CustomerCreate, db=Depends(get_db)):
"""
create a new customer
a new customer is always active by default
:param customer:the new customer to create
:param db: database session (injected)
:return: the new customer with is id
"""
customer_db = model.Customer(... | 8ac398eaea5bb14a246d3bfc3e2c33a5c23c20e1 | 3,607,231 |
from typing import Dict
from typing import Any
import logging
def _search_dashboard(*, search_term: str, page_index: int, search_type: str) -> Dict[str, Any]:
"""
Call the search service endpoint and return matching results
Search service logic defined here:
https://github.com/lyft/amundsensearchlibra... | 84472de88914696e8ff3fffe4d1687526b626a3a | 3,607,233 |
def __bestMatch__(matches, # list
negMass, # float
pmz, # pandas.Series
negRT, # float
prt, # pandas.Series
parameters # LFParameters
):
# type: (...) -> int
"""Return the index of 'ma... | 75650f8dddbae46066d37d829f5cbc30cf91eae8 | 3,607,234 |
def patch_goods(goods):
""" Updates or creates a goods """
req = request.get_json()
if goods in stock:
for k, v in req.items():
stock[goods][k] = v
res = make_response(jsonify({"message": "goods updated"}), 200)
return res
stock[goods] = req
res = make_response(jsonify({"message": "goods created"}), 201)
... | 3d6577b25b975e000961dd5748d2757379bec829 | 3,607,235 |
import importlib
def connect(settings):
"""
Connect to a database.
"""
driver = importlib.import_module(settings.pop("driver", "sqlite3"))
return driver.connect(**settings) | cd186b3210b1ec012539dfc4a5306834dc9bf058 | 3,607,236 |
def count_reads_per_sample(file):
""" Count the reads for each sample from the original fasta file """
samples={}
for line in catch_open(file):
if line.startswith(">"):
try:
sample, read = line.replace(">","").split(SAMPLE_READ_DELIMITER)
except ValueError:
... | 114b1ff9a010b84d39600c32ea6fe5aa61941d42 | 3,607,237 |
def user_model(username):
"""Return a user model"""
return {
'username': username,
'scope': 'basic',
} | c629dbca8673eb740b1fddcfcddb588930cb1fa9 | 3,607,238 |
def check_norm_state(modules, train_state):
"""Check if norm layer is in correct train state."""
for mod in modules:
if isinstance(mod, _BatchNorm):
if mod.training != train_state:
return False
return True | 82387d78a53c5435bed25da542fbef9a68d6a785 | 3,607,239 |
def getJ1939ProtocolDescription(protocol : int) -> str:
"""
Returns a description of the protocol selected with protocol arg.
Feed the result of RP1210Config.getJ1939FormatsSupported() into this function to get a description of what
the format means.
Honestly, I don't see anyone ever using thi... | a52c48930d45c04f0570689620d2b01783f27e38 | 3,607,240 |
def parse_images(images):
"""
Parses list of available images into Image objects.
Arguments:
images : dictionary of images
Returns:
parsed_images : dictionary of parsed images
"""
parsed_images = {}
for image_name, image_info in images.items():
name = image_info["Na... | e56651093f7f983bb3dfbe8d9ea6f890b5a969b6 | 3,607,242 |
def in_region(pos, regions):
"""Find whether a position is included in a region.
Parameters
----------
pos : int
DNA base position.
regions : list of tuples
List of (start, end) position integers.
Returns
-------
bool
True if the position is within an of the reg... | 07154584fe3fadf93f16bf858810e4484828eb31 | 3,607,243 |
def extract_products_as_tuple(dataset):
"""Return names of all products as a sorted tuple.
Products are chosen using ``allocatable_production``."""
return tuple(sorted([exc['name'] for exc in allocatable_production(dataset)])) | 60ef29347312931b1dc44789cda85e2e6246d7cf | 3,607,244 |
def _hue_process_transition_time(transition_seconds):
""" Transition time is in 1/10th seconds
and cannot exceed MAX_TRANSITION_TIME. """
# Max transition time for Hue is 900 seconds/15 minutes
return min(9000, transition_seconds * 10) | 69f822d2836fef91206e2845d6d3bbd7623c03fc | 3,607,246 |
import base64
def add_tasks(taskq_service, task_dict):
"""
Allow readding of multiple tasks across multiple queues.
The task_dict is a dictionary with tasks for each queue, keyed by queue
name.
Tasks themselves can be dicts like those received from GetTasks() or Task
instances.
:param tas... | a834bfb52da4a5602f10bd3bed223457e8d046c1 | 3,607,247 |
def SEQ2HP(seq, HP_dic, occ=[], nuc_type=[], T=0):
"""
Given sequence, dictionary of HP(e.g. {A-A: [HP], oct: [HP...HP],...}), occupancy(e.g. [1, 500 , 789]), nucleosome type at each occupancy(e.g. ['oct','tet','hex']), and temperature.
Return the HPs associate with the given sequence.
"""
seqstep =... | 026bf83ae472e92ed449cf6d4d53ba1afae3b941 | 3,607,248 |
def _get_observations(token, transmart_url, study, concept_path):
"""
Given full concept path (as returned from tm 1.2 rest-api /concepts) return dict
of patient_id : value
:param token:
:param transmart_url:
:param study:
:param concept_path:
:return:
"""
obs = {}
conce... | 32956aa2b7c7dd03dd053745e3e18e13a9f833c5 | 3,607,249 |
def _get_jitclass_for_dtype(dtype, upper):
"""
Get the correct jitclass of NbTriMatrixBase for the data type and triangle.
"""
if upper:
return _UPPER_JITCLASS_BY_TYPE[dtype]
else:
return _LOWER_JITCLASS_BY_TYPE[dtype] | 3446028aaf0553200c51196e717f06c2ac91abfc | 3,607,250 |
def parseLibraryLogicData(data, srcFile="?"):
"""Parses the data of a library logic file."""
if len(data) < 9:
printExit("Library logic file {} is missing required fields (len = {} < 9)".format(srcFile, len(data)))
versionString = data[0]["MinimumRequiredVersion"]
scheduleName = data[... | f9983d00252a88bfb7e3371450ac3879460da244 | 3,607,251 |
def _add_replication(bucket_name: str, study_id: str):
"""
Configures a second bucket with `-dr` suffix and replicates the primary
bucket to it.
Adds a lifecycle policy to the dr bucket to immediately roll data into
glacier for cold storage
"""
if not settings.FEAT_STUDY_BUCKETS_REPLICATION_... | afbb5e7a9490906988dc5115eb3b59b54f2bd98c | 3,607,253 |
def main_top():
""" Present the top menu page """
return render_template("main.html") | e0ca4bc2e89cc9e4aab6c1ffc3ffcfc51cdbc8af | 3,607,254 |
def extract_kpt_vectors_dense(tensor, kpts_t):
"""
Dense version of get_entries.
:param tensor: Tensor to extract from [b, c, h, w]
:param kpts_t: Tensor with indexes (x, y) in channels as [b, 2, h, w]
:return: Tensor entries as [b, c, h, w]
"""
b, c, h, w = tensor.shape
kpts = kpts_t.v... | 9c62e13e0373ea91bed4b9d8bbcaabe9b1164f04 | 3,607,255 |
def bow(s: np.ndarray) -> str:
"""
Converts array to bag of words string (this is how we represent a sparse state into a pandas table).
@param s: word counts over vocabulary
@return: string representation
"""
i, = np.where(s > 0)
return ':'.join(map(str, i)) | 4389b86bfd047753939a5300ca567dee6fec350b | 3,607,256 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 5b2dc4ee5e35ce06094c658f3555b251226821c9 | 3,607,257 |
def main():
"""Does the job"""
keep = True
photos = request_photos()
page = 1
t = False
while keep is True:
p = next(photos, False)
if p is False:
photos = request_photos(page + 1)
continue
trial = Photo.objects(flickr=p["id"]).first()
p... | 428dba0ea0b1e52d4f63e2a9adff9a3d583ca95d | 3,607,258 |
def length_average_f(x_arr, f_arr, Lx, dx=0):
""" Take length average of f(x) with respect to x (from x[0] to x[-1]).
Numerical integration is performed using trapezoidal rule.
"""
Nx = size(f_arr)
if dx>0:
return (dx/Lx)*(sum(f_arr) - 0.5*(f_arr[0] + f_arr[-1]))
else:
re = 0. ... | 086a50259bb762b0023c7aaaefa68e159d72a27b | 3,607,259 |
import re
def re_sub_replace(pattern,string,repace_symbols=('-','_'),group_name=1):
"""
当re.sub(pattern,repl,string)内置的repl = "g<1>" 不能满足替换需求的时候,
比如需要将group目标内的文字中的某个符号替换掉, 使用的时候要注意替换代码内的sub replace符号
:param pattern : re pattern
:param string : original string
"""
def replace_match(match... | 7a6b2f27ce73f6c8b316ab424362eb8383fff273 | 3,607,260 |
def generate_hgvs(prefix: str = "c") -> str:
"""Generates a random hgvs string from a small sample."""
if prefix == "p":
# Subset of 3-letter codes, chosen at random.
amino_acids = [
"Ala",
"Leu",
"Gly",
"Val",
"Tyr",
"Met",... | 3a18afbe5687d1566d9994866771ae8b91367460 | 3,607,261 |
import six
def zero_lpad(number, length):
"""
Fill 0 on the left of number
:param number: number to be padded
:param length: length of result string
:return:
"""
if six.PY3:
return str(number).ljust(length, '0')
return '{number:0>{length}}'.format(number=number, length=length) | d8682249a7094e2c0de9ff015df3c1c7525b7427 | 3,607,262 |
def _len_guards(M: int) -> bool:
"""Handle small or incorrect window lengths"""
if int(M) != M or M < 0:
raise ValueError('Window length M must be a non-negative integer')
return M <= 1 | 1a181779821570edea6eb08739fd9065de445e80 | 3,607,265 |
def get_files(dataset_name):
"""Retrieve list of files in `dataset_name`.
Arguments:
- `dataset_name`: name of the dataset
"""
data = das_client(("file dataset={0:s} system=dbs3 detail=True | "+
"grep file.name, file.nevents > 0").format(dataset_name),
... | 55c389b28b488e3d1b221fd0156463fbf7b05752 | 3,607,266 |
def line0(x,a):
"""
Straight line through origin: a*x
Parameters
----------
x : float or array_like of floats
independent variable
a : float
first parameter
Returns
-------
float
function value(s)
"""
return a*x | 247a9ac56418ec34089bab0d9a914c69eb216f31 | 3,607,267 |
def score_nxgraphs(nx_graphs, truth, verbose=False):
"""nx_graphs: a list of networkx graphs, with node feature hit_id
each graph is a track"""
total_tracks = len(nx_graphs)
new_df = graphs_to_df(nx_graphs)
matched = truth.merge(new_df, on='hit_id', how='inner')
tot_truth_weight = np.sum(matche... | c5f67bbd7cac7e023cada56f02e7601762a64259 | 3,607,268 |
from app.main import main
from app.auth import auth
def create_app(config_name):
"""
creates an instances of the application
and passes the config name, i.e development
or production, the will then pick the environments
from the configuration classes in config
"""
app = Flask(__name__)
... | 5e44acddb66fac44dc03da49ec695de161e3b5c2 | 3,607,271 |
def pushCategory(category):
"""Used to insert a new category to the table
Returns the ID of the pushed Category
----FOR INTERNAL USE ONLY----"""
queryString="INSERT INTO Categories(Category_Name) VALUES('%s')" % category
cur=executeQueryWithHandling(queryString)
print "%s categeory pushed!"... | d2a4edbf48e68056ceedfc4b2d1caec41d718cdd | 3,607,272 |
def neutralize(row_vectors: pd.DataFrame) -> pd.DataFrame:
"""
Orthogonally project row vectors onto subspace orthogonal to all ones.
(In other words, we demean each row).
If the rows of `row_vectors` represent dollar positions, then this operation
will dollar neutralize each row.
:param row_... | 2ab08d21929c6e9c38f7b3d261f2e3be8e4a191a | 3,607,275 |
def create_validator(contract, force_optional=False):
"""
Factory pattern for creating custom validator in the style
of WTForms. This function takes the contract needed to validate
against and returns a ``Form`` object that can perform
the validation according to validation rules in the contract.
... | ca5208ad16e5d52aab58beedf514018eef6edc34 | 3,607,277 |
def get_state(obj):
"""Return a State object given an object. Useful for testing."""
str = dumps(obj)
return StateUnpickler(BytesIO(str)).load() | ca690595810feb313eacd2c7c4d7ffc100214b4a | 3,607,278 |
def median(image):
"""The median pixel value"""
return np.median(image) | 16c50e1d3869847136365a2f654bdd14af4412dc | 3,607,280 |
def list_ecriture_tag(db, ecriture_id=None):
""" List ecriture for tag """
filter = {}
filter = App.get_filter(request.query.filter)
sort = App.get_sort(request.query.sort)
tags = db.query(EcritureTag.id,
Tag.nom,
Tag.valeur,
EcritureTag.... | adc470a24fb56715b4e500c32b325ac19e66f8bf | 3,607,281 |
def wishlist(request, template="shop/wishlist.html",
form_class=AddProductForm, extra_context=None):
"""
Display the wishlist and handle removing items from the wishlist and
adding them to the cart.
"""
if not settings.SHOP_USE_WISHLIST:
raise Http404
skus = request.wishli... | 9fa770098227d26cb75a06a5691284b6d9cb3816 | 3,607,282 |
def classic_mode_cpcs(request, hmc_session): # noqa: F811
# pylint: disable=redefined-outer-name,unused-argument
"""
Pytest fixture representing the set of CPCs in classic mode, from the set of
all CPCs defined in the HMC definition file.
Because the `hmc_session` parameter of this fixture is agai... | 2ba0496573463f8b554e1ecbe57876e63ffce9da | 3,607,284 |
import json
def to_json(msg):
"""Pretty-print a dict as a JSON string
Use Unicode and 2-space indents.
"""
return json.dumps(msg, ensure_ascii=False, indent=2) | e10bf04ce54482f1892aa7a7452a7004024ea6d4 | 3,607,285 |
def get_sorted_index(array, reverse_order=False):
"""
get the order of the index of a one dimensions array
@reverse_order: True, large->small
False, small->large
"""
dtype = [('index', 'i4'), ('value', 'f8')]
data = np.array([(i, array[i]) for i in range(len(array))], dtype ... | a4690583a7973f08873f086a126fa859a6514a4a | 3,607,286 |
def show_saved_playlist():
""" Displays list of saved playlists """
playlists = crud.get_saved_playlists(crud.get_user_by_email(session['EMAIL']).user_id)
playlist_ids = crud.get_user_playlist_ids(crud.get_user_by_email(session['EMAIL']).user_id)
playlists_and_playlist_ids = helper.create_dict_playlist... | 59945734789c5feeb3c3080562b2aee27b716d8e | 3,607,287 |
def get_scores(events):
"""
{game_id : quarter, secs, a_pts, h_pts, status}
"""
ids = u.get_ids(events)
links = [bm.BOV_SCORES_URL + game_id for game_id in ids]
raw = g.reqs_json(links)
scores_dict = {g_id: score(j) for g_id, j in raw.items()}
return scores_dict | 8b0dbda56f275302488f4062a0ece44bf9e49343 | 3,607,288 |
def read_style_dict(cfg):
"""Return dict of styles read from config dict.
Sections in style file are set as top-level keys of the returned dict.
"""
style = {}
# update all settings with any global settings.
if 'global' in cfg:
cfg_global = cfg.pop('global')
for rc_dict in style... | cbbbb4f68e71fa82f028cc512698184a45c88cc8 | 3,607,289 |
import math
import logging
import time
def wait_on_app(port):
""" Waits for the application hosted on this machine, on the given port,
to respond to HTTP requests.
Args:
port: Port where app is hosted on the local machine
Returns:
True on success, False otherwise
"""
retries = math.ceil(START... | 04e6150fe4ff5e889df79367098a9ef9b3aaf3cd | 3,607,290 |
def get_min_and_max_velocity_values(velocities) :
""" Повертає min та max значення швидкості у вигляді кортежу """
return (velocities.min(), velocities.max()) | f9a2995bec07d129c34581d55a070a4004b8436c | 3,607,291 |
from typing import Iterable
def get_needed_vars(*entries: str) -> Iterable[str]:
""" Parses all used variables from a string """
results = set()
for entry in entries:
variables = VARIABLE_IDENTIFIER.findall(entry) # will return tuples: (with surrounding %s, without)
results.update([match[... | 725414ad843da47cf76daf35606cf95cc694db1f | 3,607,293 |
def shape(a):
"""the shape of a matrix"""
_rows = len(a)
_cols = len(a[0]) if a else 0
return _rows, _cols | 79c32a5f09ecbea4849929a3f6f627068198953f | 3,607,294 |
def read_txt_file(file, is_list):
"""
@summary - read from a test file.
@description - method will read from a text file and either return it
as a string or a list.
If is_list is True the delimiter that will split the
text file apart is ';' and '... | cad2d80c107f165cb55b23cb71f88c228146e475 | 3,607,295 |
def compare_dictionaries(dict1, dict2):
"""
Recursively compare two dictionaries.
:return: True if exactly the same, False if not
"""
if len(dict1) != len(dict2):
return False
for key in dict1:
try:
val1, val2 = dict1[key], dict2[key]
if val1 != val2: #... | c700874e6a1f7c0911607675570a750279c47616 | 3,607,297 |
def Table(*args, **kw):
"""A schema.Table wrapper/hook for dialect-specific tweaks."""
test_opts = {k: kw.pop(k) for k in list(kw) if k.startswith("test_")}
kw.update(table_options)
if exclusions.against(config._current, "mysql"):
if (
"mysql_engine" not in kw
and "mys... | 70928cfcb77bd21dda090043b657eded4fe0b00a | 3,607,298 |
import logging
def deploy_model(bigquery_client: bigquery.Client,
model_id: str,
machine_type: str = 'n1-standard-2',
location: str = 'europe-west4') -> aiplatform.Model:
"""Creates an endpoint and deploys Vertex AI Tabular AutoML model.
Args:
bigquery_clien... | e0fbc60875b32fada33ae3a35a072cd047f6a371 | 3,607,299 |
def trustRegion(f,grad,hess,subprob,x0,r0,rmax=2.,eta=1./16,gtol=1e-5):
"""Implement the trust regions method.
Parameters:
f : callable function object
The objective function to minimize.
g : callable function object
The gradient (or approximate gradient) of the ob... | dfa3fecfff0c85e4594ed955c04fbad302b9c7b1 | 3,607,300 |
import inspect
def _filter_module_all(path, root, children):
"""Filters module children based on the "__all__" arrtibute.
Args:
path: API to this symbol
root: The object
children: A list of (name, object) pairs.
Returns:
`children` filtered to respect __all__
"""
del path
if not (inspect... | 9cbc86a6a0321722910fb2f48b8857d5d6488511 | 3,607,301 |
def meanValue(arg):
"""
return the mean value of the argument over its domain
:param arg: function
:type arg: `escript.Data`
:return: mean value
:rtype: ``float`` or ``numpy.ndarray``
"""
fs=arg.getFunctionSpace()
d=fs.getDomain()
if fs == escore.Solution(d) or fs == escore.Cont... | 699e6af31272f1e1224b17027fe7c85740112277 | 3,607,302 |
def ratio_shimenreservoir_to_shimenagrichannel():
"""
Real Name: Ratio ShiMenReservoir To ShiMenAgriChannel
Original Eqn: Sum Allocation ShiMenReservoir To ShiMenAgriChannel/Sum Allcation From ShiMenReservoir
Units: m3/m3
Limits: (None, None)
Type: component
"""
return sum_allocation_s... | e00eb525d5388965377ff5336e15b7830ba09e11 | 3,607,303 |
from datetime import datetime
def get_object_storage_class_v2(s3_locs, extra_info=False, **kwargs):
"""
Return the storage class and restoring status of an s3_loc
If "extra_info", return a dictionary including creation date, last modified date, and size
"""
#assert type(s3_locs) == type([])
f... | 0aec67e7bb2726a27e6aff54e0eaf659cb1df46f | 3,607,304 |
def contains_pattern(input: str, pattern: str) -> bool:
"""Check if the `input` contains all signals of the given `pattern`"""
assert len(input) >= len(pattern)
return all([p in input for p in pattern]) | 0fd2b5d35145fe21f855358c061995e04ad695a9 | 3,607,305 |
def is_CyclotomicField(x):
"""
Return True if x is a cyclotomic field, i.e., of the special
cyclotomic field class. This function does not return True for a
number field that just happens to be isomorphic to a cyclotomic
field.
EXAMPLES::
sage: from sage.rings.number_field.number_field... | 2c7d7a10cb15aac1a0e3600986a2fe4a8b83472b | 3,607,306 |
import json
def TestActiveTwitterToken(handle):
"""
Check whether the Twitter token details are valid.
"""
try:
twitterQuery = (
"https://api.twitter.com/1.1/users/show.json?" + "screen_name=" + handle
)
T_response, json_string = client.request(twitterQuery)
... | 7d6010aa4c629524b57975e73b42198e361a69c8 | 3,607,307 |
def verify_no_deny_list_words(file_contents, file_location):
"""Verify no segments of the file are in the list of denied words."""
error_count = 0
segments = file_contents.split('/')
for word in segments:
if word in DENY_LIST:
logger.error(f"Word '%s' in %s is not allowed.", word, fi... | 23a330b480243b6c123f5c329d0b92b88bfec1c1 | 3,607,308 |
import pkg_resources
import requests
from datetime import datetime
import json
def get_commodity_recent_data(commodity, as_json=False, order='ascending', interval='Daily'):
"""
This function retrieves recent historical data from the introduced commodity from Investing.com, which will be
returned as a :obj... | b48e573c0857d098b86b676cbb0f9b1452f159f9 | 3,607,309 |
def _prune_dict_null_str(dictionary):
"""
Prune the "None" or emptry string values from dictionary items
"""
for key, value in list(dictionary.items()):
if value is None or str(value) == "":
del dictionary[key]
if isinstance(value, dict):
dictionary[key] = _prune... | c6e408f3b3a3d2bafc77fdb1c106bd5ea3a27dbb | 3,607,310 |
import warnings
def sample_chain(
num_results,
current_state,
previous_kernel_results=None,
kernel=None,
num_burnin_steps=0,
num_steps_between_results=0,
trace_fn=lambda current_state, kernel_results: kernel_results,
return_final_kernel_results=False,
parallel_iterations=10,
na... | 75d7c75ae562f0f494dc8348dea0007696cb059b | 3,607,311 |
def d_sigmoid(x):
"""
Derivative for sigmoid used for gradient calculation
"""
y = sigmoid(x)
return y * (1. - y) | fe2a8ab8debf22bab349a65bfd29cea5a3e0e90d | 3,607,312 |
import requests
def get_interacting_proteins_string(protein, num_results=25):
"""
@Param protein:
The name of the protein that you want to generate a list of interacting proteins for.
@Param num_results (default=25):
The number of interacting proteins that you want to get.
@Return:
... | 816498d9ecb7bf144bbced55a173fd6da8a5fff4 | 3,607,313 |
def add_fill_zone_rounded_rectangle(topleft, bottomright, corner_radius, N=10, layer="F.Cu", linestart=' '):
"""
Add fill zone
In KiCad, click Place > Zone, then right click inside a zone >
:param topleft:
:param bottomright:
:param min_thickness:
:param linestart:
:return:
"""
... | 640b49af89c71a249a0020a924e63997cfcf1295 | 3,607,314 |
def count_punc(text):
"""
Count the number of punctuations within the text.
Parameters
----------
text : str
piece of text to analyze
Returns
-------
integer
the number of punctuations
Examples
--------
>>> count_punc("Hello, World!")
2
>>> coun... | e08b1973ef693c0fb12608d6303c2c054c6030ae | 3,607,315 |
from typing import Collection
from typing import Tuple
from typing import List
def decode_access_list(
access_list: Collection[Tuple[bytes, Collection[bytes]]]
) -> List[Tuple[bytes, Tuple[int, ...]]]:
"""Decode an access list into friendly Python types"""
work_list = []
if not access_list or len(acc... | 18d24f3a6f2b8c88ff47383e8586588a00d15905 | 3,607,316 |
def exception_to_http_code(exc: Exception) -> int:
"""Returns a HTTP error code from an exception object.
Args:
exc (Exception): Exception object
Returns:
int: Error code
"""
return exception_type_to_http_code(type(exc).__name__) | 2d146bae0303495b7e3578ac3cce31d2409e7621 | 3,607,317 |
def doIBDTW(SSMA, SSMB, NThreads = 8, Verbose = False):
"""
Do isometry blind dynamic time warping between two
self-similarity matrices
:param SSMA: MXM self-similarity matrix
:param SSMB: NxN self-similarity matrix
:param NThreads: How many threads to use in parallelization of
row compu... | 228b284a024ffb49a458e15930ccb5b8213dd303 | 3,607,318 |
def lxml_stringify_children(node):
"""
Returns XML contents of the node
:param node:
:return:
"""
return (node.text if node.text is not None else '') + \
''.join((etree.tostring(child, encoding='unicode') for child in node)) | 7a2f59565719d90469d6e74c15bfe9e99622b1be | 3,607,319 |
import pickle
def grab_training_data(shuffle: bool = False, direc: str = 'data/training/movie_reviews_data.pkl') -> tuple[list]:
"""
Opens the reviews stored in the pickle file.
If shuffle is true that means that we should get the data
ready by running shuffle_training_Data
"""
with open(dir... | c23b36c7571c8d152164f111503caf1f42d5682d | 3,607,320 |
import powerlaw as pl
def best_power_law_fit(S, resolution=400, percentile_min=10, percentile_max=99, sigma_threshold=0.05):
"""Returns best-fitting powerlaw.Distribution object of the data.
The built-in optimization routine for the powerlaw package often fails to find
the best/most-reasonable fit. This ... | 832901a58ca43c6b26e89121f05a92b0b00f574b | 3,607,322 |
def beta_cal(v_command):
"""βを計算"""
# 元論文(アッカーマン)
z = np.arctan(tan(v_command[1, 0]) / 2)
## ドリフト有りモデル
#lr = 0.2
#L = 0.4
#z = np.arctan(lr / L * tan(v_command[1, 0]))
return z | 98f3e2ffee92ccdc7bb5b1af8a4fb3a214d61f48 | 3,607,323 |
from typing import List
from typing import Dict
import torch
def load_examples(
examples: List[Dict[str, torch.Tensor]],
tokenizer: RecconSpanExtractionTokenizer,
max_seq_length: int = 512,
doc_stride: int = 512,
max_query_length: int = 512,
evaluate: bool = False,
output_examples: bool = ... | b13779e187af16863454bf70af987b59c3b02dfb | 3,607,324 |
def intersectionOfMaskSets(setOne, setTwo):
"""
from set two from set one
:param setOne:
:param setTwo:
:return:
@type setOne: list of dict
@type setOne: list of dict
"""
result = []
for itemOne in setOne:
for posTwo in range(len(setTwo)):
itemTwo = setTwo[pos... | 1acbb21d5cdf94e77f18692b966c7a9cfa45c002 | 3,607,326 |
import click
def service_option(**attrs):
"""A --service option for commands."""
kwargs = dict(
metavar='SERVICE',
required=False,
help='Service name.'
)
kwargs.update(attrs)
option = click.option(
'--service',
**kwargs
)
return option | 67e858589117701c5f9f8f375c67803cf9c1a2e9 | 3,607,327 |
import logging
def return_json(func):
"""
A decorator that serializes the output to JSON before returning to the
web client.
"""
def convert_to_json(self, *args, **kwargs):
return_val = func(self, *args, **kwargs)
try:
return render_json(utils.to_json(return_val))
except ... | 0dc968e49f1914bfbb827169fbea12039a0783a0 | 3,607,328 |
def recursive_fibonacci(i, seq=None):
"""Recursive solution"""
if seq is None:
seq = [0, 1]
if i > len(seq):
seq.append(seq[-1] + seq[-2])
return recursive_fibonacci(i, seq)
return i, seq[i - 1], seq[:i] | 385cac4df9ca3a47ed2968a27601a07cd80e9908 | 3,607,330 |
def count_distinct(n):
"""
Count distinct divisors.
>>> count_distinct(180) # 180 = (2*2)*(3*3)*5
3
"""
return len(set(get_divisors(n))) | 74573c40f36618578e54990400c44062e035faea | 3,607,331 |
def detect_greenthread_environment() -> str:
"""
Detect the current environment: eventlet, or gevent, or '' for default
"""
global _greenthread_environment
if _greenthread_environment is None:
_greenthread_environment = _detect_greenthread_environment()
return _greenthread_environment | 65b6143c1608fd350e281e1ccfbbbcb69317ebfa | 3,607,332 |
def get_ell_cfft(nx, dx, ny=None, dy=None):
""" returns the wavenumber l = \sqrt(lx**2 + ly**2) for each Fourier mode """
lx, ly = get_lxly_cfft(nx, dx)
return np.sqrt(lx**2 + ly**2) | e9979df5e278eea286931b96dce541475f4d7f03 | 3,607,333 |
def check_dkim(msg_bytes, fromAddr, logger):
"""
:param msg_bytes: bytes
:param fromAddr: str
:param logger: logger
:return: bool
Validate the message (passed as a byte sequence, as that's what the dkimpy library wants).
"""
d = dkim.DKIM(msg_bytes, logger=logger)
valid_dkim = d.ver... | 40d392a9726eb30f1c8136d7161245c4f539024c | 3,607,334 |
def reinstate_endpoint(cpid, old_endpoint, next_hop_ips,
proc_alias=PROC_ALIAS):
"""
Re-instate and endpoint that has been removed.
:param hostname: The hostname this endpoint resides in
:param cpid: The PID of the namespace to operate in.
:param old_endpoint: The old endpoint... | f00f7b0887079f962613feb11e271bd99f48d0d5 | 3,607,335 |
def main(*argv):
"""Do the thing"""
(prog, argv) = argparsing.grok_argv(argv)
argparser = argparsing.setup_argparse(prog=prog, description=DESCRIPTION)
_add_arguments(argparser)
args = argparser.parse_args(argv)
with open(args.version_file, "r") as version_file:
current_version = _get_v... | 236c5ce71c201a33b19d6d45b75ee86dfd08b708 | 3,607,336 |
def ticks_to_distance(ticks: int) -> Real:
"""
Convert encoder ticks into distance [cm].
:param ticks: Number of encoder ticks.
:return: Distance that number of ticks represents [cm].
"""
return ticks * WHEEL_CM_PER_TICK | 3f288ee6cbcf9cd89379b68a5e7c639485c411f8 | 3,607,337 |
def with_podcasts(feeds, update=False):
"""Looks up podcast associated with result. Adds new podcasts if they are not already in the database"""
podcasts = Podcast.objects.filter(rss__in=[f.url for f in feeds]).in_bulk(
field_name="rss"
)
new_podcasts = []
for feed in feeds:
feed.... | c35448adf541f97856e2eb43f42157e3f6f4ed65 | 3,607,338 |
def load_all_prem_types(country):
"""
Collate the matrices of different location types for a given country
:param country: str
Name of the requested country
"""
matrices = {}
for sheet_type in ("all_locations", "home", "other_locations", "school", "work"):
matrices[sheet_type] =... | 75aef412acc63215dabf2e96d25642809a9d4f84 | 3,607,339 |
def SLInt32(name):
"""signed, little endian 32-bit integer"""
return FormatField(name, "<", "l") | ef87be8a1d397dc9daa94b6175ac71c28c498d6e | 3,607,340 |
def team_manager(request, aid):
"""Manage team members."""
alert = get_object_or_404(Alert, pk=aid)
perms = alert.permissions(request.user)
student = _student(alert)
vitals = student['student']
team = [m.user for m in alert.team.all() if m.status]
matrix = []
for c in alert.category.all(... | c29621137ec3ec1c0f9d9b17acf11e6c3d940839 | 3,607,341 |
def inception_score(images, num_batches=None):
"""IS function from tfc
Args:
images: must be 4-D tensor, ranges from [0, 255]
num_batches: Number of batches to split `generated_images` in to in
order to efficiently run them through the classifier network.
"""
batches = images.shape[0]
if ... | be241dce6bc538457bcd2670bb3632b8e2d0177b | 3,607,342 |
def build_get200_model_a400_invalid_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Send a 200 response with invalid payload {'statusCodeInvalid': '400'}.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:ret... | cf524efb45add25daf08718ce0d9508f60af7c40 | 3,607,343 |
def get_identifiers_url(db_name, db_id):
"""Return an identifiers.org URL for a given database name and ID.
Parameters
----------
db_name : str
An internal database name: HGNC, UP, CHEBI, etc.
db_id : str
An identifier in the given database.
Returns
-------
url : str
... | 2889bba2519240af5f088c7d126c378d5019cb39 | 3,607,344 |
def addSimpleUserFolder(self,REQUEST=None):
"""Add a SimpleUserFolder to a container as acl_users"""
ob=SimpleUserFolder()
self._setObject('acl_users', ob)
if REQUEST is not None:
return self.manage_main(self,REQUEST) | 35cc73b8b8182cddf844ab0873979a68f38acb7e | 3,607,345 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.