content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def envi_header(inputpath):
"""
Convert a envi binary/header path to a header, handling extensions
Args:
inputpath: path to envi binary file
Returns:
str: the header file associated with the input reference.
"""
if os.path.splitext(inputpath)[-1] == '.img' or os.path.splitext(in... | 5,356,700 |
def parse_fernet_timestamp(ciphertext):
"""
Returns timestamp embedded in Fernet-encrypted ciphertext, converted to Python datetime object.
Decryption should be attempted before using this function, as that does cryptographically strong tests on the
validity of the ciphertext.
"""
try:
... | 5,356,701 |
def tagcloud(guids):
"""Get "tag cloud" for the search specified by guids
Same return format as taglist, impl is always False.
"""
guids = set(guids)
range = (0, 19 + len(guids))
tags = request.client.find_tags("EI", "", range=range, guids=guids, order="-post", flags="-datatag")
return [(tagfmt(t.name), t, False... | 5,356,702 |
def _ValidateContent(path, expected_content):
"""Helper to validate the given file's content."""
assert os.path.isfile(path), 'File didn\'t exist: %r' % path
name = os.path.basename(path)
current_content = open(path).read()
if current_content == expected_content:
print '%s is good.' % name
else:
try... | 5,356,703 |
def _test_image_path():
"""
A 100 x 50 pixel GeoTIFF image, with 0 as NODATA value
"""
return os.path.join(path, "test.tiff") | 5,356,704 |
def api_ofrecord_image_decoder_random_crop(
input_blob: remote_blob_util.BlobDef,
blob_name: str,
color_space: str = "BGR",
num_attempts: int = 10,
seed: Optional[int] = None,
random_area: Sequence[float] = [0.08, 1.0],
random_aspect_ratio: Sequence[float] = [0.75, 1.333333],
name: str =... | 5,356,705 |
def student_add_information(adding_student_id, student_information):
"""
用于添加学生的详细信息
:@param adding_student_id: int
:@param student_information: dict or str
:@return : 运行状态(True or False)
"""
if type(student_information) == dict:
adding_information = student_information
... | 5,356,706 |
def import_file_as_module(filename: str, name: Optional[str] = None) -> ModuleType:
"""
NOTE(2020-11-09|domanchi): We're essentially executing arbitrary code here, so some thoughts
should be recorded as to the security of this feature. This should not add any additional
security risk, given the followin... | 5,356,707 |
def test_to_graph_should_return_publisher_as_bnode_with_catalog() -> None:
"""It returns a name graph isomorphic to spec."""
catalog = Catalog()
catalog.identifier = "http://example.com/catalogs/1"
agent = Agent()
agent.name = {"en": "James Bond", "nb": "Djeims Bånd"}
catalog.publisher = agent
... | 5,356,708 |
async def get_show_by_month_day(month: conint(ge=1, le=12), day: conint(ge=1, le=31)):
"""Retrieve a Show object, based on month and day, containing: Show
ID, date and basic information."""
try:
show = Show(database_connection=_database_connection)
shows = show.retrieve_by_month_day(month, d... | 5,356,709 |
def generate_random_tag(length):
"""Generate a random alphanumeric tag of specified length.
Parameters
----------
length : int
The length of the tag, in characters
Returns
-------
str
An alphanumeric tag of specified length.
Notes
-----
The generated tag will... | 5,356,710 |
def test_drug_likeness_input(mocker: MockFixture, tmp_path: Path) -> None:
"""Check that the yaml input for drug likeness is correct."""
path_input = PATH_TEST / "input_test_druglikeness.yml"
mocker.patch("argparse.ArgumentParser.parse_args", return_value=argparse.Namespace(
i=path_input))
mock... | 5,356,711 |
def test_generate():
"""
GIVEN artifacts and name
WHEN generate is called with the artifacts and name
THEN the model source code is returned.
"""
artifacts = schemas_artifacts.types.ModelArtifacts(
tablename="table 1",
inherits=None,
parent=None,
description=None,... | 5,356,712 |
def blendShapeEditor(*args, **kwargs):
"""
This command creates an editor that derives from the base editor class that has controls for blendShape, control nodes.
Flags:
- control : ctl (bool) [query]
Query only. Returns the top level control for this editor. U... | 5,356,713 |
def loadmat(filename, check_arrays=False, **kwargs):
"""
Big thanks to mergen on stackexchange for this:
http://stackoverflow.com/a/8832212
This function should be called instead of direct scipy.io.loadmat
as it cures the problem of not properly recovering python dictionaries
from mat files... | 5,356,714 |
def _export_output_to_tensors(export_output):
"""Get a list of `Tensors` used in `export_output`.
Args:
export_output: an `ExportOutput` object such as `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
Returns:
a list of tensors used in export_output.
Raises:
ValueError: ... | 5,356,715 |
def train_city_s1(city:str, pollutant= 'PM2.5', n_jobs=-2, default_meta=False,
search_wind_damp=False, choose_cat_hour=False, choose_cat_month=True,
add_weight=True, instr='MODIS', op_fire_zone=False, op_fire_twice=False, op_lag=True, search_tpot=False,
main_data_folder: str = '../data/',
... | 5,356,716 |
def mask(
ctx,
files,
output,
geojson_mask,
driver,
all_touched,
crop,
invert,
creation_options):
"""Masks in raster using GeoJSON features (masks out all areas not covered
by features), and optionally crops the output raster to the extent... | 5,356,717 |
def some_more_cut_paste(possible_timelines, edge_nout_hash, cut_nout_hash, paste_point_hash):
"""
interpretation of cut_nout_hash is purely driven by how this is used in practice... do I like it? Not sure yet.
the interpretation is:
cut_nout_hash is the first thing that's _not_ included.
"""
t... | 5,356,718 |
def constructCbsdGrantInfo(reg_request, grant_request, is_managing_sas=True):
"""Constructs a |CbsdGrantInfo| tuple from the given data."""
lat_cbsd = reg_request['installationParam']['latitude']
lon_cbsd = reg_request['installationParam']['longitude']
height_cbsd = reg_request['installationParam']['height']
... | 5,356,719 |
def download_raw_pages_content(pages_count):
"""download habr pages by page count"""
return [fetch_raw_content(page) for page in range(1, pages_count + 1)] | 5,356,720 |
def tseries2bpoframe(s: pd.Series, freq: str = "MS", prefix: str = "") -> pd.DataFrame:
"""
Aggregate timeseries with varying values to a dataframe with base, peak and offpeak
timeseries, grouped by provided time interval.
Parameters
----------
s : Series
Timeseries with hourly or quart... | 5,356,721 |
def calc_buffered_bounds(
format, bounds, meters_per_pixel_dim, layer_name, geometry_type,
buffer_cfg):
"""
Calculate the buffered bounds per format per layer based on config.
"""
if not buffer_cfg:
return bounds
format_buffer_cfg = buffer_cfg.get(format.extension)
if f... | 5,356,722 |
async def read_users_me(
current_user: models.User = Depends(security.get_current_active_user),
):
"""Get User data"""
return current_user | 5,356,723 |
def base_orbit(SLC1_par, SLC2_par, baseline, logpath=None, outdir=None, shellscript=None):
"""
| Estimate baseline from orbit state vectors
| Copyright 2015, Gamma Remote Sensing, v4.2 clw 18-Apr-2018
Parameters
----------
SLC1_par:
(input) SLC-1 ISP image parameter file
SLC2_par:
... | 5,356,724 |
def cal_energy_parameters_for_one_channel(sub_sample_label_dict, channel, importance=1):
"""
the loss comes equally from four sources: connected component (0D), boundary (1D), area (2D), and rim_enhance
e.g. a small region with long boundaries means it accounts for lots of 1D loss and little of 2D loss.
... | 5,356,725 |
def get_logger(logfile):
"""Instantiate a simple logger.
"""
import logging
from contextlib import redirect_stdout
fmt = "%(levelname)s:%(filename)s:%(lineno)s:%(funcName)s: %(message)s"
#fmt = '%(levelname)s:%(filename)s:%(lineno)s:%(funcName)s:%(asctime)s: %(message)s']
datefmt = '%Y-%m-... | 5,356,726 |
def __to_signed(val, bits):
"""
internal function to convert a unsigned integer to signed
of given bits length
"""
logging.debug(" in: value = %d", val)
mask = 0x00
for i in range(int(bits / 8)):
mask |= 0xff << (i * 8)
if val >= (1 << (bits - 1)):
val = -1 - (val ^ m... | 5,356,727 |
def set_edges_connected_nodes(nodes, edges):
"""
Fill the lists of incoming and outgoing edges of the input nodes
(lists are attributes of Node objects).
The connection between nodes and edges is given by the start node and
end node of each edge.
:param nodes: list of all the... | 5,356,728 |
def compute_qp_objective(
configuration: Configuration, tasks: Iterable[Task], damping: float
) -> Tuple[np.ndarray, np.ndarray]:
"""
Compute the Hessian matrix :math:`H` and linear vector :math:`c` of the
QP objective function:
.. math::
\\frac{1}{2} \\Delta q^T H \\Delta q + c^T q
T... | 5,356,729 |
def main():
""" An example shows infernece of one model on multiple TPUs.
"""
signal.signal(signal.SIGINT, signal_handle)
# init Engine to load bmodel and allocate input and output tensors
# one engine for one TPU
engines = list()
thread_num = len(ARGS.tpu_id)
for i in range(thread_num):
engines.ap... | 5,356,730 |
def showPhaseSpectrum(ax, freq, phi, ylabel=r'$-\phi$ (mrad)',
grid=True, marker='+', ylog=False, **kwargs):
"""Show phase spectrum (-phi as a function of f)."""
if 'label' not in kwargs:
kwargs['label'] = 'obs'
ax.semilogx(freq, phi, marker=marker, **kwargs)
if ylog:
... | 5,356,731 |
def _is_existing_account(respondent_email):
"""
Checks if the respondent already exists against the email address provided
:param respondent_email: email of the respondent
:type respondent_email: str
:return: returns true if account already registered
:rtype: bool
"""
respondent = party_... | 5,356,732 |
def clean_darknet(
darknet_dir: str,
images_dir: str,
label_replacements: Dict,
label_removals: List[str] = None,
label_keep: List[str] = None,
problems_dir: str = None,
):
"""
TODO
:param darknet_dir:
:param images_dir:
:param label_replacements:
... | 5,356,733 |
def basic_checks(server,port):
"""Perform basics checks on given host"""
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 2 seconds timeout
sock.settimeout(2)
return sock.connect_ex((server,int(port))) == 0 | 5,356,734 |
def test_input_unmodified_with_nan(boundary, nan_treatment,
normalize_kernel, preserve_nan, dtype):
"""
Test that convolve_fft doesn't modify the input data
"""
array = [1., 4., 5., np.nan, 5., 7., 8.]
kernel = [0.2, 0.6, 0.2]
x = np.array(array, dtype=dtype)
... | 5,356,735 |
def test(ipu_estimator, args, x_test, y_test):
"""
Test the model on IPU by loading weights from the final checkpoint in the
given `args.model_dir`.
"""
def input_fn():
dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))
dataset = dataset.prefetch(len(x_test)).cache()
... | 5,356,736 |
def _get_service():
"""Gets service instance to start API searches.
Returns:
A Google API Service used to send requests.
"""
# Create the AI Platform service object.
# To authenticate set the environment variable
# GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
return g... | 5,356,737 |
def giq(scores, targets, I, ordered, cumsum, penalties, randomized, allow_zero_sets):
"""
Generalized inverse quantile conformity score function.
E from equation (7) in Romano, Sesia, Candes. Find the minimum tau in [0, 1] such that the correct label enters.
"""
E = -np.ones((scores.shape[0],))
... | 5,356,738 |
def setup_logging(forceDebug=False):
"""
General function to setup logger.
Everything from debug to stdout message is handle by loggers.
stdout logger handle info and warning message to STDOUT
stderr logger handle error and critical message to stderr
anything else is for debug logger which log e... | 5,356,739 |
def findUser(userId):
"""
:param userId:
:return: The user obj
Finds a particular user from a dataset.
"""
return user_collection.find_one({"user_id": userId}) | 5,356,740 |
def sub_sample_map(data, aug_map, n_input, n_output, n_teach, buffer):
"""
Expands an augmentation map to produce indexes that will allow
targets values of previous outputs to be used as inputs
"""
n_io = n_input + n_output
n_req = n_io
teach_range = range(n_teach)
tf_map = []
for ... | 5,356,741 |
def preprocess_agents_history(agents, new_data, filename):
"""Process new data into existing data object
:param agents: Existing data object
:type agents: dictionary
:param new_data: New json that needs to be applied on existing data
:type new_data: dictionary
:param filename: original filena... | 5,356,742 |
def capture_flow(pkt_hist):
"""
Monitors the flow in the file.
:param pkt_hist: a list of raw eth packets
:return: 0 (No errors)
"""
closedby = []
global numFlows, flow_buffer, sent_buffer, ackd_buffer, received_buffer, retransmissions, end_ts, retransmissions_timeout, retransmissions_fast
... | 5,356,743 |
def run_customcheck_command(check):
"""Function that starts as a thread (future) to process a custom check command
Process a custom check command until a given timeout.
The result will be added to the cached_customchecks_check_data object.
process_customcheck_results() takes care of a may dyin... | 5,356,744 |
def rcGetBBModelEnum():
""" Get the BeagleBone model as member of the BBModel Enum. """
return BBModel(rcGetBBModel()) | 5,356,745 |
def verify_table_html(*, expected_html, query=None, find=None, table, **kwargs):
"""
Verify that the table renders to the expected markup, modulo formatting
"""
from bs4 import BeautifulSoup
if find is None:
find = dict(class_='table')
if not expected_html.strip():
expect... | 5,356,746 |
def rapsearch_alignment(alignment_file, uniref, unaligned_reads_file_fasta):
"""
Run rapsearch alignment on database formatted for rapsearch
"""
bypass = utilities.check_outfiles([alignment_file])
exe = "rapsearch"
opts = config.rapsearch_opts
args = ["-q", unaligned_reads_file_fasta, "-b... | 5,356,747 |
def ordToString(ordList):
"""Use this function to convert ord values to strings."""
newStrList = []
cstr = ""
for cint in ordList:
cstr += chr(cint)
if cint == 44:
newStrList.append(cstr[:-1])
cstr = ""
return newStrList | 5,356,748 |
def remove_element(collection: str, e_id: int):
"""
Remove an element from the database.
:param collection: Collection name
:param e_id: Element id.
:raise DatabaseError: If the element is not in the collection.
"""
if _collections[collection].count_documents({"_id": e_id}) != 0:
_c... | 5,356,749 |
def get_test_data_for_successful_build():
"""Returns a test data set of test suites and cases that passed.
"""
return _get_test_data(["PASSED", "PASSED", "PASSED"]) | 5,356,750 |
def get_commits(db_session, gh_session, repos):
"""
given a list of Repo row object get all associated commits and file changes (on the default branch) for each repo.
:param db_session: the database session
:type db_session: sqlalchemy.orm.session.Session
:param gh_session: the requests session wit... | 5,356,751 |
async def TwitterRetweetAPI(
current_user: User = Depends(User.getCurrentUser),
):
"""
API 実装中…(モックアップ)
""" | 5,356,752 |
def fromOldAdjacencyList(adjlist, group=False, saturateH=False):
"""
Convert a pre-June-2014 string adjacency list `adjlist` into a set of :class:`Atom` and
:class:`Bond` objects.
It can read both "old style" that existed for years, an the "intermediate style" that
existed for a few months in 2014,... | 5,356,753 |
def read_arg_optional(
src, args, n_optional=-1, tolerance=0, mode=MODE_NON_MATH, skip_math=False):
"""Read next optional argument from buffer.
If the command has remaining optional arguments, look for:
a. A spacer. Skip the spacer if it exists.
b. A bracket delimiter. If the optional ar... | 5,356,754 |
def searcheduxapian_ajax_get_schlagwort(request, item_container):
""" moegliche Schlagworte """
schlagworte = get_schlagworte(request.GET['query'])
res = '<items>\n'
for schlagwort in schlagworte:
res += '<schlagwort>\n<name><![CDATA[%s]]></name>\n</schlagwort>\n' % schlagwort.name
res += '</items>\n'
r... | 5,356,755 |
async def answer(pc, signaling):
"""
Connect to server and receive tracks by sending an answer after awaiting an offer
"""
@pc.on("track")
def on_track(track):
print("Receiving %s" % track.kind)
if track.kind == "video":
pc.addTrack(BallTransformTrack(track))
await ... | 5,356,756 |
def expanded_X_y_sample_weights(X, y_proba, expand_factor=10,
sample_weight=None, shuffle=True,
random_state=None):
"""
scikit-learn can't optimize cross-entropy directly if target
probability values are not indicator vectors.
As a workarou... | 5,356,757 |
def refine_uniformly(dom, seg):
"""
Refine all edges of the given domain and segmentation.
:param dom: Domain to refine
:type dom: :class:`viennagrid.Domain`
:param seg: Segmentation of the domain to refine
:type seg: :class:`viennagrid.Segmentation`
:returns: A two-element tuple containing the output domain... | 5,356,758 |
def add_losses_to_graph(loss_fn, inputs, outputs, configuration, is_chief=False, verbose=0):
"""Add losses to graph collections.
Args:
loss_fn: Loss function. Should have signature f: (dict, dict, is_chief, **kwargs) -> tuple of losses and names
inputs: inputs dictionary
outputs: ou... | 5,356,759 |
def rename_tuning(name, new_name):
"""rename tuning"""
session = tables.get_session()
if session is None:
return False, 'connect'
try:
tuning_table = TuningTable()
if not tuning_table.check_exist_by_name(TuningTable, name, session):
return False, 'tuning not exist'
... | 5,356,760 |
async def get_event(token: str, event_id: str) -> dict:
"""Get event - return new if no event found."""
event = {"id": event_id, "name": "Nytt arrangement", "organiser": "Ikke valgt"}
if event_id != "":
logging.debug(f"get_event {event_id}")
event = await EventsAdapter().get_event(token, eve... | 5,356,761 |
def _xfsdump_output(data):
"""
Parse CLI output of the xfsdump utility.
"""
out = {}
summary = []
summary_block = False
for line in [l.strip() for l in data.split("\n") if l.strip()]:
line = re.sub("^xfsdump: ", "", line)
if line.startswith("session id:"):
out["S... | 5,356,762 |
def get_current():
"""Return the currently running interpreter."""
id = _interpreters.get_current()
return Interpreter(id) | 5,356,763 |
def opf():
"""One-piece-flow model
""" | 5,356,764 |
def csstext(text: str, cls: str, span: bool=False, header: bool=False) -> str:
"""
Custom build HTML text element.
"""
if span:
tag = 'span'
elif header:
tag = 'h1'
else:
tag = 'p'
return f'<{tag} class="{cls}">{str(text)}</{tag}>' | 5,356,765 |
def trans_exam_list_to_colum(example_list, headers=None):
"""
将example列表转换成以列表示的形式,用于适配输出附加信息
:param example_list: example 列表
:param headers: 需要的属性,默认为("question", "answer", "yes_or_no")
:return: {header1:[...],header2:[...],...}
"""
if headers is None:
headers = ("question", "answer... | 5,356,766 |
def member():
""" RESTful CRUD Controller """
return s3_rest_controller() | 5,356,767 |
def _now():
"""Get EST localized now datetime."""
return EST_TIMEZONE.localize(datetime.datetime.now()) | 5,356,768 |
def pydantic_model_to_pandas(pydantic_model_input) -> pd.DataFrame:
"""
Function that transforms <pydantic.BaseModel> child objects to
<pandas.DataFrame> objects
:param pydantic_model_input: Input validator for API
"""
return dict_to_pandas(pydantic_model_input.dict()) | 5,356,769 |
def assign_student_to_project(student: dict, project: dict, score: int):
"""
Assigns a student to a project
"""
projects_table = Airtable(SMT_BASE_ID, PROJECTS_TABLE, api_key=os.environ["AIRTABLE_API_KEY"])
project_id = project["id"]
project_name = project["fields"]["Name"]
current_project_... | 5,356,770 |
def main():
"""
User enter a number, and this program will compute Hailstone sequences.
Hailstone Sequences follow rules:
If a number is odd, multiply it by 3 and add 1.
If a number is even, divide it by 2
pre-condition: Waiting user to input a number.
post-condition: Show user how many the ... | 5,356,771 |
def calculate_pair_energy(coordinates, i_particle, box_length, cutoff):
"""
Calculate the interaction energy of a particle with its environment (all other particles in the system) - rewrite
Parameters
----------
coordinates : list
The coordinates for all particles in the system
... | 5,356,772 |
def cloud_optimize_inPlace(in_file:str) -> None:
"""Takes path to input and output file location. Reads tif at input location and writes cloud-optimized geotiff of same data to output location."""
## add overviews to file
cloudOpArgs = ["gdaladdo",in_file,"-quiet"]
subprocess.call(cloudOpArgs)
## copy file
inter... | 5,356,773 |
def debug_time_step(t, epidx, obs, act, extras, goal=None):
"""Save images and other stuff from time `t` in episode `epidx`."""
pth = 'tmp'
tt = str(t).zfill(2)
# Convert from BGR to RGB to match what we see in the GUI.
def save(fname, c_img):
cv2.imwrite(fname, img=cv2.cvtColor(c_img, cv2.... | 5,356,774 |
def simulation_activation(model, parcel_df, aerosols_panel):
""" Given the DataFrame output from a parcel model simulation, compute
activation kinetic limitation diagnostics.
Parameters
----------
model : ParcelModel
The ParcelModel
parcel_df : DataFrame used to generate the results to ... | 5,356,775 |
def run():
"""
Convolutional NN Text
Activation function: relu
Optimizer: AdamOptimizer
:return:
"""
# ----- Data -------
percent_test = 0.1
print("Loading data...")
positive_data_file = "data/rt-polaritydata/rt-polarity.pos"
negative_data_file = "data/rt-polaritydata/rt-pol... | 5,356,776 |
def create(options, args):
"""
Instantiate and return a Blueprint object from either standard input or by
reverse-engineering the system.
"""
try:
with context_managers.mkdtemp():
if not os.isatty(sys.stdin.fileno()):
try:
b = blueprint.Bluepr... | 5,356,777 |
def test_excel_with_empty_columns(sdc_builder, sdc_executor):
"""Test if some records had empty value for a column, it don't ignore the column and keep the same schema and
write it in avro file. Test empty values in the first, medium and last column and get it as a null.
directory >> schema_generator >> lo... | 5,356,778 |
def create_config(
case=None, Exp='Dummy', Type='Tor',
Lim=None, Bump_posextent=[np.pi/4., np.pi/4],
R=None, r=None, elong=None, Dshape=None,
divlow=None, divup=None, nP=None,
returnas=None, strict=None,
SavePath='./', path=_path_testcases,
):
""" Create easily a tofu.geom.Config object
... | 5,356,779 |
def is_project_description(description):
"""Validates the specified project description.
A valid description is simply a non-empty string.
Args:
description (str): A project description to validate.
Returns:
<bool, str|None>: A pair containing the value True if the specified descripti... | 5,356,780 |
def update_pretrained_cfg_and_kwargs(pretrained_cfg, kwargs, kwargs_filter):
""" Update the default_cfg and kwargs before passing to model
Args:
pretrained_cfg: input pretrained cfg (updated in-place)
kwargs: keyword args passed to model build fn (updated in-place)
kwargs_filter: keywor... | 5,356,781 |
def _float_incr(key, incr):
"""
Increments a redis (float) key value by a given float.
The float may be negaitve to achieve decrements.
"""
"""
Currently, this is a very bad implementation, as we are unable to
get a value inside the atomic operation.
"""
value = actor.get(key)
with actor.pipeline(transactio... | 5,356,782 |
def remove_friend():
"""
Accepts an existing friend request.
"""
data = json.loads(request.data)
friend_id = data['id']
user = interface.get_user_by_id(get_jwt_identity())
friend = interface.get_user_by_id(friend_id)
interface.remove_friendship(user, friend)
return '', 200 | 5,356,783 |
def color_col_labels(month, ax):
"""Color the column labels for the given month image."""
for col, cell in enumerate(month.header_row):
if month.col_labels[col]:
top_left, width, height = cell.get_patch()
ax.add_patch(patches.Rectangle(
top_left,
w... | 5,356,784 |
def ensure_configured(func):
"""Modify a function to call ``basicConfig`` first if no handlers exist."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(logging.root.handlers) == 0:
basicConfig()
return func(*args, **kwargs)
return wrapper | 5,356,785 |
def describe_asset_model(assetModelId=None):
"""
Retrieves information about an asset model.
See also: AWS API Documentation
Exceptions
:example: response = client.describe_asset_model(
assetModelId='string'
)
:type assetModelId: string
:param assetModelId: [R... | 5,356,786 |
def get_loss(dataset_properties: Dict[str, Any], name: Optional[str] = None) -> Type[Loss]:
"""
Utility function to get losses for the given dataset properties.
If name is mentioned, checks if the loss is compatible with
the dataset properties and returns the specific loss
Args:
dataset_prop... | 5,356,787 |
def ten_to_base(value : int, base):
"""Converts a given decimal value into the specified base.
:param value: The number to convert
:param base: The base to convert the specified number to
:return: The converted value in the specified base
"""
# Check if the base is 10, return the value
if... | 5,356,788 |
def c_exit(exitcode=0):
"""Induces a libc exit with exitcode 0"""
libc.exit(exitcode) | 5,356,789 |
def freeze_all(policies_per_player):
"""Freezes all policies within policy_per_player.
Args:
policies_per_player: List of list of number of policies.
"""
for policies in policies_per_player:
for pol in policies:
pol.freeze() | 5,356,790 |
def download_acs_data(
url: str,
download_path: Union[str, Path] = "../data/raw/",
extract: bool = True,
extract_path: Union[str, Path] = "../data/interim/",
) -> None:
"""
Downloads ACS 1-, 3-, or 5- estimates from a US Census Bureau's FTP-server URL.
"""
# Checks download_path and ext... | 5,356,791 |
def get_style(selector, name):
"""
Returns the resolved CSS style for the given property name.
:param selector:
:param name:
"""
if not get_instance():
raise Exception("You need to start a browser first with open_browser()")
return get_style_g(get_instance(), selector, name) | 5,356,792 |
def argmod(*args):
"""
Decorator that intercepts and modifies function arguments.
Args:
from_param (str|list): A parameter or list of possible parameters that
should be modified using `modifier_func`. Passing a list of
possible parameters is useful when a function's paramete... | 5,356,793 |
def arrayGenerator(generator, length=10):
"""
Creates a generator that returns an an array of values taken from the
supplied generator.
"""
while True:
yield list(itertools.islice(generator, length)) | 5,356,794 |
def group_update(group_id, group_min, group_max, desired):
"""
Test with invalid input
>>> group_update('foo', 2, 1, 4)
{}
"""
if group_min > group_max or desired < group_min or desired > group_max:
return {}
try:
client = boto3.client('autoscaling')
response = clien... | 5,356,795 |
def remove_bookmark(request, id):
"""
This view deletes a bookmark.
If requested via ajax it also returns the add bookmark form to replace the
drop bookmark form.
"""
bookmark = get_object_or_404(Bookmark, id=id, user=request.user)
if request.method == "POST":
bookmark.delete()
... | 5,356,796 |
def parse_propa(blob):
"""Creates new blob entries for the given blob keys"""
if "track_in" in blob.keys():
muon = blob["track_in"]
blob["Muon"] = Table(
{
"id": np.array(muon)[:, 0].astype(int),
"pos_x": np.array(muon)[:, 1],
"pos_y... | 5,356,797 |
def compose_nautobot(context):
"""Create Netbox instance for Travis testing.
Args:
context (obj): Used to run specific commands
var_envs (dict): Environment variables to pass to the command runner
netbox_docker_ver (str): Version of Netbox docker to use
"""
# Copy the file from ... | 5,356,798 |
def fetch_incidents():
"""
Retrieve new incidents periodically based on pre-defined instance parameters
"""
now = convert_date_to_unix(datetime.utcnow())
last_run_object = demisto.getLastRun()
if last_run_object and last_run_object.get('time'):
last_run = last_run_object.get('time')
... | 5,356,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.