content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def write_solutions(config,
input_images, bounding_boxes, image_shapes, gt_boxes=None,
gt_cls=None, anchors=None, reg_deltas=None,
cls=None, train_cls=None,
output_filepath_format=OUTPUT_FILEPATH_FORMAT,
verbose=True,
... | 58,700 |
def check_processed_data(df,col_list,na_action):
""" Checks if provided dataframe consists of required columns and no missing values
"""
check_passed = True
# Check columns
df_cols = df.columns
if set(df_cols) != set(col_list):
check_passed = False
print('Column names mismatched... | 58,701 |
def eventGenerator():
"""
event generator continuing
does not work with simple server
"""
while (True):
while Events:
event = Events.pull()
console.terse("Streamed Event {}\n\n".format(event))
yield bytes("{}\n".format(event), "ascii")
time.sle... | 58,702 |
def bezier_terms(n, t):
""" Bezier curve.
Return n+1 terms in list ()
"""
m_terms = list()
m_C = binomial_term
for i in range(n):
m_terms.append( m_C(n, i) * (1 - t)**(n - i) * t**i )
m_terms.append(t ** n)
return m_terms | 58,703 |
def execute_command(command):
"""Executes a command, capturing the output"""
output = subprocess.run(command, capture_output=True, encoding='utf-8')
if len(output.stderr) > 0:
print(output.stderr)
output.check_returncode()
return output | 58,704 |
def feed_conversation(samples, limit=5, threshold=.85):
"""helper function to feed result of classifier to Conversation module."""
try:
iter(samples)
assert not any(not isinstance(sub, tuple) for sub in samples)
except (AssertionError, TypeError) as e:
raise TypeError('samples must b... | 58,705 |
def run_test_go_stop(robot):
"""
Tests the go and stop methods of the DriveSystem class.
"""
print('--------------------------------------------------')
print('Testing the go and stop methods of a robot')
print('--------------------------------------------------')
# ------------... | 58,706 |
def _mount_config_map_op(config_map_name: str) -> OpFunc:
"""Mounts all key-value pairs found in the named Kubernetes ConfigMap.
All key-value pairs in the ConfigMap are mounted as environment variables.
Args:
config_map_name: The name of the ConfigMap resource.
Returns:
An OpFunc for mounti... | 58,707 |
def make_tree(file_name):
"""Loads reStructuredText, outputs an lxml tree"""
rst = resource_string(__name__, file_name)
xml = rst2xml(rst)
return etree.fromstring(xml) | 58,708 |
def save_comments(name, token, nfrom = 0, toappend=[]):
"""
Args:
Takes a pagename, an API token, (optionally: an integer specifying
which # post to begin from, and a list to append comments to)
Out:
a list containing:
a list of of the comments it has iterated over,... | 58,709 |
def test_operator_leakage_sparse():
"""
Test to ensure that Operator creation does not cause memory leaks for
SparseTimeFunctions.
"""
grid = Grid(shape=(5, 6))
a = Function(name='a', grid=grid)
s = SparseTimeFunction(name='s', grid=grid, npoint=1, nt=1)
w_a = weakref.ref(a)
w_s = we... | 58,710 |
def point_inside_volume(p, ab1, ab2, eps = 0.01):
"""
Check if point p is inside the aabb volume
"""
ab1 = ab1.copy() - eps
ab2 = ab2.copy() + eps
if ab1[0] <= p[0] <= ab2[0] and \
ab1[1] <= p[1] <= ab2[1] and \
ab1[2] <= p[2] <= ab2[2]:
return True
else:
retu... | 58,711 |
def check(session):
"""Ensure that get-pip.py for various Python versions, works on that version."""
# Find the appropriate get-pip.py file
public = Path("public")
locations = [
public / session.python / "get-pip.py",
public / "get-pip.py",
]
for location in locations:
i... | 58,712 |
def audience_line_tap(attr, old, new):
"""
Controls the visibility of line saving and removing buttons / widgets depending
on user selection of audience lines. Updates :any:`audience_line_tap_dict`
if a line is selected (or not).
Triggered if user taps on a line in figure :any:`p`.
Parameters
... | 58,713 |
def context_manager(actor_start, actor_stop, join):
"""Позволяет использовать синтаксис `with` вместо синтаксиса `try/finally`."""
actor_start()
try:
yield
finally:
actor_stop()
join(timeout=0.3) | 58,714 |
def vgg_input_preprocess(image, max_dim=512, **kvargs):
""" apply appropriate VGG preprocessing to image, shape=(?,h,w,c)
should be same as `tf.keras.applications.vgg19.preprocess_input(rgb_data)/255.0`
NOTE:
- x_train from dataset will be dtype=tf.float32, domain=(0,1.) AFTER tf.image.convert_image_dtype(... | 58,715 |
def ldns_rr_set_type(*args):
"""LDNS buffer."""
return _ldns.ldns_rr_set_type(*args) | 58,716 |
def setup_environment(target):
"""Setup conda environment for target and install dependencies."""
if target.name not in conda_environments():
conda_create_env(target.name)
for dep in target.conda_dependencies:
conda_install(target.name, dep)
for dep in target.pip_dependencies... | 58,717 |
def spline_jacobian(coordinates, force_coordinates, fudge=1e-5):
"""
Make the Jacobian matrix for the 2D biharmonic spline.
Follows [Sandwell1987]_.
Each column of the Jacobian is the Green's function for a single force
evaluated on all observation points.
Parameters
----------
coordi... | 58,718 |
def update_nosy (db, cl, nodeid, new_values) :
""" On sign&send of a PR we update the nosy list with the nosy list
from the purchase_type
"""
nosy = set (new_values.get ('nosy', cl.get (nodeid, 'nosy')))
pt = new_values.get ('purchase_type', cl.get (nodeid, 'purchase_type'))
nosy.update (d... | 58,719 |
def removeNewImage(update):
"""
Remove the newly built image during abort sequence.
"""
_removeImage(update.new) | 58,720 |
def whip(innings_pitched: float, bb: int, h: int) -> float:
"""Calculate a baseball pitcher's WHIP.
WHIP = (BB + H) / IP
bb = Walks / Base on balls
h = hits
"""
WHIP = (bb + h) / innings(str(innings_pitched))
return round(float(WHIP), 2) | 58,721 |
def _determine_levels(index):
"""Determine the correct levels argument to groupby."""
if isinstance(index, (tuple, list)) and len(index) > 1:
return list(range(len(index)))
else:
return 0 | 58,722 |
def integerise(series):
"""
This duplicates functionality that exists in humanleague, rather than intorducing a package dependency solely for this function
"""
sumf = sum(series)
sumi = round(sumf)
# rescale series to nearest-integer sum
series = series * sumi / sumf
# get integer and fr... | 58,723 |
def tokenize_whitespace(lines):
"""
For each line, indentify current level of indendation and compare
against indentation of previous line. Insert BLK_OPEN or BLK_CLOSE
as appropriate.
"""
firstline = True
prevdent = 0
for lnum, line in enumerate(lines):
line = line.expandtabs... | 58,724 |
def update_cluster_host_deployed_config(
cluster_id, host_id, user=None, session=None, **kwargs
):
"""Update clusterhost deployed config by cluster id and host id."""
clusterhost = _get_cluster_host(
cluster_id, host_id, session=session
)
return _update_clusterhost_deployed_config(
c... | 58,725 |
def make_ppo_runner(env, policy, num_runner_steps, gamma=0.99, lambda_=0.95,
num_epochs=3, num_minibatches=4):
""" Returns env runner for PPO """
transforms = [GAE(policy, gamma=gamma, lambda_=lambda_, normalize=False)]
if not policy.is_recurrent() and getattr(env.unwrapped, "nenvs", Non... | 58,726 |
def left_window_coords(win_size, original_left_bound):
"""
Returns a `tuple` `(new_start, new_end)` left of original bound describing a window of length `win_size` (see
note).
Note: Converts any new value less than `1` to `1`.
:param win_size: size of window to the left.
:param original_left_b... | 58,727 |
def _get_forms_to_modify(domain, modified_forms, modified_cases, is_deletion):
"""Used on user.retire() and user.unretire()
Returns a list of IDs of forms which only modify the cases passed in and
which aren't already listed in `modified_forms`.
"""
form_ids_to_modify = set()
for case_id in mod... | 58,728 |
def build_post_required_integer_header_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Test explicitly required integer. Please put a header 'headerParameter' => null and the client
library should throw before the request is sent.
See https://aka.ms/azsdk/python/protocol/quickstar... | 58,729 |
def mask2rle(img: np.ndarray):
"""
img: numpy array, 1 - mask, 0 - background
Returns run length as string formated
"""
pixels = img.copy().flatten()
pixels = np.concatenate([[0], pixels, [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(... | 58,730 |
def make_mask(df: pd.DataFrame, image_name: str="img.jpg", shape: tuple=(256, 1600)):
"""
Create mask based on df, image name and shape.
"""
encoded_masks = df.loc[df["im_id"] == image_name, "EncodedPixels"]
masks = np.zeros((shape[0], shape[1], 4), dtype=np.float32)
for idx, label in enumerate... | 58,731 |
def setup_log():
"""配置日志"""
# 设置日志的记录等级
logging.basicConfig(level=PeiZhiLei.LOG_LEVEL) # 调试debug级
# 创建日志记录器,指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
# 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
formatter = loggi... | 58,732 |
def parse_filters(tokens: List[str]) -> Dict[str, str]:
"""Parses a filter description, like 'filter-for', 'refcounty', '42'."""
ret: Dict[str, str] = {}
filter_for = False
for index, value in enumerate(tokens):
if value == "filter-for":
filter_for = True
continue
... | 58,733 |
def format_val(v):
"""Takes in float and formats as str with 1 decimal place
:v: float
:returns: str
"""
return '{:.1f}%'.format(v) | 58,734 |
def _can_cast(type1, type2):
"""NOT_RPYTHON: operates on BaseType subclasses"""
return casting_table[type1.num][type2.num] | 58,735 |
def rmsf(temp_rmsf_array,ax=None,title="",plotrange=0,num_res=0,barcolor="blue",threshold=0,res_offset=0):
"""
description
Parameters
----------
rmsf_array : NumPy array or str filename of array.
either the array itself or a filename containing the array
ax : matplotlib ax
matplo... | 58,736 |
def concat(layers):
"""
Args:
layers (list(layer)): a list of layers
"""
return (
np.concatenate([l[0] for l in layers]),
np.concatenate([l[1] for l in layers])
) | 58,737 |
def array_to_bytes(arr: np.ndarray):
"""
Dumps a numpy array into a raw byte string.
:param arr: A numpy array.
:return: A `bytes` string.
"""
shape = arr.shape
ndim = arr.ndim
ret = struct.pack('i', ndim) + struct.pack('i' * ndim, *shape) + arr.tobytes(order='C')
return ret | 58,738 |
def set_checkpoint_status(checkpoint_name, status):
"""
Sets the status of a checkpoint in this test.
:param checkpoint_name: Name of checkpoint.
:param status: 'Passed' or 'Failed'
:return:
"""
# Colorize these outputs for easy readability.
COLOR = '\033[91m'
END_COLOR = '\033[0m'
... | 58,739 |
def count_parameters(model):
"""
number of model parameters to update
"""
return sum(p.numel() for p in model.parameters() if p.requires_grad) | 58,740 |
def train_model_with_test(model, optimizer, train_loader, test_loader, model_func, lr_scheduler, optim_cfg, start_epoch,
total_epochs, start_iter, rank, tb_log, ckpt_save_dir, train_sampler=None,
lr_warmup_scheduler=None, ckpt_save_interval=1, test_interval=1, max_ckp... | 58,741 |
def main():
"""
This function controls the flow of the script as well as ensuring
certain steps happen for benchmarking.
"""
# Paths
debruijn_path = "/Users/dreyceyalbin/Dropbox/Fall2020-classes/Algorithms/project/DebruijnExtend/"
python_path = debruijn_path + "DebruijnExtend_v3.py"
psip... | 58,742 |
def unwrap_vec_wrapper(env: Union["GymEnv", VecEnv], vec_wrapper_class: Type[VecEnvWrapper]) -> Optional[VecEnvWrapper]:
"""
Retrieve a ``VecEnvWrapper`` object by recursively searching.
:param env:
:param vec_wrapper_class:
:return:
"""
env_tmp = env
while isinstance(env_tmp, VecEnvWra... | 58,743 |
def parseLintignoreText(lintignoreText):
"""
*lintignoreText* should be the text of a 'lintignore' file. Return
the corresponding list of regexes to match against file paths.
"""
lintignoreLines = joinLists([parseLintignoreLine(x)
for x in lintignoreText.splitlines()... | 58,744 |
def statistics(uid):
"""Return url statistics
Arguments:
- `uid`: The hashed id of the url
"""
if not DB.exists(uid):
abort(404)
else:
entry = DB.get(uid)
entry = json.loads(entry)
short_link = uid
full_link = entry["url"]
clicks = entry["traffic... | 58,745 |
def ProfileMatrix(kmer_list, k, t, mode, pseudo_count=1): # nrow = t, ncol = k
"""Input a list of kmers and output a entropy score or profile probilities.
It can be switched to hamming distance score by setting mode.
"""
matrix = [[0] * k for i in range(4)] # Initiate a zero-filled nested list.
f... | 58,746 |
def you_to_yall(text: str) -> str:
"""Convert all you's to y'all."""
pattern = r'\b(y)(ou)\b'
return re.sub(pattern, r"\1'all", text, flags=re.IGNORECASE) | 58,747 |
def svn_client_list4(*args):
"""svn_client_list4(char const * path_or_url, svn_opt_revision_t peg_revision, svn_opt_revision_t revision, apr_array_header_t patterns, svn_depth_t depth, apr_uint32_t dirent_fields, svn_boolean_t fetch_locks, svn_boolean_t include_externals, svn_client_list_func2_t list_func, void * b... | 58,748 |
def SetGitTrace2ParentSid(env=None):
"""Set up GIT_TRACE2_PARENT_SID for git tracing."""
# We roughly follow the format git itself uses in trace2/tr2_sid.c.
# (1) Be unique (2) be valid filename (3) be fixed length.
#
# Since we always export this variable, we try to avoid more expensive calls.
# e.g. We do... | 58,749 |
def trivial_max_gcd_sum(arr_a: List[int], arr_b: List[int]) -> int:
"""Calculate max gcd sum.
Complexity: O(n^2).
"""
max_gcd = 0
max_sum = 0
for num_a in arr_a:
for num_b in arr_b:
cur_gdc = gcd(num_a, num_b)
if cur_gdc > max_gcd:
max_gcd = cur_g... | 58,750 |
def get_displays():
"""
Return the list of displays.
"""
# get dispays names
conns = ["xrandr", "--query"]
res = Popen(conns, stdout=PIPE).communicate()[0].decode(ENC)
regex = r"\n([^\s]*) (connected|disconnected).*"
names = [res[0] for res in re.findall(regex, res)]
# create display... | 58,751 |
def generate_subcommands(os_command, os_file, subcommands, extra_params,
suffix, title_suffix):
"""Convert os_command help subcommands for all subcommands to RST.
:param os_command: client command to document
:param os_file: open filehandle for output of RST file
:param subc... | 58,752 |
def tjur_r2(y_true, y_score):
"""
Tjur Pseudo R-squared
Parameters
----------
y_true : numpy array
True values (observed response).
y_score : numpy array
Predicted probabilities.
Returns
-------
t_r2 : float
Tjur Pseudo R-squared.
"""
y_mu1 = y_scor... | 58,753 |
def _create_table(conn, plant_name):
"""
Utility for creating table in DB based on fixed schema (based on sensor output).
Args:
conn (obj): database connection (sqlite)
plant_name (str): name of plant for writing to correct table
"""
cur = conn.cursor() # instantiate a cursor obj
... | 58,754 |
def get_full_std_lib(indent=0):
""" Get the code for the full PyScript standard library.
The given indent specifies how many sets of 4 spaces to prepend.
If the full stdlib is made available in JavaScript, multiple
snippets of code can be transpiled without inlined stdlib parts by
using ``py2js... | 58,755 |
def unit(aClass, value):
""" Calls the 'unit' method of 'aClass' with 'value'. """
return aClass.unit(value) | 58,756 |
def list_location_consortiums(location_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListLocationConsortiumsResult:
"""
Collection of the consortium payload.
:param str location_name: Location Name.
"""
__args__ = dict()
__ar... | 58,757 |
def typeshed_py_version(options: Options) -> Tuple[int, int]:
"""Return Python version used for checking whether module supports typeshed."""
# Typeshed no longer covers Python 3.x versions before 3.6, so 3.6 is
# the earliest we can support.
if options.python_version[0] >= 3:
return max(options... | 58,758 |
def pcr(adata, covariate, embed=None, n_comps=50, recompute_pca=True, verbose=False):
"""
PCR for Adata object
Checks whether to
+ compute PCA on embedding or expression data (set `embed` to name of embedding matrix e.g. `embed='X_emb'`)
+ use existing PCA (only if PCA entry exists)
... | 58,759 |
async def update_one(model: DeclarativeMeta, obj: BaseModel, pk_param: int, pk_attr: str = 'id'):
""" Update one """
query = update(model).where(pk_param == getattr(model, pk_attr)).values(obj.dict())
await database.execute(query)
return {**obj.dict(), pk_attr: pk_param} | 58,760 |
def recordDescribe(*args, **kwargs):
"""
.. deprecated:: 0.42.0
Use :func:`record_describe()` instead.
"""
print("dxpy.recordDescribe is deprecated; please use record_describe instead.", file=sys.stderr)
return record_describe(*args, **kwargs) | 58,761 |
def yellow_mask(original):
"""
Create a mask from the yellowish pixels of the frame, combining RGB mask and HSV mask
"""
hsv = yellow_mask_hsv(original)
rgb = yellow_mask_rgb(original)
mask = np.zeros_like(rgb)
mask[(hsv == 1) | (rgb == 1)] = 1
return mask | 58,762 |
def getClass():
"""
Takes in a JSON of the form {'_id' : String}
Returns all the information for a class including _id stringified
{'result' : None/JSON, 'success' : Boolean}
"""
if request.json is None or '_id' not in request.json:
abort(400)
if not dbworker.validateAccessList([... | 58,763 |
def isstrictlyascending(lam):
"""This determines whether the index string is a strictly ascending sequence
Parameters
----------
lam : an indexable object of things that are comparable. Usually an array of integers
Returns
-------
bool : true if the sequence is strictly ascending, else fal... | 58,764 |
def collections_endpoint(url):
""" Resource endpoint handler
:param url: the url that led here
.. versionchanged:: 0.0.7
Using 'utils.request_method' helper function now.
.. versionchanged:: 0.0.6
Support for HEAD requests
.. versionchanged:: 0.0.2
Support for DELETE resour... | 58,765 |
def create_action(parent, text, shortcut=None, icon=None, tip=None,
toggled=None, triggered=None, data=None, menurole=None,
context=Qt.WindowShortcut):
"""Create a QAction"""
action = QAction(text, parent)
if triggered is not None:
action.triggered.connect(t... | 58,766 |
def _validate_dialect(dialect: csv.Dialect) -> None:
"""
Validate csv dialect instance.
Raises
------
ValueError
If incorrect dialect is provided.
"""
for param in MANDATORY_DIALECT_ATTRS:
if not hasattr(dialect, param):
raise ValueError(f"Invalid dialect {dialec... | 58,767 |
def to_aws_tags(tags):
"""
When you assign tags to an AWS resource, you have to use the form
[{"key": "KEY1", "value": "VALUE1"},
{"key": "KEY2", "value": "VALUE2"},
...]
This function converts a Python-style dict() into these tags.
"""
return [
{"key": key, "valu... | 58,768 |
def add_reaction(message_id: int, emoji_name: str) -> None:
"""Add an emoji reaction to a message."""
request = {
"message_id": message_id,
"emoji_name": emoji_name,
}
response = client.add_reaction(request)
log_exit(response) | 58,769 |
def marcar_informe_twiteado():
"""Marca que el último informe descargado ya tiene su tweet asociado"""
basedatos.actualizar_valor("informe_no_twiteado", False) | 58,770 |
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
Arguments:
X -- input dataset, of shape (2, number of examples)
parameters -- python dictionary containing... | 58,771 |
def compose_postprocessing(postprocessing):
"""
Compose a postprocessing transform to be performed.
Params
------
postprocessing : dict
- dictionary defining all preprocessing steps to be taken with their
values
e.g. {"Name" : "RescaleIntensity"}
... | 58,772 |
def run_ksp(graph, cfg, k, thresh=10, algorithm=KSP.find_ksp):
"""
Build the shortest path trees and compute k diverse shortest paths
"""
# construct sp trees
_ = graph.sp_trees(**cfg)
# compute k shortest paths
ksp_processor = KSP(graph)
ksp_out = algorithm(ksp_processor, k, thresh=thre... | 58,773 |
def handler(event, context):
"""
api entry function
"""
output = process_api_request(event, put_schedule_tags, logger)
logger.info(output)
return output | 58,774 |
def count_pred_result(args, file_name, logit_id, class_num=41, max_seq_length=128):
"""
support two method to calc f1 sore, if dataset has two class, suggest using BF1,
else more than two class, suggest using MF1.
Args:
args: param of config.
file_name: label file name.
logit_id:... | 58,775 |
def check_for_winner(players) -> bool:
"""Checks all players for a single winner. Returns True if there is a winner.
Keyword arguments:
players -- list of player objects
"""
return sum(map(lambda x: not x.is_bankrupt(), players)) == 1 | 58,776 |
def infer(
context: click.Context,
modify_paths: Iterable[str],
print_only: bool,
full_only: bool,
recursive: bool,
in_place: bool,
json: bool,
annotate_from_existing_stubs: bool,
debug_infer: bool,
full_stubs: bool,
) -> int:
"""
Try adding type annotations to untyped co... | 58,777 |
def random(num_points, span):
"""
This function generates a set of random x and y coordinates using the
numpy uniform random number generator 'numpy.random.uniform()'.
Parameters
----------
num_points : int
The number of points to generate
span : World class
The w... | 58,778 |
def test_calculate_electrical_stress_factor(subcategory_id, type_id, voltage_ratio):
"""calculate_electrical_stress_factor() should return a float value on
success."""
_attributes = copy.deepcopy(ATTRIBUTES)
_attributes["subcategory_id"] = subcategory_id
_attributes["type_id"] = type_id
_attribu... | 58,779 |
def stream_t(text, result):
"""
Parse a bit of text and compare it to the expected token stream.
Each actual test function calls this.
"""
tkl = scanner.tokenize(text)
msg = print_token_list(tkl)
assert result is not None, \
msg + 'NO EXPECT LIST\n [\n' + ptl2(tkl) + ' ]\n'
... | 58,780 |
def get_game_player(game_state):
"""Get the game player whose turn it is to play."""
num_players = len(game_state.game_players)
for game_player in game_state.game_players:
if game_state.turn_number % num_players == game_player.turn_order:
return game_player
return None | 58,781 |
def details(location_slug: str):
"""View: Location Details"""
slug = slugify(location_slug)
if location_slug and location_slug != slug:
return redirect_url(url_for("locations.details", location_slug=slug))
database_connection = mysql.connector.connect(**current_app.config["database"])
locat... | 58,782 |
def get_widget_config(id_):
"""Get a widget
:param id: The ID of the widget
:type id: str
:rtype: Report
"""
widget_config = WidgetConfig.query.get(id_)
return widget_config.to_dict() | 58,783 |
def extract_info_attributes(round_datum):
"""Extract information attributes for current round using NLU annotations.
Args:
round_datum: Current round information
Returns:
get_attribute_matches: Information attributes
"""
user_annotation = ast.literal_eval(round_datum["transcript_an... | 58,784 |
def get_headers_pairs_list(filename, verbose=False):
"""
Read data for clustering from a given file.
Data format: <email_number> <header>.
Clusters are separated with a blank line.
:param filename: file with input data for clustering.
:param verbose: Whether to be verbose. Default - False.
... | 58,785 |
def maintainer_menu(request):
"""
View for maintainer menu page.
This page can only access by superuser and maintainer.
:param request: WSGI request from user.
:return: Render the maintainer menu page and pass the value from context to the template (maintainer.html)
"""
hero_image = 'img/m... | 58,786 |
def _get_platform_property_from_targets(platform, property, default):
"""
Load properties from targets.json file somewhere in the project structure
:param platform:
:return: property value, None if property not found
"""
for targets_path in _find_targets_json(os.getcwd()):
with suppress... | 58,787 |
def declaration_path(decl, with_defaults=True):
"""
returns a list of parent declarations names
:param decl: declaration for which declaration path should be calculated
:type decl: :class:`declaration_t`
:rtype: [names], where first item contains top parent name and last item
contains... | 58,788 |
def fit_largest_peak(xs, ys, num):
"""
Algorithm to "fit" the largest peak
:param xs: numpy array of floats, time series data
:param ys: numpy array of floats, power data
:param num: integer, number of peaks to fit
:return:
"""
sort = np.argsort(xs)
xs, ys = xs[sort], ys[sort]
#... | 58,789 |
def visualize_embeddings(embeddings, experiment_name='default'):
"""Save the embeddings to be visualised using t-sne on TensorBoard
Based on https://medium.com/@vegi/visualizing-higher-dimensional-data-using-t-sne-on-tensorboard-7dbf22682cf2
"""
tf_embeddings = tf.Variable(np.concatenate(embeddings... | 58,790 |
def reproduce_figure_three(g_test_res_csv_filepath="G_test_results.csv"):
"""
Reproduces Fig. 3 from the original paper.
:param g_test_res_csv_filepath: a filepath to a file with G-test results to use
:return: nothing
"""
print("\nReproducing Fig. 3")
print("=" * 18)
# Read the G-test o... | 58,791 |
def direction_neuron(layer,
direction,
x=None,
y=None,
batch=None):
"""Visualize a single (x, y) position along the given direction
Similar to the neuron objective, defaults to the center neuron.
InceptionV1 example:
>... | 58,792 |
def _run_jlab_string(talktorials_dst_dir):
"""
Print command for starting JupyterLab from workspace folder.
Parameters
----------
talktorials_dst_dir : str or pathlib.Path
Path to directory containing the talktorial folders.
"""
talktorials_dst_dir = Path(talktorials_dst_dir)
... | 58,793 |
def moment2d(grid):
"""
>>> moment2d([[5, 6, 7, 2, 4]])
[[0, 6, 14, 6, 16]]
"""
return list(map(moment, grid)) | 58,794 |
def update_data(new_data):
""" Write all quotes to data.json.
Try to open data file and dump new data to it.
Except if the file not found then let the user know that
file can't be found.
"""
try:
with open(filename, 'w') as data_json:
json.dump(new_data, data_json, indent=4... | 58,795 |
def colorManagementPrefs(*args, **kwargs):
"""
This command allows querying and editing the color management global data in a scene.
Returns: None
"""
pass | 58,796 |
def prepare_data_for_net(
vocabulary: dict,
samples: list,
labels_map: dict,
pos_map: dict,
dependencies_map: dict,
entity_length_distribution: typing.Tuple[float, float],
include_entities_nodes: bool=False,
include_entities_children: bool=False,
c... | 58,797 |
def get_onprem_cost_efficiency_handler(request):
""" Queries the OneSphere metrics API and returns the private cloud cost efficiency.
"""
# Get KMS secured environment variables
api_base = request.metadata.get('api_base', None)
token = request.metadata.get('token', None)
# Get service status
... | 58,798 |
def _setup_triangle_plot(parameters, kwargs):
"""Modify a dictionary of kwargs for bounded KDEs
Parameters
----------
parameters: list
list of parameters being plotted
kwargs: dict
kwargs to be passed to pesummary.gw.plots.publication.triangle_plot
or pesummary.gw.plots.publ... | 58,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.