content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_parser(args):
""" Function which add the command line arguments required for the cyclomatic complexity report parser"""
# Create the parser
cyclo_parser = argparse.ArgumentParser(description='cyclomatic complexity gate Parser')
# Add the arguments
cyclo_parser.add_argument('--cyclo', met... | 5,324,800 |
def get_month_day_range(date):
"""
For a date 'date' returns the start and end date for the month of 'date'.
Month with 31 days:
>>> date = datetime.date(2011, 7, 27)
>>> get_month_day_range(date)
(datetime.date(2011, 7, 1), datetime.date(2011, 7, 31))
Month with 28 days:
>>> date = da... | 5,324,801 |
def measure_of_risk_callback(app):
"""
Attaches the callback function for the component
rendered in the measure_of_risk function
Args:
app = the dash app
Returns:
None
"""
component_id = 'measure-risk'
@app.callback(
Output(component_id + 'out', 'children'),
... | 5,324,802 |
def dot(
a: Union[float, ArrayLike],
b: Union[float, ArrayLike],
*,
dims: Optional[Tuple[int, int]] = None
) -> Union[float, Array]:
"""
Get dot product of simple numbers, vectors, and matrices.
Matrices will be detected and the appropriate logic applied
unless `dims` is provided. `dims... | 5,324,803 |
def read_float64(field: str) -> np.float64:
"""Read a float64."""
return np.float64(field) if field != "" else np.nan | 5,324,804 |
def write_hypergraph(hgr, colored = False):
"""
Return a string specifying the given hypergraph in DOT Language.
@type hgr: hypergraph
@param hgr: Hypergraph.
@type colored: boolean
@param colored: Whether hyperedges should be colored.
@rtype: string
@return: String specify... | 5,324,805 |
def sort_gtf(gtf_path, out_path):
"""Sorts a GTF file based on its chromosome, start position, line number.
:param gtf_path: path to GTF file
:type gtf_path: str
:return: path to sorted GTF file, set of chromosomes in GTF file
:rtype: tuple
"""
logger.info('Sorting {}'.format(gtf_path))
... | 5,324,806 |
def leia_dinheiro(msg):
"""
-> Recebe um valor digitado pelo usuário e verifica se é um
valor númerico válido
:param msg: Mensagem a ser mostrada ao usuário
:return: Retorno o valor digitado pelo usuário caso seja válido
"""
while True:
num = input(msg).strip().replace(',', '.') # S... | 5,324,807 |
def format_analyse(parsed_tokens, to_1d_flag=False):
"""
入力
parsed_tokens # list(list(str)) : 変数毎の変数名/インデックスがtokenizedなトークンリスト
出力
res,dic # FormatNode,OrderedDict<str:VariableInformation> : フォーマット情報のノードと変数の情報を保持した辞書を同時に返す
"""
appearanc... | 5,324,808 |
def KAMA(df: pd.DataFrame, window: int = 10, pow1: int = 2, pow2: int = 30) -> pd.DataFrame:
"""
Kaufman's Adaptive Moving Average (KAMA) is an indicator that
indicates both the volatility and trend of the market.
"""
df_with_signal = df.copy()
df_with_signal["signal"] = kama(df["close"], window... | 5,324,809 |
def cast_to_str(obj):
"""Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence
"""
if isinstance(obj, str):
return obj
if isinstance(obj, Seq):
retu... | 5,324,810 |
def _octet_bits(o):
"""
Get the bits of an octet.
:param o: The octets.
:return: The bits as a list in LSB-to-MSB order.
:rtype: list
"""
if not isinstance(o, int):
raise TypeError("o should be an int")
if not (0 <= o <= 255):
raise ValueError("o should be between 0 and ... | 5,324,811 |
def _collect_calculation_data(calc):
"""
Recursively collects calculations from the tree, starting at given
calculation.
"""
from aiida.common.links import LinkType
from aiida.orm.data import Data
from aiida.orm.calculation import Calculation
from aiida.orm.calculation.job import JobCalc... | 5,324,812 |
def clf():
"""
Clear the current figure.
"""
plt.clf()
plt.show(block=False) | 5,324,813 |
def pickle_squeeze(data, pkl_file, fmt='lzma'):
""" looks like compress_pickle may be the way to go """
if isinstance(pkl_file, str): pkl_file = path(pkl_file)
if type(fmt) not in (list, tuple): fmt = [fmt]
if len(fmt): fmt = [_s.lower() for _s in fmt]
with pkl_file.open('wb') as hfile:
lo... | 5,324,814 |
def to_graph(l):
"""
Credit: Jochen Ritzel
https://stackoverflow.com/questions/4842613/merge-lists-that-share-common-elements
"""
G = networkx.Graph()
for part in l:
# each sublist is a bunch of nodes
G.add_nodes_from(part)
# it also implies a number of edges:
G.a... | 5,324,815 |
def convert_mcmc_labels(param_keys, unit_labels=False):
"""Returns sequence of formatted MCMC parameter labels
"""
keys = list(param_keys)
for i, key in enumerate(keys):
if 'qb' in key:
label_str = r'$Q_\mathrm{b,' + f'{key[-1]}' + '}$'
elif 'mdot' in key:
label_... | 5,324,816 |
def _set_grid():
"""It sets the grid from the data to be plotted."""
space=set_color(" ", h.point_color)
h.grid=[[space for c in range(h.cols)] for r in range(h.rows)]
if h.line:
_add_to_grid(*_get_line(), h.line_marker, h.line_color)
if h.point:
_add_to_grid(h.x, h.y, h.point_marker... | 5,324,817 |
def superuser_exempt(filter_authorization_verification):
"""Decorator to exempt any superuser from filtering, authorization, or verification functions."""
def superuser_exempt_fun(request, arg):
if request.user.is_superuser:
if isinstance(arg, QuerySet):
return arg
... | 5,324,818 |
def relName(path, cwd=None, root=None):
"""Return pathname relative to `cwd`.
If possible, returns a relative pathname for path. The rules are:
1. If the file is in or below `cwd` then a simple relative name is
returned. For example: 'dir/fred.c'.
2. If both the file and `cwd` are in ... | 5,324,819 |
def paf_to_lastz(job, paf_file, sort_secondaries=True):
"""
Makes lastz output using paftools.js. Also splits the input paf_file into two files
in the output, one for the primary and the other for secondary.
sort_secondaries bool, if true, will cause fxn to return two files instead of one.
"""... | 5,324,820 |
def test_get_bond_by_host_account_id(populated_table):
"""
Get all bonds for a given host account id.
"""
bonds = crud.get_bonds_by_host_account_id(host_account_id="H0002")
assert len(bonds) == 2
assert 'H0002-S0002' in [bond.bond_id for bond in bonds]
assert 'H0002-S0003' in [bond.bond_id f... | 5,324,821 |
def u1(lambd, q):
"""Openqasm u1 gate."""
from mindquantum import Circuit
return Circuit().rz(lambd, q) | 5,324,822 |
def get_simple_object(key='slug', model=None, self=None):
"""
get_simple_object() => Retrieve object instance.
params => key, model, self
return => object (instane)
"""
try:
if key == 'id':
id = self.kwargs['id']
instance = model.objects.get(id=id)
else:
... | 5,324,823 |
def test_windows_powershell(windows):
"""Test powershell execution"""
# Run a real powershell snippet
r = windows.platform.powershell("$PSVersionTable.PSVersion")
assert len(r) == 1
assert isinstance(r[0], dict)
# Ensure we get an exception
with pytest.raises(PowershellError):
wind... | 5,324,824 |
def test_parse_sstat_nodes_1():
"""Parse nodes from sstat called with args -i -a -p -n
PrologFlags=Alloc
"""
output = "22942.0|prod76-0006|354345|"
nodes = ["prod76-0006"]
parsed_nodes = slurmParser.parse_sstat_nodes(output, "22942.0")
assert nodes == parsed_nodes | 5,324,825 |
def test_iterate_k562_data_loader():
""" Iterate throught the dataloader backed by
the dataset, make sure the number of points seen
is in the neighbourhood of what's correct.
"""
valid_dataset, valid_loader = setup_k562_dataset_and_loader(transform=True)
torch.manual_seed(0)
num_epochs = 1... | 5,324,826 |
def create_app():
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
# vvvvv use sqlite database vvvvv
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
# vvvvv have DB initialize the app
DB.init_app(app)
@app.route('/')
def root():
... | 5,324,827 |
def MPITest(commsize):
"""
A decorator that repeatedly calls the wrapped function,
with communicators of varying sizes.
This converts the test to a generator test; therefore the
underlyig test shall not be a generator test.
Parameters
----------
commsize: scalar or tuple
Sizes ... | 5,324,828 |
def getClassicalPitchNames(pitches):
"""
takes a list of pitches and returns a list of classical pitch class names
"""
return getPitchNames([normalizePitch(x,12) for x in pitches],getClassicalPitchNameCandidates) | 5,324,829 |
def toPyUIList(res):
# type: (str) -> List[pymel.core.uitypes.PyUI]
"""
returns a list of PyUI objects
Parameters
----------
res : str
Returns
-------
List[pymel.core.uitypes.PyUI]
"""
if res is None:
return []
import pymel.core.uitypes
return [pymel.core.ui... | 5,324,830 |
def test_initial_routing():
"""
Test the action of fr.route_flow() on the grid.
"""
fr.route_flow()
assert_array_equal(mg.at_node['flow__receiver_node'], r_old)
assert_array_almost_equal(mg.at_node['drainage_area'], A_old) | 5,324,831 |
def best_B(Ag):
""" Given an antigenic determinant Ag this function returns the binding
value of the best possible binder. """
top = 0
for i in range(len(Ag)):
etop = np.min(cf.TD20[int(Ag[i]) - 1])
top += etop
return top | 5,324,832 |
def forward_gradients_v2(ys, xs, grad_xs=None, gate_gradients=False):
"""Forward-mode pushforward analogous to the pullback defined by tf.gradients.
With tf.gradients, grad_ys is the vector being pulled back, and here d_xs is
the vector being pushed forward."""
if type(ys) == list:
v = [tf.ones_... | 5,324,833 |
def __limit_less(lim1, lim2):
"""Helper function for comparing two rlimit values, handling "unlimited" correctly.
Params:
lim1 (integer): first rlimit
lim2 (integer): second rlimit
Returns:
true if lim1 <= lim2
"""
if lim2 == resource.RLIM_INFINITY:
return True
... | 5,324,834 |
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"}) | 5,324,835 |
def getswarmlocations() -> List[str]:
"""
checks if the provided location is a location where a swarm can happen.
:param location: the provided location
:return: boolean if location is in the list of locations where swarms can happen,
"""
swarmlocationlist = open("commands/data/swarmlocations.cs... | 5,324,836 |
def Request(
default: Any = Undefined,
*,
default_factory: Optional[NoArgAnyCallable] = None,
alias: Optional[str] = None,
) -> Any:
"""
Used to provide extra information about a field.
:param default: since this is replacing the field’s default, its first argument is used
to set the ... | 5,324,837 |
def get_jobs(when=None, only_scheduled=False):
"""
Returns a dictionary mapping of job names together with their respective
application class.
"""
# FIXME: HACK: make sure the project dir is on the path when executed as ./manage.py
import sys
try:
cpath = os.path.dirname(os.path.real... | 5,324,838 |
def fill_plug_cache():
"""
主要为遍历vim插件目录,并将插件目录列表显示出来
"""
cb = vim.current.buffer
print(cb.name)
vimplug_root = vim.eval('g:exprjlist_vimplug_root_dir')
if 0 == len(vimplug_root):
return
label = 'vimplug'
candidates = []
for item in os.listdir(vimplug_root):
item... | 5,324,839 |
def get_project_id():
""" Gets the project ID. It defaults to the project declared in the
enviorment variable PROJECT but if it can't find it there it will
try looking for a service account and take the project ID from there
Args:
Returns:
"""
service_acc_address = os.environ.get('GOOGLE_APPLICATION_CREDENT... | 5,324,840 |
def val_err_str(val: float, err: float) -> str:
"""
Get a float representation of a value/error pair and create a string representation
12.345 +/- 1.23 --> 12.3(12)
12.345 +/- 0.012 -> 12.345(12
12345 +/- 654 ---> 12340(650)
:param val: float representing the value
:param err: float represe... | 5,324,841 |
def compareTaggers(model1, model2, string_list, module_name):
"""
Compare two models. Given a list of strings, prints out tokens & tags
whenever the two taggers parse a string differently. This is for spot-checking models
:param tagger1: a .crfsuite filename
:param tagger2: another .crfsuite filenam... | 5,324,842 |
def test_update_feed_deleted(
db_path, make_reader, call_update_method, feed_action, entry_action
):
"""reader.update_feed should raise FeedNotFoundError if the feed is
deleted during parsing.
reader.update_feeds shouldn't (but should log).
"""
parser = Parser()
reader = make_reader(db_pa... | 5,324,843 |
def discrete_distribution(probabilities, path='', fig_name='distribution_events_states.pdf', v_labels=None,
h_labels=None, title=None, color_map=None, figsize=(12, 6), size_labels=16, size_values=14,
bottom=None, top=None, left=None, right=None, savefig=False, usetex=... | 5,324,844 |
def predict(model_dir, model_type, train_steps, train_data, test_data):
"""Prediction by the model. train_file_name and test_file_name are the ones
split from train.csv without header and with target. test1_file_name is the
file with header and no target for final predication"""
train_file_name, test_file_name... | 5,324,845 |
def find_map(address):
"""
Look up a specified address in the /proc/PID/maps for a process.
Returns: A string representing the map in question, or None if no match.
"""
maps = fetch_maps()
for m in re.finditer(begin_pattern, maps):
begin = int(m.group("begin"), 16)
end = int(m.g... | 5,324,846 |
def _format_css_declarations(content: list, indent_level: int) -> str:
"""
Helper function for CSS formatting that formats a list of CSS properties, like `margin: 1em;`.
INPUTS
content: A list of component values generated by the tinycss2 library
OUTPUTS
A string of formatted CSS
"""
output = ""
tokens = t... | 5,324,847 |
def rosen_hess(x):
"""
The Hessian matrix of the Rosenbrock function.
Parameters
----------
x : array_like
1-D array of points at which the Hessian matrix is to be computed.
Returns
-------
rosen_hess : ndarray
The Hessian matrix of the Rosenbrock function at `x`.
... | 5,324,848 |
def flow_corr():
"""
Symmetric cumulants SC(m, n) at the MAP point compared to experiment.
"""
fig, axes = plt.subplots(
figsize=figsize(0.5, 1.2), sharex=True,
nrows=2, gridspec_kw=dict(height_ratios=[4, 5])
)
observables = ['sc', 'sc_normed']
ylims = [(-2.5e-6, 2.5e-6), (... | 5,324,849 |
def close_unclosed_camera_motions(device_id: str):
"""
Camera motion is opened and closed by mqtt events.
- Opened: the field `motion_started_at` is defined but not `motion_ended_at`.
- Closed: both fields are set.
It might happen (in a bad scenario), that the close event does not happen (i.e servic... | 5,324,850 |
def dodecagon(samples=128, radius=1):
"""Create a dodecagon mask.
Parameters
----------
samples : `int`, optional
number of samples in the square output array
radius : `float`, optional
radius of the shape in the square output array. radius=1 will fill the
x
Returns
... | 5,324,851 |
def test_launch_mesos_container():
"""Launches a Mesos container with a simple command."""
app_def = apps.mesos_app(app_id='/mesos-container-app')
app_id = app_def["id"]
client = marathon.create_client()
client.add_app(app_def)
common.deployment_wait(service_id=app_id)
tasks = client.get_... | 5,324,852 |
def port_name(name, nr=0):
"""Map node output number to name."""
return name + ":" + str(nr) | 5,324,853 |
def workflow_run_jobs_page_info(response):
""" Show information about workflow run jobs search response:
the list of job IDs.
"""
ids = []
for data in response.json()['jobs']:
ids.append(data['id'])
info('Workflow run job IDs: {}', ids) | 5,324,854 |
def url(ticker, start_date, end_date):
"""Format the correct URL from the params"""
base_url = ''.join([API_BASE_PATH, ticker, '.csv'])
params = {'start_date': start_date, 'end_date': end_date}
if API_KEY_ENV in os.environ:
params['api_key'] = os.environ[API_KEY_ENV]
return ''.join([base_u... | 5,324,855 |
def deploy_htdf_faucet(conftest_args):
"""
run this test case, if only run single test
run this test case, if run this test file
"""
time.sleep(5)
gas_wanted = 3000000
gas_price = 100
tx_amount = 0
data = BYTECODES
memo = 'test_deploy_htdf_faucet'
htdfrpc = HtdfRPC(chaid_id... | 5,324,856 |
def make_vgroup(module, array):
""" Create Volume Group"""
changed = True
if not module.check_mode:
api_version = array._list_available_rest_versions()
if module.params['bw_qos'] or module.params['iops_qos'] and VG_IOPS_VERSION in api_version:
if module.params['bw_qos'] and not m... | 5,324,857 |
def test_mnist_basic():
"""
Validate MnistDataset
"""
logger.info("Test MnistDataset Op")
# case 1: test loading whole dataset
data1 = ds.MnistDataset(DATA_DIR)
num_iter1 = 0
for _ in data1.create_dict_iterator(num_epochs=1):
num_iter1 += 1
assert num_iter1 == 10000
# c... | 5,324,858 |
def AC3(csp, queue=None, removals=None, arc_heuristic=csp.dom_j_up):
"""[Figure 6.3]"""
if queue is None:
queue = {(Xi, Xk) for Xi in csp.variables for Xk in csp.neighbors[Xi]}
csp.support_pruning()
queue = arc_heuristic(csp, queue)
checks = 0
while queue:
(Xi, Xj) = queu... | 5,324,859 |
def load(
name: str,
ids: Optional[List[Union[str, int]]] = None,
limit: Optional[int] = None,
) -> pandas.DataFrame:
"""Load dataset data to a pandas DataFrame.
Args:
name:
The dataset name.
ids:
If provided, load dataset records with given ids.
limi... | 5,324,860 |
def _stringify(values):
"""internal method: used to convert values to a string suitable for an xml attribute"""
if type(values) == list or type(values) == tuple:
return " ".join([str(x) for x in values])
elif type(values) == type(True):
return "1" if values else "0"
else:
return ... | 5,324,861 |
def xml_safe(s):
"""Returns the XML-safe version of a given string.
"""
new_string = s.replace("&", "&").replace("<", "<")
new_string = new_string.replace("\r", "").replace("\n", "<br/>")
return new_string | 5,324,862 |
def range_values(ent):
"""Extract values from the range and cached label."""
data = {}
range_ = [e for e in ent.ents if e._.cached_label.split('.')[0] == 'range'][0]
values = re.findall(FLOAT_RE, range_.text)
if not all([re.search(INT_TOKEN_RE, v) for v in values]):
raise RejectMatch
... | 5,324,863 |
def plot_mw_nii_bars(ax, snr_min = None, shaded_kwargs = {}, **kwargs):
"""
Plots vertical lines and bars on bpt Diagram for Tilted Disk where only
NII/HA line is detected
Parameters
----------
ax 'matplotlib.pyplot.figure.axes'
axes to plot lines on
snr_min: 'number', optional, mu... | 5,324,864 |
def get_weights(connections):
"""Returns the weights of the connections
:param connections:
:return: Numpy array of weights
"""
return np.array(nest.GetStatus(connections, keys="weight")) | 5,324,865 |
def w2v_matrix_vocab_generator(w2v_pickle):
"""
Creates the w2v dict mapping word to index and a numpy matrix of (num words, size of embedding), words will
be mapped to their index, such that row ith will be the embedding of the word mapped to the i index.
:param w2v_pickle: Dataframe containing token ... | 5,324,866 |
def concat(
dfs, axis=0, join="outer", uniform=False, filter_warning=True, ignore_index=False
):
"""Concatenate, handling some edge cases:
- Unions categoricals between partitions
- Ignores empty partitions
Parameters
----------
dfs : list of DataFrame, Series, or Index
axis : int or s... | 5,324,867 |
def resize(dataset: xr.Dataset, invalid_value: float = 0) -> xr.Dataset:
"""
Pixels whose aggregation window exceeds the reference image are truncated in the output products.
This function returns the output products with the size of the input images : add rows and columns that have been
truncated. Thes... | 5,324,868 |
def score(graphs, schema, url, port):
"""
graphs is expected to be a list of dictionaries, where each entry in the
list represents a graph with
* key idx -> index value
* key nodes -> list of ints representing vertices of the graph
* key edges -> list of list of ints representing edges of grap... | 5,324,869 |
def group_by_author(commits: List[dict]) -> Dict[str, List[dict]]:
"""Group GitHub commit objects by their author."""
grouped: Dict[str, List[dict]] = {}
for commit in commits:
name = commit["author"]["login"]
if name not in grouped:
grouped[name] = []
grouped[name].appen... | 5,324,870 |
def convert(name):
"""
CamelCase to under_score
:param name:
:return:
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | 5,324,871 |
def plot(graph, particles=None, polyline=None, particles_alpha=None, label_start_end=True,
bgcolor='white', node_color='grey', node_size=0, edge_color='lightgrey', edge_linewidth=3, **kwargs):
"""
Plots particle approximation of trajectory
:param graph: NetworkX MultiDiGraph
UTM projection
... | 5,324,872 |
def non_empty_string(value):
"""Must be a non-empty non-blank string"""
return bool(value) and bool(value.strip()) | 5,324,873 |
def metadataAbstractElementRequiredChildElementTest6():
"""
Optional child elements, child elements required.
>>> doctestMetadataAbstractElementFunction(
... testMetadataAbstractElementKnownChildElements,
... metadataAbstractElementRequiredChildElementTest6(),
... requiredChildEleme... | 5,324,874 |
def index():
"""
List containers
"""
containers = g.api.get_containers()
clonable_containers = []
for container in containers:
if container['state'] == 'STOPPED':
clonable_containers.append(container['name'])
context = {
'containers': containers,
'clonable... | 5,324,875 |
def spatial_discounting_mask():
"""
Input:
config: Config should have configuration including HEIGHT, WIDTH,
DISCOUNTED_MASK.
Output:
tf.Tensor: spatial discounting mask
Description:
Generate spatial discounting mask constant.
Spatial discounting mask is first int... | 5,324,876 |
def does_file_exist(filepath:Path)-> bool:
"""
Checks if file path exists.
"""
if os.path.exists(filepath):
LOG.info("Data path detected:\n{}\.".format(filepath))
return True
else:
LOG.info("Data path\n{}\nnot detected. Downloading now...".format(filepath))
return F... | 5,324,877 |
def pca_results(scaled, pca):
"""
Plot the explained variance of the DataSet as a barchart,
and return a DataFrame with the explained variance for each
feature, for each dimension of the PCA.
-----------------------------------------------------------
# Parameters:
# scaled (pd.DataFrame): The DataFrame in wh... | 5,324,878 |
def get_uid_from_user(user):
"""Return UID from user name
Looks up UID matching the supplied user name;
returns None if no matching name can be found.
NB returned UID will be an integer.
"""
try:
return pwd.getpwnam(str(user)).pw_uid
except KeyError:
return None | 5,324,879 |
def get_approval_distance(election_1: ApprovalElection, election_2: ApprovalElection,
distance_id: str = None) -> float or (float, list):
""" Return: distance between approval elections, (if applicable) optimal matching """
inner_distance, main_distance = extract_distance_id(distance_... | 5,324,880 |
def test_plot_part_of():
"""Plot both the standard 'is_a' field and the 'part_of' relationship."""
fout_log = "plot_relationship_part_of.log"
obj = _Run()
names = NAME2GOIDS
# names = ["heartjogging"]
with open(fout_log, 'w') as prt:
for name in names:
goids = NAME2GOIDS[name... | 5,324,881 |
def get_base_folder():
"""Return the base folder of ProfileQC."""
return Path(__file__).parent | 5,324,882 |
def u16le_list_to_byte_list(data):
"""! @brief Convert a halfword array into a byte array"""
byteData = []
for h in data:
byteData.extend([h & 0xff, (h >> 8) & 0xff])
return byteData | 5,324,883 |
def test_Add2():
""" x+i+y, i=0..100
"""
n = 101
while n:
n -= 1
x + n + y | 5,324,884 |
def test_list_non_positive_integer_min_length_1_nistxml_sv_iv_list_non_positive_integer_min_length_2_5(mode, save_output, output_format):
"""
Type list/nonPositiveInteger is restricted by facet minLength with
value 6.
"""
assert_bindings(
schema="nistData/list/nonPositiveInteger/Schema+Insta... | 5,324,885 |
def process_IBM_strings(string):
"""
Format all the IBM string in the same way, creating a single string of lowercase characters
:param string:
:return:
"""
parts = string.split()
result = str(parts[0].lower())
for part in parts[1:]:
result += " " + str(part.lower())
return r... | 5,324,886 |
def get_sample_size(number_of_clones, fold_difference, error_envelope_x_vals, error_envelope_y_vals, number_of_error_bars):
"""
This returns the number of cells in a sample that produce the an
error bar of max_error_bar for a given number_of_clones in the
parent population.
This is the inverse ... | 5,324,887 |
def get_r2(y,yhat):
""" Calcualte the coef. of determination (R^2) """
ybar = np.mean(y)
return 1 - (np.sum((y-yhat)**2))/(np.sum((y-ybar)**2)) | 5,324,888 |
def get_context() -> Dict[str, Any]:
"""
Retrieve the current Server Context.
Returns:
- Dict[str, Any]: the current context
"""
ctx = _context.get() # type: ignore
if ctx is not None:
assert isinstance(ctx, dict)
return ctx.copy()
else:
return {} | 5,324,889 |
def kiinteisto_alueiksi(kiinteisto):
"""
kiinteist: kiinteisto/property register
An artificial property / constituency division will be made for the regionalization of postal codes.
A brute-force distribution is used, where the relative number of residential properties in the constituen... | 5,324,890 |
def tokenizeBedStream(bedStream):
"""
Iterator through bed file, returning lines as list of tokens
"""
for line in bedStream:
if line != '':
tokens = line.split()
yield tokens | 5,324,891 |
def test_constructor_types():
""" """
tc = TaxonomyConverter()
for dname, conv in tc.convs.items():
assert isinstance(conv, torch.nn.Module) | 5,324,892 |
def G1DListCrossoverSinglePoint(genome, **args):
"""
The crossover of G1DList, Single Point
.. warning:: You can't use this crossover method for lists with just one element.
"""
sister = None
brother = None
gMom = args["mom"]
gDad = args["dad"]
if len(gMom) == 1:
utils.raise... | 5,324,893 |
def optional_observation_map(env, inner_obs):
"""
If the env implements the `observation` function (i.e. if one of the
wrappers is an ObservationWrapper), call that `observation` transformation
on the observation produced by the inner environment
"""
if hasattr(env, 'observation'):
retur... | 5,324,894 |
def RunMetadataLabels(run_metadata):
"""Returns all labels in run_metadata."""
labels = []
for dev_stats in run_metadata.step_stats.dev_stats:
for node_stats in dev_stats.node_stats:
labels.append(node_stats.timeline_label)
return labels | 5,324,895 |
def run(DEBUG, HOSTNAME, PORT, SQL_ROUTE):
"""
This function actually runs the application using some
configuration variables located at the config module.
This function has to be runned from the run.py file
"""
global dh
dh = DataHandler(SQL_ROUTE)
setup_table(dh)
app.run(host=HOST... | 5,324,896 |
def ShouldPackageFile(filename, target):
"""Returns true if the file should be a part of the resulting archive."""
if chromium_utils.IsMac():
file_filter = r'^.+\.(a|dSYM)$'
elif chromium_utils.IsLinux():
file_filter = r'^.+\.(o|a|d)$'
else:
raise NotImplementedError('%s is not supported.' % sys.pla... | 5,324,897 |
def is_entity_extractor_present(interpreter: Interpreter) -> bool:
"""Checks whether entity extractor is present."""
extractors = get_entity_extractors(interpreter)
return extractors != [] | 5,324,898 |
def get_workflow(name, namespace):
"""Get a workflow."""
api_group = "argoproj.io"
api_version = "v1alpha1"
co_name = "workflows"
co_client = _get_k8s_custom_objects_client()
return co_client.get_namespaced_custom_object(api_group, api_version,
n... | 5,324,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.