content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_rule_full_description(tool_name, rule_id, test_name, issue_dict):
"""
Constructs a full description for the rule
:param tool_name:
:param rule_id:
:param test_name:
:param issue_dict:
:return:
"""
issue_text = issue_dict.get("issue_text", "")
# Extract just the first lin... | 5,309,200 |
def generate_config(context):
""" Entry point for the deployment resources. """
resources, outputs = create_dashboard_resource(context)
return {"resources": resources, "outputs": outputs} | 5,309,201 |
def index_embedding_words(embedding_file):
"""Put all the words in embedding_file into a set."""
words = set()
with open(embedding_file) as f:
for line in tqdm(f, total=count_file_lines(embedding_file)):
w = Vocabulary.normalize(line.rstrip().split(' ')[0])
words.add(w)
... | 5,309,202 |
def test_alias_json(session):
"""Assert the json format of alias."""
identifier = 'CP1234567'
business = factory_business(identifier)
alias = Alias(
alias='ABC Ltd.',
type='TRANSLATION',
business_id=business.id
)
alias.save()
alias_json = {
'id': str(alias.id)... | 5,309,203 |
def dst():
"""Simple spatial graph nodes where all but one have been translated"""
dst = np.array([[0,0],
[1,0.1],
[0,1.1],
[1,1.1]])
return dst | 5,309,204 |
def recursive_prefix(addr):
"""
Recursively prefix a function tree with a user defined string.
"""
func_addr = idaapi.get_name_ea(idaapi.BADADDR, idaapi.get_func_name(addr))
if func_addr == idaapi.BADADDR:
idaapi.msg("Prefix: 0x%08X does not belong to a defined function\n" % addr)
re... | 5,309,205 |
def check_length(seed, random, query_words, key_max):
"""
Google limits searches to 32 words, so we need to make sure we won't be generating anything longer
Need to consider
- number of words in seed
- number of words in random phrase
- number of words in the lists from the query
Will raise ... | 5,309,206 |
def warp_from_camera_motion(R0, t0, R1, t1, normal, distance, K1, K0_inv=None):
"""
R0, t0: source camera pose in object frame.
R1, t1: target camera pose in object frame.
normal, distance: normal and distance of object's principal plane (in object frame.)
K1: target camera's intrinsics
K0_... | 5,309,207 |
def mcar_test(df, significance_level=0.05):
"""
Function for performing Little's chi-square test (1988) for the assumption (null hypothesis) of
missing completely at random (MCAR). Data should be multivariate and quantitative, categorical
variables do not work. The null hypothesis is equivalent to sayin... | 5,309,208 |
def init_pyboof(java_port:int=25333, python_port:int=25334, size_mb:int=2):
"""
Initializes PyBoof by connecting a Java Virtual Machine (JVM) using Py4J and if requested, will create a
memory mapped file to enabled much faster file transfers of larger objects.
If you wish to run multiple independent pr... | 5,309,209 |
def test_habitat():
"""
Test Habitat class
"""
hab = habbing.Habitat(temp=True)
assert hab.name == "test"
hab.db.close(clear=True)
hab.ks.close(clear=True)
"""End Test""" | 5,309,210 |
def test_cli_extract_command_usage():
"""Tests ralph extract command usage."""
runner = CliRunner()
result = runner.invoke(cli, ["extract", "--help"])
assert result.exit_code == 0
assert (
"Options:\n"
" -p, --parser [gelf] Container format parser used to extract events\n"
... | 5,309,211 |
def sind(x):
"""Trigonometric sine using :func:`np.sin <numpy.sin>`, element-wise with an input in degree.
Parameters
----------
x : array_like
Input array in degree.
Returns
-------
y : array_like
The corresponding tangent values. This is a scalar if x is a scalar.
""... | 5,309,212 |
def _stretch_intensity(image, smoothing_sigma=2.0):
"""Stretches the intensity range of the image to (0, 255)."""
output = image * 1
blurred = (gaussian(output, sigma=smoothing_sigma) * 255).astype('uint8')
i_max = blurred.max()
i_min = blurred.min()
logging.info('Stretching image intensity: m... | 5,309,213 |
def create_model(model_name, label, visibility, workspace, description):
"""Create a new registeredmodel entry.
"""
public_within_org = visibility == "org"
client = Client()
model = client.create_registered_model(model_name, workspace=workspace, public_within_org=public_within_org,
... | 5,309,214 |
def is_string(val):
"""
Is the supplied value a string or unicode string?
See: https://stackoverflow.com/a/33699705/324122
"""
return isinstance(val, (str, u"".__class__)) | 5,309,215 |
def inner_join(table_left, table_right, column):
"""
Inner join. If columns are repeated, the left table has preference.
:param table_left:
:param table_right:
:param column:
:return:
"""
if column not in table_left.keys:
raise ValueError('{} not in left table'.format(column))
... | 5,309,216 |
def drawGameState(screen, gs):
""" Draw board and draw pieces so that we can
draw pieces and board seperately. """
drawBoard(screen)
drawPieces(screen, gs.board) | 5,309,217 |
def time_string():
"""
Generate a string of numbers generated from now time (UTC).
"""
# UTC time up to microseconds
time_str = datetime.utcnow().strftime("%Y%m%d%H%M%S")
return time_str | 5,309,218 |
def colorvsn1(studydata, column, context):
"""Please convert numeric codes of 0 and 99 to the text strings they represent."""
return column.mask(column == 0, 'No').mask(column > 90, "Don't Know") | 5,309,219 |
def test_run_parse_when_no_dict_and_no_args_in(mock_pipe):
"""Default parse to true when dict_in doesn't exists and no args_in."""
out = run('arb pipe')
assert type(out) is Context
assert out == {}
assert not out.is_in_pipeline_scope
mock_pipe.assert_called_once_with(
name='arb pipe',
... | 5,309,220 |
def flatten_omegaconf(cfg: Any) -> Dict[Any, Any]:
"""Recursively flatten a nested Dict into a simple one.
The difference between this function and `recurse` is that the dictionnary produced
by this one doesn't have the hydra variables "$" anymore, and that the keys are
alphabetically sorted.
Used... | 5,309,221 |
def reports(request, report, casetype='Call'):
"""Handle report rendering"""
query = request.GET.get('q', '')
datetime_range = request.GET.get("datetime_range")
agent = request.GET.get("agent")
category = request.GET.get("category", "")
form = ReportFilterForm(request.GET)
dashboard_stats = ... | 5,309,222 |
def test_exists_in_assumed_account(
assumed_session: boto3.Session, namespace: str, variables: Dict[str, Any]
) -> None:
"""Test that the deployed stack exists in the assumed account."""
assert_session_belongs_to_account(
assumed_session, variables["account_id"]["test-alt"]
)
assert assumed_... | 5,309,223 |
def score(hand):
"""
Compute the maximal score for a Yahtzee hand according to the
upper section of the Yahtzee score card.
hand: full yahtzee hand
Returns an integer score
"""
max_score = 0
sorted_hand_list = sorted(list(set(hand)))
for i_mem in sorted_hand_list:
... | 5,309,224 |
def mismatched_units_matching_numbers_of_integer_digits(
digits: int, num_trials: int
) -> Dict[str, Union[str, float]]:
"""The hardest subtask. The input units and output units can all differ.
The number of digits supplied to both inputs is the same.
"""
examples = []
for _ in range(num_trials):
... | 5,309,225 |
def context_get(stack, name):
"""
Find and return a name from a ContextStack instance.
"""
return stack.get(name) | 5,309,226 |
def get_first_published_date(organization):
"""
Get first publisher date from an organization. Check if the date is invalid, get the date
:param organization:
:return:
"""
_invalid_dates = ('No data published', 'Date not found', 'Date is not valid')
# Check if publisher date already exists.... | 5,309,227 |
def test_vars(env_vars):
"""Method to identify the active and inactive environment variables for a specific conda environment
test_vars
=========
This method is used to get the active and inactive environment variables for a specific conda environment
created by ggd.
Parameters:
---------... | 5,309,228 |
def determine_redemption_annuity(
months_to_legal_maturity: int,
outstanding_balance: float,
interest_rate: float,
annuity: Optional[float] = None,
) -> float:
"""Calculate the redemption of an annuity mortgage.
On basis of the outstanding_balance at the start of the month, the inte... | 5,309,229 |
def _read(fname):
"""Returns content of a file.
"""
fpath = os.path.dirname(__file__)
fpath = os.path.join(fpath, fname)
with open(fpath, 'r') as file_:
return file_.read() | 5,309,230 |
def test_paragraph_extra_65xa():
"""
Test case extra 65xa: Paragraph with inline image with newline after the URI and no text
"""
# Arrange
source_markdown = """a"""
expected_tokens = [
"[para(1,1):\n]",
"[text(1,1):a:]",
"[image(1,2):inline:/uri::Foo::::Fo... | 5,309,231 |
def getversion(online=True):
"""Return a pywikibot version string.
@param online: (optional) Include information obtained online
"""
data = dict(getversiondict()) # copy dict to prevent changes in 'cache'
data['cmp_ver'] = 'n/a'
if online:
try:
hsh3 = getversion_onlinerepo... | 5,309,232 |
def test_interface_conversion():
"""Test interface conversion."""
from Python.Test import Spam, ISpam
ob = ConversionTest()
assert ISpam(ob.SpamField).GetValue() == "spam"
assert ob.SpamField.GetValue() == "spam"
ob.SpamField = Spam("eggs")
assert ISpam(ob.SpamField).GetValue() == "eggs"
... | 5,309,233 |
def _ppl(
target: str,
model_yaml: str,
status_dir: str,
log_dir: str,
result_dir: str,
input_config: str,
) -> None:
"""
[ONLY Standalone]Run PPL
TARGET: model uri or model workdir path, in Starwhale Agent Docker Environment, only support workdir path.
INPUT_JSON: dataset uri o... | 5,309,234 |
def euclidean_distance(X1, X2):
"""
Function to compute the euclidean distance between two vectors
:param X1: Vector 1
:param X2: Vector 2
:return: Scalar euclidean distance between X1 and X2
"""
return np.sqrt(np.sum(np.square(X1 - X2), axis=1)) | 5,309,235 |
async def get_exchanges_for_market(symbol, collections_dir='./'):
"""
Returns the list of exchanges on which a market is traded
"""
try:
with open('{}collections.json'.format(collections_dir)) as f:
collections = json.load(f)
for market_name, exchanges in collections.items():... | 5,309,236 |
def load_demonstrations(demo_dir, env_name):
"""Load expert demonstrations.
Outputs come with the following format:
[
[{observation: o_1, action: a_1}, ...], # episode 1
[{observation: o'_1, action: a'_1}, ...], # episode 2
...
]
Args:
demo_dir: directory path of expert demonstrati... | 5,309,237 |
def projectNodePosOnly(pt, upVec, p0, v1, v2):
"""
Project a point pt onto a triagnulated surface and the solution
that is the closest in the positive direction (as defined by
upVec).
pt: The initial point
upVec: The vector pointing in the search direction
p0: A numpy array of triangle orig... | 5,309,238 |
def load_obj_tsv(fname, topk=None, hide_images=False):
"""Load object features from tsv file.
:param fname: The path to the tsv file.
:param topk: Only load features for top K images (lines) in the tsv file.
Will load all the features if topk is either -1 or None.
:return: A list of image objec... | 5,309,239 |
def show(shell, case_insensitive):
"""Show the click-completion-command completion code"""
extra_env = (
{"_CLICK_COMPLETION_COMMAND_CASE_INSENSITIVE_COMPLETE": "ON"}
if case_insensitive
else {}
)
click.echo(click_completion.core.get_code(shell, extra_env=extra_env)) | 5,309,240 |
def test_existing_efs(
region,
scheduler,
efs_stack,
pcluster_config_reader,
clusters_factory,
vpc_stack,
request,
key_name,
cfn_stacks_factory,
):
"""
Test when efs_fs_id is provided in the config file, the existing efs can be correctly mounted.
To verify the efs is the... | 5,309,241 |
def get_scalar_metrics(means, logvar, Y_val, n_MC):
"""
Estimate predictive log likelihood:
log p(y|x, D) = log int p(y|x, w) p(w|D) dw
~= log int p(y|x, w) q(w) dw
~= log 1/n_MC sum p(y|x, w_k) with w_k sim q(w)
= LogSumExp log p(y|x, w_k) - log n_MC
... | 5,309,242 |
def test_ap_open(dev, apdev):
"""AP with open mode (no security) configuration"""
hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
hwsim_utils.test_connectivity(dev[0].ifname, apdev[0]['ifname'])
ev = hapd.wait_event([ "AP-STA-CO... | 5,309,243 |
def extract_patterns(df):
"""
Extracts the unique patterns of contestation in an electoral system. Mimicks Linzer 2012's `findpatterns` R function.
Arguments
----------
df : data frame
dataframe containing vote values
votecols: list
list of columns conta... | 5,309,244 |
def group_api(request):
"""
状态码说明:
200:成功
60001: 数据库操作异常
60002:etcd推送异常
60003: 不支持的请求
接口返回结果示例:{resultCode:200,data:response,info:u'成功'}
"""
"""
创建组接口
"""
if not request.user.has_perm('home_application.can_add_groups'):
return render(request, '403.html'... | 5,309,245 |
def tree_names (tree):
"""Get the top-level names in a tree (including files and directories)."""
return [x[0] for x in list(tree.keys()) + tree[None] if x is not None] | 5,309,246 |
def make_fig(in_frame, target, pred, fname):
""" Make figure to visualize performance
Parameters
----------
in_frame : torch.tensor
Input frame tensor
target : torch.tensor
Target (real) frame
pred : torch.tensor
Predicted target frame
fname : str
Output file ... | 5,309,247 |
def update_information_first(update=False):
"""
Decorator to wrap :class:`Information <ansys.mapdl.core.misc.Information>`
methods to force update the fields when accessed.
Parameters
----------
update : bool, optional
If ``True``, the class information is updated by calling ``/STATUS``... | 5,309,248 |
def find_key(key: str, up: any):
"""根据key提取Value"""
if dict == type(up):
if key in up:
return up[key]
else:
for dict_key, dict_value in up.items():
if dict == type(dict_value) or list == type(dict_value):
result = find_key(key, dict_val... | 5,309,249 |
def main():
"""
适合存在可能影响最大最小值的异常点的大量数据
归一化处理异常值偏差较大的情况时容易出问题, 需要使用标准化
标准化将原始数据处理到均值为0, 标准差为1的范围
x_final = (x - avg) / sigma
也即是, (x - 该列平均值) / 标准差
标准差的计算为:
1. 计算平均值 avg
2. 计算方差, 即该列所有值 (x1 - avg)^2 + (x2 - avg)^2 + (x3 - avg)^2 + ... + (xn - avg)^2 / (n - 1)
3. 方差开方的结果即是标准差 sigma... | 5,309,250 |
def get_class_names(file_meta, aspect_table):
"""
Creates and looks up names for classification, i.e. classifications that are not found in the database (custom)
will be generated and existing ones (non-custom) looked up in the classification_definitions table.
The name is generated as a combination of ... | 5,309,251 |
def handle_setup(last_step):
"""
Main logic for the module. It allows for restarting the
initialization at any point if one of the modules should crash.
Args:
last_step (int): The last stored successful step, for starting
over on errors. If `< 0`, initialization has finished and no
... | 5,309,252 |
def interface_configuration_update(
node_id,
interface_name,
description,
address,
netmask,
active='act',
... | 5,309,253 |
def get_attrs(expr: relay.expr.Expr) -> Any:
"""Get the attributes from an expression."""
if isinstance(expr, Call):
return expr.attrs
if isinstance(expr, TupleGetItem):
return get_attrs(expr.tuple_value)
return {} | 5,309,254 |
def clastic_decorator(subdecorator):
"""
If a decorator needs to accept *args and/or **kwargs,
this function makes that possible by precomputing the
argspec of the to-be-wrapped function and propagating
it to the decorated version, where it is available to
clastic for computing dependencies.
... | 5,309,255 |
def process_snapshots(os_client, dry_run):
"""Delete every expired snapshot"""
destroyed_snapshot = 0
errors = 0
for snapshot in os_client.block_storage.snapshots(status="available"):
try:
log.debug("Looking at snapshot", snapshot=snapshot.id)
if "expire_at" not in snapsh... | 5,309,256 |
def test_generate_cloudwatch_monitoring_no_kinesis():
"""CLI - Terraform Generate Cloudwatch Monitoring - Kinesis Disabled"""
cluster_dict = common.infinitedict()
CONFIG['clusters']['test']['modules']['cloudwatch_monitoring']['kinesis_alarms_enabled'] = False
CONFIG['clusters']['test']['modules']['cloud... | 5,309,257 |
def fixed_width_repr_of_int(value, width, pad_left=True):
"""
Format the given integer and ensure the result string is of the given
width. The string will be padded space on the left if the number is
small or replaced as a string of asterisks if the number is too big.
:param int value: An inte... | 5,309,258 |
def _getCompiledName(fldName, clsName):
"""Return mangled fldName if necessary, else no change."""
# If fldName starts with 2 underscores and does *not* end with 2 underscores...
if fldName[:2] == '__' and fldName[-2:] != '__':
return "_%s%s" % (clsName, fldName)
else:
return fldName | 5,309,259 |
def get_api_client():
"""Establish connection and set up an API client using credentials."""
# Disable OAuthlib's HTTPS verification when running locally.
# *DO NOT* leave this option enabled in production.
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
api_service_name = "youtube"
api_version... | 5,309,260 |
def writeAnon(outf, p):
"""
Write an anonymized version of the data into a line of a csv file
This function will create a file with the user profile data, stripped of
identifying information (the user_id, name, and address of the student)
All that is left is the gender, the year of birth, the l... | 5,309,261 |
def backward_subd(U, y, pr):
"""Given a lower triangular matrix U and right-side vector y,
compute the solution vector x solving Ux = y."""
# x = zerod(len(y))
x = [De(0.0) for ix in y]
for i in range(len(x), 0, -1):
val_i = (y[i-1] - dot(U[i-1][i:], x[i:])) / U[i-1][i-1]
aa... | 5,309,262 |
def get_recoverable_databases(credentials: Credentials, subscription_id: str, server: Dict) -> List[Dict]:
"""
Returns details of the Recoverable databases in a server.
"""
try:
client = get_client(credentials, subscription_id)
recoverable_databases = list(
map(
... | 5,309,263 |
async def async_get_service(hass, config, discovery_info=None):
"""Get the Tibber notification service."""
tibber_connection = hass.data[TIBBER_DOMAIN]
return TibberNotificationService(tibber_connection.send_notification) | 5,309,264 |
def get_project(datasource):
"""Get the project info from given datasource
Args:
datasource: The odps url to extract project
"""
_, _, _, project = MaxComputeConnection.get_uri_parts(datasource)
return project | 5,309,265 |
def pearson_correlation_terms(co_elements, first_set, second_set,
first_set_avg, second_set_avg):
"""
Description
A function which returns the pearson correlation terms between
two elements.
Arguments
:param co_elements: Number of co-elements.
:... | 5,309,266 |
def r_gyration(selection='all', from_state=1, to_state=1, step=1, visual=True,
by_state=True):
"""
Calculates radius of gyration for a PyMOL object
Arguments:
-------------------------------------------------
selection: key word. Selects and object
from_state: int. First ... | 5,309,267 |
def train(clf, onehot_encoder, params):
"""
Trains the model given training data.
Arguments:
clf (class) : lstm model
params (dict) : contains model, dimension, and batch parameters
Returns:
clf (class) : the trained model
"""
num_epochs = params['num_epochs']
... | 5,309,268 |
def get_sorted_qlist_wstats(course_id, topic_id, user_id=None):
""" Return a list of questions, sorted by position. With
some statistics (may be expensive to calculate).
"""
def cmp_question_position(a, b):
"""Order questions by the absolute value of their positions
since we use -... | 5,309,269 |
def _install_apache():
""" Install and set up apache and mod_wsgi. """
sudo('apt-get install -q -y apache2 libapache2-mod-wsgi')
sudo('a2enmod wsgi', warn_only=True) | 5,309,270 |
def get_telem_values(tstop, msids, days=7):
"""
Fetch last ``days`` of available ``msids`` telemetry values before
time ``tstop``.
:param tstop: start time for telemetry (secs)
:param msids: fetch msids list
:param days: length of telemetry request before ``tstop``
:returns: astropy Table ... | 5,309,271 |
def doc_vocab2multi_hot(doc_vocab, vocab_size):
"""
Input doc_vocab: batch_size * max_doc_vocab_size
Return multi-hot tensors: doc_vocab_mh: batch_size * vocab_size
"""
# logger.info('doc_vocab: {}'.format(doc_vocab.size()))
doc_vocab_mh = torch.zeros([len(doc_vocab), vocab_siz... | 5,309,272 |
async def async_remove_entry(hass, config_entry):
"""Handle removal of an entry."""
try:
await hass.config_entries.async_forward_entry_unload(config_entry, "sensor")
_LOGGER.info("Successfully removed sensor from the gkeep integration")
except ValueError as e:
_LOGGER.exception(e)
... | 5,309,273 |
def ConvertListToCSVString(csv_list):
"""Helper to convert a list to a csv string."""
return ','.join(str(s) for s in csv_list) | 5,309,274 |
def list_projects(verbose=True):
"""
Lists all projects that exist.
Args:
verbose: can be silent
"""
home_path, db_path, run_path, archive_path, disc = wrftamer_paths()
list_of_projects = [
name
for name in os.listdir(db_path)
if os.path.isdir(os.path.join(db_... | 5,309,275 |
def random_scale(img, min_size):
"""
min_size default: 640
正因为调用了这个函数,初始化成归一化的坐标就不用维护了
"""
h, w = img.shape[: 2]
if max(h, w) > 1280:
scale = 1280.0 / max(h, w)
img = cv2.resize(img, dsize=None, fx=scale, fy=scale)
h, w = img.shape[: 2]
random_scale = np.array([0.5, 1.0,... | 5,309,276 |
def get_learn_performance(model):
""" For acquiring the sum total performance of a strategy"""
# get the list of agent
strategy = [a.strategy for a in model.schedule.agents]
# get the list of agent performances
scores = [a.score for a in model.schedule.agents]
# for each in that list, when stra... | 5,309,277 |
def min_distance_bottom_up(word1: str, word2: str) -> int:
"""
>>> min_distance_bottom_up("intention", "execution")
5
>>> min_distance_bottom_up("intention", "")
9
>>> min_distance_bottom_up("", "")
0
"""
m = len(word1)
n = len(word2)
dp = [[0 for _ in range(n + 1)] for _ in ... | 5,309,278 |
def adjust_cell_formula(value, k):
""" Cell formula, i.e., if i=5, val=?(A11)+?(B12) -> val=A16+B17 """
if isinstance(value, str):
for i in range(value.count('?(')):
if value and '?(' in value and ')' in value:
i = value.index('?(')
j = value.index(')', i)
... | 5,309,279 |
def insert_data(id: str, og: str, value: int):
"""
Insert data in db
Params:
id: short url(primary key)
og: original url
value: number of visit
returns:
True if successful else False
"""
query = f'''INSERT INTO URLS (ID, ORIGINAL, VISITS) VALUES ("{str(id)}", "{st... | 5,309,280 |
def main(df):
"""
main function returs a clean data frame
Returns
-------
df_new : pandas data frame
clean data.
"""
df_new = data_cleaning(df)
return df_new | 5,309,281 |
def lCQgCPevBZXs():
"""Package link to operation."""
pkg = Package("pkg")
return pkg.circles.long_operation.Bar | 5,309,282 |
def preprocess_dataset(data: str, threshold: int = 4, alpha: float = 0.5, beta: float = 0.5) -> Tuple:
"""Load and Preprocess datasets."""
# load dataset.
if data == 'yahoo':
col = {0: 'user', 1: 'item', 2: 'rate'}
with codecs.open(f'../data/yahoo/train.txt', 'r', 'utf-8', errors='ignore') a... | 5,309,283 |
def _update_machine_if_necessary(
machine, session=None, **kwargs
):
"""Update machine is there is something to update."""
utils.update_db_object(
session, machine, **kwargs
) | 5,309,284 |
def week_tasks():
"""function used to print to-do tasks on a week time from the current date"""
weeks_day = {0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday",
4: "Friday", 5: "Saturday", 6: "Sunday"}
today = datetime.today()
week = [today.date() + timedelta(days=x) for x in rang... | 5,309,285 |
def _write_whole_disk_image(image, image_info, device):
"""Writes a whole disk image to the specified device.
:param image: Local path to image file to be written to the disk.
:param image_info: Image information dictionary.
This parameter is currently unused by the function.
:pa... | 5,309,286 |
def test_create_bool():
"""
Create Bool Block
"""
# When I create a Bool block
t = Bool()
# Then I see the appropriate JSON
results = {
"bool": {}
}
homogeneous(t, results) | 5,309,287 |
def inspect_dataset(dataset_name: str):
"""See detailed metadata about a dataset.
Args:
dataset_name (str): string name of the dataset to inspect
"""
try:
metadata = cli_spinner("Downloading dataset metadata from S3...", get_dataset_metadata, dataset_name)
click.echo(_stringify_... | 5,309,288 |
def isExtended(lut):
""" Returns True if the lookup table has been extended with isExtended.
I.e. returns True if the last and second to last LUT entries are the same
"""
assertIsLut(lut)
return np.array_equal(lut[-1, :], lut[-2, :]) | 5,309,289 |
def test_HindcastEnsemble_instantiating_standard_name(
da_lead, dim, new_dim, cf_standard_name
):
"""Instantiating a HindcastEnsemble without init dim only works if matching CF standard name is set."""
init = (
da_lead.to_dataset(name="var").expand_dims("member").assign_coords(member=[1])
)
... | 5,309,290 |
def exclude_regexps(regexps, suite):
"""Returns the tests whose id does not match with any of the regexps."""
if not regexps:
# No regexpes, no filtering
return suite
def matches_none_of(test):
# A test is kept if its id matches none of the 'excludes' regexps
tid = test.id()... | 5,309,291 |
def _load_fcn(path, extension):
"""Actual loading function, which handles the cases specified in `load()`."""
if extension == "pt":
obj = to.load(path)
elif extension == "npy":
obj = np.load(path)
elif extension == "pkl":
obj = joblib.load(path)
else:
return NotImplem... | 5,309,292 |
def test_updating_feature_documentation():
"""Test that we properly update the documentation of a Feature when using
set_feat.
"""
class DocTester(DummyParent):
#: This is the docstring for
#: the Feature test.
test = Feature(True)
assert DocTester.test.__doc__.split('\n')... | 5,309,293 |
def tasks_mult_per_owner():
"""Several owners with several tasks each."""
return (
Task('Make a cookie', 'Raphael'),
Task('Use an emoji', 'Raphael'),
Task('Move to Berlin', 'Raphael'),
Task('Create', 'Michelle'),
Task('Inspire', 'Michelle'),
Task('Encourage', 'Mi... | 5,309,294 |
def generate_systemd_scion_config(host, archive, with_sig_dummy_entry=False):
"""
Generate the configuration archive for the :host: in the given archive-writer
:param host: Host object
:param scionlab.util.archive.BaseArchiveWriter archive: output archive-writer
:returns: list of systemd units that ... | 5,309,295 |
def lascoverage(inputfile):
"""
Provide a file name with extension:
- las
- laz
...extract a tight polygon around the XY points in the file
and return a GeoJSON polygon
"""
# define a pipeline
metapipeline = {
"pipeline": [
{
"type": "readers.las"... | 5,309,296 |
def list_contacts_command():
"""
List all contacts.
Lists all contacts matching the specified filters. If no filters are provided
then all unblocked and undeleted contacts will be returned.
demisto parameter: (number) mobile
mobile number to filter the contacts by
demisto parameter: (... | 5,309,297 |
def get_renovations(ids, cache_time=5):
"""
Get stadium renovation by ID
Args:
ids: renovation ID(s). Can be a single string ID, comma separated string, or list.
cache_time: response cache lifetime in seconds, or `None` for infinite cache
"""
if isinstance(ids, list):
ids = ... | 5,309,298 |
def _simulate_delta_rule_2A(task_design,
alpha,
initial_value_learning,
alpha_pos=None,
alpha_neg=None):
"""Q learning (delta learning rule) for two alternative... | 5,309,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.