content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_upcoming_assignments_calendar_events(request_ctx, **request_kwargs):
"""
Returns the current user's upcoming events, i.e. the same things shown
in the dashboard 'Coming Up' sidebar.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:return: Li... | 5,324,700 |
def sync(erpnext_support_issue=None):
"""
Syncs Support Issue with Server.
"""
fields = ["name", "frappe_issue_id", "status", "last_sync_on"]
filters = [
["status", "=", "Open"],
["frappe_issue_id", "!=", ""],
["last_sync_on", "!=", ""]
]
if erpnext_support_issue:
filters.append(["name", "=", erpnext_s... | 5,324,701 |
def test_whitelist_nested_classes(
assert_errors,
parse_ast_tree,
whitelist_name,
code,
default_options,
mode,
):
"""Testing that it is possible to nest whitelisted classes."""
tree = parse_ast_tree(mode(code.format(whitelist_name)))
visitor = NestedComplexityVisitor(default_options... | 5,324,702 |
def mse_loss(y,loc):
""" Mean squared error loss function
Use mean-squared error to regress to the expected value
Parameters:
loc: mean
"""
loss = (y-loc)**2
return K.mean(loss) | 5,324,703 |
def _get_license_key_outputs(session):
"""Returns the account id and policy ARN for the license key secret if they exist"""
global __cached_license_key_nr_account_id
global __cached_license_key_policy_arn
if __cached_license_key_nr_account_id and __cached_license_key_policy_arn:
return __cached_... | 5,324,704 |
def get_sample_untransformed(shape, distribution_type, distribution_params,
seed):
"""Get a distribution based on specification and parameters.
Parameters can be a list, in which case each of the list members is used to
generate one row (or column?) of the resulting sample matrix. Ot... | 5,324,705 |
def __convert_sysctl_dict_to_text():
"""
Convert sysctl configuration dict to text with each property value pair separated on new line
"""
import params
sysctl_file_content = "### HAWQ System Parameters ###########\n"
for key, value in params.hawq_sysctl.iteritems():
if not __valid_input(value):
r... | 5,324,706 |
def vizualScript(
inputds: str,
script: Union[List[Dict[str, Any]], Dict[str, Any]],
script_needs_compile: bool = False,
properties: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Create a view that implements a sequence of vizual commands over a fixed input table
Parameters
--------... | 5,324,707 |
def test_multiple_fits_different_columns():
"""HyperTransformer should be able to be used multiple times regardless of the data.
Fitting, transforming and reverse transforming should work when called on different data.
"""
# Setup
data = pd.DataFrame({'col1': [1, 2, 3], 'col2': [1.0, 0.0, 0.0]})
... | 5,324,708 |
def _to_sparse_input_and_drop_ignore_values(input_tensor, ignore_value=None):
"""Converts a `Tensor` to a `SparseTensor`, dropping ignore_value cells.
If `input_tensor` is already a `SparseTensor`, just return it.
Args:
input_tensor: A string or integer `Tensor`.
ignore_value: Entries in `dense_tensor` ... | 5,324,709 |
def parse_date(date_str):
"""
>>> parse_date("22 April 2011 at 20:34")
datetime.datetime(2011, 4, 22, 20, 34)
>>> parse_date("9 July 2011")
datetime.datetime(2011, 7, 9, 0, 0)
>>> parse_date("September 2003")
datetime.datetime(2003, 9, 1, 0, 0)
"""
try:
return datetime.strpt... | 5,324,710 |
def readTmpFile( processPid ):
""" Read the temp file """
fileName = os.path.join( tempfile.gettempdir(), 'mms-' + str( processPid ) )
if not os.path.isfile( fileName ):
return None
f = open( fileName )
try:
fileContent = f.read()
# Handle the legacy json files
if... | 5,324,711 |
def save_transitions_to_file(dynamics, state_space, action_space, N, T, filename, verbose=True, sample_trajectories=False):
"""
samples transition data from (dynamics, state_space, action_space)
with N total datasets with T samples each
saves to filename in the npz format
sample_trajectories: ... | 5,324,712 |
def pkcs7_unpad_strict(data, block_size=16):
"""Same as `pkcs7_unpad`, but throw exception on incorrect padding.
Mostly used to showcase the padding oracle attack.
"""
pad = data[-1]
if ord(pad) < 1 or ord(pad) > block_size:
raise Exception('Invalid padding length')
for i in range(2, or... | 5,324,713 |
def cut(d1: dict, d2: dict) -> dict:
"""Removes the keys/values in `d1` to `d2` if they do
not already exist (non-mutating action)
Examples:
.. highlight:: python
.. code-block:: python
from map_ops.operations import cut
d1 = {"foo": 1, "bar": 1}
d2 = ... | 5,324,714 |
def chiresponse(A,x):
"""
Deprecated, just use normal "response" function above!
The response function used in the chi squared fitting portion of the simulation.
Meant to imitate the actual response of a scintillator.
Inputs 2 vectors, and responds with a cos^x dependence.
Parame... | 5,324,715 |
def app_config_js():
"""
Render app_config.js to file.
"""
from static import _app_config_js
with _fake_context('/js/includes/app_config.js'):
response = _app_config_js()
with open('www/js/includes/app_config.js', 'w') as f:
f.write(response.data) | 5,324,716 |
def _remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content | 5,324,717 |
def text_save(final_result, section, path):
""" 추출한 글자를 저장합니다.
index, start_time, end_time, section, contents
:param final_result: 전처리 된 문자
:param path: csv 파일 저장 경로
"""
f = open(path, 'w', encoding='utf-8', newline='')
wr = csv.writer(f)
wr.writerow(['index', 'start_time', 'end_time', 'section', 'content... | 5,324,718 |
def execute_no_overwrite_part1(tmpdir):
"""Create expected output."""
config = configparser.ConfigParser()
config_path = pathlib.Path('tests/data/tasks/osco/demo-osco-to-oscal.config')
config.read(config_path)
section = config['task.osco-to-oscal']
section['output-dir'] = str(tmpdir)
tgt = o... | 5,324,719 |
def data_downloader(genome_ids: List[str],
output_directory: Optional[str] = None,
metadata: Optional[str] = None) -> List[str]:
"""
Parameters
----------
genome_ids
A list of assembly accession id's
output_directory
Directory to look for and ... | 5,324,720 |
def find_loop_size( public_key, subject=7 ):
"""
To transform a subject number, start with the value 1.
Then, a number of times called the loop size, perform the following steps:
- Set the value to itself multiplied by the subject number.
- Set the value to the remainder after dividing... | 5,324,721 |
def update_learning_curves(learning_curves, results):
"""
Updates learning curves with given results.
Parameters
----------
learning_curves : dict
Learning curves
results : dict
Dictionary containing results of current epoch
"""
for phase in results:
for metric... | 5,324,722 |
def lambda_local_ep(ngl, ind_passive, passive_el, disp_vector, dyna_stif, coord, connect, E, v, rho):
""" Calculates the lambda parameter of the local elastic potential energy function.
Args:
ngl (:obj:`int`): Degrees of freedom.
ind_passive (:obj:`numpy.array`): Index of passive elements.
... | 5,324,723 |
async def test_verify_image_signatures(
fake_registry_v2_image_source: FakeRegistryV2ImageSourceNoLabels,
image_name: ImageName,
):
"""Test verifying the signatures within the image configuration."""
# An exception should be raised if the image configuration is not signed
with pytest.raises(NoSignat... | 5,324,724 |
def from_spanning_matroid(matroid: tuple[set[T], list[set[T]]]) -> list[set[T]]:
"""Construct flats from a matroid defined by spanning sets.
Args:
matroid (tuple[set[T], list[set[T]]]): A matroid defined by spanning sets.
Returns:
list[set[T]]: The flats of a given matroid.
"""
E, ... | 5,324,725 |
def train_concise_ch11(trainer_fn, hyperparams, data_iter, num_epochs=4):
"""Defined in :numref:`sec_minibatches`"""
# 初始化模型
net = nn.Sequential(nn.Linear(5, 1))
def init_weights(m):
if type(m) == nn.Linear:
torch.nn.init.normal_(m.weight, std=0.01)
net.apply(init_weights)
o... | 5,324,726 |
def select_angles_from_sites(networkx_graph, top, Atom1, Atom2, Atom3):
"""Return angles based on interactive selection."""
params_list = select_params_on_networkx(
networkx_graph, [Atom1, Atom2, Atom3]
)
if params_list:
edges_widget = widgets.Dropdown(
options=params_list,
... | 5,324,727 |
def suppress_traceback(debug: bool = True) -> None:
"""
Decorator to suppress traceback when in debug mode.
Parameters
----------
debug: bool
turn on debug mode or not
Returns
-------
None
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*arg... | 5,324,728 |
def reset_logger():
"""Makes sure that mutations to the logger don't persist between tests."""
logger = logging.getLogger('awsprocesscreds')
original_level = logger.level
original_handlers = copy.copy(logger.handlers)
original_filters = copy.copy(logger.filters)
# Everything after the yield wil... | 5,324,729 |
def statistics_on_atlases(in_registered_map, name_map, prefix_file=None):
"""Computes a list of statistics files for each atlas.
Args:
in_registered_map (str): Map already registered on atlases.
name_map (str): Name of the registered map in CAPS format.
prefix_file (Opt[str]):
... | 5,324,730 |
def render_projection_from_filelist(files: list) -> str:
"""Render a full projection montage from the given list of files
Returns the filename to the output image, which must be manually
deleted after use.
"""
temp_dir = tempfile.TemporaryDirectory()
convert_filelist_to_tempfiles(files, temp_d... | 5,324,731 |
def get_value_for_attribute(attribute):
"""For a given key return the value.
Args:
attribute (str): Some metadata key.
Returns:
str: The value of the requested key, if key isn't present then None.
"""
path = '/computeMetadata/v1/instance/attributes/%s' % attribute
try:
... | 5,324,732 |
def list_selected_groups(remote):
"""Returns a list of unique facegroup IDs for the current face selection (requires an active selection)"""
cmd1 = mmapi.StoredCommands()
key1 = cmd1.AppendSelectCommand_ListSelectedFaceGroups()
remote.runCommand(cmd1)
groups1 = mmapi.vectori()
cmd1.GetSelectComm... | 5,324,733 |
def do_3009(pc, target_id, x, y, skill_id, skill_lv):
"""ファイアブラスト 対象の範囲に火焔攻撃を行う"""
monster = get_monster(pc, target_id, x, y, skill_id, skill_lv)
if monster is None:
return
start_cast(pc, target_id, x, y, skill_id, skill_lv, 500)
monsters.skill_attack_monster_range(pc, monster, (3, 3), 50, skill_id, skill_... | 5,324,734 |
def mock_cali_query(tmpdir):
"""Create a mock cali-query path."""
tmpdir = tmpdir.mkdir("tmp-bin")
cali_query = tmpdir.join("cali-query")
with cali_query.open("w") as file:
file.write("")
st = os.stat(str(cali_query))
os.chmod(str(cali_query), st.st_mode | stat.S_IEXEC)
# save curr... | 5,324,735 |
def make_user_variable(
id_name, cluster_name, w_name, d_name, y_tree_name, y_name, x_name_ord,
x_name_unord, x_name_always_in_ord, z_name_list,
x_name_always_in_unord, z_name_split_ord, z_name_split_unord,
z_name_mgate, z_name_amgate, x_name_remain_ord, x_name_remain_unord,
x_balance_name_ord, ... | 5,324,736 |
def _quotes_add_night(quotes):
"""为 quotes 中应该有夜盘但是市价合约文件中没有夜盘的品种,添加夜盘时间"""
for symbol in quotes:
product_id = quotes[symbol]["product_id"]
if quotes[symbol].get("trading_time") and product_id in night_trading_table:
quotes[symbol]["trading_time"].setdefault("night", [night_trading_t... | 5,324,737 |
def show(red, green, blue, blink):
"""
CLI tool to write sigle color to busylight.
"""
bl = busylight.BusyLight(red=red, green=green, blue=blue, blink=blink)
bl.write() | 5,324,738 |
def get_skip_report_step_by_index(skip_report_list):
"""Parse the missed step from skip a report.
Based on the index within the skip report file (each line a report), the
missed step for this entry gets extracted. In case no step could be found,
the whole entry could not been parsed or no report for th... | 5,324,739 |
def write_api(entrypoint, kind="node", pkg_path=None, overwrite=False):
"""
"""
entrypoint_name = entrypoint['Name'].replace(".", "_").lower()
class_name = entrypoint['NewName']
class_dir = entrypoint['Module']
class_type = entrypoint['Type']
class_file = class_name.lower()
doc_builder ... | 5,324,740 |
def constraint_notes_are(sequence: FiniteSequence, beat_offset: int, pitches: List[int]) -> bool:
"""Tells us if the context note on the given beat_offset
has the same pitches as the given list of pitches
"""
if beat_offset > sequence.duration:
return True
offset_event = sequence.event_at(be... | 5,324,741 |
async def test_setup_g1(opp):
"""Test setup with a G1 vehicle."""
entry = await setup_subaru_integration(
opp, vehicle_list=[TEST_VIN_1_G1], vehicle_data=VEHICLE_DATA[TEST_VIN_1_G1]
)
check_entry = opp.config_entries.async_get_entry(entry.entry_id)
assert check_entry
assert check_entry.s... | 5,324,742 |
def display_progress_bar(current_value: int,
goal_value: int,
bar_length: Optional[int] = 50,
bar_title: Optional[str] = "progress",
hash_symbol: Optional[str] = "#",
bar_title_color: Fore = Fore... | 5,324,743 |
def make_anuga_params():
"""Function to make the example ANUGA parameters."""
params = pt.modelParams()
path = os.path.join(os.path.dirname(__file__), 'ex_anuga_data.npz')
data = np.load(path)
# pull depth and stage from that data
depth = data['depth']
qx = data['qx']
qy = data['qy']
... | 5,324,744 |
def test_enum_validation_in_template(tiny_template, tmpdir):
"""Test that the reader can load from a small xlsx file"""
XlTemplateWriter().write(tmpdir.join("test_enum_validation.xlsx"), tiny_template)
workbook = openpyxl.load_workbook(tmpdir.join("test_enum_validation.xlsx"))
worksheet = workbook["TE... | 5,324,745 |
def clip(tensor: T.Tensor, a_min: T.Scalar=None,
a_max: T.Scalar=None) -> T.Tensor:
"""
Return a tensor with its values clipped between a_min and a_max.
Args:
tensor: A tensor.
a_min (optional): The desired lower bound on the elements of the tensor.
a_max (optional): The de... | 5,324,746 |
def remove_objects_from_args(args, # type: Iterable[Any]
kwargs, # type: Dict[str, Any]
pvalue_class # type: Union[Type[T], Tuple[Type[T], ...]]
):
# type: (...) -> Tuple[List[Any], Dict[str, Any], List[T]]
"""For internal use ... | 5,324,747 |
def reminder_validator(input_str):
"""
Allows a string that matches utils.REMINDER_REGEX.
Raises ValidationError otherwise.
"""
match = re.match(REMINDER_REGEX, input_str)
if match or input_str == '.':
return input_str
else:
raise ValidationError('Expected format: <number><w|... | 5,324,748 |
def evaluate_nll(confidences, true_labels, log_input=True, eps=1e-8, reduction="mean"):
"""
Args:
confidences (Array): An array with shape [N, K,].
true_labels (Array): An array with shape [N,].
log_input (bool): Specifies whether confidences are already given as log values.
eps ... | 5,324,749 |
def start(filename=None, level=logging.INFO, debug=False):
"""After initialization, start file logging.
"""
global _logging_started
assert _logging_configured
if _logging_started:
return
if debug:
handler = logging.StreamHandler()
else:
handler = logging.handlers.Ro... | 5,324,750 |
def parse(features: str) -> AirPlayFlags:
"""Parse an AirPlay feature string and return what is supported.
A feature string have one of the following formats:
- 0x12345678
- 0x12345678,0xabcdef12 => 0xabcdef1212345678
"""
match = re.match(r"^0x([0-9A-Fa-f]{1,8})(?:,0x([0-9A-Fa-f]{1,8})|)$",... | 5,324,751 |
def _prefix_with_swift_module(path, resource_info):
"""Prepends a path with the resource info's Swift module, if set.
Args:
path: The path to prepend.
resource_info: The resource info struct.
Returns: The path with the Swift module name prepended if it was set, or just
the path itself if ... | 5,324,752 |
def str2datetime(dt, format=None):
"""
convert a string into a datetime object, it can be:
- 2013-05-24 18:49:46
- 2013-05-24 18:49:46.568
@param dt string
@param format format for the conversion, the most complete one is
``%Y-%m-%d %H:%M:%S.%f``
... | 5,324,753 |
def run_func_motion_correct(func_reorient, out_dir=None, run=True):
"""Run the 'func_motion_correct_workflow' function to execute the modular
workflow with the provided inputs.
:type func_reorient: str
:param func_reorient: Filepath to the deobliqued, reoriented functional
tim... | 5,324,754 |
def add_ackers(parser):
""" Add --ackers option to parser """
parser.add_argument(
"-a",
"--ackers",
help="Set number of acker executors for your topology. "
"Defaults to the number of worker nodes in your "
"Storm environment.",
type=option_alias("topology.acker.... | 5,324,755 |
def get_zoomin(self, scale=1.0):
"""
Returns a spherical region encompassing maximally refined cells.
Moved from Amr class.
What should it do??
Parameters
----------
scale : float
The radius of the returned sphere is scaled by 'scale'.
"""
from ..utils import sampling
... | 5,324,756 |
def _CreateTsMonFlushingProcess(options):
"""Creates a separate process to flush ts_mon metrics.
Useful for multiprocessing scenarios where we don't want multiple ts-mon
threads send contradictory metrics. Instead, functions in
chromite.lib.metrics will send their calls to a Queue, which is consumed by a
ded... | 5,324,757 |
def parse_repeating_time_interval_to_days(date_str):
"""Parsea un string con un intervalo de tiempo con repetición especificado
por la norma ISO 8601 en una cantidad de días que representa ese intervalo.
Devuelve 0 en caso de que el intervalo sea inválido.
"""
intervals = {'Y': 365, 'M': 30, 'W': 7... | 5,324,758 |
def get_pk_and_validate(model):
"""
:param model:
:return:
"""
hits = []
for field in get_model_fields(model):
extra_attrs = field.field_info.extra
if extra_attrs.get('primary_key'):
hits.append(field)
hit_count = len(hits)
if hit_count != 1:
raise ER... | 5,324,759 |
def test_from_partial():
"""Test from_partial works correctly."""
assert Dice.from_partial({1: Fraction(1, 2),}) == Dice.from_full(
{0: Fraction(1, 2), 1: Fraction(1, 2),}
)
assert Dice.from_partial({1: Fraction(1, 3), 2: Fraction(1, 3),}) == Dice.from_full(
{0: Fraction(1, 3), 1: Fract... | 5,324,760 |
def lat_to_y(lat):
"""Convert latitude to Web-Mercator
Args:
lat: a latutude value
Returns:
float: a Web-Mercator y coordinate
"""
r = 6_378_137 # radius of the Earth at the equator
return log(tan((90 + lat) * pi / 360)) * r | 5,324,761 |
def AddPrivateNetworkIpArgs(parser):
"""Set arguments for choosing the network IP address."""
parser.add_argument(
'--private-network-ip',
help="""\
Specifies the RFC1918 IP to assign to the instance. The IP should be in
the subnet or legacy network IP range.
""") | 5,324,762 |
def test_bucket_dump_returns_objs_in_compartment_order(get_model_instances):
"""
Bucket.dump should return a list of objects that have been "put"
into the bucket in compartment and then PK order.
"""
bucket = relationtrees.Bucket([m.EndNode, m.ReferenceNode])
bucket.put(get_model_instances(['ref... | 5,324,763 |
def find_file(filename):
"""Find a file of given name on the file system.
This function is intended to use in tests and demo applications
to locate data files without resorting to absolute paths. You may
use it for your code as well.
It looks in the following locations:
* If an absolute filen... | 5,324,764 |
def test_createIngress(kubeConfig):
"""
Do I create a Ingress kubernetes resource from a yaml manifest file?
"""
namespace = 'g-se-com'
fileData = 'data'
pOpen = patch_open(fileData)
pCall = patch.object(lib.TxKubernetesClient, 'call')
pApiMethod = patch.object(client,
'Extension... | 5,324,765 |
def test_epo_move_system_command(requests_mock):
"""
Unit test to validate epo_get_version_command
Args:
requests_mock ():mocking the http GET request
Returns:
test Passed or Failed
"""
requests_mock.get(f'{EPO_URL}/remote/system.move?names=TIE&parentGroupId=2',
... | 5,324,766 |
def generate_lasso_mask(image, selectedData):
"""
Generates a polygon mask using the given lasso coordinates
:param selectedData: The raw coordinates selected from the data
:return: The polygon mask generated from the given coordinate
"""
height = image.size[1]
y_coords = selectedData["lass... | 5,324,767 |
def test_no_folding(runner, foo_package):
"""Must create all missing folders."""
result = runner.invoke(steeve.cli, ['--no-folding', 'stow', 'foo', '1.0'])
assert result.exit_code == 0
assert not os.path.islink('bin')
assert os.path.islink(os.path.join('bin', 'foo')) | 5,324,768 |
def test_medicationstatement_2(base_settings):
"""No. 2 tests collection for MedicationStatement.
Test File: medicationstatementexample4.json
"""
filename = base_settings["unittest_data_dir"] / "medicationstatementexample4.json"
inst = medicationstatement.MedicationStatement.parse_file(
file... | 5,324,769 |
def plot_scatter(
title,
x_metric,
y_metrics,
x_axis_title,
y_axis_title,
df_aggregated
):
"""
Function to plot and format a scatterplot from the aggregated dataframe
"""
data = []
shapes = list()
for y_metric in y_metrics:
data.append(
go.Scatter(
... | 5,324,770 |
def guitar(C):
"""Triangular wave (pulled guitar string)."""
L = 0.75
x0 = 0.8*L
a = 0.005
freq = 440
wavelength = 2*L
c = freq*wavelength
from math import pi
w = 2*pi*freq
num_periods = 1
T = 2*pi/w*num_periods
# Choose dt the same as the stability limit for Nx=50
dt... | 5,324,771 |
def start_threads_dict():
"""
获取指定URL起始THREADS字典
:return: dict-->配置中指定URL起始THREADS字典
"""
temp_dict = dict()
enable_flag = const.CONF.get('Auto_Test.assign_start_threads', 'ENABLE')
if enable_flag and isinstance(enable_flag, str):
if enable_flag.lower() == 'true':
temp_dic... | 5,324,772 |
def exists_in_s3(s3_path: str) -> Optional[bool]:
"""Check whether a fully specified s3 path exists.
Args:
s3_path: Full path on s3 in format "s3://<bucket_name>/<obj_path>".
Returns:
Boolean of whether the file exists on s3 (None if there was an error.)
"""
bucket, key = decompose... | 5,324,773 |
def validate_single_matching_uri(all_blockchain_uris: List[str], w3: Web3) -> str:
"""
Return a single block URI after validating that it is the *only* URI in
all_blockchain_uris that matches the w3 instance.
"""
from ethpm.uri import check_if_chain_matches_chain_uri
matching_uris = [
u... | 5,324,774 |
def test_count_for_loops():
"""Test case for counting the for loops."""
expected_for = 1
assert test_pycount.count_for_loops() == expected_for | 5,324,775 |
def ListAndWaitForObjects(service, counting_start_time,
expected_set_of_objects, object_prefix):
"""List objects and wait for consistency.
Args:
service: the ObjectStorageServiceBase object to use.
counting_start_time: The start time used to count for the inconsistency
win... | 5,324,776 |
def test_breadth(capsys, tree):
"""Correct output order."""
tree.breadth_first_traversal(lambda n: print(n.__str__()))
sys.stderr.write("10\n5\n3\n6\nmeow\n15\n11\n")
out, err = capsys.readouterr()
assert out == err | 5,324,777 |
def load_mbb_player_boxscore(seasons: List[int]) -> pd.DataFrame:
"""Load men's college basketball player boxscore data
Example:
`mbb_df = sportsdataverse.mbb.load_mbb_player_boxscore(seasons=range(2002,2022))`
Args:
seasons (list): Used to define different seasons. 2002 is the earliest av... | 5,324,778 |
def countdown(code, input):
""" .countdown <month> <day> <year> - displays a countdown to a given date. """
error = '{red}Please use correct format: %scountdown <month> <day> <year>' % code.prefix
text = input.group(2).strip()
if ' ' in text:
text = text.split()
elif '/' in text:
tex... | 5,324,779 |
def split_rdd(rdd):
"""
Separate a rdd into two weighted rdds train(70%) and test(30%)
:param rdd
"""
SPLIT_WEIGHT = 0.7
(rdd_train, rdd_test) = rdd.randomSplit([SPLIT_WEIGHT, 1 - SPLIT_WEIGHT])
return rdd_train, rdd_test | 5,324,780 |
def QuickSort(A, l, r):
"""
Arguments:
A -- total number list
l -- left index of input list
r -- right index of input list
Returns:
ASorted -- sorted list
cpNum -- Number of comparisons
"""
# Number of comparisons
cpNum = r - l
# Base case
if cpNum == 0:
return [A[l]], 0
elif cpNum ... | 5,324,781 |
def get_cache_dir():
"""get directory to store data cached by application
"""
return os.path.join(get_userdata_dir(), CACHE_DIR) | 5,324,782 |
def checksum(input):
""" Checksum by counting items that have duplicates and/or triplicates and multiplying"""
checksum_twos = 0
checksum_threes = 0
for id in input:
c = [v for k,v in Counter(id).items()]
if 2 in c:
checksum_twos += 1
if 3 in c:
... | 5,324,783 |
def Rescale(UnscaledMatrix, Scales):
"""Forces a matrix of raw (user-supplied) information
(for example, # of House Seats, or DJIA) to conform to
svd-appropriate range.
Practically, this is done by subtracting min and dividing by
scaled-range (which itself is max-min).
"""
# Calulate multi... | 5,324,784 |
def test_is_url_image(url, expected_result, expected_error):
"""Test if url return an image."""
with expected_error:
assert is_url_image(url) == expected_result | 5,324,785 |
def winrate_of(node: sgf.Node) -> float:
"""
The winrate of the node/position is defined as winrate of the most visited child.
"""
max_visits = 0
winrate = 0
variations = ([] if node.next == None else [node.next]) + node.variations
for child in variations:
if "B" in child.properties ... | 5,324,786 |
def extract_kernel_version(kernel_img_path):
"""
Extracts the kernel version out of the given image path.
The extraction logic is designed to closely mimick the logic Zipl configuration to BLS
conversion script works, so that it is possible to identify the possible issues with kernel
images.
:... | 5,324,787 |
def about(request):
""" About view """
try:
about = About.objects.get().description
except:
about = "No information here yet."
return render(request, 'about_page.html', {'about': about}) | 5,324,788 |
def concat_strings(string_list):
"""
Concatenate all the strings in possibly-nested string_list.
@param list[str]|str string_list: a list of strings
@rtype: str
>>> list_ = (["The", "cow", "goes", "moo", "!"])
>>> concat_strings(list_)
'The cow goes moo !'
>>> list_ = (["This... | 5,324,789 |
def produce_grid(tuple_of_limits, grid_spacing):
"""Produce a 2D grid for the simulation system.
The grid is based on the tuple of Cartesian Coordinate limits calculated in
an earlier step.
Parameters
----------
tuple_of_limits : tuple
``x_min, x_max, y_min, y_max``
grid_spacing : ... | 5,324,790 |
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 9))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.xticks([])
plt.yticks([])
plt.title(' '.join(name.split('_')).title(), color='white')
... | 5,324,791 |
def run_disruptions():
"""
Only check for disruptions
"""
click.secho('Needs implementing', fg='red') | 5,324,792 |
def intensity_histogram_measures(regionmask, intensity):
"""Computes Intensity Distribution features
This functions computes features that describe the distribution characteristic of the instensity.
Args:
regionmask=binary image
intensity= intensity image
"""
feat= Intensity_His... | 5,324,793 |
def match(input_character, final_answer):
"""
:param input_character: str, allow users to input a string that will be verified whether
there are any matches with the final answer.
:param final_answer: str, the final answer.
:return: str, return the matching result that could consist of '-' and lette... | 5,324,794 |
def read_json(filename, **kwargs):
"""Read JSON.
Parameters
----------
filename : str
**kwargs
Keyword arguments into :meth:`~astropy.cosmology.Cosmology.from_format`
Returns
-------
`~astropy.cosmology.Cosmology` instance
"""
# read
if isinstance(filename, (str, by... | 5,324,795 |
def menu_load_notes(window, text1, text2, com_socket):
"""Menu selected load notes option."""
load_notes(window, text1, text2, com_socket) | 5,324,796 |
def render_error(request, status=500, title=_('Oops!'),
err_msg=_('An error occured')):
"""Render any error page with a given error code, title and text body
Title and description are passed through as-is to allow html. Make
sure no user input is contained therein for security reasons. The... | 5,324,797 |
def affaire_spatial(request):
"""
Get modification affaire by affaire_fille
"""
# Check connected
if not check_connected(request):
raise exc.HTTPForbidden()
results = request.dbsession.query(VAffaire).filter(
VAffaire.date_cloture == None
).filter(
VAffaire.date_envo... | 5,324,798 |
def get_cosets(big_galois: GaloisGroup, small_galois: GaloisGroup) -> SetOfCosets:
"""
Given a big group `big_galois` and a subgroup `small_galois`, return the cosets
of small_galois \\ big_galois.
Args:
big_galois: A `GaloisGroup` whose cosets to examine
small_galois: The acting subgro... | 5,324,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.