content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calc_c_o(row):
"""
C or O excess
if (C/O>1):
excess = log10 [(YC/YH) - (YO/YH)] + 12
if C/O<1:
excess = log10 [(YO/YH) - (YC/YH)] + 12
where YC = X(C12)/12 + X(C13)/13
YO = X(O16)/16 + X(O17)/17 + X(O18)/18
YH = XH/1.00794
"""
yh = row['H'] / 1.00794
... | 5,338,300 |
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
#display total travel time
total_travel_time = df["Trip Duration"].sum()
print("the total travel time in hours:", total_travel_time/... | 5,338,301 |
def create_job_from_file(job_file):
"""Creates a job from a JSON job specification.
:param job_file: Path to job file.
:type job_file: str
:returns: Job object of specified type.
"""
logger.info("Creating Job from {}.".format(job_file))
with open(job_file) as f:
params = json.loads(... | 5,338,302 |
def test_user_config_json_error_conflict():
"""Test that @arg.user_config_json causes
CommandLineTool.run() to exit cleanly with return value 1
if both user_config (-c) and --user-config-json parameters
are given
"""
class T(CommandLineTool):
"""Test class"""
@arg.user_config
... | 5,338,303 |
def compile_insert_unless_conflict(
stmt: irast.InsertStmt,
typ: s_objtypes.ObjectType,
*, ctx: context.ContextLevel,
) -> irast.OnConflictClause:
"""Compile an UNLESS CONFLICT clause with no ON
This requires synthesizing a conditional based on all the exclusive
constraints on the object.
"... | 5,338,304 |
def plot_to_image(figure):
"""
Converts the matplotlib plot specified by "figure" to a PNG image and
returns it. The supplied figure is closed and inaccessible after this call.
"""
# Save the plot to a PNG in memory
buf = io.BytesIO()
figure.savefig(buf, format="png")
buf.seek(0)
# ... | 5,338,305 |
def test_skasch() -> None:
"""
Run `python -m pytest ./day-19/part-2/skasch.py` to test the submission.
"""
assert (
SkaschSubmission().run(
"""
--- scanner 0 ---
404,-588,-901
528,-643,409
-838,591,734
390,-675,-793
-537,-823,-458
-485,-357,347
-345,-311,381
-661,-816,-575
-876,649,... | 5,338,306 |
def sent2vec(model, words):
"""文本转换成向量
Arguments:
model {[type]} -- Doc2Vec 模型
words {[type]} -- 分词后的文本
Returns:
[type] -- 向量数组
"""
vect_list = []
for w in words:
try:
vect_list.append(model.wv[w])
except:
continue
vect_list = ... | 5,338,307 |
def postXML(server: HikVisionServer, path, xmldata=None):
"""
This returns the response of the DVR to the following POST request
Parameters:
server (HikvisionServer): The basic info about the DVR
path (str): The ISAPI path that will be executed
xmldata (str): This should be formatte... | 5,338,308 |
def get_government_trading(gov_type: str, ticker: str = "") -> pd.DataFrame:
"""Returns the most recent transactions by members of government
Parameters
----------
gov_type: str
Type of government data between:
'congress', 'senate', 'house', 'contracts', 'quarter-contracts' and 'corpora... | 5,338,309 |
def print_bytes(data):
"""
Prints a given string as an array of unsigned bytes
:param data:
:return:
"""
raw_arr = struct.unpack('<%dB' % len(data), data)
print(raw_arr) | 5,338,310 |
def pf_mobility(phi, gamma):
""" Phase field mobility function. """
# return gamma * (phi**2-1.)**2
# func = 1.-phi**2
# return 0.75 * gamma * 0.5 * (1. + df.sign(func)) * func
return gamma | 5,338,311 |
def print_df_stats(df: pd.DataFrame, df_train: pd.DataFrame, df_val: pd.DataFrame, df_test: pd.DataFrame, label_encoder, prediction):
"""
Print some statistics of the splitted dataset.
"""
try:
labels = list(label_encoder.classes_)
except AttributeError:
labels = []
headers = ["I... | 5,338,312 |
def hivtrace(id,
input,
reference,
ambiguities,
threshold,
min_overlap,
compare_to_lanl,
fraction,
strip_drams_flag=False,
filter_edges="no",
handle_contaminants="remove",
skip_... | 5,338,313 |
def parse_author_mail(author):
"""从形如 ``author <author-mail>`` 中分离author与mail"""
pat = author_mail_re.search(author)
return (pat.group(1), pat.group(2)) if pat else (author, None) | 5,338,314 |
def tag(name, content='', nonclosing=False, **attrs):
"""
Wraps content in a HTML tag with optional attributes. This function
provides a Pythonic interface for writing HTML tags with a few bells and
whistles.
The basic usage looks like this::
>>> tag('p', 'content', _class="note", _id="not... | 5,338,315 |
def _reconcile_phenotype(meth, fba_model_id, phenotype_id, out_model_id):
"""Run Gapfilling on an FBA Model [16]
:param fba_model_id: an FBA model id [16.1]
:type fba_model_id: kbtypes.KBaseFBA.FBAModel
:ui_name fba_model_id: FBA Model ID
:param phenotype_id: a phenotype simulation ID [16.2]
:t... | 5,338,316 |
def label_global_entities(ax, cmesh, edim, color='b', fontsize=10):
"""
Label mesh topology entities using global ids.
"""
coors = cmesh.get_centroids(edim)
coors = _to2d(coors)
dim = cmesh.dim
ax = _get_axes(ax, dim)
for ii, cc in enumerate(coors):
ax.text(*cc.T, s=ii, color=c... | 5,338,317 |
def build_filename():
"""Build out the filename based on current UTC time."""
now = datetime.datetime.utcnow()
fname = now.strftime('rib.%Y%m%d.%H00.bz2')
hour = int(now.strftime('%H'))
if not hour % 2 == 0:
if len(str(hour)) == 1:
hour = "0%d" % (hour - 1)
else:
... | 5,338,318 |
def sample_sequence(model, length, context=None, temperature=1.0, top_k=10, sample=True,
device='cuda', use_constrained_decoding=False, constrained_decoding_threshold=0.3,
person_to_category_to_salient_ngram_embed=(), word_embeds=(), tokenizer=None):
"""
:param model:
:param length:
:param context:
:par... | 5,338,319 |
def test_hive_partition_sensor_async_execute_failure(context):
"""Tests that an AirflowException is raised in case of error event"""
task = HivePartitionSensorAsync(
task_id="task-id",
table=TEST_TABLE,
partition=TEST_PARTITION,
metastore_conn_id=TEST_METASTORE_CONN_ID,
)
... | 5,338,320 |
def test_cache_add(cache: Cache):
"""Test that cache.add() sets a cache key but only if it doesn't exist."""
key, value = ("key", "value")
ttl = 2
cache.add(key, value, ttl)
assert cache.get(key) == value
assert cache.expire_times()[key] == ttl
cache.add(key, value, ttl + 1)
assert ca... | 5,338,321 |
def main(debug=False, args=None):
"""Start the app. We will see if we need this anyway."""
log.info('>>>>> Starting development server at http://{}/api/ <<<<<'.format(
flask_app.config['SERVER_NAME']))
# flask_app.run(debug=settings.FLASK_DEBUG)
# flask_app.run(debug=config_json["FLASK_DEBUG"])
... | 5,338,322 |
def tf1 ( fun , **kwargs ) :
"""Convert function object to TF1
"""
from ostap.math.models import tf1 as _tf1
return _tf1 ( fun , **kwargs ) | 5,338,323 |
def normalize_requires(filename, **kwargs):
"""Return the contents of filename, with all [Require]s split out and ordered at the top.
Preserve any leading whitespace/comments.
"""
if filename[-2:] != '.v': filename += '.v'
kwargs = fill_kwargs(kwargs)
lib = lib_of_filename(filename, **kwargs)
all_i... | 5,338,324 |
def deprecate_module_with_proxy(module_name, module_dict, deprecated_attributes=None):
"""
Usage:
deprecate_module_with_proxy(__name__, locals()) # at bottom of module
"""
def _ModuleProxy(module, depr):
"""Return a wrapped object that warns about deprecated accesses"""
# http:/... | 5,338,325 |
def nexthop_vr(pano, base_xpath, static_route_name, nexthop, destination):
"""
Sets static route with a nexthop VR
Parameters
----------
pano : Panorama
A PanDevice for Panorama
base_xpath : str
The initial API command for the virtual router
static_route_name : str... | 5,338,326 |
def index():
"""
Returns:
render_template (flask method): contains data required to render visualizations
"""
graphs = []
# extract data needed for visuals
# TODO: Below is an example - modify to extract data for your own visuals
genre_counts = df.groupby('genre')['message'].co... | 5,338,327 |
def test_pseudonymize__day__1():
"""It makes sure that the pseudonymized day is not bigger than 28."""
from gocept.pseudonymize import day
assert 19 == pseudo(10, day) | 5,338,328 |
def date(
instance,
fg_color=[255, 255, 255], bg_color=[0, 0, 0],
scroll=0.1
):
"""Display the date in the french format (dd/mm/yyyy)"""
instance.show_message(
strftime("%d/%m/%Y"),
text_colour=fg_color,
back_colour=bg_color,
scroll_speed=scroll
) | 5,338,329 |
def uniform_dec(num):
"""
Declination distribution: uniform in sin(dec), which leads to a uniform distribution across all declinations.
Parameters
----------
num : int
The number of random declinations to produce.
"""
return (numpy.pi / 2.) - numpy.arccos(2 * random.random_sample(num... | 5,338,330 |
def run_vcfeval(job, context, sample, vcf_tbi_id_pair, vcfeval_baseline_id, vcfeval_baseline_tbi_id,
fasta_path, fasta_id, bed_id, out_name = None, score_field=None):
"""
Run RTG vcf_eval to compare VCFs.
Return a results dict like:
{
"f1": f1 score as float,
"summary... | 5,338,331 |
def helicsInputGetBytes(ipt: HelicsInput) -> bytes:
"""
Get the raw data for the latest value of a subscription.
**Parameters**
- **`ipt`** - The input to get the data for.
**Returns**: Raw string data.
"""
if HELICS_VERSION == 2:
f = loadSym("helicsInputGetRawValue")
else:
... | 5,338,332 |
def named_char_class(char_class, min_count=0):
"""Return a predefined character class.
The result of this function can be passed to :func:`generate_password` as
one of the character classes to use in generating a password.
:param char_class: Any of the character classes named in
... | 5,338,333 |
def parse_args():
"""Parse commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
help='specify minSdkVersion used by the build system')
parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_... | 5,338,334 |
def make_grid(spatial_dim: Sequence[int]) -> torch.Tensor:
"""Make the grid of coordinates for the Fourier neural operator input.
Args:
spatial_dim: A sequence of spatial deimensions `(height, width)`.
Returns:
A torch.Tensor with the grid of coordinates of size `(1, height, width,
... | 5,338,335 |
def _default_handlers(stream, logging_level, include_time):
"""Return a list of the default logging handlers to use.
Args:
stream: See the configure_logging() docstring.
include_time: See the configure_logging() docstring.
"""
# Create the filter.
def should_log(record):
"""Retu... | 5,338,336 |
def find_spec2d_from_spec1d(spec1d_files):
"""
Find the spec2d files corresponding to the given list of spec1d files.
This looks for the spec2d files in the same directory as the spec1d files.
It will exit with an error if a spec2d file cannot be found.
Args:
spec1d_files (list of str): List o... | 5,338,337 |
def bootstrap_cfg():
"""Allow PyScaffold to be used to package itself.
Usually, running ``python setup.py egg_info --egg-base .`` first is a good
idea.
"""
src_dir = os.path.join(__location__, 'src')
egg_info_dir = os.path.join(__location__, 'PyScaffold.egg-info')
has_entrypoints = os.path.... | 5,338,338 |
def datedif(ctx, start_date, end_date, unit):
"""
Calculates the number of days, months, or years between two dates.
"""
start_date = conversions.to_date(start_date, ctx)
end_date = conversions.to_date(end_date, ctx)
unit = conversions.to_string(unit, ctx).lower()
if start_date > end_date:
... | 5,338,339 |
def tan(data):
"""Compute elementwise tan of data.
Parameters
----------
data : relay.Expr
The input data
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.tan(data) | 5,338,340 |
def first_facility():
"""Last business day before or on 5th day of the Submission month, 8:00am"""
facility_partial(5) | 5,338,341 |
def default_main(puzzle_class: Type[Puzzle]):
"""A default main function for puzzle scripts."""
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--interactive", action="store_true")
parser.add_argument("file", help="file containing Alloy instance txt")
args = parser.parse_args()
wit... | 5,338,342 |
def get_battery_data(battery, user=None, start = None, end = None):
""" Returns a DataFrame with battery data for a user.
Parameters
----------
battery: DataFrame with battery data
user: string, optional
start: datetime, optional
end: datetime, optional
"""
assert isinstance(battery,... | 5,338,343 |
def fix_brushes(brushes, thresh, vmf_in, snaplo, snaphi):
"""
Find and fix brushes with floating point plane coordinates.
Returns a tuple containing the total number of brushes whose coordinates
were rounded, a list of tuples which pairs suspicious brush IDs with the
greatest deviation any one of t... | 5,338,344 |
def mutate():
"""
Handles the '/mutate' path and accepts CREATE and UPDATE requests.
Sends its response back, which either denies or allows the request.
"""
try:
logging.debug(request.json)
admission_request = AdmissionRequest(request.json)
response = __admit(admission_reques... | 5,338,345 |
def _data_writer(data, file_path, sr = 16000):
""" A wrapper to write raw binary data or waveform
"""
file_name, file_ext = os.path.splitext(file_path)
if file_ext == '.wav':
nii_wav_tk.waveFloatToPCMFile(data, file_path, sr = sr)
elif file_ext == '.txt':
nii_warn.f_die("Cannot write... | 5,338,346 |
def ascii_to_raster(input_ascii, output_raster,
input_type=np.float32, input_proj=None):
"""Convert an ASCII raster to a different file format
Args:
input_ascii (str):
output_raster (str):
input_type ():
input_proj ():
Returns:
None
"""
i... | 5,338,347 |
def pds_p_score(studydata, column, context):
"""Please split this field between 'pds_pv_boy_tanner' for boys and 'pds_pv_girl_tanner' for girls."""
studydata['pds_pv_girl_tanner'] = column.where(studydata.gender=='F')
studydata['pds_pv_boy_tanner'] = column.where(studydata.gender=='M') | 5,338,348 |
def generate_options_for_resource_group(control_value=None, **kwargs) -> List:
"""Dynamically generate options for resource group form field based on the user's selection for Environment."""
if control_value is None:
return []
# Get the environment
env = Environment.objects.get(id=control_value... | 5,338,349 |
def printallspoff(pths):
""" Print SP_OFF values for all CORRTAG files (should be same for RAWTAG files)
Parameters
----------
pths : list of str
list of paths to the files
Returns
-------
"""
for ifldpth in pths:
raws = glob.glob(ifldpth + '*corrtag_*.fits')
f... | 5,338,350 |
def plot_map(fvcom, tide_db_path, threshold=np.inf, legend=False, **kwargs):
"""
Plot the tide gauges which fall within the model domain (in space and time) defined by the given FileReader object.
Parameters
----------
fvcom : PyFVCOM.read.FileReader
FVCOM model data as a FileReader object.... | 5,338,351 |
def generate_vocab_file(corpus_dir):
"""
Generate the vocab.txt file for the training and prediction/inference.
Manually remove the empty bottom line in the generated file.
"""
data_list = []
vocab_list = []
freq_dist = {}
seq_len_dict = {}
# Special tokens, with IDs: 0, 1, 2
f... | 5,338,352 |
def test_cli_with_no_login_or_password(config, capsys, valid_connection):
"""Test empty login parameters."""
testargs = ["yessssms", "-m", "test"] # "-l", "\"\"", "-p", "\"\""]
# print("test:..." + str(YesssSMS.const.CONFIG_FILE_PATHS))
with (mock.patch.object(sys, "argv", testargs)):
with pyte... | 5,338,353 |
def insertDataCaller(columns):
"""Calls the insertData function a few times to insert info into the DB."""
cols = ['transformer', 'timestamp', 'vlt_a', 'vlt_b', 'vlt_c', 'volt']
insertData(['transformerOutput.csv'], 'TransformerData', cols)
cols = ['circuit', 'timestamp', 'amp_a', 'amp_b', 'amp_c', 'mvar', ... | 5,338,354 |
def test_get_set_head():
"""test public header CRUD via slashpath """
mydat = mkh5.mkh5(TEST_H5)
mydat.reset_all()
mydat.create_mkdata(S01["gid"], S01["eeg_f"], S01["log_f"], S01["yhdr_f"])
# test get->set->get round trip
head_pattern = "S01/dblock_0/streams/MiPa/"
before_head = mydat.geth... | 5,338,355 |
def create_transfer_event(imsi, old_credit, new_credit, reason,
from_number=None, to_number=None):
"""Creates a credit transfer event."""
_create_event(imsi, old_credit, new_credit, reason,
from_number=from_number, to_number=to_number) | 5,338,356 |
def get_element_block(
xml_string: str,
first_name: str,
second_name: str = None,
include_initial: bool = True,
include_final: bool = True
) -> str:
"""
warning: use great caution if attempting to apply this function,
or anything like it, to tags that that may appear more than o... | 5,338,357 |
def eval_eu_loss(ambiguity_values, dfs_ambiguity):
"""Calculate the expected utility loss that results from a setting that
incorporates different levels of ambiguity.
Args:
ambiguity_values (dict): Dictionary with various levels of ambiguity
to be implemented (key = name of scenario).
... | 5,338,358 |
def reset(ip: str = None, username: str = None) -> int:
"""
Reset records that match IP or username, and return the count of removed attempts.
This utility method is meant to be used from the CLI or via Python API.
"""
attempts = AccessAttempt.objects.all()
if ip:
attempts = attempts.... | 5,338,359 |
def try_patch_column(meta_column: MetaColumn) -> bool:
"""Try to patch the meta column from request.json.
Generator assignment must be checked for errors.
Disallow column type change when a generator is assigned and when the column
is imported. An error is raised in that case.
"""
if 'col_type... | 5,338,360 |
def get_subvs(parent):
"""
:param parent:
:return:
"""
import btrfsutil
#ls_dirs=[os.path.join(parent, name) for name in os.listdir(parent) if os.path.isdir(os.path.join(parent, name))]
return [directory for directory in os.listdir(parent) if btrfsutil.is_subvolume(directory)] | 5,338,361 |
def readout(x, mask, aggr='add'):
"""
Args:
x: (B, N_max, F)
mask: (B, N_max)
Returns:
(B, F)
"""
return aggregate(x=x, dim=1, aggr=aggr, mask=mask, keepdim=False) | 5,338,362 |
def _update_ipython_ns(shell, globals, locals):
"""Update the IPython 0.11 namespace at every visit"""
shell.user_ns = locals.copy()
try:
shell.user_global_ns = globals
except AttributeError:
class DummyMod:
"""A dummy module used for IPython's interactive namespace."""
... | 5,338,363 |
def debug_ssh(function):
"""Decorator to generate extra debug info in case off SSH failure"""
def wrapper(self, *args, **kwargs):
try:
return function(self, *args, **kwargs)
except tempest.lib.exceptions.SSHTimeout:
try:
original_exception = sys.exc_info()... | 5,338,364 |
def editTags(
tagPaths, # type: List[String]
attributes, # type: Dict
parameters, # type: Dict
accessRights, # type: String
overrides, # type: Dict
alarmList, # type: String
alarmConfig, # type: Dict
provider="", # type: Optional[String]
json=None, # type: Optional[String]
)... | 5,338,365 |
def cases():
"""
Loads all filenames of the pre-calculated test cases.
"""
case_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'cases'
)
cases = []
for dir_path, _, files in os.walk(case_dir):
cases = cases + [os.path.join(dir_path, f) for f in files... | 5,338,366 |
def remove_old_ckpts(model_dir, reverse=False):
""" reverse=False->loss, reverse=True->reward, Only keep the highest three checkpoints. """
ckpts = os.listdir(join(model_dir, 'ckpt'))
score_list = [float(ckpt.split('-')[-1]) for ckpt in ckpts]
ckpts_score_sorted = sorted(zip(score_list, ckpts), key=lamb... | 5,338,367 |
def axisAligned(angle, tol=None, axis=None):
""" Determine if a line (represented by its angle) is aligned with an axis.
Parameters
----------
angle : float
The line's angle of inclination (in radians)
tol : float
Maximum distance from `axis` for which `angle` is still considered to... | 5,338,368 |
def gpio_pin_expression(conf):
"""Generate an expression for the given pin option.
This is a coroutine, you must await it with a 'yield' expression!
"""
if conf is None:
return
from esphome import pins
for key, (func, _) in pins.PIN_SCHEMA_REGISTRY.items():
if key in conf:
... | 5,338,369 |
def make_results_dict(
mesh_data,key_descriptor,
key_transformation=None,
verbose=False
):
"""Load mesh data into dictionary, using specified parameter tuple as
key.
Example key descriptor:
(("Nsigmamax",int),("Nmax",int),("hw",float))
Example:
>>> KEY_DESCRI... | 5,338,370 |
def plot_1d(x_test, mean, var):
"""
Description
----------
Function to plot one dimensional gaussian process regressor mean and
variance.
Parameters
----------
x_test: array_like
Array containing one dimensional inputs of the gaussian process
model.
Mean: array_like
... | 5,338,371 |
def sentence_to_windows(sentence, min_window, max_window):
"""
Create window size chunks from a sentence, always starting with a word
"""
windows = []
words = sentence.split(" ")
curr_window = ""
for idx, word in enumerate(words):
curr_window += (" " + word)
curr_window = cur... | 5,338,372 |
def get_master_name(els):
"""Function: get_master_name
Description: Return name of the master node in a Elasticsearch cluster.
Arguments:
(input) els -> ElasticSearch instance.
(output) Name of master node in ElasticSearch cluster.
"""
return els.cat.master().strip().split(" "... | 5,338,373 |
def flop_turn_river(dead: Sequence[str]) -> Sequence[str]:
"""
Get flop turn and river cards.
Args:
dead: Dead cards.
Returns:
5 cards.
"""
dead_concat = "".join(dead)
deck = [card for card in DECK if card not in dead_concat]
return random.sample(deck, 5) | 5,338,374 |
def smith_gassmann(kstar, k0, kfl2, phi):
"""
Applies the Gassmann equation.
Returns Ksat2.
"""
a = (1 - kstar/k0)**2.0
b = phi/kfl2 + (1-phi)/k0 - (kstar/k0**2.0)
ksat2 = kstar + (a/b)
return ksat2 | 5,338,375 |
async def _preflight_cors(request):
"""Respond to preflight CORS requests and load parameters."""
if request.method == "OPTIONS":
return textify("ok", headers=generate_cors_headers(request))
request['args'] = {}
if request.form:
for key in request.form:
key_lower = key.lower(... | 5,338,376 |
def login_teacher():
""" Login User and redirect to index page. """
# forget any user
session.clear()
# if user reached via route POST
if request.method == "POST":
# check user credentials
email_id = request.form.get("email_id")
passw = request.form.get("password")
... | 5,338,377 |
def upload_file():
"""Upload files"""
print("UPLOADED FILES", len(request.files))
if not os.path.exists(FILE_START_PATH):
os.makedirs(FILE_START_PATH)
# Set the upload folder for this user if it hasn't been set yet
# pylint: disable=consider-using-with
if 'upload_folder' not in session ... | 5,338,378 |
def mult_to_bytes(obj: object) -> bytes:
"""Convert given {array of bits, bytes, int, str, b64} to bytes"""
if isinstance(obj, list):
i = int("".join(["{:01b}".format(x) for x in obj]), 2)
res = i.to_bytes(bytes_needed(i), byteorder="big")
elif isinstance(obj, int):
res = obj.to_by... | 5,338,379 |
def get_barrier(loopy_opts, local_memory=True, **loopy_kwds):
"""
Returns the correct barrier type depending on the vectorization type / presence
of atomics
Parameters
----------
loopy_opts: :class:`loopy_utils.loopy_opts`
The loopy options used to create this kernel.
local_memory: ... | 5,338,380 |
def envset(**kwargs):
"""
Set environment variables that will last for the duration of the with
statement.
To unset a variable temporarily, pass its value as None.
"""
prev = {}
try:
# record the original values
for name in kwargs:
prev[name] = os.getenv(name)
... | 5,338,381 |
def monthly_rain(year, from_month, x_months, bound):
"""
This function downloaded the data embedded tif files from the SILO Longpaddock Dataset
and creates a cumulative annual total by stacking the xarrays. This function is embedded
in the get_rainfall function or can be used separately
Paramet... | 5,338,382 |
def organize_by_chromosome(genes, transcripts):
""" Iterate through genes and transcripts and group them by chromosome """
gene_dict = {}
transcript_dict = {}
for ID in genes:
gene = genes[ID]
chromosome = gene.chromosome
if chromosome not in gene_dict:
chrom_genes =... | 5,338,383 |
def get_synth_stations(settings, wiggle=0):
""" Compute synthetic station locations.
Values for mode "grid" and "uniform" and currently for tests on global Earth geometry.
TODO: incorporate into settings.yml
:param settings: dict holding all info for project
:type settings: dict
:param wi... | 5,338,384 |
def test_show_chromosome_labels(dash_threaded):
"""Test the display/hiding of chromosomes labels."""
prop_type = 'bool'
def assert_callback(prop_value, nclicks, input_value):
answer = ''
if nclicks is not None:
answer = FAIL
if PROP_TYPES[prop_type](input_value) == ... | 5,338,385 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
name = entry.data.get(CONF_NAME)
ha = get_ha(hass, name)
if ha is not None:
await ha.async_remove()
clear_ha(hass, name)
return True | 5,338,386 |
def relay_state(pin):
"""Take in pin, return string state of the relay"""
logger.debug("relay_state() for pin %s", pin)
disabled = GPIO.digitalRead(pin)
logger.debug("Pin %s disabled: %s", pin, disabled)
state = "off"
if not disabled:
state = "on"
logger.debug("Relay state for pin %s... | 5,338,387 |
def calc_fn(grid, size, coefficients=(-0.005, 10)):
""" Apply the FitzHugh-Nagumo equations to a given grid"""
a, b, *_ = coefficients
out = np.zeros(size)
out[0] = grid[0] - grid[0] ** 3 - grid[1] + a
out[1] = b * (grid[0] - grid[1])
return out | 5,338,388 |
def test_str():
"""
Проверка текстового представления
"""
c = Carousel(window=4)
assert str(c) == 'Carousel([], window=4)'
c = Carousel([1, 2, 3])
assert str(c) == 'Carousel([1, 2, 3], window=3)'
c = Carousel([1, 2, 3], window=2)
assert str(c) == 'Carousel([2, 3], window=2)' | 5,338,389 |
def destr(screenString):
"""
should return a valid screen object
as defined by input string
(think depickling)
"""
#print "making screen from this received string: %s" % screenString
rowList = []
curRow = []
curAsciiStr = ""
curStr = ""
for ch in screenString:
if ch == '\n':
# then we are done with... | 5,338,390 |
def analytical_solution_with_penalty(train_X, train_Y, lam, poly_degree):
"""
加惩罚项的数值解法
:param poly_degree: 多项式次数
:param train_X: 训练集的X矩阵
:param train_Y: 训练集的Y向量
:param lam: 惩罚项系数
:return: 解向量
"""
X, Y = normalization(train_X, train_Y, poly_degree)
matrix = np.linalg.inv(X.T.dot(... | 5,338,391 |
def formule_haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""
Description:
Calcule la distance entre deux points par la formule de Haversine.
Paramètres:
lat1: {float} -- Latitude du premier point.
lon1: {float} -- Longitude du premier point.
la... | 5,338,392 |
def __load_functions__ (symtbl):
"""Loads all Python functions from the module specified in the
``functions`` configuration parameter (in config.yaml) into the given
symbol table (Python dictionary).
"""
modname = ait.config.get('functions', None)
if modname:
module = pydoc.locate(modna... | 5,338,393 |
def get_word_combinations(word):
"""
'one-two-three'
=>
['one', 'two', 'three', 'onetwo', 'twothree', 'onetwothree']
"""
permutations = []
parts = [part for part in word.split(u'-') if part]
for count in range(1, len(parts) + 1):
for index in range(len(parts) - count + 1):
... | 5,338,394 |
def env_to_file(env_variables, destination_path=None, posix=True):
"""
Write environment variables to a file.
:param env_variables: environment variables
:param destination_path: destination path of a file where the
environment variables will be stored. the
... | 5,338,395 |
def _phase_norm(signal, reference_channel=0):
"""Unit normalization.
Args:
signal: STFT signal with shape (..., T, D).
Returns:
Normalized STFT signal with same shape.
"""
angles = np.angle(signal[..., [reference_channel]])
return signal * np.exp(-1j * angles) | 5,338,396 |
def maintenance_():
"""Render a maintenance page while on maintenance mode."""
return render_template("maintenance/maintenance.html") | 5,338,397 |
def CanEditHotlist(effective_ids, hotlist):
"""Return True if a user is editor(add/remove issues and change rankings)."""
return any([user_id in (hotlist.owner_ids + hotlist.editor_ids)
for user_id in effective_ids]) | 5,338,398 |
def key_inbetween():
""" keys inbetweens of selected objects (only selected channels) """
selected = cmds.ls(sl=True)
for sel in selected:
cmds.setKeyframe(sel, hierarchy="none", shape=False, an=True) | 5,338,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.