content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def wrap_coroutine_in_current_trace_context(coro):
"""Wraps the coroutine in the currently active span."""
trace_span_yields = _current_span_yields()
async def _wrapped():
with _with_span_yields(trace_span_yields):
return await coro
return _wrapped() | 5,302,100 |
def masked_greater_equal(x, value, copy=True):
"""
Mask an array where greater than or equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x >= value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
---... | 5,302,101 |
def most_recent_unique_file(datadir):
"""Returns most recent file of 'unique' type in datadir.
A 'unique' has form <timestamp,secs>.<hostname>.<i-node>.
Returns only the filename of the file, not the entire path.
"""
absdatadir = os.path.abspath(datadir)
if not os.path.isdir(absdatadir):
... | 5,302,102 |
def register_vcs(vcs_type, clazz):
"""
:param vcs_type: id, ``str``
:param clazz: class extending VcsClientBase
"""
_VCS_TYPES[vcs_type] = clazz | 5,302,103 |
def test_missing_inventory_path_or_key(monkeypatch):
"""Test if an error is generated if no key for credential decryption
or no inventory path is provided
"""
with pytest.raises(InventorySourceError,
match=r'Unable to retrieve the key *'):
StaticManagerInventory(MagicMock(... | 5,302,104 |
def GISfast(start_idx,
stop_idx,
params,
train_states):
"""Fast version of Greedy Iterative Search
This search procedure assumes the output layer is a linear layer
Args:
start_idx (int): Start index in the list of operator sets
stop_idx (int): Stop index... | 5,302,105 |
def die(message):
"""Die in a command line way."""
sys.exit(1) | 5,302,106 |
def _get_lines(filename):
"""Returns a list of lines from 'filename', joining any line ending in \\
with the following line."""
with open(filename, "r") as f:
lines = []
accum = ""
for line in f:
if line.endswith("\\\n"):
accum += line[:-2]
els... | 5,302,107 |
def CSMToBinary(D, Kappa):
"""
Turn a cross-similarity matrix into a binary cross-simlarity matrix, using partitions instead of
nearest neighbors for speed
:param D: M x N cross-similarity matrix
:param Kappa:
If Kappa = 0, take all neighbors
If Kappa < 1 it is the fraction of mutual... | 5,302,108 |
def create_runner(path, commands, logfile, run_async=False, name='re.runner'):
"""Create a bash script for executing `commands` sequentially in remote system
Parameters
----------
path : str
Path in remote device, from where `commands` should be executed
commands : list
A list of commands to be execu... | 5,302,109 |
def replace_punctuation_and_whitespace(text):
"""Replace occurrences of punctuation (other than . - _) and any consecutive white space with ."""
rx = re.compile(r"[^\w\s\-.]|\s+")
return rx.sub(".", text) | 5,302,110 |
def url_quote(s, charset='utf-8', safe='/:'):
"""URL encode a single string with a given encoding."""
if isinstance(s, unicode):
s = s.encode(charset)
elif not isinstance(s, str):
s = str(s)
return urllib.quote_plus(s, safe=safe) | 5,302,111 |
def _collective_projector(op: Op, state: ProjectorState, inputs, outputs):
"""Projects a collective op over D devices that has D inputs and D outputs,
one on each device."""
assert len(inputs) == len(outputs)
for in_v, out_v in zip(inputs, outputs):
assert in_v.device == out_v.device
group =... | 5,302,112 |
def remove_symbols(text):
""" Removes all symbols and keep alphanumerics """
whitelist = []
return [re.sub(r'([^a-zA-Z0-9\s]+?)',' ',word) for word in text if word not in whitelist] | 5,302,113 |
def is_url(string):
"""
Function used to check if a string is a valid URL
:param string: element to be checked
:return: True if string is an URL, False otherwise
"""
global IS_URL_REGEX
return re.match(IS_URL_REGEX, string) is not None | 5,302,114 |
def merge_tokens(token_dict, idx_cluster, cluster_num, token_weight=None):
"""Merge tokens in the same cluster to a single cluster.
Implemented by torch.index_add(). Flops: B*N*(C+2)
Return:
out_dict (dict): dict for output token information
Args:
token_dict (dict): dict for input token... | 5,302,115 |
def main():
"""Install process."""
parser = argparse.ArgumentParser()
parser.add_argument("--debug", action="store_true", default=False,
help="Enable debug output")
parser.add_argument("--force", action="store_true", default=False,
help="Force installation... | 5,302,116 |
def arrayfy(data, stats, vocab):
"""
Create data-arrays from the nested-list form of data
data: The data in nested list form
stats: The stats file dumped from preprocessing
vocab: The vocab file dumped from preprocessing
"""
context_len,dec_ip_len,dec_op_len,sent_len=get_len(data... | 5,302,117 |
def filter_out_length_of_one(word):
"""
Filters out all words of length 1
:param word: Input word
:return: None if word is of length 1, else the original word
"""
if len(word) > 1:
return True
return False | 5,302,118 |
def test_session():
"""
Test of Session Commit/Rollback
"""
server = AllegroGraphServer(AG_HOST, AG_PORT, USER, PASSWORD, proxy=AG_PROXY)
catalog = server.openCatalog(CATALOG)
myRepository = catalog.getRepository(STORE, Repository.OPEN)
myRepository.initialize()
common = myRepository.get... | 5,302,119 |
def plot_histograms(frame, img_array):
"""Creates histogram widget and plots it.
Converts image arrays to histograms for display
Args:
frame (Tk Frame): frame to put histograms of images
img_array (np array): np array containing image data
Returns:
hist_plots (Widget): histogr... | 5,302,120 |
def _make_view_conditionalupdate(update, param, grad, delta, view_func, eps):
"""
produces a test and an update vector, if the test is true then one should use the update vector
works with a view of the parameters
"""
param_view = view_func(param)
grad_view = view_func(grad)
cond = _is_scale... | 5,302,121 |
def forbidden(e):
"""
Informs the user that he/she is forbidden from accessing a resource.
Parameters
----------
e : str
A custom error message
Returns
-------
json
JSON representation of the error message
"""
error_code = HTTPStatus.FORBIDDEN.value
resp... | 5,302,122 |
def main():
"""
Parses the command line and dispatches subcommand.
"""
parser = argparse.ArgumentParser(
fromfile_prefix_chars='@',
epilog="""Arguments can also be placed in a text file, one per line.
Pass the file name prefixed by '@': %(prog)s @/path/to/arg_file.txt""... | 5,302,123 |
def eval_env(env, model, n_episodes, render_mode='none'):
"""
Evaluate a model against an environment over N games.
"""
results = {
'reward': np.zeros(n_episodes),
}
with Bar('Eval', max=n_episodes) as bar:
for k in range(n_episodes):
done, state = False, None
... | 5,302,124 |
def bmesh_join(list_of_bmeshes, list_of_matrices, *, normal_update=False, bmesh):
"""takes as input a list of bm references and outputs a single merged bmesh
allows an additional 'normal_update=True' to force _normal_ calculations.
"""
bm = bmesh.new()
add_vert = bm.verts.new
add_face = bm.face... | 5,302,125 |
def example9():
"""
:return:
"""
print(f'{t()}'
f'{translator.translate("नमस्ते दुनिया", dest="pt")}') | 5,302,126 |
def verificarCPF(cpf):"""
:param cpf: Os 11 dígitos do CPF sem pontos e traços
:return: Se o CPF é válido, e sendo válido retorna de qual região é o CPF
""" | 5,302,127 |
def make_peg_parser(input_filename, embeds, module_name=None):
"""Creates the secondary PEG parser file which overrides Grako's defaults
with Multiparser's own customizations.
"""
with open(input_filename, 'r', encoding='utf8') as f:
grammar = f.read()
match = re.search(r'\(\*multiparser_o... | 5,302,128 |
def send_typing_action(func):
"""Sends typing action while processing func command."""
@wraps(func)
def command_func(update, context, *args, **kwargs):
context.bot.send_chat_action(
chat_id=update.effective_message.chat_id, action=ChatAction.TYPING
)
return func(update, ... | 5,302,129 |
def generate_example_2():
"""
Generates example appropriate for testing footprint calculations
:return:
"""
shn = HetNet(params={
'r': {},
'b': {},
'g': {}
})
shn.add_node('r1', dict(color='r'))
shn.add_node('r2', dict(color='r'))
shn.add_node('b1', dict(colo... | 5,302,130 |
def extract_toc(source, setting_key="default", body_only=True, initial_header_level=None, silent=True):
"""
Extract the TOC from the rendered content by the parser
This is very tricky, we add the ``contents`` directive to the document,
parse it again (sic) with docutils, then parse it with Element... | 5,302,131 |
def ordered_variants_and_indices(labels):
"""
Get the ordered variant labels, where the labels are sorted by chromosome
and position, and the indices corresponding to the sort,
Parameters
----------
labels : list(tuple(str))
The list of variant labels. Each label is a tuple of
(... | 5,302,132 |
def run_customized_training(strategy,
bert_config,
max_seq_length,
max_predictions_per_seq,
model_dir,
steps_per_epoch,
steps_per_loop,
... | 5,302,133 |
def _extract_users(status: dict) -> list:
"""Extract the list of users connected to the server."""
try:
return [user["name"] for user in status.raw["players"]["sample"]]
except KeyError:
return [] | 5,302,134 |
def test_cauchy_predict_intervals_mh():
"""
Tests prediction intervals are ordered correctly
"""
model = pf.GAS(data=data, ar=1, sc=1, family=pf.Cauchy())
x = model.fit('M-H', nsims=400)
predictions = model.predict(h=10, intervals=True)
assert(np.all(predictions['99% Prediction Interval'].v... | 5,302,135 |
def read_json(jsonfile):
"""Read a json file into a dictionary
Args:
jsonfile: the name of the json file to read
Returns:
the contents of the JSON file as a dictionary
>>> from click.testing import CliRunner
>>> test = dict(a=1)
>>> with CliRunner().isolated_filesystem():
... ... | 5,302,136 |
def vgg19(
inputs: tf_compat.Tensor,
training: Union[bool, tf_compat.Tensor] = True,
num_classes: int = 1000,
class_type: str = None,
kernel_initializer=tf_compat.glorot_uniform_initializer(),
bias_initializer=tf_compat.zeros_initializer(),
beta_initializer=tf_compat.zeros_initializer(),
... | 5,302,137 |
def create_table(
query_path: str,
query_params: Dict[str, Any],
destination_project: str,
destination_dataset: str,
destination_table: str,
partition_field: str) -> str:
"""Creates a Bigquery table from a parameterized .sql file.
This method executes sql files with {named} parameters and w... | 5,302,138 |
def test_path_type(test_case, type, request, testdata):
"""Run and compare results to expected"""
# target = os.path.join(testdata, request.node.originalname, test_case)
assert True
# assert path_type(target) == type | 5,302,139 |
def filter_inf_n_nan(tensors: List[torch.Tensor], return_indexes: bool = False):
"""Filters out inf and nans from any tensor.
This is usefull when there are instability issues,
which cause a small number of values to go bad.
Args:
tensor (List): tensor to remove nans and infs from.
Returns... | 5,302,140 |
def bytescale(data, cmin=None, cmax=None, high=255, low=0):
"""
Byte scales an array (image).
Byte scaling means converting the input image to uint8 dtype and scaling
the range to ``(low, high)`` (default 0-255).
If the input image already has dtype uint8, no scaling is done.
Parameters
----... | 5,302,141 |
def cupy_cuda_MemoryPointer(nb_arr):
"""Return cupy.cuda.MemoryPointer view of a numba DeviceNDArray.
"""
import cupy
addr = nb_arr.device_ctypes_pointer.value
size = nb_arr.alloc_size
mem = cupy.cuda.UnownedMemory(addr, size, nb_arr)
return cupy.cuda.MemoryPointer(mem, 0) | 5,302,142 |
def InterpretData(regType, data, dataExpand):
"""
Returns the most sensible interpretation of a registry binary blob
according to its registry type. Here is the mapping:
REG_SZ UTF-8 string
REG_EXPAND_SZ UTF-8 string
REG_MULTI_SZ Array of UTF-8 str... | 5,302,143 |
async def test_service_adjust_time_while_running(
hass: ha.HomeAssistant, skip_start, skip_dependencies, skip_history
):
"""Test adjust_time service call while sequence is running."""
full_path = test_config_dir + "service_adjust_time_while_running.yaml"
config = CONFIG_SCHEMA(load_yaml_config_file(ful... | 5,302,144 |
def debye(rho_bulk, charge, permittivity=79, temperature=298.15):
"""Calculate the Debye length.
The Dybe length indicates at which distance a charge will be screened off.
Arguments:
rho_bulk: dictionary of the bulk number densites for each ionic species [1/m^3]
charge: dictionary of the charge of each ionic spec... | 5,302,145 |
def generate_code(graph, ext, testing=None, include=None, include_h=None, init=None):
"""
Display C code to stdout
:param graph: data-flow graph
"""
if ext == '.h':
generate_header_h(graph)
generate_header_c(testing, graph)
if ext == '.h':
generate_include(include_h, graph.p... | 5,302,146 |
def add_require_from_module_paths(requiring_filepath, relative_module_paths):
"""
Add `require("{module}")` in `requiring_filepath`, under the first `--[[add_require]]` tag,
for each relative module path in `relative_module_paths`.
"""
with open(requiring_filepath, 'r') as f:
# create a tem... | 5,302,147 |
def get_traffic_policy(Id=None, Version=None):
"""
Gets information about a specific traffic policy version.
See also: AWS API Documentation
Exceptions
:example: response = client.get_traffic_policy(
Id='string',
Version=123
)
:type Id: string
:param I... | 5,302,148 |
def rl_player(symbol, training):
"""The simple player.
Chooses the first legal move.
"""
move = None # For priming.
last_board = None
while True:
try:
board = yield move
except IllegalMove as e:
raise RuntimeError('illegal move by AI player') from e
... | 5,302,149 |
def zero_float(string):
"""Try to make a string into a floating point number and make it zero if
it cannot be cast. This function is useful because python will throw an
error if you try to cast a string to a float and it cannot be.
"""
try:
return float(string)
except:
return 0 | 5,302,150 |
def http_server():
"""Await the HTTP server to be ready."""
for i in range(1000):
rsp = requests.get("http://localhost:5678")
if rsp.status_code == 200:
break
time.sleep(0.1)
else:
raise RuntimeError("timed out waiting for HTTP server") | 5,302,151 |
def _special_att_handling(attype, col_args): # noqa: C901
""" laundry list of special handling that sqlalchemy
does to convert between a Postgres type and a Sqlalchemy type """
kwargs = {}
if attype == 'uuid':
kwargs = {'as_uuid': True}
args = ()
elif attype == 'numeric':
... | 5,302,152 |
def leapfrog(atoms, step):
"""
Propagate the dynamics of the system via the leapfrog algorithm one step
Parameters
-----------
atoms: ase.Atoms ase.Atoms
The atomic configuration for the system
step: float
The step size for the simulation, the new momentum/velocity is step *
... | 5,302,153 |
def transonic_airliner(display=None,
Propulsion=1,
EngineDia=2.9,
FuselageScaling=[55.902, 55.902, 55.902],
NoseLengthRatio=0.182,
TailLengthRatio=0.293,
WingScaleFactor=44.56,
... | 5,302,154 |
def branch_color():
"""Return red if the current branch is dirty, yellow if the dirtiness can
not be determined, and green if it clean. These are bold, intense colors
for the foreground.
"""
dwd = dirty_working_directory()
if dwd is None:
color = '{BOLD_INTENSE_YELLOW}'
elif dwd:
... | 5,302,155 |
def checksum(data) -> int:
"""
Found on: http://www.binarytides.com/raw-socket-programming-in-python-linux/. Modified to work in python 3.
The checksum is the 16-bit ones's complement of the one's complement sum
of the ICMP message starting with the ICMP Type (RFC 792).
:param data: data to built ch... | 5,302,156 |
def streaming_mean_absolute_error(predictions, labels, weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Computes the mean absolute error between the labels and predictions.
The `str... | 5,302,157 |
def _number_convert(match):
"""
Convert number with an explicit base
to a decimal integer value:
- 0x0000 -> hexadecimal
- 16'h0000 -> hexadecimal
- 0b0000 -> binary
- 3'b000 -> binary
- otherwise -> decimal
"""
prefix, base, number = match.groups()
if prefix is not None:
... | 5,302,158 |
def histy(X,Y,axis=None,**kwargs):
"""
Plot a histogram (using matplotlib.hist) with multiple classes of data
Any additional arguments are passed directly into hist()
Each class of data are plotted as a different color
To specify specific histogram colors, use e.g. facecolor={0:'blue',1:'green',...}... | 5,302,159 |
def detection_targets_graph(proposals, gt_class_ids, gt_boxes, config):
"""Generates detection targets for one image. Subsamples proposals and
generates target class IDs, bounding box deltas, and masks for each.
Inputs:
proposals: [N, (z1, y1, x1, z2, y2, x2)] in normalized coordinates. Might be zero p... | 5,302,160 |
def create_mc2_yaml():
"""
Subroutine to create new yaml file for motioncorr
"""
project_name = get_proj_name()
# Create the yaml file, then automatically update it
prmMod.new_mc2_yaml(project_name)
update_mc2_yaml() | 5,302,161 |
def Enum(name,names,values=None):
"""
Create a new enum class with the given names and values.
Parameters:
[name] A string denoting the name of the enum.
[names] A list of strings denoting the names of the individual enum values.
[values] (optional) A list of integer values of the enums. ... | 5,302,162 |
def prefetch(max_prefetch=1):
"""
Decorator for wrapping a function which returns a generator with `BackgroundGenerator`.
A new instance of `BackgroundGenerator` is created every time the decorated function is called.
Parameters
----------
max_prefetch : int, optional, default: 1
... | 5,302,163 |
def _convert_port_to_geometry(port, layer = 0):
""" Converts a Port to a label and a triangle Device that are then added
to the parent.
Parameters
----------
port : Port
Port to be converted.
layer : int, array-like[2], or set
Specific layer(s) to put label and geometry on.
... | 5,302,164 |
def set_batch_anomaly_score_args(args, fields=None,
dataset_fields=None):
"""Return batch anomaly score args dict
"""
batch_anomaly_score_args = {
"name": args.name,
"description": args.description_,
"tags": args.tag,
"header": args.predictio... | 5,302,165 |
def pgengine(request):
"""Create a sqlalchemy engine for a PostgreSQL DB."""
envFile = request.param
if os.environ.get('DBCONNECTION', None) is None:
with open(envFile) as envVars:
for line in envVars:
var, val = line.split('=', 1)
var = var.strip()
... | 5,302,166 |
def get_next_expid(n=None):
"""
Return the next exposure ID to use from {proddir}/etc/next_expid.txt
and update the exposure ID in that file.
Use file locking to prevent multiple readers from getting the same
ID or accidentally clobbering each other while writing.
Args:
n (int, optiona... | 5,302,167 |
def get_scientific_name(taxon_id):
"""Get scientific name for input taxon_id.
:param taxon_id: NCBI taxonomy identifier
:return scientific_name: scientific name of sample that distinguishes its taxonomy
"""
# endpoint for scientific name
url = 'http://www.ebi.ac.uk/ena/taxonomy/rest/tax-id'
... | 5,302,168 |
def push_span(node, trace_id, parent_id, service_name):
"""Pushes to Honeycomb a span corresponding to a given test result object and returns its randomly generated ID."""
span_id = secrets.token_hex(16)
ev = libhoney.new_event()
ev.add_field("service_name", service_name)
ev.add_field("name", node.n... | 5,302,169 |
def pre_choice(key):
"""Will be what the player hears every time they come back to choice"""
wearing()
storage.screen = "choice"
spk("Press the numbers to choose a bodypart") | 5,302,170 |
def main():
"""
This program is for a game which lasts a very long time- Hangman!!!
At first, users see the dashed words and know how many alphabets they have to guess.
Users have N_TURNS to be able to win this game.
Also, users were expected only to type in one alphabet per round.
"""
strin... | 5,302,171 |
def grafica_nube(
nube,
dim_figura=(10, 10),
titulo='Términos más frecuentes',
ubicacion_archivo='',
graficar=True):
""" Permite graficar o guardar una nube de palabras.
:param nube: (WordCloud) Objeto tipo WordCloud correspondiente a la nube de palabras.
:param dim_... | 5,302,172 |
def expected_ts(ts_id):
"""
Returns a ts composed of expected slope results (having same id as gen_ts method)
:param ts_id: Identifier of the TS to get expected results (see content below for the structure)
:type ts_id: int
:return: the TS data points
:rtype: np.array
"""
if ts_id == ... | 5,302,173 |
def export_data_csv():
""" Build a CSV file with the Client data from the database
:return: The CSV file in StringIO
"""
result = query_client.get_all_clients()
output = io.StringIO()
writer = csv.writer(output)
line = ['Numéro client', 'Nom du client', 'Adresse mail']
writer.writero... | 5,302,174 |
def phi_cdf(phi, eps):
"""The cumulative distribution of a given azimuthal angle :math:`phi` given
a distance between neighboring beads of :math:`\Epsilon = ds/l_p`."""
f0, fpi = phi_Z_0_1_(eps)
return (phi_indef_(phi, eps) - f0)/(fpi - f0) | 5,302,175 |
def main():
"""Registers and transforms each input image and saves the result."""
args = docopt(__doc__)
if args['choose_windows']:
reference = load_image(args['<base_image>'])
windows = get_windows(reference)
np.savetxt(args['<window_file>'], windows.astype('int'), fmt='%i')
e... | 5,302,176 |
def _detect_global_scope(node, frame, defframe):
""" Detect that the given frames shares a global
scope.
Two frames shares a global scope when neither
of them are hidden under a function scope, as well
as any of parent scope of them, until the root scope.
In this case, depending from something ... | 5,302,177 |
def _determine_column_type(data_types):
"""Given a set of Python column types, returns either 'number' or 'string'."""
# Allow None which will be converted to NaN.
if all(
issubclass(t, (_numbers.Number, type(None))) and not issubclass(t, bool)
for t in data_types):
return 'number'
return 'strin... | 5,302,178 |
def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
data = pd.read_csv(filename, parse_dat... | 5,302,179 |
def _discrete_extkalman_update(time, randvar, data, measmod, **kwargs):
"""
"""
mpred, cpred = randvar.mean(), randvar.cov()
if np.isscalar(mpred) and np.isscalar(cpred):
mpred, cpred = mpred * np.ones(1), cpred * np.eye(1)
jacob = measmod.jacobian(time, mpred, **kwargs)
meascov = measmo... | 5,302,180 |
def rating_calc(item, ocurrences, last_ocurrences, total_ocurrences):
""" Calculates the rating of the target language.
"""
rating = ocurrences / total_ocurrences
if item in last_ocurrences:
rating *= 2
if last_ocurrences and item == last_ocurrences[-1]:
rating *= 4
return rating | 5,302,181 |
def render_home_page():
"""The home page.
Returns
-------
Rendered template
A rendered template for the home page.
"""
return render_template(page_constants.HED_TOOLS_HOME_PAGE) | 5,302,182 |
def process(sentence):
"""Pre-process sentence(s) for BERT. Returns:
- tokenized text (with [CLS] and [SEP] tokens)
- segment sentence ids ([0s & 1s])
- indexed tokens """
tokenized_text = ["[CLS]"] + tokenizer.tokenize(sentence) + ["[SEP]"]
tokenized_text = tokenized_text[:512]
... | 5,302,183 |
async def get_group_membership_by_id(group_id, rest_client=None):
"""
Get the membership list of a group.
This is a paginated request that is fairly slow when linked with LDAP.
Args:
group_id (str): group id
Returns:
list: usernames
"""
start = 0
inc = 50
ret = []
... | 5,302,184 |
def getche(): # real signature unknown; restored from __doc__
"""
getche() -> key character
Similar to getch(), but the keypress will be echoed if it represents
a printable character.
"""
pass | 5,302,185 |
def make_tissue2subtissue2sample_id(rawdir: str) -> pd.DataFrame:
"""Construct multi-indexed pd.Series that maps each tissue-subtissue
combination to the corresponding column names"""
sample_id_df = pd.read_csv(
Path(rawdir) / "GTEx_Analysis_v8_Annotations_SampleAttributesDS.txt", sep="\t",
)
... | 5,302,186 |
def get_file_name(path: str):
""" gets 'folder1/folder2/folder3/file_name.extension"
return file_name
"""
# validation
if type(path) != str:
path = str(path)
if not is_valid_path(path):
raise InvalidPathError
# /validation
sep = get_path_sep(path)
... | 5,302,187 |
def dev():
"""
Runs all development services.
"""
processes = []
for p in ['devserver', 'watch', 'livereload']:
processes.append(subprocess.Popen(['fab', p]))
try:
for p in processes:
p.wait()
except KeyboardInterrupt:
for p in processes:
p.se... | 5,302,188 |
def makeKey(password, salt):
"""make master key"""
if not hasattr(password, 'decode'):
password = password.encode('utf-8')
if not hasattr(salt, 'decode'):
salt = salt.lower()
salt = salt.encode('utf-8')
# Here we use 100,000 iterations since that is the default that the
# bit... | 5,302,189 |
def test_packages(host):
"""
Check if packages are installed
"""
packages = []
if host.system_info.distribution in ('debian', 'ubuntu'):
packages = [
'redis-server',
'redis-sentinel',
]
for package in packages:
assert host.package(package).is_in... | 5,302,190 |
async def test_step_origin_coordinates(
hass: HomeAssistant, user_step_result: data_entry_flow.FlowResult
) -> None:
"""Test the origin coordinates step."""
menu_result = await hass.config_entries.flow.async_configure(
user_step_result["flow_id"], {"next_step_id": "origin_coordinates"}
)
ass... | 5,302,191 |
def compute_df_orbit_param(trajectory_df, cpu_count, ram_dir):
"""
Compute the orbital elements of a set of trajectories. Computation are done in parallel.
Parameters
----------
trajectory_df : dataframe
the set of trajectories, the following columns are required : "ra", "dec", "dcmag", "fi... | 5,302,192 |
def run_episode(environment, agent, is_training=False):
"""Run a single episode."""
timestep = environment.reset()
while not timestep.last():
action = agent.step(timestep, is_training)
new_timestep = environment.step(action)
if is_training:
agent.update(timestep, action, new_timestep)
ti... | 5,302,193 |
def determine_col_names_from_input(exprs: List[str], cols: List[str], force: Any = False):
"""
Takes a list of (possibly wildcarded) input column names and a list of actual column names
and determines which, if any, actual column names are matches. If any input column name
expression does not match at ... | 5,302,194 |
def detect(net, im):
""" """
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
# Visualize d... | 5,302,195 |
def HellingsDownsCoeff(phi, theta):
"""
Calculate Hellings and Downs coefficients from two lists of sky positions.
Parameters
----------
phi : array, list
Pulsar axial coordinate.
theta : array, list
Pulsar azimuthal coordinate.
Returns
-------
ThetaIJ : array
... | 5,302,196 |
def save_classifier(cl, fn, use_joblib=True, **kwargs):
"""Save a classifier to disk.
Parameters
----------
cl : classifier object
Pickleable object or a classify.VigraRandomForest object.
fn : string
Writeable path/filename.
use_joblib : bool, optional
Whether to prefer... | 5,302,197 |
def prediction_times(models, X, Y):
"""
Get predictions times for different models
:param models: dictionary of models (models must contain predict function)
:type models: dict
:param X: data for prediction
:type X: array
:param Y: true values
:type Y: array
:return: prediction time... | 5,302,198 |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | 5,302,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.