content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main():
"""
lcd = SmartOpen_LCD()
lcd.set_blacklight(150)
color = lcd.color_table['white']
lcd.fill_screen(color)
print("done")
"""
lcd = SmartOpen_LCD()
lcd.set_blacklight(150)
color = random.choice(list(lcd.color_table.keys()))
lcd.fill_screen(color)
width = 240... | 900 |
def profileown():
"""Display user's profile"""
return render_template("profile.html", user=session, person=session, books=None) | 901 |
def GetChildConfigListMetadata(child_configs, config_status_map):
"""Creates a list for the child configs metadata.
This creates a list of child config dictionaries from the given child
configs, optionally adding the final status if the success map is
specified.
Args:
child_configs: The list of child co... | 902 |
def get_samples(df, selected_rows, no_of_samples, records_in_db):
""" get samples without shuffling columns """
df_fixed = None
df_random = None
generic_data_dict = []
#drop rows with 'ignore' set to 'yes'
if 'ignore' in df.columns:
df = df[df["ignore"] != "yes"]
df = df.drop(['i... | 903 |
def update_member_names(oldasndict, pydr_input):
"""
Update names in a member dictionary.
Given an association dictionary with rootnames and a list of full
file names, it will update the names in the member dictionary to
contain '_*' extension. For example a rootname of 'u9600201m' will
be repl... | 904 |
def assert_type(assertions: list):
"""
use this function to do type checking on runtime
- pass an array of assertions
[(var_1, type_1), (var_2, type_2), ...]
e.g.: [(arg1, int), (arg2, str), ....]
- nesting e.g.: list[int] is not possible. Instead do (list_arg[0], int)
"""
for i in r... | 905 |
def part1(entries: str) -> int:
"""part1 solver take a str and return an int"""
houses = {(0, 0): 1}
pos_x, pos_y = 0, 0
for direction in entries:
delta_x, delta_y = moves[direction]
pos_x += delta_x
pos_y += delta_y
houses[(pos_x, pos_y)] = houses.get((pos_x, pos_y), 0) ... | 906 |
def delete_news_publisher(app_user, service_user, solution):
"""Delete a news publisher and revoke create news role."""
from solutions.common.bizz.messaging import POKE_TAG_BROADCAST_CREATE_NEWS
key = SolutionNewsPublisher.createKey(app_user, service_user, solution)
publisher = db.get(key)
if publis... | 907 |
def init_questionnaire_db_command():
"""Create CLI for creating a new database with `flask init-db`.
**Careful: This will overwite the current one and all data will
be lost.**
"""
init_questionnaire_db()
click.echo('Initialized the questionnaire database') | 908 |
def beqs(
screen, asof=None, typ='PRIVATE', group='General', **kwargs
) -> pd.DataFrame:
"""
Bloomberg equity screening
Args:
screen: screen name
asof: as of date
typ: GLOBAL/B (Bloomberg) or PRIVATE/C (Custom, default)
group: group name if screen is organized into g... | 909 |
def quantile_compute(x, n_bins):
"""Quantile computation.
Parameters
----------
x: pd.DataFrame
the data variable we want to obtain its distribution.
n_bins: int
the number of bins we want to use to plot the distribution.
Returns
-------
quantiles: np.ndarray
th... | 910 |
def remove_conflicting_jars(source_path):
""" Removes jars uploaded which may conflict with AppScale jars.
Args:
source_path: A string specifying the location of the source code.
"""
lib_dir = os.path.join(find_web_inf(source_path), 'lib')
if not os.path.isdir(lib_dir):
logger.warn('Java source does ... | 911 |
def print_newline():
"""
Add new line
"""
print "" | 912 |
def remove_separators(version):
"""Remove separator characters ('.', '_', and '-') from a version.
A version like 1.2.3 may be displayed as 1_2_3 in the URL.
Make sure 1.2.3, 1-2-3, 1_2_3, and 123 are considered equal.
Unfortunately, this also means that 1.23 and 12.3 are equal.
Args:
vers... | 913 |
def parse_coverage_status(status):
"""Parse a coverage status"""
return Status.HIT if status.upper() == 'SATISFIED' else Status.MISSED | 914 |
def max_index(list):
"""Returns the index of the max value of list."""
split_list = zip(list, range(len(list)))
(retval, retI) = reduce(lambda (currV, currI), (nV, nI):
(currV, currI) if currV > nV
else (nV, nI), split_list)
return retI | 915 |
def mask_coverage(coverage: mx.sym.Symbol, source_length: mx.sym.Symbol) -> mx.sym.Symbol:
"""
Masks all coverage scores that are outside the actual sequence.
:param coverage: Input coverage vector. Shape: (batch_size, seq_len, coverage_num_hidden).
:param source_length: Source length. Shape: (batch_si... | 916 |
def DFS_complete(g):
"""Perform DFS for entire graph and return forest as a dictionary.
Result maps each vertex v to the edge that was used to discover it.
(Vertices that are roots of a DFS tree are mapped to None.)
"""
forest = {}
for u in g.vertices():
if u not in forest:
forest[u] = None ... | 917 |
def _transform_p_dict(p_value_dict):
"""
Utility function that transforms a dictionary of dicts into a dataframe representing the dicts as rows
(like tuples). Is needed to keep track of the feature names and corresponding values.
The underlying datastructures are confusing.
:param p_value_dict: dic... | 918 |
def iou(
predict: torch.Tensor,
target: torch.Tensor,
mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
"""
This is a great loss because it emphasizes on the active
regions of the predict and targets
"""
dims = tuple(range(predict.dim())[1:])
if mask is not None:
predic... | 919 |
def get_sequence(seq_id):
"""
TO DO:
1. redirection 303. (not tested in compliance_suite)
2. Note: compliance_suite ignores the range if it is out of bounds or if > SUBSEQUENCE_LIMIT
3. Ambiguous error code resolution in refget documentation:
range:
The server MUST respond with ... | 920 |
def getCondVisibility(condition):
"""
Returns ``True`` (``1``) or ``False`` (``0``) as a ``bool``.
:param condition: string - condition to check.
List of Conditions: http://wiki.xbmc.org/?title=List_of_Boolean_Conditions
.. note:: You can combine two (or more) of the above settings by using "+" a... | 921 |
def write_jpeg(input: torch.Tensor, filename: str, quality: int = 75):
"""
Takes an input tensor in CHW layout and saves it in a JPEG file.
Arguments:
input (Tensor[channels, image_height, image_width]): int8 image tensor
of `c` channels, where `c` must be 1 or 3.
filename (str): Path to... | 922 |
def get_xy_strs(kpts):
""" strings debugging and output """
_xs, _ys = get_xys(kpts)
xy_strs = [('xy=(%.1f, %.1f)' % (x, y,)) for x, y, in zip(_xs, _ys)]
return xy_strs | 923 |
def mockTrainTextExport(poicol, resdir, city_idx=None):
""" export the training trails and testing instance for inspection
"""
conf = Configuration()
conf['expr.target'] = poicol
conf['expr.model'] = 'mockTrainTextExport'
if city_idx is None:
cityloop(conf, resdir, 'tt')
else:
... | 924 |
def history_cumulative(request):
"""
This endpoints returns the number of cumulative infections for each area given a date in history.
"""
days = int(request.query_params.get("days"))
observed = Covid19DataPoint.objects.all()
historyDate = max([d.date for d in observed]) - timedelta(days=-days)
... | 925 |
def check_partial(func, *args, **kwargs):
"""Create a partial to be used by goodtables."""
new_func = partial(func, *args, **kwargs)
new_func.check = func.check
return new_func | 926 |
def test_perform_search_with_configuration(
monkeypatch, patch_search_command, namespace_args, grim_config, trainer_config, search_overrides
):
"""Tests that SearchCommand objects correctly perform searches with the specified trainer configurations.
Ensures:
- The correct configuration file is writ... | 927 |
def compress_file(filename: str, dest_file: str = "") -> None:
"""
Open the <filename> and compress its contents on a new one.
:param filename: The path to the source file to compress.
:param dest_file: The name of the target file. If not provided (None),
a default will be used w... | 928 |
def mcas(mc, entries):
"""Multi-entry compare-and-set.
Synopsis:
>>> from memcache_collections import mcas
>>> mc = memcache.Client(['127.0.0.1:11211'], cache_cas=True)
>>> # initialize a doubly-linked list with two elements
>>> mc.set_multi({
... 'foo': {'next': 'bar'},
... 'bar': ... | 929 |
def figure_8s(N_cycles=2, duration=30, mag=0.75):
"""
Scenario: multiple figure-8s.
Parameters
----------
N_cycles : int
How many cycles of left+right braking.
duration : int [sec]
Seconds per half-cycle.
mag : float
Magnitude of braking applied.
"""
on = [(2... | 930 |
def validate(integrations: Dict[str, Integration], config: Config):
"""Validate CODEOWNERS."""
codeowners_path = config.root / "CODEOWNERS"
config.cache["codeowners"] = content = generate_and_validate(integrations)
with open(str(codeowners_path)) as fp:
if fp.read().strip() != content:
... | 931 |
def test_components(ctx):
"""Create textures of different components"""
c1 = ctx.texture((10, 10), components=1)
c2 = ctx.texture((10, 10), components=2)
c3 = ctx.texture((10, 10), components=3)
c4 = ctx.texture((10, 10), components=4)
assert c1.components == 1
assert c2.components == 2
... | 932 |
def run():
"""Run ipfs daemon.
cmd: ipfs daemon # --mount
__ https://stackoverflow.com/a/8375012/2402577
"""
IPFS_BIN = "/usr/local/bin/ipfs"
log("==> Running [green]IPFS[/green] daemon")
if not os.path.isfile(config.env.IPFS_LOG):
open(config.env.IPFS_LOG, "a").close()
with d... | 933 |
def grad_ast(func, wrt, motion, mode, preserve_result, verbose):
"""Perform AD on a single function and return the AST.
Args:
See `grad`.
Returns:
node: The AST of a module containing the adjoint and primal function
definitions.
required: A list of non-built in functions that this function c... | 934 |
def sortRules(ruleList):
"""Return sorted list of rules.
Rules should be in a tab-delimited format: 'rule\t\t[four letter negation tag]'
Sorts list of rules descending based on length of the rule,
splits each rule into components, converts pattern to regular expression,
and appends it to the e... | 935 |
def get_all_ngram_counts(sequences, n):
"""
UC Computes the prevalence of ngrams in a collection of sequences.
"""
pass | 936 |
def v3_settings_response():
"""Define a fixture that returns a V3 subscriptions response."""
return load_fixture("v3_settings_response.json") | 937 |
def supercelltar(tar, superdict, filemode=0o664, directmode=0o775, timestamp=None,
INCARrelax=INCARrelax, INCARNEB=INCARNEB, KPOINTS=KPOINTSgammaonly, basedir="",
statename='relax.', transitionname='neb.', IDformat='{:02d}',
JSONdict='tags.json', YAMLdef='supercell.yam... | 938 |
def Geom2dLProp_Curve2dTool_FirstParameter(*args):
"""
* returns the first parameter bound of the curve.
:param C:
:type C: Handle_Geom2d_Curve &
:rtype: float
"""
return _Geom2dLProp.Geom2dLProp_Curve2dTool_FirstParameter(*args) | 939 |
def test_get_cd0_oswald():
"""TODO: create the test when the function is finalized!"""
pass | 940 |
def decode_regression_batch_image(x_batch, y_batch, x_post_fn = None, y_post_fn = None, **kwargs):
"""
x_batch: L or gray (batch_size, height, width, 1)
y_batch: ab channel (batch_size, height, width, 2)
x_post_fn: decode function of x_batch
y_post_fn: decode function of y_batch
"""
a... | 941 |
def get_mag_from_obs(h, e, d0=0):
"""gets the magnetic north components given the observatory components.
Parameters
__________
h: array_like
the h component from the observatory
e: array_like
the e component from the observatory
d0: float
the declination baseline angle ... | 942 |
def get_local_host(choice='IP'):
"""
choice: 'IP' or 'NAME'
"""
if choice == 'IP':
cmd = 'hostname -i'
else:
cmd = 'hostname'
out = subprocess.check_output(cmd.split())
if choice == 'hostname':
return out.strip('\n')
else:
ip_tmp = out.strip(... | 943 |
def set_cell(client, instance, colid, value, file_=None):
"""Set the value of one cell of a family table.
Args:
client (obj):
creopyson Client.
instance (str):
Family Table instance name.
colid (str):
Column ID.
value (depends on data type):
... | 944 |
def find_bounds(particles):
"""
Find the maximum and minimum bounds describing a set of particles.
"""
min_bound = np.array(
[np.min(particles[:, 0]), np.min(particles[:, 1]), np.min(particles[:, 2])]
)
max_bound = np.array(
[np.max(particles[:, 0]), np.max(particles[:, 1]), np.... | 945 |
def load_job_queue(job_queue, list_of_workers, list_of_jobs):
"""Puts each player file (string) into the job_queue, then puts in 1 poison pill for each process"""
[job_queue.put(job) for job in list_of_jobs]
# noinspection PyUnusedLocal
[job_queue.put(None) for _dummy in list_of_workers] | 946 |
def get_tags_date(link, default_date=None):
"""Extract tags and date from the link."""
tags = ["links"]
date = ""
fltr = [
"Bookmarks Menu",
"Bookmark Bar",
"Personal Toolbar Folder",
"Importierte Lesezeichen",
"Bookmarks Toolbar",
"Kein Label vorhanden",
... | 947 |
def _is_future(time, time_ref=None):
"""
check if `time` is in future (w.r.t. `time_ref`, by default it is now)
Parameters
----------
time : int or datetime
the time to check (if int it's considered a
timestamp, see :py:meth:`datetime.timestamp`)
time_ref : int or datetime
... | 948 |
def test_init_descriptor_always_initted():
"""We should be able to get a height and width even on no-tty Terminals."""
t = Terminal(stream=StringIO())
eq_(type(t.height), int) | 949 |
def afs(debugger, command, context, result, _):
"""
Get the address for a symbol regardless of the ASLR offset
(lldb) afs viewDidLoad
-[UIViewController viewDidLoad]: 0x1146c79a4
...
(lldb) afs -[MyViewController viewDidLoad]:
0x1146c79a4
"""
# TODO: Allow user to pass module for s... | 950 |
def create_and_train_model(x_learn, y_learn, model, n_cores):
"""General method to create and train model"""
print(model.fit(x_learn, y_learn))
start_time = datetime.now()
c_val = cross_val_score(model, x_learn, y_learn, cv=10, n_jobs=n_cores)
end_time = datetime.now()
print(type(model).__name__... | 951 |
def cardidolizedimageurl(context, card, idolized, english_version=False):
"""
Returns an image URL for a card in the context of School Idol Contest
"""
prefix = 'english_' if english_version else ''
if card.is_special or card.is_promo:
idolized = True
if idolized:
if getattr(card... | 952 |
def extract_simple_tip(e):
"""
"""
emin = e.min()
emax = e.max()
indices = [nearest_index(emin), nearest_index(emax)]
indices.sort()
imin,imax = indices
imax +=1 # for python style indexing
return imin, imax | 953 |
def adjust_learning_rate_local(optimizer, epoch, lr0):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
# if lr0<=1e-4:
# if epoch < 90:
# lr = lr0 * (0.99**(epoch//30))
# elif epoch < 180:
# lr = lr0 * (0.9**(epoch//30))
... | 954 |
def convert(ctx, amount: float=1, from_currency=None, to_currency=None):
"""
Convert.
Convert between currencies. Defaults to geolocated currencies.
"""
_update_currencies(ctx.config.app_id, ctx.storage)
if amount is None:
amount = 1
if from_currency is None and to_currency is Non... | 955 |
def batch_generator(adjs, nbrs, nnlbls, atts, labels, N_map, E_map, Y_map, V_num=28, bsize=32, dim_f=0, dim_a=0, dim_e=0, nY=2, k=3, pk=10):
"""graph is processed(add padding) as needed"""
epch = 0
N = len(labels)
while True:
order = np.random.permutation(N)
for i in range(0, N-bsize, bs... | 956 |
def moveresize(win, x=None, y=None, w=None, h=None, window_manager=None):
"""
This function attempts to properly move/resize a window, accounting for
its decorations.
It doesn't rely upon _NET_FRAME_EXTENTS, but instead, uses the actual
parent window to adjust the width and height. (I've found _NET... | 957 |
def parse_pipeline_config(pipeline_config_file):
"""Returns pipeline config and meta architecture name."""
with tf.gfile.GFile(pipeline_config_file, 'r') as config_file:
config_str = config_file.read()
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
text_format.Merge(config_str, pipeline_config)
... | 958 |
def get_pwl(time_series, pwl_epsilon):
""" This is a wrapper function for getting a bounded piecewise linear approximation of the data """
if not isinstance(pwl_epsilon, (int, float)):
raise TypeError("pwl_epsilon must be a numeric type!")
if not (isinstance(time_series, pd.DataFrame) or isinstanc... | 959 |
def to_array(string):
"""Converts a string to an array relative to its spaces.
Args:
string (str): The string to convert into array
Returns:
str: New array
"""
try:
new_array = string.split(" ") # Convert the string into array
while "" in new_array: # Check if th... | 960 |
def convert_atoms_to_pdb_molecules(atoms: t.List[Atom]) -> t.List[str]:
"""
This function converts the atom list into pdb blocks.
Parameters
----------
atoms : t.List[Atom]
List of atoms
Returns
-------
t.List[str]
pdb strings of that molecule
"""
... | 961 |
def unvoiced_features(sig,fs,vcont,sil_cont):
"""
Unvoiced segment features.
Requires voiced and silence/pauses segment detection.
"""
#Unvoiced features
uv_seg,_,_ = unvoiced_seg(sig,fs,vcont,sil_cont)
lunvoiced = []
for uv in uv_seg:
lunvoiced.append(len(uv)/fs)#Length of ... | 962 |
def test_markerfacecolors_allclose(axis):
"""Are the markerfacecolors almost correct?"""
err = 1e-12
markerfacecolor = np.array([0.1, 1, 1])
axis.plot([1, 2.17, 3.3, 4], [2.5, 3.25, 4.4, 5], markerfacecolor=list(markerfacecolor + err))
pc = LinePlotChecker(axis)
with pytest.raises(AssertionErro... | 963 |
def civic_methods(method001, method002, method003):
"""Create test fixture for methods."""
return [method001, method002, method003] | 964 |
def _generate_tags(encoding_type, number_labels=4):
"""
:param encoding_type: 例如BIOES, BMES, BIO等
:param number_labels: 多少个label,大于1
:return:
"""
vocab = {}
for i in range(number_labels):
label = str(i)
for tag in encoding_type:
if tag == 'O':
if ... | 965 |
def test_delete_topic(host):
"""
Check if can delete topic
"""
# Given
topic_name = get_topic_name()
ensure_topic(
host,
topic_defaut_configuration,
topic_name
)
time.sleep(0.3)
# When
test_topic_configuration = topic_defaut_configuration.copy()
test_t... | 966 |
def interrupts():
"""
En - Re-enables interrupts [after they've been disabled by noInterrupts()]
Fr - Revalide les interruptions [après qu'elles aient été désactivées par noInterrupts()]
"""
fichier=open(SWIRQ_PATH,'r')
irqnum=0x0
ret=ioctl(fichier,SWIRQ_ENABLE,struct.pack("@B",irqnum))
irqnum=0x1
ret=i... | 967 |
def delete_link_tag(api_client, link_id, tag_key, **kwargs): # noqa: E501
"""delete_link_tag # noqa: E501
Delete link tag by key
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> response = await api.delete_link_tag(clie... | 968 |
def test_sortie(mission):
"""
:type mission: MissionReport
"""
data = {
'aircraft_id': 10011,
'bot_id': 10012,
'pos': {'x': 7500.0, 'y': 0.0, 'z': 7500.0},
'account_id': '76638c27-16d7-4ee2-95be-d326a9c499b7',
'profile_id': '8d8a0ac5-095d-41ea-93b5-09599a5fde4c',
... | 969 |
def test_user_details(user, mocker):
"""
Test for:
User.biography property
User.media_count property
User.follower_count property
User.following_count property
User.user_detail method
User.full_info method
"""
user_details = {
"biography": random_string(),
"media_... | 970 |
def infect_graph(g, title):
"""
Function to infect the graph using SI model.
Parameters:
g: Graph
Returns:
G : Infected graph
t : Time of diffusion of each node
"""
G=g
# Model selection - diffusion time
model = ep.SIModel(G)
nos = 1/len(G)
# Model Configuration
config = mc.Configurat... | 971 |
def main_func_SHORT():
""" Func. called by the main T """
sleep(SHORT)
return True | 972 |
def RedirectStdoutStderr(filename):
"""Context manager that replaces stdout and stderr streams."""
if filename is None:
yield
return
with open(filename, 'a') as stream:
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = stream
sys.stderr = stream
util.CheckStdoutForColorSupp... | 973 |
def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \
-> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]:
"""
Randomly split given sample to a training- and testing sample
Parameters
----------
X : DataFrame of shape (n_samples, n_features)
Dat... | 974 |
def split_a_book(file_name, outfilename=None):
"""Split a file into separate sheets
:param str file_name: an accessible file name
:param str outfilename: save the sheets with file suffix
"""
book = get_book(file_name=file_name)
if outfilename:
saveas = outfilename
else:
save... | 975 |
def s2sdd(s):
""" Converts a 4-port single-ended S-parameter matrix
to a 2-port differential mode representation.
Reference: https://www.aesa-cortaillod.com/fileadmin/documents/knowledge/AN_150421_E_Single_ended_S_Parameters.pdf
"""
sdd = np.zeros((2, 2), dtype=np.complex128)
sdd[0, 0] = 0.5*(s... | 976 |
def plot_gdf(gdf, map_f=None, maxitems=-1, style_func_args={}, popup_features=[],
tiles='cartodbpositron', zoom=6, geom_col='geometry', control_scale=True):
"""
:param gdf: GeoDataFrame
GeoDataFrame to visualize.
:param map_f: folium.Map
`folium.Map` object where the GeoDataFram... | 977 |
def set_catflap_cat_inside(request, catflap_uuid):
"""GET so it can be used as an email link."""
catflap = CatFlap.objects.get(uuid=catflap_uuid)
if not catflap.cat_inside:
catflap.cat_inside = True
catflap.save()
track_manual_intervention(catflap, cat_inside=True)
return redire... | 978 |
def feature_list():
"""Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc
Returns
-------
list
List of :class:`.Feature` objects
"""
lib_features_c_array = ctypes.POINTER(Feature)()
lib_features_size = ctypes.c_size_t()
c... | 979 |
def _symm_herm(C):
"""To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_jilk*"""
nans = np.isnan(C)
C[nans] = np.einsum('jilk', C)[nans].conj()
return C | 980 |
def cat(self, dim=0):
"""Map of 'cat' pytorch method."""
x = self
dim = _dim_explicit(x[0].shape, dim)
return P.concat(x, dim) | 981 |
def survey(nara_file=None):
"""
Generate a summary of the data structure.
:param nara_file:
:return:
"""
if not nara_file:
nara_file = os.path.abspath(
os.path.join(os.path.dirname(__file__), "nara-export-latest.json")
)
with open(nara_file, "r") as f:
na... | 982 |
def test_ticker_gains_negative_balance(transactions, exchange_rates_mock):
"""If the first transaction added is a sell, it is illegal since
this causes a negative balance, which is impossible"""
sell_transaction = transactions[2]
tg = TickerGains(sell_transaction.ticker)
er = ExchangeRate('USD'... | 983 |
def test_usage():
"""usage"""
rv, out = getstatusoutput(prg)
assert rv > 0
assert out.lower().startswith('usage') | 984 |
def _name_xform(o):
"""transform names to lowercase, without symbols (except underscore)
Any chars other than alphanumeric are converted to an underscore
"""
return re.sub("\W", "_", o.lower()) | 985 |
def runner(app):
"""创建一个运行器,用于调用应用注册的 Click 命令"""
return app.test_cli_runner() | 986 |
def remove_all_objects(scene):
""" Given a planning scene, remove all known objects. """
for name in scene.get_known_object_names():
scene.remove_world_object(name) | 987 |
def create_activation_cache(model):
"""Creates an activation cache for the tensors of a model."""
input_quantizer = quantized_relu(8, 0)
output_cache = {}
# If using a Sequential model, the input layer is hidden. Therefore, add the
# input quantization to the cache if the first layer is not an input layer
... | 988 |
def feature_scatterplot(fset_path, features_to_plot):
"""Create scatter plot of feature set.
Parameters
----------
fset_path : str
Path to feature set to be plotted.
features_to_plot : list of str
List of feature names to be plotted.
Returns
-------
(str, str)
R... | 989 |
def model1(v, va, vb, ka, Wa, Wb, pa):
"""
A translation of the equation from Sandström's Dynamic NMR Spectroscopy,
p. 14, for the uncoupled 2-site exchange simulation.
v: frequency whose amplitude is to be calculated
va, vb: frequencies of a and b singlets (slow exchange limit) (va > vb)
ka: ra... | 990 |
def calculate_laminar_flame_speed(
initial_temperature,
initial_pressure,
species_dict,
mechanism,
phase_specification="",
unit_registry=_U
):
"""
This function uses cantera to calculate the laminar flame speed of a given
gas mixture.
Parameters
-----... | 991 |
def random_seed(seed):
"""Execute code inside this with-block using the specified random seed.
Sets the seed for random, numpy.random and torch (CPU).
WARNING: torch GPU seeds are NOT set!
Does not affect the state of random number generators outside this block.
Not thread-safe.
Args:
... | 992 |
def extrapolate_coverage(lines_w_status):
"""
Given the following input:
>>> lines_w_status = [
(1, True),
(4, True),
(7, False),
(9, False),
]
Return expanded lines with their extrapolated line status.
>>> extrapolate_coverage(lines_w_status) == [
(1, ... | 993 |
def get_image_features(filename):
"""
Param:
Path to image
Returns:
Desired features of image in the form of a dictionary (key = feature_name, value = feature_value)
"""
array, metadata = nrrd.read(filename)
return {k: f(array, metadata, filename) for k, f in image_feature_functi... | 994 |
def get_DCT_transform_matrix(N):
"""
Return the normalised N-by-N discrete cosine transform (DCT) matrix.
Applying the returned transform matrix to a vector x: D.dot(x) yields the
DCT of x. Applying the returned transform matrix to a matrix A: D.dot(A)
applies the DCT to the columns of A. Taking D.... | 995 |
def get_reduce_nodes(name, nodes):
"""
Get nodes that combine the reduction variable with a sentinel variable.
Recognizes the first node that combines the reduction variable with another
variable.
"""
reduce_nodes = None
for i, stmt in enumerate(nodes):
lhs = stmt.target.name
... | 996 |
def extract_mesh_descriptor_id(descriptor_id_str: str) -> int:
""" Converts descriptor ID strings (e.g. 'D000016') into a number ID (e.g. 16). """
if len(descriptor_id_str) == 0:
raise Exception("Empty descriptor ID")
if descriptor_id_str[0] != "D":
raise Exception("Expected descriptor ID to... | 997 |
def process_sources(sources_list):
"""
This function processes the sources result
:param sources_list: A list of dictionaries
:return: A list of source objects
"""
sources_results = []
for sources_item in sources_list:
id = sources_item.get('id')
name = sources_item.get('name... | 998 |
def encrypt(message_text, key):
"""Method Defined for ENCRYPTION of a Simple \
String message into a Cipher Text Using \
2x2 Hill Cipher Technique
\nPARAMETERS\n
message_text: string to be encrypted
key: string key for encryption with length <= 4
\nRETURNS\n
cipher_text: encrypted Mess... | 999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.