content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_required_webots_version():
"""Return the Webots version compatible with this version of the package."""
return 'R2020b revision 1' | 5,318,100 |
def ScoreStatistics(scores, percentile):
"""
Capture statistics related to the gencall score distribution
Args:
scores (list(float)): A list of gencall scores
percentile (int): percentile to calculate
gc_10 : 10th percentile of Gencall score distribution
gc_50 : 50th... | 5,318,101 |
def download_drill(load=True): # pragma: no cover
"""Download scan of a power drill.
Originally obtained from Laser Design.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returne... | 5,318,102 |
def schlieren_colormap(color=[0, 0, 0]):
"""
Creates and returns a colormap suitable for schlieren plots.
"""
if color == 'k':
color = [0, 0, 0]
if color == 'r':
color = [1, 0, 0]
if color == 'b':
color = [0, 0, 1]
if color == 'g':
color = [0, 0.5, 0]
if c... | 5,318,103 |
def evaluate_binned_cut(values, bin_values, cut_table, op):
"""
Evaluate a binned cut as defined in cut_table on given events
Parameters
----------
values: ``~numpy.ndarray`` or ``~astropy.units.Quantity``
The values on which the cut should be evaluated
bin_values: ``~numpy.ndarray`` or... | 5,318,104 |
def add_EVM(final_update, wd, consensus_mapped_gff3):
"""
"""
db_evm = gffutils.create_db(final_update, ':memory:', merge_strategy='create_unique', keep_order=True)
ids_evm = [gene.attributes["ID"][0] for gene in db_evm.features_of_type("mRNA")]
db_gmap = gffutils.create_db(consensus_mapped_gff3,... | 5,318,105 |
def validate(schema):
"""Validate the schema
Validations performed:
Values of default data (if any)
Existence of dynamic modules
Enums keyed by string value
Args:
schema (pkcollections.Dict): app schema
"""
sch_models = schema.model
sch_enums = schema.enum
s... | 5,318,106 |
def smartCheck(policy_del, policy_add,
list_rules_match_add=None,
matched_rules_extended=None,
subpolicy=False,
print_add_matches=False,
print_progress=False,
DEBUG=False):
"""
smartCheck will compare two policies trying t... | 5,318,107 |
def _write_training_dataset_hdfs_hdf5(df, write_mode, path, training_dataset):
"""
Writes a dataframe of data as a training dataset on HDFS in the hdf5 format
Args:
:df: the dataframe to materialize
:path: the hdfs path where the dataframe will be materialized
:write_mode: spark wri... | 5,318,108 |
def generator(samples, batch_size=32, is_training=True):
"""
Lazy batch train/validation generator for memory efficiency
"""
num_samples = len(samples)
#vertical, horizontal range for random translation
x_translate_range = 100
y_translate_range = 10
while 1: # Loop forever so the gener... | 5,318,109 |
def test_tuning_transm():
"""Function to test the tuning function."""
tunning_function('transm') | 5,318,110 |
def create_volume(cinder, size, name=None, image=None):
"""Create cinder volume.
:param cinder: Authenticated cinderclient
:type cinder: cinder.Client
:param size: Size of the volume
:type size: int
:param name: display name for new volume
:type name: Option[str, None]
:param image: Ima... | 5,318,111 |
def function_linenumber(function_index=1, function_name=None, width=5):
"""
:param width:
:param function_index: int of how many frames back the program should look (2 will give the parent of the caller)
:param function_name: str of what function to look for (should not be used with function_index
... | 5,318,112 |
def get_event_times(
data: np.ndarray,
kernel_size: int = 71,
skip_first: int = 20 * 60,
th: float = 0.1,
abs_val: bool = False,
shift: int = 0,
debug: bool = False,
) -> Tuple[list, list]:
"""
Given a 1D time serires it gets all the times there's a new 'stimulus' (signal going >... | 5,318,113 |
def setup_persistent_monitoring():
"""
Change monitoring backend to OCS
"""
sc = helpers.default_storage_class(interface_type=constants.CEPHBLOCKPOOL)
# Get the list of monitoring pods
pods_list = get_all_pods(
namespace=defaults.OCS_MONITORING_NAMESPACE,
selector=["prometheus",... | 5,318,114 |
def init_base_item(mocker):
"""Initialize a dummy BaseItem for testing."""
mocker.patch.multiple(
houdini_package_runner.items.base.BaseItem,
__abstractmethods__=set(),
__init__=lambda x, y: None,
)
def _create():
return houdini_package_runner.items.base.BaseItem(None)
... | 5,318,115 |
def create_sftp_client2(host, port, username, password, keyfilepath, keyfiletype):
"""
create_sftp_client(host, port, username, password, keyfilepath, keyfiletype) -> SFTPClient
Creates a SFTP client connected to the supplied host on the supplied port authenticating as the user with
supplied user... | 5,318,116 |
def get_vectorize_layer(max_features=10000, sequence_length=250) \
-> tf.keras.layers.experimental.preprocessing.TextVectorization:
"""Transforms a batch of strings into either a list of token indices or a dense representation.
Parameters
----------
max_features : int
The maximum size o... | 5,318,117 |
def test_login_success(self):
"""
In this case both are false, meaning the if statements doesn't get executed
"""
return login_user(test_user.email, test_user.password) == test_user | 5,318,118 |
def write_function_child(string_obj, function, input_flow_list, output_flow_list,
xml_attribute_list):
"""Construct plantuml_text recursively"""
function_input_port = []
function_output_port = []
external_input_port = []
external_output_port = []
parent_function_port = [... | 5,318,119 |
def test_map_and_unmap_attribute():
"""tests the mapping of an attribute. 'first_name' in 'people_tiny.csv' to 'all_names' in the
minimal_schema_mapping project. Checks that the mappings don't contain that mapping to start,
then maps, and asserts that it has that mapping"""
client = utils.client.create(... | 5,318,120 |
def test_arduino_io_shutdown(serial_handlers, memory_db, msg_publisher, msg_subscriber,
cmd_publisher, cmd_subscriber):
"""Confirm request to shutdown is recorded."""
board = 'telemetry'
port = 'arduinosimulator://?board=' + board
board = board + '_board'
with open_seria... | 5,318,121 |
def fetch_latest():
"""Function to import all the replication files since the last import or the
last 1000.
FIXME: define error in except line
"""
try:
last_import = Import.objects.all().order_by('-end')[0].end
except:
last_import = None
sequence = get_last_replication_id()
... | 5,318,122 |
def Train(corpus):
"""
Parameters:
corpus: String
"""
# List<TaggedWord>
startMarkers = []
startMarkers.append(TaggedWord("<STARTTAG>", "<STARTTAG>"))
startMarkers.append(TaggedWord("<STARTTAG>", "<STARTTAG>"))
# List<TaggedWord>
endMarkers = []
endMarkers.append(TaggedWo... | 5,318,123 |
async def tally():
"""
Get the results of all election tallies.
Returns:
Tally results for each contest in the election
"""
tally = election.get_election_tally()
results = {
"contests": [
{
"contest": contest,
"selections": [
... | 5,318,124 |
def expand_parameters_from_remanence_array(magnet_parameters, params, prefix):
"""
Return a new parameters dict with the magnet parameters in the form
'<prefix>_<magnet>_<segment>', with the values from 'magnet_parameters'
and other parameters from 'params'.
The length of the array 'magnet_paramete... | 5,318,125 |
def addToOrStartNewRange(oldRange, tissueRangeScores, newPosition, vals, tissues, tissueFhs):
"""For all the tissues in vals, figure out if we are still in the same exon
and adding to the previous range/score combo, or if we are in the same
exon but with a different score, or a new exon alto... | 5,318,126 |
def transformNode(doc, newTag, node=None, **attrDict):
"""Transform a DOM node into new node and copy selected attributes.
Creates a new DOM node with tag name 'newTag' for document 'doc'
and copies selected attributes from an existing 'node' as provided
in 'attrDict'. The source 'node' can be None. At... | 5,318,127 |
def jsonify(status=200, indent=2, sort_keys=True, **kwargs):
""" Creates a jsonified response. Necessary because the default
flask.jsonify doesn't correctly handle sets, dates, or iterators
Args:
status (int): The status code (default: 200).
indent (int): Number of spaces to indent (default... | 5,318,128 |
def _delete_task(project, collection, task):
"""Deletes a document from the firestore collection.
Args:
project: String representing the GCP project to use
collection: A string representing the firestore collection
task: The firestore document to be deleted
"""
db = firestore.Client(project)
_dec... | 5,318,129 |
def detect_symbols(
sources_dir: Path,
host: str = "http://127.0.0.1",
port: int = 8001,
try_expand_macros: Optional[bool] = None,
require_blank_border: Optional[bool] = None,
insert_function_elements: Optional[bool] = None,
merge_adjacent_elements: Optional[bool] = None,
) -> List[Symbol]:
... | 5,318,130 |
def browse(dataset_id=None, endpoint_id=None, endpoint_path=None):
"""
- Get list of files for the selected dataset or endpoint ID/path
- Return a list of files to a browse view
The target template (browse.jinja2) expects an `endpoint_uri` (if
available for the endpoint), `target` (either `"dataset... | 5,318,131 |
def tag_group(tag_group, tag):
"""Select a tag group and a tag."""
payload = {"group": tag_group, "tag": tag}
return payload | 5,318,132 |
def rollup(step: Step, store: TableStore):
"""Rollup a table to produce an aggregation summary.
:param step:
Parameters to execute the operation.
See :py:class:`~data_wrangling_components.engine.verbs.rollup.RollupArgs`.
:type step: Step
:param store:
Table store that co... | 5,318,133 |
def prefix_provider(string: str) -> str:
"""Prefix string with `_{provider}_`"""
from optimade.server.config import CONFIG
if string in CONFIG.provider_fields.get("structures", []):
return f"_{CONFIG.provider.prefix}_{string}"
return string | 5,318,134 |
def combine_sequences(vsequences, jsequences):
"""
Do a pairwise combination of the v and j sequences to get putative germline sequences for the species.
"""
combined_sequences = {}
for v in vsequences:
vspecies, vallele = v
for j in jsequences:
_, jallele= j
... | 5,318,135 |
def read_seq_file(filename):
"""Reads data from sequence alignment test file.
Args:
filename (str): The file containing the edge list.
Returns:
str: The first sequence of characters.
str: The second sequence of characters.
int: The cost per gap in a sequence.
... | 5,318,136 |
def test_restarting():
""" Test stopping and starting the ioloop.
"""
res = []
def add_res(i):
res.append(i)
def try_start():
try:
app.start()
except RuntimeError:
res.append('RTE')
# Create new ioloop always
loop = asyncio.new_event_loop()
... | 5,318,137 |
def OrthogonalInit(rng, sizeX, sizeY, sparsity=-1, scale=1):
"""
Orthogonal Initialization
"""
sizeX = int(sizeX)
sizeY = int(sizeY)
assert sizeX == sizeY, 'for orthogonal init, sizeX == sizeY'
if sparsity < 0:
sparsity = sizeY
else:
sparsity = numpy.minimum(sizeY, spa... | 5,318,138 |
def build_complement(dna):
"""
:param dna: str, the DNA strand that user gives(all letters are upper case)
:return: str, the complement of dna
"""
new_dna = ''
for base in dna:
if base == 'A':
new_dna += 'T'
elif base == 'T':
new_dna += 'A'
elif ba... | 5,318,139 |
def com_google_fonts_check_162(ttFont, style):
""" Check name table: TYPOGRAPHIC_SUBFAMILY_NAME entries. """
from unidecode import unidecode
from fontbakery.utils import name_entry_id
from fontbakery.constants import NAMEID_TYPOGRAPHIC_SUBFAMILY_NAME
failed = False
style_with_spaces = style.replace('Italic... | 5,318,140 |
def _seasonal_prediction_with_confidence(arima_res, start, end, exog, alpha,
**kwargs):
"""Compute the prediction for a SARIMAX and get a conf interval
Unfortunately, SARIMAX does not really provide a nice way to get the
confidence intervals out of the box, so we ha... | 5,318,141 |
def attack(X_train, y_train, X_test, y_test, unmon_label, args, VERBOSE=1):
"""
Perform WF training and testing
"""
classes = len(set(list(y_train)))
print(classes)
# shuffle and split for val
s = np.arange(X_test.shape[0])
np.random.shuffle(s)
sp = X_test.shape[0]//2
X_va = X_t... | 5,318,142 |
def create_lexicon(pos, neg):
"""Create Lexicon."""
lexicon = []
for fi in [pos, neg]:
with open(fi, 'r') as f:
contents = f.readlines()
for l in contents[:hm_lines]:
all_words = word_tokenize(l.lower())
lexicon += list(all_words)
lexicon =... | 5,318,143 |
def trailing_zeros(x):
""" Number of trailing zeros in a number."""
if x % 1 != 0 | x == 0:
return 0
magn = floor(log10(x))
trailing = 0
for i in range(1, magn + 1):
if x % (10 ** i) == 0:
trailing = i
else:
break
return trailing | 5,318,144 |
def crawler(root_url, out_file, out_format='xml', maxtasks=100,
batch_size=10000, prefix=None, load=False):
"""
run crowler
:param root_url: Site root url
:param out_file: path to the out file
:param out_format: format of out file [xml, txt]
:param maxtasks: max count of tasks
:r... | 5,318,145 |
def _check_dependency(dependency: xml.etree.ElementTree.Element,
include: List[str],
exclude: Optional[List[str]] = None) -> bool:
"""Check a dependency for a component.
Verifies that the given {dependency} is satisfied by components listed in
`include` or `exclu... | 5,318,146 |
def top_height(sz):
"""Returns the height of the top part of size `sz' AS-Waksman network."""
return sz // 2 | 5,318,147 |
def insert_sequence_read_set(db: DatabaseSession, sample_id: int, urls: list):
"""
Insert sequencing read set directly into warehouse.sequence_read_set,
with the *sample_id* and *urls*.
"""
LOG.debug(f"Inserting sequence read set for sample {sample_id}")
data = {
"sample_id": sample_id,... | 5,318,148 |
def constructAuxGraph(path):
"""
This function constructs the auxiliary graph given a python dictionary as argument wich
consists of the # of the path as the key of the dictionary and the path (source, intermediate
nodes, destination) that a predifined route has to traverse in order to go from the sou... | 5,318,149 |
def eval_time(function: Callable):
"""decorator to log the duration of the decorated method"""
def timed(*args, **kwargs):
log = logging.getLogger(__name__)
time_start = time.time()
result = function(*args, **kwargs)
time_elapsed = round(time.time() - time_start, 2)
log... | 5,318,150 |
def parse_data(
data: Union[AnnData, DataFrame, np.ndarray],
gene_names: Optional[Iterable[str]] = None,
sample_names: Optional[Iterable[str]] = None
) -> Tuple[np.ndarray, list, list]:
"""Reduces :class:`~anndata.AnnData` and :class:`~pandas.DataFrame` to a :class:`~numpy.dnarray` and extracts
`gen... | 5,318,151 |
def german_actionset_unaligned(german_X):
"""Generate an actionset for German data."""
# setup actionset
action_set = ActionSet(X = german_X)
immutable_attributes = ['Age', 'Single', 'JobClassIsSkilled', 'ForeignWorker', 'OwnsHouse', 'RentsHouse']
action_set[immutable_attributes].mutable = Fals... | 5,318,152 |
def recursively_contains(val1, val2, parent_key=None):
"""
Returns True if val1 is a subset of val2 both in its items as
well as the items's items if it's a list or a dictionary.
Returns False if there are items within val1 but not in val2.
"""
# If not same data type, fail
if type(val1) != ... | 5,318,153 |
def generate_email(sender, recipient, subject, body, attachment_path):
"""Creates an email with an attachement."""
# Basic Email formatting
message = email.message.EmailMessage()
message["From"] = sender
message["To"] = recipient
message["Subject"] = subject
message.set_content(body)
# Process the attachment a... | 5,318,154 |
def scroll_to_line(view, line, animate):
"""Scroll y-axis so that `line` appears at the top of the viewport."""
x, y = view.text_to_layout(view.text_point(line, 0))
view.run_command('_sublime_linter_scroll_y', {'y': y, 'animate': animate}) | 5,318,155 |
def test_mode(user, godmode=False, questions_list=None, quiz_id=None):
"""creates a trial question paper for the moderators"""
if questions_list is not None:
trial_course = Course.objects.create_trial_course(user)
trial_quiz = Quiz.objects.create_trial_quiz(trial_course, user)
trial_que... | 5,318,156 |
def add_auth_token(auth_token: str, desc: Optional[str],
call_count_limit: Optional[int] = None,
call_count_limit_relative: bool = False) -> bool:
"""
Add or update an auth token to the DB. Local cache will be updated during next API request in is_auth_token_valid(...)!
... | 5,318,157 |
def id_for_new_id_style(old_id, is_metabolite=False):
""" Get the new style id"""
new_id = old_id
def _join_parts(the_id, the_compartment):
if the_compartment:
the_id = the_id + '_' + the_compartment
return the_id
def _remove_d_underscore(s):
"""Removed repeated, le... | 5,318,158 |
def analysis_instance_start_success(instance_uuid, instance_name, records,
action=False, guest_hb=False):
"""
Analyze records and determine if instance is started
"""
always = True
possible_records \
= [(action, NFV_VIM.INSTANCE_NFVI_ACTION_START),
... | 5,318,159 |
def tensorboards(ctx, query, sort, page):
"""List tensorboard jobs for this project.
Uses [Caching](/references/polyaxon-cli/#caching)
"""
user, project_name = get_project_or_local(ctx.obj.get('project'))
page = page or 1
try:
response = PolyaxonClient().project.list_tensorboards(usern... | 5,318,160 |
def evaluate_on_semeval_2012_2(w):
"""
Simple method to score embedding using SimpleAnalogySolver
Parameters
----------
w : Embedding or dict
Embedding or dict instance.
Returns
-------
result: pandas.DataFrame
Results with spearman correlation per broad category with speci... | 5,318,161 |
def setup(hass, config):
"""Set up MagicHome Component."""
from magichome import MagicHomeApi
magichome = MagicHomeApi()
username = config[DOMAIN][CONF_USERNAME]
password = config[DOMAIN][CONF_PASSWORD]
company = config[DOMAIN][CONF_COMPANY]
platform = config[DOMAIN][CONF_PLATFORM]
has... | 5,318,162 |
def download_all_files_from_directory_rec(source_dir, target_dir):
"""Downloads all files in the Google Drive directory at [source_dir] (recursively)
into the [target_dir] on the local machine."""
drive = Drive("https://www.googleapis.com/auth/drive.readonly")
files = drive.ls(source_dir)
for f... | 5,318,163 |
def valid_lsi(addr):
"""Is the string a valid Local Scope Identifier?
>>> valid_lsi('1.0.0.1')
True
>>> valid_lsi('127.0.0.1')
False
>>> valid_lsi('1.0.1')
False
>>> valid_lsi('1.0.0.365')
False
>>> valid_lsi('1.foobar')
False
"""
parts = addr.split('.')
if not ... | 5,318,164 |
def test_cray_hsm_state_components_delete(cli_runner, rest_mock):
""" Test `cray hsm state components delete` with valid params """
runner, cli, config = cli_runner
url_template = '/apis/smd/hsm/v1/State/Components'
comp = 'x0c0s1b0n0'
result = runner.invoke(cli, ['hsm', 'state', 'components', 'del... | 5,318,165 |
def imshow_coocc(coocc, percent=True, ax=None):
"""visualize profile class co-occurrence matrix"""
ax = ax or plt.gca()
size = coocc.shape[0]
annot = (coocc*100).round().astype(int).values if percent else coocc.values
ax.imshow(coocc.T)
for x in range(size):
for y in range(size):
... | 5,318,166 |
def check_options(input_dir1, input_dir2, output_dir, chunk_size, usage):
"""
Make sure the supplied options are meaningful. Separate from the
process_options function to curb function length.
"""
# Check all arguments before printing usage message
is_invalid = False
# Check that ... | 5,318,167 |
def sub_m(D, C_lasso, C_group, C_ridge, eta=1e0):
"""Solve the Sub_m subproblem."""
return shrink(D, C_lasso * eta, C_group * eta, C_ridge * eta) | 5,318,168 |
def move(arg: str, dest: str):
"""Move files in glob `arg` to `dest` with `shutil.move`"""
for f in glob.glob(arg):
removeIfExists(join(dest, os.path.basename(f)))
shutil.move(f, dest) | 5,318,169 |
def grade(morse_code, inputs):
"""Grades how well the `inputs` represents the expected `morse_code`.
Returns a tuple with three elements. The first is a Boolean telling if we
consider the input good enough (this is the pass/fail evaluation). The next
two elements are strings to be show, respectively, in... | 5,318,170 |
def test_md032_bad_list_within_block_quote_surrounded():
"""
Test to make sure we get the expected behavior after scanning a good file from the
test/resources/rules/MD026 directory that has atx headings that do not end with
punctuation.
"""
# Arrange
scanner = MarkdownScanner()
supplied... | 5,318,171 |
def main():
"""
Main steering function.
"""
dist_pc, OoM = parse_distance()
dist_cm = pc_to_cm(dist_pc, OoM)
print("{} pc = {} cm".format(dist_pc * OoM, dist_cm))
return | 5,318,172 |
def test_macsec_psk_br3(dev, apdev):
"""MACsec PSK (bridge; 3 devices)"""
try:
run_macsec_psk_br(dev, apdev, 3, [10, 20, 30])
finally:
cleanup_macsec_br(count=3) | 5,318,173 |
def create_test_endpoint(client, ec2_client, name=None, tags=None):
"""Create an endpoint that can be used for testing purposes.
Can't be used for unit tests that need to know/test the arguments.
"""
if not tags:
tags = []
random_num = get_random_hex(10)
subnet_ids = create_subnets(ec2_... | 5,318,174 |
def plot_clusters(estimator, X, chart=None, fig=None, axes=None,
n_rows=None, n_cols=None,
sample_labels=None, cluster_colors=None,
cluster_labels=None, center_colors=None,
center_labels=None,
center_width=3,
col... | 5,318,175 |
def head(url):
"""
Make a HEAD request to the URL. If we do not get a 404 then the URL is
valid. If there are any exceptions then return False.
"""
try:
resp = s.head(url, timeout=5, verify=False)
except requests.exceptions.RequestException:
return False
if resp.status_... | 5,318,176 |
def cmd_SetNodeToAbsolutePathRecursive(event):
"""Change "/dirname/" to "@path /absolute/path/to/dirname", recursively"""
c = event.get('c')
for s in run_recursive(c):
cmd_SetNodeToAbsolutePath(event, p=s) | 5,318,177 |
def long_description():
"""Reads the README file"""
with open(pathlib.Path(WORKING_DIRECTORY, "README.rst")) as stream:
return stream.read() | 5,318,178 |
def load_embeddings(embeddings_path, aws=False):
"""Loads pre-trained word embeddings from tsv file.
Args:
embeddings_path - path to the embeddings file.
Returns:
embeddings - dict mapping words to vectors;
dim - dimension of the vectors.
"""
if aws:
embeddings = {}
reader = csv.reader(i... | 5,318,179 |
def dibujar_persona(display, posicion, color):
"""Dibuja la persona en la posición especificada y color definido.
Parámetros
----------
display : Pantalla de Pygame
Pantalla donde se dibujará la persona
posicion : tuple
Posición donde se dibujará la persona
color : Color de Pyga... | 5,318,180 |
async def create_check_request(
installation_url: str, repo_name: str, token: str, check_name: str, head_sha: str
) -> Dict[str, Any]:
"""
Initiate Check after Pull Request was created.
It contains terminal hash from PR, name, unique github id.
"""
org_name = installation_url.rstrip("/").split("... | 5,318,181 |
def get_public_key() -> bytes:
"""
Retrieve the raw public key.
:return: Bytes of key
"""
key = Ed25519PrivateKey.from_private_bytes(config.WEBHOOK_KEY)
return key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) | 5,318,182 |
def send_cat_picture(update: Update, context: CallbackContext):
"""
Обработчик команды /cat и кнопки "Прислать котика"
Args:
update: Контекст бота
context: Внешний контекст
Returns:
None
"""
cat_list = glob("images/*.jp*g")
cat_pic = choice(cat_list)
context.bot... | 5,318,183 |
def kill_child_processes_by_pids(pids_to_kill: List[int], timeout: int = 5) -> None:
"""
Kills child processes for the current process.
First, it sends the SIGTERM signal, and after the time specified by the `timeout` parameter, sends
the SIGKILL signal, if the process is still alive.
:param pids_... | 5,318,184 |
def create_empty_array(n_k, n_vals_i, n_feats):
"""Create null measure in the array form.
Parameters
----------
n_k: int
the number of perturbations
n_vals_i: int
the number of indices of the output measure.
n_feats: int
the number of features.
Returns
-------
... | 5,318,185 |
def transform_bbox(x):
"""
Function purpose: Transform bounding box (str) into geometry
x: bounding box (str)
"""
try:
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(x[0], x[1])
ring.AddPoint(x[2], x[1])
ring.AddPoint(x[2], x[3])
ring.AddPoint(x[0], x[3... | 5,318,186 |
def addUser(username: str, autoGenerateKeys: bool = True, keys: list = []):
"""
Create an user with the corresponding username to the users list and return the corresponding user id which can be used as index
username: name of the user
autoGenerateKeys: generate elGammal keys for the user
keys: bas... | 5,318,187 |
def setup_logging(debug=False):
"""
Set up the logging for hypernode_vagrant_runner
:param bool debug: Log DEBUG level to console (INFO is default)
:return obj logger: The logger object
"""
logger = getLogger('hypernode_vagrant_runner')
logger.setLevel(DEBUG if debug else INFO)
console_h... | 5,318,188 |
def _analytical_expectation_worker_func(indices, programs, params, ops):
"""Compute the expectation of the op[batch_index], w.r.t
circuit[batch_index] where batch_index is calculated from indices."""
x_np = _convert_simple_view_to_np(INFO_DICT['arr'], np.float32,
INFO_D... | 5,318,189 |
def test_issue_312_regression():
"""
Make sure there is no trailing comma when writing a CRTF string with
no metadata.
"""
reg = EllipseSkyRegion(center=SkyCoord(279.174990 * u.deg,
-21.257123 * u.deg, frame='fk5'),
width=0.001571... | 5,318,190 |
def remove_conf(module):
"""
Remove specified module from db
Module is identified by its name in lowercase
"""
# Get the original document
res = db.delete("configuration", 'name', str(module).lower())
if res == None:
raise ConfError("Module '%s' wasn't deleted" % module, status_c... | 5,318,191 |
def video(package):
"""method for download video
"""
params = package.get('params')
video_id = params.get(ParamType.VideoID)
request = package.get('request')
range_header = request.META.get('HTTP_RANGE', '').strip()
range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I)
range_mat... | 5,318,192 |
def test_dft(test, expectedShape, raises):
"""Test normalisation works for arrays of one and positive integers."""
import fourier_functions
if raises:
with pytest.raises(raises):
npt.assert_equal(fourier_functions.fourier_to_coefficients(test)[1].shape, expectedShape)
else:
n... | 5,318,193 |
def task_items(max_entries=None):
"""Information about the items in the task queue. Returns a
generator of QueueItems.
Keyword arguments:
max_entries - (int) (Default: None) Maximum number of items to
return. Default is to return all entries.
"""
con = sqlite3.connect(str(DB_PATH))
... | 5,318,194 |
def _remove_anchors_in_pattern(pattern: str) -> Tuple[Optional[str], Optional[str]]:
"""
We need to remove the anchors (``^``, ``$``) since schemas are always anchored.
This is necessary since otherwise the schema validation fails.
See: https://stackoverflow.com/questions/4367914/regular-expression-in-... | 5,318,195 |
def bfs(connections, start, goal=None):
"""
Requires a connections dict with tuples with neighbors per node.
Or a connections function returning neighbors per node
Returns
if goal == None: return dict of locations with neighbor closest to start
elif goal found: returns path to goal
el... | 5,318,196 |
def test_part2_exercise_solution(exercise_solution):
"""Test part 2 on exercise_solution input"""
assert exercise_solution.part2() == 5208377027195 | 5,318,197 |
def uninstall(plugin_name):
"""Uninstalls a plugin (no migrations)."""
validate_plugin(plugin_name)
plugin = PluginRegistry.query.filter_by(name=plugin_name).first_or_404()
if plugin.is_installed:
PluginStore.query.filter_by(plugin_id=plugin.id).delete()
db.session.commit()
clic... | 5,318,198 |
def reverse_complement(dna):
"""
Reverse-complement a DNA sequence
:param dna: string, DNA sequence
:type dna: str
:return: reverse-complement of a DNA sequence
"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
return ''.join([complement[base] for base in dna[::-1]]) | 5,318,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.