content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def log_report():
""" The log report shows the log file. The user can filter and search the log. """
log_main = open(main_log, 'r').readlines()
data_main = []
for line in log_main:
split_line = line.split(' ')
data_main.append([' '.join(split_line[:2]), ' '.join(split_line[2:])])
ret... | 53905c90bed2666c7e668bf76ff03a6ba93eca5b | 6,520 |
def int_or_none(x) -> int:
"""Either convert x to an int or return None."""
try:
return int(x)
except TypeError:
return None
except ValueError:
return None | e7fbd422a6c61293c9f4f71df211a85570d4400e | 6,521 |
def needed_to_build_multi(deriv_outputs, existing=None, on_server=None):
"""
:param deriv_outputs: A mapping from derivations to sets of outputs.
:type deriv_outputs: ``dict`` of ``Derivation`` to ``set`` of ``str``
"""
if existing is None:
existing = {}
if on_server is None:
on... | d05083ea9c71c982d312e8b420b21bba92b80ee4 | 6,523 |
def iscode(c):
"""
Tests if argument type could be lines of code,
i.e. list of strings
"""
if type(c) == type([]):
if c:
return type(c[0]) == type('')
else:
return True
else: return False | e60da6c05922ff1e67db15fa4caa1500a8f470c7 | 6,524 |
def get_comment_list(request, thread_id, endorsed, page, page_size, requested_fields=None):
"""
Return the list of comments in the given thread.
Arguments:
request: The django request object used for build_absolute_uri and
determining the requesting user.
thread_id: The id of th... | 980e52645e96853339df0525359ddba4698bf7e7 | 6,525 |
from typing import List
def files(name: str, dependencies=False, excludes=None) -> List[PackagePath]:
"""
List all files belonging to a distribution.
Arguments:
name:
The name of the distribution.
dependencies:
Recursively collect files of dependencies too.
... | cfda01bb7e6858e378aadeea47e6e4a0d76dda2f | 6,526 |
def ready_to_delete_data_node(name, has_executed, graph):
"""
Determines if a DataPlaceholderNode is ready to be deleted from the
cache.
Args:
name:
The name of the data node to check
has_executed: set
A set containing all operations that have been executed so fa... | 7da3c6053146a1772223e29e1eca15107e0347b6 | 6,527 |
import hashlib
def extract_hash_parts(repo):
"""Extract hash parts from repo"""
full_hash = hashlib.sha1(repo.encode("utf-8")).hexdigest()
return full_hash[:2], full_hash[2:] | aa1aebaf9b8330539eb0266c4ff97fd3459753c8 | 6,528 |
def create_cloud_mask(im_QA, satname, cloud_mask_issue):
"""
Creates a cloud mask using the information contained in the QA band.
KV WRL 2018
Arguments:
-----------
im_QA: np.array
Image containing the QA band
satname: string
short name for the satellite: ```'L5', 'L7', 'L8... | 5143c1c61425a131bdb3b0f91018643c9a9d4123 | 6,529 |
import re
def split_bucket(s3_key):
"""
Returns the bucket name and the key from an s3 location string.
"""
match = re.match(r'(?:s3://)?([^/]+)/(.*)', s3_key, re.IGNORECASE)
if not match:
return None, s3_key
return match.group(1), match.group(2) | 6b854bdc9d105643a9fa528e6fefd19672451e63 | 6,530 |
def contains_chinese(ustr):
"""
将字符串中的中文去除
Args:
ustr: 字符串
Returns: 去除中文的字符串
"""
return any('\u4e00' <= char <= '\u9fff' for char in ustr) | 8d53a214e1754e1c129f1583a298f5a19e1f76d3 | 6,531 |
def payment_activity():
"""Request for extra-curricular activity"""
try:
req_json = request.get_json(force=True)
except TypeError:
return jsonify(message='Invalid json input'), 400
activity_info = req_json['activity']
student = req_json['student']
envelope_args = {
'sign... | a313b6e5ed00ffc9b3685ce28a9c640e96276347 | 6,532 |
def gdc_to_dos_list_response(gdcr):
"""
Takes a GDC list response and converts it to GA4GH.
:param gdc:
:return:
"""
mres = {}
mres['data_objects'] = []
for id_ in gdcr.get('ids', []):
mres['data_objects'].append({'id': id_})
if len(gdcr.get('ids', [])) > 0:
mres['nex... | a237a64f55c15fb10070d76b6f3cc4f283460a96 | 6,533 |
def get_labels_by_db_and_omic_from_graph(graph):
"""Return labels by db and omic given a graph."""
db_subsets = defaultdict(set)
db_entites = defaultdict(dict)
entites_db = defaultdict(dict)
# entity_type_map = {'Gene':'genes', 'mirna_nodes':'mirna', 'Abundance':'metabolites', 'BiologicalProcess':'... | 14374977afb09fded25f78e14fced607bb8f9ea1 | 6,534 |
import logging
def covid_API_england ():
"""Function retrieves date, hospital admissions, total deaths
and daily cases using government API"""
england_only = [
'areaType=nation',
'areaName=England'
]
dates_and_cases = {
"date": "date",
"newCasesByPublishDate": ... | a13090a052a35dd675c1fb31b861cbcc4b9e7c4a | 6,536 |
from meerschaum.actions.shell import default_action_completer
from typing import Optional
from typing import List
from typing import Any
def _complete_uninstall(
action : Optional[List[str]] = None,
**kw : Any
) -> List[str]:
"""
Override the default Meerschaum `complete_` function.
""... | 1cfdc5694a069c924316f57e4804ae04d63bb4af | 6,537 |
def test_bucket():
"""Universal bucket name for use throughout testing"""
return 'test_bucket' | 2f78b1b1bf7ccfff07ca29213d975f3b20f0e9a5 | 6,538 |
def us_send_code():
"""
Send code view.
This takes an identity (as configured in USER_IDENTITY_ATTRIBUTES)
and a method request to send a code.
"""
form_class = _security.us_signin_form
if request.is_json:
if request.content_length:
form = form_class(MultiDict(request.ge... | 7ca09dc6d6fdc7840d893e01b4166d65a1b9cc02 | 6,541 |
def merge_texts(files, file_index, data_type):
""" merge the dataframes in your list """
dfs, filenames = get_dataframe_list(files, file_index, data_type)
# enumerate over the list, merge, and rename columns
try:
df = dfs[0]
# print(*[df_.columns for df_ in dfs],sep='\n')
for i, ... | 4e336a240afd100797b707efc9ccc96feb8d2919 | 6,542 |
def create_dictionary(names, months, years, max_sustained_winds, areas_affected, updated_damages, deaths):
"""Create dictionary of hurricanes with hurricane name as the key and a dictionary of hurricane data as the value."""
hurricanes = dict()
num_hurricanes = len(names)
for i in range(num_hurricanes):
hur... | 5a27d5349113f29d2af55df27a2ee2c2cc524549 | 6,543 |
def create_variable_type(parent, nodeid, bname, datatype):
"""
Create a new variable type
args are nodeid, browsename and datatype
or idx, name and data type
"""
nodeid, qname = _parse_nodeid_qname(nodeid, bname)
if datatype and isinstance(datatype, int):
datatype = ua.NodeId(datatyp... | b2202b929bc51e2a2badfef6ec31df45e9736268 | 6,544 |
def load_NWP(input_nc_path_decomp, input_path_velocities, start_time, n_timesteps):
"""Loads the decomposed NWP and velocity data from the netCDF files
Parameters
----------
input_nc_path_decomp: str
Path to the saved netCDF file containing the decomposed NWP data.
input_path_velocities: str
... | d96dacc14404f59b15a428e62608765486623460 | 6,545 |
def get_ts(fn, tc, scale=0):
"""Returns timestamps from a frame number and timecodes file or cfr fps
fn = frame number
tc = (timecodes list or Fraction(fps),tc_type)
scale default: 0 (ns)
examples: 3 (µs); 6 (ms); 9 (s)
"""
scale = 9 - scale
tc, tc_type = tc
if tc_type... | 845b2600268a2942ca0fe2b09336ab724b00e299 | 6,546 |
import numpy
def adapt_array(array):
"""
Using the numpy.save function to save a binary version of the array,
and BytesIO to catch the stream of data and convert it into a BLOB.
:param numpy.array array: NumPy array to turn into a BLOB
:return: NumPy array as BLOB
:rtype: BLOB
"""
out... | 36a62c745de0e933b520821ea7cce70f5013c5d2 | 6,547 |
def make_queue(paths_to_image, labels, num_epochs=None, shuffle=True):
"""returns an Ops Tensor with queued image and label pair"""
images = tf.convert_to_tensor(paths_to_image, dtype=tf.string)
labels = tf.convert_to_tensor(labels, dtype=tf.uint8)
input_queue = tf.train.slice_input_producer(
... | 7a2ad9338642a5d6c7af59fe972ee9fd07f128b8 | 6,548 |
def display_import(request, import_id):
"""Display the details of an import."""
import_object = get_object_or_404(RegisteredImport, pk=import_id)
context_data = {'import': import_object}
return render(request, 'eats/edit/display_import.html', context_data) | b5676dd5da1791fb6eda3d6989b9c7c0c8b02b8c | 6,549 |
def TransformContainerAnalysisData(image_name, occurrence_filter=None,
deployments=False):
"""Transforms the occurrence data from Container Analysis API."""
analysis_obj = container_analysis_data_util.ContainerAndAnalysisData(
image_name)
occs = FetchOccurrencesForResource... | d7021dde08a77ac6922274f3e69d841983728f4e | 6,550 |
def bilinear_initializer(shape, dtype, partition_info):
"""
Bilinear initializer for deconvolution filters
"""
kernel = get_bilinear_kernel(shape[0], shape[1], shape[2])
broadcasted_kernel = np.repeat(kernel.reshape(shape[0], shape[1], shape[2], -1), repeats=shape[3], axis=3)
return broadcaste... | 48a7cc2808e72df816c9b6ff7a8975eb52e4185e | 6,552 |
def pdf():
"""
Демо-версия PDF отчеа, открывается прямо в браузере,
это удобнее, чем каждый раз скачивать
"""
render_pdf(sample_payload_obj, './output.pdf')
upload_file('./output.pdf')
return send_file('./output.pdf', attachment_filename='output.pdf') | a2a60c26df9844e605606538d40d1402cd5a4985 | 6,553 |
def run_clear_db_es(app, arg_env, arg_skip_es=False):
"""
This function actually clears DB/ES. Takes a Pyramid app as well as two flags. _Use with care!_
For safety, this function will return without side-effect on any production system.
Also does additional checks based on arguments supplied:
If... | e7d865dec8691c4d0db7bef71b68bab9bc5174a2 | 6,554 |
def init_total_population():
"""
Real Name: b'init total population'
Original Eqn: b'init Infected asymptomatic+init Susceptible'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
return init_infected_asymptomatic() + init_susceptible() | cf742a00d0140c48dbdb4692dabbb8bbd6c5c6b2 | 6,555 |
def one_hot(dim: int, idx: int):
""" Get one-hot vector """
v = np.zeros(dim)
v[idx] = 1
return v | 84b87b357dc7b7bf54af4718885aa1d6fbcb35e4 | 6,556 |
import re
def process_priors(prior_flat, initial_fit):
"""Process prior input array into fit object."""
if any(
[float(val) <= 0 for key, val in prior_flat.items() if key.endswith("sdev")]
):
raise ValueError("Standard deviations must be larger than zero.")
prior = {}
for key, val... | 32358fb494a221e5e7d5d4d73776993f1c363f0f | 6,557 |
def _sample_data(ice_lines, frac_to_plot):
"""
Get sample ice lines to plot
:param ice_lines: all ice lines
:param frac_to_plot: fraction to plot
:return: the sampled ice lines
"""
if frac_to_plot < 1.:
ice_plot_data = ice_lines.sample(int(ice_lines.shape[0] * frac_to_plot))
e... | e5da9b1ecaf615863504e81cdd246336de97b319 | 6,558 |
def fast_dot(M1, M2):
"""
Specialized interface to the numpy.dot function
This assumes that A and B are both 2D arrays (in practice)
When A or B are represented by 1D arrays, they are assumed to reprsent
diagonal arrays
This function then exploits that to provide faster multiplication
""... | b34e44787f48dfb25af4975e74262f3d8eaa5096 | 6,559 |
async def autoredeem(
bot: commands.Bot,
guild_id: int
) -> bool:
"""Iterates over the list of users who have
enabled autoredeem for this server, and if
one of them does redeem some of their credits
and alert the user."""
await bot.wait_until_ready()
conn = bot.db.conn
guild = bot.g... | ee0a34e4aa9d85e9402dcbec8a1ecce5a2ca58e1 | 6,560 |
from typing import Optional
from typing import Sequence
def plot_heatmap(
data: DataFrame,
columns: Optional[Sequence[str]] = None,
droppable: bool = True,
sort: bool = True,
cmap: Optional[Sequence[str]] = None,
names: Optional[Sequence[str]] = None,
yaxis: boo... | 84233ee9293131ce98072f880a3c1a57fc71b321 | 6,562 |
def iadd_tftensor(left, right, scale=1):
"""This function performs an in-place addition. However, TensorFlow returns
a new object after a mathematical operation. This means that in-place here
only serves to avoid the creation of a TfTensor instance. We do not have
any control over the memory where the T... | 3f14de3df3544b74f0a900fca33eb6cdf6e11c00 | 6,563 |
def encode(string_):
"""Change String to Integers"""
return (lambda f, s: f(list( ord(c) for c in str(string_) ) , \
s))(lambda f, s: sum(f[i] * 256 ** i for i in \
range(len(f))), str(string_)) | da3a729c2024d80792e08424745dc267ca67dff7 | 6,565 |
def generate_file_prefix(bin_params):
""" Use the bin params to generate a file prefix."""
prefix = "bin_"
for j in range(0, len(bin_params)):
if (j + 1) % 2 != 0:
prefix += str(bin_params[j]) + "-"
else:
prefix += str(bin_params[j]) + "_"
return prefix | cc058a64fcab77f6a4794a8bf7edb1e0e86c040c | 6,566 |
def extract_features_from_html(html, depth, height):
"""Given an html text, extract the node based features
including the descendant and ancestor ones if depth and
height are respectively nonzero."""
root = etree.HTML(html.encode('utf-8')) # get the nodes, serve bytes, unicode fails if html has meta
... | ee7b627bf7c859fc886eab10f6a8b6b793653262 | 6,567 |
def __clean_field(amazon_dataset, option):
"""Cleanes the Text field from the datset """
clean = []
if option == 1:
for i in amazon_dataset['Text']:
clean.append(__one(i))
elif option == 2:
for i in amazon_dataset['Summary']:
clean.append(__one(i))
else:
... | 1e8ef28c810413b87804a42514059c347d715972 | 6,568 |
import warnings
def _read_atom_line(line):
"""
COLUMNS DATATYPE FIELD DEFINITION
-------------------------------------------------------------------------------------
1 - 6 RecordName "ATOM "
7 - 11 Integer serial Atom serial number.
13... | e511352dcc0bfcdec98035673adf759256c13e4c | 6,570 |
from typing import List
def semantic_parse_entity_sentence(sent: str) -> List[str]:
"""
@param sent: sentence to grab entities from
@return: noun chunks that we consider "entities" to work with
"""
doc = tnlp(sent)
ents_ke = textacy.ke.textrank(doc, normalize="lemma")
entities = [ent for ... | c65fa1d8da74b86b3e970cbf7f351e03d5a3fcec | 6,571 |
from numpy import array
def match_cam_time(events, frame_times):
"""
Helper function for mapping ephys events to camera times. For each event in events, we return the nearest
camera frame before the event.
Parameters
----------
events : 1D numpy array
Events of interest. Sampled at... | 3f086a0f65a34183a429cf3c50e90fdc742672d3 | 6,574 |
import ctypes
def _glibc_version_string_ctypes() -> Optional[str]:
"""
Fallback implementation of glibc_version_string using ctypes.
"""
try:
except ImportError:
return None
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "If filename is NULL, ... | 86ae885182585eeb1c5e53ee8109036dd93d06d3 | 6,575 |
from typing import Sequence
from typing import List
from typing import Tuple
def encode_instructions(
stream: Sequence[Instruction],
func_pool: List[bytes],
string_pool: List[bytes],
) -> Tuple[bytearray, List[bytes], List[bytes]]:
"""
Encode the bytecode stream as a single `bytes` object that can... | 0a371731f627b96ca3a07c5ac992fd46724a7817 | 6,576 |
def get_random(selector):
"""Return one random game"""
controller = GameController
return controller.get_random(MySQLFactory.get(), selector) | 89f458a434cd20e10810d03e7addb1c5d6f1475a | 6,577 |
def get_ssh_dispatcher(connection, context):
"""
:param Message context: The eliot message context to log.
:param connection: The SSH connection run commands on.
"""
@deferred_performer
def perform_run(dispatcher, intent):
context.bind(
message_type="flocker.provision.ssh:ru... | 1cb965c4e175276672173d5696e3196da5725fce | 6,578 |
def read_ac(path, cut_off, rnalen):
"""Read the RNA accessibility file and output its positions and values
The file should be a simple table with two columns:
The first column is the position and the second one is the value
'#' will be skipped
"""
access = []
with open(path) as f:
... | 0a8b6c2ff6528cf3f21d3b5efce14d59ff8ad2b6 | 6,579 |
def subtableD0(cxt: DecoderContext, fmt: Format):
""" ORI """
fmt = FormatVI(fmt)
return MNEM.ORI, [Imm(fmt.imm16, width=16, signed=False), Reg(fmt.reg1), Reg(fmt.reg2)], 2 | 2bb307bd74568745b7f453365f7667c383cae9ff | 6,580 |
from datetime import datetime
def format_date(unix_timestamp):
""" Return a standardized date format for use in the two1 library.
This function produces a localized datetime string that includes the UTC timezone offset. This offset is
computed as the difference between the local version of the timestamp ... | cc1a6ee0c604e14f787741ff2cb0e118134c9b92 | 6,581 |
import copy
from operator import and_
def or_(kb, goals, substitutions=dict(), depth=0, mask=None,
k_max=None, max_depth=1):
"""Base function of prover, called recursively.
Calls and_, which in turn calls or_, in order to recursively calculate scores for every possible proof in proof
tree.
A... | d19382167143ffc3b5267fda126cc4f8d45fc86c | 6,582 |
import copy
def print_term(thy, t):
"""More sophisticated printing function for terms. Handles printing
of operators.
Note we do not yet handle name collisions in lambda terms.
"""
def get_info_for_operator(t):
return thy.get_data("operator").get_info_for_fun(t.head)
def get_pri... | 745b378dac77411ba678911c478b6f5c8915c762 | 6,583 |
def build_model():
"""Builds the model."""
return get_model()() | f843bce4edf099efd138a198f12c392aa2e723cd | 6,584 |
def truncate_field_data(model, data):
"""Truncate all data fields for model by its ``max_length`` field
attributes.
:param model: Kind of data (A Django Model instance).
:param data: The data to truncate.
"""
fields = dict((field.name, field) for field in model._meta.fields)
return dict((n... | 3f0c77d279e712258d3a064ca9fed06cd64d9eaf | 6,585 |
import io
def get_all_students(zip):
"""Returns student tuple for all zipped submissions found in the zip file."""
students = []
# creating all the student objects that we can zip files of
for filename in zip.namelist():
if not filename.endswith(".zip"):
continue
firstname,... | d5088ecf43275664e8420f30f508e70fad7cef77 | 6,586 |
def is_shipping_method_applicable_for_postal_code(
customer_shipping_address, method
) -> bool:
"""Return if shipping method is applicable with the postal code rules."""
results = check_shipping_method_for_postal_code(customer_shipping_address, method)
if not results:
return True
if all(
... | cca519a35ab01dddac71ac18bdf8a40e1b032b83 | 6,587 |
def populate_api_servers():
""" Find running API servers. """
def api_server_info(entry):
prefix, port = entry.rsplit('-', 1)
project_id = prefix[len(API_SERVER_PREFIX):]
return project_id, int(port)
global api_servers
monit_entries = yield monit_operator.get_entries()
server_entries = [api_serve... | 0543e350917c3fe419022aebdd9002098021923a | 6,588 |
def create_recipe_json(image_paths: list) -> dict:
"""
Orchestrate the various services to respond to a create recipe request.
"""
logger.info('Creating recipe json from image paths: {}'.format(image_paths))
full_text = load_images_return_text(image_paths)
recipe_json = assign_text_to_recip... | 25ef26d15bf20384df81f46da519c07ea883d5a7 | 6,590 |
def rstrip_extra(fname):
"""Strip extraneous, non-discriminative filename info from the end of a file.
"""
to_strip = ("_R", "_", "fastq", ".", "-")
while fname.endswith(to_strip):
for x in to_strip:
if fname.endswith(x):
fname = fname[:len(fname) - len(x)]
... | 281ff6dcfae1894dd4685acf433bde89538fe87e | 6,591 |
def run(preprocessors, data, preprocessing=defaultdict(lambda: None), fit=True):
"""Applies preprocessing to data. It currently suppoerts StandardScaler and
OneHotEncoding
Parameters
----------
preprocessors : list
preprocessors to be applied
data : pd.DataFrame
data to be prepr... | 94b10007896062760a278cdeaf60388152c96f73 | 6,592 |
def vouchers_tab(request, voucher_group, deleted=False, template_name="manage/voucher/vouchers.html"):
"""Displays the vouchers tab
"""
vouchers = voucher_group.vouchers.all()
paginator = Paginator(vouchers, 20)
page = paginator.page((request.POST if request.method == 'POST' else request.GET).get("p... | f488c21a83b6b22e3c0e4d5fa2e35156435bada7 | 6,593 |
def spots_rmsd(spots):
""" Calculate the rmsd for a series of small_cell_spot objects
@param list of small_cell_spot objects
@param RMSD (pixels) of each spot
"""
rmsd = 0
count = 0
print 'Spots with no preds', [spot.pred is None for spot in spots].count(True), 'of', len(spots)
for spot in spots:
if... | 13809a7a0353dc18b037cd2d78944ed5f9cdc596 | 6,595 |
def sanitize_df(data_df, schema, setup_index=True, missing_column_procedure='fill_zero'):
""" Sanitize dataframe according to provided schema
Returns
-------
data_df : pandas DataFrame
Will have fields provided by schema
Will have field types (categorical, datetime, etc) provided by sch... | 8664f9dd8feea60044397072d85d21c8b5dfd6d4 | 6,596 |
def get_id_argument(id_card):
"""
获取身份证号码信息
:param id_card:
:return:
"""
id_card = id_card.upper()
id_length = len(id_card)
if id_length == 18:
code = {
'body': id_card[0:17],
'address_code': id_card[0:6],
'birthday_code': id_card[6:14],
... | ae4cad97e787fe1b0697b6a0f842f0da09795d6a | 6,597 |
def rhypergeometric(n, m, N, size=None):
"""
Returns hypergeometric random variates.
"""
if n == 0:
return np.zeros(size, dtype=int)
elif n == N:
out = np.empty(size, dtype=int)
out.fill(m)
return out
return np.random.hypergeometric(n, N - n, m, size) | e8ea95bb742891037de264462be168fab9d68923 | 6,598 |
def my_model_builder(my_model: MyModel) -> KerasModel:
"""Build the siamese network model """
input_1 = layers.Input(my_model.input_shape)
input_2 = layers.Input(my_model.input_shape)
# As mentioned above, Siamese Network share weights between
# tower networks (sister networks). To allow this, we w... | 53b32468469e7fc8cbc8f2776a1711181363bf60 | 6,600 |
from datetime import datetime
def create_embed(
title,
description,
fields = None,
colour = None,
timestamp = datetime.utcnow(),
author = None,
author_icon = None,
thumbnail = None,
image = None,
footer = None
):
"""Create an Embed
Args:
title (str): Set title
... | 741238fc50e2eda98a5cbfeab0c5c4d5cb3adbf2 | 6,601 |
def autoCalibration(I):
"""Returns horizontal and vertical factors by which every distance in
pixels should be multiplied in order to obtain the equivalent distance in
millimeters. This program assumes that the scale presents clear axis ticks and
that the distance between two biggest ticks is equal to 1... | 30016c41a8b21531cfd277a669a6b16b01322387 | 6,602 |
def reverse_handler(handler_input):
"""Check if a verb is provided in slot values. If provided, then
looks for the paradigm in the irregular_verbs file.
If not, then it asks user to provide the verb again.
"""
# iterate over the dictionaries in irregular_verbs.py and looks for
# the verb in the... | f1b49b88314f3218af03c6910d72729f888f2a11 | 6,603 |
def load_wrf_data(filename):
"""Load required data form the WRF output file : filename"""
base_data=load_vars(filename,wrfvars)
skin_t=load_tskin(filename,tsvar,landmask)
base_data.append(skin_t)
atts=mygis.read_atts(filename,global_atts=True)
return Bunch(data=base_data,global_atts=at... | da6439d3d4adfc8b84d5bf5911aa5e4b9d628baa | 6,604 |
def sanitize_date(date_dict: dict):
"""
Function to take the date values entered by the user and check their validity. If valid it returns True,
otherwise it sets the values to None and returns False
:param date_dict:
:return:
"""
month = date_dict["month"]
day = date_dict["day"]
ye... | c8cc01c8c1259ab8c4b263e36ae9f85a95356017 | 6,606 |
def create_scale(tonic, pattern, octave=1):
"""
Create an octave-repeating scale from a tonic note
and a pattern of intervals
Args:
tonic: root note (midi note number)
pattern: pattern of intervals (list of numbers representing
intervals in semito... | f9337289fda2e1b08cd371d3e91cc5a23c9c9822 | 6,607 |
def _qfloat_append(qf, values, axis=None):
"""Implement np.append for qfloats."""
# First, convert to the same unit.
qf1, qf2 = same_unit(qf, values, func=np.append)
nominal = np.append(qf1.nominal, qf2.nominal, axis)
std = np.append(qf1.uncertainty, qf2.uncertainty, axis)
return QFloat(nominal,... | 46049a2ba43997578ae502acd395cfa767e623ca | 6,608 |
from typing import List
def filter_by_mean_color(img:np.ndarray, circles:List[Circle], threshold=170) -> List[Circle]:
"""Filter circles to keep only those who covers an area which high pixel mean than threshold"""
filtered = []
for circle in circles:
box = Box(circle=circle)
area = box.ge... | d23f92d363cd4df70ba0d0d01450865546d7f289 | 6,609 |
def ParseSortByArg(sort_by=None):
"""Parses and creates the sort by object from parsed arguments.
Args:
sort_by: list of strings, passed in from the --sort-by flag.
Returns:
A parsed sort by string ending in asc or desc.
"""
if not sort_by:
return None
fields = []
for field in sort_by:
... | cc2c40d8d810396420e5c3ede0d65159ed21d6bc | 6,610 |
def dense_to_text(decoded, originals):
"""
Convert a dense, integer encoded `tf.Tensor` into a readable string.
Create a summary comparing the decoded plaintext with a given original string.
Args:
decoded (np.ndarray):
Integer array, containing the decoded sequences.
... | d7d4ec6ef2653a4e9665711201cef807a6c9830b | 6,611 |
def admin_view_all_working_curriculums(request):
""" views all the working curriculums offered by the institute """
user_details = ExtraInfo.objects.get(user = request.user)
des = HoldsDesignation.objects.all().filter(user = request.user).first()
if str(des.designation) == "student" or str(des.designat... | 8ba99fe5712c8a93b62e2ab0c9e22594a442d9bd | 6,612 |
def getEmuAtVa(vw, va, maxhit=None):
"""
Build and run an emulator to the given virtual address
from the function entry point.
(most useful for state analysis. kinda heavy though...)
"""
fva = vw.getFunction(va)
if fva == None:
return None
cbva,cbsize,cbfva = vw.getCodeBlock(v... | bea812a1d74b39e9ba83fde56bf90e4055425b89 | 6,613 |
def _create_test_validity_conditional(metric):
"""Creates BigQuery SQL clauses to specify validity rules for an NDT test.
Args:
metric: (string) The metric for which to add the conditional.
Returns:
(string) A set of SQL clauses that specify conditions an NDT test must
meet to be c... | 8c65150bdbed3ba75546fc64d8b322d9950339c1 | 6,614 |
from typing import Union
from typing import Sequence
def tfds_train_test_split(
tfds: tf.data.Dataset,
test_frac: float,
dataset_size: Union[int, str],
buffer_size: int = 256,
seed: int = 123,
) -> Sequence[Union[tf.data.Dataset, tf.data.Dataset, int, int]]:
"""
!!! does not properly work,... | 8bbb554eca8a09716279a5d818e1cc3e7bd5ad16 | 6,615 |
from datetime import datetime
def seconds_to_hms(seconds):
"""
Convert seconds to H:M:S format.
Works for periods over 24H also.
"""
return datetime.timedelta(seconds=seconds) | e862be76c6ef6b76f8e4f6351e033193ddefd5b8 | 6,616 |
def _add_spot_2d(image, ground_truth, voxel_size_yx, precomputed_gaussian):
"""Add a 2-d gaussian spot in an image.
Parameters
----------
image : np.ndarray, np.uint
A 2-d image with shape (y, x).
ground_truth : np.ndarray
Ground truth array with shape (nb_spots, 4).
- coord... | 45c32a181df1d0239b0ad872d7c0ad83862338ed | 6,618 |
import requests
def bing(text, bot):
"""<query> - returns the first bing search result for <query>"""
api_key = bot.config.get("api_keys", {}).get("bing_azure")
# handle NSFW
show_nsfw = text.endswith(" nsfw")
# remove "nsfw" from the input string after checking for it
if show_nsfw:
t... | 5aa5fe7acdc64c815d4a8727b06c13f1e3e3b2ce | 6,619 |
from typing import List
def single_length_RB(
RB_number: int, RB_length: int, target: int = 0
) -> List[List[str]]:
"""Given a length and number of repetitions it compiles Randomized Benchmarking
sequences.
Parameters
----------
RB_number : int
The number of sequences to construct.
... | dda3f5a191c666460fc4c791c33530940986b623 | 6,620 |
def decode(text_file_abs_path, threshold=10):
"""
Decodes a text into a ciphertext.
Parameters
---------
text_file_abs_path: str
Returns
-------
ciphertext: str
"""
try:
with open(text_file_abs_path, "rb") as f:
text = f.read()
except Exc... | c0c8c96438baedda43940e2373edc4714511b507 | 6,621 |
def templatetag(parser, token):
"""
Outputs one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
... | 3b441ec3035f8efde9fd2507ab83c83ec5940a7a | 6,622 |
def reflected_phase_curve(phases, omega, g, a_rp):
"""
Reflected light phase curve for a homogeneous sphere by
Heng, Morris & Kitzmann (2021).
Parameters
----------
phases : `~np.ndarray`
Orbital phases of each observation defined on (0, 1)
omega : tensor-like
Single-scatter... | e6f9fadaec4614b5ea0058d13956cb5ef13d57b5 | 6,623 |
from operator import pos
def costspec(
currencies: list[str] = ["USD"],
) -> s.SearchStrategy[pos.CostSpec]:
"""Generates a random CostSpec.
Args:
currencies: An optional list of currencies to select from.
Returns:
A new search strategy.
"""
return s.builds(pos.CostSpec, curr... | 4147a7046e5d4b16a6f919d77683a849ceb2ce54 | 6,624 |
import json
import base64
def _process_input(data, context):
""" Pre-process request input before it is sent to TensorFlow Serving REST API
Args:
data (obj): the request data stream
context (Context): an object containing request and configuration details
Returns:
(dict): a JSON-... | 542e9d04a8e93cb835f049ebd3c9105e24e3b5ac | 6,626 |
def similarity_matrix_2d(X, Y, metric='cos'):
"""
Calculate similarity matrix
Parameters:
X: ndarray
input matrix 1
Y: ndarray
input matrix 2
distFunc: function
distance function
Returns:
result: ndarray
similarity matrix
"""
n_X ... | 02d78531347c3acb90049505297c009c845e27d2 | 6,627 |
def issue_list_with_tag(request, tag=None, sortorder=None):
"""
For a tag. display list of issues
"""
if tag:
stag = "\"%s\"" % tag
issues = Issue.tagged.with_any(stag)
tag_cloud = []
if issues:
tag_cloud = get_tagcloud_issues(issues)
issues = iss... | 1f51db85a0b5008819fda73d3d86fa184b56b327 | 6,628 |
def update_deal(id, deal_dict):
"""
Runs local validation on the given dict and gives passing ones to the API to update
"""
if utils.validate_deal_dict(utils.UPDATE, deal_dict, skip_id=True):
resp = utils.request(utils.UPDATE, 'deals', {'id': id}, data=deal_dict)
return utils.parse(resp)... | 82355c1a0204128f30b66a91fc22e3650b99f74d | 6,629 |
def plot_tilt_hist(series, ntile: str, group_name: str, extra_space: bool = True):
"""
Plots the histogram group tilts for a single ntile
:param series: frame containing the avg tilts, columns: group, index: pd.Period
:param ntile: the Ntile we are plotting for
:param group_name: the name of the gro... | 8f3077831cd11092e2a14bc60152ba693c0da6a6 | 6,630 |
def get_constraints_for_x(cell, board):
"""
Get the constraints for a given cell cell
@param cell Class instance of Variable; a cell of the Sudoku board
@param board
@return Number of constraints
"""
nconstraints = 0
# Row
for cellj in board[cell.row][:cell.col]:
if cellj.... | a46cda54569a12e80b9d52896f07335480799cb1 | 6,631 |
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print average([20, 30, 70])
40.0
"""
try:
return stats.mean(values)
except ZeroDivisionError:
return None | 85d02529404301891e0ecd1f2a9b76695a357504 | 6,632 |
def get_subgraph_pos(G, pos):
""" Returns the filtered positions for subgraph G. If subgraph = original graph then pos will be returned.
Parameters
----------
G : nx.Graph
A graph object.
Pos : dict
A dictionary with nodes as keys and positions as values.
Example
-------... | ca7fc389cc51aaace7a751f2107fe5cfbfd22e6c | 6,633 |
def _calculateWindowPosition(screenGeometry, iconGeometry, windowWidth, windowHeight):
"""
Calculate window position near-by the system tray using geometry of a system tray
and window geometry
@param screenGeometry: geometry of the screen where system tray is located
@type screenGeometry: QRect
... | 112011828dcfd0a6a54b6fe2c3d8acd92baf6c64 | 6,634 |
def build_from_config(config: dict, name: str) -> HomingMotor:
"""Build the named HomingMotor from data found in config"""
def check_for_key(key, cfg):
if key not in cfg:
raise RuntimeError('Key "{}" for HomingMotor "{}" not found.'.format(key, name))
else:
return cfg[ke... | ce39fc8db48da8145b9221120c3ec02f3bdda40f | 6,635 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.