content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_requirements():
"""
Obtenir la liste de toutes les dépences
:return: la liste de toutes les dépences
"""
requirements = []
with open(REQUIREMENTS_TXT, encoding="utf-8") as frequirements:
for requirement_line in frequirements.readlines():
requirement_line = requirement... | 5,337,300 |
def equ2gal(ra, dec):
"""Converts Equatorial J2000d coordinates to the Galactic frame.
Note: it is better to use AstroPy's SkyCoord API for this.
Parameters
----------
ra, dec : float, float [degrees]
Input J2000 coordinates (Right Ascension and Declination).
Returns
-------
g... | 5,337,301 |
def require_pyoptsparse(optimizer=None):
"""
Decorate test to raise a skiptest if a required pyoptsparse optimizer cannot be imported.
Parameters
----------
optimizer : String
Pyoptsparse optimizer string. Default is None, which just checks for pyoptsparse.
Returns
-------
Test... | 5,337,302 |
def addition(a:Union[int, float], b:Union[int, float]) -> Union[int, float]:
"""
A simple addition function. Add `a` to `b`.
"""
calc = a + b
return calc | 5,337,303 |
def print_version():
"""
Print the module version information
:return: returns 1 for for exit code purposes
:rtype: int
"""
print("""
%s version %s - released %s"
""" % (__docname__, __version__, __release__))
return 1 | 5,337,304 |
def splitpath(path):
""" Split a path """
drive, path = '', _os.path.normpath(path)
try:
splitunc = _os.path.splitunc
except AttributeError:
pass
else:
drive, path = splitunc(path)
if not drive:
drive, path = _os.path.splitdrive(path)
elems = []
try:
... | 5,337,305 |
def vmf1_zenith_wet_delay(dset):
"""Calculates zenith wet delay based on gridded zenith wet delays from VMF1
Uses gridded zenith wet delays from VMF1, which are rescaled from the gridded height to actual station height by
using Equation(5) described in Kouba :cite:`kouba2007`.
Args:
dset (Data... | 5,337,306 |
def docs(session):
"""Build the docs."""
session.install("-r", os.path.join("docs", "requirements-docs.txt"))
session.install("-e", ".")
shutil.rmtree(os.path.join("docs", "source", "_build"), ignore_errors=True)
session.run(
"sphinx-build",
"-W", # warnings as errors
"-T"... | 5,337,307 |
def get_hash(dictionary):
"""Takes a dictionary as input and provides a unique hash value based on the
values in the dictionary. All the values in the dictionary after
converstion to string are concatenated and then the HEX hash is generated
:param dictionary: A python dictionary
:return: A HEX hash
Credit... | 5,337,308 |
def convert_to_tensor(value, dtype=None, device = None):
"""
Converts the given value to a Tensor.
Parameters
----------
value : object
An object whose type has a registered Tensor conversion function.
dtype : optional
Optional element type for the returned tensor. If missing, t... | 5,337,309 |
def send_email(to_address, from_address,subject, message,cc=[],files=[],host="localhost", port=587, username='', password=''):
"""Sending an email with python.
Args:
to_address (str): the recipient of the email
from_address (str): the originator of the email
subject (str): m... | 5,337,310 |
def aggregate_extrema(features, Th, percentage = True) :
"""
Summary:
Function that tries to remove false minima aggregating closeby extrema
Arguments:
features - pandas series containing the extrema to be aggregated.
The series is of the form: Max, Min, Max, Max, M... | 5,337,311 |
def load_embedded_frame_data(session_path, camera: str, raw=False):
"""
:param session_path:
:param camera: The specific camera to load, one of ('left', 'right', 'body')
:param raw: If True the raw data are returned without preprocessing (thresholding, etc.)
:return: The frame counter, the pin state... | 5,337,312 |
async def test_app_and_product(app, product):
"""Create a test app and product which can be modified in the test"""
await product.create_new_product()
await app.create_new_app()
await product.update_scopes(
[
"urn:nhsd:apim:app:level3:shared-flow-testing",
"urn:nhsd:api... | 5,337,313 |
def reconstruct(edata, mwm=80.4, cme=1000):
"""
Reconstructs the momentum of the neutrino and anti-neutrino, given the
momentum of the muons and bottom quarks.
INPUT:
edata: A list containing the x, y, and z momentum in GeV of the charged leptons
and bottom qua... | 5,337,314 |
def run_sql_command(query: str, database_file_path:str, unique_items=False) -> list:
"""
Returns the output of an SQL query performed on a specified SQLite database
Parameters:
query (str): An SQL query
database_file_path (str): absolute path of the SQLite database file
... | 5,337,315 |
def group_into_profiled_intervals(records: Iterable[Reading],
interval_m: int = 30,
profile: List[float] = PROFILE_DEFAULT
):
""" Group load data into billing intervals, if larger split first
:param records: T... | 5,337,316 |
def plot_3d_pose(pose, elev=0, azim=0, figsize=(8, 8)):
"""
Visualize a 3D skeleton.
:param pose: numpy array (3 x 17) with x, y, z coordinates with COCO keypoint format.
:param elev: Elevation angle in the z plane.
:param azim: Azimuth angle in the x, y plane.
:param figsize: Figure size.
:... | 5,337,317 |
def zeta_nbi_nvi_ode(t, y, nb, C, nv, nb0, nbi_ss, f, g, c0, alpha, B, pv, e, R, eta, mu, nbi_norm = True):
"""
Solving the regular P0 equation using the ODE solver (changing s > 0)
t : time to solve at, in minutes
y : y[0] = nvi, y[1] = nbi, y[2] = zeta(t)
"""
F = f*g*c0
r = R*g*... | 5,337,318 |
def intercalamento_listas(lista1, lista2):
""" Usando 'lista1' e 'lista2', ambas do mesmo comprimento,
crie uma nova lista composta pelo intercalamento entre as duas.""" | 5,337,319 |
def get_irsa_catalog(ra=165.86, dec=34.829694, radius=3, catalog='allwise_p3as_psd', wise=False, twomass=False):
"""Query for objects in the `AllWISE <http://wise2.ipac.caltech.edu/docs/release/allwise/>`_ source catalog
Parameters
----------
ra, dec : float
Center of the query region, dec... | 5,337,320 |
def _create_supporting_representation(model,
support_root = None,
support_uuid = None,
root = None,
title = None,
content_type = '... | 5,337,321 |
def os_kernel():
"""
Get the operating system's kernel version
"""
ker = "Unknown"
if LINUX:
ker = platform.release()
elif WIN32 or MACOS:
ker = platform.version()
return ker | 5,337,322 |
def get_inputfuncs(session, *args, **kwargs):
"""
Get the keys of all available inputfuncs. Note that we don't get
it from this module alone since multiple modules could be added.
So we get it from the sessionhandler.
"""
inputfuncsdict = dict(
(key, func.__doc__) for key, func in sessio... | 5,337,323 |
def call(args, env=None, cwd=None, outputHandler=None, outputEncoding=None, timeout=None, displayName=None, options=None):
"""
Call a process with the specified args, logging stderr and stdout to the specified
output handler which will throw an exception if the exit code or output
of the process indicates an erro... | 5,337,324 |
def prettyFloat(value, roundValue=False):
"""Return prettified string for a float value.
TODO
----
add flag for round to
add test
"""
## test-cases:
# if change things her, look that they are still good (mod-dc-2d)
if roundValue and abs(round(value)-value) < 1e-4 and abs(val... | 5,337,325 |
def make_nested_pairs_from_seq(args):
"""
Given a list of arguments, creates a list in Scheme representation
(nested Pairs).
"""
cdr = Nil()
for arg in reversed(args):
cdr = Pair(arg, cdr)
return cdr | 5,337,326 |
def add_tc_qdisc(device, qdisc_type, parent=None, handle=None, latency_ms=None,
max_kbps=None, burst_kb=None, kernel_hz=None,
namespace=None):
"""Add/replace a TC qdisc on a device
pyroute2 input parameters:
- rate (min bw): bytes/second
- burst: bytes
- late... | 5,337,327 |
def print_warning(text: str) -> None:
""" Prints a warning. """
print(Style.DIM + Back.YELLOW + Fore.BLACK + "[/!\\] " + text)
print(Style.RESET_ALL, end="") | 5,337,328 |
def get_aug_assign_symbols(code):
"""Given an AST or code string return the symbols that are augmented
assign.
Parameters
----------
code: A code string or the result of an ast.parse.
"""
if isinstance(code, str):
tree = ast.parse(code)
else:
tree = code
n = AugAs... | 5,337,329 |
def stack_dict(state: Dict[Any, tf.Tensor]) -> tf.Tensor:
"""Stack a dict of tensors along its last axis."""
return tf.stack(sorted_values(state), axis=-1) | 5,337,330 |
def compact_float(n, max_decimals=None):
"""Reduce a float to a more compact value.
Args:
n: Floating point number.
max_decimals: Maximum decimals to keep; defaults to None.
Returns:
An integer if `n` is essentially an integer, or a string
representation of `n` red... | 5,337,331 |
def resample_2d(X, resolution):
"""Resample input data for efficient plotting.
Parameters:
-----------
X : array_like
Input data for clustering.
resolution : int
Number of "pixels" for 2d histogram downscaling.
Default 'auto' downscales to 200x200 for >5000
samples, ... | 5,337,332 |
def is_mocked(metric_resource: MetricResource) -> bool:
"""
Is this metrics a mocked metric or a real metric?
"""
return metric_resource.spec.mock is not None | 5,337,333 |
def negative_embedding_subtraction(
embedding: np.ndarray,
negative_embeddings: np.ndarray,
faiss_index: faiss.IndexFlatIP,
num_iter: int = 3,
k: int = 10,
beta: float = 0.35,
) -> np.ndarray:
"""
Post-process function to obtain more discriminative image descriptor.
Parameters
-... | 5,337,334 |
def op_conv_map(operator):
"""Convert operator or return same operator"""
return OPERATOR_CONVERSION.get(operator, operator) | 5,337,335 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Demo Calendar platform."""
calendar_data_future = DemoGoogleCalendarDataFuture()
calendar_data_current = DemoGoogleCalendarDataCurrent()
add_entities(
[
DemoGoogleCalendar(hass, calendar_data_future, "... | 5,337,336 |
def getGMapKey():
"""Return value for <gmapKey/> configuration parameter."""
return sciflo.utils.ScifloConfigParser().getParameter('gmapKey') | 5,337,337 |
def agent_action(tid: uuid.UUID, name: str, action: AgentAction) -> None:
"""
Execute an action on an agent
:param tid: The environment this agent is defined in.
:param name: The name of the agent.
:param action: The type of action that should be executed on an agent.
* pause: A... | 5,337,338 |
def macromodel_optimisation(
precursors, optimiser, temp_dir, collection_name, db_name, db_url
):
"""
Optimises cages and returns the modified cage.
Args:
precursors: SMILES of precursors to be optimised.
optimise: Optimiser callable to use.
temp_dir: Path of temporary directory... | 5,337,339 |
def get_stored_credentials():
"""
Gets the credentials, username and password, that have been stored in
~/.shrew/config.ini and the secure keychain respectively without bothering
to prompt the user if either credential cannot be found.
:returns: username and password
:rtype:... | 5,337,340 |
async def main(
urlfile,
outfile: IO[str],
gateway_node: SSHNode,
client_node: Sequence[SSHNode],
n_clients: int,
checkpoint_dir: Optional[pathlib.Path],
gateway_endpoint: Optional[str],
**kwargs
):
"""Script entry pooint."""
logging.basicConfig(
format='[%(asctime)s] %(n... | 5,337,341 |
def _ro_hmac(msg, h=None):
"""Implements random oracle H as HMAC-SHA256 with the all-zero key.
Input is message string and output is a 32-byte sequence containing the HMAC
value.
Args:
msg: Input message string.
h: An optional instance of HMAC to use. If None a new zeroed-out instance
will be u... | 5,337,342 |
def test_person__DeletePersonForm__3(person_data, browser, loginname):
"""It cannot be accessed by some roles."""
browser.login(loginname)
browser.assert_forbidden(browser.PERSON_DELETE_URL) | 5,337,343 |
def get_unique_slug(model_instance, sluggable_field_name, slug_field_name):
"""
Takes a model instance, sluggable field name (such as 'title') of that
model as string, slug field name (such as 'slug') of the model as string;
returns a unique slug as string.
"""
slug = slugify(getattr(model_insta... | 5,337,344 |
def test_SFA(noise_dataset):
"""Test that a SFA model can be fit with no errors.
"""
X = noise_dataset
model = SFA(n_components=3)
model.fit(X)
model.transform(X)
model.fit_transform(X) | 5,337,345 |
def where(ctx):
"""Print path to data directory."""
log.debug('chemdataextractor.data.where')
click.echo(get_data_dir()) | 5,337,346 |
def get_precomputed_features(source_dataset, experts):
"""Get precomputed features from a set of experts and a dataset.
Arguments:
source_dataset: the source dataset as an instance of Base Dataset.
experts: a list of experts to use precomputed features from
Returns: A list of dicts, where ... | 5,337,347 |
def _local_distribution():
"""
获取地区分布
"""
data = {}
all_city = Position.objects.filter(status=1).values_list("district__province__name", flat=True)
value_count = pd.value_counts(list(all_city)).to_frame()
df_value_counts = pd.DataFrame(value_count).reset_index()
df_value_counts.columns =... | 5,337,348 |
def paradigm_filler(shared_datadir) -> ParadigmFiller:
"""
hese layout, paradigm, and hfstol files are **pinned** test data;
the real files in use are hosted under res/ folder, and should not
be used in tests!
"""
return ParadigmFiller(
shared_datadir / "layouts",
shared_datadir ... | 5,337,349 |
def apply_scaling(data, dicom_headers):
"""
Rescale the data based on the RescaleSlope and RescaleOffset
Based on the scaling from pydicomseries
:param dicom_headers: dicom headers to use to retreive the scaling factors
:param data: the input data
"""
# Apply the rescaling if needed
pr... | 5,337,350 |
def fprint(*objects, color='', style='', **kwargs):
"""Print text with fancy colors and formatting
Parameters
----------
*objects
objects to print
color : str
one- or two-character string specifying color:
r (red)
dr (dark red)
hr (highlight red)
... | 5,337,351 |
def test_1_1_FConnectionResetError():
"""
Tests formatting a FConnectionResetError exception with adjusted traceback.
"""
with pytest.raises(Exception) as excinfo:
exc_args = {
'main_message': 'Problem with the construction project.',
'expected_result': 'A door',
... | 5,337,352 |
def allowed_couplings(coupling, flow, free_id, symmetries):
"""Iterator over all the allowed Irreps for free_id in coupling if the
other two couplings are fixed.
"""
from itertools import product
if len(coupling) != 3:
raise ValueError(f'len(coupling) [{len(coupling)}] != 3')
if len(fl... | 5,337,353 |
def poly_iou(poly1, poly2, thresh=None):
"""Compute intersection-over-union for two GDAL/OGR geometries.
Parameters
----------
poly1:
First polygon used in IOU calc.
poly2:
Second polygon used in IOU calc.
thresh: float or None
If not provided (default), returns the floa... | 5,337,354 |
def plotCorrHeatmap(mat, fout):
"""
Correlation heatmap plot for two samples correlation.
"""
#fig, ax = pylab.subplots(
cmap = sns.diverging_palette(250, 15, s=75, l=40, n=11).as_hex()
cmap[int(len(cmap) / 2)] = "#FFFFFF"
cmap = ListedColormap(cmap)
g = sns.clustermap(
mat,
... | 5,337,355 |
def score_file(filename):
"""Score each line in a file and return the scores."""
# Prepare model.
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = "inputs" in encoders
# Prepare features for feeding into the model.
if has_inputs:
inpu... | 5,337,356 |
def doi_responses():
"""Responses for doi.org requests."""
import responses
from renku.core.commands.providers.dataverse import DATAVERSE_API_PATH, DATAVERSE_VERSION_API
from renku.core.commands.providers.doi import DOI_BASE_URL
with responses.RequestsMock(assert_all_requests_are_fired=False) as r... | 5,337,357 |
def order_result():
"""
Get a specific order
"""
raise NotImplemented | 5,337,358 |
def lat_lng_to_tile_xy(latitude, longitude, level_of_detail):
"""gives you zxy tile coordinate for given latitude, longitude WGS-84 coordinates (in decimal degrees)
"""
x, y = lat_lng_to_pixel_xy(latitude, longitude, level_of_detail)
return pixel_xy_to_tile_xy(x, y) | 5,337,359 |
def test_arithmetic_simplify_05():
""" test_arithmetic_simplify_05 """
x = Tensor(np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32))
res = arithmetic_simplify_05(x)
expect = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.int32)
assert np.all(res.asnumpy() == expect) | 5,337,360 |
def update_inverse_jacobian(previous_inv_jac, dx, df, threshold=0, modify_in_place=True):
"""
Use Broyden method (following Numerical Recipes in C, 9.7) to update inverse Jacobian
current_inv_jac is previous inverse Jacobian (n x n)
dx is delta x for last step (n)
df is delta errors for last step (n... | 5,337,361 |
def _subsets_recursive(items, size, begin_index=0):
"""Recursize subset enumeration.
Args:
items: the list of items. Must be indexable.
size: the current subset size.
begin_index: the index to begin at.
Yields:
all subsets of "items" of size == "size" starting from
... | 5,337,362 |
def _ConvertStack(postfix):
"""Convert postfix stack to infix string.
Arguments:
postfix: A stack in postfix notation. The postfix stack will be modified
as elements are being popped from the top.
Raises:
ValueError: There are not enough arguments for functions/operators.
Returns:
A string of... | 5,337,363 |
def count_repeats_for_motif(seq, motif, tally, intervals=None):
"""
seq --- plain sequence to search for the repeats (motifs)
motif --- plain sequence of repeat, ex: CGG, AGG
intervals --- 0-based start, 1-based end of Intervals to search motif in
"""
if intervals is None: # use the whole sequen... | 5,337,364 |
def get_oauth2_token(session: requests.Session, username: str, password: str):
"""Hackily get an oauth2 token until I can be bothered to do this correctly"""
params = {
'client_id': OAUTH2_CLIENT_ID,
'response_type': 'code',
'access_type': 'offline',
'redirect_uri': OAUTH2_REDIRE... | 5,337,365 |
def main():
""" call zopeedit as a lib
"""
args = sys.argv
input_file=''
if '--version' in args or '-v' in args:
credits = ('Zope External Editor %s\n'
'By atReal\n'
'http://www.atreal.net') % __version__
messageDialog(credits)
sys.exit(... | 5,337,366 |
def press_level(pressure, heights, plevels, no_time=False):
"""
Calculates geopotential heights at a given pressure level
Parameters
----------
pressure : numpy.ndarray
The 3-D pressure field (assumes time dimension, turn off
with `no_time=True`)
heights : numpy.ndarray
... | 5,337,367 |
def setup_ks_indexer():
"""
KS_INDEXER
:return:
"""
api = ApiResource(server_host=cmx.cm_server, username=cmx.username, password=cmx.password)
cluster = api.get_cluster(cmx.cluster_name)
service_type = "KS_INDEXER"
if cdh.get_service_type(service_type) is None:
print "> %s" % ser... | 5,337,368 |
def test_get_result(mock_send_message):
"""Test Dmaap's class method."""
OranDmaap.get_result()
mock_send_message.assert_called_once_with('GET',
'Get result from previous request',
(f"{BASE_URL}/events/A1-POLICY-AGEN... | 5,337,369 |
def valtoindex(thearray, thevalue, evenspacing=True):
"""
Parameters
----------
thearray: array-like
An ordered list of values (does not need to be equally spaced)
thevalue: float
The value to search for in the array
evenspacing: boolean, optional
If True (default), assu... | 5,337,370 |
def get_converter(result_format, converters=None):
"""
Gets an converter, returns the class and a content-type.
"""
converters = get_default_converters() if converters is None else converters
if result_format in converters:
return converters.get(result_format)
else:
raise ValueE... | 5,337,371 |
def _deduce_ConstantArray(
self: ast.ConstantArray, ctx: DeduceCtx) -> ConcreteType: # pytype: disable=wrong-arg-types
"""Deduces the concrete type of a ConstantArray AST node."""
# We permit constant arrays to drop annotations for numbers as a convenience
# (before we have unifying type inference) by allowi... | 5,337,372 |
def _to_bool(s):
"""Convert a value into a CSV bool."""
if s.lower() == 'true':
return True
elif s.lower() == 'false':
return False
else:
raise ValueError('String cannot be converted to bool') | 5,337,373 |
def register(*args, cache_default=True):
"""
Registers function for further caching its calls and restoring source.
Example:
``` python
@register
def make_ohe_pclass(df):
...
```
"""
def __register(func):
# if source_utils.source_is_saved(func) and not source_ut... | 5,337,374 |
def make_absolute_paths(content):
"""Convert all MEDIA files into a file://URL paths in order to
correctly get it displayed in PDFs."""
overrides = [
{
'root': settings.MEDIA_ROOT,
'url': settings.MEDIA_URL,
},
{
'root': settings.STATIC_ROOT,
... | 5,337,375 |
def social_distancing_start_40():
"""
Real Name: b'social distancing start 40'
Original Eqn: b'31'
Units: b'Day'
Limits: (None, None)
Type: constant
b''
"""
return 31 | 5,337,376 |
def _initialize_project(stolos_url, project):
"""
Initialize a Stolos project with the needed files, using the response from
the server.
"""
config.update_project_config(
{
"project": {
"uuid": project["uuid"],
"stack": project["stack"]["slug"] if ... | 5,337,377 |
def parse_argv(argv):
"""
parse argv
"""
psr = argparse.ArgumentParser(prog=argv[0])
psr.add_argument("--users-csv", default="users.csv",
help=("a csv file describing directories to monitor, which at minimum must have a column 'notebooks'."
" they are ... | 5,337,378 |
def get_token_auth_header(params):
"""
Obtains the Access Token from the Authorization Header
"""
auth = get_token(params)
parts = auth.split()
if parts[0].lower() != "bearer":
raise AuthError({"code": "invalid_header", "description": "Authorization header must start with Bearer"}, 401)... | 5,337,379 |
def create():
"""Create a backup based on SQLAlchemy mapped classes"""
# create backup files
alchemy = AlchemyDumpsDatabase()
data = alchemy.get_data()
backup = Backup()
for class_name in data.keys():
name = backup.get_name(class_name)
full_path = backup.target.create_file(name,... | 5,337,380 |
def bam(fastq_name, samfile, samtools, index_type): # type: (str, str, str, str) -> None
"""Use SAMtools to convert a SAM to BAM file"""
logging.info("FASTQ %s: Converting SAM to BAM", fastq_name)
bam_start = time.time() # type: float
# Make BAM name
bamfile = samfile.replace('sam', 'bam') # type:... | 5,337,381 |
async def test_error_fetching_new_version_bad_json(opp, aioclient_mock):
"""Test we handle json error while fetching new version."""
aioclient_mock.get(updater.UPDATER_URL, text="not json")
with patch(
"openpeerpower.helpers.system_info.async_get_system_info",
return_value={"fake": "bla"},
... | 5,337,382 |
def check_hu(base: str, add: Optional[str] = None) -> str:
"""Check country specific VAT-Id"""
weights = (9, 7, 3, 1, 9, 7, 3)
s = sum(int(c) * w for (c, w) in zip(base, weights))
r = s % 10
if r == 0:
return '0'
else:
return str(10 - r) | 5,337,383 |
def store_data(file, rewards, arms, agent_list):
"""
Store the rewards, arms, and agents to a pickled file.
Parameters
----------
file : string
File name.
rewards : array
Evolution of cumulative rewards along training.
arms : array
Evolution of the number of arms alo... | 5,337,384 |
def _eval(squad_ds: SquadDataset):
"""Perform evaluation of a saved model."""
# Perform the evaluation.
sen, doc = _chunked_eval(squad_ds)
# Evaluation is finished. Compute the final 1@N statistic and record it.
print("index size=%s questions=%s" % (
len(squad_ds.master_index), len(squad_ds.queries))... | 5,337,385 |
def scrape_headline(news_link):
"""
function to scrape the headlines from a simple news website
:return: a dictionary with key as html link of the source and
value as the text in the headline of the news in the html link
"""
#Headlines
#URL = 'https://lite.cnn.com/en'... | 5,337,386 |
def read_xml(img_path):
"""Read bounding box from xml
Args:
img_path: path to image
Return list of bounding boxes
"""
anno_path = '.'.join(img_path.split('.')[:-1]) + '.xml'
tree = ET.ElementTree(file=anno_path)
root = tree.getroot()
ObjectSet = root.findall('object')
... | 5,337,387 |
def YumInstall(vm):
""" Installs SysBench 0.5 for Rhel/CentOS. We have to build from source!"""
vm.Install('build_tools')
vm.InstallPackages('bzr')
vm.InstallPackages('mysql mysql-server mysql-devel')
vm.RemoteCommand('cd ~ && bzr branch lp:sysbench')
vm.RemoteCommand(('cd ~/sysbench && ./autogen.sh &&'
... | 5,337,388 |
def a2funcoff(*args):
"""a2funcoff(ea_t ea, char buf) -> char"""
return _idaapi.a2funcoff(*args) | 5,337,389 |
def str(obj):
"""This function can be used as a default `__str__()` in user-defined classes.
Classes using this should provide an `__info__()` method, otherwise the `default_info()`
function defined in this module is used.
"""
info_func = getattr(type(obj), "__info__", default_info)
return "{}(... | 5,337,390 |
def isin_strategy(
pandera_dtype: Union[numpy_engine.DataType, pandas_engine.DataType],
strategy: Optional[SearchStrategy] = None,
*,
allowed_values: Sequence[Any],
) -> SearchStrategy:
"""Strategy to generate values within a finite set.
:param pandera_dtype: :class:`pandera.dtypes.DataType` in... | 5,337,391 |
def test_joboffer_edit_with_all_fields_empty(publisher_client, user_company_profile):
"""
Test the validation of empty fields
"""
client = publisher_client
company = user_company_profile.company
offer = JobOfferFactory.create(company=company)
target_url = reverse(EDIT_URL, kwargs={'slug': ... | 5,337,392 |
def test_year_insert(session, year_data):
"""Year 001: Insert multiple years into Years table and verify data."""
years_list = range(*year_data['90_to_94'])
for yr in years_list:
record = Years(yr=yr)
session.add(record)
years = session.query(Years.yr).all()
years_from_db = [x[0] fo... | 5,337,393 |
def listen_to_related_object_post_save(sender, instance, created, **kwargs):
"""
Receiver function to create agenda items. It is connected to the signal
django.db.models.signals.post_save during app loading.
The agenda_item_update_information container may have fields like type,
parent_id, comment,... | 5,337,394 |
def arrToDict(arr):
"""
Turn an array into a dictionary where each value maps to '1'
used for membership testing.
"""
return dict((x, 1) for x in arr) | 5,337,395 |
async def test_default_setup(hass, monkeypatch):
"""Test all basic functionality of the rflink sensor component."""
# setup mocking rflink module
event_callback, create, _, _ = await mock_rflink(
hass, CONFIG, DOMAIN, monkeypatch)
# make sure arguments are passed
assert create.call_args_lis... | 5,337,396 |
def getPercentGC(img, nbpix) :
"""Determines if a page is in grayscale or colour mode."""
if img.mode != "RGB" :
img = img.convert("RGB")
gray = 0
for (r, g, b) in img.getdata() :
if not (r == g == b) :
# optimize : if a single pixel is no gray the whole page is color... | 5,337,397 |
def rotate(angle: float, iaxis: int) -> ndarray:
"""
Calculate the 3x3 rotation matrix generated by a rotation
of a specified angle about a specified axis. This rotation
is thought of as rotating the coordinate system.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rotate_c.html
:par... | 5,337,398 |
def build_categories(semanticGroups):
"""
Returns a list of ontobio categories or None
Parameters
----------
semanticGroups : string
a space delimited collection of semanticGroups
"""
if semanticGroups is None:
return None
categories = []
for semanticGroup in semant... | 5,337,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.