content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def is_close(A, B, tol=np.sqrt(_eps)):
"""
Check if two matrices are close in the sense of trace distance.
"""
if tracedist(A, B) < tol:
return True
else:
A[np.abs(A) < tol] = 0.0
B[np.abs(B) < tol] = 0.0
A /= np.exp(1j*np.angle(A[0,0]))
B /= np.exp(1j*np.angl... | 5,356,400 |
def hist3d_numba_seq_weight(tracks, weights, bins, ranges, use_memmap=False, tmp=None):
"""Numba-compiled weighted 3d histogram
From https://iscinumpy.dev/post/histogram-speeds-in-python/
Parameters
----------
tracks : (x, y, z)
List of input arrays of identical length, to be histogrammed
... | 5,356,401 |
def test_stem_name():
""" test the internal function to find the stemp of a filename"""
assert fm._stem_name("Test.xlsx") == "test"
assert fm._stem_name(r"c:\test\test.xlsx") == "test"
assert fm._stem_name(r".\Test.xls") == "test" | 5,356,402 |
def do_extract(
archive: str,
*,
output_dir: typing.Optional[str],
verbose: bool,
name_encoding: str,
) -> None:
"""Extract all files and directories from an archive."""
if output_dir is None:
output_dir = os.path.basename(archive) + ".extracted"
with click.open_file(archive, "rb") as archivef:
parsed =... | 5,356,403 |
def convertTimeQuiet(s):
"""
Converts a time String in the form hh:mm:ss[.nnnnnnnnn] to a long nanoseconds offset from Epoch.
:param s: (java.lang.String) - The String to convert.
:return: (long) QueryConstants.NULL_LONG if the String cannot be parsed, otherwise long nanoseconds offset from Epoch.
... | 5,356,404 |
def pop_first_non_none_value(
*args,
msg: Optional[str] = "default error msg",
):
"""
Args:
args: a list of python values
Returns:
return the first non-none value
"""
for arg in args:
if arg is not None:
return arg
raise ValueError(f"{msg} can't find n... | 5,356,405 |
def addToolbarItem(
aController,
anIdentifier,
aLabel,
aPaletteLabel,
aToolTip,
aTarget,
anAction,
anItemContent,
aMenu,
):
"""
Adds an freshly created item to the toolbar defined by
aController. Makes a number of assumptions about the
implementation of aController. ... | 5,356,406 |
def start(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
update.message.reply_text(
"Hi! I am a work in progress bot. My job is to help this awesome CTLPE Intake 5 group, "
"especially with deadlines. Type /deadlines to start. For list of sup... | 5,356,407 |
def all_equal(iterable):
"""
Returns True if all the elements are equal.
Reference:
Add "equal" builtin function
https://mail.python.org/pipermail/python-ideas/2016-October/042734.html
"""
groups = groupby(iterable)
return next(groups, True) and not next(groups, Fal... | 5,356,408 |
async def alliance(ctx,*,request : str=''):
"""Returns trophy data over time for an alliance"""
results = member_info.alliance(request)
member_info.os.chdir('plots')
result = [x for x in zip(results[0],results[1])]
await ctx.send("Alliance trophy data over time. Alliance names and IDs:"+lined_s... | 5,356,409 |
def is_str(required=False, default=None, min_len=None, max_len=None, pattern=None):
"""
Returns a function that when invoked with a given input asserts that the input is a valid string
and that it meets the specified criteria. All text are automatically striped off of both trailing and leading
... | 5,356,410 |
def test_100606_closed():
"""Test that we can accurately close off an unclosed polygon."""
prod = parser(get_test_file("SPCPTS/PTSDY1_closed.txt"))
# prod.draw_outlooks()
outlook = prod.get_outlook("CATEGORICAL", "TSTM", 1)
assert abs(outlook.geometry.area - 572.878) < 0.01 | 5,356,411 |
def test_arange():
"""
test arange default
Returns:
None
"""
with fluid.dygraph.guard():
x = paddle.arange(1, 5, 0.5)
expect = [1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000, 4.5000]
tools.compare(x.numpy(), expect) | 5,356,412 |
def load_property_file(filename):
"""
Loads a file containing x=a,b,c... properties separated by newlines, and
returns an OrderedDict where the key is x and the value is [a,b,c...]
:param filename:
:return:
"""
props = OrderedDict()
if not os.path.exists(filename):
return props
... | 5,356,413 |
def fit_curve(df, country, status, start_date, end_date=None):
"""
Summary line.
Extended description of function.
Parameters:
arg1 (int): Description of arg1
Returns:
int: Description of return value
"""
# Select the data
slc_date = slice(start_date, end_date)
y_data = ... | 5,356,414 |
def load_data_from(file_path):
"""
Loads the ttl, given by file_path and returns (file_path, data, triple_count)
Data stores triples.
"""
graph = Graph()
graph.parse(file_path, format="ttl")
data = {}
triple_count = 0
for subject, predicate, object in graph:
triple_count += ... | 5,356,415 |
def change_circle_handler():
"""Change the circle radius."""
global radius
radius = size
# Insert code to make radius label change. | 5,356,416 |
def test_def_type_in_submod_procedure():
"""Test that going into the definition of a type bound procedure in a submodule"""
string = write_rpc_request(1, "initialize", {"rootPath": str(test_dir)})
file_path = test_dir / "subdir" / "test_submod.F90"
string += def_request(file_path, 36, 13)
errcode, r... | 5,356,417 |
def get_predictability(X, y, dtype='continuous'):
"""Returns scores for various models when given a dataframe and target set
Arguments:
X (dataframe)
y (series)
dtype (str): categorical or continuous
Note: X and y must be equal in column length
Returns... | 5,356,418 |
def generate_guid(shard=0, base_uuid=None):
"""
Generates an "optimized" UUID that accomodates the btree indexing
algorithms used in database index b-trees. Check the internet for
details but the tl;dr is big endian is everything.
Leveraging the following as the reference implementation:
https:... | 5,356,419 |
def load(name):
"""Loads dataset as numpy array."""
x, y = get_uci_data(name)
if len(y.shape) == 1:
y = y[:, None]
train_test_split = 0.8
random_permutation = np.random.permutation(x.shape[0])
n_train = int(x.shape[0] * train_test_split)
train_ind = random_permutation[:n_train]
test_ind = random_per... | 5,356,420 |
def read_file(filename):
"""
Read :py:class:`msbuildpy.corflags.CorFlags` from a .NET assembly file path.
**None** is returned if the PE file is invalid.
:param filename: A file path to a .NET assembly/executable.
:return: :py:class:`msbuildpy.corflags.CorFlags` or **None**
"""
... | 5,356,421 |
def cleanup_all(threshold_date=None):
"""Clean up the main soft deletable resources.
This function contains an order of calls to
clean up the soft-deletable resources.
:param threshold_date: soft deletions older than this date will be removed
:returns: total number of entries removed from the datab... | 5,356,422 |
def parse_config(config_strings):
"""Parse config from strings.
Args:
config_strings (string): strings of model config.
Returns:
Config: model config
"""
temp_file = tempfile.NamedTemporaryFile()
config_path = f'{temp_file.name}.py'
with open(config_path, 'w') as f:
... | 5,356,423 |
def validate_profile_info(df, fix=False):
"""
Validates the form of an information profile dataframe. An information profile dataframe must look something like this:
pos info info_err
0 0.01 0.005
1 0.03 0.006
2 0.006 0.008
A 'pos' column reports the... | 5,356,424 |
def load(*names, override=True, raise_exception=False):
"""
Read the given names and load their content into this configuration module.
:param names: a varg that contains paths (str) to the conf files
that need to be read or names of environment variables with paths.
:param override: determines whet... | 5,356,425 |
def consolidate_variables(
inputs: Iterable[Tuple[core.Key, xarray.Dataset]],
merge_kwargs: Optional[Mapping[str, Any]] = None,
) -> Iterator[Tuple[core.Key, xarray.Dataset]]:
"""Consolidate chunks across distinct variables into (Key, Dataset) pairs."""
kwargs = dict(
compat='equals',
join='exac... | 5,356,426 |
def test_network_netstat(network):
"""
network.netstat
"""
ret = network.netstat()
exp_out = ["proto", "local-address"]
for val in ret:
for out in exp_out:
assert out in val | 5,356,427 |
def degrees(cell):
"""Convert from radians to degress"""
return math.degrees(GetNum(cell)) | 5,356,428 |
def create_address(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'POST':
data = JSONParser().parse(request)
serializer = AddressSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(... | 5,356,429 |
def passthrough_build(source_path, build_path):
"""Simply copies files into the build directory without any special instructions."""
build_dir, _ = os.path.split(build_path)
shutil.rmtree(build_path)
shutil.copytree(source_path, build_path)
return | 5,356,430 |
def createPhysicalAddressDataframe(userDf):
"""
This method create PhoneNumber dataframe for CDM
:param userDf: person dataframe
:type userDf: object
"""
addressColumns = [
"id as personId","city","country","officeLocation","postalCode","state","streetAddress"
]
return userDf.selec... | 5,356,431 |
def methods_cli(obj: object, exit=True) -> None:
"""Converts an object to an application CLI.
Every public method of the object that does not require arguments becomes
a command to run.
"""
stack_funcnames = {_frame_to_funcname(frame_info) for frame_info in
inspect.stack()}
... | 5,356,432 |
def test_to_graph_should_return_identifier() -> None:
"""It returns a standard graph isomorphic to spec."""
standard = Standard()
standard.identifier = "http://example.com/standards/1"
src = """
@prefix dct: <http://purl.org/dc/terms/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-sy... | 5,356,433 |
def test_reproject_continuous(n=100, m=20, r=10):
"""Test pre._reprojection.reproject_continuous()."""
# Construct dummy operators.
k = 1 + r + r*(r+1)//2
D = np.diag(1 - np.logspace(-1, -2, n))
W = la.qr(np.random.normal(size=(n,n)))[0]
A = W.T @ D @ W
Ht = np.random.random((n,n,n))
H =... | 5,356,434 |
def index():
""" Custom View """
module_name = deployment_settings.modules[module].name_nice
return dict(module_name=module_name) | 5,356,435 |
def _lm_map_func(hparams, sos_id, eos_id, prot_size):
"""Return a closure for the BDLM with the SOS/EOS ids"""
def lm_map_func(id, seq_len, seq, phyche):
prot_eye = tf.eye(prot_size)
# split characters
seq = tf.string_split([seq], delimiter="").values
# map to integers
se... | 5,356,436 |
def isSpecificInterfaceType(t, name):
""" True if `t` is an interface type with the given name, or a forward
declaration or typedef aliasing it.
`name` must not be the name of a typedef but the actual name of the
interface.
"""
t = unaliasType(t)
return t.kind in ('interface', 'forward') an... | 5,356,437 |
def is_stem(path: Optional[str]) -> bool:
"""Check if the given path is a stem."""
if path is None:
return False
path = path.lower()
parent = str(Path(path).parent)
if parent == ".":
root, ext = os.path.splitext(path)
if ext == "":
return True
return False | 5,356,438 |
def now():
"""Returns the current time in ISO8501 format.
"""
return datetime.datetime.now().isoformat() | 5,356,439 |
def get_CF_matrix_from_parent_vector(parent, D, alpha, beta):
"""Documentation to be added."""
cell_ids = list(D.keys())
mut_ids = list(D[cell_ids[0]].keys())
children = {}
children[ROOT] = []
for mut_id in mut_ids:
children[mut_id] = []
for child_id, parent_id in parent.items():
... | 5,356,440 |
def get_resource_path(filename: str = "") -> str:
"""
get the resource path in the resource in the test dir.
/path/to/resource/filename
"""
current = os.path.abspath(__file__)
current_path = os.path.dirname(current)
resource_dir = os.path.join(current_path, 'resource')
return os.path.joi... | 5,356,441 |
def esr_1_2(out_filename, source_folder, dest_folder=getcwd(),
one_hot=True, normalized=True, out_type="float", balanced_classes=False,
n_batch=None, batch_size=None, validation_size=30, validation_as_copy=False, test_size=160, save_stats=False):
"""Create a esr dataset for DENN."""
dataset_p... | 5,356,442 |
def chec_to_2d_array(input_img, img_map=chec_transformation_map()):
"""
Convert images comming form "CHEC" cameras in order to get regular 2D
"rectangular" images directly usable with most image processing tools.
Parameters
----------
input_img : numpy.array
The image to convert
Re... | 5,356,443 |
def noop_chew_func(_data, _arg):
"""
No-op chew function.
"""
return 0 | 5,356,444 |
async def http_session(aioresponse) -> aiohttp.ClientSession:
"""
Fixture function for a aiohttp.ClientSession.
Requests fixture aioresponse to ensure that all client sessions do not make actual requests.
"""
resolver = aiohttp.AsyncResolver()
connector = aiohttp.TCPConnector(resolver=resolver)... | 5,356,445 |
def find_middle_snake_less_memory(old_sequence, N, new_sequence, M):
"""
A variant of the 'find middle snake' function that uses O(min(len(a), len(b)))
memory instead of O(len(a) + len(b)) memory. This does not improve the
worst-case memory requirement, but it takes the best case memory requirement
... | 5,356,446 |
def music_pos(style_name, st, at):
"""
Returns the track position to Ren'Py.
"""
global time_position
if music.get_pos(channel="music_room") is not None:
time_position = music.get_pos(channel="music_room")
readableTime = convert_time(time_position)
d = Text(readableTime, style=sty... | 5,356,447 |
def get_time(data=None):
"""Receive a dictionary or a string and return a datatime instance.
data = {"year": 2006,
"month": 11,
"day": 21,
"hour": 16,
"minute": 30 ,
"second": 00}
or
data = "21/11/06 16:30:00"
2018-04-17T17:13:50Z
... | 5,356,448 |
def set_clock(child, timestamp=None):
"""Set the device's clock.
:param pexpect.spawn child: The connection in a child application object.
:param datetime timestamp: A datetime tuple (year, month, day, hour, minute, second).
:returns: The updated connection in a child application object.
:rtype: pe... | 5,356,449 |
def import_databases(from_release, to_release, from_path=None, simplex=False):
""" Imports databases. """
devnull = open(os.devnull, 'w')
if not from_path:
from_path = POSTGRES_DUMP_MOUNT_PATH
from_dir = os.path.join(from_path, "upgrade")
LOG.info("Importing databases")
try:
#... | 5,356,450 |
def feature_structure(string, case, intr=False):
"""Convert person-number string to a single feature structure.
Examples:
>>> feature_structure('1s', 'Nom', True)
['Nom', '+1', '-2', '-3', '+sg', '-pl', '+intr']
>>> feature_structure('2p', 'Abs', True)
['Abs', '-1', '+2', '-3', '-sg', '+pl', '... | 5,356,451 |
def repo_description(gurl, owner, repo):
"""
Returns: (status_code, status_text, data)
data = {"created_at": date, "description": str,
"stargazers_count": int, "subscribers_count": int}
"""
res = "/repos/{}/{}".format(owner, repo)
response = gurl.request(funcs.get_hub_url(res))
c... | 5,356,452 |
def check_omf_version(file_version):
"""Validate file version compatibility against the current OMF version
This logic may become more complex with future releases.
"""
if file_version is None:
return True
return file_version == OMF_VERSION | 5,356,453 |
def create_ks_scheduled_constant_graph_ops(
graph: tf_compat.Graph,
global_step: tf_compat.Variable,
var_names: List[str],
begin_step: int,
end_step: int,
ks_group: str,
) -> Tuple[tf_compat.Tensor, List[PruningOpVars]]:
"""
Creates constant model pruning ops. Does not modify the graph.... | 5,356,454 |
def findImages(dataPath):
"""
Finds all the images needed for training on the path `dataPath`.
Returns `([centerPaths], [leftPath], [rightPath], [measurement])`
"""
directories = [x[0] for x in os.walk(dataPath)]
dataDirectories = list(filter(lambda directory: os.path.isfile(directory + '/drivin... | 5,356,455 |
def insert(user_job_id: ObjectId, classifier: str, fastq_path: str, read_type: str or None = None) -> ObjectId:
"""
Insert a new ClassificationJob into the collection.
:param user_job_id: Which UserJob is associated with this ClassificationJob
:param classifier: The classifier to use
:param fastq_pa... | 5,356,456 |
def as_columns(
things: List[Union[SheetColumn, list, tuple, set, str]]
) -> List[SheetColumn]:
"""A list of each thing as a SheetColumn"""
result = []
for thing in things:
if isinstance(thing, SheetColumn):
sheet_column = thing
elif isinstance(thing, (list, tuple, set)):
... | 5,356,457 |
def generator_path(x_base, y_base):
"""[summary]
use spline 2d get path
"""
sp2d = Spline2D(x_base, y_base)
res = []
for i in np.arange(0, sp2d.s[-1], 0.1):
x, y = sp2d.calc_position(i)
yaw = sp2d.calc_yaw(i)
curvature = sp2d.calc_curvature(i)
res.append(... | 5,356,458 |
def test_model_recommend_food(model, two_person_data):
"""
Test the random selection of the food
"""
model.add_data(two_person_data)
assert type(model.recommend('Jason')) == str | 5,356,459 |
def index(request):
"""Render site index page."""
return {} | 5,356,460 |
def bellman_ford_with_term_status(graph, is_multiplicative=False):
"""
An implementation of the multiplication-based Bellman-Ford algorithm.
:param: graph - The graph on which to operate. Should be a square matrix, where edges that don't
exist have value None
:param: graph_labels - ... | 5,356,461 |
def decoder(z, rnn, batch_size, state=None, n_dec=64, reuse=None):
"""Summary
Parameters
----------
z : TYPE
Description
rnn : TYPE
Description
batch_size : TYPE
Description
state : None, optional
Description
n_dec : int, optional
Description
... | 5,356,462 |
def extract_locus_with_pyfaidx(blast_outformat_6_file, query_id, full_path_to_assembly, full_path_to_output, left_buffer = left_buffer, right_buffer = right_buffer):
"""The purpose of this function is to extract the regions from each contig of interest."""
#collects regions from blastout file
result ... | 5,356,463 |
def parse_file(filename):
"""Parses the file containing the db schema
Key Arguments:
filename - the file to parse"""
f = open(filename, 'r')
lines = f.readlines()
f.close()
db = {}
for line in lines:
s_line = line.split('\t')
if s_line[0] == 'TABLE_CATALOG':
... | 5,356,464 |
def only_sig(row_a,row):
"""Returns only significant events"""
if(row_a[-1] != '-' and row_a[-1] != 0.0 and row_a[-1] <= 0.05):
row = row[0].split('_') + row[2:]
row.insert(2, 'A.to.G')
print '\t'.join(map(str,row)) | 5,356,465 |
def est_L(sample_list, est_method, bandwidth = 0.5):
"""Estimate L from a list of samples.
Parameter
------------------------------------------
sample_list: list
a list of samples for arm i at time t
est_method: str
can be one of the choice of 'kde', 'naive'
'kde': kernel de... | 5,356,466 |
def columnpicker(
frame="None",
track_id="None",
x_coordinates="None",
y_coordinates="None",
z_coordinates="None",
measurment="None",
second_measurment="None",
field_of_view_id="None",
additional_filter="None",
measurement_math="None",
Ok=False,
):
"""Dialog with magicgui... | 5,356,467 |
def create_test_area(test_tiles):
"""Create geometry from test images
Parameters
----------
test_tiles : list
directory with test images
Returns
-------
GeoPandas DataFrame
all test images merged into a GeoDataFrame
"""
multipolygon = ogr.Geometry(ogr.wkbMultiPolyg... | 5,356,468 |
def check_token(token) -> bool:
"""Check ReCaptcha token
Args:
token
Returns:
bool
"""
if os.getenv("CI"):
return True
url = "https://www.google.com/recaptcha/api/siteverify"
secret_key = os.getenv("RECAPTCHA_SECRET_KEY")
payload = {
"secret": secret_... | 5,356,469 |
def covSEard(x,
z,
ell,
sf2
):
"""GP squared exponential kernel.
This function is based on the 2018 GP-MPC library by Helge-André Langåker
Args:
x (np.array or casadi.MX/SX): First vector.
z (np.array or casadi.MX/SX): Second vector.
... | 5,356,470 |
def make_devid(identity):
"""
Generate device ID from device identity data trying to follow the same
logic as devauth does. Returns a string containing device ID.
"""
d = SHA256.new()
# convert to binary as needed
bid = identity if type(identity) is bytes else identity.encode()
d.update(... | 5,356,471 |
def _save(maximum_distance):
"""
Save the maximum distance to the file.
:param maximum_distance: Maximum distance to save.
:return: Maximum distance saved.
"""
log.info(f'Saving maximum distance: [{maximum_distance}]')
with open(FILE_NAME_MAXIMUM_DISTANCE, 'w') as file:
file.write(st... | 5,356,472 |
def get_recomm_products(user_id: str) -> List[Text]:
"""
Gets the top 10 products the user is most likely to purchase.
:returns: List of product ids.
"""
instances_packet = {
"instances": [user_id]
}
prediction = aiplatform_recomm_endpoint.predict(instances=instances_packet)
return prediction[0][... | 5,356,473 |
def test_generate_f_file(monkeypatch, mock_broker_config_paths):
"""A CSV with fields in the right order should be written to the file
system"""
fileF_mock = Mock()
monkeypatch.setattr(jobQueue, 'fileF', fileF_mock)
fileF_mock.generateFRows.return_value = [
dict(key4='a', key11='b'), dict(ke... | 5,356,474 |
def relu(Z):
"""
:param Z: -- the linear output in this layer
:return:
A -- the activation output in this layer
activation_cache -- a dictionary contains Z and A
"""
[m, n] = Z.shape
A = np.zeros((m,n))
for i in range(m):
for j in range(n):
if Z[i][j]... | 5,356,475 |
async def shutdown_tasks(app: 'Application') -> 'None':
"""Shutdown unfinished async tasks.
:param app: web server application
"""
log.info('Shutdown tasks')
tasks = asyncio.Task.all_tasks(loop=app.loop)
if tasks:
for task in tasks:
task.cancel()
try:
aw... | 5,356,476 |
def month(x: pd.Series) -> pd.Series:
"""
Month of each value in series
:param x: time series
:return: month of observations
**Usage**
Returns the month as a numeric value for each observation in the series:
:math:`Y_t = month(t)`
Month of the time or date is the integer month numbe... | 5,356,477 |
def test_passwd_lib_file(topology):
"""
Ensure library file is located at '/usr/lib/'
Using bash shell from the switch
1. Open bash shell for OpenSwitch instance
2. Run command to verify a shared object exists in the filesystem
```bash
stat --printf="%U %G %A\n" /usr/lib/libpasswd_srv.so.0.... | 5,356,478 |
def example_metrics_postprocessor_fn(
samples: typing.List[metrics_pb2.MetricFamily]
) -> None:
"""
An example metrics postprocessor function for MetricsCollector
A metrics postprocessor function can mutate samples before they are sent out
to the metricsd cloud service. The purpose of this is usual... | 5,356,479 |
def _library_from_nglims(gi, sample_info, config):
"""Retrieve upload library from nglims specified user libraries.
"""
names = [config.get(x, "").strip() for x in ["lab_association", "researcher"]
if config.get(x)]
check_names = set([x.lower() for x in names])
for libname, role in conf... | 5,356,480 |
async def test_deploy(ops_test: OpsTest, charm: str, series: str):
"""Deploy the charm-under-test.
Assert on the unit status before any relations/configurations take place.
"""
# Set a composite application name in order to test in more than one series at the same time.
application_name = f"{APP_NA... | 5,356,481 |
def get_commandline_parser():
"""it parses commandline arguments."""
parser = argparse.ArgumentParser(description='Toolpath generator.')
parser.add_argument('--stl-filepath', help='filpath of stl file.')
parser.add_argument('--diameter', help='Diameter of toolbit.')
parser.add_argument('--step-size'... | 5,356,482 |
def repack_folder(sourcedir, dst):
"""Pack sourcedir into dst .zip archive"""
if '7z' in UTIL_EXE:
# a: Add files to archive
# -tzip: "zip" Type archive
# -mx9: compression Method x9 (max)
args = [UTIL_EXE.get('7z', None)]
if args[0] is None:
return
ar... | 5,356,483 |
def con_isogonal(cos0,assign=False,**kwargs):
"""
keep tangent crossing angle
X += [lt1,lt2, ut1,ut2, cos]
(ue1-ue3) = lt1 * ut1, ut1**2 = 1
(ue2-ue4) = lt2 * ut2, ut2**2 = 1
ut1 * ut2 = cos
if assign:
cos == cos0
"""
w = kwargs.get('isogonal')
mesh = kwargs.get('mesh')... | 5,356,484 |
def download_is_complete(date):
"""
Has the process of downloading prescribing data for this date finished
successfully?
"""
return os.path.exists(local_storage_prefix_for_date(date) + SENTINEL_SUFFIX) | 5,356,485 |
def tf_apply_with_probability(p, fn, x):
"""Apply function `fn` to input `x` randomly `p` percent of the time."""
return tf.cond(
tf.less(tf.random_uniform([], minval=0, maxval=1, dtype=tf.float32), p),
lambda: fn(x),
lambda: x) | 5,356,486 |
def train_and_eval():
"""Train and evaluate the model."""
m = build_estimator(model_dir)
# set num_epochs to None to get infinite stream of data.
m.train(
input_fn=input_fn(train_file_name, num_epochs=1, num_threads=1, shuffle=True),
steps=2000)
# set steps to None to run evaluation... | 5,356,487 |
def test_probabilities_gridworld(size=5):
"""
Check transition-probabilities for GridWorld
Args:
size: The size of the world to be used for testing.
"""
check_zero_probabilities(gridworld.GridWorld(size)) | 5,356,488 |
def adjoin(x,seq,test=lambda x,y: x is y):
"""Tests whether item is the same as an existing element of list. If the
item is not an existing element, adjoin adds it to list (as if by cons) and
returns the resulting list; otherwise, nothing is added and the original
list is returned. """
retur... | 5,356,489 |
def list_users(ctx):
"""List all users"""
iam = boto3.client('iam', aws_access_key_id=ctx.obj['access_key'],
aws_secret_access_key=ctx.obj['secret_key'])
now = datetime.datetime.now(datetime.timezone.utc)
print("{0:20}|{1:15}|{2:10}|{3}".format("Name", "Age", "Groups", "Keys"))
... | 5,356,490 |
def get_service_logs(
project_id: str = PROJECT_ID_PARAM,
service_id: str = SERVICE_ID_PARAM,
lines: Optional[int] = Query(None, description="Only show the last n lines."),
since: Optional[datetime] = Query(
None, description="Only show the logs generated after a given date."
),
componen... | 5,356,491 |
def alloc_emergency_exception_buf():
"""stub method.""" | 5,356,492 |
def uniquify_contacts(contacts):
"""
Return a sequence of contacts with all duplicates removed.
If any duplicate names are found without matching numbers, an exception is raised.
"""
ctd = {}
for ct in contacts:
stored_ct = ctd.setdefault(ct.name, ct)
if stored_ct.dmrid != ct.dm... | 5,356,493 |
def optimize_bank_transaction_list(bank_transactions):
"""Append related objects using select_related and prefetch_related"""
return bank_transactions.select_related('block') | 5,356,494 |
def store_client(rc):
"""Context manager for file storage
Parameters
----------
rc : RunControl
Yields
-------
client : StorageClient
The StorageClient instance
"""
store = find_store(rc)
path = storage_path(store, rc)
sync(store, path)
yield StorageClient(r... | 5,356,495 |
def rss():
""" RSS2 Support.
support xml for RSSItem with 12 diaries.
Args:
none
Return:
diaries_object: list
site_settings: title, link, description
"""
articles = Diary.objects.order_by('-publish_time')[:12]
items = []
for article in articles:
cont... | 5,356,496 |
def _interpolate_solution_at(target_time, solver_state, validate_args=False):
"""Computes the solution at `target_time` using 4th order interpolation.
Args:
target_time: Floating `Tensor` specifying the time at which to obtain the
solution. Must be within the interval of the last time step of the
`... | 5,356,497 |
def test_drawcities():
"""Draw Cities"""
mp = MapPlot(
title="Fill and Draw Cities",
subtitle="This is my subtitle",
continentalcolor="blue",
sector="iowa",
nocaption=True,
)
mp.drawcities()
return mp.fig | 5,356,498 |
def from_hi(psi_0, mpa_type, system_index, hi, tau=0.01, state_compression_kwargs=None,
op_compression_kwargs=None, second_order_trotter=False, t0=0, psi_0_compression_kwargs=None,
track_trace=False):
"""
Factory function for imaginary time TMP-objects (ITMPS, ITMPO, ITPMPS)
:par... | 5,356,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.