content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mk_minus(ctx, x):
"""
mk_minus(Int_ctx ctx, Int_net x) -> Int_net
Parameters
----------
ctx: Int_ctx
x: Int_net
"""
return _api.mk_minus(ctx, x) | 71,000 |
def socket_enabled(pytestconfig):
"""Enable socket.socket for duration of this test function.
This incorporates changes from https://github.com/miketheman/pytest-socket/pull/76
and hardcodes allow_unix_socket to True because it's not passed on the command line.
"""
socket_was_disabled = socket.sock... | 71,001 |
def test_evaluate(model, expected_device):
"""Test that the discovered device looks like expected."""
url = "https://127.0.0.1/bar"
with requests_mock.Mocker() as mock:
mock.get(url, text=get_sample_content(
"{model}_upnp.xml".format(model=model)))
device = evaluate_scpd_xml(url)... | 71,002 |
def cred_secret_issue_proof(params, num_privs, num_pubs):
""" The proof that the mixed public / private credential issuing is correct """
G, _, _, _ = params
n = num_privs + num_pubs
# Contruct the proof
zk = ZKProof(G)
## The variables
bCx0 = zk.get(Gen, "bCx_0")
u, g, h, Cx0, pub = ... | 71,003 |
def test_get_next_queued_returns_first_pending() -> None:
"""It should return the first command that's pending."""
pending_command = create_pending_command()
running_command = create_running_command()
completed_command = create_completed_command()
subject = get_command_view(
is_running=True... | 71,004 |
def _is_unc_path(some_path) -> bool:
"""True if path starts with 2 backward (or forward, due to python path hacking) slashes."""
return (
len(some_path) > 1
and some_path[0] == some_path[1]
and some_path[0] in (os.sep, os.altsep)
) | 71,005 |
def create_h5_files(camels_root: PosixPath,
out_file: PosixPath,
basins: List,
dates: List,
with_basin_str: bool = True,
seq_length: int = 270):
"""[summary]
Parameters
----------
camels_root : Posix... | 71,006 |
def makePlane(w, l):
"""
4 points make a plane about the origin of size w, l
"""
return [mathutils.Vector(x) for x in [(-w/2, -l/2, 0), (-w/2, l/2, 0), (w/2, l/2, 0), (w/2, -l/2, 0)]] | 71,007 |
def calculate_gravity(a: Body3D, b: Body3D):
"""
Calculate the acceleration of body A due to the force of gravity applied by body B.
"""
def gravity(pos_a, pos_b):
if pos_a < pos_b:
return 1
elif pos_a > pos_b:
return -1
else:
return 0
retu... | 71,008 |
def _get_first_window(split_text):
"""Get first :const:`~gensim.parsing.keywords.WINDOW_SIZE` tokens from given `split_text`.
Parameters
----------
split_text : list of str
Splitted text.
Returns
-------
list of str
First :const:`~gensim.parsing.keywords.WINDOW_SIZE` tokens... | 71,009 |
def scope_access_level(app, uid, wid, scid):
"""Check the access level of the given player to the given world and
scope.
If the scope is global, the world creator has creator access, everybody
else is a visitor.
If the scope is personal, the owner has creator access. (This is actually
in the sco... | 71,010 |
def member_to_badge_proximity(fileobject, time_bins_size='1min', tz='US/Eastern'):
"""Creates a member-to-badge proximity DataFrame from a proximity data file.
Parameters
----------
fileobject : file or iterable list of str
The proximity data, as an iterable of JSON strings.
time_b... | 71,011 |
def get_producer_version():
"""
Internal helper function to return the producer version
"""
from .. import __producer_version__
return __producer_version__ | 71,012 |
def setup(bot: Bot) -> None:
"""Loads the botstats cog."""
bot.add_cog(BotStats(bot)) | 71,013 |
def consensus_tree() -> str:
"""Gets the consensus tree page.
:return: The consensus tree page.
"""
# Set the default options
if "analyoption" not in session:
session["analyoption"] = constants.DEFAULT_ANALYZE_OPTIONS
if "bctoption" not in session:
session["bctoption"] = constan... | 71,014 |
def fitgaussian(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution found by a fit"""
xx, yy, dx, dy, angle = fastfit.d4s(data)
# For some reason x and y are exchanged
params = [np.max(data), yy, xx, dy/4, dx/4, -angle, np.min(data)]
errorfunction = la... | 71,015 |
def plot_learning_curve(input_dict: dict, trial_log: np.ndarray, filename_png: str):
"""
Plot of game running average score and critic loss for environment.
Parameters:
input_dict: dictionary containing all execution details
trial_log: log of episode data of a single trial
filen... | 71,016 |
def mapped_state(state):
"""
Mapped a given state into the state as neural network input, insert trivial vehicles until vehs_num = 18
:param state: given state
:return: new state
"""
num_diff = 18 - len(state)
for i in range(num_diff):
state.append([0, 0, 0, 0, 0, 2])
return sta... | 71,017 |
def create_emb(e_name, emb):
"""
Embeddings are typically accessed with very large slices (or all of the embedding),
and do not benefit from overly aggressive compression due to their format. Given
this, we use:
* large tile size (1000)
* default compression level
"""
filters = tiledb.F... | 71,018 |
def load_wm_model_from_file(model, filepath):
""" Loads the data required for the usnx embed_model function
"""
MODEL_SUFFIX, HISTORY_SUFFIX, TRIGGER_SUFFIX = "MODEL", "HISTORY", "TRIGGER.npz"
if filepath is not None:
filepath = os.getcwd()[0:os.getcwd(
).rfind('WatermarkRobustness')] +... | 71,019 |
def uniform_non_negative_integers_with_sum(count, sum_):
"""Returns list of size `count` of integers >= 0, summing to `sum_`."""
positive = uniform_positive_integers_with_sum(count, sum_ + count)
return [i - 1 for i in positive] | 71,020 |
def crypt_key():
"""Check if the crypt key is complicated enough"""
logger.info("Validating crypt key")
crypt_key_check = stager.utils.password.Check(
stager.pages.encryption_input.CRYPT_KEY,
min_length=stager.utils.CONFIG.crypt_key_minimum_length,
mixed_case=stager.utils.CONFIG.cr... | 71,021 |
def test_websites_content_create_with_textid(drf_client, global_admin_user):
"""If a text_id is added when POSTing to the WebsiteContent, we should use that instead of creating a uuid"""
drf_client.force_login(global_admin_user)
website = WebsiteFactory.create()
payload = {
"type": "sitemetadata... | 71,022 |
def cms_create_display_profile() -> qc3const.PyCapsule:
"""Artificial functionality. The function emulates built-in display
profile reading profile resource attached to the package.
Returns a handle to lcms built-in display profile wrapped
as a Python object.
The handle doesn't require to be closed... | 71,023 |
def transformation(func: Callable[[Any], Any], target: Generator):
"""Transforms data and sends it down the pipe.
Args:
func: A function which transforms the data.
target: Next processor
"""
while True:
data = yield
target.send(func(data)) | 71,024 |
def test_same_col(mention_setup):
"""Test the same_col function."""
mentions = mention_setup
# Different column
assert mentions[51].get_span() == "Joan"
assert mentions[52].get_span() == "saag"
assert not same_col((mentions[51], mentions[52]))
# Same column
assert mentions[57].get_span... | 71,025 |
def send_script(script_to_send,robot_ip):
"""
Opens a socket to the Robot and sends a script
Args:
script_to_send: Script to send to socket
robot_id: Integer. ID of robot
"""
'''Function that opens a socket connection to the robot'''
PORT = 30002
HOST = robot_ip
s = s... | 71,026 |
def mocked_has_multiple_views(mocker):
"""Return mocked 'nomenclator.utilities.has_multiple_views' function."""
import nomenclator.utilities
return mocker.patch.object(nomenclator.utilities, "has_multiple_views", ) | 71,027 |
def pre_post_process_layer(prev_out,
out,
process_cmd,
dropout_rate=0.,
epsilon=1e-12,
name=''):
"""
Add residual connection, layer normalization and droput to the out tensor
... | 71,028 |
def lookup_file_from_mixcli_userhome(filename: str) -> Optional[str]:
"""
Try to lookup a file with given name, if environment variable for MixCli user home is present, is a valid dir,
and if a file with given name is found in that dir.
:param filename: Name of expected file to lookup
:return: None... | 71,029 |
def get_dns_records(domain, rdtype, nameserver):
"""Retrieves the DNS records matching the name and type and returns a list of records"""
records = []
try:
dns_resolver = dns.resolver.Resolver()
dns_resolver.nameservers = [nameserver]
dns_response = dns_resolver.query(domain, rdtype)... | 71,030 |
def create_renderer(window, attach_callbacks=True):
"""
This is a helper function that wraps the appropriate version of the Pyglet
renderer class, based on the version of pyglet being used.
"""
# Determine the context version
# Pyglet < 2.0 has issues with ProgrammablePipeline even when the cont... | 71,031 |
def update_plot(plot_result_values, batch=0, n_max_neuron_per_raster=40):
"""
This function iterates the matplotlib figure on every call.
It plots the data for a fixed sequence that should be representative of the expected computation
:return:
"""
# Clear the axis to print new plots
for k i... | 71,032 |
async def test_interval_is_longer_than_blocking(event_loop):
"""
*awake_msg* blocks for 0.5 seconds, which is a shorter time than the 2sec period -
everything should proceed fine
"""
p = Periodic(awake_msg, 2.0)
event_loop.call_soon(p.start)
await asyncio.sleep(0.01) # Yielding control to t... | 71,033 |
def _ffmpeg_fmt(dtype):
"""
Convert numpy dtypes to format strings understood by ffmpeg.
Parameters
----------
dtype : numpy dtype
Data type to be converted.
Returns
-------
str
ffmpeg format string.
"""
# convert dtype to sample type
dtype = np.dtype(dtype... | 71,034 |
def pct(n, d, mul=100.0, **kwargs):
""" Percentage by the same logic.
You can override mul and nan if you like.
"""
return rat(n, d, mul=mul, **kwargs) | 71,035 |
def findIKhandles():
""" Returns a list of all IK handles in the scene """
return mc.ls(type="ikHandle") | 71,036 |
def when_all(*desired_flags):
"""
Register the decorated function to run when all of ``desired_flags`` are active.
Note that handlers whose conditions match are triggered at least once per
hook invocation.
For backwards compatibility, this decorator can pass arguments, but it is
recommended to... | 71,037 |
def ingest_dns_record_by_fqdn(
neo4j_session: neo4j.Session, update_tag: int, fqdn: str, points_to_record: str, record_label: str,
dns_node_additional_label: Optional[str] = None,
) -> None:
"""
Creates a :DNSRecord node in the graph from the given FQDN and performs DNS resolution to connect it to its
... | 71,038 |
def detail_url(profile_id):
"""Return profile detail url"""
return reverse('profile-detail', args=[profile_id]) | 71,039 |
def fetch_result_csv_fp(dir):
"""
Find result CSV in dir. Currently just finds the first non-system file CSV in dir, assuming only one exists; more sophisticated checks need to be added.
:param dir: directory to search in.
:return: path to csv.
"""
csv = [os.path.join(dir, x) for x in os.listdir... | 71,040 |
def test_watermarks_restored_after_stable(
looper,
chkFreqPatched,
txnPoolNodeSet,
sdk_pool_handle, sdk_wallet_client):
"""
A backup replica doesn't participate in consensus, and hence doesn't update watermarks.
Then if it gets a quorum of stashed checkpoints (in fact Replica... | 71,041 |
def main() -> int:
"""Main code"""
parser = _get_parser()
args = parser.parse_args()
spec_url = args.spec_url
spec_file = args.spec_file
enforce_defaults = args.enforce_defaults
schema = _load_spec(spec_file, spec_url)
validator = _create_validator(schema, enforce_defaults)
file_p... | 71,042 |
def enable_deployer_network(config_path=None):
"""creates or modifies the network elements on the deployer which allow
communication between the POWER-Up container and the cluster nodes
and switches. Management networks such as those used for switch
management port access can utilize the default linux
... | 71,043 |
def inis2dict(ini_paths: Union[str, Sequence[str]]) -> dict:
"""
Take one or more ini files and return a dict with configuration from all,
interpolating bash-style variables ${VAR} or ${VAR:-DEFAULT}.
:param ini_paths: path or paths to .ini files
"""
var_dflt = r'\${(.*?):-(.*?)}'
def _int... | 71,044 |
def run_empty_query(dataset_name: str):
"""Returns basic stats (group and row count, etc.) over the dataset. A GET request since no query is passed."""
query = {}
should_stream = bool_request_arg('stream')
return do_run_query(dataset_name, query, should_stream) | 71,045 |
def get_files(d, sites=None, exts=None):
"""Get list of files in the specified directory, optionally filtering by file extension(s)"""
l = []
if type(exts) in (str, basestring):
exts = [exts]
for fname in os.listdir(d):
file_ext = os.path.splitext(fname)[1].lower()
if exts and fi... | 71,046 |
def add_ref():
"""Starts a gui where you can select a referance frames
that gets added to the db.
"""
pass | 71,047 |
def read_training_schema():
"""Responsible for reading the schema from schema_training.json
"""
params=read_params()
path = params['data_schemas']['training_schema']
with open(path) as f:
schema=json.load(f)
LengthOfDateStampInFile = schema['LengthOfDateStampInFile']
LengthOfTimeStam... | 71,048 |
def propagate(w,b,X,Y):
"""
实现前向传播的代价函数及反向传播的梯度
输入:
w -- 权重,一个numpy数组,大小为(图片长度*图片高度*3,1)
b -- 偏差,一个标量
X -- 训练数据,大小为(图片长度*图片高度*3,1)
Y -- 真实“标签”向量,大小为(1,样本数量)
输出:
cost -- 逻辑回归的负对数似然代价函数
dw -- 相对于w的损失梯度,因此与w的形状相同
db -- 相对于b的损失梯度,因此与b的形状相同
"""
m = X.shape[1]
#... | 71,049 |
def extend_segments(X_conv, X_cont, peaks, min_diff_trav, cqt_window, sr, bin_thresh_segment, perc_tail):
"""
The segments surfaced by the convolution have tails that fade to 0, we want the binarizing
threshold to be lower for these tails than the rest of the array
"""
new_cont = X_cont.copy()
a... | 71,050 |
def minus(a, b, rm_na=False):
""" show whats in list b which isn't in list a """
if rm_na:
a=rm_na(a)
b=rm_na(b)
s = set(b)
return [x for x in a if x not in b]
#return list(set(a).difference(set(b))) | 71,051 |
def moveeffect_059(score: int, move: Move, user: Pokemon, target: Pokemon, battle: AbstractBattle) -> int:
"""
Move Effect Name: Averages the user's and target's Defense/Special Defense.
"""
adef = user.base_stats.get("def", 0)
aspd = user.base_stats.get("spd", 0)
odef = target.base_stats.get(... | 71,052 |
def re_group(regexp, text):
"""search for regexp in text, return 1st group on match"""
m = re.search(regexp, text)
if m: return m.group(1) | 71,053 |
def remove_comments(run_file):
"""
removes comments from .idf file after writing.
:param run_file: .idf file name.
:return:
"""
with open(run_file, 'r+') as f:
data = f.readlines()
for num, line in enumerate(data):
data[num] = re.sub(re.compile("!-.*?\n"), "\n", data[... | 71,054 |
def adapt_field(field):
""" Convert sql field name to application field
"""
if field in app_fields:
adapted_field = app_fields[field]
if adapted_field != '':
return adapted_field
return field | 71,055 |
def im_to_double(im):
"""
"""
min_val = np.min(im.ravel())
max_val = np.max(im.ravel())
return (im.astype('float') - min_val) / (max_val - min_val) | 71,056 |
def read_script_config():
""" This fucntion reads default CAD tools path from configuration file """
global config, cad_tools
config = ConfigParser(interpolation=ExtendedInterpolation())
config.read_dict(script_env_vars)
default_cad_tool_conf = os.path.join(flow_script_dir, os.pardir, 'misc',
... | 71,057 |
def dos_from_bands(bands, smearing, npoints):
"""
Compute DOS from bands
:param bands: The `BandsData` to be used as input.
:param smearing: Smearing width in eV
:param npoints: Number of points
"""
bands_data = bands.get_bands(also_occupations=False, also_labels=False)
_, weights = ban... | 71,058 |
def cubeellipse(theta, lam=0.6, gamma=1.0, s=4.0, r=1.0, h=1.2):
"""Create an RGB colormap from an input angle theta. Takes lam (a list of
intensity values, from 0 to 1), gamma (a nonlinear weighting power),
s (starting angle), r (number of revolutions around the circle), and
h (a hue factor)."""
im... | 71,059 |
def load(f: IO[str]) -> Any:
"""YAML load data from stream
Args:
f (IO[str]): IO Stream with data
Returns:
Any: YAML Data
"""
yml = ruamel.yaml.YAML(typ="safe")
return yml.load(f) | 71,060 |
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
a_substrings = set(substring_tokenize(a, n))
b_substrings = set(substring_tokenize(b, n))
return a_substrings & b_substrings | 71,061 |
def drop_db():
"""This function's responsability is to wipe out a database.
This could be implement within each StorageBackend, it's just a bit more akward because at this
point the database connection is not stored in the app anymore.
"""
backend = flask.current_app.config['STORAGE_BACKEND']
... | 71,062 |
def output_csv(profile_list):
"""Writes gathered info in CSV format.
Args:
profile_list (List[selenium.webdriver.remote.webelement.WebElement]): The found list of profile link elements.
Returns:
None
"""
import csv
writer = csv.DictWriter(sys.stdout, fieldnames=['Name', 'URL'])... | 71,063 |
def iteritems(dictionary):
"""Replacement to account for iteritems/items switch in Py3."""
if hasattr(dictionary, "iteritems"):
return dictionary.iteritems()
return dictionary.items() | 71,064 |
def same_class(
query_dataset_name: str,
queried_dataset_name: str,
query_embeddings_name: str,
queried_embeddings_name: str,
k: int,
distance: str,
n_gpu: int,
processes: int,
):
"""Cross-modal image recall of same class elements."""
click.echo(
"Calculating cross modal ... | 71,065 |
def _gather_data(item):
"""Gathers gateways used and start_time"""
# pylint: disable=protected-access
request = item._request
gateways = {}
# Most of the time gateways are referenced indirectly through lifecycle hooks, so I have to detect them like this
if "api_client" in request.fixturenames:
... | 71,066 |
def validate_testapps(apis, api_configs):
"""Ensures the chosen apis are valid, based on the config."""
if "all" in apis:
return [key for key in api_configs]
for api in apis:
if api not in api_configs:
raise RuntimeError("Testapp given as flag not found in config: %s" % api)
return apis | 71,067 |
def _encrypt_bhv(trace):
"""
加密轨迹
:param trace:
:return:
"""
with open('ysf_slider.js', 'rb') as f:
js = f.read().decode()
ctx = execjs.compile(js)
return ctx.call('getCompress', trace) | 71,068 |
def randomize(s):
"""
Set random values to the parameters in the parameter set, with
values chosen according to the bounds.
"""
for p in s:
p.value = p.bounds.random(1)[0] | 71,069 |
def main():
"""Run main function."""
content = get_badges()
with README.open("r+") as fileh:
data = fileh.read()
fileh.seek(0)
data = content + "\n\n" + data
fileh.write(data)
fileh.flush() | 71,070 |
def loginAysnSuggest(session, username, password):
"""
登录接口
ps: 不需要验证码
:return:
"""
loginAysnSuggestUrls = urls.get("loginAysnSuggest")
data = {
"loginUserDTO.user_name": username,
"userDTO.password": password
}
loginAysnSuggestRsp = session.httpClint.send(urls=loginA... | 71,071 |
def prune_basis(basis, use_copy=True):
"""
Removes primitives that have a zero coefficient, and
removes duplicate shells
This only finds EXACT duplicates, and is meant to be used
after uncontracting
If use_copy is True, the input basis set is not modified.
"""
if use_copy:
bas... | 71,072 |
def insert(node, data):
"""
Insert data in BST rooted at node if necessary, and return new root.
Assume node is the root of a Binary Search Tree.
@param BinaryTree node: root of a binary search tree.
@param object data: data to insert into BST, if necessary.
>>> b = BinaryTree(8)
>>> b = ... | 71,073 |
def read_version(other_file_name, filename):
"""Read the the current version or build of the app"""
version = ""
version = read_file(other_file_name, filename)
if version:
version = version.rstrip()
if not version:
version = "__UNKNOWN__"
return version | 71,074 |
def api_tag_list():
"""Listing for all tags.
"""
tags = db.session.query(database.TagRecord).all()
return _tags_response(tags) | 71,075 |
def turtle_triangle(side_length=100):
"""loop through a triangle"""
for i in range(3): # i is an iterator whose value changes each time it is used
forward(side_length)
right(120) | 71,076 |
def test_get_listening_locators(datareader):
"""
This test checks:
- DataReader::get_listening_locators
"""
locator_list = fastdds.LocatorList()
assert(fastdds.ReturnCode_t.RETCODE_OK ==
datareader.get_listening_locators(locator_list))
assert(0 < locator_list.size()) | 71,077 |
def logout_researcher(request: HttpRequest):
""" clear session information for a researcher """
if SESSION_UUID in request.session:
del request.session[SESSION_UUID]
if EXPIRY_NAME in request.session:
del request.session[EXPIRY_NAME] | 71,078 |
def load_file_as_str(file_path: str) -> str:
"""
Loads the file at a specificed path, returns an error otherwise
:param file_path (str): The path to the file you want to load
:return _file a str of the contents of the file
"""
_file = ""
try:
with open(file_path, "r") as fp:... | 71,079 |
def test_2nd_order_bc():
"""test whether 2nd order boundary conditions can be used"""
grid = UnitGrid([8, 8])
field = ScalarField.random_uniform(grid)
field.laplace([{"value": "sin(y)"}, {"value": "x"}]) | 71,080 |
def add_variables(md, g, deadline: int, start, vertices_t, searchers=None):
# TODO IMPORTANT change to allow for different zetas!
"""Create the variables for my optimization problem
:param searchers:
:param start:
:param vertices_t:
:param deadline
"""
# variables related to searcher po... | 71,081 |
def _dol_to_lod(dol):
"""Convert a dict-of-lists into a list-of-dicts.
Reverse transformation of :func:`_lod_to_dol()`.
"""
keys = list(dol.keys())
lod = []
for i in range(len(dol[keys[0]])):
lod.append({k: v[i] for k, v in dol.items()})
return lod | 71,082 |
def splitchildren(
src=os.path.join(SCRAPED_DATA_DIR, "scraped", "bgg_rankings_children_GameItem.jl"),
dst_dir=os.path.join(SCRAPED_DATA_DIR, "rankings", "bgg", "bgg_children"),
dst_file="%Y%m%d-%H%M%S.csv",
overwrite=False,
):
"""Split the children rankings data as one CSV file per date."""
dja... | 71,083 |
def _fix_axis(x_lab, fig_config, axlw=0.4, rem_list=('top', 'right')):
"""
Fix the axis limits, labels and lines.
Argument:
--------
x_lab - axis labels
fig_config - figure configurations
ax_fs - fontsize for axis and tick labels
ax_lw - linewidth of axis lines
r... | 71,084 |
def infomap(adata: AnnData, basis: str = "umap", color: str = "infomap", *args, **kwargs):
"""\
Scatter plot for infomap community detection in selected basis.
Parameters
----------
adata: :class:`~anndata.AnnData`
an Annodata object.
%(scatters.parameters.no_adata|basis)s
... | 71,085 |
def test_handle_django_permission_denied(mocker):
"""Ensure `rest_framework` handler for ``PermissionDenied`` is called."""
drf_handler_mock = mocker.patch(API_EXCEPTION_HANDLER_PATH)
handlers.handle_django_permission_denied(PermissionDenied(), {})
drf_handler_mock.assert_called_once()
exception, ... | 71,086 |
def main():
"""Run the tests defined by the command line args.
Run the tests defined by the command line args or if none were provided
read the tests from the charms tests.yaml config file
"""
args = parse_args(sys.argv[1:])
cli_utils.setup_logging(log_level=args.loglevel.upper())
tests = a... | 71,087 |
def Refresh(creds, http_client=None):
"""Refresh credentials.
Calls creds.refresh(), unless they're SignedJwtAssertionCredentials.
Args:
creds: oauth2client.client.Credentials, The credentials to refresh.
http_client: httplib2.Http, The http transport to refresh with.
Raises:
RefreshError: If the... | 71,088 |
def partscreen(x, y, top, left, debug_mode=False, monitor_resolution=None):
"""
take screeenshot for a part of the screen to find some part of the image
"""
global partImg
debug("entered screenpart")
import mss.tools
with mss.mss() as sct:
monitor = {"top": top, "left": left, "width... | 71,089 |
def get_base_complex_data(model, complex_id):
"""If a complex is modified in a metabolic reaction it will not
have a formation reaction associated with it. This function returns
the complex data of the "base" complex, which will have the subunit
stoichiometry of that complex"""
# First try unmodifi... | 71,090 |
def register_tre(tre_type, tre_id=None, replace=False):
"""
Register a type in the TRE registry.
Parameters
----------
tre_type : type
A subclass of TRE
tre_id : None|str
The id for the type. The class name will be used if not supplied.
replace : bool
Should we repla... | 71,091 |
def _CheckLGTMsForPublicAPI(input_api, output_api):
"""Check LGTMs for public API changes.
For public API files make sure there is an LGTM from the list of owners in
PUBLIC_API_OWNERS.
"""
results = []
requires_owner_check = False
for affected_file in input_api.AffectedFiles():
affected_file_path = a... | 71,092 |
def update_content(content_id):
"""
**Update Information of a Specific Content Record**
This function allows user to update a specific content information through their content_id.
:param content_id: id of the content
:type content_id: int
:return: content information updat... | 71,093 |
def compute_winner_index(interactions, game=None):
"""Returns the index of the winner of the Match"""
scores = compute_final_score(interactions, game)
if scores is not None:
if scores[0] == scores[1]:
return False # No winner
return max([0, 1], key=lambda i: scores[i])
retu... | 71,094 |
def get_shard_index(shard_name):
"""Returns tuple of shard index, num_shards based on a shard name."""
if shard_name in ['0', '-']:
return 0, 1
shard_begin, shard_end = shard_name.split('-')
num_bytes_used = max(len(shard_begin), len(shard_end)) / 2
if shard_begin:
shard_begin = int(shard_begin, 16)
... | 71,095 |
def main(action: str) -> None:
"""
Run specified action
"""
pg_instance = PyGame(WINDOWS_SIZE, FRAME_RATE)
pg_instance.init(action) | 71,096 |
def decode_segmap(label_mask, dataset='pascal'):
"""Decode segmentation class labels into a color image
Args:
label_mask (np.ndarray): an (M,N) array of integer values denoting
the class label at each spatial location.
Returns:
np.ndarray: the resulting decoded color image.
"""... | 71,097 |
def validate_term_frequency_normalization_options(raw_val):
"""
Validate a term frequency normalization option.
"""
if raw_val not in ['unscaled-log', 'weakest-scaled-log', 'weakly-scaled-log', 'moderately-scaled-log',
'strongly-scaled-log', 'scaled-log']:
raise ValidationE... | 71,098 |
def test_atomic_g_month_max_exclusive_2_nistxml_sv_iv_atomic_g_month_max_exclusive_3_4(mode, save_output, output_format):
"""
Type atomic/gMonth is restricted by facet maxExclusive with value
--11.
"""
assert_bindings(
schema="nistData/atomic/gMonth/Schema+Instance/NISTSchema-SV-IV-atomic-gM... | 71,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.