content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def check_manifest():
"""Check that the files listed in the MANIFEST are present when the
source is unpacked.
"""
try:
f = open('MANIFEST')
except:
print '\n*** SOURCE WARNING: The MANIFEST file is missing!'
return
try:
manifest = [l.strip() for l in f.readlines()... | 5,289,800 |
def count_set_bits(number):
""" Returns the number of set bits in number """
count = 0
while number:
count += number & 1
number >>= 1
return count | 5,289,801 |
def feedback_on(roll=True, pitch=True):
"""
Turn intensity feedback on or off
roll = True / False for roll feedback
pitch = True / False for pitch feedback
"""
caput('13IDA:efast_pitch_pid.FBON', 0)
caput('13XRM:edb:use_fb', 0)
caput('13IDA:efast_roll_pid.FBON', 0)
if pitch: caput('... | 5,289,802 |
def generate_trace(npts, dt, o):
"""
This populates the trace
"""
tr = obspy.Trace()
tr.stats.network = 'IL'
tr.stats.station = 'UIC'
tr.stats.channel = 'SES'
tr.stats.starttime = o - 30
tr.stats.sampling_rate = 1/dt
tr.stats.delta = dt
tr.stats.npts = npts
... | 5,289,803 |
def gaussian_2d(size, x0=0, y0=0, sigma_x=1, sigma_y=1, peak=1, dtype=np.float64):
"""
Returns a 2d Gaussian in a square 2d numpy array.
Default is a centered disc of spread=peak=1.
:param size: The height and width of returned array (pixels)
:param x0: x coordinate of center (pixels)
:param y... | 5,289,804 |
def test_pretty_print_word(sowpods, expected_output, capfd):
"""Ensure we are formatting the literal word 'word' correctly."""
pretty_print("word", anagrams_in_word("word", sowpods=sowpods))
stdout, _ = capfd.readouterr()
for line in expected_output:
assert line in stdout | 5,289,805 |
def save_conf(fn=None):
"""Save current configuration to file as YAML"""
if fn is None:
fn = conf['conf_file']
with open(fn, 'w') as f:
yaml.dump(conf, f) | 5,289,806 |
def send_email(msg, subject, send_to_email='default',
mail_from='from_default'):
"""Sets up and sends the email"""
# Format the message and set the subject
msg_send = MIMEText(str(msg))
msg_send['Subject'] = subject
msg_send['To'] = conf.EMAIL[send_to_email]
msg_send['Sender'] = c... | 5,289,807 |
def get_user_from_cache(user_id):
"""Get User from cache."""
logger.info("Searching user in cache files.")
try:
db_cache_file_path = USER_CACHE_DIR + "/" + user_id + ".json"
if os.path.isfile(db_cache_file_path):
logger.info("Found user in cache with id %s", user_id)
... | 5,289,808 |
def setup_admin():
"""
Creates a superuser account.
"""
if not blueprint.get('auth', True) or blueprint.get('slave'):
return
upload_conf(auth=False) and restart()
admin = blueprint.get('admin', {})
roles = [
{'role': 'userAdminAnyDatabase', 'db': 'admin'},
{'role': ... | 5,289,809 |
def FunConstantFold(fun: ir.Fun, allow_conv_conversion) -> int:
"""Relies solely on the ins.operand_def info"""
return ir.FunGenericRewriteWithBbl(fun, _InsConstantFold,
allow_conv_conversion=allow_conv_conversion) | 5,289,810 |
def serialize_environment_to_file(environment: Environment,
path: Optional[str]):
"""Dumps the environment to file.
See :func:`.save_environment`.
:param environment: Environment to save.
:param path: Output file path.
Default: IDACT_... | 5,289,811 |
def test_zeroing_gradients(zero_grad):
"""
Test for zeroing gradients functionality (zero_grads_for_pruned_modules in base algo)
:param zero_grad: zero grad or not
"""
config = get_basic_pruning_config(input_sample_size=[2, 1, 8, 8])
config['compression']['params']['prune_first_conv'] = True
... | 5,289,812 |
def copy_config(data_file=None,
local_file=None,
src=None, rep=None, private_league=False):
"""Copy default configuration file locally for user to edit
Optionally pass list of lines to replace in configuration file
:param data_file: file with configurations
:param local_file:... | 5,289,813 |
def write_data_to_csv(data, path=pathlib.Path("data/_parameters/main.csv")):
"""
Opens `path` in append mode and write the data
"""
with path.open("a", newline="") as outfile:
csv_writer = csv.writer(outfile)
csv_writer.writerow(data) | 5,289,814 |
def app_initialized(parent=None):
"""Inicialization of Framework
Args:
parent (obj, optional): Parent object. Defaults to None.
"""
opfapi.CTX.app_framework = opfapi.FlameAppFramework()
print("{} initializing".format(
opfapi.CTX.app_framework.bundle_name))
load_apps() | 5,289,815 |
def records_accelerometer_to_file(filepath: str, records_accelerometer: kapture.RecordsAccelerometer) -> None:
"""
Writes accelerometer records to file
:param filepath: output file path.
:param records_accelerometer: records to save
"""
records_generic_to_file(filepath, records_accelerometer) | 5,289,816 |
def linear_ramp(t, t0=0.0, dt=1.0, y0=0.0, dy=1.0):
"""Linear Ramp Function
This function describes the linear transition between two constant values.
Parameter
---------
t : np.ndarray
Time variable
t0 : float
Start time of the ramp
dt : float
Transition length
... | 5,289,817 |
def add_flow_draft(client: SymphonyClient, name: str) -> FlowDraft:
"""This function add flow draft
:param name: Name of the flow draft
:type name: str
:raises:
* FailedOperationException: Internal symphony error
:return: FlowDraft object
:rtype: :class:`~psym.common.data_class.FlowDr... | 5,289,818 |
def hazard_ratio(y_true, x, model_coefs, threshold):
"""Hazard ratio can be interpreted as the chance of an event occurring
in the group A divided by the chance of the event occurring in the group B
Parameters
----------
y_true : pandas.DataFrame
DataFrame with annotation of samples. Two co... | 5,289,819 |
def main():
"""
train the model
:return:
"""
#---------------------------
# load image data and label
#---------------------------
img_array = np.load("../data/processed/image_array.npy")
code_array = np.load("../data/processed/code_array.npy")
name_array = np.load("../data/pro... | 5,289,820 |
def create_output_groups(group, dataset):
"""Create any intermediate groups necessary to write the specified dataset"""
# Split path into components, ignoring any of zero length
names = [n for n in dataset.split("/") if len(n) > 0]
# Create groups if necesary
while len(names) > 1:
if names... | 5,289,821 |
def test_copy_by_default_true():
"""should export correct data when "Copy By Default?" setting is true"""
results = yvs.get_result_list('mat 5.3')
nose.assert_equal(results[0]['variables']['copybydefault'], 'True')
nose.assert_equal(results[0]['subtitle'], 'Copy content to clipboard')
nose.assert_eq... | 5,289,822 |
def config_logger(args):
"""Configure the logger."""
handler = logging.StreamHandler()
if args.verbose and yes(args.verbose):
logger.setLevel('DEBUG')
handler.setLevel('DEBUG')
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s: %(message)s'
)
handl... | 5,289,823 |
def list_deployment_instances(deploymentId=None, nextToken=None, instanceStatusFilter=None, instanceTypeFilter=None):
"""
Lists the instance for a deployment associated with the IAM user or AWS account.
See also: AWS API Documentation
Exceptions
:example: response = client.list_deployment_... | 5,289,824 |
def check_par():
"""Return two intervals that give different results for parallel resistors.
>>> r1, r2 = check_par()
>>> x = par1(r1, r2)
>>> y = par2(r1, r2)
>>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y)
True
"""
r1 = interval(1, 1) # Replace this line!
... | 5,289,825 |
def ri2rr(data):
"""
Append imaginary data to end of real data, returning a real array.
"""
s = list(data.shape)
half = int(s[-1])
s[-1] = half * 2
n = np.empty(s, data.real.dtype)
n[..., :half] = data.real
n[..., half:] = data.imag
return n | 5,289,826 |
def init_project(project_id,
project_name=None,
project_description=None,
project_authors=None):
"""Initialize the necessary files specific to the web app."""
if not project_id and not isinstance(project_id, str) \
and len(project_id) >= 3:
... | 5,289,827 |
def create_certificate(path=None, text=False, csr=None, timeout=120, **kwargs):
"""
Create a certificate by asking the master to sign a certificate signing
request (CSR) or create a CSR on-the-fly.
path:
Path to write certificate to. Either ``path`` or ``text`` must be
specified.
t... | 5,289,828 |
def test_eq_2():
"""Test equality of two PhotoInfo objects when one has memoized property"""
photosdb1 = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
photosdb2 = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
photos1 = photosdb1.photos(uuid=[UUID_DICT["in_album"]])
photos2 = photosdb2.photos(uuid=[UUID_DICT["in_albu... | 5,289,829 |
def is_segmental(a_char: str) -> bool:
"""
Whether a character is one that is used in the
International Phonetic Alphabet to represent something
that is not a diacritic, and can stand on its own.
This means characters that can represent a
consonant or vowel.
"""
return elem_w(strict_segmentals)(a_char) | 5,289,830 |
async def test_brightness_controlling_scale(hass, mqtt_mock_entry_with_yaml_config):
"""Test the brightness controlling scale."""
with assert_setup_component(1, light.DOMAIN):
assert await async_setup_component(
hass,
light.DOMAIN,
{
light.DOMAIN: {
... | 5,289,831 |
def merge(arr1: Array, arr2: Array) -> Array:
"""
:param arr1, arr2: Two sorted arrays (descending order)
"""
if len(arr1) == 0: return arr2
if len(arr2) == 0: return arr1
resArr = Array(arr1.type)
it1, it2 = iter(arr1), iter(arr2)
tmp1, tmp2 = map(next, [it1, it2])
while True:
... | 5,289,832 |
def _get_storage_service(storage_service_id):
"""Return Storage Service with ID or None.
Unlike elsewhere in our application, here we do not fall back to
a different StorageService if the user-supplied ID is invalid to
prevent inaccurate information from being returned.
:param storage_service_id: ... | 5,289,833 |
def sign_tx(hw_session: HWSessionBase, rt_data: AppRuntimeData, utxos_to_spend: List[wallet_common.UtxoType],
tx_outputs: List[wallet_common.TxOutputType], tx_fee):
"""
Creates a signed transaction.
:param hw_session:
:param utxos_to_spend: list of utxos to send
:param tx_outputs: list o... | 5,289,834 |
def AddUpdateFlags(parser):
"""Add general arguments for `commitments update` flag."""
AddAutoRenew(parser) | 5,289,835 |
def format_error_and_line():
"""Return a brief description of the current exception as a string."""
exception_type, value, tb = sys.exc_info()
return format_error_and_line_from_info(exception_type, value, tb) | 5,289,836 |
def phases_from_complex(wts, continuous=False, do_detrend=False):
"""Calculates phases from 1d or 2d wavelet/hilbert arrays, dim0 is time"""
if len(wts.shape) == 1:
#1d
phasen = n.arctan2(wts.imag,wts.real)
if not (continuous or do_detrend):
return phasen
else:
... | 5,289,837 |
def create_shared_link(folder_id):
"""
Creates an Internet accessible shared link of folder given its identifier.
:param folder_id: Folder identifier.
:return: Shared link if the creation was successful, None otherwise.
"""
box_client = Client(JWTAuth.from_settings_file(BOX_CONFIG_FILE_PATH))
... | 5,289,838 |
def lstr(filepath: str) -> str:
"""Alias for lstring"""
return lstring(filepath) | 5,289,839 |
def ingest_proper_motions(db, sources, pm_ras, pm_ra_errs, pm_decs, pm_dec_errs, pm_references, save_db=False,
verbose=False):
"""
Parameters
----------
db
Database object
sources
list of source names
pm_ras
list of proper motions in right ascen... | 5,289,840 |
def movingaverage(inputs, pvalues, dbcur):
"""
inputs: #sensor0, #sensor1, #number
outputs : value
"""
n = inputs["#number"].getvalue()
v = inputs["#sensor1"].getvalue()
if pvalues is None or len(pvalues) == 0:
# first time
values = [v, deque([v] * n)]
else:
q =... | 5,289,841 |
def pjax(template_names, request, default="pjax_base.html"):
"""
Returns template name for request.
:param request: Django request or boolean value
:param template_names: Base theme name or comma-separated names of base and
pjax templates.
Examples::
{% extends "base.html"|pjax:requ... | 5,289,842 |
def opt(arg, help=None, type=None, abbrev=None, choices=None, metavar=None):
"""
Decorator for annotating optional arguments
"""
abbrev = abbrev or arg[0]
return functools.partial(
_annotate, arg, (help, 'option', abbrev, type, choices, metavar)) | 5,289,843 |
def wrap_scikit_classifier(scikit_class):
"""Wrap a sklearn classifier as a BaseNode subclass.
The wrapper maps these node methods to their sklearn equivalents:
- _stop_training -> fit
- _execute -> predict
"""
newaxis = numpy.newaxis
# create a wrapper class for a sklearn classifier
... | 5,289,844 |
def ConfiguredValueTaskAwaitable(*args, **kwargs): # real signature unknown
""" """
pass | 5,289,845 |
def get_arkouda_numlocales():
"""
Returns a default number of locales to use. 2 if Arkouda has multilocale
support, 1 otherwise. Can be overridden with ARKOUDA_NUMLOCALES.
:return: number of locales
:rtype: int
"""
if is_multilocale_arkouda():
return int(os.getenv('ARKOUDA_NUMLO... | 5,289,846 |
def for_each_client_jit(client_init: ClientInit, client_step: ClientStep,
client_final: ClientFinal) -> ForEachClient:
"""Creates a for each client function backed by `jax.jit`."""
client_init_jit = jax.jit(client_init)
client_step_jit = jax.jit(client_step)
client_final_jit = jax.jit(cl... | 5,289,847 |
def normalize_buffer(input_buffer):
"""Clear color from input_buffer and special characters.
:param str input_buffer: input buffer string from device
:return: str
"""
# \033[1;32;40m
# \033[ - Escape code
# 1 - style
# 32 - text color
# 40 - Background colour
color_pat... | 5,289,848 |
def make_header(ob_size):
"""Make the log header.
This needs to be done dynamically because the observations used as input
to the NN may differ.
"""
entries = []
entries.append("t")
for i in range(ob_size):
entries.append("ob{}".format(i))
for i in range(4):
entries.app... | 5,289,849 |
def reconstruct_3D(*arg):
"""
Reconstruct full size image from a cropped image
Parameters
----------
arg[0] : string
The path and image file name of the original image.
arg[1] : string
The path and image file name of the segmented image.
arg[2]: ndarray
Coordenates of th... | 5,289,850 |
def test_list_language_length_2_nistxml_sv_iv_list_language_length_3_2(mode, save_output, output_format):
"""
Type list/language is restricted by facet length with value 7.
"""
assert_bindings(
schema="nistData/list/language/Schema+Instance/NISTSchema-SV-IV-list-language-length-3.xsd",
i... | 5,289,851 |
def rowslice(table, *sliceargs):
"""
Choose a subsequence of data rows. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 5],
... ['d', 7],
... ['f', 42]]
... | 5,289,852 |
def evaluate_g8( mu, kappa, nu, sigma, s8 ):
"""
Evaluate the eighth constraint equation and also return the jacobian
:param float mu: The value of the modulus mu
:param float kappa: The value of the modulus kappa
:param float nu: The value of the modulus nu
:param float sigma: The value of the... | 5,289,853 |
def generateIdealisedFlatFieldSurface(numdata=2066, floor=1e5, xsize=2048, ysize=2066):
"""
"""
# generate random data
x = (np.random.random(numdata) - 0.5)
y = (np.random.random(numdata) - 0.5)
xx, yy = np.meshgrid(np.linspace(x.min(), x.max(), xsize), np.linspace(y.min(), y.max(), ysize))
... | 5,289,854 |
def listroot():
"""Return list of filenames contained in root directory."""
import os
return os.listdir('/') | 5,289,855 |
def normalize_company_id_length(business_id):
"""
Normalize given Company ID to 8-digits format.
Example:
========
>>> company_id = "27074358"
>>> normalize_company_id_length(company_id) == "27074358"
True
>>> company_id = "2707435"
>>> normalize_company_id_leng... | 5,289,856 |
def create_cnn_model() -> tf.keras.Model:
"""Returns a sequential keras CNN Model."""
return tf.keras.Sequential(
[
tf.keras.layers.Conv2D(
16,
8,
strides=2,
padding="same",
activation="relu",
inp... | 5,289,857 |
def calculateXYZByPCAMethod(df, clusterNumber=20, threshold=0.5):
"""
- copy given matrix
- remove all rows/columns where all values are below given
- apply spectral analysis for colouring --> colour
- apply PCA dimension reduction --> x,y,z
- add x,y,z and colour and return matrix
thresho... | 5,289,858 |
def task(
fn: Callable, **task_init_kwargs: Any
) -> "prefect.tasks.core.function.FunctionTask":
"""
A decorator for creating Tasks from functions.
Args:
- fn (Callable): the decorated function
- **task_init_kwargs (Any): keyword arguments that will be passed to the `Task`
c... | 5,289,859 |
def pre_save_handler(sender, instance, **kwargs):
"""
Intercept attempts to save and insert the current date and time into
creation and modification date fields.
"""
now = timezone.now()
if instance.id is None:
instance.creation_date = now
instance.modification_date = now | 5,289,860 |
def load_data(messages_filepath, categories_filepath):
"""
Load Messages data and Categories data, and merge then into unique dataframe.
Arguments:
messages_filepath -> Path to the CSV file containing messages
categories_filepath -> Path to the CSV file containing ca... | 5,289,861 |
def format_filename(s):
"""
Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``, `.` or `..`
... | 5,289,862 |
def three_spectrums():
"""Makes a plot showing three spectrums for a sinusoid.
"""
thinkplot.preplot(rows=1, cols=3)
pyplot.subplots_adjust(wspace=0.3, hspace=0.4,
right=0.95, left=0.1,
top=0.95, bottom=0.1)
xticks = range(0, 900, 200)
... | 5,289,863 |
def get_credentials() -> MySQLConnection:
"""
A helper function used to get the credentials for the server, simplifying
the process.
"""
# Try to get the credentials for the server.
credentials = []
try:
with open("sensitive/database_credentials", 'rt') as key:
for item i... | 5,289,864 |
def plot_max_cdv_data(stc_mft, lhmrinds, rhmrinds):
"""
Plot max CDV data.
Parameters
----------
stcdata: stc with ||cdv|| (point sequence as in fwdmag['source_rr'])
"""
print("##### Attempting to plot max. cdv data:")
fig = plt.figure()
stcdata = stc_mft.data
plt.plot(1e3 * stc_... | 5,289,865 |
def getGraphStructure(xml_file, graph_type="morphology"):
"""Traverse the given xml file as a tree by pre-order and return the graph structure as a parents list"""
def preorder(b, parent_idx=-1):
self_idx = len(parents)
parents.append(parent_idx)
if "body" not in b:
return
... | 5,289,866 |
def load_star(file_name: str) -> pd.DataFrame:
"""
Load a star file.
Arguments:
file_name - Path to the star file
Returns:
Pandas dataframe containing the star file
"""
header_names: typing.List[str]
import_names: typing.List[str]
skip_index: int
star_data: pd.DataFrame
... | 5,289,867 |
def approve_draft(request, draft_pk):
"""Approves current draft
:param request: mostly for user
:param draft_pk: Unique id for current draft
:return: DraftRegistrationApproval obj
"""
draft = get_draft_or_error(draft_pk)
user = request.user.osf_user
draft.approve(user)
return redire... | 5,289,868 |
def _check_perms(obj_name, obj_type, new_perms, cur_perms, access_mode, ret):
"""
Helper function used by ``check_perms`` for checking and setting Grant and
Deny permissions.
Args:
obj_name (str):
The name or full path to the object
obj_type (Optional[str]):
Th... | 5,289,869 |
def lidar4to3():
"""
convert the lidar points for Nx4 shape to Nx3 shape, i.e., remove the reflectivity.
:return:
"""
filename = path_in + file1
print("Processing: ", filename)
scan = np.fromfile(filename, dtype=np.float32)
print(np.shape(scan))
scan = scan.reshape((-1, 4))
scan ... | 5,289,870 |
def update_dvc_config(
path: Path,
config: Dict[str, Any],
workflow: Optional[str] = None,
verbose: bool = False,
silent: bool = False,
force: bool = False,
) -> bool:
"""Re-run the DVC commands in dry mode and update dvc.yaml file in the
project directory. The file is auto-generated bas... | 5,289,871 |
def IsRuntype_RealTrade():
"""运行模式: 是否实盘交易"""
run_type = Environment.get_instance().config.base.run_type
return run_type == RUN_TYPE.LIVE_TRADING | 5,289,872 |
def load_model(opts):
"""
Load models (here we refer to them as data) from load_path
"""
load_data = {}
load_datas = []
path = opts.load_path if opts.load_path is not None else []
if path is not None:
print(" [*] Loading data from {}".format(path))
load_data = torch_load_cpu... | 5,289,873 |
def run_prep_ffxml_main(tomlfile):
"""Main simulation loop."""
log.info(f"Preparing a run from '{tomlfile}'")
settings = toml.load(open(tomlfile, "r"))
log.debug(f"Loaded these settings. {settings}")
try:
format_vars: Dict[str, str] = settings["format_vars"]
except KeyError:
f... | 5,289,874 |
def hi_lo(data_series, current_max, current_min):
"""Determine the new highest and lowest value."""
try:
highest = numpy.max(data_series)
except:
highest = max(data_series)
if highest > current_max:
new_max = highest
else:
new_max = current_max
try:... | 5,289,875 |
def main(dataflow_tag, input_dir, db, transformations=False, blast="blastn"):
"""
:param dataflow_tag:
:param contigs_file:
:param db:
:return:
"""
dataflow_tag = dataflow_tag
df = Dataflow(dataflow_tag)
def create_schemas():
"""
This should only be executed if the ... | 5,289,876 |
def check_presence_download(filename: Path, backup_url):
"""Check if file is present otherwise download."""
if not filename.is_file():
from .readwrite import _download
_download(backup_url, filename) | 5,289,877 |
def load_index(in_file, index):
"""
Process hhk file
in_file: path to file
:type in_file: str
index:
:type index: dics(str, set(tuple(str, str)))
:raise: RuntimeError in case of processing error
"""
if not os.path.isfile(in_file):
raise RuntimeError("File... | 5,289,878 |
def do_list_wtps(gargs, args, leftovers):
""" List currently defined components. """
code, data = connect(gargs, ('GET', '/api/v1/wtps'))
if code[0] != 200:
print("%s %s" % code)
sys.exit()
for entry in data:
connection = ""
if 'connection' in entry and entry['connec... | 5,289,879 |
def ChangeBackslashToSlashInPatch(diff_text):
"""Formats file paths in the given patch text to Unix-style paths."""
if not diff_text:
return None
diff_lines = diff_text.split('\n')
for i in range(len(diff_lines)):
line = diff_lines[i]
if line.startswith('--- ') or line.startswith('+++ '):
diff... | 5,289,880 |
def test_vividlight():
"""Test vividlight."""
background = Image.open(THISDIR + "/background.png")
foreground = Image.open(THISDIR + "/foreground.png")
assert imgcompare.is_equal(
blendLayers(background, foreground, BlendType.VIVIDLIGHT),
THISDIR + "/vividlight_expected.png",
tolerance=1,
) | 5,289,881 |
def parse_line(text: str) -> str:
"""Parses one line into a word."""
text = text.rstrip()
if text[0] == "+":
return text[1:]
if text[0] == "@" or text[0] == "!" or text[0] == "$":
w = text.split("\t")[1]
if "#" in w:
return w.split("#")[0].rstrip()
else:
... | 5,289,882 |
def show_all_keypoints(image, predicted_key_pts, gt_pts=None):
"""Show image with predicted keypoints"""
plt.imshow(image)
plt.scatter(predicted_key_pts[:, 0], predicted_key_pts[:, 1], s=20, marker='.', c='m')
# plot ground truth points as green pts
if gt_pts is not None:
plt.scatter(gt_pts[... | 5,289,883 |
def map_gauss_coef_pares(
node_coef_pares: Tuple[float, float], seg_a: float, seg_b: float
) -> Sequence[Tuple[float, float]]:
"""
Linearly maps node_coef_pares on [seg_a, seg_b] to [-1, 1],
Given the pares of nodes and coefficient finds the approximate value of
an integral on [-1, 1] of function i... | 5,289,884 |
def test_md002_bad_proper_atx_heading_start_with_alternate_configuration():
"""
Test to make sure we get the expected behavior after scanning a good file from the
test/resources/rules/md002 directory that starts with a h1 atx heading. The modified
configuration will cause the file to be parsed with rep... | 5,289,885 |
def _logs_cleanup() -> None:
"""Stops all firmware log redirections"""
global _logs_dict
for log in _logs_dict.values():
log.stop() | 5,289,886 |
def reproject_blanksky(infile, outfile, evt2, asol, clobber=False):
"""
Reproject the background to match the coordinates of the observational
evt2 data.
"""
clobber = "yes" if clobber else "no"
logger.info("Reprojecting the background to match the evt2 file ...")
subprocess.check_call(["pun... | 5,289,887 |
def vpt(candles: np.ndarray, source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]:
"""
Volume Price Trend (VPT)
:param candles: np.ndarray
:param source_type: str - default: "close"
:param sequential: bool - default=False
:return: float | np.ndarray
"""
can... | 5,289,888 |
def get_shell_lc() -> str:
"""取得當前shell的語言代碼。
Returns:
str: 當前shell的語言代碼。
"""
loc = locale.getdefaultlocale()
lc = loc[0]
return lc | 5,289,889 |
def wilder_ma(series: nda.NdType, periods: int = 14, warm_periods: tp.Union[int, None] = None):
"""
Wilder's Moving Average
"""
if warm_periods is None:
warm_periods = periods
return ema(series, periods * 2 - 1, warm_periods) | 5,289,890 |
def dict_to_cidr(obj):
"""
Take an dict of a Network object and return a cidr-formatted string.
:param obj:
Dict of an Network object
"""
return '%s/%s' % (obj['network_address'], obj['prefix_length']) | 5,289,891 |
def replace_tuple(tuple_obj, replace_obj, replace_index):
"""Create a new tuple with a new object at index"""
if len(tuple_obj) - 1 <= replace_index:
return tuple_obj[:replace_index] + (replace_obj,)
else:
return tuple_obj[:replace_index] + (replace_obj,) + tuple_obj[replace_index+1:] | 5,289,892 |
def RegisterCLSIDsFromDict( dict ):
"""Register a dictionary of CLSID's and classes.
This module performs the same function as @RegisterCLSID@, but for
an entire dictionary of associations.
Typically called by makepy generated modules at import time.
"""
mapCLSIDToClass.update(dict) | 5,289,893 |
def add_validation(
self,
attribute_name,
validation_method_name,
validate_null = False,
properties = {},
contexts = ("default",),
**kwargs
):
"""
Adds a validation method to the attribute with the given name.
The adding of the validation can be configured using the pr... | 5,289,894 |
def validate(business: Business, annual_report: Dict) -> Error:
"""Validate the annual report JSON."""
if not business or not annual_report:
return Error(HTTPStatus.BAD_REQUEST, [{'error': _('A valid business and filing are required.')}])
err = validate_ar_year(business=business,
... | 5,289,895 |
def _timedelta_str_to_schedule_time(time_value: str) -> str:
"""Convert time string to schedule start/end time to hexadecimale.
Args:
data: time to convert. e.g. "21:00".
Return:
Hexadecimal representation of time_value argument.
Raises:
aioswitcher.erros.EncodingError: wh... | 5,289,896 |
def submit_WMS(job, infileList):
""" Submit the job locally or to the WMS
"""
dirac = Dirac()
job.setInputData(infileList)
job.setJobGroup('SimpleCtapipe-test')
res = dirac.submit(job)
Script.gLogger.notice('Submission Result: ', res)
return res | 5,289,897 |
def FindBinary( binary, user_options ):
"""Find the path to the Gocode/Godef binary.
If 'gocode_binary_path' or 'godef_binary_path'
in the options is blank, use the version installed
with YCM, if it exists.
If the 'gocode_binary_path' or 'godef_binary_path' is
specified, use it as an absolute path.
If ... | 5,289,898 |
def test_for_each_as_target_property_iterables(temp_factory):
"""Test for_each option of input"""
# test iterable
execute_workflow(
r"""
[0: shared={'res':'step_output'}]
import pandas as pd
data = pd.DataFrame([(0, 1, 'Ha'), (1, 2, 'Hello'), (2, 4, 'World')], columns=['A', '... | 5,289,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.