content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_assign_cmd_failed():
"""
Tests if the assignment was successful or not
"""
cmd = {
"pid": 1234,
"retcode": 1,
"stderr": "",
"stdout": "kern.securelevel: 1 -> 9000",
}
mock_cmd = MagicMock(return_value=cmd)
with patch.dict(openbsd_sysctl.__salt__, {"cm... | 39,000 |
def get_session():
"""
Used for dependency injection in API.
"""
engine = create_engine(settings.database.uri)
session_local = sessionmaker(autocommit=False, autoflush=False, bind=engine)
session = session_local()
try:
yield session
finally:
session.close() | 39,001 |
def _apply_function(x, fname, **kwargs):
"""Apply `fname` function to x element-wise.
# Arguments
x: Functional object.
# Returns
A new functional object.
"""
validate_functional(x)
fun = get_activation(fname)
lmbd = []
for i in range(len(x.outputs)):
lmbd.appe... | 39,002 |
def GetFilesSplitByOwners(files):
"""Returns a map of files split by OWNERS file.
Returns:
A map where keys are paths to directories containing an OWNERS file and
values are lists of files sharing an OWNERS file.
"""
files_split_by_owners = {}
for action, path in files:
dir_with_owners = os.path.... | 39,003 |
def get_url(city):
"""
Gets the full url of the place you want to its weather
You need to obtain your api key from open weather, then give my_api_key the value of your key below
"""
my_api_key = 'fda7542e1133fa0b1b312db624464cf5'
unit = 'metric' # To get temperature in Celsius
weat... | 39,004 |
def login() -> ApiResponse:
"""Login a member"""
member_json = request.get_json()
email = member_json["email"]
password = member_json["password"]
member = MemberModel.find_by_email(email)
if member and member.verify_password(password) and member.is_active:
identity = member_sc... | 39,005 |
def rhythmic_diminution(seq: Sequence, factor: Union[int, float]) -> Iterator[Event]:
"""Return a new stream of events in which all the durations of
the source sequence have been reduced by a given factor.
"""
return (Event(e.pitches, e.duration/factor) for e in seq.events) | 39,006 |
def get_line_offset():
"""Return number of characters cursor is offset from margin. """
user_pos = emacs.point()
emacs.beginning_of_line()
line_start = emacs.point()
emacs.goto_char(user_pos)
return user_pos - line_start | 39,007 |
def cloc_tm(*args, **kwargs):
""" Run cloc including testing and measurements """
cloc('', *args, **kwargs) | 39,008 |
def test_scheduler_task(scheduler: Scheduler) -> None:
"""
scheduler_task decorator should allow custom evaluation.
"""
@scheduler_task("task1", "redun")
def task1(
scheduler: Scheduler, parent_job: Job, sexpr: SchedulerExpression, x: int
) -> Promise:
return scheduler.evaluate(... | 39,009 |
def verse(day):
"""Produce the verse for the given day"""
ordinal = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
'seventh',
'eighth',
'ninth',
'tenth',
'eleventh',
'twelfth',
]
gifts = [
... | 39,010 |
def create_todo(business, ar_year, ar_min_date, ar_max_date, order, enabled): # pylint: disable=too-many-arguments
"""Return a to-do JSON object."""
todo = {
'task': {
'todo': {
'business': business.json(),
'header': {
'name': 'annualRepor... | 39,011 |
async def invite_accept_handler(
invite_id: uuid.UUID = Form(...),
current_user: models.User = Depends(get_current_user),
db_session=Depends(yield_db_session_from_env),
) -> data.GroupUserResponse:
"""
Accept invite request.
If the user is verified, adds user to desired group and marks the invit... | 39,012 |
def read_current_labels(project_id, label_history=None):
"""Function to combine label history with prior labels.
Function that combines the label info in the dataset and
the label history in the project file.
"""
# read the asreview data
as_data = read_data(project_id)
# use label history ... | 39,013 |
def get_mindiff(d1, d2, d3):
""" This function determines the minimum difference from checkboxes 3, 5, and 7,
and counts the number of repetitions. """
min_diff = []
for i, _ in enumerate(d1):
diffs_list = [d1[i], d2[i], d3[i]]
md = min(diffs_list)
if md == d1[i]:
m_... | 39,014 |
def mode(lyst):
"""Returns the mode of a list of numbers."""
# Obtain the set of unique numbers and their
# frequencies, saving these associations in
# a dictionary
theDictionary = {}
for number in lyst:
freq = theDictionary.get(number, None)
if freq == None:
# number... | 39,015 |
def download(dataset, path='./', quiet=False, sub_dir='', debug=False, use_cache=True):
"""Download scripts for retriever."""
args = {
'dataset': dataset,
'command': 'download',
'path': path,
'sub_dir': sub_dir,
'quiet': quiet
}
engine = choose_engine(args)
en... | 39,016 |
def project_permissions(project_id):
"""View and modify a project's permissions.
"""
# does user have access to the project?
project = helpers.get_object_or_exception(Project,
Project.id == project_id,
exceptions... | 39,017 |
def setSupportedTransports(supportedTransports):
"""Set the given supported transports.
:param dict supportedTransports: The transport types that BridgeDB
currently supports.
"""
logging.debug("Setting %d supported transports." %
len(supportedTransports))
global SUPPORTED... | 39,018 |
def fetch_community_crime_data(dpath=None):
"""Downloads community crime data.
This function removes missing values, extracts features, and
returns numpy arrays
Parameters
----------
dpath: str | None
specifies path to which the data files should be downloaded.
default: None
... | 39,019 |
def linear_forward(A, W, b):
"""
Implement the linear part of a layer's forward propagation.
Arguments:
A -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
b ... | 39,020 |
def get_task_reviews_count(request):
"""RESTful version of getting all reviews of a task
"""
logger.debug('get_task_reviews_count is running')
task_id = request.matchdict.get('id', -1)
task = Task.query.filter(Task.id == task_id).first()
if not task:
transaction.abort()
return ... | 39,021 |
async def mp_force(p: 'Player', m: 'Match', msg: Sequence[str]) -> str:
"""Force a player into the current match by name."""
if len(msg) != 1:
return 'Invalid syntax: !mp force <name>'
if not (t := await glob.players.get(name=' '.join(msg))):
return 'Could not find a user by that name.'
... | 39,022 |
def files_iter(start_dir='.', dir_includes=None, dir_excludes=(),
file_includes=None, file_excludes=(), package_only=False):
"""
Iterate over files (recursively) starting in start_dir.
NOTE : all *_includes and *_excludes are applied to *local* directory and file names.
Parameters
-... | 39,023 |
def draw_concat(Gs, Zs, reals, NoiseAmp, in_s, mode, opt):
"""get image at previous scale"""
G_z = in_s
if Gs:
if mode == 'rand':
count = 0
for G, Z_opt, real_curr, real_next, noise_amp in zip(Gs, Zs, reals, reals[1:], NoiseAmp):
if count == 0:
... | 39,024 |
def generate_spline_window_chips(*, image_paths, output_dir):
"""Interpolates all images using a squared spline window"""
if not image_paths:
return []
first_image = image_paths[0]
with rasterio.open(first_image) as src:
chip_size = src.width
n_channels = src.count
asser... | 39,025 |
def read(filename):
"""
Read TOUGHREACT chemical input file.
Parameters
----------
filename : str
Input file name.
"""
with open_file(filename, "r") as f:
out = read_buffer(f)
return out | 39,026 |
def visit_bottomup(f, d):
"""Visits and rewrites a nested-dict ``d`` from the bottom to the top,
using the ``f`` predicate."""
if isinstance(d, dict):
return f({k: visit_bottomup(f, v) for (k, v) in d.items()})
else:
return f(d) | 39,027 |
def watson_transcribe(recording):
"""
Send Recorded Audio to IBM Watson for Transcription and return the transcription as formated word per line.
"""
print(10 * "*" + "Watson Transcribe" + 10 * "*")
watson_username = os.environ.get('WATSON_USERNAME')
watson_password = os.environ.get('WATSON_PASSWORD... | 39,028 |
def main():
"""
This function:
- prepares the loader and stage 1 scripts
- constructs the malicious LNK file, passing the stage 1 script as the encoded
PowerShell command to execute
- appropriately appends the dummy PDF, meterpreter DLL, and loader script to the LNK file
- zips the resulting LNK file
"""
... | 39,029 |
def processNonTerminal(nt):
"""
Finds the rule expansion for a nonterminal and returns its expansion.
"""
return processRHS(grammar.getRHS(nt)) | 39,030 |
def get_attributes_as_highlighted_html(rid):
"""Get column descriptions for a given CSV file. The columns are described in EML
attribute elements.
"""
return {
k: dex.util.get_etree_as_highlighted_html(v)
for k, v in get_attributes_as_etree(rid).items()
} | 39,031 |
def bound_update(unary,X,kernel,bound_lambda,bound_iteration =20, batch = False, manual_parallel =False):
"""
Here in this code, Q refers to Z in our paper.
"""
start_time = timeit.default_timer()
print("Inside Bound Update . . .")
N,K = unary.shape;
oldE = float('inf')
# Initializ... | 39,032 |
def get_walkable_field_names(model: Model, field_types: List[Field] = None) -> List[str]:
"""Get a list with names of all fields that can be walked"""
if field_types is None:
field_types = [ManyToManyField, ManyToOneRel]
fields_to_walk = []
fields = getattr(model, '_meta').get_fields()
for f... | 39,033 |
def normalize(email):
"""
Returns a NormalizedEmail with the appropriate contents
"""
try:
v = validate_email(email)
return NormalizedEmail(v['email'])
except EmailNotValidError as e:
return NormalizedEmail(str(e), error=True) | 39,034 |
def commit(ctx, result, *args, **kwargs):
"""Commit the diary to Git if --commit was supplied."""
g = ctx.obj
if g.commit:
# Redirect to /dev/null if quiet
output = os.devnull if g.quiet else None
# Commit the diary file
code = subprocess.call(["git", "commit", "-m", "Up... | 39,035 |
def valid_flavor_list():
"""
this includes at least 'BIAS', 'LIGHT' based on forDK.tar.gz samples
capitalization inconsistent in forDK.tar.gz samples
need to keep an eye out for additional valid flavors to add
"""
# not sure how to deal with reduced image flavors that I've invented:
# R... | 39,036 |
def start(hypervisor_uri, uuids):
"""Start one or more domains."""
start_domains(uuids, hypervisor_uri=hypervisor_uri) | 39,037 |
def loadfits(filename, dir="", index=0):
"""READS in the data of a .fits file (filename)"""
filename = capfile(filename, '.fits')
filename = dirfile(filename, dir)
if os.path.exists(filename):
# CAN'T RETURN data WHEN USING memmap
# THE POINTER GETS MESSED UP OR SOMETHING
#return... | 39,038 |
async def show_tile_with_body(
request: Request, response: Response,
body: TileRequest,
path: Path = Depends(imagepath_parameter),
extension: OutputExtension = Depends(extension_path_parameter),
headers: ImageRequestHeaders = Depends(),
config: Settings = Depends(get_settings)
):
"""
**`... | 39,039 |
def create_mesh(ob_name, coords, edges=[], faces=[]):
"""Create point cloud object based on given coordinates and name.
Keyword arguments:
ob_name -- new object name
coords -- float triplets eg: [(-1.0, 1.0, 0.0), (-1.0, -1.0, 0.0)]
"""
# Create new mesh and a new object
me = bpy.... | 39,040 |
def get_time_from_datetime(data):
""" Returns a timedelta64 series the form "hh:mm:ss" from data, being a
datetime64 series
"""
time = data.apply(lambda x: np.timedelta64(x.hour, 'h') + np.timedelta64(x.minute, 'm') + np.timedelta64(x.second, 's'))
return time | 39,041 |
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'postgres_db'):
g.postgres_db.close() | 39,042 |
def showLeaderboard(user_id, command, channel):
"""
Command <leaderboard> will display the current leaderboard using Slack's message attachment API
"""
global red_wins, blue_wins
text = ""
attachment = json.dumps([
{
"color": "#ff2b2b",
"text": "Red Team points: " + str(r... | 39,043 |
def mms_feeps_pitch_angles(trange=None, probe='1', level='l2', data_rate='srvy', datatype='electron', suffix=''):
"""
Generates a tplot variable containing the FEEPS pitch angles for each telescope from magnetic field data.
Parameters:
trange : list of str
time range of interest [startt... | 39,044 |
def tokenize(text):
"""Converts text to tokens. Case-folds, removes stop words, lemmatises text.
This is the same tokenization as is done on the training data for the model.
"""
# Set up dict for lemmatisation
tag_map = defaultdict(lambda : "n") # by default, assume nouns
tag_map['J'] = "a" #... | 39,045 |
def test_pin_pod():
"""Tests that a pod can be pinned to a specific host."""
pod_def = pods.ports_pod()
pod_id = pod_def['id']
host = common.ip_other_than_mom()
common.pin_pod_to_host(pod_def, host)
client = marathon.create_client()
client.add_pod(pod_def)
common.deployment_wait(servi... | 39,046 |
def do_command(client, command, indices, params=None):
"""
Do the command.
"""
if command == "alias":
return alias(
client, indices, alias=params['name'], remove=params['remove']
)
if command == "allocation":
return allocation(client, indices, rule=para... | 39,047 |
def initialize (pelicanobj):
"""Initialize the Libravatar plugin"""
pelicanobj.settings.setdefault ('LIBRAVATAR_MISSING', None)
pelicanobj.settings.setdefault ('LIBRAVATAR_SIZE', None) | 39,048 |
def filetostr(filename):
"""
filetostr
"""
try:
with open(filename, "rb") as stream:
return stream.read()
except:
return None | 39,049 |
def _validate_rule_match_criteria(rule, issues, neg_pfx):
"""Validates and canonicalises a rule's match criteria.
Each call validates either the negated or non-negated match criteria.
I.e. the ones with "!" prefixed or not.
:param rule: The dict for the individual rule. If this contains selectors,
... | 39,050 |
def run():
"""Run the script.
- Parsing command-line arguments
- Creating synthetic regression data
- Initiating training process
- Testing final network
"""
### Parse CLI arguments.
parser = argparse.ArgumentParser(description='Nonlinear regression with ' +
... | 39,051 |
def valid_for(days):
"""Return a text saying for how many days
the certificate is valid for or years if it spans over years."""
delta = timedelta(days=days)
value = ''
if delta.days / 365 > 1:
value += '%d years' % (delta.days / 365)
else:
value += '%d days' % delta.days
retu... | 39,052 |
def redditor_info(bot, trigger, match=None):
"""Show information about the given Redditor"""
commanded = re.match(bot.config.core.prefix + 'redditor', trigger)
r = praw.Reddit(
user_agent=USER_AGENT,
client_id='6EiphT6SSQq7FQ',
client_secret=None,
)
match = match or trigger
... | 39,053 |
def tract_generator(sft, affine, bundle, bundle_dict, colors, n_points,
n_sls_viz=3600, n_sls_min=75):
"""
Generates bundles of streamlines from the tractogram.
Only generates from relevant bundle if bundle is set.
Uses bundle_dict and colors to assign colors if set.
Otherwise, r... | 39,054 |
def process_and_combine_responses(output_file, survey_date=None):
"""Combine xlsx files from the ./cw22-survey/data/raw folder containing Mentimeter
survey responses into a single CSV file for analysis.
Args:
output_file (str): The name of the file to save processed survey responses in.
sur... | 39,055 |
def vcr_config() -> dict:
"""VCR config that adds a custom before_record_request callback."""
nessie_test_config.cleanup = False
return {
"before_record_request": before_record_cb,
} | 39,056 |
def main(): # pylint: disable=R0914,R0912,R0915
"""The main method"""
images = {}
materials = {}
meshes = {}
objects = {}
groups = {}
texts = {}
# Set up our FileDescription
fileid = FileId(filename = bpy.path.abspath(bpy.data.filepath))
file_descr = FileDescription(file=fileid)... | 39,057 |
def get_best(get_fitness, optimalFitness, geneSet, display,
show_ion, target, parent_candidates, seed=None,
hull=None, simplex=None, verbose=0, hull_bounds=[0, 1],
inner_search=True, parent_cap=25, mutation_cap=1000):
"""
the primary public function of the engine
Para... | 39,058 |
def main():
"""Create the model and start the training."""
args = get_arguments()
if os.path.exists(args.snapshot_dir)==False:
os.mkdir(args.snapshot_dir)
f = open(args.snapshot_dir+'GTA2Cityscapes_log.txt', 'w')
w, h = map(int, args.input_size.split(','))
input_size = (w, h)
w... | 39,059 |
def generate_info_endpoint_reply(request):
"""
This just returns a hardcoded introspection string.
"""
available_api_versions = {}
for ver in optimade_supported_versions:
available_api_versions[optimade_supported_versions[ver]] = request['baseurl'] + ver
response = {
"links": {
... | 39,060 |
def M(s,o):
"""
M -
s - array of predictions (or simulated)
o - array of observations (or targets)
"""
s,o = np.array(s),np.array(o)
return np.nansum( np.abs( np.divide(s-o,o) ))/len(o) | 39,061 |
def check_link_exist(destination: str):
"""Check if link already exists and return otherwise return None"""
session: Session = db_session.create_session()
result = session.execute(
f"SELECT short_link FROM links WHERE destination = '{destination}'",
) # fix possible SQL injection
for row i... | 39,062 |
def smart_404(request):
"""Returns a 404 message that tries to help the user."""
base_url = settings.HOST_URL
not_found = {
'type': None,
'redirect_url': base_url
}
path_arguments = request.path.split('/')[1:]
if path_arguments and path_arguments[0].isdigit():
try:
... | 39,063 |
def get_basemap():
"""
Use cached copy of basemap from the script's parent folder
otherwise download basemap from imgur
"""
url = "https://i.imgur.com/yIVogZH.png"
image = "basemap.png"
location = PATH + image
print(location)
try:
basemap = cbook.get_sample_data(location)
... | 39,064 |
def pairs_to_annotations(annotation_pairs):
"""
Convert an array of annotations pairs to annotation array.
:param annotation_pairs: list(AnnotationPair) - annotations
:return: list(Annotation)
"""
annotations = []
for ap in annotation_pairs:
if ap.ann1 is not None:
annota... | 39,065 |
def sanitize_param(value, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X'):
"""Clean incoming parameters (strings or lists)"""
if isinstance(value, string_types):
return sanitize_text(value, valid_characters=valid_characters, character_map=character_map, invalid_character... | 39,066 |
def default_meta(inherit=True):
"""Initialize default meta for particular plugin.
Default Meta is inherited by all children comparing to Meta which is unique
per plugin.
:param inherit: Whatever to copy parents default meta
"""
def decorator(plugin):
plugin._default_meta_init(inherit)... | 39,067 |
def get_default_database_name():
"""
gets default database name.
:rtype: str
"""
return get_component(DatabasePackage.COMPONENT_NAME).get_default_database_name() | 39,068 |
def npm_local_packages():
"""
Get list of local packages
:return: a tuple of dicts
"""
local_dependencies = {}
local_dev_dependencies = {}
package_json = get_package_json()
for name, version in package_json.get("dependencies", {}).items():
match = LOCAL_PACKAGE.match(version)
... | 39,069 |
def test_filter_column_isin(df, iterable):
"""
`filter_column_isin` should return the property that the column of
interest's set of values should be a subset of the iterable provided.
This encompasses a few scenarios:
- Each element in iterable is present in the column.
- No elements of iterabl... | 39,070 |
def lagrangian_descriptor(u, v, p_value = 0.5):
"""
Vector field equation for Lagrangian descriptor.
Parameters
----------
v : ndarray, shape(n,2)
Vector field at given point.
p_value : float, optional
Exponent in Lagrangian descriptor definition.
0 is the a... | 39,071 |
def xymatch(x1, y1, x2, y2, tol=None, nnearest=1):
"""Fast cross-matching of xy coordinates: from https://gist.github.com/eteq/4599814"""
x1 = np.array(x1, copy=False)
y1 = np.array(y1, copy=False)
x2 = np.array(x2, copy=False)
y2 = np.array(y2, copy=False)
if x1.shape != y1.shape:
rais... | 39,072 |
def get_infection_probas_mean_field(probas, transmissions):
"""
- probas[i,s] = P_s^i(t)
- transmissions = csr sparse matrix of i, j, lambda_ij(t)
- infection_probas[i] = sum_j lambda_ij P_I^j(t)
"""
infection_probas = transmissions.dot(probas[:, 1])
return infection_probas | 39,073 |
def eval_task(algo, specific_testsets, measures, head_items, crossfold_index, save_path=None, load_path=None, uid_plus_iid_to_row=None):
"""
Evaluate on specific testsets.
This function exists to make testset evaluation easier to parallelize.
"""
ret = []
if load_path and uid_plus_iid_to_row is ... | 39,074 |
def newton(RJ, x0, verbose = False, rtol = 1.0e-6, atol = 1.0e-10, miter = 50,
linesearch = 'none', bt_tau = 0.5, bt_c = 1.0e-4):
"""
Manually-code newton-raphson so that I can output convergence info, if
requested.
Parameters:
RJ function return the residual + jacobian
x0 ... | 39,075 |
def gen_oltp_trace(
tpcc_weight: str, tpcc_rates: List[int], pattern_iter: int) -> bool:
"""
Generates the trace by running OLTP TPCC benchmark on the built database
:param tpcc_weight: Weight for the TPCC workload
:param tpcc_rates: Arrival rates for each phase in a pattern
:param pattern_... | 39,076 |
def plot_hmesh(mesh, box=None, proj='pc', figsize=[9,4.5],
title=None, do_save=None, do_lsmask='fesom', color_lsmask=[0.6, 0.6, 0.6],
linecolor='k', linewidth=0.2, linealpha=0.75, pos_extend=None,):
"""
---> plot FESOM2 horizontal mesh:
___INPUT:_____________________________... | 39,077 |
def _get_feature_proportion(features_percentage: int,
indices_number: int) -> int:
"""
Computes a number of features based on the given percentage.
"""
assert (isinstance(features_percentage, int)
and 0 <= features_percentage <= 100
and isinstance(indi... | 39,078 |
def get_data(whereto):
"""
récupère les données
@param whereto destination
"""
download_data('velib_synthetique.zip', website='xdtd', whereTo=whereto)
download_data('besancon.df.txt.zip', website='xdtd', whereTo=whereto) | 39,079 |
def nmap_smb_vulnscan():
"""
Scans available smb services in the database for smb signing and ms17-010.
"""
service_search = ServiceSearch()
services = service_search.get_services(ports=['445'], tags=['!smb_vulnscan'], up=True)
services = [service for service in services]
service_dict = ... | 39,080 |
def orthoProjectionMatrix(left, right, bottom, top, nearClip=0.01, farClip=100.,
out=None, dtype=None):
"""Compute an orthographic projection matrix with provided frustum
parameters.
Parameters
----------
left : float
Left clipping plane coordinate.
right : flo... | 39,081 |
def get_nsnames(zone):
"""Get list of nameservers names to query"""
if Prefs.NO_NSSET:
if not Prefs.ADDITIONAL:
print("ERROR: -n requires specifying -a")
usage()
return Prefs.ADDITIONAL
answers = dns.resolver.resolve(zone, 'NS', 'IN')
return Prefs.ADDITIONAL + s... | 39,082 |
def pbmcs_10x_cite_seq(
save_path: str = "data/",
protein_join: str = "inner",
run_setup_anndata: bool = True,
) -> anndata.AnnData:
"""
Filtered PBMCs from 10x Genomics profiled with RNA and protein.
Datasets were filtered for doublets and other outliers as in
https://github.com/YosefLab/t... | 39,083 |
def binom(n, k):
"""Binomial coefficients for :math:`n choose k`
:param n,k: non-negative integers
:complexity: O(k)
"""
prod = 1
for i in range(k):
prod = (prod * (n - i)) // (i + 1)
return prod | 39,084 |
def resource_map():
"""Dynamically generate a map of resources that will be managed for a
single hook execution.
"""
resource_map = deepcopy(BASE_RESOURCE_MAP)
release = os_release('keystone')
if CompareOpenStackReleases(release) < 'liberty':
resource_map.pop(POLICY_JSON)
if os.path... | 39,085 |
def get_not_found_swagger_schema():
""" """
class NotFoundResponseModel(Schema):
""" """
type = "object"
properties = {
"message": {
"type": "string",
}
}
return NotFoundResponseModel | 39,086 |
def find_project(testrun_url):
"""
Find a project name from this Polarion testrun URL.
:param testrun_url: Polarion test run URL
:returns: project name eg "CEPH" or "ContainerNativeStorage"
"""
url_suffix = testrun_url[59:]
index = url_suffix.index('/')
return url_suffix[:index] | 39,087 |
def routine_callback(match: tuple) -> None:
"""Packet sniffer callback
Args:
match (tuple): A packet that matches our filter; consists
of URL of packet recipient and match content
"""
LOGGER.info(f'match found in transport to {match[0]}')
LOGGER.info(match[1]) | 39,088 |
def test_get_files_dependent_fuzzers_afl_runner_dockerfile():
"""Tests that the right modules are returned by get_files_dependent_fuzzers
when passed fuzzers/afl/runner.Dockerfile."""
afl_runner_dockerfile = os.path.join(utils.ROOT_DIR, 'fuzzers', 'afl',
'runner.Dock... | 39,089 |
def gen_5sec_audio(track, channel):
"""Generates a 5 second audio loop in 5sec.aiff"""
track_filename = "tmp/track{nr}{channel}.aiff".format(nr=track, channel=channel)
cmd = ["ffmpeg"]
cmd.append("-y")
cmd.append("-i")
cmd.append("tmp/low_beep.aiff")
cmd.append("-i")
cmd.append("tmp/lo... | 39,090 |
def c2ip(c2, uname):
""" return complete ip address for c2 with substituted username """
return c2['ip_address'].replace('USER', uname) | 39,091 |
def checkCommitChain(commits):
"""checkCommitChain(commits)
Verifies that the list of commits is suitable for a review, meaning that
no commits is a merge and that each commit is the parent of the following
commit. If not, throws an exception describing the issue."""
if len(commits) > 1:
for commit i... | 39,092 |
def beacon(config):
"""
Watch the configured directories
Example Config
.. code-block:: yaml
beacons:
watchdog:
- directories:
/path/to/dir:
mask:
- create
- modify
- delete
... | 39,093 |
def scenario(request):
"""
Retrieve the parameters and nodes for a scenario
Parameters:
model_uuid (uuid): required
scenario_id (int): required
Returns: HttpResponse
Example:
GET: /component/scenario/
"""
model_uuid = request.GET['model_uuid']
scenario_id = request.GET['s... | 39,094 |
def already_voted(replied: str, user_id: str, db: dataset.Database) -> bool:
"""Search in the database for an existing vote of the user on the replied message
Args:
replied: id of the message which the vote is a reply
user_id: id of the user who's voting
Returns:
The return value. ... | 39,095 |
def create_bi_sequence_embedding(inputs, seq_lengths, repr_dim, vocab_size, emb_name, rnn_scope, reuse_scope=False):
"""
Bidirectional encoding
:param inputs: tensor [d1, ... ,dn] of int32 symbols
:param seq_lengths: [s1, ..., sn] lengths of instances in the batch
:param repr_dim: dimension of embed... | 39,096 |
async def input_checker(user_guess: str) -> bool:
"""Check if the user's input is actually a word.
Method for checking if input is in text file: https://stackoverflow.com/a/4944929"""
if len(user_guess) != 5:
valid = False
else:
with open(wordfile_path, encoding='utf-8', errors='ignore... | 39,097 |
def pascal_voc_vgg16_config():
"""Specify the parameters to tune below."""
mc = base_model_config('PASCAL_VOC')
mc.DEBUG_MODE = False
# Data Augmentation
#mc.LOSS_TYPE = 'YOLO'
mc.DATA_AUG_TYPE = 'YOLO'
# Network Architecture
mc.BN = True
mc.IMAGE_WIDTH ... | 39,098 |
def computeBasisFunctionsReferenceElement(edge_orientation, face_orientation, Nord, points):
"""Compute the basis function for the reference element.
:param ndarray edges_orientation: orientation for edges
:param ndarray faces_orientation: orientation for faces
:param int Nord: polynomial order of nede... | 39,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.