content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _validate_method(method, where):
"""Helper for get_params()"""
if method is None:
return None
if method not in ['signal', 'thread']:
raise ValueError('Invalid method %s from %s' % (method, where))
return method | 5,301,800 |
def load_yaml(s: Union[bytes, IO, IO[bytes], Text, IO[Text]]):
"""Load a Yaml document.
This is a helper function which tries to use the fast ``CLoader``
implementation and falls back to the native Python version on failure.
"""
import yaml
try:
from yaml import CLoader as Loader
ex... | 5,301,801 |
def _get_specs_and_amplitude_traces(all_audio, fs, spec_params):
"""
Return spectrograms and amplitude traces given a list of audio.
Parameters
----------
all_audio : list of numpy.ndarray
List of audio.
fs : int
Audio samplerate
spec_params : dict
Contains keys `'nperseg'`, `'noverlap'`, `'min_freq'`, `'... | 5,301,802 |
def make_index(
all_modules: Mapping[str, pdoc.doc.Module],
is_public: Callable[[pdoc.doc.Doc], bool],
default_docformat: str,
) -> list[dict]:
"""
This method compiles all currently documented modules into a pile of documentation JSON objects,
which can then be ingested by Elasticlunr.js.
"... | 5,301,803 |
def parent(path: str) -> str:
"""Get path's parent
e.g
j.sals.fs.parent("/home/rafy/testing_make_dir/test1") -> '/home/rafy/testing_make_dir'
Args:
path (str): path to get its parent
Returns:
str: parent path.
"""
return str(pathlib.Path(path).parent) | 5,301,804 |
def slugify(text):
"""
Turn the text content of a header into a slug for use in an ID
"""
non_safe = [c for c in text if c in non_url_safe]
if non_safe:
for c in non_safe:
text = text.replace(c, '')
# Strip leading, trailing and multiple whitespace, convert remaining whitespa... | 5,301,805 |
def _getText(nodelist):
""" returns collected and stripped text of textnodes among nodes in nodelist """
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc.strip() | 5,301,806 |
def strip_html(text):
"""See http://stackoverflow.com/a/9662362"""
return re.sub('<[^<]+?>', '', text) | 5,301,807 |
def sampling(DAG, n=1000, verbose=3):
"""Generate sample(s) using forward sampling from joint distribution of the bayesian network.
Parameters
----------
DAG : dict
Contains model and adjmat of the DAG.
n : int, optional
Number of samples to generate. The default is 1000.
verbos... | 5,301,808 |
def from_json(json_data, key):
"""Extract values from JSON data.
:arg dict json_data: The JSON data
:arg str key: Key to get data for.
:Returns: The value of `key` from `json_data`, or None if `json_data`
does not contain `key`.
"""
if key in json_data:
return json_data[key]
... | 5,301,809 |
def weights_dask(weights):
"""
Weighting array by cosine of the latitude.
"""
return weights.chunk() | 5,301,810 |
def get_secure_random_string(size):
"""
Return a string of ``size`` random bytes. Returned string is suitable for
cryptographic use.
:param size: Size of the generated string.
:type size: ``int``
:return: Random string.
:rtype: ``str``
"""
value = os.urandom(size)
value = binas... | 5,301,811 |
def plot_confusion_matrix(cm, colormap=plt.get_cmap(), labels='012', do_plot=True):
"""Plot a confusion matrix.
Parameters
----------
cm: array
Confusion matrix
colormap: :class:`matplotlib.colors.Colormap`
Color map
labels:
Labels
do_plot: boolean
Whether th... | 5,301,812 |
def is_not_json(bytestring):
"""
:param bytes bytestring: A candidate byte string to inspect.
:return bool: ``False`` if and only if ``bytestring`` is JSON encoded.
"""
try:
loads(bytestring)
except:
return True
return False | 5,301,813 |
def test_split_i_and_get_allele_1():
"""
Reverse_stranded library
i[0] = forward ref allele
i[1] = reverse ref allele
i[2] = forward non-ref allele
i[3] = reverse non-ref allele
:return:
"""
i = '0,3,0,3'
ref, alt, sense = fv.split_i_and_get_allele(i, reverse_split=True)
asse... | 5,301,814 |
def get_ingredients():
"""Find all available ingredients.
Returns:
list(IngredientDto): A list of all ingredients.
"""
ingredient_entities = IngredientEntity.query.all()
return [ingredient_entity_to_dto(entity, entity.availability) for entity in ingredient_entities] | 5,301,815 |
def add_stock(request):
"""
This view renders Create brand Page """
prod_obj = Product.objects.all()
if not request.user.is_viewer :
context = {
"title": "Create Stock",
"products": prod_obj
}
return render(request, 'add_stock.html',context)
else:
... | 5,301,816 |
def project(a):
""" De-homogenize vector """
return a[:-1] / float(a[-1]) | 5,301,817 |
def test_semisup_linop():
"""Test ovk.semisup.SemisupLinop."""
np.random.seed()
n = 100
p = 5
lbda2 = .1
# supervised indices
B = np.random.randint(2, size=(n)).astype(np.bool)
# Graph Laplacian
n_unsup = np.sum(~B)
L = np.random.randn(n_unsup, n_unsup)
L = np.dot(L, L.T)
... | 5,301,818 |
def add_presentations_sheet(supervisor, modified_df):
"""Adding the Presentations sheet with all Presentations according to the talk order on the presentation day"""
src_grading_wb = load_workbook('DataSources/Foik_GradingSheetSeminar.xlsx')
print("The available sheets in the xlsx file")
print(src_gradi... | 5,301,819 |
def test_insert_model(db, model_query, data_pool):
"""Test query model insert."""
data = data_pool[model_query.model_class]
model = model_query.save(data)
dbmodels = db.query(model_query.model_class).all()
assert len(dbmodels) == 1
assert model is dbmodels[0] | 5,301,820 |
def ospathjoin(*args, **kwargs):
"""
Simple ``o.path.join`` for a specific platform.
@param args list of paths
@param kwargs additional parameters, among them,
*platform* (win32 or ...)
@return path
"""
def build_value(*args,... | 5,301,821 |
def load_obj(filename: str, default_mtl='default_mtl', triangulate=False) -> WavefrontOBJ:
"""Reads a .obj file from disk and returns a WavefrontOBJ instance
Handles only very rudimentary reading and contains no error handling!
Does not handle:
- relative indexing
- subobjects or groups
- line... | 5,301,822 |
def initialize(config):
"""
Initializes the object storage manager for the analysis archive.
NOTE: this is not thread-safe, should be called once on service startup, not in request threads/path
:param config:
:return:
"""
global _manager_singleton
if _manager_singleton is None:
... | 5,301,823 |
def calculate_service(rasters, nodata, alpha, part_wild, out_uris):
"""Calculate the service raster. The finished raster will be saved to
out_uris['service_value'].
rasters - a dictionary with these entries:
'farm_value' - a GDAL dataset.
'farm_abundance' - a GDAL dataset.
... | 5,301,824 |
def get_car(shape):
"""Get car image as input."""
return get_img(shape, "car.JPEG", np.float32, should_scale=True) | 5,301,825 |
def get_total(session, Model):
"""Should be made in a context manager"""
stmt = select(func.count(Model.id))
_total = session.execute(stmt)
total = _total.scalar()
return total | 5,301,826 |
def temp_c_2_f(temp):
"""
translate Celsius to Fahrenheit
T(°F) = (T(°C) * 1.8) + 32
"""
tc = (Decimal("%s" % temp) * Decimal("1.8")) + 32
return tc | 5,301,827 |
def CLT2_ci(mean_log, std_log, n, ci=0.95):
""" Returns the error margin for the geometric mean based
on the central limit theorem and the t-statistics.
Parameters
----------
mean_log : scalar, float
the arithmetic mean of the log-transformed data
std_log : scalar, float
the st... | 5,301,828 |
def convert_to_resource(apps, schema_editor):
"""
Convert file to resource in WebsiteContent
"""
WebsiteContent = apps.get_model("websites", "WebsiteContent")
WebsiteContent.objects.filter(type="file").update(type="resource") | 5,301,829 |
def create_and_wait_kfp_run(pipeline_id: str,
version_id: str,
run_name: str,
experiment_name: str = "Default",
api_version: str = KATIB_API_VERSION_V1BETA1,
**kwargs):
"""Crea... | 5,301,830 |
def work_bucks():
""" Create a report with all issues with wrong usage of bucks.
"""
graphies = []
graphie_xliff('1_high_priority_platform.xliff.json', graphies)
## graphie_xliff('2_high_priority_content.xliff.json', graphies)
graphie_xliff('3_medium_priority.xliff.json', graphies)
## graphie_... | 5,301,831 |
def coraldistancemap(edgemask,x_mesh,y_mesh):
""" Function generating an array with the minimum distances to a coral object
The edgemask object should be a boolean array with the same shape as the x- and y-meshes.
It is True where the edges of the coral objects are located and False everywhere else
"""
... | 5,301,832 |
def conditional_entropy(xs, ys, bx=0, by=0, b=2.0, local=False):
"""
Compute the (local) conditional entropy between two time series.
This function expects the **condition** to be the first argument.
The bases *bx* and *by* are inferred from their respective time series if
they are not pro... | 5,301,833 |
def screen_aos(mol, active_atoms, den_mat_a, ovlp, trunc_lambda):
"""Screen AOs for truncation"""
include = [False] * mol.nbas
active_aos = []
for shell in range(mol.nbas):
aos_in_shell = list(range(mol.ao_loc[shell], mol.ao_loc[shell + 1]))
if mol.bas_atom(shell) not in active_atoms: ... | 5,301,834 |
def setup_decision_tree_classifier(training_data,
training_target,
testing_data,
features = "preprocessed",
method = "count",
ngrams=(1,1)):
... | 5,301,835 |
def push_from_kafka_to_db(msg):
"""
Insert data from Kafka-topic to DB
Expected data format
[
('User_ID','Product_ID','Rank'),
('User_ID','Product_ID','Rank'),
('User_ID','Product_ID','Rank'),
...
]
"""
try:
... | 5,301,836 |
def doubleMetaphone(field):
"""TODO.
Examples:
.. code:: python
> print(doubleMetaphone('John Woodward'))
> {'ANTRT', 'JNTRT'}
"""
return {metaphone for metaphone in doublemetaphone(field) if metaphone} | 5,301,837 |
def find_nearest(data, target, align='start', max_time_diff=None):
"""Finds the index of the nearest row in `data` to `target` time.
Args:
* data (pd.Series or pd.DataFrame): if `align==back` then `data` must
have an `end` column.
* target (pd.Timeseries or timestamp)
* align (str): `... | 5,301,838 |
def clipped_error(x):
"""
# Huber loss (delta = 1)
L(a) = if abs(a) < delta -> 0.5*a*a
else -> delta*(abs(a) - 0.5*delta)
"""
# function where return the coordination of the values which is meet for the condition
# where(condition, x, y) 根据condition返回x或y中的元素
return tf.... | 5,301,839 |
def _rotate_affine(affine, shape, rotation):
"""
Work in progress. Does not work yet.
:param affine:
:param shape:
:param rotation:
:return:
"""
assert_affine_is_diagonal(affine)
# center the image on (0, 0, 0)
temp_origin = (affine.diagonal()[:3] * np.asarray(shape)) / 2
tem... | 5,301,840 |
def update_defaults(k):
"""Set a configuration option to the correct default value if it hasn't
been manually set"""
c = data.get_config(k)
if c.get("is_user_set"):
# Has been manually set, so ignore
return
if "choice_group" in c:
update_choice_default(c['choice_group'])
... | 5,301,841 |
def b_inv(b_mat):
"""
inverse function for 2x2 matrix
:param b_mat: [M, 2, 2]
:return: [M, 2, 2]
"""
b00 = b_mat[:, 0, 0]
b01 = b_mat[:, 0, 1]
b10 = b_mat[:, 1, 0]
b11 = b_mat[:, 1, 1]
det = (b00 * b11 - b01 * b10)
b00 = b00 / (det + eps)
b01 = b01 / (det + eps)
b10 =... | 5,301,842 |
def report_statuses(status_type, status_iter):
"""Report status codes from list of folder_pb2.*Response."""
counter = collections.Counter(element.lower() for element in status_iter)
for status, count in sorted(counter.items()):
logging.info('%-15s %-15s %d', status_type, status, count) | 5,301,843 |
def right_bit_shift(lhs, rhs, ctx):
"""Element ↳
(num, num) -> a << b
(str, num) -> a.rjust(b, " ")
(num, str) -> b.rjust(a, " ")
(str, str) -> a.rjust(len(b)-len(a), " ")
"""
ts = vy_type(lhs, rhs)
return {
(NUMBER_TYPE, NUMBER_TYPE): lambda: int(lhs) >> int(rhs),
(str, ... | 5,301,844 |
def write_log_to_file(message):
"""
Write a log line to a file - don't use it in production!
"""
with open('/tmp/rostests.out', 'a') as rostest_file:
rostest_file.write(message)
rostest_file.write('\n') | 5,301,845 |
def record_data(address, name, filename, overwrite, duration, file_type, bluetooth):
"""Record data from Explore to a file """
if name is None and address is None:
raise ValueError("Either name or address must be given!")
explorepy.set_bt_interface(bluetooth)
explore = explorepy.explore.Explore(... | 5,301,846 |
def setup_and_run_fortran_script(file, mult, temp):
"""
Runs fortran script to produce 'fort.10' files etc...
"""
filetype = get_filetype(file)
if filetype == 'gamess':
thermo_initial_geom_gamess(file)
freq_data_gamess(file)
run(file, mult, temp)
if filetype == 'gauss':
... | 5,301,847 |
def save_table(table, table_name, run, batch, source, basename='xrb',
subdir=''):
"""Save provided table to oscillations project
"""
source_path = os.path.join(PROJECT_PATH, source)
batch_str = grid_strings.get_batch_string(batch, source)
run_str = get_run_string(run, basename)
r... | 5,301,848 |
def extractOutputData(odb: str, script: str):
"""Extract output data using python script
Parameters
----------
odb: str
File path of the output database
script: str
File path of the script
"""
abaqus = 'abaqus'
if 'ABAQUS_BAT_PATH' in os.environ.keys():
abaqus = ... | 5,301,849 |
def spell_check(text, spell):
"""Fix misspelled words"""
suggestions = spell.lookup_compound(text, 2)
if suggestions:
return suggestions[0].term
else:
return text | 5,301,850 |
def get_favicon():
"""
Function used internally to send static files from the static
folder to the browser
内部使用send_static_file方法将静态文件夹中的图片数据发送到浏览器
"""
# 找到网站图片的静态资源并返回
return current_app.send_static_file("news/favicon.ico") | 5,301,851 |
def adagrad(lr, epsilon, weight_decay):
"""\
Adagrad optimizer.
Adagrad is an optimizer with parameter-specific learning rates, which are
adapted relative to how frequently a parameter gets updated during
training. The more updates a parameter receives, the smaller the learning
rate. See: http:... | 5,301,852 |
def layout_agnostic_vocabulary_vector(
results: List[Dict],
number_of_words: int
) -> List[str]:
"""Create a layout agnostic vocabulary vector
Finds the most popular words out of a bag comprised of all layouts
Guarantees a length based on number_of_words
:param List[Dict] ocr_resul... | 5,301,853 |
def store_matrix(matrix='',
output_dir_path='',
out_file_name='',
output_format=''):
"""store_matrix."""
if not os.path.exists(output_dir_path):
os.mkdir(output_dir_path)
full_out_file_name = os.path.join(output_dir_path, out_file_name)
if outpu... | 5,301,854 |
def getTriangularVertices(n,
rotationAngles = [0, 0, 0],
phi_start = 0,
phi_end = np.pi,
plotIt = False):
""" Triangular approximation of a sphere
Two angular sweeps are necessary. One is theta that goes arou... | 5,301,855 |
def _get_role_prefix(node):
"""Calculates the node role prefix used for grouping nodes in the graph"""
try:
role_prefix = node['role'][0].split("_")[0]
if role_prefix == REPO['EXCLUDE_ROLE_PREFIX']:
role_prefix = 'none'
role_prefix = node['role'][1].split("_")[0]
... | 5,301,856 |
def check_message(
message_id,
parameter: Optional[Union[str, Dict]],
level_type: Optional[Union[str, List[str]]],
level: Optional[Union[int, List[int], Dict]],
**kwargs,
) -> bool:
"""
Check whether GRIB message fits conditions.
Parameters
----------
message... | 5,301,857 |
def process(fh: TextIO) -> FastaInfo:
""" Process a file """
if lengths := [len(rec.seq) for rec in SeqIO.parse(fh, 'fasta')]:
return FastaInfo(filename=fh.name,
min_len=min(lengths),
max_len=max(lengths),
avg_len=round(np.mean(... | 5,301,858 |
def write_tweets_out(tweet_list, outfile):
""" Write tweet list to a line seperated json .gz in the same format as the decahose.
"""
with gzip.open(outfile, 'wb') as f:
for tweet in tweet_list:
f.write(json.dumps(tweet).encode('utf8'))
f.write('\n'.encode('utf8'))
retu... | 5,301,859 |
def cln_info(record):
"""Annotates pathogenicity using ClinVar
Args:
record (tuple): vcf line with fields separated in tuple
Returns:
significance + '|' + disease (str): pathogenicity and disease name implicated
"""
try:
significance = re.search(r"(CLNSIG=)([A-Za-z_]+)",... | 5,301,860 |
def n_clinic_to_unit_cube(x_array,box):
"""
---Inputs---
x_array : {2 mode numpy array}
array defining the "real" coordinate(s) at which to calculate values of
basis functions
shape (n_points, d)
dimension of first mode gives number of points
dimension of second m... | 5,301,861 |
def permission_request_delete_link(context, perm):
"""
Renders a html link to the delete view of the given permission request.
Returns no content if the request-user has no permission to delete foreign
permissions.
"""
user = context['request'].user
if user.is_authenticated():
link_k... | 5,301,862 |
def dummies(data):
"""
Manually creates labels for property type. sklearn label encoder was breaking the model shape.
"""
data['Property_Area'] = data['Property_Area'].replace('Rural', 0, regex=True)
data['Property_Area'] = data['Property_Area'].replace('Semiurban', 1, regex=True)
data['Property... | 5,301,863 |
def get_specs():
"""
Get FSM specifications stored in this file.
"""
from fsm.fsmspec import FSMSpecification
spec = FSMSpecification(
name='faq',
hideTabs=True,
title='Take the courselet core lessons',
pluginNodes=[
START,
SHOW_FAQS,
... | 5,301,864 |
def jdk_extract_exe(jdk_archive_path, jdk_install_path):
"""
Extract the specified Oracle JDK EXE installer into the `get_tools_dir()`
directory.
Reference: <http://superuser.com/a/896186>.
Args:
jdk_archive_path (str): The local path to the Oracle JDK EXE installer to
... | 5,301,865 |
def render(
markup: str,
style: Union[str, Style] = "",
emoji: bool = True,
emoji_variant: Optional[EmojiVariant] = None,
) -> Text:
"""Render console markup in to a Text instance.
Args:
markup (str): A string containing console markup.
emoji (bool, optional): Also render emoji ... | 5,301,866 |
def get_namespaced_custom_object_with_retries(namespace, name):
"""Call get_namespaced_customer_object API with retries.
Args:
namespace: namespace for the workflow.
name: name of the workflow.
"""
# Due to https://github.com/kubernetes-client/python-base/issues/59,
# we need to recreate the API clie... | 5,301,867 |
def info_colon_to_dict(value):
"""
Simple function to convert colon separated string to dict
"""
return info_to_dict(value, ":") | 5,301,868 |
def parse_markdown(filename):
""" Takes a .md file and returns a parsed version in HTML.
Parses a markdown file using mistune, returns a string which
contains the parsed information in HTML.
Args:
filename: the file to be parse, must be a .md file.
Returns:
Vari... | 5,301,869 |
def query_task_until_finished(task_id):
"""Blocks until an iControl LX task finishes or fails"""
max_attempts = 60
while max_attempts > 0:
max_attempts -= 1
status = get_task_status(task_id)
LOG.debug("task: %s returned status %s", task_id, status)
if status and status == 'FI... | 5,301,870 |
def create_full_example() -> model.DictObjectStore:
"""
Creates an :class:`~.aas.model.provider.DictObjectStore` which is filled with an example
:class:`~aas.model.aas.Asset`, :class:`~aas.model.submodel.Submodel`, :class:`~aas.model.concept.ConceptDescription`
and :class:`~aas.model.aas.AssetAdministra... | 5,301,871 |
def check_consistent_length(y_true: List[List[str]], y_pred: List[List[str]]):
"""
Check that all arrays have consistent first and second dimensions.
Checks whether all objects in arrays have the same shape or length.
Args:
y_true : 2d array.
y_pred : 2d array.
"""
len_true = lis... | 5,301,872 |
def startup(datasette):
"""Fires directly after Datasette first starts running""" | 5,301,873 |
def filter_kmeans_segmentation(np_img, compactness=10, n_segments=800):
"""
Use K-means segmentation (color/space proximity) to segment RGB image where each segment is
colored based on the average color for that segment.
Args:
np_img: Binary image as a NumPy array.
compactness: Color proxim... | 5,301,874 |
def _pytd_signature(
function: ast3.AST,
is_async: bool,
exceptions: Optional[List[pytd_node.Node]] = None
) -> pytd.Signature:
"""Construct a pytd signature from an ast.FunctionDef node."""
name = function.name
args = function.args
pos_params = [Param.from_arg(a, False) for a in args.args]
kwonly... | 5,301,875 |
def anno_heat(X, row_anno=None, col_anno=None,
row_order_ids=None, col_order_ids=None,
xticklabels=False, yticklabels=False,
row_cluster=False, col_cluster=False,
**kwargs):
"""
Heatmap with column or row annotations. Based on seaborn.clustermap()
Row... | 5,301,876 |
def dao_exchange_rate_mock():
"""
:return: Mock of gold_digger.database.DaoExchangeRate
"""
return Mock(DaoExchangeRate) | 5,301,877 |
def find_exec(executable: str, compat: Optional[str] = None, root: str = '/') \
-> Tuple[str, str]:
"""Search an executable in the system
Uses the ``PATH`` environment variable.
:param executable: Executable to search
:param compat: Path to a binary that the executable must be compatible with
... | 5,301,878 |
def ucsc_visualize(big_storage, rna_info, configs=None):
"""
This function takes care of generating binding sites, converting them to
appropriate formats (BED files, then bigBED files, wig, bigwig, etc.),
generating density plots, setting them up as a track hub structure, and
finally uploading them ... | 5,301,879 |
def _repr_odict(dumper, data):
"""
Represent OrderedDict in yaml dump.
Source: https://gist.github.com/weaver/317164
License: Unspecified
>>> data = OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
>>> yaml.dump(data, default_flow_style=False) # doctest: +SKIP
'!!omap\\n... | 5,301,880 |
def remove_identifiers(database, identifier_name):
"""Removes an identifier from all sections in the database"""
for section in database["sections"]:
section.pop(identifier_name, None) | 5,301,881 |
def _update_inventory(context, rp, inventory):
"""Update an inventory already on the provider.
:raises `exception.ResourceClassNotFound` if inventory.resource_class
cannot be found in either the standard classes or the DB.
"""
_ensure_rc_cache(context)
rc_id = _RC_CACHE.id_from_string(i... | 5,301,882 |
def create_db(self):
"""Establishes connection with database, and creates the table
if it does not already exist.
"""
conn = sqlite3.connect('file_xfer.db')
with conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS timestamps(unix REAL)")
conn.commit()
c.clos... | 5,301,883 |
def assert_all_loaded(pairs, raise_=True):
"""
Returns True if all SleepStudy objects in 'pairs' have the 'loaded'
property set to True, otherwise returns False.
If raise_ is True, raises a NotImplementedError if one or more objects are
not loaded. Otherwise, returns the value of the assessment.
... | 5,301,884 |
def downgrade(migrate_engine):
"""Revert removal of the instance_group_metadata table."""
meta = MetaData(bind=migrate_engine)
Table('instance_groups', meta, autoload=True)
Table('shadow_instance_groups', meta, autoload=True)
if not migrate_engine.has_table('instance_group_metadata'):
group... | 5,301,885 |
def wait_to_finish_playing(proc="all", tag="playback"):
"""
Busy wait until the processors finished playing.
For this function to work, the rcx-circuit must have a tag that is 1
while output is generated and 0 otherwise. The default name for this
kind of tag is "playback". "playback" is read repeat... | 5,301,886 |
def send_page(self, data={}):
"""Render HTML and send page to client"""
# Prepare context data for page
page = data["page"]
context = {}
match page:
case "list":
context = {"posts": Post.objects.all().order_by("-created_at")[:POST_PER_PAGE]}
case "single":
co... | 5,301,887 |
def start(view=None):
"""start the celery server
:param: if view is set to any value start also rabit and attach
to it so we can see the log
"""
# pprint (fabric.state.output)
with settings(warn_only=True):
stop()
time.sleep(2)
PROGRESS.next()
mq.start()
... | 5,301,888 |
def max_pool(x, ksize, stride, name):
"""
Create a max pooling layer
:param x: input to max-pooling layer
:param ksize: size of the max-pooling filter
:param stride: stride of the max-pooling filter
:param name: layer name
:return: The output array
"""
return tf.nn.max_pool(x,
... | 5,301,889 |
def _check_robot_postproc_compatibility(robot, processor):
"""
Verify the compatibility of the selected robot and the processor.
:return:
"""
warning = ''
robot_type = mimic_utils.get_robot_type(robot)
processor_type = processor.type_robot
# Always return without a warning if the p... | 5,301,890 |
def test_from_string_frame_uri(suffix):
"""Checks frame numbers are parsed correctly and behaves as expected."""
uri = _FRAME_URI if suffix is None else f'{_FRAME_URI}/{suffix.value}'
frame_uri = URI.from_string(uri)
# Properties.
assert frame_uri.base_url == _BASE_URL
assert frame_uri.study_ins... | 5,301,891 |
def flush(hand):
"""Return True if there is a flush"""
suits = [s for r,s in hand]
return len(set(suits)) == 1 | 5,301,892 |
def filter_by_name(candidates: List[Element], query: EdifactStackQuery) -> List[Element]:
"""
returns those elements that have the given name (in the query)
"""
filtered_by_names = [
x
for x in candidates
if are_similar_names(x.attrib["name"], query.name)
or ("ahb... | 5,301,893 |
def expand_params(params_to_env):
"""
Given a dictionary like:
{
"AwsAccessKeyId": "AWS_ACCESS_KEY_ID",
"AwsSecretAccessKey": "AWS_SECRET_ACCESS_KEY",
"KeyNukerOrg": "KEYNUKER_ORG",
}
Convert to a string like:
--param KeyNukerOrg default --param AwsAccessKeyId ***** --... | 5,301,894 |
def remote_shortname(socket):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
return socket.gethostname().split('.', 1)[0] | 5,301,895 |
def deleteAllCoregroups():
"""Deletes all Coregroups and their associated access points except the DefaultCoreGroup.
Be careful with this code. It can actually delete the DefaultCoreGroup.
And if you do, the ws runtime will be completely messed up. You've been warned."""
m = "deleteAllCoreGroups:"
... | 5,301,896 |
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description='Parsing CAN log data')
parser.add_argument('--file', required=True)
args = parser.parse_args()
parse_data(args.file) | 5,301,897 |
def MakePlot(specWithCuts, specWithoutCuts, options):
"""
Creating the final plot. The plot will be a two panel plot:
1st panel shows the comparison of the spectra.
2nd panel shows the ratio of the normalised spectra with and
without pileup rejection (as without/with)
... | 5,301,898 |
def network_instance_list(network=None, host=None):
"""
Retrieves information about all resources.
Parameter *kind*:
If *kind* is set, only resources with a matching kind will be returned.
Return value:
A list with information entries of all matching network_instances. Each list
entry contains exactly th... | 5,301,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.