content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_test_config(doc):
""" Get the configuration element. """
test_config = doc.documentElement
if test_config.tagName != 'configuration':
raise RuntimeError('expected configuration tag at root')
return test_config | 5,344,800 |
def _get_control_vars(control_vars):
"""
Create the section of control variables
Parameters
----------
control_vars: str
Functions to define control variables.
Returns
-------
text: str
Control variables section and header of model variables section.
"""
text =... | 5,344,801 |
def echo():
"""Echo data"""
return request.get_data() + '\n' | 5,344,802 |
def get_ids():
"""
Get all SALAMI IDs related to RWC
"""
# Filename for SALAMI RWC metadata
metadata_file = os.path.join(
dpath.SALAMI, 'metadata', 'id_index_rwc.csv')
ids = []
with open(metadata_file, "r") as rwc_file:
reader = csv.reader(rwc_file)
next(reader) #sk... | 5,344,803 |
def _get_signature_def(signature_def_key, export_dir, tags):
"""Construct a `SignatureDef` proto."""
signature_def_key = (
signature_def_key or
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY)
metagraph_def = saved_model_cli.get_meta_graph_def(export_dir, tags)
try:
signature_def = signa... | 5,344,804 |
def illuminance_to_exposure_value(E, S, c=250):
"""
Computes the exposure value :math:`EV` from given scene illuminance
:math:`E` in :math:`Lux`, *ISO* arithmetic speed :math:`S` and
*incident light calibration constant* :math:`c`.
Parameters
----------
E : array_like
Scene illumina... | 5,344,805 |
def feedback(code, guess):
"""
Return a namedtuple Feedback(blacks, whites) where
blacks is the number of pegs from the guess that
are correct in both color and position and
whites is the number of pegs of the right color but wrong position.
"""
blacks = sum(g == c for g, c in zip(guess, cod... | 5,344,806 |
def print_config(conf):
""" Print debug information for a halogen.config.ConfigBase subclass """
width: int = terminal_size().width
print("=" * width)
print("")
print(f" • CONFIG: {conf.name}")
print(f" • PREFIX: {conf.prefix}")
print("")
print("-" * width)
print(" • I... | 5,344,807 |
def Logging(logfile=None):
"""Custom logging function.
Args:
logfile: The name of log files. Log will be stored in logs_dir.
Returns:
The same output of the call function with logging information.
"""
# Create logs_dir if the directory logs is not exist.
logs_dir = 'log... | 5,344,808 |
def find_winning_dates(placed_bets, winning_date):
"""
Finds the placed bets with the dates closest to the winning date
:param placed_bets: iterable of PlacedDateBet
:param winning_date: datetime.date
:return: list of winning PlacedDateBets
"""
from datetime import date
from .models impo... | 5,344,809 |
def create_greedy_policy(Q):
"""
Creates a greedy policy based on Q values.
Args:
Q: A dictionary that maps from state -> action values
Returns:
A function that takes an observation as input and returns a vector
of action probabilities.
"""
def policy_fn(observation):
... | 5,344,810 |
def delay_data_inputflag_future(delay_data_inputflag_future_main):
"""Make function level future shape delay uvcal object."""
delay_object = delay_data_inputflag_future_main.copy()
yield delay_object
del delay_object | 5,344,811 |
def get_tags(rule, method, **options):
"""
gets the valid tags for given rule.
:param pyrin.api.router.handlers.base.RouteBase rule: rule instance to be processed.
:param str method: http method name.
:rtype: list[str]
"""
return get_component(SwaggerPackage.COMPONENT_NAME).get_tags(rule,... | 5,344,812 |
def register_engines():
"""Register engines."""
for filename in os.listdir(os.path.join(os.path.dirname(__file__))):
if not os.path.isfile(os.path.join(os.path.dirname(__file__), filename)):
continue
if filename == '__init__.py':
continue
try:
importl... | 5,344,813 |
def import_module_set_env(import_dict):
"""
https://stackoverflow.com/questions/1051254/check-if-python-package-is-installed
Safely imports a module or package and sets an environment variable if it
imports (or is already imported). This is used in the main function for
checking whether or not `cup... | 5,344,814 |
async def test_config_no_update(ismartgateapi_mock, hass: HomeAssistant) -> None:
"""Test config setup where the data is not updated."""
api = MagicMock(GogoGate2Api)
api.async_info.side_effect = Exception("Error")
ismartgateapi_mock.return_value = api
config_entry = MockConfigEntry(
domain... | 5,344,815 |
def get_paybc_transaction_request():
"""Return a stub payment transaction request."""
return {
'clientSystemUrl': 'http://localhost:8080/abcd',
'payReturnUrl': 'http://localhost:8081/xyz'
} | 5,344,816 |
def hid_exit():
"""Clean up hidapi library resources.
Arguments:
None
Returns:
None"""
global __hidapi
assert __hidapi is not None
if __hidapi.hid_exit() != 0:
raise RuntimeError('hid_exit() failed.') | 5,344,817 |
def dropout_forward(x, dropout_param):
"""
Performs the forward pass for (inverted) dropout.
Inputs:
- x: Input data, of any shape
- dropout_param: A dictionary with the following keys:
- p: Dropout parameter. We drop each neuron output with probability p.
- mode: 'test' or 'train'. If the mode is tr... | 5,344,818 |
def cholesky(a: Union[numpy.ndarray, pandas.core.frame.DataFrame, List[List[float]]]):
"""
usage.scipy: 5
usage.statsmodels: 48
"""
... | 5,344,819 |
def pretreatment(filename):
"""pretreatment"""
poems = []
file = open(filename, "r")
for line in file: #every line is a poem
#print(line)
title, poem = line.strip().split(":") #get title and poem
poem = poem.replace(' ','')
if '_' in poem or '《' in poem or '[' in poem o... | 5,344,820 |
def forward_fdm(order, deriv, adapt=1, **kw_args):
"""Construct a forward finite difference method.
Further takes in keyword arguments of the constructor of :class:`.fdm.FDM`.
Args:
order (int): Order of the method.
deriv (int): Order of the derivative to estimate.
adapt (int, opti... | 5,344,821 |
def lrp_linear_torch(hin, w, b, hout, Rout, bias_nb_units, eps, bias_factor=0.0, debug=False):
"""
LRP for a linear layer with input dim D and output dim M.
Args:
- hin: forward pass input, of shape (D,)
- w: connection weights, of shape (D, M)
- b: biases, o... | 5,344,822 |
def create_resource_group(resource_client, resource_group, location):
# type: (azure.mgmt.resource.resources.ResourceManagementClient,
# str, str) -> None
"""Create a resource group if it doesn't exist
:param azure.mgmt.resource.resources.ResourceManagementClient
resource_client: resource... | 5,344,823 |
def get_list_by_ingredient(ingredient):
""" this should return data for filtered recipes by ingredient """
res = requests.get(f'{API_URL}/{API_KEY}/filter.php', params={"i":ingredient})
return res.json() | 5,344,824 |
def test_get_account_balance_invalid_node_url():
"""
Case: get a balance of an account by passing an invalid node URL.
Expect: the following node URL is invalid error message.
"""
invalid_node_url = 'domainwithoutextention'
runner = CliRunner()
result = runner.invoke(cli, [
'account... | 5,344,825 |
def platform_config_update(config):
"""
Update configuration for the remote platform
@param config The configuration dictionary to use/update
"""
remote_port_map = build_ifaces_map(get_ifaces())
config["port_map"] = remote_port_map.copy()
config["caps_table_idx"] = 0 | 5,344,826 |
def chk_sudo():
"""\
Type: decorator.
The command will only be able to be executed by the author if the author is owner or have permissions.
"""
async def predicate(ctx):
if is_sudoers(ctx.author):
return True
await ctx.message.add_reaction("🛑")
raise excepts.Not... | 5,344,827 |
def have_same_items(list1, list2):
""" Проверяет состоят ли массивы list1 и list2 из одинакового
числа одних и тех же элементов
Parameters
----------
list1 : list[int]
отсортированный по возрастанию массив уникальных элементов
list2 : list[int]
массив... | 5,344,828 |
def main(
consumer_key: str,
consumer_secret: str,
access_token: str,
access_token_secret: str,
bearer_token: str,
hashtags: frozenset[str] = frozenset(
[
"binit",
"binthis",
"bintweet",
"junktweet",
"rmit",
"rmthis"... | 5,344,829 |
def analyze(geometry_filenames, mode='global', training_info=None, stride=None,
box_size=None, configs=None, descriptor=None, model=None,
format_=None, descriptors=None, save_descriptors=False,
save_path_descriptors=None, nb_jobs=-1, **kwargs):
"""
Apply ARISE to given list ... | 5,344,830 |
def get_params(name, seed):
"""Some default parameters.
Note that this will initially include training parameters that you won't need for metalearning since we have our own training loop."""
configs = []
overrides = {}
overrides["dataset_reader"] = {"lazy": True}
configs.append(Params(override... | 5,344,831 |
def rgb2hex(rgb):
"""Converts an RGB 3-tuple to a hexadeximal color string.
EXAMPLE
-------
>>> rgb2hex((0,0,255))
'#0000FF'
"""
return ('#%02x%02x%02x' % tuple(rgb)).upper() | 5,344,832 |
def path_regex(
path_regex: Union[str, re.Pattern], *, disable_stage_removal: Optional[bool] = False
):
"""Validate the path in the event against the given path pattern.
The following APIErrorResponse subclasses are used:
PathNotFoundError: When the path doesn't match.
Args:
path: A re... | 5,344,833 |
async def root():
"""Health check"""
return {"status": "OK"} | 5,344,834 |
def build_foreign_keys(
resources: Dict[str, dict],
prune: bool = True,
) -> Dict[str, List[dict]]:
"""Build foreign keys for each resource.
A resource's `foreign_key_rules` (if present) determines which other resources will
be assigned a foreign key (`foreign_keys`) to the reference's primary key:... | 5,344,835 |
def port_scan(ip):
"""Run a scan to determine what services are responding.
Returns nmap output in JSON format.
"""
# validate input
valid_ip = ipaddress.ip_address(ip)
# nnap requires a `-6` option if the target is IPv6
v6_flag = '-6 ' if valid_ip.version == 6 else ''
nmap_command = f'... | 5,344,836 |
def test_quoted_digits():
"""
Any value that is composed entirely of digits
should be quoted for safety.
CloudFormation is happy for numbers to appear as strings.
But the opposite (e.g. account numbers as numbers) can cause issues
See https://github.com/awslabs/aws-cfn-template-flip/issues/41
... | 5,344,837 |
def create_table(p, table_name, schema):
"""Create a new Prism table.
Parameters
----------
p : Prism
Instantiated Prism class from prism.Prism()
table_name : str
The name of the table to obtain details about. If the default value
of None is specified, details regarding fir... | 5,344,838 |
def get_args():
"""
Parses and processes args, returning the modified arguments as a dict.
This is to maintain backwards compatibility with the old of parsing
arguments.
"""
parser = make_parser()
args = parser.parse_args()
process_args(args)
return vars(args) | 5,344,839 |
def run_asm_pprinter(ir: gtirb.IR, args: Iterable[str] = ()) -> str:
"""
Runs the pretty-printer to generate an assembly output.
:param ir: The IR object to print.
:param args: Any additional arguments for the pretty printer.
:returns: The assembly string.
"""
asm, _ = run_asm_pprinter_with_... | 5,344,840 |
def fix_ccdsec(hdu):
""" Fix CCDSEC keywords in image extensions """
section_regexp = re.compile(SECTION_STRING)
# In unbinned space
ccdsec = _get_key_value(hdu, 'CCDSEC')
detsec = _get_key_value(hdu, 'DETSEC')
if None in [ccdsec, detsec]:
raise ValueError("CCDSEC {}; detsec {}".format... | 5,344,841 |
def reload(hdf):
"""Reload a hdf file, hdf = reload(hdf)"""
filename = hdf.filename
return load(filename) | 5,344,842 |
def test__add_obscon_as_predictors() -> None:
"""
Test `hsr4hci.training.add_obscon_as_predictors`.
"""
np.random.seed(42)
# Create an expected signal
expected_signal = np.zeros(100)
expected_signal[50] = 1
for i in range(5):
expected_signal = np.convolve(
expected_... | 5,344,843 |
def test_is_testrun_available(api_client, tr_plugin):
""" Test of method `is_testrun_available` """
tr_plugin.testrun_id = 100
api_client.send_get.return_value = {'is_completed': False}
assert tr_plugin.is_testrun_available() is True
api_client.send_get.return_value = {'error': 'An error occured'}... | 5,344,844 |
def read_image(im_name, n_channel, data_dir='', batch_size=1, rescale=None):
""" function for create a Dataflow for reading images from a folder
This function returns a Dataflow object for images with file
name containing 'im_name' in directory 'data_dir'.
Args:
im_name (... | 5,344,845 |
def build_optimizer(config, model):
"""
Build optimizer, set weight decay of normalization to 0 by default.
"""
skip = {}
skip_keywords = {}
if hasattr(model, 'no_weight_decay'):
skip = model.no_weight_decay()
if hasattr(model, 'no_weight_decay_keywords'):
skip_keywords = mod... | 5,344,846 |
def do_monitor_tcp_check_list(client, args):
""" List monitor items """
kwargs = {}
if args.tenant:
kwargs['tenant'] = args.tenant
if args.system:
kwargs['is_system'] = True
monitors = client.tcpcheck.list(**kwargs)
utils.print_list(monitors, client.tcpcheck.columns) | 5,344,847 |
def publish() -> None:
"""Publish project."""
check_version()
raise NotImplementedError("Publishing hasn't been implemented yet.") | 5,344,848 |
def powderrays(dlist, ki=None, phi=None):
"""Calculate powder ray positions."""
instr = session.instrument
if ki is None:
mono = instr._attached_mono
ki = to_k(mono.read(), mono.unit)
for line in check_powderrays(ki, dlist, phi):
session.log.info(line) | 5,344,849 |
def ising2d_worm(T_range, mcsteps, L):
"""T = temperature [K]; L = Length of grid."""
def new_head_position(worm, lattice):
"""
Extract current worm head position indices,
then randomly set new worm head position index.
lattice.occupied points to either lattice.bonds_x or latti... | 5,344,850 |
def rcrgb_plot(a,out=None) :
""" Plot logg classification from bitmask
"""
b=bitmask.ParamBitMask()
rgb=np.where((a['PARAMFLAG'][:,1] & b.getval('LOGG_CAL_RGB')) > 0)[0]
rc=np.where((a['PARAMFLAG'][:,1] & b.getval('LOGG_CAL_RC')) > 0)[0]
ms=np.where((a['PARAMFLAG'][:,1] & b.getval('LOGG_CAL_MS')... | 5,344,851 |
def valid_chapter_name(chapter_name):
"""
判断目录名称是否合理
Args:
chapter_name ([type]): [description]
"""
for each in ["目录"]:
if each in chapter_name:
return False
return True | 5,344,852 |
def lex_min(perms: Iterable[Perm]) -> Tuple[Perm, ...]:
"""Find the lexicographical minimum of the sets of all symmetries."""
return min(all_symmetry_sets(perms)) | 5,344,853 |
def migrate_service(cluster, service, command, success_string, timeout, region):
"""Run a single task based on service's task definition in AWS ECS and wait for it to stop with success."""
migrate_service_func(cluster, service, command, success_string, timeout, region) | 5,344,854 |
def subfield(string, delim, occurrence):
"""
function to extract specified occurence of subfield from string
using specified field delimiter
eg select subfield('abc/123/xyz','/',0) returns 'abc'
eg select subfield('abc/123/xyz','/',1) returns '123'
eg select subfield('abc/123/xyz','/',2) retu... | 5,344,855 |
def in_hull(points, hull):
"""
Test if points in `p` are in `hull`
`p` should be a `NxK` coordinates of `N` points in `K` dimensions
`hull` is either a scipy.spatial.Delaunay object or the `MxK` array of the
coordinates of `M` points in `K`dimensions for which Delaunay triangulation
will be computed
"""
... | 5,344,856 |
def sample_random(X_all, N):
"""Given an array of (x,t) points, sample N points from this."""
set_seed(0) # this can be fixed for all N_f
idx = np.random.choice(X_all.shape[0], N, replace=False)
X_sampled = X_all[idx, :]
return X_sampled | 5,344,857 |
def write_text_list_to_file(text_list, writer):
"""
Merge a list of texts into a single text file
Args:
text_list: A list of texts (List[String])
writer: A file writer
"""
try:
for text in text_list:
writer.writelines(text)
except Exception as e:
logg... | 5,344,858 |
def hand_rankings(class_counts):
"""Print a table of the probability of various hands
class_counts: histogram of hand classifications
"""
total = sum(class_counts.values())
print("Prob ", "Classification")
print("------", "--------------")
for classification in PokerHand.classifications + [... | 5,344,859 |
def read(db,
query: Optional[dict] = None,
pql: any = None,
order_by: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
disable_count_total: bool = False,
**kwargs):
"""Read data from DB.
Args:
db (MontyCollec... | 5,344,860 |
def check_horizontal(board: list) -> bool:
"""
Function check if in each line are unique elements.
It there are function return True. False otherwise.
>>> check_horizontal(["**** ****",\
"***1 ****",\
"** 3****",\
"* 4 1****"... | 5,344,861 |
def _update(data, update):
"""Update *data* identified by *name* with *value*.
Args:
data (munch.Munch): data to update
update (str): update to apply
Raises:
RuntimeError: on error
"""
try:
name, value = update.split('=')
except ValueError:
raise Runtim... | 5,344,862 |
def IsDir(msg=None):
"""Verify the directory exists."""
def f(v):
if os.path.isdir(v):
return v
else:
raise Invalid(msg or 'not a directory')
return f | 5,344,863 |
def update_events(dt: float, pos_x: float, pos_y: float, dir_x: float, dir_y: float, plane_x: float, plane_y: float):
""" Updates player position in response to user input.
"""
for e in pygame.event.get():
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_ESCAPE:
pygame.q... | 5,344,864 |
def test_config_controller_failed(hass, mock_ctrl, mock_scanner):
"""Test for controller failure."""
config = {
'device_tracker': {
CONF_PLATFORM: unifi.DOMAIN,
CONF_USERNAME: 'foo',
CONF_PASSWORD: 'password',
}
}
mock_ctrl.side_effect = APIError(
... | 5,344,865 |
def deg_to_xyz(lat_deg, lon_deg, altitude):
"""
http://www.oc.nps.edu/oc2902w/coord/geodesy.js
lat,lon,altitude to xyz vector
input:
lat_deg geodetic latitude in deg
lon_deg longitude in deg
altitude altitude in km
output:
returns vector x 3 long ECEF in... | 5,344,866 |
def remove_unused_colours(ip, line_colours):
"""
>>> remove_unused_colours(np.array([[0,0,3], [1,5,1], [2,0,6], [2,2,2],[4,4,0]]), {2, 4})
array([[0, 0, 0],
[0, 0, 0],
[2, 0, 0],
[2, 2, 2],
[4, 4, 0]])
"""
#get a list of all unique colours
all_colours... | 5,344,867 |
def extract_info(spec):
"""Extract information from the instance SPEC."""
info = {}
info['name'] = spec.get('InstanceTypeId')
info['cpu'] = spec.get('CpuCoreCount')
info['memory'] = spec.get('MemorySize')
info['nic_count'] = spec.get('EniQuantity')
info['disk_quantity'] = spec.get('DiskQuan... | 5,344,868 |
def sum_values(**d):
# doc string 예제. git commit 메시지 쓰듯이 쓰면 된다
"""dict의 values를 더한 값을 리턴
key는 뭐가 들어오던지 말던지 신경 안 쓴다.
"""
return sum_func(*d.values()) | 5,344,869 |
def parse_title(title):
"""Parse strings from lineageos json
:param title: format should be `code - brand phone`
"""
split_datum = title.split(' - ')
split_name = split_datum[1].split(' ')
device = split_datum[0]
brand = split_name[0]
name = ' '.join(split_name[1:])
return [brand,... | 5,344,870 |
def addCountersTransactions(b):
"""Step 2 : The above list with count as the last element should be
[
[1, 1, 0, 1],
[0, 0, 0, 4],
[1, 1, 1, 3]
]
converted to the following way
[
[1, 1, 0, 1, 0],
[1, 1, 1, 3, 4]
]
with cnt 1 and cnt 2 for anti-mirroring tec... | 5,344,871 |
def aggregate_layers(
hidden_states: dict, mode: typing.Union[str, typing.Callable]
) -> np.ndarray:
"""Input a hidden states dictionary (key = layer, value = 2D array of n_tokens x emb_dim)
Args:
hidden_states (dict): key = layer (int), value = 2D PyTorch tensor of shape (n_tokens, emb_dim)
R... | 5,344,872 |
def get_bg_stat_info(int_faces, adj_list, face_inds, face_inds_new):
"""
Out put list of faces and list of verts for each stat.
"""
stat_faces = []
stat_verts = []
for k in range(len(int_faces)):
# Check if face already exists.
if int_faces[k] != 0:
continue
... | 5,344,873 |
def _build_server_data():
"""
Returns a dictionary containing information about the server environment.
"""
# server environment
server_data = {
'host': socket.gethostname(),
'argv': sys.argv
}
for key in ['branch', 'root']:
if SETTINGS.get(key):
server_d... | 5,344,874 |
def config_data() -> dict:
"""Dummy config data."""
return {
"rabbit_connection": {
"user": "guest",
"passwd": "guest",
"host": "localhost",
"port": 5672,
"vhost": "/",
},
"queues": {"my_queue": {"settings": {"durable": True}, "... | 5,344,875 |
def write_layers(layers):
"""
"""
ext = os.path.splitext(layers_file)
if ext == '.pkl':
# pickle
pickle.dump(layers, open(layers_file, 'w'))
else:
# write image file
layers.data = numpy.asarray(layers.data, dtype=layers_data_type)
layers.write(file=layers_... | 5,344,876 |
def copy_linear(net, net_old_dict):
"""
Copy linear layers stored within net_old_dict to net.
"""
net.linear.weight.data = net_old_dict["linears.0.weight"].data
net.linear.bias.data = net_old_dict["linears.0.bias"].data
return net | 5,344,877 |
async def read_book(request: Request) -> dict:
"""Read single book."""
data = await request.json()
query = readers_books.insert().values(**data)
last_record_id = await database.execute(query)
return {"id": last_record_id} | 5,344,878 |
def setup_dev():
"""Runs the set-up needed for local development."""
return setup_general() | 5,344,879 |
def countAllAnnotationLines(
mpqa_dir="mpqa_dataprocessing\\database.mpqa.cleaned", doclist_filename='doclist.2.0'
):
"""
It counts all annotation lines available in all documents of a corpus.
:return: an integer
"""
m2d = mpqa2_to_dict(mpqa_dir=mpqa_dir)
mpqadict = m2d.corpus_to_dict(doclis... | 5,344,880 |
def get_article_score(token, article_id):
"""
查看文章
:param article_id:
:param token:
:return:
"""
data = {
"id": article_id,
"token": token
}
try:
res = requests.post("https://information.17wanxiao.com/cms/api/info/detail", data=data).json()
if res['res... | 5,344,881 |
def convergence(report: Report, **kwargs):
"""
Function that displays the convergence using a antco.report.Report object.
Parameters
----------
report: antco.report.Report
antco.report.Report instance returned by the antco.run() function.
**kwargs
figsize: tuple, default=(8, 5)... | 5,344,882 |
def scene():
""" Check that the scene is valid for submission and creates a report """
xrs.validation_report.new_report()
valid = True
# Start by getting into object mode with nothing selected
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.select_all(action='DESELECT')
if (xrs.collection.collecti... | 5,344,883 |
def ca_set_container_policies(h_session, h_container, policies):
"""
Set multiple container policies.
:param int h_session: Session handle
:param h_container: target container handle
:param policies: dict of policy ID ints and value ints
:return: result code
"""
h_sess = CK_SESSION_HAND... | 5,344,884 |
def update_records() -> None:
""" Updates the records page. """
records = load_file("records")
times, people = records["records"], records["people"]
# If graduated, add to alumni list
graduated = [person for person in people if datetime.now() > summer(person[-1])]
if len(graduated) > 0:
... | 5,344,885 |
def run_trial(benchmark):
"""Runs the benchmark once and returns the elapsed time."""
args = ['.build/debug/slox', join('test', 'benchmark', benchmark + '.lox')]
proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
out = out.decode("utf-8").replace('\r\n', '\n')
# Remove... | 5,344,886 |
def extend(arr, num=1, log=True, append=False):
"""Extend the given array by extraplation.
Arguments
---------
arr <flt>[N] : array to extend
num <int> : number of points to add (on each side, if ``both``)
log <bool> : extrapolate in log-space
append <bool> :... | 5,344,887 |
def to_relative(path, root, relative):
"""Converts any absolute path to a relative path, only if under root."""
if sys.platform == 'win32':
path = path.lower()
root = root.lower()
relative = relative.lower()
if path.startswith(root):
logging.info('%s starts with %s' % (path, root))
path = os.p... | 5,344,888 |
def do_associate_favorite(parser, token):
"""
@object - object to return the favorite count for
"""
try:
tag, node, user = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires one argument" % token.contents.split()[0]
return AssociateFa... | 5,344,889 |
def test_module_in_place(testdir):
"""Make sure the run in place option works"""
# copy_example copies what is IN the given directory, not the directory itself...
testdir.copy_example("testmodule")
# Moving module to make sure we can run in place,
# by making sure the module name in module.yml is i... | 5,344,890 |
def parse_cookie(cookie: Type[BaseModel]) -> Tuple[List[Parameter], dict]:
"""Parse cookie model"""
schema = get_schema(cookie)
parameters = []
components_schemas = dict()
properties = schema.get('properties')
definitions = schema.get('definitions')
if properties:
for name, value in... | 5,344,891 |
def p_cast_operator(p):
"""
value : LEFT_PARENTHESIS value RIGHT_PARENTHESIS value %prec CCAST
"""
p[0] = '%s%s%s%s' % (p[1], p[2], p[3], p[4]) | 5,344,892 |
def bdev_nvme_add_error_injection(client, name, opc, cmd_type, do_not_submit, timeout_in_us,
err_count, sct, sc):
"""Add error injection
Args:
name: Name of the operating NVMe controller
opc: Opcode of the NVMe command
cmd_type: Type of NVMe command. Va... | 5,344,893 |
def tetheredYN(L0, KxStar, Rtot, Kav, fully=True):
""" Compare tethered (bispecific) vs monovalent """
if fully:
return polyc(L0, KxStar, Rtot, [[1, 1]], [1.0], Kav)[2][0] / \
polyfc(L0 * 2, KxStar, 1, Rtot, [0.5, 0.5], Kav)[0]
else:
return polyc(L0, KxStar, Rtot, [[1, 1]], [1.0... | 5,344,894 |
def __add_docker_image(aws_session, compose_config, service_name, tag):
"""
Adds the Docker image to a service in a docker-compose config.
The image is only added if an existing image doesn't exist for the service.
:param aws_session: The AWS session.
:param compose_config: The docker-compose config... | 5,344,895 |
def test_timestamp_spacing_one_timestamp(times):
"""An index with only one timestamp has uniform spacing."""
assert_series_equal(
time.spacing(times[[0]], times.freq),
pd.Series(True, index=[times[0]])
) | 5,344,896 |
def valid_payload(request):
"""
Fixture that yields valid data payload values.
"""
return request.param | 5,344,897 |
def lookup_content(path, source_id):
"""
Look for a filename in the form of:
ARCHIVE_SOURCEID.[extension]
"""
content_filename = None
files = [f for f in os.listdir(path) if not f.endswith(".xml")]
for f in files:
tokens = os.path.splitext(f)[0].split("_")
if len(tokens) == 0... | 5,344,898 |
def external(pgm, inp, out, cor, tim=5):
"""
The external checker is used to check for outputs using an external
program that reads the input and the generated output and writes
to stdout the veredict. If the program runs for more than tim seconds,
'IE' is returned. 'IE' also returne... | 5,344,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.