content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def lock_file(filename):
"""
Locks a file so that the exodus reader can safely read
a file without something else writing to it while we do it.
"""
with open(filename, "a+") as f:
fcntl.flock(f, fcntl.LOCK_SH)
yield
fcntl.flock(f, fcntl.LOCK_UN) | 5,327,900 |
def get_install_path():
"""Use registry and asking the user to better determine the install directory."""
reg_likely_path = get_registry_path()
if reg_likely_path:
user_path = get_user_path(initial_dir=reg_likely_path.as_posix())
else:
user_path = get_user_path(initial_dir=r'C:/Program F... | 5,327,901 |
def constant(t, length):
""" ezgal.sfhs.constant( ages, length )
Burst of constant starformation from t=0 to t=length """
if type(t) == type(np.array([])):
sfr = np.zeros(t.size)
m = t <= length
if m.sum(): sfr[m] = 1.0
return sfr
else:
return 0.0 if t > length el... | 5,327,902 |
def export_json(data, output=None):
"""Creates a json file as output"""
if output is not None:
if not output.endswith('.json'):
output += '.json'
with open(f'{output}', 'w') as f:
json.dump(data, f)
else:
print(data) | 5,327,903 |
def write_values(event_number, cube, index, oasis_file):
"""
write out one oasis compatible csv file
write out one file for wind gusts histogram bin index an # x, y, z file
output should be index, grid point histogram bin index value, confidence for all grid points:
"""
# Check we get... | 5,327,904 |
def model_setup_fn(attrs):
"""Generate the setup function for models."""
model = load_model(attrs['type'], attrs['data'])
def func(self):
self.model = model
self.type = attrs['type']
self.data = attrs['data']
self.network_type = attrs['network_type']
self.dto = attr... | 5,327,905 |
def run_throughput_inner(query_root, data_dir, generated_query_dir,
host, port, database, user, password,
stream, num_streams, queue, verbose):
"""
:param query_root:
:param data_dir: subdirectory with data to be loaded
:param generated_query_dir: subdi... | 5,327,906 |
def _mkdir(space, dirname, mode=0777, recursive=False, w_ctx=None):
""" mkdir - Makes directory """
mode = 0x7FFFFFFF & mode
if not _valid_fname(dirname):
space.ec.warn("mkdir() expects parameter 1 to "
"be a valid path, string given")
return space.w_False
if not ... | 5,327,907 |
def test_error_y_is_None():
"""Assert that an error is raised when y is None for some strategies."""
selector = FeatureSelector(strategy="univariate", solver=f_regression, n_features=9)
pytest.raises(ValueError, selector.fit, X_reg) | 5,327,908 |
def test_colorizer(event=None):
"""Run all unit tests for leoColorizer.py."""
g.run_unit_tests('leo.unittests.core.test_leoColorizer.TestColorizer') | 5,327,909 |
def prepare_fixed_decimal(data, schema):
"""Converts decimal.Decimal to fixed length bytes array"""
if not isinstance(data, decimal.Decimal):
return data
scale = schema.get('scale', 0)
size = schema['size']
# based on https://github.com/apache/avro/pull/82/
sign, digits, exp = data.as_... | 5,327,910 |
def hello_fmt(values: Dict[str, List[int]]):
"""Print the sum per category.
Args:
values: Dict containing lists of int per category.
"""
print(", ".join(f"{k}: {sum(v)}" for k, v in values.items())) | 5,327,911 |
def _create_profile_d_file(prefix):
"""
Create profile.d file with Java environment variables set.
"""
from fabtools.require.files import file as require_file
require_file(
'/etc/profile.d/java.sh',
contents=dedent("""\
export JAVA_HOME="%s/jdk"
export PATH="... | 5,327,912 |
def test_add_method():
"""Tests the __add__ method"""
options={"column_names":["Frequency","b","c"],"column_names_delimiter":",","data":[[0.1*10**10,1,2],[2*10**10,3,4]],
"data_delimiter":'\t',
"header":['Hello There',"My Darling"],"column_names_begin_token":'#',"comment_begin":'!',
... | 5,327,913 |
def test_arrayer_thread():
"""Tests that the arrayer monitor thread can be restarted after exit"""
j1 = Job(array_task(1))
j1.task = array_task
sched = mock_scheduler()
exec = mock_executor(sched)
arr = job_array.JobArrayer(exec, submit_interval=10000.0, stale_time=0.05, min_array_size=5)
... | 5,327,914 |
def test_feature_flexiblerollout_stickiness_100(unleash_client):
"""
Feature.flexible.rollout.custom.stickiness_100 should be enabled without field defined for 100%
"""
# Set up API
responses.add(responses.POST, URL + REGISTER_URL, json={}, status=202)
responses.add(responses.GET, URL + FEATURES... | 5,327,915 |
def wait_ele_disappear(context, selector=None):
"""
The specified selector element string disappears from the page within
a specified period of time
:param context: step context
:param selector: locator string for selector element (or None).
"""
g_Context.step.wait_ele_disappear(context, se... | 5,327,916 |
def device_traits() -> dict[str, Any]:
"""Fixture that sets default traits used for devices."""
return {"sdm.devices.traits.Info": {"customName": "My Sensor"}} | 5,327,917 |
def writeOutput(ipData,outfilename):
""" Writes the text output """
# Get the current working directory so we can write the results file there
outfilename = os.path.join(os.getcwd(),outfilename+'.txt')
file1 = open(outfilename,'w')
numPoints = ipData.size
for i in xrange(numPoints)... | 5,327,918 |
async def setup_bga_account(message, bga_username, bga_password):
"""Save and verify login info."""
# Delete account info posted on a public channel
discord_id = message.author.id
if message.guild:
await message.delete()
account = BGAAccount()
logged_in = account.login(bga_username, bga_... | 5,327,919 |
def calculate_equivalent_diameter(areas):
"""Calculate the equivalent diameters of a list or numpy array of areas.
:param areas: List or numpy array of areas.
:return: List of equivalent diameters.
"""
areas = np.asarray(areas)
diameters = np.sqrt(4 * areas / np.pi)
return diameters.tolis... | 5,327,920 |
def test_audit_log(s3_stubber):
"""Test that reversion revisions are created."""
company_without_change = CompanyFactory(
great_profile_status=Company.GREAT_PROFILE_STATUSES.published,
)
company_with_change = CompanyFactory(
great_profile_status=Company.GREAT_PROFILE_STATUSES.unpublished... | 5,327,921 |
def truncation_error(stencil: list, deriv: int, interval: str = DEFAULT_INTERVAL):
"""
derive the leading-order of error term
in the finite difference equation based on the given stencil.
Args:
stencil (list of int): relative point numbers
used for discretization.
deriv (int... | 5,327,922 |
def _get_parameter_defaults(fpm, metadata, readout_mode, subarray, frame_time,
temperature, cosmic_ray_mode, verbose=2,
logger=LOGGER):
"""
Helper function to obtain appropriate defaults for parameters
that have not been explicitly set.
(Saves... | 5,327,923 |
def cmd_renderurl(cfg, command, argv):
"""Renders a single url of your blog to stdout."""
parser = build_parser('%prog renderurl [options] <url> [<url>...]')
parser.add_option('--headers',
action='store_true', dest='headers', default=False,
help='Option that caus... | 5,327,924 |
def combine_expressions(expressions, relation='AND', licensing=Licensing()):
"""
Return a combined license expression string with relation, given a list of
license expressions strings.
For example:
>>> a = 'mit'
>>> b = 'gpl'
>>> combine_expressions([a, b])
'mit AND gpl'
>>> assert ... | 5,327,925 |
def parrallelize(model: nn.Module) -> nn.Module:
""" Make use of all available GPU using nn.DataParallel
NOTE: ensure to be using different random seeds for each process if you use techniques like data-augmentation or any other techniques which needs random numbers different for each steps. TODO: make sure this... | 5,327,926 |
def get_prof_details(prof_id):
"""
Returns the details of the professor in same order as DB.
"""
cursor = sqlite3.connect('./db.sqlite3').cursor()
cursor.execute("SELECT * FROM professor WHERE prof_id = ?;", (prof_id))
return cursor.fetchone() | 5,327,927 |
def test_can_understand_Td_symmetry():
"""Ensure values match regression logfiles for Td symmetry."""
data = datasets.logfiles["tanaka1996"][
"methane@UMP2/6-311G(2df,2pd)"
] # tetrahedron
moments, axes, atomcoords = coords.inertia(data.atommasses, data.atomcoords)
assert moments == pytest.... | 5,327,928 |
def get_process_path(tshark_path=None, process_name='tshark'):
"""
Finds the path of the tshark executable. If the user has provided a path
or specified a location in config.ini it will be used. Otherwise default
locations will be searched.
:param tshark_path: Path of the tshark binary
:raises ... | 5,327,929 |
def test_set_simplify():
"""This tests our ability to simplify set objects.
This test is pretty simple since sets just serialize to
lists, with a tuple wrapper with the correct ID (3)
for sets so that the detailer knows how to interpret it."""
input = set(["hello", "world"])
set_detail_index =... | 5,327,930 |
def test_add_order_error_validate_bool_product_code(client):
"""Must be error on validate data"""
data = dict(user_id=1, product_code=False)
response = client.post("/orders", headers=HEADERS, json=data)
response_data = response.json().get("detail")[0]
assert response.status_code == status.HTTP_422_U... | 5,327,931 |
def stats_per_gop(processed_video_sequence, needed=[]):
"""
general helper to extract statistics on a per gop basis
"""
logging.debug(f"calculate {needed} gop based for {processed_video_sequence}")
results = []
for gop in by_gop(processed_video_sequence, columns=needed + ["FrameType"]):
... | 5,327,932 |
def test_TileServer_get_tiles_url():
"""Should work as expected (create TileServer object and get tiles endpoint)."""
r = RasterTiles(raster_path)
app = TileServer(r)
assert app.get_tiles_url() == "http://127.0.0.1:8080/tiles/{z}/{x}/{y}.png" | 5,327,933 |
def available_help(mod, ending="_command"):
"""Returns the dochelp from all functions in this module that have _command
at the end."""
help_text = []
for key in mod.__dict__:
if key.endswith(ending):
name = key.split(ending)[0]
help_text.append(name + ":\n" + mod.__dict__... | 5,327,934 |
def __s_polynomial(g, h):
"""
Computes the S-polynomial of g, h. The S-polynomial is a polynomial built explicitly so that the leading terms
cancel when combining g and h linearly.
"""
deg_g = __multidegree(g)
deg_h = __multidegree(h)
max_deg = map(max, zip(deg_g, deg_h))
R = g.parent()... | 5,327,935 |
def notification_reminder(paci_list,supervisor,operator,type):
"""
This method sends first, second, reminders and then send third one and cc supervisor in the email
"""
first_reminder_list=[]
second_reminder_list=[]
penality_reminder_list=[]
if paci_list and len(paci_list) > 0:
fo... | 5,327,936 |
def generate_map_chunk(size_x: int, size_y: int, biome_type: str, x_offset: int = 0, y_offset: int = 0):
"""
Function responsible for generating map chunk in specified or random biome type,
map chunk is basically a rectangular part of a map;
generated array is basically nested list represent... | 5,327,937 |
def initialize(g, app):
"""
If postgresql url is defined in configuration params a
scoped session will be created
"""
if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']:
# Database connection established for console commands
for k, v in app.config['DATABASES']['... | 5,327,938 |
def register(workflow_id, workflow_version):
"""Register an (empty) workflow definition in the database."""
name = "workflow_definitions:{}:{}".format(workflow_id, workflow_version)
workflow_definition = dict(id=workflow_id, version=workflow_version,
stages=[])
# DB.set_ha... | 5,327,939 |
def newid(length=16):
"""
Generate a new random string ID.
The generated ID is uniformly distributed and cryptographically strong. It is
hence usable for things like secret keys and access tokens.
:param length: The length (in chars) of the ID to generate.
:type length: int
:returns: A ra... | 5,327,940 |
def test_process_cycle(zs2_file_name, verbose=True):
"""This is a test to check if util output changed
in an incompatible manner. A zs2 file is read, converted to XML,
and back-converted to a raw datastream."""
if verbose:
print('Decoding %s...' % zs2_file_name)
data_stream = _parser.l... | 5,327,941 |
def test_dataset_isel(
dask_client, # pylint: disable=redefined-outer-name,unused-argument
):
"""Test dataset selection."""
ds = create_test_dataset()
selected_ds = ds.isel(slices=dict(x=slice(0, 2)))
assert selected_ds.dimensions == dict(x=2, y=2)
assert selected_ds.attrs == (dataset.Attri... | 5,327,942 |
def test_interpolation_dx():
"""
Test interpolation of a SparseFunction from a Derivative of
a Function.
"""
u = unit_box(shape=(11, 11))
sf1 = SparseFunction(name='s', grid=u.grid, npoint=1)
sf1.coordinates.data[0, :] = (0.5, 0.5)
op = Operator(sf1.interpolate(u.dx))
assert sf1.da... | 5,327,943 |
def test_gas_concentration(value):
"""
Test if the Stc3xGasConcentration() type works as expected for different
values.
"""
result = Stc3xGasConcentration(value.get('ticks'))
assert type(result) is Stc3xGasConcentration
assert type(result.ticks) is int
assert result.ticks == value.get('t... | 5,327,944 |
def get_dev_risk(weight, error):
"""
:param weight: shape [N, 1], the importance weight for N source samples in the validation set
:param error: shape [N, 1], the error value for each source sample in the validation set
(typically 0 for correct classification and 1 for wrong classification)
"""
... | 5,327,945 |
def skewness_fn(x, dim=1):
"""Calculates skewness of data "x" along dimension "dim"."""
std, mean = torch.std_mean(x, dim)
n = torch.Tensor([x.shape[dim]]).to(x.device)
eps = 1e-6 # for stability
sample_bias_adjustment = torch.sqrt(n * (n - 1)) / (n - 2)
skewness = sample_bias_adjustment * (
... | 5,327,946 |
def encrypt(message):
""" Self-developed encryption method that uses base conversion """
base = random.randint(3, 9)
number_list = []
for i in message:
number_list.append(keys.index(i)+1)
converted_number_list = []
for i in number_list:
converted_number_list.append(convert(i, bas... | 5,327,947 |
def run_shell(cmd: list[str], cwd: str = "", silent: bool = False) -> None:
"""Run command silently."""
if silent:
subprocess.call(
cmd,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
else:
subprocess.call(cmd, cwd=cwd) | 5,327,948 |
def drop_it():
"""
Given the array arr, iterate through and remove each element starting from the first element (the 0 index)
until the function func returns true when the iterated element is passed through it.
Then return the rest of the array once the condition is satisfied, otherwise,
arr should ... | 5,327,949 |
def get_signature_algorithm(algorithm_type_string):
"""convert a string into a key_type (TFTF_SIGNATURE_TYPE_xxx)
returns a numeric key_type, or raises an exception if invalid
"""
try:
return TFTF_SIGNATURE_ALGORITHMS[algorithm_type_string]
except:
raise ValueError("Unknown algorith... | 5,327,950 |
def print_wer_vs_length():
"""Print the average word error rate for each length sentence."""
avg_wers = map(mean, wer_bins)
for i in range(len(avg_wers)):
print "%5d %f"%(i, avg_wers[i])
print "" | 5,327,951 |
def pytest_sessionstart():
""" Download sct_testing_data prior to test collection. """
logger.info("Downloading sct test data")
downloader.main(['-d', 'sct_testing_data', '-o', sct_test_path()]) | 5,327,952 |
def bending_without_n_iteration(model, values, concrete_type, exp):
"""Calculate the necessery longitudial reinforcment of a
beam that is loaded by a torque load without normal forces.
Parameters
----------
model : class
class method that contains the Finite Element Analysis
Returns
... | 5,327,953 |
def corrgroups60(display=False):
""" A simulated dataset with tight correlations among distinct groups of features.
"""
# set a constant seed
old_seed = np.random.seed()
np.random.seed(0)
# generate dataset with known correlation
N = 1000
M = 60
# set one coefficent from each grou... | 5,327,954 |
def test_string_indexer():
"""Test String indexers."""
ob = Test.StringIndexerTest()
assert ob["spam"] is None
assert ob[u"spam"] is None
ob["spam"] = "spam"
assert ob["spam"] == "spam"
assert ob["spam"] == u"spam"
assert ob[u"spam"] == "spam"
assert ob[u"spam"] == u"spam"
ob[... | 5,327,955 |
def alpha_nu_gao08(profile, **kwargs):
"""log normal distribution of alpha about the
alpha--peak height relation from Gao+2008"""
z = kwargs["z"]
alpha = kwargs["alpha"]
# scatter in dex
if "sigma_alpha" in kwargs:
sigma_alpha = kwargs["sigma_alpha"]
else:
# take scatter fr... | 5,327,956 |
def testRedirect():
"""Redirect URL"""
assert ['http://rediretinmyurl.com/http://dest.url.org/1/2/3/4?434', 'http://secondurl.com', 'ftp://1.2.3.4/adsfasdf'] == grab('http://rediretinmyurl.com/http://dest.url.org/1/2/3/4?434 http://secondurl.com ftp://1.2.3.4/adsfasdf', needScheme) | 5,327,957 |
def get_feed_entries(helper, name, stats):
"""Pulls the indicators from the minemeld feed."""
feed_url = helper.get_arg('feed_url')
feed_creds = helper.get_arg('credentials')
feed_headers = {}
# If auth is specified, add it as a header.
if feed_creds is not None:
auth = '{0}:{1}'.format(... | 5,327,958 |
def test_eager(celery_worker, task_app_request, dbsession, demo_user):
"""When in eager mode, transactions are executed properly.."""
celery = get_celery(task_app_request.registry)
celery._conf["task_always_eager"] = True
try:
# Try RetryableTransactionTask in eager mode
with transact... | 5,327,959 |
def get_skeleton_definition(character):
"""
Returns skeleton definition of the given character
:param character: str, HIK character name
:return: dict
"""
hik_bones = dict()
hik_count = maya.cmds.hikGetNodeCount()
for i in range(hik_count):
bone = get_skeleton_node(character, i)... | 5,327,960 |
def get_f_a_st(
fuel="C3H8",
oxidizer="O2:1 N2:3.76",
mech="gri30.cti"
):
"""
Calculate the stoichiometric fuel/air ratio of an undiluted mixture using
Cantera. Calculates using only x_fuel to allow for compound oxidizer
(e.g. air)
Parameters
----------
fuel : str
... | 5,327,961 |
def get_parser_args(args=None):
"""
Transform args (``None``, ``str``, ``list``, ``dict``) to parser-compatible (list of strings) args.
Parameters
----------
args : string, list, dict, default=None
Arguments. If dict, '--' are added in front and there should not be positional arguments.
... | 5,327,962 |
def parse_time_to_min(time):
"""Convert a duration to an integer in minutes.
Example
-------
>>> parse_time_to_min("2m 30s")
2.5
"""
if " " in time:
return sum([parse_time_to_min(t) for t in time.split(" ")])
time = time.strip()
for unit, value in time_units.items():
... | 5,327,963 |
def relate_stream_island(stream_layer, island_layer):
"""
Return the streams inside or delimiting islands.
The topology is defined by DE-9IM matrices.
:param stream_layer: the layer of the river network
:stream_layer type: QgisVectorLayer object (lines)
:param island_layer: the layer... | 5,327,964 |
def stringify_array(v,
maxDepth=None,
maxItems=-1,
maxStrlen=-1):
"""
Convert a dict to a string representation.
Parameters:
d(dict) : the data dict to convert
maxDepth (int|None): if > 0, then ellipsise structures deeper than th... | 5,327,965 |
def rpickle(picke_file, state=None):
"""
Save the state of the gps file treated
"""
logger.warning('Running rpickle ...')
results = []
if picke_file.isfile():
with open(picke_file, 'rb') as read_pickle:
results += pickle.load(read_pickle)
# print results
return result... | 5,327,966 |
def navigation_task(MAX_LOOP, direction):
""" Moving Alphabot """
Ab = alphabot.AlphaBot2()
try:
count = 0
while count < MAX_LOOP:
time.sleep(0.300)
if direction.lower() == 'forward':
Ab.forward()
if direction.lower() == 'backward':
... | 5,327,967 |
def test_pydist():
"""Make sure pydist.json exists and validates against our schema."""
# XXX this test may need manual cleanup of older wheels
import jsonschema
def open_json(filename):
return json.loads(open(filename, 'rb').read().decode('utf-8'))
pymeta_schema = open_json(resource_file... | 5,327,968 |
def should_print(test_function):
"""should_print is a helper for testing code that uses print
For example, if you had a function like this:
```python
def hello(name):
print('Hello,', name)
```
You might want to test that it prints "Hello, Nate" if you give it the
name "Nate". To d... | 5,327,969 |
def clusters_to_annotations(image):
"""
<gui>
<item name="image" type="Image" label="Image" role="output"/>
</gui>
"""
itk_image = medipy.itk.medipy_image_to_itk_image(image, False)
annotations_calculator = itk.ClustersToAnnotationsCalculator[itk_image].New(
Imag... | 5,327,970 |
def fista(y, A, At, reg_weight, noise_eng, max_iter=100, update_reg=False, **kwargs):
"""
The FISTA algorithm for the ell1 minimisation problem:
min_x |y - Ax|^2 + reg * |x|_1
:param y: the given measurements (here it is the Fourier transform at certain frequencies)
:param A: the mapping from the sp... | 5,327,971 |
def produce_segmentation(indices: list[list[int]], wav_name: str) -> list[dict]:
"""produces the segmentation yaml content from the indices of the probabilistic_dac
Args:
indices (list[list[int]]): output of the probabilistic_dac function
wav_name (str): the name of the wav file (with the .wav ... | 5,327,972 |
def create_table_persons():
"""
Table: fp.persons
Partition key: name (string)
Attributes: polls (number), friends (number)
RCU: 2
WCU: 2
"""
try:
print('Creating persons table...')
dynamodb.create_table(
TableName='fp.persons',
KeySchema... | 5,327,973 |
def trac_get_tracs_for_object(obj, user=None, trac_type=None):
"""
Returns tracs for a specific object.
"""
content_type = ContentType.objects.get_for_model(type(obj))
qs = Trac.objects.filter(content_type=content_type, object_id=obj.pk)
if user:
qs = qs.filter(user=user)
if trac_typ... | 5,327,974 |
def open_in_browser(url : str):
"""Open the link in (default) browser.
Args:
url (string): URL to be opened
Raises:
NorURLError: If the url is NOT a url.
"""
val = url_validate(url)
if val == True:
webbrowser.open_new_tab(url) # Use built-in module to open url in ne... | 5,327,975 |
def display_help(parser, sub_command_parsers, perf_args, adb_device, verbose):
"""Display help for command referenced by perf_args.
Args:
parser: argparse.ArgumentParser instance which is used to print the
global help string.
sub_command_parsers: Dictionary of argparse.ArgumentParser instances
... | 5,327,976 |
def db_upgrade(c, target="head"):
"""
Upgrade the db to the target alembic revision.
"""
c.run(f"poetry run alembic upgrade {target}", pty=True, env=env) | 5,327,977 |
def size_from_ftp(ftp, url):
"""Get size of a file on an FTP server.
Parameters
----------
ftp : FTP
An open ftplib FTP session.
url : str
File URL.
Returns
-------
int
Size in bytes.
"""
url = urlparse(url)
return ftp.size(url.path) | 5,327,978 |
def set_name_line(hole_lines, name):
"""Define the label of each line of the hole
Parameters
----------
hole_lines: list
a list of line object of the slot
name: str
the name to give to the line
Returns
-------
hole_lines: list
List of line object with label
... | 5,327,979 |
def dist_to_boxes(points, boxes):
"""
Calculates combined distance for each point to all boxes
:param points: (N, 3)
:param boxes: (N, 7) [x, y, z, h, w, l, ry]
:return: distances_array: (M) torch.Tensor of [(N), (N), ...] distances
"""
distances_array = torch.Tensor([])
box_corners = ki... | 5,327,980 |
def print_listdir(x):
"""."""
log = logging.getLogger('SIP.workflow.function')
log.info('HERE A')
print('Task id = {} {}'.format(x, os.listdir('.')))
return x, os.listdir('.') | 5,327,981 |
def blackwhite2D(data,xsize=None,ysize=None,show=1):
"""blackwhite2D(data,xsize=None,ysize=None,show=1)) - display list or array data as black white image
default popup window with (300x300) pixels
"""
if type(data) == type([]):
data = array(data)
w,h = data.shape[1],data.shape[0]
... | 5,327,982 |
def contains_digit(s):
"""Find all files that contain a number and store their patterns.
"""
isdigit = str.isdigit
return any(map(isdigit, s)) | 5,327,983 |
def to_signed(dtype):
"""
Return dtype that can hold data of passed dtype but is signed.
Raise ValueError if no such dtype exists.
Parameters
----------
dtype : `numpy.dtype`
dtype whose values the new dtype needs to be able to represent.
Returns
-------
`numpy.dtype`
"... | 5,327,984 |
def prepare_model_runs(args):
"""Generate multiple model runs according to a model run file referencing a scenario
with multiple variants.
"""
# Read model run and scenario using the Store class
store = _get_store(args)
nb_variants = len(store.read_scenario_variants(args.scenario_name))
# De... | 5,327,985 |
def listen_for_wakeword():
"""Continuously detecting the appeareance of wakeword from the audio stream. Higher priority than the listen() function.
Returns:
(bool): return True if detected wakeword, False otherwise.
"""
gotWakeWord = core.listen_for_wakeword()
return gotWakeWord | 5,327,986 |
def test_server():
"""
Validate Server operations.
"""
server: Server[int] = Server()
assert str(server) == "(Server: busy=False)"
assert server.ready
assert not server.busy
assert server.size == 0
# Push a packet
server.serve(10)
assert not server.ready
assert server.bu... | 5,327,987 |
def import_string(import_name):
"""Returns a callable for a given setuptools style import string
:param import_name: A console_scripts style import string
"""
import_name = str(import_name).replace(":", ".")
try:
import_module(import_name)
except ImportError:
if "." not in impor... | 5,327,988 |
def kurtosis(x,y):
"""
Calculate kurtosis of the probability
distribution of the forecast error if
an observation and forecast vector are given.
Both vectors must have same length, so pairs of
elements with same index are compared.
Description:
Kurtosis is a measure of the magnitud... | 5,327,989 |
def preprocess_text(sentence):
"""Handle some weird edge cases in parsing, like 'i' needing to be capitalized
to be correctly identified as a pronoun"""
cleaned = []
words = sentence.split(' ')
for w in words:
if w == 'i':
w = 'I'
if w == "i'm":
w = "I'm"
... | 5,327,990 |
def _GetModuleFromPathViaPkgutil(module_path, name_to_give):
"""Loads module by using pkgutil.get_importer mechanism."""
importer = pkgutil.get_importer(os.path.dirname(module_path))
if importer:
if hasattr(importer, '_par'):
# par zipimporters must have full path from the zip root.
# pylint:disab... | 5,327,991 |
def test_both_inputs():
"""Test error while both type of inputs used"""
result = runner.invoke(main, BAD_BOTH_PARAMS_COMMAND)
assert result.exit_code == 1 | 5,327,992 |
def weighted_l2_loss(gt_value, pred_value, weights):
"""Computers an l2 loss given broadcastable weights and inputs."""
diff = pred_value - gt_value
squared_diff = diff * diff
if isinstance(gt_value, float):
gt_shape = [1]
else:
gt_shape = gt_value.get_shape().as_list()
if isinstance(weights... | 5,327,993 |
def csr_scale_rows(*args):
"""
csr_scale_rows(npy_int32 const n_row, npy_int32 const n_col, npy_int32 const [] Ap, npy_int32 const [] Aj,
npy_bool_wrapper [] Ax, npy_bool_wrapper const [] Xx)
csr_scale_rows(npy_int32 const n_row, npy_int32 const n_col, npy_int32 const [] Ap, npy_int32 const [] Aj,
... | 5,327,994 |
def Uninstall(vm):
"""Uninstalls the pip package on the VM."""
pip.Uninstall(vm, pip_cmd='pip3') | 5,327,995 |
def view_scene(args: argparse.Namespace) -> None:
"""Read GTSFM output from .txt files and render the scene to the GUI.
We also zero-center the point cloud, and transform camera poses to a new
world frame, where the point cloud is zero-centered.
Args:
args: rendering options.
"""
point... | 5,327,996 |
def get_homography_calibration_files(fullpath=True):
"""
Returns a list of the homography calibration yaml files in the homgraphies directory
of the mct configuration.
"""
file_list = os.listdir(homographies_dir)
dummy, params_file = os.path.split(homography_calibrator_params_file)
file_list... | 5,327,997 |
def complexity_hjorth(signal):
"""**Hjorth's Complexity and Parameters**
Hjorth Parameters are indicators of statistical properties initially introduced by Hjorth
(1970) to describe the general characteristics of an EEG trace in a few quantitative terms, but
which can applied to any time series. The pa... | 5,327,998 |
def load_gecko():
"""
target variable is column "A375 Percent rank"
"""
data_nonessential = pandas.read_excel(settings.pj(settings.offtarget_data_dir, 'GeCKOv2_Non_essentials_Achilles_A375_complete.xls')) #(4697, 31)
data_all_A375 = pandas.read_csv(settings.pj(settings.offtarget_data_dir, 'GeckoAvan... | 5,327,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.