content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def print_comparison(map, conn):
"""map: (study | ohdsi) -> to_column -> value -> count
"""
for column in map['ohdsi'].keys():
concept_name = _get_concept_name(column, conn)
if (len(map['ohdsi'][column].keys()) > MAX_CONCEPTS_TO_LIST):
# STATS: too many values to list, run ... | 5,323,600 |
def test_split(data, test_size=0.3):
"""
Split data to train and test subsets.
:param data: Array like list.
:param test_size: Size of test subset.
:return: Returns tuple of matrix like subsets (train_subset, test_subset).
"""
return sklearn.model_selection.train_test_split(data, test_size) | 5,323,601 |
def meet_players(players):
"""создаем игроков"""
if len(players)>0: players.clear()
players.append(dict(name = "Компьютер", fool = 0,last = False,hand = []))
name = ""
while name =="": name = input("Введите ваше имя: ")
### name = "Alex"###
players.append(dict(name = name, fool = 0, last = F... | 5,323,602 |
def eye_movements_question(buffer, remaining_lines):
"""
Parses the eye movements for viewing a single question
"""
buffer.append('MSG ' + trial_metadatas.get('timestamp_end_lim') + ' DISPLAY ON\n')
buffer.append('MSG ' + trial_metadatas.get('timestamp_end_lim') + ' SYNCTIME\n')
button_number ... | 5,323,603 |
def unpack_remotedata(o, byte_keys=False, myset=None):
""" Unpack WrappedKey objects from collection
Returns original collection and set of all found keys
Examples
--------
>>> rd = WrappedKey('mykey')
>>> unpack_remotedata(1)
(1, set())
>>> unpack_remotedata(())
((), set())
>>... | 5,323,604 |
def zenith_azimuth_from_spatial_freq(fx, fy, fz, wavelen=550e-6, atype='deg', tol=1e-12):
"""returns the zenith and azimuth angles associated with spatial frequencies
Parameters
----------
fx : float
spatial frequency along x-axis (unit=cycles/mm)
fy : float
spatial frequency along ... | 5,323,605 |
def xscontrol_Vars(*args):
"""
Args:
pilot(Handle_IFSelect_SessionPilot)
Returns:
static Handle_XSControl_Vars
Returns the Vars of a SessionPilot, it is brought by Session
it provides access to external variables
"""
return _XSControl.xscontrol_Vars(*args) | 5,323,606 |
def swing_twist_decomposition(q, twist_axis):
""" code by janis sprenger based on
Dobrowsolski 2015 Swing-twist decomposition in Clifford algebra. https://arxiv.org/abs/1506.05481
"""
q = normalize(q)
#twist_axis = np.array((q * offset))[0]
projection = np.dot(twist_axis, np.array([q[1], q[2... | 5,323,607 |
def DatasetFileName(filename):
"""Returns location of `filename` within --dataset_dir`."""
return os.path.join(dataset_dir, filename) | 5,323,608 |
def resolve_s1_slc(identifier, download_url, project):
"""Resolve S1 SLC using ASF datapool (ASF or NGAP). Fallback to ESA."""
# determine best url and corresponding queue
vertex_url = "https://datapool.asf.alaska.edu/SLC/SA/{}.zip".format(
identifier)
r = requests.head(vertex_url, allow_redire... | 5,323,609 |
def equivalent_gaussian_Nsigma_from_logp(logp):
"""Number of Gaussian sigmas corresponding to tail log-probability.
This function computes the value of the characteristic function of a
standard Gaussian distribution for the tail probability equivalent to the
provided p-value, and turns this value into ... | 5,323,610 |
def test_y1_uncertainties_spline_with_constant_distribution():
"""
"""
# old size
m = 5
# new size
n = 6
# bin edges
x_old = np.linspace(0., 1., m+1)
x_new = np.array([-.3, -.09, 0.11, 0.14, 0.2, 0.28, 0.73])
subbins = np.array([-.3, -.09, 0., 0.11, 0.14, 0.2, 0.28, 0.4, 0.6,... | 5,323,611 |
def fetch_ratings():
"""Fetches ratings from the given URL."""
url = "http://files.grouplens.org/datasets/movielens/ml-25m.zip"
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir, "download.zip")
logging.info(f"Downloading zip file from {url}")
urlretrieve(url, ... | 5,323,612 |
def cop(session):
"""Run all pre-commit hooks."""
session.install("pip==20.3.1")
session.install(".[all]", "--use-deprecated=legacy-resolver")
session.run("pre-commit", "install")
session.run("pre-commit", "run", "--show-diff-on-failure", "--all-files") | 5,323,613 |
def _parse_affected(text):
"""Extract the affected releases, services, and other software
Args:
text: the text version of the security note
Returns:
a list of the affected releases
"""
valid_releases = ['austin', 'bexar', 'cactus', 'diablo', 'essex',
'folsom', 'gri... | 5,323,614 |
def _window_view(a, window, step = None, axis = None, readonly = True):
"""
Create a windowed view over `n`-dimensional input that uses an
`m`-dimensional window, with `m <= n`
Parameters
-------------
a : Array-like
The array to create the view on
... | 5,323,615 |
def approveReport(id):
"""
Function to approve a report
"""
# Approve the doc source entity record
sgtable = s3db.stats_group
sgt_table = s3db.stats_group_type
resource = s3db.resource("stats_group", id=id, unapproved=True)
resource.approve()
# find the type of report that we ha... | 5,323,616 |
def _maybe_promote_geometry(geom):
""" Either promote the geometry to a Multi-geometry, or return input"""
promoter = _promotion_dispatch.get(geom.type, lambda x: x[0])
return promoter([geom]) | 5,323,617 |
def cut(
x: numpy.ndarray,
bins: range,
right: bool,
labels: None,
precision: int,
include_lowest: bool,
):
"""
usage.xarray: 1
"""
... | 5,323,618 |
def preprocess_input(frames):
"""Resize and subtract mean from video input
Args:
frames (tf.Tensor): Video frames to preprocess. Expected shape
(frames, rows, columns, channels).
Returns:
A TF Tensor.
"""
# Reshape to 128x171
frames = tf.ima... | 5,323,619 |
def register_alias(alias):
"""
Appends text to 'employee_registry.txt'
"""
with open(os.path.join(ROOT_DIR, 'employee_registry.txt'), 'a') as f:
f.write('{0} was here!\t{1}\n'.format(alias, date.today()).expandtabs(50)) | 5,323,620 |
def get_cache_info(path: Path) -> CacheInfo:
"""Return the information used to check if a file is already formatted or not."""
stat = path.stat()
return stat.st_mtime, stat.st_size | 5,323,621 |
def notify_any_failure(task, exception):
# type: (luigi.Task) -> None
"""
Will be called directly after a successful execution
and is used to update any relevant metrics
"""
# Where to store the metrics:
registry = CollectorRegistry()
# Generate metrics:
record_task_outcome(r... | 5,323,622 |
def gmm_component_contributions_to_message_length(responsibilities,
log_likelihoods,
covs, weights):
"""
Return the component-wise contributions to the message length.
"""
K, N = responsibilities.shape
... | 5,323,623 |
def validate(request):
"""Method for validating a common request."""
validation = versioning.validate(request)
if validation['status'] != 'ok':
return validation
cursor = mysql.connection.cursor()
validation = player.validate(request, cursor)
if validation['status'] != 'ok':
re... | 5,323,624 |
def copy_clipboard(name,flag):
"""For directly cutting paste to different pahes like powerpoint etc"""
new=""
for i in name:
if i==".":
break
new+=i
if flag==1:
stri="xclip -in -selection c "+new+".html"
else:
stri="xclip -in -selection c "+new+".rtf"
os.system(stri) | 5,323,625 |
def submit_workload(the_hosts, dir_name, db, workload, the_time, target = None):
"""
Schedules the workload.
Note: we cannot use ycsb.workload, because it is decorated
"""
database = get_db(db)
load = get_workload(workload)
def inner_submit_workload():
with cd(dir_name):
... | 5,323,626 |
def text_to_list(text):
""" Convert the paper into a list of preformatted sentences. """
s = symbol.substitute_symbol(text)
# Convert all characters to lowercase
s = s.lower()
# Convert text into list of paragraphs
a = s.split("\r\n")
b = ignoretopics.ignore_topics(a)
b = accenter.deacc... | 5,323,627 |
def train(datafile, outputfile, **kwargs):
"""Train varigram language model with VariKN
Positional arguments:
datafile -- Filename for training corpus
outpufile -- Filename for trained model
Keyword arguments:
optdata -- Filename for optimization data
norder -- Limit model order (0... | 5,323,628 |
def make_anagram_dict(filename):
"""Takes a text file containing one word per line.
Returns a dictionary:
Key is an alphabetised duple of letters in each word,
Value is a list of all words that can be formed by those letters"""
result = {}
fin = open(filename)
for line in fin:
w... | 5,323,629 |
def test_hierarchical_seeding(RefSimulator):
"""Changes to subnetworks shouldn't affect seeds in top-level network"""
def create(make_extra, seed):
objs = []
with nengo.Network(seed=seed, label='n1') as model:
objs.append(nengo.Ensemble(10, 1, label='e1'))
with nengo.Net... | 5,323,630 |
def group_property_types(row : str) -> str:
"""
This functions changes each row in the dataframe to have the one
of five options for building type:
- Residential
- Storage
- Retail
- Office
- Other
this was done to reduce the dimensionality down to the top building
types.
... | 5,323,631 |
def parseLbannLayer(l, tensorShapes, knownNodes=[]):
"""
Parses a given LBANN layer and returns the equivalent ONNX expressions needed to be represent the layer.
Args:
l (lbann_pb2.Layer): A LBANN layer to be converted.
tensorShapes (dict): Shapes of known named tensors.
knownNodes ... | 5,323,632 |
def load_lang(language, phon=False, segment=False, load_morph=True, verbose=False):
"""Load a language's morphology.
@param language: a language label
@type language: string
"""
morpho.load_lang(language, phon=phon, segment=segment, load_morph=load_morph,
verbose=verbose) | 5,323,633 |
def write_simple_templates(n_rules, body_predicates=1, order=1):
"""Generate rule template of form C < A ^ B of varying size and order"""
text_list = []
const_term = "("
for i in range(order):
const_term += chr(ord('X') + i) + ","
const_term = const_term[:-1] + ")"
write_string = "{0} ... | 5,323,634 |
def get_datatoken_minter(datatoken_address):
"""
:return: Eth account address of the Datatoken minter
"""
dt = get_dt_contract(get_web3(), datatoken_address)
publisher = dt.caller.minter()
return publisher | 5,323,635 |
def GetAssetCreationTime(primStack, assetIdentifier):
"""Finds the weakest layer in which assetInfo.identifier is set to
'assetIdentifier', and considers that an "asset-defining layer". We then
effectively consult the asset resolver plugin to tell us the creation
time for the asset, based on the layer.... | 5,323,636 |
def symplectic_map_personal(x, px, step_values, n_iterations, epsilon, alpha, beta, x_star, delta, omega_0, omega_1, omega_2, action_radius, gamma=0.0):
"""computation for personal noise symplectic map
Parameters
----------
x : ndarray
x initial condition
px : ndarray
px... | 5,323,637 |
def wl_offset(input_table, **kwargs):
"""
Derives wavelength offsets for white dwarf exposures.
Cross-correlates flux and net from white dwarf exposures against one another to derive
offsets
Parameters
----------
input_table : abscal.common.exposure_data_table.AbscalDataTable
... | 5,323,638 |
def GetRevertedRevision(message):
"""Parse message to get the reverted revision if there is one."""
lines = message.strip().splitlines()
if not lines:
return None
if not lines[0].lower().startswith('revert'):
return None
for line in reversed(lines): # pragma: no cover
# TODO: Handle cases where... | 5,323,639 |
def line_center(p0, p1):
"""
given two points p0, p1 inside a poincare disk
find the centre and radius of the arc that defines a line through them
https://en.wikipedia.org/wiki/Poincar%C3%A9_disk_model#Analytic_geometry_constructions_in_the_hyperbolic_plane
"""
u1, u2, u3 = p0
v1, v2, v3 = p... | 5,323,640 |
def infer_decimals(value):
"""
Devuelve la cantidad de cifras decimales del valor, aplicando una heurística de corrección
previa.
Para valores del estilo 1.0000000000000001, (común al serializar números en punto flotante),
se los trunca a 17 - N dígitos, siendo N la cantidad de dígitos enteros del ... | 5,323,641 |
def desalt_smiles(row, smilesfield, desalter):
"""This function creates desalted smiles for a pandas dataframe row
row : row of the dataframe
smilesfiel : str (name of the smiles field in the row)
desalter : instance of Smiles_desalter class
reaction_list : list of dictionaries (rdkit reaction ... | 5,323,642 |
def mesh_vertex_2_coloring(mesh):
"""Try to color the vertices of a mesh with two colors only without adjacent vertices with the same color.
Parameters
----------
mesh : Mesh
A mesh.
Returns
-------
dict, None
A dictionary with vertex keys pointing to colors, if two-colorab... | 5,323,643 |
def tokens_to_smiles(tokens: List[str], special_tokens: List[str] = BAD_TOKS) -> str:
"""Combine tokens into valid SMILES string, filtering out special tokens
Args:
tokens: Tokenized SMILES
special_tokens: Tokens to not count as atoms
Returns:
SMILES representation of provided token... | 5,323,644 |
def test_slice_negative_from():
"""Test that a negative from value starts cutting at the end minus from."""
assert apply_slicing('012345', {'from': -2}) == '45' | 5,323,645 |
def build(
url_service, from_file, only_bundle, env_file, current, stash, watch, name, local
):
"""Freeze and build a runtime for your proyect into the server"""
c = client.from_file(from_file, url_service)
# prepare secrets
try:
pv = c.get_private_key()
except errors.PrivateKeyNotFound:... | 5,323,646 |
def _get_port_by_uuid(client, port_uuid, **params):
"""Return a neutron port by UUID.
:param client: A Neutron client object.
:param port_uuid: UUID of a Neutron port to query.
:param params: Additional parameters to pass to the neutron client
show_port method.
:returns: A dict describing t... | 5,323,647 |
def propagate_task_state_change(cycle_task):
"""Propagates change of cycle task state to cycle task group and
workflow cycle.
"""
cycle_task_group = cycle_task.cycle_task_group
if all(task.state == cycle_task.state
for task in cycle_task_group.cycle_tasks):
cycle_task_group.state = cycle_task.sta... | 5,323,648 |
def is_unit_by_year(text: str) -> bool:
"""
是否是以年为计量单位
@param text:
@return:
@rtype: bool
"""
log.info(f'invoke method -> is_unit_by_year(), time unit text: {text}')
try:
unit = DateUnit(text.strip())
except ValueError as e:
log.error(str(e))
return False
... | 5,323,649 |
def merge_leading_dims(array_or_tensor, n_dims=2):
"""Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of d... | 5,323,650 |
def delete_private_key(account):
"""Deletes the private key for the given account."""
service_name = _get_keyring_service_name(account.name)
keyring.delete_password(service_name, account.address) | 5,323,651 |
def export_release(dataroot='/data/sets/nuimages', version: str = 'v1.0') -> None:
"""
This script tars the image and metadata files for release on https://www.nuscenes.org/download.
:param dataroot: The nuImages folder.
:param version: The nuImages dataset version.
"""
# Create export folder.
... | 5,323,652 |
def get_genresults(recipe: MyRecipe) -> tp.Generator:
"""Yield the contribution name, generator name and the dictionary expression of the structure."""
for con_name, con in recipe.contributions.items():
for gen_name, gen in con.generators.items():
yield dict(name=gen_name, con_name=con_name,... | 5,323,653 |
def mock_elgato_config_flow() -> Generator[None, MagicMock, None]:
"""Return a mocked Elgato client."""
with patch(
"homeassistant.components.elgato.config_flow.Elgato", autospec=True
) as elgato_mock:
elgato = elgato_mock.return_value
elgato.info.return_value = Info.parse_raw(load_f... | 5,323,654 |
def ootf_inverse_HLG_BT2100_1(F_D, L_B=0, L_W=1000, gamma=None):
"""
Defines *Recommendation ITU-R BT.2100* *Reference HLG* inverse opto-optical
transfer function (OOTF / OOCF) as given in *ITU-R BT.2100-1*.
Parameters
----------
F_D : numeric or array_like
:math:`F_D` is the luminance ... | 5,323,655 |
def test_cog_translate_tags():
"""Should work as expected (create cogeo file)."""
runner = CliRunner()
with runner.isolated_filesystem():
cog_translate(raster_path_tags, "cogeo.tif", jpeg_profile, quiet=True)
with rasterio.open("cogeo.tif") as src:
assert src.tags()["OVR_RESAMPLI... | 5,323,656 |
def get_categories_for_area(area_id):
"""
Return a list of rows from the category table that all contain the given area.
"""
return request_or_fail("/area/" + str(area_id) + "/category") | 5,323,657 |
def iou(box1, box2, x1y1x2y2=True):
""" iou = intersection / union """
if x1y1x2y2:
# min and max of 2 boxes
mx = min(box1[0], box2[0])
Mx = max(box1[2], box2[2])
my = min(box1[1], box2[1])
My = max(box1[3], box2[3])
w1 = box1[2] - box1[0]
h1 = box1[3] -... | 5,323,658 |
def summarize_worm_file(w):
"""
Print the header information of a worm file.
:param w: a WormFile object
"""
print("Worm header information:")
for k,v in w.header.items():
print(u' {0}:\t{1}'.format(k, v).expandtabs(20)) | 5,323,659 |
def register_handlers(dp) -> None:
"""Registers bot handlers."""
register_start_handler(dp)
register_menu_handler(dp)
register_catalog_product_detail_handler(dp)
register_handler_cart(dp)
register_handlers_location(dp)
register_handler_waiting_email(dp)
register_handler_delivery(dp)
... | 5,323,660 |
def mock_get_data(mocker, remote_path):
"""Mock the get_data funcion of SegmentClient class.
Arguments:
mocker: The mocker fixture.
remote_path: The remote path of data.
Returns:
The patched mocker and response data.
"""
response_data = [RemoteData(remote_path=remote_path)... | 5,323,661 |
def gen_string(**kwargs) -> str:
"""
Generates the string to put in the secrets file.
"""
return f"""\
apiVersion: v1
kind: Secret
metadata:
name: keys
namespace: {kwargs['namespace']}
type: Opaque
data:
github_client_secret: {kwargs.get('github_client_secret')}
... | 5,323,662 |
def draw_one_group_members(applications, winners_num, set_just=True,
**kwargs):
"""internal function
decide win (waiting) or lose for each group
"""
target_status = \
kwargs['target_status'] if 'target_status' in kwargs else "pending"
win_status = \
kwa... | 5,323,663 |
def get_props_from_row(row):
"""Return a dict of key/value pairs that are props, not links."""
return {k: v for k, v in row.iteritems() if "." not in k and v != ""} | 5,323,664 |
def generate_url(resource, bucket_name, object_name, expire=3600):
"""Generate URL for bucket or object."""
client = resource.meta.client
url = client.generate_presigned_url(
"get_object",
Params={"Bucket": bucket_name, "Key": object_name},
ExpiresIn=expire,
)
return url | 5,323,665 |
def test_interp_dense_grid_from_sparse_insufficient_points_simplex() -> None:
"""Try to interpolate a dense grid using an insufficient number of samples.
Attempts interpolation with 2 data points (need at least 4).
"""
bev_img: NDArrayByte = np.zeros((10, 10, 3), dtype=np.uint8)
points: NDArrayInt ... | 5,323,666 |
def khal_list(
collection,
daterange: Iterable[str] = None,
conf: dict = None,
agenda_format=None,
day_format: str=None,
once=False,
notstarted: bool = False,
width: bool = False,
env=None,
datepoint=None,
):
"""returns a list of all events in `daterange`"""
assert datera... | 5,323,667 |
def get_current_time(tzinfo=timezone.utc):
"""Get current time."""
return datetime.utcnow().replace(tzinfo=tzinfo) | 5,323,668 |
def F7(x):
"""Easom function"""
s = -math.cos(x[0])*math.cos(x[1])*math.exp(-(x[0] - math.pi)**2 - (x[1]-math.pi)**2)
return s | 5,323,669 |
def get_local_real_format():
"""
Returns : char **rf,int *rflen
*args :
C prototype: int cbf_get_local_real_format (char ** real_format );
CBFLib documentation:
DESCRIPTION
cbf_get_local_integer_byte_order returns the byte order of integers
on the machine on which the API is being... | 5,323,670 |
def zaxis_to_world(kpt: torch.Tensor):
"""Transform kpt from 2D+Z to 3D Real World Coordinates (RWC) for ITOP Dataset
Args:
kpt (np.ndarray): Array containing keypoints to transform
Returns:
np.ndarray: Converted keypoints
"""
tmp = kpt.clone()
tmp[..., 0] = (tmp[..., 0].clone... | 5,323,671 |
def invoke_IOError():
"""
Raised when an I/O operation (such as a print statement,
the built-in open() function or a method of a file object) fails for an I/O-related reason,
e.g., “file not found” or “disk full”.
"""
try:
a = open("unexistant.txt", 'r')
except IOError as e:
... | 5,323,672 |
def mock_response(req, resp_obj, resp_code):
""" Mock response for MyHTTPSHandler
"""
resp = urllib2.addinfourl(StringIO(resp_obj),
'This is a mocked URI!',
req.get_full_url())
resp.code = resp_code
resp.msg = "OK"
return resp | 5,323,673 |
def update_resolution_report(domain, report=None, updated=None):
"""Update the resolution report for a domain."""
if report is None:
report = {}
if updated is None:
updated = datetime.datetime.now()
db.set('resolution_report:{}'.format(domain), report)
db.set(
'resolution_rep... | 5,323,674 |
def merge_to_and_fro_3_1(sbox):
"""merge_to_and_fro_3_1"""
# A (--o------o---x------x
# ( \ / /
# B (---o--x---o----------
# 2 34 5 67 8 90 1
init_merge_to_and_fro_3(sbox, mod_9=False, mod_10=False)
symmetric_merge(sbox, 'B', 'A',
expect_changes=[],
... | 5,323,675 |
def test_list_as_anonymous_user(default_client):
"""Tests if an anonymous user can list groups"""
url = _get_group_url()
response = default_client.get(url)
assert response.status_code == status.HTTP_200_OK | 5,323,676 |
def http_login(request):
"""
Called after successfull basic HTTP authentication and check if user filled
his profile.
"""
logger.debug('Request full path: %s', request.get_full_path())
redirection = ""
# Should we redirect after login ?
if "next" in request.GET:
qr = request.GET... | 5,323,677 |
def run_tests_from_command_line():
"""
Run the tests in Maya standalone mode
"""
maya.standalone.initialize()
# Make sure all paths in PYTHONPATH are also in sys.path
# When a Maya module is loaded, the scripts folder is added to PYTHONPATH, but it doesn't seem to be added
# sys.path. So w... | 5,323,678 |
def py_func_bernoulli(input):
"""
Binormial python function definition
"""
prob_array = sigmoid(np.array(input))
sample = np.random.binomial(1, prob_array)
return sample | 5,323,679 |
def test_create_proxy_class():
"""
Test the create_proxy_class function for logging, and exceptions.
"""
base_name = 'base_name'
proxy = create_proxy_class(base_name)
setattr(proxy, 'v1', 'my_attr')
assert proxy.v1 == 'my_attr'
message = 'Invalid version `%s` for `%s`' % ('v2', base_... | 5,323,680 |
def rsync(params, src, dst):
""" Execute rsync command.
"""
# command = "rsync {params} {src} {dst} >/dev/null 2>&1".format(params=params, src=quote(src), dst=quote(dst))
command = "rsync {params} {src} {dst}".format(params=params, src=quote(src), dst=quote(dst))
subprocess.check_call(command, shell... | 5,323,681 |
def dist(subnetworks, node_id,
path_method='dijkstra',
inter_group=False, inter_group_dist=None, rep_dist=None):
"""
Parameters
----------
subnetworks (subg): LIST. List of sub-graphs for each sub-network.
node_id : INT. Source node ID for calculating in-group distances.
... | 5,323,682 |
def update_account():
"""
Update an account
"""
account = Account.query.filter(Account.id == session['user']['account']['id']).first()
for key, value in request.form.items():
setattr(account, key, value)
db_session.add(account)
db_session.commit()
session['user']['account... | 5,323,683 |
def test_valid_url_scheme():
"""Client instance created if URL starts with ftps://."""
FTPS('ftps://<user>:<password>@host') | 5,323,684 |
def write_template(document):
"""
Write out software management plan template as Markdown.
This Markdown is intended to be used as an intermediary before
onward conversion into another format e.g. to docx, odt or
html, using, for example, pandoc.
The Markdown starts with:
---
... | 5,323,685 |
def test_base_event():
"""Test BaseEvent"""
log_line = 'L 01/11/2013 - 16:57:49:'
check_event(generic.BaseEvent, log_line) | 5,323,686 |
def test_reset():
"""
Test if it return a RabbitMQ node to its virgin state
"""
mock_run = MagicMock(
return_value={"retcode": 0, "stdout": "saltstack", "stderr": ""}
)
with patch.dict(rabbitmq.__salt__, {"cmd.run_all": mock_run}):
assert rabbitmq.reset() == "saltstack" | 5,323,687 |
def test_rst_conf_multi_line():
"""Test that the python dictionary can span multiple lines."""
py_percent_nb = """
# %%
rst_conf = {
"jupyter_execute_options": [
":hide-code:", ":hide-output:", ":code-below:", ":linenos:"
]
}
1+1"""
expected = """
.. jupyter... | 5,323,688 |
def quaternion_multiply(quaternion1, quaternion0):
"""Return multiplication of two quaternions.
>>> q = quaternion_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
>>> numpy.allclose(q, [-44, -14, 48, 28])
True
"""
x0, y0, z0, w0 = quaternion0
x1, y1, z1, w1 = quaternion1
return numpy.array((
... | 5,323,689 |
def triangulate_nviews(P, ip):
"""
Triangulate a point visible in n camera views.
P is a list of camera projection matrices.
ip is a list of homogenised image points. eg [ [x, y, 1], [x, y, 1] ], OR,
ip is a 2d array - shape nx3 - [ [x, y, 1], [x, y, 1] ]
len of ip must be the same as len of P
... | 5,323,690 |
def _load_config_impl_moduleconfig(configMap, config_reader, global_config):
""" 讀取模組設定資訊
參數:
configMap - 設定值資訊字典
config_reader - 以「模組的設定名稱」為鍵「模組實體」為值的 dict 結構體
global_config - 全域設定值
回傳值:
(無)
"""
for mod_cfgname, mod_object in config_reader.iteritems():
if mod_cfgname in configMap:
m = mod_object.get... | 5,323,691 |
def docs(session):
"""Build docs"""
session.install("sphinx")
session.run("python", "setup.py", "docs") | 5,323,692 |
def get_require_files(path,require_file_list,regex=True,matched_part='xls',if_walk_path=True):
"""
检查某个路径是否包含必须的文档
:param path:路径
:param require_file_list: 要检查的文档/文件夹是否存在
:param regex : 是否需要用re去匹配
:return : 如果不存在,返回空字典,如果文档存在 返回需要文档的对应绝对路径字典
"""
if type(require_file_list) != list... | 5,323,693 |
def decompose_entry_to_dict_2107_Stavropol(entry:str)-> Dict:
"""
Выделяем данные из одной записи в dictionary
------------------------------------------------------------------------------------------------------
03.07.2021 12:52 -> Перевод с карты -> 3 500,00 -> 28 655,30
03.07.2021 123456 -> SBOL пе... | 5,323,694 |
def _create_data_sources(data, index_sort="none"):
"""
Returns datasources for index and value based on the inputs. Assumes that
the index data is unsorted unless otherwise specified.
"""
# if not isinstance(data, ndarray) and (len(data) < 2):
# raise RuntimeError("Unable to create datasour... | 5,323,695 |
def initdb_handler():
"""
Make a call to initialize the database.
"""
initializeDatabase()
print("Initialized the " + __name__ + " database.")
# Initial settings for application state
update_settings(DANGER['SAFE'], ENVIRONMENT['FOREST FIRE'], STATE['STOPPED']) | 5,323,696 |
def discriminate(outputs, classes_to_detect):
"""Select which classes to detect from an output.
Get the dictionary associated with the outputs instances and modify
it according to the given classes to restrict the detection to them
Args:
outputs (dict):
instances (detectron2.struct... | 5,323,697 |
def request_get_with_timeout_retry(url: str, retries: int) -> Response:
"""
Makes a GET request, and retries if the server responds with a 504 (timeout)
Args:
url (str): The URL of the Mailgun API endpoint
retries (int): The number of times to retry the request
Returns:
respons... | 5,323,698 |
def show_version():
"""
Affiche la version et les informations sur le programme dans la console
"""
print("===============================================================")
print(f"Productivity App v{__VERSION__}")
print(f"Made by {__AUTHOR__} (with the advices of {__ADVISOR__})")
print("Sou... | 5,323,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.