content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_role_present_absent_dry_run(vmware_datacenter, service_instance, dry_run):
"""
Test scenarios for vmware_esxi.role_present state run with test=True
"""
role_name = "A{}".format(uuid.uuid4())
random_role = "Random{}".format(uuid.uuid4())
# create a new role
ret = esxi.role_present(... | 5,338,000 |
def extract_filter(filter_path):
"""Given a path to the weka's filter file,
return a list of selected features."""
with open(filepath) as f:
lnum = 0
for line in f:
lnum += 1 #pointer to the next line to read
if line.strip().startswith('Selected attributes:'):
... | 5,338,001 |
def pull(local_dir, remote_host, remote_dir, delete=False, verbose=0):
"""
Get the remote files to the local directory.
"""
ignore_file_pth = join(local_dir, ignore_file_name)
transmit_dir(source_host=remote_host, source_dir=remote_dir, target_host=None, target_dir=local_dir,
delete=delete, ignore_file_pth=ignor... | 5,338,002 |
def convert_to_roman_numeral(number_to_convert):
"""
Converts Hindi/Arabic (decimal) integers to Roman Numerals.
Args:
param1: Hindi/Arabic (decimal) integer.
Returns:
Roman Numeral, or an empty string for zero.
"""
arabic_numbers = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9,... | 5,338,003 |
def plot_with_pandas():
"""Generate plot, using pandas."""
df = pd.read_csv('inputs/run_times.csv') # CHANGE THIS LINE TO READ FILE WITH SPEEDS, NOTJUST RUN TIMES
df.plot(x="trial", y="distance") # CHANGE THIS LINE TO PLOT TRIALS ON X-AXIS AN... | 5,338,004 |
def rotate_xyz(vector: Vector, angle_x: float = 0., angle_y: float = 0., angle_z: float = 0.):
"""
Rotate a 3d-vector around the third (z) axis
:param vector: Vector to rotate
:param angle_x: Rotation angle around x-axis (in degrees)
:param angle_y: Rotation angle around y-axis (in degrees)
:pa... | 5,338,005 |
def get_project_from_data(data):
"""
Get a project from json data posted to the API
"""
if 'project_id' in data:
return get_project_by_id(data['project_id'])
if 'project_slug' in data:
return get_project_by_slug(data['project_slug'])
if 'project_name' in data:
return get_... | 5,338,006 |
def transform_bundle(bundle_uuid: str,
bundle_version: str,
bundle_path: str,
bundle_manifest_path: str,
extractor: DSSExtractor):
"""
Per bundle callback passed to DSSExtractor.extract.
Generates cell and expression table r... | 5,338,007 |
def _from_atoms_and_bonds(atm_dct, bnd_dct):
""" Construct a molecular graph from atom and bond dictionaries.
format:
gra = (atm_dct, bnd_dct)
:param atm_dct: atom dictionary
:type atm_dct: dict
:param bnd_dct: bond dictionary
:type bnd_dct: dict
:rtype:... | 5,338,008 |
def __getattr__(item):
"""Ping the func map, if an attrib is not registered, fallback to the dll"""
try:
res = func_map[item]
except KeyError:
return dll.__getattr__(item)
else:
if callable(res):
return res # Return methods from interface.
else:
r... | 5,338,009 |
def moves(possibleMoves):
"""shows all the possible moves available"""
Game()
for i in range(8):
for j in range(8):
if possibleMoves[i][j] != "":
pg.draw.circle(window, green, (j * 100 + 50, (i * 100 + 50)), 10)
pg.display.update() | 5,338,010 |
def seed_random_state(seed):
"""
Turn seed into np.random.RandomState instance
"""
if (seed is None) or (isinstance(seed, int)):
return np.random.RandomState(seed)
elif isinstance(seed, np.random.RandomState):
return seed
raise ValueError("%r cannot be used to generate numpy.rand... | 5,338,011 |
def test_input_redundancy_RULE110():
"""Test Input Redundancy - RULE110"""
n = RULE110()
k_r, true_k_r = n.input_redundancy(mode='node',bound='upper',norm=False) , 7/8
assert (k_r == true_k_r) , ('Input Redundancy (node,upper bound) for RULE110 node does not match. %s != %s' % (k_r,true_k_r))
k_r, true_k_r = n.in... | 5,338,012 |
def _normalize_dashboard_link(link, request):
"""
Given a dashboard link, make sure it conforms to what we expect.
"""
if not link.startswith("http"):
# If a local url is given, assume it is using the same host
# as the application, and prepend that.
link = url_path_join(f"{reque... | 5,338,013 |
def _plot_func_posterior_pdf_node_nn(
bottom_node,
axis,
value_range=None,
samples=10,
bin_size=0.2,
plot_likelihood_raw=False,
**kwargs
):
"""Calculate posterior predictives from raw likelihood values and plot it on top of a histogram of the real data.
The function does not defin... | 5,338,014 |
async def delete(category_id: int):
"""Delete category with set id."""
apm.capture_message(param_message={'message': 'Category with %s id deleted.', 'params': category_id})
return await db.delete(category_id) | 5,338,015 |
def find_files(fields):
""" Finds all FLT files from given fields and places them with metadata
into OrderedDicts.
Parameters
----------
fields : list of strings
The CLEAR fields; retain ability to specify the individual pointings
so that can easily re-run single ones if find an is... | 5,338,016 |
def test_orderstorage__Orderstorage__isLast__1(storage):
"""It raises a `KeyError` if the item is not in the list."""
with pytest.raises(KeyError):
storage.isLast('foo', 'fuz') | 5,338,017 |
def tag_boundaries(htmlifiers):
"""Return a sequence of (offset, is_start, Region/Ref/Line) tuples.
Basically, split the atomic tags that come out of plugins into separate
start and end points, which can then be thrown together in a bag and sorted
as the first step in the tag-balancing process.
Li... | 5,338,018 |
def to_canonical_name(resource_name: str) -> str:
"""Parse a resource name and return the canonical version."""
return str(ResourceName.from_string(resource_name)) | 5,338,019 |
def apply_query_filters(query, model, **kwargs):
"""Parses through a list of kwargs to determine which exist on the model,
which should be filtered as ==, and which should be filtered as LIKE
"""
for k, v in six.iteritems(kwargs):
if v and hasattr(model, k):
column = getattr(model, ... | 5,338,020 |
def bytes_to_b64_str(bytestring: bytes) -> str:
"""Converts random bytes into a utf-8 encoded string"""
return b64encode(bytestring).decode(config.security.ENCODING) | 5,338,021 |
def read_event_analysis(s:Session, eventId:int) -> AnalysisData:
"""read the analysis data by its eventId"""
res = s.query(AnalysisData).filter_by(eventId=eventId).first()
return res | 5,338,022 |
def eval_semeval2012_analogies(
vectors, weight_direct, weight_transpose, subset, subclass
):
"""
For a set of test pairs:
* Compute a Spearman correlation coefficient between the ranks produced by vectors and
gold ranks.
* Compute an accuracy score of answering MaxDiff questions.... | 5,338,023 |
def form_examples(request, step_variables):
"""
extract the examples from the request data, if possible
@param request: http request object
@type request rest_framework.request.Request
@param step_variables: set of variable names from the bdd test
@type step_variables: set(basestring)
@retu... | 5,338,024 |
def get_typefromSelection(objectType="Edge", info=0):
""" """
m_num_obj, m_selEx, m_objs, m_objNames = get_InfoObjects(info=0, printError=False)
m_found = False
for m_i_o in range(m_num_obj):
if m_found:
break
Sel_i_Object = m_selEx[m_i_o]
Obj_i_Object = m_objs[m_i_o]... | 5,338,025 |
def load_file(file_path, mode='rb', encoder='utf-8'):
"""
Loads the content of a given filename
:param file_path: The file path to load
:param mode: optional mode options
:param encoder: the encoder
:return: The content of the file
"""
with xbmcvfs.File(xbmcvfs.translatePath(file_path), ... | 5,338,026 |
def centcalc_by_weight(data):
"""
Determines the center (of grtavity) of a neutron beam on a 2D detector by weigthing each pixel with its count
--------------------------------------------------
Argments:
----------
data : ndarray : l x m x n array with 'pixel' - data to weight ove... | 5,338,027 |
def sum(a, axis=None, dtype=None, out=None, keepdims=False):
"""Returns the sum of an array along given axes.
Args:
a (cupy.ndarray): Array to take sum.
axis (int or sequence of ints): Axes along which the sum is taken.
dtype: Data type specifier.
out (cupy.ndarray): Output arra... | 5,338,028 |
def to_bool(env, default="false"):
"""
Convert a string to a bool.
"""
return bool(util.strtobool(os.getenv(env, default))) | 5,338,029 |
def public_key():
""" returns public key """
return textwrap.dedent('''
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwBLTc+75h13ZyLWlvup0OmbhZWxohLMMFCUBClSMxZxZdMvyzBnW
+JpOQuvnasAeTLLtEDWSID0AB/EG68Sesr58Js88ORUw3VrjObiG15/iLtAm6hiN
BboTqd8jgWr1yC3LfNSKJk82qQzHJPlCO9Gc5HcqvWrIrq... | 5,338,030 |
def register_blueprints(current_app) -> None:
"""Register app blueprints."""
current_app.register_blueprint(product_blueprint)
current_app.register_blueprint(cart_blueprint)
current_app.register_blueprint(customer_blueprint)
current_app.register_blueprint(restaurant_blueprint)
current_app.regist... | 5,338,031 |
def fetch_WIPOgamma(subset, classification_level, data_home, extracted_path, text_fields = ['abstract', 'description'], limit_description=300):
"""
Fetchs the WIPO-gamma dataset
:param subset: 'train' or 'test' split
:param classification_level: the classification level, either 'subclass' or 'maingroup'... | 5,338,032 |
def latest_maven_version(group_id: str, artifact_id: str) -> Optional[str]:
"""Helper function to find the latest released version of a Maven artifact.
Fetches metadata from Maven Central and parses out the latest released
version.
Args:
group_id (str): The groupId of the Maven artifact
... | 5,338,033 |
def zeropoint(info_dict):
"""
Computes the zero point of a particular system configuration
(filter, atmospheric conditions,optics,camera).
The zeropoint is the magnitude which will lead to one count per second.
By definition ZP = -2.5*log10( Flux_1e-_per_s / Flux_zeromag ),
where Flux_1e-_per_s ... | 5,338,034 |
def logUncaughtExceptions(*exc_info):
"""
Set sys.excepthook to this if you want to make sure a script-ending
exception gets logged. Otherwise that info tends to disappear.
I got this script here:
http://blog.tplus1.com/index.php/2012/08/05/python-log-uncaught-exceptions-with-sys-excepthook/
I ... | 5,338,035 |
def extract_binary_function_range(ida64_path, script_path, binary_paths):
"""this will generate a .json file for each binary file in same path indicating the range of function"""
# binary_paths = use_ida_scripts_get_function_starts_and_ends.read_binary_list(binary_path_list)
# print(binary_paths)
for bi... | 5,338,036 |
def model_comp(real_data, deltaT, binSize, maxTimeLag, abc_results1, final_step1, abc_results2, final_step2,\
model1, model2, distFunc, summStat_metric, ifNorm,\
numSamplesModelComp, eval_start = 3, disp1 = None, disp2 = None):
"""Perform Baysian model comparison with ABC fits from m... | 5,338,037 |
def unwrap(*args, **kwargs):
"""
This in a alias for unwrap_array, which you should use now.
"""
if deprecation_warnings:
print('Use of "unwrap" function is deprecated, the new name '\
' is "unwrap_array".')
return unwrap_array(*args, **kwargs) | 5,338,038 |
def solve():
"""solve form"""
if request.method == 'GET':
sql="SELECT g.class, p.origin, p.no, p.title, p.address FROM GIVE g, PROBLEM p WHERE g.origin=p.origin AND g.no=p.no AND class = 1"
cursor.execute(sql)
week1=[]
for result in cursor.fetchall():
week1.append({
"class":result['class'],
"origin... | 5,338,039 |
def build_path(entities, path_patterns, strict=False):
"""
Constructs a path given a set of entities and a list of potential
filename patterns to use.
Args:
entities (dict): A dictionary mapping entity names to entity values.
path_patterns (str, list): One or more filename patterns to w... | 5,338,040 |
def schedule_compensate():
"""
swagger-doc: 'schedule'
required: []
req:
course_schedule_id:
description: '课程id'
type: 'string'
start:
description: '课程开始时间 format YYYY-mm-dd HH:MM:ss.SSS'
type: 'string'
end:
description: '课程结束时间 in sql format YYY... | 5,338,041 |
def parse(xml):
"""
Parse headerdoc XML into a dictionary format.
Extract classes, functions, and global variables from the given XML output
by headerdoc. Some formatting and text manipulation takes place while
parsing. For example, the `@example` is no longer recognized by headerdoc.
`parse()` will extract exam... | 5,338,042 |
def ReadKeywordValueInFile(filename,keyword):
""" Get value in the expression of keyword=vlaue in file
:param str filenname: file name
:param str keywors: keyword string
:return: value(str) - value string
"""
value=None; lenkey=len(keyword)
if not os.path.exists(filename): retur... | 5,338,043 |
def deprecation_warning(
old: str,
new: Optional[str] = None,
error: Optional[Union[bool, Exception]] = None) -> None:
"""Warns (via the `logger` object) or throws a deprecation warning/error.
Args:
old (str): A description of the "thing" that is to be deprecated.
new (O... | 5,338,044 |
def getSolventList():
"""
Return list of solvent molecules for initializing solvation search form.
If any of the Mintz parameters are None, that solvent is not shown in the list since it will cause error.
"""
database.load('solvation', '')
solvent_list = []
for index, entry in database.solva... | 5,338,045 |
def subset_samples(md_fp: str, factor: str, unstacked_md: pd.DataFrame,
number_of_samples: int, logs:list) -> pd.DataFrame:
"""
Subset the metadata to a maximum set of 100 samples.
! ATTENTION ! In case there are many columns with np.nan,
these should be selected to sele... | 5,338,046 |
def _process_image(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height:... | 5,338,047 |
def broadcast(msg):
"""
Send msg to every client.
"""
for client in CLIENT_LIST:
if type(msg) is list:
for m in msg:
client.send(m + '\n')
else:
client.send(msg + '\n') | 5,338,048 |
def to_rna_sequences(model):
"""
Convert all the sequences present in the model to RNA.
:args dict model: Description model.
"""
for seq, path in yield_sub_model(model, ["sequence"]):
set_by_path(model, path, str(Seq(seq).transcribe().lower()))
return model | 5,338,049 |
async def test_fetch_convbot_with_exc():
"""Test fetch_convbot_with_exc."""
my_route = respx.post("https://convbot-yucongo.koyeb.app/text/").mock(
return_value=Response(204)
)
await fetch_convbot("Hello")
assert my_route.called | 5,338,050 |
def rest_get_repositories(script, project=None, start=0, limit=50):
"""
Gets a list of repositories via REST
:param script: A TestScript instance
:type script: TestScript
:param project: An optional project
:type project: str
:param start: The offset to start from
:type start: int
:p... | 5,338,051 |
def clean_float(input_float):
"""
Return float in seconds (even if it was a timestamp originally)
"""
return (timestamp_to_seconds(input_float)
if ":" in str(input_float) else std_float(input_float)) | 5,338,052 |
def resize(
image,
output_shape,
order=1,
mode="constant",
cval=0,
clip=True,
preserve_range=False,
anti_aliasing=False,
anti_aliasing_sigma=None,
):
"""A wrapper for Scikit-Image resize().
Scikit-Image generates warnings on every call to resize() if it doesn't
receive the rig... | 5,338,053 |
def get_subsystem_fidelity(statevector, trace_systems, subsystem_state):
"""
Compute the fidelity of the quantum subsystem.
Args:
statevector (list|array): The state vector of the complete system
trace_systems (list|range): The indices of the qubits to be traced.
to trace qubits... | 5,338,054 |
def jyfm_data_coke(indicator="焦炭总库存", headers=""):
"""
交易法门-数据-黑色系-焦炭
:param indicator: ["焦企产能利用率-100家独立焦企产能利用率", "焦企产能利用率-230家独立焦企产能利用率",
"焦炭日均产量-100家独立焦企焦炭日均产量", "焦炭日均产量-230家独立焦企焦炭日均产量", "焦炭总库存",
"焦炭焦企库存-100家独立焦企焦炭库存", "焦炭焦企库存-230家独立焦企焦炭库存", "焦炭钢厂库存", "焦炭港口库存", "焦企焦化利润"]
:type indicator: str
... | 5,338,055 |
def reset_s3_client():
"""Clear the S3 client, to free memory."""
global S3_CLIENT
S3_CLIENT = None | 5,338,056 |
def test_wrong_data():
"""
Feature: Fault injector
Description: Test fault injector
Expectation: Throw TypeError exception
"""
# load model
ckpt_path = '../../dataset/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
net = Net()
param_dict = load_checkpoint(ckpt_path)
lo... | 5,338,057 |
def generate_index_distribution(
numTrain: int, numTest: int, numValidation: int, params: UQDistDict
) -> Tuple[Any, ...]:
"""
Generates a vector of indices to partition the data for training. NO
CHECKING IS DONE: it is assumed that the data could be partitioned in the
specified blocks and that the ... | 5,338,058 |
def generacionT (v, m):
"""
Signature of a message with hash, hashed. Here we have to use the private key.
Parameters:
m (int): Number of oil
v (int): Number of vinager
Returns:
T (matrix): Matrix with dimension nxn
"""
#Matriz de distorsion
T = []
n = v + m
for i in range(n):
... | 5,338,059 |
def isotherm_from_bel(path):
"""
Get the isotherm and sample data from a BEL Japan .dat file.
Parameters
----------
path : str
Path to the file to be read.
Returns
-------
dataDF
"""
with open(path) as file:
line = file.readline().rstrip()
meta = {}
... | 5,338,060 |
def image(height, width, image_dir):
"""
Create a background with a image
"""
images = [xx for xx in os.listdir(image_dir) \
if xx.endswith(".jpeg") or xx.endswith(".jpg") or xx.endswith(".png")]
if len(images) > 0:
image_name = images[random.randint(0, len(images) - 1)]
... | 5,338,061 |
def model(x, a, b, c):
"""
Compute
.. math::
y = A + Be^{Cx}
Parameters
----------
x : array-like
The value of the model will be the same shape as the input.
a : float
The additive bias.
b : float
The multiplicative bias.
c : float
The expone... | 5,338,062 |
def test_export_slow_mo_unadjusted():
"""test VideoAsset.export for slow mo video"""
test_dict = UUID_DICT["slow_mo"]
uuid = test_dict["uuid"]
lib = PhotoLibrary()
photo = lib.fetch_uuid(uuid)
with tempfile.TemporaryDirectory(prefix="photokit_test") as tempdir:
export_path = photo.expor... | 5,338,063 |
def add_abspath(dirs: List):
"""Recursively append the absolute path to the paths in a nested list
If not a list, returns the string with absolute path.
"""
if isinstance(dirs, list):
for i, elem in enumerate(dirs):
if isinstance(elem, str):
dirs[i] = os.path.abspath... | 5,338,064 |
def download(new_file_name, file_id):
"""
A function that accesses and downloads files from Google Drive.
Parameters
----------
new_file_name: string
The file name you want a google doc to have after download.
file_if: string
The file id of your desired file on google drive.
... | 5,338,065 |
def equal_matches(
matches_a: kapture.Matches,
matches_b: kapture.Matches) -> bool:
"""
Compare two instances of kapture.Matches.
:param matches_a: first set of matches
:param matches_b: second set of matches
:return: True if they are identical, False otherwise.
"""
assert i... | 5,338,066 |
def convert_to_example(img_data, target_data, img_shape, target_shape, dltile):
""" Converts image and target data into TFRecords example.
Parameters
----------
img_data: ndarray
Image data
target_data: ndarray
Target data
img_shape: tuple
Shape of the image data (h,... | 5,338,067 |
def linear(args, output_size, bias, bias_start=0.0, scope=None, var_on_cpu=True, wd=0.0):
"""Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.
Args:
args: a 2D Tensor or a list of 2D, batch x n, Tensors.
output_size: int, second dimension of W[i].
bias: boolean, whether to add a bi... | 5,338,068 |
def _start_job(rule, settings, urls=None):
"""Start a new job for an InfernoRule
Note that the output of this function is a tuple of (InfernoJob, DiscoJob)
If this InfernoJob fails to start by some reasons, e.g. not enough blobs,
the DiscoJob would be None.
"""
job = InfernoJob(rule, settings, ... | 5,338,069 |
def set_driver(driver):
"""
Sets the Selenium WebDriver used to execute Helium commands. See also
:py:func:`get_driver`.
"""
_get_api_impl().set_driver_impl(driver) | 5,338,070 |
def test_code_search_single_page(mocker, responses):
"""Tests ls.ls for a single page of responses"""
response_content = {
'items': [{
'repository': {
'full_name': 'repo/repo1',
},
}, {
'repository': {
'full_name': 'repo/repo2',... | 5,338,071 |
def mult(dic,data,r=1.0,i=1.0,c=1.0,inv=False,hdr=False,x1=1.0,xn='default'):
"""
Multiple by a Constant
Parameter c is used even when r and i are defined. NMRPipe ignores c when
r or i are defined.
Parameters:
* dic Dictionary of NMRPipe parameters.
* data array of spectral data.
... | 5,338,072 |
def generate_gps_photon(stream, source, focus, angle_gantry, angle_couch, angle_coll, beamletsize, sad, sfd, energy_mev, desc='Diverging Square field', gps_template=None):
"""Generate the gps input file using a template
Args:
idx (int): index of beamlet in beam (row-major order)
sour... | 5,338,073 |
def navigation_target(m) -> re.Pattern:
"""A target to navigate to. Returns a regular expression."""
if hasattr(m, 'any_alphanumeric_key'):
return re.compile(re.escape(m.any_alphanumeric_key), re.IGNORECASE)
if hasattr(m, 'navigation_target_name'):
return re.compile(m.navigation_target_name)... | 5,338,074 |
def hammingDistance(strA, strB):
""" Determines the bitwise Hamming Distance between two strings. Used to
determine the fitness of a mutating string against the input.
Example:
bin(ord('a')) == '0b1100001'
bin(ord('9')) == '0b0111001'
bin... | 5,338,075 |
def dump_tree(ifaces):
"""
Yields all the interfaces transitively implemented by the set in
reverse-depth-first order
"""
for i in ifaces:
yield from dump_tree(i.ifaces)
yield i | 5,338,076 |
def json_parser(path):
"""
Generator that parse a JSON file which contains an array of hashes.
INPUT -> string, path to JSON file
OUTPUT -> dict, yield a media
"""
with open(path) as json_file:
json_data = json.load(json_file)
for i in range(len(json_data)):
yield json_data[i... | 5,338,077 |
def _change_draft_metadata_file_names(bumped_data_structures: dict, new_version: str) -> None:
"""
Change metadata file names of data structures that were RELEASED
from <dataset>__DRAFT.json to <dataset>__<new_version>.json.
"""
for data_structure in bumped_data_structures:
if data_structure... | 5,338,078 |
def convert(s, syntax=None):
"""Convert a regex regular expression to re syntax.
The first argument is the regular expression, as a string object,
just like it would be passed to regex.compile(). (I.e., pass the
actual string object -- string quotes must already have been
removed and the standard ... | 5,338,079 |
def current_user(request):
"""Return the list of all the users with their ids.
"""
query = select([
User.id.label('PK_id'),
User.Login.label('fullname')
]).where(User.id == request.authenticated_userid)
print
return dict(DBSession.execute(query).fetchone()) | 5,338,080 |
def test_auth_decorator_no_permissions():
"""Test auth decorator when no permissions are supplied"""
with pytest.raises(AuthError) as err:
get_access("", "latte")()
assert err.value.code == 401
assert err.value.description == "User don't have access to resource." | 5,338,081 |
async def test_allowlist(hass, mock_client):
"""Test an allowlist only config."""
await _setup(
hass,
{
"include_domains": ["light"],
"include_entity_globs": ["sensor.included_*"],
"include_entities": ["binary_sensor.included"],
},
)
tests = [... | 5,338,082 |
def get_test_examples_labels(dev_example_list, batch_size):
"""
:param dev_example_list: list of filenames containing dev examples
:param batch_size: int
:return: list of nlplingo dev examples, dev labels
"""
dev_chunk_generator = divide_chunks(dev_example_list, NUM_BIG_CHUNKS)
test_examples... | 5,338,083 |
def unpack_collections(*args, **kwargs):
"""Extract collections in preparation for compute/persist/etc...
Intended use is to find all collections in a set of (possibly nested)
python objects, do something to them (compute, etc...), then repackage them
in equivalent python objects.
Parameters
-... | 5,338,084 |
def get_usernames(joomlasession):
"""Get list of usernames on the homepage."""
users = joomlasession.query(Jos_Users).all()
return [user.username for user in users] | 5,338,085 |
def minor_block_encoder(block, include_transactions=False, extra_info=None):
"""Encode a block as JSON object.
:param block: a :class:`ethereum.block.Block`
:param include_transactions: if true transaction details are included, otherwise
only their hashes
:param extra_i... | 5,338,086 |
def test_interpretation(capsys, inputs, kgos, options):
"""Test metadata interpretation. Four tests are run:
- A single compliant file
- A single compliant file with verbose output
- Multiple files, the first of which is non-compliant
- Using the --failures-only option to only print output for non-c... | 5,338,087 |
def heaviside(x):
"""Implementation of the Heaviside step function (https://en.wikipedia.org/wiki/Heaviside_step_function)
Args:
x: Numpy-Array or single Scalar
Returns:
x with step values
"""
if x <= 0:
return 0
else:
return 1 | 5,338,088 |
def FallbackReader(fname):
"""Guess the encoding of a file by brute force by trying one
encoding after the next until something succeeds.
@param fname: file path to read from
"""
txt = None
for enc in GetEncodings():
try:
handle = open(fname, 'rb')
reader = codec... | 5,338,089 |
def graph_3D(data, col="category", list_=[None], game=None, extents=None):
"""
3D t-sne graph data output
:param data: a pandas df generated from app_wrangling.call_boardgame_data()
:param col: string indicating which column (default 'category')
:param list_: list of elements in column (default [No... | 5,338,090 |
def creation_validation(ctx, **kwargs):
"""
check availability of path used in field private key path of
node properties
"""
# combine properties
obj = combine_properties(ctx, kwargs=kwargs,
names=[PRIVATE_KEY, PUBLIC_KEY],
proper... | 5,338,091 |
def get_selector(info, mode="advanced"):
"""
The selector that decides the scope of the dashboard. It MUST have the keywords
?work and ?author.
You can override everything here by adapting the query on WDQS:
https://w.wiki/3Cmd
Args:
info: either a dict containing complex information f... | 5,338,092 |
def set_row_csr(csr, rows, value=0):
"""Set all nonzero elements to the given value. Useful to set to 0 mostly."""
for row in rows:
start = csr.indptr[row]
end = csr.indptr[row + 1]
csr.data[start:end] = value
if value == 0:
csr.eliminate_zeros() | 5,338,093 |
def get_table_names(self, connection, schema=None, **kw):
"""
Get table names
Args:
connection ():
schema ():
**kw:
Returns:
"""
return self._get_table_or_view_names(
["r", "e"], connection, schema, **kw
) | 5,338,094 |
def get_general(prefix, generator, pars, **kwargs):
""" A general getter function that either gets the asked-for data
from a file or generates it with the given generator function. """
pars = get_pars(pars, **kwargs)
id_pars, pars = get_id_pars_and_set_default_pars(pars)
try:
result = read_... | 5,338,095 |
def gen_case(test):
"""Generates an OK test case for a test
Args:
test (``Test``): OK test for this test case
Returns:
``dict``: the OK test case
"""
code_lines = str_to_doctest(test.input.split('\n'), [])
for i in range(len(code_lines) - 1):
if code_lines[i+1].sta... | 5,338,096 |
def run_count1(known_args, options):
"""Runs the first example pipeline."""
logging.info('Running first pipeline')
p = beam.Pipeline(options=options)
(p | beam.io.ReadFromText(known_args.input)
| Count1()
| beam.io.WriteToText(known_args.output))
p.run().wait_until_finish() | 5,338,097 |
def get_user_list_view(request):
"""
render user admin view
Arguments:
request {object} -- wsgi http request object
Returns:
html -- render html template
"""
if request.user.has_perm('auth.view_user'):
user_list = User.objects.all()
temp_name = 'admin/li... | 5,338,098 |
def to_odds(p):
"""
Converts a probability to odds
"""
with np.errstate(divide='ignore'):
return p / (1 - p) | 5,338,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.