content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def run_services(*services, **kwargs):
"""This function starts the Network :class:`.Manager` and then starts the
specified :class:`~msl.network.service.Service`\\s.
This is a convenience function for running the Network :class:`.Manager`
only when the specified :class:`~msl.network.service.Service`\\s ... | 38,200 |
def read_raw_antcnt(input_fname, montage=None, eog=(), event_id=None,
event_id_func='strip_to_integer', preload=False,
verbose=None):
"""Read an ANT .cnt file
Parameters
----------
input_fname : str
Path to the .cnt file.
montage : str | None | instanc... | 38,201 |
def addrstr(ip: netaddr.IPNetwork) -> str:
"""
helper for mapping IP addresses to config statements
"""
address = str(ip.ip)
if netaddr.valid_ipv4(address):
return "ip address %s" % ip
elif netaddr.valid_ipv6(address):
return "ipv6 address %s" % ip
else:
raise ValueError("invalid address... | 38,202 |
def generate_nums(number_of_nums: int, queue_nums: queue.Queue[int]) -> None:
""" generate numbers """
generate_nums_done.clear()
for _ in range(number_of_nums):
num = randint(1,11)
print(f"generate number: {num}")
queue_nums.put(num)
time.sleep(1)
generate_nums_done.s... | 38,203 |
def upload_fixture_file(domain, filename, replace, task=None, skip_orm=False):
"""
should only ever be called after the same file has been validated
using validate_fixture_file_format
"""
workbook = get_workbook(filename)
if skip_orm is True:
return _run_fast_fixture_upload(domain, wor... | 38,204 |
def between_unbounded_preceding_and_current_row(self):
"""Check range between unbounded preceding and current row frame with and without order by.
"""
with Example("with order by"):
expected = convert_output("""
four | ten | sum | last_value
------+-----+-----+------------
... | 38,205 |
def lambda_plus_mu_elimination(
offspring: list, population: list, lambda_: int):
""" Performs the (λ+μ)-elimination step of the evolutionary algorithm
Args:
offspring (list): List of the offspring
population (list): List of the individuals in a population
lambda_ (int): Number ... | 38,206 |
def dVdtau(z):
""" cosmological time-volume element [Mpc^3 /redshift /sr]
it is weighted by an extra (1+z) factor to reflect the rate
in the rest frame vs the observer frame
"""
DH=c_light_kms/cosmo.H0
return DH*(1+z)*DA(z)**2/E(z) | 38,207 |
def test_6_1_8_etc_gshadow_exists(host):
"""
CIS Ubuntu 20.04 v1.1.0 - Rule # 6.1.8
Tests if /etc/gshadow file exists
"""
assert host.file(ETC_GSHADOW).exists | 38,208 |
def receive(message):
"""
Function to read whatever is presented to the serial port and print it to the console.
Note: For future use: Currently not used in this code.
"""
messageLength = len(message)
last_message = []
try:
while arduinoData.in_waiting > 0:
for i in range... | 38,209 |
def fit(model_types: List[str],
state_cb_arg_name: Optional[str] = None,
instance_arg_name: Optional[str] = None) -> Callable:
"""Decorator used to indicate that the wrapped function is a fitting
function. The decorated function should take at least one argument - model
instance (passed as t... | 38,210 |
def markLocation(stream):
"""Creates text file showing current location in context."""
# Mainly for debugging
RADIUS = 5000
stream.seek(-RADIUS, 1)
outputDoc = open('PyPDF4_pdfLocation.txt', 'w')
outputDoc.write(stream.read(RADIUS))
outputDoc.write('HERE')
outputDoc.write(stream.read(RAD... | 38,211 |
def infer_filetype(filepath, filetype):
"""
The function which infer file type
Parameters
----------
filepath : str
command line argument of filepath
filetype : str
command line argument of filetype
Returns
-------
filepath : str
filepath
filetype : str
... | 38,212 |
def suite_for_devices(devices):
"""Create a TyphonSuite to display multiple devices"""
suite = TyphonSuite()
for device in devices:
suite.add_device(device)
return suite | 38,213 |
def get_3d_points(preds_3d):
"""
Scales the 3D points.
Parameters
----------
preds_3d : numpy.ndarray
The raw 3D points.
Returns
-------
preds_3d : numpy.ndarray
The scaled points.
"""
for i,p in enumerate(preds_3d):
preds_3d[i] = preds_3d[i] - preds_3d[... | 38,214 |
def LUT(src, lut, dst=None): # real signature unknown; restored from __doc__
""" LUT(src, lut[, dst]) -> dst """
pass | 38,215 |
def mms_load_data(trange=['2015-10-16', '2015-10-17'], probe='1', data_rate='srvy', level='l2',
instrument='fgm', datatype='', anc_product=None, descriptor=None,
varformat=None, prefix='', suffix='', get_support_data=False, time_clip=False,
no_update=False, center_measurement=False, notplot=False, data_r... | 38,216 |
def get_random_card_id_in_value_range(min, max, offset):
"""
Randomly picks a card ranged between `min` and `max` from a given offset.
The offset determines the type of card.
"""
card_id = roll(
min + offset,
max + offset)
return card_id | 38,217 |
def task_configuration(config_path):
""" NLP-Task configuration/mapping """
df = pd.read_json(config_path)
names = df.name.values.tolist()
mapping = {
df['name'].iloc[i]: (
df['text'].iloc[i],
df['labels'].iloc[i],
df['description'].iloc[i],
df['m... | 38,218 |
def test_freetext_query_location_extracted_or_enriched(session, geo, expected_number_of_hits):
"""
Describe what the test is testing
"""
json_response = get_search(session, params={'q': geo, 'limit': '0'})
hits_total = json_response['total']['value']
compare(hits_total, expected_number_of_hits) | 38,219 |
def train(model, optimizer, criterion, data_loader, imshape=(-1, 1, 299, 299),
device='cpu'):
"""
Train a model given a labeled dataset
Args:
model (nn.Module): Model
criterion (torch.nn.optim): Criterion for loss function calculation
data_loader (DataLoader): DataLoader f... | 38,220 |
def cli():
"""Manages Workbench configuration.""" | 38,221 |
def get_random_rep(embedding_dim=50, scale=0.62):
"""The `scale=0.62` is derived from study of the external GloVE
vectors. We're hoping to create vectors with similar general
statistics to those.
"""
return np.random.normal(size=embedding_dim, scale=0.62) | 38,222 |
def calculate_pretrain_epoches(stage_ds:DatasetStage,
train_batch_size:int,
train_steps_per_epoch:int=DEF_STEPS_PER_EPOCH)->int:
""" Calculate the number of epoches required to match the reference model in
the number of parameter updates.
Ref. https:/... | 38,223 |
def get_container_info(node, repositories):
"""Check the node name for errors (underscores)
Returns:
toscaparser.nodetemplate.NodeTemplate: a deepcopy of a NodeTemplate
"""
if not repositories:
repositories = []
NodeInfo = namedtuple(
"NodeInfo",
[
"name"... | 38,224 |
def pass_calibration_data(sim_model):
"""
The User of the QuantizationSimModel API is expected to write this function based on their data set.
This is not a working function and is provided only as a guideline.
:param sim_model:
:return:
"""
# User action required
# The following line ... | 38,225 |
def query_db_to_build_2by2_table(
db,
drug1_id,
drug2_id,
drug1_efficacy_definition_query_sql,
drug2_efficacy_definition_query_sql,
environment,
):
"""
Query the given DB to build a 2-by-2 table comparing the given
drugs.
Return a 2-by-2 table where the e... | 38,226 |
def rmedian(image, r_inner, r_outer, **kwargs):
"""
Median filter image with a ring footprint. This
function produces results similar to the IRAF
task of the same name (except this is much faster).
Parameters
----------
image : ndarray, MaskedImageF, or ExposureF
Original image dat... | 38,227 |
def validate_username(username):
"""
Verifies a username is valid, raises a ValidationError otherwise.
Args:
username (unicode): The username to validate.
This function is configurable with `ENABLE_UNICODE_USERNAME` feature.
"""
username_re = slug_re
flags = None
message = acco... | 38,228 |
def docstring():
"""
Decorator: Insert docstring header to a pre-existing docstring
"""
sep="\n"
def _decorator(func):
docstr = func.__doc__
title = docstr.split("Notes",1)[0]
docstr = docstr.replace(title,"")
func.__doc__ = sep.join([docstr_header(title,func.__name__... | 38,229 |
def wait_for_stack_update(stack_name) -> bool:
"""Returns boolean indicating update success"""
stack = _get_boto_resource("cloudformation").Stack(stack_name)
while True:
stack.reload()
logger.debug(f"Stack '%s' status: %s", stack_name, stack.stack_status)
if 'ROLLBACK' in stack.stac... | 38,230 |
def load_class_names():
"""
Load the names for the classes in the CIFAR-10 data-set.
Returns a list with the names. Example: names[3] is the name
associated with class-number 3.
"""
# Load the class-names from the pickled file.
raw = _unpickle(filename="batches.... | 38,231 |
def categories():
"""Router for categories page."""
categories = get_categories_list()
return render_template('categories.html',
categories=categories) | 38,232 |
def load_images(imgpaths, h, w, imf='color'):
"""Read in images and pre-processing 'em
Args:
imgpaths: a list contains all the paths and names of the images we want to load
h: height image is going to resized to
width: width image is going to resized to
imf: image format when loaded as color or gr... | 38,233 |
def nextpow2(value):
"""
Find exponent such that 2^exponent is equal to or greater than abs(value).
Parameters
----------
value : int
Returns
-------
exponent : int
"""
exponent = 0
avalue = np.abs(value)
while avalue > np.power(2, exponent):
exponent += 1
... | 38,234 |
def clarkezones(reference, test, units,
numeric=False):
"""Provides the error zones as depicted by the
Clarke error grid analysis for each point in the reference and test datasets.
Parameters
----------
reference, test : array, or list
Glucose values obtained from the refer... | 38,235 |
def test_compute_specifier_from_version():
"""Test function 'compute_specifier_from_version'."""
version = "0.1.5"
expected_range = ">=0.1.0, <0.2.0"
assert expected_range == compute_specifier_from_version(Version(version))
version = "1.0.0rc1"
expected_range = ">=1.0.0rc1, <2.0.0"
assert ... | 38,236 |
def createSettingsMenu(self): # void MainWindow::createSettingsMenu()
"""
TOWRITE
"""
actionHash = self.actionHash
qDebug("MainWindow createSettingsMenu()")
self.menuBar().addMenu(self.settingsMenu)
self.settingsMenu.addAction(actionHash["ACTION_settingsdialog"])
self.settingsMenu.addSe... | 38,237 |
def normalize_graph(graph):
"""
Take an instance of a ``Graph`` and return the instance's identifier and ``type``.
Types are ``U`` for a :class:`~rdflib.graph.Graph`, ``F`` for
a :class:`~rdflib.graph.QuotedGraph` and ``B`` for a
:class:`~rdflib.graph.ConjunctiveGraph`
>>> from rdflib import ... | 38,238 |
async def mock_candle_producer(state: SharedState, symbol: str):
"""Produces a fake candle, every two seconds."""
i = 1
while not state.stop:
asyncio.sleep(2)
raw_candle = fake_candle(i, symbol)
message = Message(
time =Pipe.to_datetime(time=raw_candle["k"]["... | 38,239 |
def findTargetNode(root, nodeName, l):
"""
Recursive parsing of the BVH skeletal tree using breath-first
search to locate the node that has the name of the targeted body part.
Args:
root (object): root node of the BVH skeletal tree
nodeName (string): name of the targeted body part
l (list): e... | 38,240 |
def ddtodms(decLat: float, decLon: float):
""" Converts coord point from decimal degrees to Hddd.mm.ss.sss """
try:
lat = float(decLat)
lon = float(decLon)
except ValueError as e:
raise e
# Get declination
ns = "N" if lat >= 0 else "S"
ew = "E" if lon >= 0 else "W"
la... | 38,241 |
def test_list_g_year_month_max_length_4_nistxml_sv_iv_list_g_year_month_max_length_5_4(mode, save_output, output_format):
"""
Type list/gYearMonth is restricted by facet maxLength with value 10.
"""
assert_bindings(
schema="nistData/list/gYearMonth/Schema+Instance/NISTSchema-SV-IV-list-gYearMont... | 38,242 |
def get_file_paths(folder, extension_tuple=('.nrrd', '.tiff', '.tif', '.nii', '.bmp', 'jpg', 'mnc', 'vtk'), pattern=None):
"""
Test whether input is a folder or a file. If a file or list, return it.
If a dir, return all images within that directory.
Optionally test for a pattern to sarch for in the file... | 38,243 |
async def test_device_delete(aresponses):
"""Test deleting a device."""
aresponses.add(
"api.getnotion.com",
"/api/users/sign_in",
"post",
aresponses.Response(
text=load_fixture("auth_success_response.json"),
status=200,
headers={"Content-Type"... | 38,244 |
def gen_colors(img):
""" Ask backend to generate 16 colors. """
raw_colors = fast_colorthief.get_palette(img, 16)
return [util.rgb_to_hex(color) for color in raw_colors] | 38,245 |
def request(match, msg):
"""Make an ESI GET request, if the path is known.
Options:
--headers nest the response and add the headers
"""
match_group = match.groupdict()
if "evepc.163.com" in (match_group["esi"] or ""):
base_url = ESI_CHINA
else:
base_url = esi_base_u... | 38,246 |
def __getattr__(attr):
"""
This dynamically creates the module level variables, so if
we don't call them, they are never created, saving time - mostly in the CLI.
"""
if attr == "config":
return get_config()
elif attr == "leader_hostname":
return get_leader_hostname()
else:
... | 38,247 |
def _diff_st(p,dl,salt,temp,useext=False):
"""Calculate sea-ice disequilibrium at ST.
Calculate both sides of the equations
given pressure = pressure of liquid water
chemical potential of ice = potential of liquid water
and their Jacobians with respect to pressure and liquid w... | 38,248 |
def getNormalizedISBN10(inputISBN):
"""This function normalizes an ISBN number.
>>> getNormalizedISBN10('978-90-8558-138-3')
'90-8558-138-9'
>>> getNormalizedISBN10('978-90-8558-138-3 test')
'90-8558-138-9'
>>> getNormalizedISBN10('9789085581383')
'90-8558-138-9'
>>> getNormalizedISBN10('9031411515')
... | 38,249 |
def move(browser, coordinate, coordinate0):
""" 从坐标coordinate0,移动到坐标coordinate """
time.sleep(0.05)
length = sqrt((coordinate[0] - coordinate0[0]) ** 2 + (coordinate[1] - coordinate0[1]) ** 2) # 两点直线距离
if length < 4: # 如果两点之间距离小于4px,直接划过去
ActionChains(browser).move_by_offset(coordinate[0]... | 38,250 |
def hashtag_is_valid(tag, browser, delay=5):
"""
Check if a given hashtag is banned by Instagram
:param delay: Maximum time to search for information on a page
:param browser: A Selenium Driver
:param tag: The hashtag to check
:return: True if the hashtag is valid, else False
"""
try:
... | 38,251 |
def create_nanopub(np_client, drug_id, disease_id):
"""Create a Nanopublication in RDF for a drug-disease association
using the BioLink model
"""
# Or: 1. construct a desired assertion (a graph of RDF triples)
nanopub_rdf = Graph()
nanopub_rdf.bind("biolink", URIRef('https://w3id.org/biolink/voc... | 38,252 |
def get_price_data(startdate, enddate):
"""
returns a dataframe containing btc price data on every day between startdate and enddate
:param startdate:
:param enddate:
:return:
"""
url = 'https://api.coindesk.com/v1/bpi/historical/close.json?start=' + startdate + '&end=' + enddate
driver.... | 38,253 |
def create_exec(docker_client, container, config, username, logger): #pylint: disable=W0613
"""Register a command to run against a container.
:Returns: Dictionary
:param docker_client: For communicating with the Docker daemon.
:type docker_client: docker.client.DockerClient
:param container: The ... | 38,254 |
def mk_prmsl_file_list(data_root_dir: str, start_date: datetime) -> Tuple[list, list]:
"""mk_prmsl_file_list.
return "prmsl_file_list".
prmsl_file_list is consisted of prmsl file(netcdf) older than "start_date."
Args:
data_root_dir (str): data_root_dir
start_date (datetime): start_date
... | 38,255 |
def get_batch(generator, batch_size, num_steps, max_word_length, pad=False):
"""Read batches of input."""
cur_stream = [None] * batch_size
inputs = np.zeros([batch_size, num_steps], np.int32)
char_inputs = np.zeros([batch_size, num_steps, max_word_length], np.int32)
global_word_ids = np.zeros([batch_size, nu... | 38,256 |
def test_commands_subtract_invalid_substracted_subnets(mock_method):
"""
Test initializing subtract command
"""
test_args = [
'netlookup', 'subtract',
'-n', '192.168.0.0/33',
'192.168.0.0/24'
]
with patch.object(sys, 'argv', test_args):
with pytest.raises(SystemEx... | 38,257 |
def infer(source_type: str = None, source: str = None, model: str = None, dataset: str = None):
"""
Performs semantic segmentation for the given input using the pre-trained FCN model.
:param source_type: type of source
:param source: path to source file or directory in the local file system
:param m... | 38,258 |
def read_keywords(fname):
"""Read id file"""
with open(fname, 'r') as f:
reader = csv.reader(f)
header = next(reader)
assert header == ['keyword']
return list(row[0] for row in reader) | 38,259 |
def klucbPoisson(x, level, lower=float("-inf"), upper=float("inf")):
"""returns u such that kl(x,u)=level for the Poisson kl-divergence."""
if (lower==x):
klucb(x, level, klPoisson(a,b), lowerbound=x, upperbound=x+level+np.sqrt(level*level+2*x*level))
elif (upper==x):
klucb(x, level, klPoisson(a,b), lowerbound=l... | 38,260 |
def inscribe(mask):
"""Guess the largest axis-aligned rectangle inside mask.
Rectangle must exclude zero values. Assumes zeros are at the
edges, there are no holes, etc. Shrinks the rectangle's most
egregious edge at each iteration.
"""
h, w = mask.shape
i_0, i_1 = 0, h - 1
j_0, j_1 =... | 38,261 |
def vaf_above_or_equal(vaf):
"""
"""
return lambda columns, mapper: float(columns[mapper['Variant_allele_ratio']]) >= vaf | 38,262 |
def user_token_headers(client_target: TestClient, sql_session: Session) -> Dict[str, str]:
"""fake user data auth"""
return auth_token(
client=client_target, username="johndoe", sql=sql_session) | 38,263 |
def new_sequence_details(script_path, config=None, increment_sequence_index=True):
"""Generate the details for a new sequence: the toplevel attrs sequence_date,
sequence_index, sequence_id; and the the output directory and filename prefix for
the shot files, according to labconfig settings. If increment_... | 38,264 |
def conv_1_0_string_to_packed_binary_string(s):
"""
'10101111' -> ('\xAF', False)
Basically the inverse of conv_packed_binary_string_to_1_0_string,
but also returns a flag indicating if we had to pad with leading zeros
to get to a multiple of 8.
"""
if not is_1_0_string(s):
raise Va... | 38,265 |
def accuracy_win_avg(y_true, y_proba):
"""
Parameters
----------
y_true: n x n_windows
y_proba: n x n_windows x n_classes
"""
y_pred = win_avg(y_proba)
return accuracy(y_true[:,0], y_pred) | 38,266 |
def pause_program(seconds="5"):
"""
Stops the program for given seconds
"""
loader.pause_program(seconds) | 38,267 |
def ortho_projection(left=-1, right=1, bottom=-1, top=1, near=.1, far=1000):
"""Orthographic projection matrix."""
return np.array((
(2 / (right-left), 0, 0, -(right+left) / (right-left)),
(0, 2 / (top-bottom), 0, -(top+bottom) / (top-botto... | 38,268 |
def ais_InitLengthBetweenCurvilinearFaces(*args):
"""
* Finds attachment points on two curvilinear faces for length dimension. @param thePlaneDir [in] the direction on the dimension plane to compute the plane automatically. It will not be taken into account if plane is defined by user.
:param theFirstFace:
... | 38,269 |
def test_is_round_done_no_tasks(agg):
"""Test that is_round_done returns True in the corresponded case."""
agg.assigner.get_all_tasks_for_round = mock.Mock(return_value=[])
is_round_done = agg._is_round_done()
assert is_round_done is True | 38,270 |
def handle_new_deal(thebot, deal, strategy):
"""New deal (short or long) to activate SL on"""
botid = thebot["id"]
deal_id = deal["id"]
pair = deal['pair']
actual_profit_percentage = float(deal["actual_profit_percentage"])
# Take space between trigger and actual profit into account
activat... | 38,271 |
def _get_data_handlers(raw_data_folder, run_uuid, use_s3=False, s3=None):
"""Returns a file_or_stream and data_cleaner"""
if not use_s3:
os.makedirs(os.sep.join(raw_data_folder), exist_ok=True)
raw_data_file = os.sep.join(raw_data_folder + [run_uuid + '.csv.gz'])
# If a cache is found, u... | 38,272 |
def get_methylation_dataset(methylation_array, outcome_col, convolutional=False, cpg_per_row=1200, predict=False, categorical=False, categorical_encoder=False, generate=False):
"""Turn methylation array into pytorch dataset.
Parameters
----------
methylation_array : MethylationArray
Input Methy... | 38,273 |
def es_config_fixture() -> ElastalkConf:
"""
This fixture returns an `ElasticsearchConf` (configuration) object.
:return: the configuration object
"""
return ElastalkConf() | 38,274 |
def convert_doc_to_latex(doc, verbatim_strings = [], use_gold_trees=False):
"""
This function expects a list of ccg_trees, and a list of tokens
(as produced by transccg). Then, it converts each pair (ccg_tree, ccg_tokens)
into a presentation MathML string, and wraps them with HTML code.
verbatim_str... | 38,275 |
def validate_anchor_segments(segments):
"""Very basic validation of segments, making sure UNH, BGM and UNT exist and are in the right place."""
if not (segments[0][0] == 'UNH' or segments[1][0] == 'UNH'):
raise MissingSegmentAtPositionError('UNH')
if not (segments[1][0] == 'BGM' or segments[2][0] ==... | 38,276 |
def axis_angle_to_quaternion(rotation: ArrayOrList3) -> np.ndarray:
"""Converts a Rodrigues axis-angle rotation to a quaternion.
Args:
rotation: axis-angle rotation in [x,y,z]
Returns:
equivalent quaternion in [x,y,z,w]
"""
r = Rotation.from_rotvec(rotation)
return r.as_quat() | 38,277 |
def encode(encoding, data):
"""
Encodes the given data using the encoding that is specified
:param str encoding: encoding to use, should be one of the supported encoding
:param data: data to encode
:type data: str or bytes
:return: multibase encoded data
:rtype: bytes
:raises ValueError... | 38,278 |
def test_ct_d015_ct_d015_v(mode, save_output, output_format):
"""
TEST :Syntax Checking for top level complexType Declaration :
simpleContent, content of restriction and content of enumeration
"""
assert_bindings(
schema="msData/complexType/ctD015.xsd",
instance="msData/complexType/c... | 38,279 |
def tiny_video_net(model_string,
num_classes,
num_frames,
data_format='channels_last',
dropout_keep_prob=0.5,
get_representation=False,
max_pool_predictions=False):
"""Builds TinyVideoNet based on model s... | 38,280 |
def test_missing_integers_are_increasing(integers: t.List[int]) -> None:
"""Generated numbers should be sorted in increasing order."""
result = list(take(len(integers), missing_integers(integers)))
for i in range(1, len(result)):
assert result[i-1] < result[i] | 38,281 |
def get_tensor_from_cntk_convolutional_weight_value_shape(tensorValue, tensorShape):
"""Returns an ell.math.DoubleTensor from a trainable parameter
Note that ELL's ordering is row, column, channel.
4D parameters (e.g. those that represent convolutional weights) are stacked vertically in the row dimens... | 38,282 |
def impfzentrum_waehlen(bundesland: str, plz: str, driver: webdriver.Chrome):
"""Wahelt das Impfzentrum auf der Startseite aus
Args:
bundesland (str): Bundesland muss im Drop-Down Menue verfuegbar sein
plz (str): Plz des Impfzentrums
driver (webdriver.Chrome): webdriver
"""
# B... | 38,283 |
def load_f0(fhandle: TextIO) -> annotations.F0Data:
"""Load a Dagstuhl ChoirSet F0-trajectory.
Args:
fhandle (str or file-like): File-like object or path to F0 file
Returns:
F0Data Object - the F0-trajectory
"""
times = []
freqs = []
voicings = []
confs: List[Optional[f... | 38,284 |
def to_str_constant(s: str, quote="'") -> str:
"""
Convert a given string into another string that is a valid Python representation of a string constant.
:param s: the string
:param quote: the quote character, either a single or double quote
:return:
"""
if s is None:
raise ValueErro... | 38,285 |
def signum(x):
"""
Return -1 if x < 0, 1 if 0 < x, or 0 if x == 0
"""
return (x > 0) - (x < 0) | 38,286 |
def pull_data_from_gcs(search_prefix=None):
"""Pulls down fuzzer data from GCS to local machine."""
# Create worker pool
pool = multiprocessing.Pool(None)
# Check if local DST path exists first, if not, create it
parent_dst = os.path.join(os.getenv("HW_FUZZING"), "data")
if not os.path.exists(parent_dst):
... | 38,287 |
def dojs(dogis = False):
""" Minifies the js"""
# Define which files we want to include
# also need to amend sahana.js.cfg
configDictCore = {
"web2py": "..",
"T2": "..",
"S3": ".."
}
configFilenam... | 38,288 |
def _construct_dataloader(dataset, batch_size, shuffle, seed=0, num_workers=0, class_balance=False):
"""Construct a data loader for the provided data.
Args:
data_set ():
batch_size (int): The batch size.
shuffle (bool): If True the data will be loaded in a random order. Defaults to True... | 38,289 |
def _get_cpu_type():
"""
Return the CPU type as used in the brink.sh script.
"""
base = platform.processor()
if not base:
base = platform.machine()
if base == 'aarch64': # noqa:cover
return 'arm64'
if base == 'x86_64':
return 'x64'
if base == 'i686':
... | 38,290 |
def DatesRangeFieldWidget(field, request): # pylint: disable=invalid-name
"""Dates range widget factory"""
return FieldWidget(field, DatesRangeWidget(request)) | 38,291 |
def test_shift(set_up_basis_data):
"""Test pre.shift()."""
X = set_up_basis_data
# Try with bad data shape.
with pytest.raises(ValueError) as exc:
roi.pre.shift(np.random.random((3,3,3)))
assert exc.value.args[0] == "data X must be two-dimensional"
# Try with bad shift vector.
with... | 38,292 |
def data2file(cfg, filename, title, filedata):
"""Write data dictionary into ascii file.
Parameters
----------
cfg : dict
Configuration dictionary of the recipe
filename : str
String containing the file name
title : str
String containing the file header
filedata : di... | 38,293 |
async def explode(pos : Tuple[int, int], power : int, sub_exclusions : List[str] = [], npc_exclusions : List[int] = []):
"""
Makes an explosion in pos, dealing power damage to the centre square,
power-1 to the surrounding ones, power-2 to those that surround and
so on.
"""
from ALTANTIS.subs.sta... | 38,294 |
def get_aux_dset_slicing(dim_names, last_ind=None, is_spectroscopic=False):
"""
Returns a dictionary of slice objects to help in creating region references in the position or spectroscopic
indices and values datasets
Parameters
------------
dim_names : iterable
List of strings denoting ... | 38,295 |
def make_etag(value, is_weak=False):
"""Creates and returns a ETag object.
Args:
value (str): Unquated entity tag value
is_weak (bool): The weakness indicator
Returns:
A ``str``-like Etag instance with weakness indicator.
"""
etag = ETag(value)
etag.is_weak = is_weak
... | 38,296 |
def plot_scatter(results,colname1,colname2):
"""Scatter plot of two columns against each other.
results -- results as created by load_results()
colname1 -- first colname, eg. "EDGES"
colname2 -- second colname, eg. "AUC"
"""
header,rows = results
name2idx = indices(header)
col1,col2 = na... | 38,297 |
def srmi_one_dependent(
data, dependent, predictors, do_available_regressions, sample_size):
"""Auxiliary function that performs linear regression imputation for the
dependent column. The difference with srmi_step() is that in
that function dependent can be None, in which case this function is
c... | 38,298 |
def is_closer_to_goal_than(a, b, team_index):
""" Returns true if a is closer than b to goal owned by the given team """
return (a.y < b.y, a.y > b.y)[team_index] | 38,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.