content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_processor():
"""Test if the processor runs and returns expected values
"""
acc_baseline, acc_CNN, y_test, y_pred = Processor.runProcessor(full=False)
assert acc_baseline > 0
assert acc_CNN > 0
np.testing.assert_equal(y_test.shape, (10, 10))
np.testing.assert_equal(y_pred.shape, (10,... | 5,307,000 |
def create_pickle_data():
"""create the pickle data"""
# custom geometry column name
gdf_the_geom = geopandas.GeoDataFrame(
{"a": [1, 2, 3], "the_geom": [Point(1, 1), Point(2, 2), Point(3, 3)]},
geometry="the_geom",
)
# with crs
gdf_crs = geopandas.GeoDataFrame(
{"a": [... | 5,307,001 |
def test_integer_max_inclusive003_1544_integer_max_inclusive003_1544_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=maxInclusive and value=7 and
document value=5
"""
assert_bindings(
schema="msData/datatypes/Facets/integer/integer_maxInclusive003.xsd",
... | 5,307,002 |
def test_file_path_evaluation(
tmp_path: Path,
default_rules_collection: RulesCollection,
ansible_project_layout: Dict[str, str],
) -> None:
"""Test file path evaluation when using import_tasks / include_tasks in the project.
Usage of import_tasks / include_tasks may introduce false positive load-f... | 5,307,003 |
def complete_month(year, month):
""" Return a string with the month number padded with zero if the month has
only one digit. It is also necessary to provide a year.
:param year:
:param month:
:return: Month number padded with zero.
:rtype: str
"""
return datetime(year, month, 1).strftim... | 5,307,004 |
def add_logging_level(level_name, level_num):
"""
Adapted from https://stackoverflow.com/a/35804945
(Which is to say, shamelessly stolen and tidied up a bit)
This function will add an additional logging level
"""
method_name = level_name.lower()
if hasattr(logging, level_name) and logging._... | 5,307,005 |
def on_closing(event=None):
"""This function is to be called when the window is closed."""
my_msg.set("\q")
send() | 5,307,006 |
def train_model(
output_model_path,
training_spectra_path,
training_labels_path,
validation_spectra_path,
validation_labels_path,
test_spectra_path,
test_labels_path,
network_factory,
class_names=None,
learning_rate=1e-5,
weight_de... | 5,307,007 |
async def test_create_bracket(mocker):
"""Creates a bracket."""
mock_bot = tosurnament_mock.BotMock()
mock_bot.session.add_stub(Tournament(id=1, guild_id=tosurnament_mock.DEFAULT_GUILD_MOCK.id, current_bracket_id=2))
cog = tosurnament_mock.mock_cog(tournament_module.get_class(mock_bot))
await cog.c... | 5,307,008 |
def score_glue(eval_folder):
"""Join GLUE evaluation"""
# MRPC
mrpc_scores = []
df = pd.read_csv(os.path.join(eval_folder, "mrpc_eval.csv"))
score = ((df['accuracy_score'] + df['f1_score'])/2.0).max()
mrpc_scores.append(score)
# MNLI
df = pd.read_csv(os.path.join(eval_folder, "mnli... | 5,307,009 |
def test_container_to_text_default_encoding_and_err(test_input, expected):
"""
Test for passing objects to container_to_text(). Default encoding and errors
"""
assert container_to_text(test_input, encoding=DEFAULT_ENCODING,
errors=DEFAULT_ERR_HANDLER) == expected | 5,307,010 |
def test_spanreed_code_compliance():
"""
THIS TEST SHOULD REMAIN. IT VALIDATES THAT ALL ERRORS HAVE A UNIQUE CODE AND DO
NOT CONFLICT WITH SPANREED'S RESERVED ERROR CODES
"""
used_codes = set()
for obj in error_module.__dict__.values():
if not isinstance(obj, type):
continue... | 5,307,011 |
def greater_equal(self, other):
""" Equivalent to the >= operator.
"""
return _PropOpB(self, other, numpy.greater_equal, numpy.uint8) | 5,307,012 |
def simu_data(evoked, forward, noise_cov, n_dipoles, times, nave=1):
"""Simulate an evoked dataset with 2 sources.
One source is put in each hemisphere.
"""
# Generate the two dipoles data
mu, sigma = 0.1, 0.005
s1 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(times - mu) ** 2 /
... | 5,307,013 |
def list_api(file_pattern):
"""
return list according to file_pattern
"""
file_list = [f for f in glob.glob(file_pattern)]
targets = []
for file in file_list:
targets.append(os.path.basename(file).split(".")[0])
return targets | 5,307,014 |
def run_experiment(name, contiki, cooja, simulation_file):
"""
Launch the COOJA simulation of an experiment.
All the log of the experiment will be stored in COOJA.log
"""
main_command = ["java", "-mx512m"]
# COOJA
main_command.extend(["-jar", cooja])
# Simulation file
main_command.ap... | 5,307,015 |
def createSharedLibrary(libname, jarfile):
"""Creates a shared library on the specified cell with the given name and jarfile"""
m = "createSharedLibrary:"
#sop(m,"Entry. Create shared library. libname=%s jarfile=%s" % (repr(libname), repr(jarfile) ))
cellname = getCellName()
cell_id = getCellId(cell... | 5,307,016 |
def refined_grid(epc_file, source_grid, fine_coarse,
inherit_properties = False, inherit_realization = None, inherit_all_realizations = False,
source_grid_uuid = None, set_parent_window = None, infill_missing_geometry = True,
new_grid_title = None, new_epc_file = None)... | 5,307,017 |
def transform(window, transform):
"""Construct an affine transform matrix relative to a window.
Parameters
----------
window: Window
The input window.
transform: Affine
an affine transform matrix.
Returns
-------
Affine
The affine transform matrix for the given ... | 5,307,018 |
def auto_escape_sub(match):
"""Escapes ampersands (&) in normal text."""
return escape(match.group(0)) | 5,307,019 |
def get_lib_dir():
"""
Anaconda specific
"""
dirname = 'DLLs' if sys.platform == 'win32' else 'lib'
libdir = os.path.join(sys.prefix, dirname)
return libdir | 5,307,020 |
def populate_form_data(form):
"""
populate form data from settings
"""
for k, _ in form.data.items():
if k == "csrf_token":
continue
value = gluu_settings.db.get(k.upper())
if value:
form[k].data = value
return form | 5,307,021 |
def list_cached_maps():
"""Return a list of all cached maps."""
return local_index()['maps'] | 5,307,022 |
def win2():
"""
This is the configuration for the best performing model from the DPRNN
paper. Training takes very long time with this configuration.
"""
# The model becomes very memory consuming with this small window size.
# You might have to reduce the chunk size as well.
batch_size = 1
... | 5,307,023 |
def _viewer_size(shape):
""" Define the size of the viewer.
Returns: width_view, height_view
"""
# slices_width = sagittal_width (y) + coronal_width (x) + axial_width (x)
slices_width = shape[1] + 2 * shape[0]
# slices_height = max of sagittal_height (z), coronal_height (z), and
# axial... | 5,307,024 |
def lemma_magic(line, cell=None, local_ns=None):
"""Magic to print the LaTeX and result for a Lemma expression
made from the given form."""
if line:
expr = hy_eval_in_ns(f'(require [lemma.core [expr]])\n(expr {line})', local_ns)
return expr
elif cell:
exprs = hy_eval_in_ns(f'(req... | 5,307,025 |
def delete_all_airpollution(lat, lon):
"""Delete all the previous data in the database
under AirPollution model
"""
AirPollution.object.filter(location_lat=lat, location_lon=lon).delete() | 5,307,026 |
def soft_render_variable_num_blocks(
primitives,
num_blocks,
stacking_program,
raw_locations,
raw_color_sharpness,
raw_blur,
num_channels=3,
num_rows=32,
num_cols=32,
):
"""
Args
primitives (list [num_primitives])
num_blocks [*shape]
stacking_program (... | 5,307,027 |
def all_users(number=-1, etag=None):
"""Iterate over every user in the order they signed up for GitHub.
.. deprecated:: 1.2.0
Use :meth:`github3.github.GitHub.all_users` instead.
:param int number: (optional), number of users to return. Default: -1,
returns all of them
:param str etag... | 5,307,028 |
def neighboring_basis_images(accord, lat):
"""Given a coordinate and the corresponding lattice, return
a list of the same coordinate within the neighboring lattice
cells (27 total, including the original coordinate)
Parameters
----------
accord : AtomCoord
lat : Lattice
Returns
---... | 5,307,029 |
def tinyimagenet():
"""
This method is adapted from https://github.com/rmccorm4/Tiny-Imagenet-200/blob/master/networks/data_utils.py
You can find the LICENSE with copyright notive below this method.
"""
path, wnids_path = 'tiny-imagenet-200', 'tiny-imagenet-200'
resize='False'
num_clas... | 5,307,030 |
def preview_agents(previewAgentsArn=None, nextToken=None, maxResults=None):
"""
Previews the agents installed on the EC2 instances that are part of the specified assessment target.
See also: AWS API Documentation
Exceptions
Examples
Previews the agents installed on the EC2 instances that ar... | 5,307,031 |
def update_image(image, centroids):
"""
Update RGB values of pixels in `image` by finding
the closest among the `centroids`
Parameters
----------
image : nparray
(H, W, C) image represented as an nparray
centroids : int
The centroids stored as an nparray
Returns
---... | 5,307,032 |
def url_for(req: Request, name: str, **kwargs) -> str:
"""
Get the URL for a route, absolute with our own BASE_URL
"""
relative_url = req.scope["router"].url_path_for(name, **kwargs)
return f"{str(conf.BASE_URL).rstrip('/')}{relative_url}" | 5,307,033 |
def scrub_email(address):
"""
Remove the local-part from an email address
for the sake of anonymity
:param address: <str>
:return: <str>
"""
if '@' in address:
domain = address.split('@')[1]
return 'user@{}'.format(domain)
else:
return address | 5,307,034 |
def Printer(print_format, out=None, defaults=None, console_attr=None):
"""Returns a resource printer given a format string.
Args:
print_format: The _FORMATTERS name with optional attributes and projection.
out: Output stream, log.out if None.
defaults: Optional resource_projection_spec.ProjectionSpec d... | 5,307,035 |
def pattern_search(search_pattern):
"""
Search for search_pattern in pattern. Convert from hex if needed
Looking for needle in haystack
@param search_pattern: pattern to serach for
"""
needle = search_pattern
try:
if needle.startswith('0x'):
# Strip off '0x', convert to ASCII and reverse
needle = needl... | 5,307,036 |
def get_file_references(dist):
"""
Yield FileReference found in a ``dist`` importlib_metadata.Distribution.
"""
if not dist.files:
return
for filepath in dist.files or []:
# FIXME: the path is relative to the "site-packages" directory or the
# root of a wheel but this should... | 5,307,037 |
def test_mets_dnx():
"""Test basic construction of METS DNX"""
ie_dc_dict = {"dc:title": "test title"}
mets = mdf.build_mets(
ie_dmd_dict=ie_dc_dict,
pres_master_dir=os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'data',
'test_batch_1',
... | 5,307,038 |
def write_data(data=None,
data_op_file=None):
"""
Given the arguments below, writes crtomo-readable file.
:param nelem: number of cells
:param electrode_spacing: electrode spacing
:param data: np.array containing A B M N locations in METERS, RESISTANCE, and IP (mrad)
:param data... | 5,307,039 |
def construct_neighbors(taxid):
"""Construct Neighbor objects for all neighbors of a taxonomic ID.
Args:
taxid: taxonomic ID to download neighbors for
Returns:
list of Neighbor objects
"""
logger.info(("Constructing a list of neighbors for taxid %d") % taxid)
expected_col_orde... | 5,307,040 |
def get_votes(discussion: dict) -> dict:
"""Retrieves votes on both argumentations and the thesis itself.
"""
path = f'{domain}/discussions/{discussion["id"]}/perspectives/1/votes?filter=all'
return requests.get(path).json()['votes'] | 5,307,041 |
def modify_res(res, cur):
""" Преобразует список-результат запроса в свисок словарей"""
result = list()
for ll in res:
temp_dict = dict()
for k, v in zip(cur.description, ll):
temp_dict[k[0]] = bytes(v) if type(v) is memoryview else v
result.append(temp_dict)
return r... | 5,307,042 |
def get_X_hs_out_d_t(X_NR_d_t, X_req_d_t_i, V_dash_supply_d_t_i, X_hs_out_min_C_d_t, L_star_CL_d_t_i, region):
"""(15-1)(15-2)
Args:
X_NR_d_t: 日付dの時刻tにおける非居室の絶対湿度(kg/kg(DA))
X_req_d_t_i: 日付dの時刻tにおける暖冷房区画iの熱源機の出口における要求絶対湿度(kg/kg(DA))
V_dash_supply_d_t_i: 日付dの時刻tにおける暖冷房区画iのVAV調整前の吹き出し風量(m3/h)
... | 5,307,043 |
def ys_write_btor(
ctx = None,
toolchain = None,
name = None,
mode = None,
srcs = [],
deps = [],
preamble = [],
arguments = [],
multiclock = _DEFAULT_MULTICLOCK,
nomem = _DEFAULT_NOMEM,
syn = _DEFAULT_SYN):
"""Compile a Verilog ... | 5,307,044 |
def get_standard_model_list():
"""Returns the list of all models shown in the main paper figures."""
return [m for m in MODEL_SIZE.keys() if not m.startswith("bit-imagenet")] | 5,307,045 |
def retry(exceptions, total_attempts=3, delay=3, backoff=2):
"""Decorator for retrying function calls.
:param exceptions: expected exceptions to retry on -- class or tuple
:param total_attempts: times to run function before failure. -- int
:param delay: initial delay between retries in seconds. -- int
... | 5,307,046 |
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""Return the sum along diagonals of the array.
If a is 2-d, returns the sum along the diagonal of self with the given offset, i.e., the
collection of elements of the form a[i,i+offset]. If a has more than two
dimensions, then the axes spe... | 5,307,047 |
def robot_eye(xfade_n, xfade_sec, pin, led_n, color, bg_color,
move_mode, speed,
brightness, offset, interactive, debug):
""" robot_eye """
obj = RobotEyes_Circle7LEDs(xfade_n=xfade_n,
xfade_sec=xfade_sec,
pin=pin, led_... | 5,307,048 |
def test_audio_frame():
"""Test AudioFrame."""
assert AudioFrame.is_topic(AudioFrame.topic(site_id=site_id))
assert AudioFrame.get_site_id(AudioFrame.topic(site_id=site_id)) == site_id | 5,307,049 |
def forum_page_item():
"""developer item loaded from html file"""
return items.load_forum_page(fake_response_from_file('forum_page.html', url=fixtures.FORUM_URL)) | 5,307,050 |
def _GetBestVisibleResponse(_input_proto, output_proto, _config):
"""Add fake paths to a successful GetBestVisible response."""
package_info = common_pb2.PackageInfo(
category='category',
package_name='name',
version='1.01',
)
output_proto.package_info.CopyFrom(package_info) | 5,307,051 |
def test_render():
"""
For good measure, render some actual templates.
"""
class CountryTable(tables.MemoryTable):
name = tables.TextColumn()
capital = tables.TextColumn()
population = tables.NumberColumn(verbose_name="Population Size")
currency = tables.NumberColumn(vis... | 5,307,052 |
def make_pulse(duration, pulsechan):
"""
Configure the counter `pulsechan` to output
a pulse of the given `duration` (in seconds).
"""
pulse = daq.Task()
pulse.CreateCOPulseChanTime(
pulsechan, "", # physical channel, name to assign
daq.DAQmx_Val_Seconds, # units:sec... | 5,307,053 |
def disp_multiple(im1=None, im2=None, im3=None, im4=None):
"""
Combines four images for display.
"""
height, width = im1.shape
combined = np.zeros((2 * height, 2 * width, 3), dtype=np.uint8)
combined[0:height, 0:width, :] = cv2.cvtColor(im1, cv2.COLOR_GRAY2RGB)
combined[height:, 0:width, ... | 5,307,054 |
def params_args(args=None):
"""
Parse command line arguments
:param args: command line arguments or None (default)
:return: dictionary of parameters
"""
# parameters of model and files
params = argparse.ArgumentParser(description='Run distribute model simnet bow.')
params.add_argument("-... | 5,307,055 |
def parse_arguments(args):
"""Parse the commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--version", action="version", version="%(prog)s 2.0")
parser.add_argument("input", help="directory to analyze")
parser.add_argument("--output", help="The directory where to plac... | 5,307,056 |
def dump(glob,file):
"""dump global"""
glob=glob.replace('^','')
gref=iris.gref(glob)
_d=ddata(gref)
if _d[0] < 1 :
print('Global not found')
return 0
if file == "" :
file=glob+".json"
#; init file
fil=open(file,'w')
fil.write('{"gbl":"'+glob+'","n... | 5,307,057 |
def plot_bestfit(bin):
""" Plot best fit. """
table = Table.read("{}_bestfit.fits".format(bin))
values = yaml.load(open("{}.yaml".format(bin)))
wave = table["lam"].data
norm = values["flux_norm"] * np.power(10., -20) * u.Unit("erg/s/cm/cm/AA")
flux = table["galaxy"].data * norm
error = table... | 5,307,058 |
def truncated_normal_init(m: nn.Module):
"""Initializes the weights of the given module using a truncated normal distribution."""
if isinstance(m, nn.Linear):
input_dim = m.weight.data.shape[0]
stddev = 1 / (2 * np.sqrt(input_dim))
mbrl.util.math.truncated_normal_(m.weight.data, std=std... | 5,307,059 |
def load_config_yaml(path: str) -> Dict[str, Any]:
"""
Load yaml from local/remote location
"""
with fsspec.open(path, "r") as f:
d = yaml.safe_load(f)
return d | 5,307,060 |
def ngrams(letters: List[str], n: int) -> List[Tuple]:
"""
Given a list of letters, write a function that returns a list of all possible ngrams of length N.
>>> list(ngrams(['a'], 2))
[]
>>> list(ngrams(['a', 'b', 'c'], 2))
[('a', 'b'), ('b', 'c')]
>>> list(ngrams(['a', 'b', 'c', 'd'], 2))... | 5,307,061 |
def parse_sexp(toc_input, toc_output, indent_str, i):
"""
Translate TOC in the s-exp format output by ``djvused`` to a
format understood by ``pdfbeads``.
``toc_input[i:]`` is the string to parse, and ``indent_str`` is
the string of tabulations for our current level in the output
TOC. The outpu... | 5,307,062 |
def test_get_temperature_rise_spec_sheet(page_number):
"""get_temperature_rise_spec_sheet() should return a float value for the
temperature_rise on success."""
_temperature_rise = inductor.get_temperature_rise_spec_sheet(page_number)
assert isinstance(_temperature_rise, float)
assert (
_tem... | 5,307,063 |
def symm_area(col, n):
"""
returns n + (n - 1) + ... + (n - col + 1)
i.e., the number of matrix elements below and including the diagonal and
from column 0 to column `col`
"""
return col * (2 * n - col + 1) // 2 | 5,307,064 |
def parse_data_pkt(pkt, tk):
"""Extract data from a WPA packet @pkt with temporal key @tk"""
TSC, TA, data = parse_TKIP_hdr(pkt)
TK = [orb(x) for x in tk]
rc4_key = gen_TKIP_RC4_key(TSC, TA, TK)
return ARC4_decrypt(rc4_key, data) | 5,307,065 |
def finder(scenario, multiplier, conserve_total):
"""yield what we can find."""
res = []
for dirname, _dirpath, filenames in os.walk("/i/0/cli"):
for fn in filenames:
res.append(
[f"{dirname}/{fn}", scenario, multiplier, conserve_total]
)
return res | 5,307,066 |
def test_no_lifecycle_policy():
"""Test that expiration is parsed from a bucket with multiple rules."""
expected_params = {"Bucket": "cloudtrail"}
stubber.add_client_error(
method="get_bucket_lifecycle_configuration",
service_error_code="NoSuchLifecycleConfiguration",
service_message... | 5,307,067 |
def find_device(p, tags):
"""
Find an audio device to read input from
"""
device_index = None
for i in range(p.get_device_count()):
devinfo = p.get_device_info_by_index(i)
print("Device %d: %s" % (i, devinfo["name"]))
for keyword in tags:
if keyword in devinfo["n... | 5,307,068 |
def check_value(name, value, expected):
""" simplify verification of values in extract_from """
if isinstance(expected, (list, tuple)):
if value not in expected:
exp_str = '[' + ' OR '.join('{0:04X}'.format(val)
for val in expected) + ']'
r... | 5,307,069 |
def group_freeTime():
"""
Connect with the database first and get all the collection inside,
then merge each collection by calling merge function in the available time.
After merge all the free time, use them to replace the current database collection.
Since the database_Free is sorted by the start time, for the c... | 5,307,070 |
def dict2xml_str(
attr_type: bool,
attr: dict[str, Any],
item: dict[str, Any],
item_func: Callable[[str], str],
cdata: bool,
item_name: str,
item_wrap: bool,
parentIsList: bool,
parent: str = "",
list_headers: bool = False,
) -> str:
"""
parse dict2xml
"""
keys_st... | 5,307,071 |
def test_one():
"""Test complex one."""
atom_areas_ref = np.loadtxt(DATA_DIR / "atom_areas/1.txt")
elements, coordinates = read_xyz(XYZ_DIR / "1.xyz")
sasa = SASA(elements, coordinates)
atom_areas = np.array(list(sasa.atom_areas.values()))
assert_almost_equal(sasa.area, 624, decimal=0)
asse... | 5,307,072 |
def top_user_decks(pages):
"""
Gets the hearthpwn.com urls for pages worth of top-rated user-created decks
Returns a list of urls
"""
top_decks = []
main_url = "https://www.hearthpwn.com/"
search_url = "decks?filter-deck-tag=1&filter-show-constructed-only=y&filter-show-standard=1&page="
... | 5,307,073 |
def iterate_flattened(d):
"""
Recursively iterate over the items of a dictionary.
Provides a full dotted paths for every leaf.
"""
for key in sorted(d.keys()):
value = d[key]
if isinstance(value, dict) and value:
for k, v in iterate_flattened(d[key]):
yie... | 5,307,074 |
def fail(msg: str) -> Parser:
"""A parser that always fails with the given message."""
@parser
def g(cursor: Cursor, aux: Any):
raise Failure(msg)
return g | 5,307,075 |
def build_model_cols(feature_dict: dict, out_vocab_dir=None, print_details=True):
"""
Builds inputs needed to specify a tf.keras.Model. The tf_cols_* are TensorFlow feature_columns. The
inputs_* are dictionaries of tf.keras.Inputs. The tf_cols_* are used to specify keras.DenseFeatures methods and
the i... | 5,307,076 |
def normalize_lons(l1, l2):
"""
An international date line safe way of returning a range of longitudes.
>>> normalize_lons(20, 30) # no IDL within the range
[(20, 30)]
>>> normalize_lons(-17, +17) # no IDL within the range
[(-17, 17)]
>>> normalize_lons(-178, +179)
[(-180, -178), (179... | 5,307,077 |
def gitless_drafts():
""" Render the gitless posts that a user has created in table form
Editors can see all the posts created via Gitless_Editing
"""
prefixes = current_app.config.get('WEB_EDITOR_PREFIXES', [])
if prefixes == []:
raise Exception('Web editing is not configured')
que... | 5,307,078 |
def register():
""" Registers a new user. """
username = request.args.get('username')
email = request.args.get('email')
password = request.args.get('password')
if not all([username, email, password]):
msg = 'You must provide a username, email, and password to register.'
return jsoni... | 5,307,079 |
def regress_from_features(batch_features, out_dim):
"""Regress to a rotation representation from point cloud encodings.
In Zhou et al, CVPR19, the paper describes this regression network as an MLP
mapping 2048->512->512->out_dim, but the associated code implements it with
one less layer: 2048->512->out_dim. We... | 5,307,080 |
def get_object_name(trans_id):
"""
This method is used to get the object name
Args:
trans_id: unique transaction id
"""
# Check the transaction and connection status
status, error_msg, conn, trans_obj, session_obj = \
check_transaction_status(trans_id)
if error_msg == gett... | 5,307,081 |
def input_fn(dir, subset, batch_size):
"""Create a dataset from a list of filenames and shard batches from it"""
dir1 = "G:/unaltered_TEM_crops-171x171/"
dir2 = "G:/unaltered_STEM_crops-171x171/"
with tf.device('/cpu:0'):
dataset1 = tf.data.Dataset.list_files(dir1+"*.tif") #dir+subset+"... | 5,307,082 |
def extract_list(p):
"""Check if there is a list after p"""
for sibling in p.next_siblings:
if sibling.name == 'ul':
return [li.text for li in sibling.find_all('li')]
if sibling.name == 'p':
return None | 5,307,083 |
def download(year: str, month: str, destdir: str):
"""
Downloads on-time performance data and returns local filename
year e.g.'2015'
month e.g. '01 for January
"""
logging.info('Requesting data for {}-{}-*'.format(year, month))
url = os.path.join(SOURCE,
"On_Time_Repo... | 5,307,084 |
def set_icon(x, textrect):
"""Automatically fills a TextRect with an icon from Hazard or FontAwesome fonts"""
xl = x.lower()
if xl in haz_lookup_dict:
textrect.style.set_attr("font-name", "Hazard")
textrect.text = haz_lookup_dict[xl]
if xl in fa_lookup_dict:
textrect.style.set_at... | 5,307,085 |
def _in_simplifiable_layout(layout_idx: int) -> Callable[[Coupling], bool]:
"""
Return if (q1,q2) qubit is in simplifiable layout.
"""
if layout_idx == 0:
return lambda q: (not q[0][1] % 2) and q[0][0] == q[1][0]
if layout_idx == 1:
return lambda q: (not q[0][0] % 2) and q[0][1] == ... | 5,307,086 |
def mean_squared_error(
original: Union[Iterable, Sized],
forecasted: Union[Iterable, Sized]) -> float:
"""
Рассчитывает среднюю квадратичную ошибку. Формула:
MSE = sum((o - f) ^ 2) / n
:param original: истинные (эталонные) значения
:param forecasted: спрогнозированные значе... | 5,307,087 |
def test_fillstates():
"""Can we fill states"""
data = {"AK": 10, "HI": 30, "IA": 40, "NY": 80}
mp = MapPlot(
sector="nws",
title="Fill AK, HI, IA, NY States",
subtitle="test_fillstates",
nocaption=True,
)
mp.fill_states(data, lblformat="%.0f", ilabel=True)
return... | 5,307,088 |
def test_stolen_import_json_api(flask_app, db_conn, api_version):
"""Test Depot ID not known yet.
Verify that job_metadata returns a JSON containing job metadata
for importing stolen_list job.
"""
extra_metadata = {'output_stats':
{'num_records_updated': 20,
... | 5,307,089 |
def resample_ortho_sca(raw_image, raw_ulx, raw_uly, raw_pixel_size, x, y):
""" Resample geosca image to new map grids.
Arguments:
raw_image: 2D array
Raw geosca image data.
raw_ulx, raw_uly: float
Map coordinates of the upper-left corner of the raw image.
raw_pixe... | 5,307,090 |
def isQSO_highz_faint(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,
objtype=None, release=None, dchisq=None, maskbits=None,
primary=None, south=True):
"""Definition of QSO target for highz (z>2.0) faint QSOs. Returns a boolean array.
Parameters
--... | 5,307,091 |
def is_email_validate(self, attribute_name, attribute_value, properties):
"""
Validates an attribute to ensure that the value is an email.
:type attribute_name: String
:param attribute_name: The name of the attribute to be validated.
:type attribute_value: Object
:param attribute_value: ... | 5,307,092 |
def obter_posicoes_jogador(tab, peca):
"""
Devolve as posicoes ocupadas pelo jogador.
:param tab: tabuleiro
:return: tuplo
Recebe um tabuleiro, e devolve um tuplo com todas as posicoes ocupadas pelo jogador no tabuleiro inserido.
"""
return tuple(pos for pos in obter_posicoes() i... | 5,307,093 |
def install_excepthook() -> None:
"""Install a thin wrapper for sys.excepthook to catch gulag-related stuff."""
sys._excepthook = sys.excepthook # backup
def _excepthook(
type_: Type[BaseException],
value: BaseException,
traceback: types.TracebackType
):
if type_ is Keybo... | 5,307,094 |
def find_true_link(s):
"""
Sometimes Google wraps our links inside sneaky tracking links, which often fail and slow us down
so remove them.
"""
# Convert "/url?q=<real_url>" to "<real_url>".
if s and s.startswith('/') and 'http' in s:
s = s[s.find('http'):]
return s | 5,307,095 |
def generate_png_stem(fnames: List[str],
smiles_on_command_line: Optional[List[str]],
config: Smiles2PngConfig) -> str:
"""Generate a stem for generated png files.
Complicated by the fact that input might be from stdin,
and so the first file name might be '-'.
Args:... | 5,307,096 |
def _get_block_indices(y):
"""
y is a length n_verts vector of labels
returns a length n_verts vector in the same order as the input
indicates which block each node is
"""
block_labels, block_inv, block_sizes = np.unique(
y, return_inverse=True, return_counts=True
)
n_blocks = l... | 5,307,097 |
def _unmerge_points(
board_points: Tuple[int, ...]
) -> Tuple[Tuple[int, ...], Tuple[int, ...]]:
"""Return player and opponent board positions starting from their respective ace points."""
player: Tuple[int, ...] = tuple(
map(
lambda n: 0 if n < 0 else n,
board_points,
... | 5,307,098 |
def test_single_point():
"""Tests for the number of data points greater than 1."""
os.chdir(os.path.dirname(__file__) + '/data')
proc = subprocess.Popen(['swc', 'check', 'fail_single_point.swc'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... | 5,307,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.