content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extract_and_coadd(ra, dec, pm_ra, pm_dec, match_radius=4./3600.,
search_radius=25./60, sigma_clip=None, query_timeout=60.,
upper_limits=True, return_exps=False):
"""
The top-level function of this module, extract_and_coadd finds sources in
GALEX archive matchi... | 27,400 |
async def create_payout(
session: ClientSession, data: CreatePayoutRequest
) -> CreatePayoutResponse:
"""
Create a payout.
"""
url = RAZORPAY_BASE_URL + "/payouts"
async with session.post(
url,
json=data.__dict__,
auth=aiohttp.BasicAuth(RAZORPAY_KEY_ID, RAZORPAY_KEY_SECR... | 27,401 |
def eval_ocr_metric(pred_texts, gt_texts):
"""Evaluate the text recognition performance with metric: word accuracy and
1-N.E.D. See https://rrc.cvc.uab.es/?ch=14&com=tasks for details.
Args:
pred_texts (list[str]): Text strings of prediction.
gt_texts (list[str]): Text strings of ground tru... | 27,402 |
def get_all_zones():
"""Return a list of all available zones."""
cf = CloudFlare.CloudFlare(raw=True)
page_number = 0
total_pages = 1
all_zones = []
while page_number < total_pages:
page_number += 1
raw_results = cf.zones.get(params={'per_page':100, 'page':page_number})
z... | 27,403 |
def entry_id(e):
"""entry identifier which is not the bibtex key
"""
authortitle = ''.join([author_id(e),title_id(e)])
return (e.get('doi','').lower(), authortitle) | 27,404 |
def AskNumber(text="unknown task"):
"""
Asks the user to interactively input a number (float or int) at any point in the script, and returns the input number.
| __option__ | __description__
| --- | ---
| *text | an optional string to identify for what purpose the chosen number will be used.
"""
def ValidateN... | 27,405 |
def TokenEmphasis(character="_"):
"""
Italic (`<i>`, `<em>`) text is rendered with one asterisk or underscore
"""
assert character in ("_", "*")
return {
"type": "Characters",
"data": character,
"_md_type": mdTokenTypes["TokenEmphasis"],
} | 27,406 |
def get_data(filename, **kwargs):
"""
get selected data file
"""
filepath = os.path.join(data.__path__[0], filename)
return np.genfromtxt(filepath, **kwargs) | 27,407 |
def generate_plan(suite, node):
"""Randomly generates a plan, completely ignoring norms. This is mainly for testing the norm driven algorithm"""
plan = [node]
next_actions = next_actions(suite,node)
# print "Next actions ", next_actions
while (next_actions != []):
a = random.sample(next_acti... | 27,408 |
def update_y(pred_coords, ypart_tracker, history=1500):
"""
Update y-tracker and store last 1500 detection
:param pred_coords: y coordinates
:param ypart_tracker: choose keypoints based on input conditions
:return: y-tracker
"""
anks_val = (pred_coords[15] + pred_coords[16]) * 0.5
shdr_v... | 27,409 |
def augmentData(features, labels):
"""
For augmentation of the data
:param features:
:param labels:
:return:
"""
features = np.append(features, features[:, :, ::-1], axis=0)
labels = np.append(labels, -labels, axis=0)
return features, labels | 27,410 |
def generate_election_spec_contest_groups(e, synpar):
"""
Greate synpar.n_cids-1 'random' contest groups.
They get ids like 'gid2-6' meaning they cover cids 2 to 6 inclusive.
"""
e.gids = []
cids_list = sorted(list(e.cids))
for (low, high) in syn.generate_segments(e, synpar, 1, synpar.n_ci... | 27,411 |
def train_adversary():
""" Trains an adversary on data from the data censoring process. """
def accuracy(pred, true):
u = true.cpu().numpy().flatten()
p = np.argmax(pred.cpu().detach().numpy(), axis=1)
acc = np.sum(u == p)/len(u)
return acc
tmp_secret_classifier.train(... | 27,412 |
def sigmoid(x):
""" Implement 1 / ( 1 + exp( -x ) ) in terms of tanh."""
return 0.5 * (np.tanh(x / 2.) + 1) | 27,413 |
def get_unique_output_values(signals):
"""
Based on segment length, determine how many of the possible four
uniquely identifiable digits are in the set of signals.
"""
unique_digit_count = 0
for signal in signals:
for digit in signal["output"]:
if len(digit) in (2, 3, 4, 7):... | 27,414 |
def feature_evaluation(X: pd.DataFrame, y: pd.Series,
output_path: str = ".") -> NoReturn:
"""
Create scatter plot between each feature and the response.
- Plot title specifies feature name
- Plot title specifies Pearson Correlation between feature and response
- P... | 27,415 |
def split_and_pad(s, sep, nsplit, pad=None):
""" Splits string s on sep, up to nsplit times.
Returns the results of the split, pottentially padded with
additional items, up to a total of nsplit items.
"""
l = s.split(sep, nsplit)
return itertools.chain(l, itertools.repeat(None, nsplit+1-... | 27,416 |
def transpose_report(report):
"""Transposes the report. Columns into rows"""
return list(map(list, zip(*report))) | 27,417 |
def _shape_from_resolution(resolution):
"""
Calculate the shape of the global Earth relief grid given a resolution.
Parameters
----------
resolution : str
Same as the input for load_earth_relief
Returns
-------
shape : (nlat, nlon)
The calculated shape.
Examples
... | 27,418 |
def test_base_reader_rosbag_accel():
"""Run the base reader test."""
import numpy as np
from pydtk.io import BaseFileReader
path = 'test/records/rosbag_model_test/data/records.bag'
reader = BaseFileReader()
timestamps, data, columns = reader.read(path=path, contents='/vehicle/acceleration')
... | 27,419 |
def __virtual__():
"""
Load module only if cx_Oracle installed
"""
if HAS_CX_ORACLE:
return __virtualname__
return (
False,
"The oracle execution module not loaded: python oracle library not found.",
) | 27,420 |
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up the Zigbee Home Automation switches."""
discovery_info = zha.get_discovery_info(hass, discovery_info)
if discovery_info is None:
return
from zigpy.zcl.clusters.general ... | 27,421 |
def find_plugins():
""" Finds all Python packages inside the port.plugins directory """
return [os.path.join(importer.path, name) for importer, name, ispkg in pkgutil.iter_modules(plugins.__path__) if ispkg] | 27,422 |
def saturation(rgb_img, threshold=255, channel="any"):
"""Return a mask filtering out saturated pixels.
Inputs:
rgb_img = RGB image
threshold = value for threshold, above which is considered saturated
channel = how many channels must be saturated for the pixel to be masked out ("any", "all")... | 27,423 |
def get_fuel_from(mass: int) -> int:
"""Gets fuel from mass.
Args:
mass (int): mass for the fuel
Returns:
int: fuel necessary for the mass
"""
return mass // 3 - 2 | 27,424 |
def test_energy_density_function():
"""
Compute the Zeeman energy density over the entire mesh, integrate it, and
compare it to the expected result.
"""
mesh = df.RectangleMesh(df.Point(-50, -50), df.Point(50, 50), 10, 10)
unit_length = 1e-9
H = 1e6
# Create simulation object.
sim ... | 27,425 |
def my_Bayes_model_mse(params):
""" Function fits the Bayesian model from Tutorial 4
Args :
params (list of positive floats): parameters used by the model (params[0] = posterior scaling)
Returns :
(scalar) negative log-likelihood :sum of log probabilities
"""
trial_ll = np.zeros_li... | 27,426 |
def validate_request_tween_factory(handler, registry):
"""
Updates request.environ's REQUEST_METHOD to be X_REQUEST_METHOD if present.
Asserts that if a POST (or similar) request is in application/json format,
with exception for /metadata/* endpoints.
Apache config:
SetEnvIf Request_Method ... | 27,427 |
def gen(camera):
"""Video streaming generator function."""
# initialise some variables
frame_count = 0;
bytes_io = BytesIO()
skip_frame = 1;
face_names = []
face_locations = []
while True:
print("Capturing image.")
camera.capture(output, format="rgb")
im = Image.fromarray(output,'RGB')
# process eve... | 27,428 |
async def get_rank(display_number: int, minimal_msg_number: int,
display_total_number: int, group_id: int) -> str:
""" 获取排行榜 """
repeat_list = recorder_obj.repeat_list(group_id)
msg_number_list = recorder_obj.msg_number_list(group_id)
ranking = Ranking(group_id, display_number, minim... | 27,429 |
def feedback(request):
"""FeedbackForm"""
if (request.method == 'POST'):
form = forms.FeedbackForm(request.POST)
# pdb.set_trace()
if form.is_valid():
form.save()
type = form.cleaned_data['type']
type = dict(form.fields['type'].choices)[type]
... | 27,430 |
def get_convolutional_args(call, include_buffers=False, remove_constants=False):
"""A method to extract the arguments from conv2d or depthwise_conv2d extern call."""
args = call.args
conv_args = []
remove_indices = [0]
if remove_constants:
remove_indices += [41, 42, 44, 45]
for i, arg ... | 27,431 |
def view_party(party_id):
"""View dashboard for that party."""
party = party_service.find_party(party_id)
if party is None:
abort(404)
days = party_service.get_party_days(party)
days_until_party = (party.starts_at.date() - date.today()).days
orga_count = orga_team_service.count_member... | 27,432 |
def _sequence_like(instance, args):
"""Converts the sequence `args` to the same type as `instance`.
Args:
instance: an instance of `tuple`, `list`, `namedtuple`, `dict`,
`collections.OrderedDict`, or `composite_tensor.Composite_Tensor`
or `type_spec.TypeSpec`.
args: elements to be converted... | 27,433 |
def patch_violinplot():
"""Patch seaborn's violinplot in current axis
to workaround matplotlib's bug ##5423."""
from matplotlib.collections import PolyCollection
ax = plt.gca()
for art in ax.get_children():
if isinstance(art, PolyCollection):
art.set_edgecolor((0.3, 0.3, 0.3)) | 27,434 |
def subcat_add():
"""
添加小分类
"""
if request.method == 'POST':
cat_name = request.form['cat_name']
super_cat_id = request.form['super_cat_id']
# 检测名称是否存在
subcat = SubCat.query.filter_by(cat_name=cat_name).count()
if subcat :
return "<script>ale... | 27,435 |
def handle_candidate_results(
data: Union[
structs.NationalSummaryPresident,
structs.StateSummaryPresident,
structs.StateSummaryCongressionalResult,
structs.CountyCongressionalResult,
structs.CountyPresidentialResult,
],
named_candidate_factory: Any,
record: SQLRe... | 27,436 |
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up the Alexa sensor platform by config_entry."""
return await async_setup_platform(
hass,
config_entry.data,
async_add_devices,
discovery_info=None) | 27,437 |
def parse_duration(dur: str) -> int:
"""Generates seconds from a human readable duration."""
if not DURATION_REGEX.match(dur):
raise ValueError('Time passed does not match required format: `XX:XX` or `XX:XX:XX`')
parts = dur.split(':')
seconds = 0
if len(parts) == 3:
seconds += int... | 27,438 |
def shorter_uuid(length=7, starter=None, with_original=False):
"""
Generate an even shorter short UUID generated by the shortuuid library.
:param length: Length of trimmed ID.
:param starter: Whether to begin with an already-created ShortUUID.
Useful when using recursively.
:par... | 27,439 |
async def connect_web_socket(uri: str,
serializer: Union[aiowamp.SerializerABC, Sequence[aiowamp.SerializerABC]] = None,
*,
ssl_context: ssl.SSLContext = None) -> WebSocketTransport:
"""Connect to a router using web socket transp... | 27,440 |
def ok_git_config_not_empty(ar):
"""Helper to verify that nothing rewritten the config file"""
# TODO: we don't support bare -- do we?
assert_true(os.stat(opj(ar.path, '.git', 'config')).st_size) | 27,441 |
def group_by(s: Iterable[_ElementType],
key: Callable[[_ElementType], _GroupType],
gfunc: Optional[Callable[[List[_ElementType]], _ResultType]] = None) -> Dict[_GroupType, _ResultType]:
"""
Overview:
Divide the elements into groups.
:param s: Elements.
:param key: Grou... | 27,442 |
def update_key(context,alias,new_url,new_api_key,fetch_api_key):
"""
Update stored Galaxy API key.
Update the Galaxy URL and/or API key stored
against ALIAS.
"""
instances = Credentials()
if alias not in instances.list_keys():
logger.error("'%s': not found" % alias)
sys.exit... | 27,443 |
def init_templateflow_wf(
bids_dir,
output_dir,
participant_label,
mov_template,
ref_template='MNI152NLin2009cAsym',
use_float=True,
omp_nthreads=None,
mem_gb=3.0,
modality='T1w',
normalization_quality='precise',
name='templateflow_wf',
fs_subjects_dir=None,
):
"""
... | 27,444 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""
Set up iDiamant from a config entry.
"""
implementation = (
await config_entry_oauth2_flow.async_get_config_entry_implementation(
hass, entry
)
)
# Set unique id if non was set.
if... | 27,445 |
def test_apply_conversion(qtbot, value, precision, unit, show_unit, expected_format_string):
"""
Test the unit conversion by examining the resulted format string.
Expectations:
Provided with the value, precision, unit, and the show unit Boolean flag by the user, this function must provide
the corr... | 27,446 |
def Qest(ICobj, r=None):
"""
Estimate Toomre Q at r (optional) for ICs, assuming omega=epicyclic
frequency. Ignores disk self-gravity
"""
if not hasattr(ICobj, 'sigma'):
raise ValueError, 'Could not find surface density profile (sigma)'
G = SimArray(1.0, 'G')
kB = ... | 27,447 |
def get_projector_csr_file(config_name: str) -> str:
"""Returns full path to projector server crt file"""
return join(get_run_configs_dir(), config_name, f'{PROJECTOR_JKS_NAME}.csr') | 27,448 |
def test_xiaomi():
"""
KITTI视差图——>深度图——>点云
"""
def disp2depth(b, f, disp):
"""
"""
disp = disp.astype(np.float32)
non_zero_inds = np.where(disp)
depth = np.zeros_like(disp, dtype=np.float32)
depth[non_zero_inds] = b * f / disp[non_zero_inds]
... | 27,449 |
def get_img(shape, path, dtype, should_scale=True):
"""Get image as input."""
resize_to = shape[1:3]
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
img = PIL.Image.open(path)
img = img.resize(resize_to, PIL.Image.ANTIALIAS)
img_np = np.array(img).astype(dtype)
img_np =... | 27,450 |
def render_author(**kwargs):
"""
Unstrict template block for rendering authors:
<div class="author">
<img class="author-avatar" src="{author_avatar}">
<p class="author-name">
<a href="{author_link}">{author_name}</a>
</p>
<p class="user-handle">{author_handle}</p>... | 27,451 |
def save_pattern(seq, end):
""" Saves a polar graph of the GCS sequence, up to a specified stopping point in the sequence
@param seq (list[int]) - the generalized chopstick sequence
@param end (int) - only GCS numbers less than or equal to `end` are included in the graph
"""
size = round(log(end)) ... | 27,452 |
def make_epsilon_greedy_policy(Q: defaultdict, epsilon: float, nA: int) -> callable:
"""
Creates an epsilon-greedy policy based on a given Q-function and epsilon.
I.e. create weight vector from which actions get sampled.
:param Q: tabular state-action lookup function
:param epsilon: exploration fac... | 27,453 |
def write_init(proxy_parameters=None, exception=None):
"""Encodes and returns an MPI ('Metadata Init') response."""
return _write_init(Method.MPI, MetadataProviderError, proxy_parameters,
exception) | 27,454 |
def run(loaded_sns_message, context):
"""Send an Alert to its described outputs.
Args:
alerts [dict]: SNS message dictionary with the following structure:
{
'default': alert
}
The alert is another dict with the following structure:
{
'record': ... | 27,455 |
def pfam_to_pubmed(family):
"""get a list of associated pubmed ids for given pfam access key.
:param family: pfam accession key of family
:type family: str
:return: List of associated Pubmed ids
:rettype:list"""
url='https://pfam.xfam.org/family/'+family
pattern='http://www.ncbi.nlm.nih... | 27,456 |
def cvConvexHull2(input, hull_storage=None, orientation=CV_CLOCKWISE, return_points=0):
"""CvSeq_or_CvMat cvConvexHull2(list_or_tuple_of_CvPointXYZ input, void* hull_storage=NULL, int orientation=CV_CLOCKWISE, int return_points=0)
Finds convex hull of point set
[ctypes-opencv] OpenCV's note: a vertex o... | 27,457 |
def display(result, args):
"""
Displays the language identification results
according to the format defined by command line arguments.
:param result: the language identification results.
:param args: the command line arguments.
"""
formatter = get_formatter(args.format)
formatter(re... | 27,458 |
def main(params):
""" PIPELINE for matching
:param {str: str} params:
"""
# tl_expt.set_experiment_logger(params['path_expt'])
# tl_expt.create_subfolders(params['path_expt'], LIST_SUBDIRS)
logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))
if not os.path.isdir(params['path_outpu... | 27,459 |
def init_classifier(config: Union[str, mmcv.Config],
checkpoint: Optional[str] = None,
device: str = 'cuda:0',
options: Optional[Dict] = None) -> nn.Module:
"""Prepare a few shot classifier from config file.
Args:
config (str or :obj:`mmcv.Con... | 27,460 |
def get_cognito_events(IdentityPoolId=None):
"""
Gets the events and the corresponding Lambda functions associated with an identity pool.
This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
See also: AWS API D... | 27,461 |
def get_twitter_auth():
"""Setup Twitter authentication.
Return: tweepy.OAuthHandler object
"""
try:
credentials = read_credentials()
consumer_key = credentials.get('consumer_key')
consumer_secret = credentials.get('consumer_secret')
access_token = credentials.get('acces... | 27,462 |
def write_parameters(data, run_dir, is_parallel):
"""Write the parameters file
Args:
data (dict): input
run_dir (py.path): where to write
is_parallel (bool): run in background?
"""
pkio.write_text(
run_dir.join(template_common.PARAMETERS_PYTHON_FILE),
_generate_p... | 27,463 |
def Newton_method(f, df, start:float=0.0, max_step:int=32, sign_dig:int=6)->float:
"""
Newton method.
---------------------------
Args:
None.
Returns:
None.
Raises:
None.
"""
fun = lambda x: x - f(x)/df(x)
return fixed_point(fun, start, max_step, sign_dig) | 27,464 |
def validate_blueprints(ctx):
"""Check all blueprints in the project for errors"""
data = utilities.convert_input_to_dict(ctx)
cmd = utilities.get_commandline(SENTINEL_SCRIPT_PATH, ["run-module", "ue4", "project", "commandlet"], data, sub_command_arguments=["--task=Compile-Blueprints"])
utilities.run_... | 27,465 |
def get_all(isamAppliance, count=None, start=None, filter=None, check_mode=False, force=False):
"""
Retrieve a list of federations
"""
return isamAppliance.invoke_get("Retrieve a list of federations",
"{0}/{1}".format(uri, tools.create_query_string(count=count, start=... | 27,466 |
def roty(theta):
"""
Rotation about Y-axis
@type theta: number
@param theta: the rotation angle
@rtype: 3x3 orthonormal matrix
@return: rotation about Y-axis
@see: L{rotx}, L{rotz}, L{rotvec}
"""
ct = cos(theta)
st = sin(theta)
return mat([[ct, 0, st],
... | 27,467 |
def connect_default_signals(model_class):
"""
Use this function to connect default signals to your custom model.
It is called automatically, if default cities_light models are used,
i.e. settings `CITIES_LIGHT_APP_NAME` is not changed.
"""
if 'Country' in model_class.__name__:
signals.pr... | 27,468 |
def test_pe_validation_right_size_invalid_number():
"""Test if an invalid number is really invalid"""
invalid_number = '1520309645'
assert pe.start(invalid_number) == False | 27,469 |
def dfs_iter(graph, start):
"""Iterativni verze DFS (vcetne casovych znamek)."""
# vkladam uzel a index potencialniho naslednika, kterym mam pokracovat
stack = [(start, 0)]
time = 1
graph.discovery_time[start] = time
graph.visited[start] = True
while stack: # not empty
u, v = stack... | 27,470 |
def flush(name, family="ipv4", ignore_absence=False, **kwargs):
"""
.. versionadded:: 2014.7.0
.. versionchanged:: Magnesium
Flush current nftables state
family
Networking family, either ipv4 or ipv6
ignore_absence
If set to True, attempts to flush a non-existent table will n... | 27,471 |
def solution(s):
"""
Check if a string has properly matching brackets
:param s: String to verify if it is well-formed
:return: 1 if the brackets are properly matching, 0 otherwise
"""
return check_matching_brackets(s, opening="(", closing=")") | 27,472 |
def process_to_annotation_data(df, class_names, video_fps, min_len):
"""
This function cleans the output data, so that there are
no jumping frames.
"""
j = 1 # Helper
# Minimum qty of frames of the same task in order to
# consider it a whole task
min_frames = int(float(min_len) * float... | 27,473 |
def test_successful_parse_undocumented_endpoints() -> None:
"""
Asserts that a schema section is returned successfully.
"""
schema = fetch_from_dir(settings.BASE_DIR + '/demo_project/openapi-schema.yml')
for url in ['/api/v1/cars/incorrect/', '/api/v1/trucks/incorrect/']:
schema_section = p... | 27,474 |
def dicom_dir():
"""Decompress DICOM files into a temp directory"""
with TemporaryDirectory(prefix="dcm-test") as temp_dir:
# Unpack tar to temp dir and yield list of paths
with tarfile.open(DICOM_TAR, "r:bz2") as tf:
tf.extractall(temp_dir)
temp_dir = Path(temp_dir)
... | 27,475 |
def throw_sardana_exception(exc):
"""Throws an exception as a tango exception"""
if isinstance(exc, SardanaException):
if exc.exc_info and None not in exc.exc_info:
Except.throw_python_exception(*exc.exc_info)
else:
tb = "<Unknown>"
if exc.traceback is not Non... | 27,476 |
def reduce_memmap(a):
"""Pickle the descriptors of a memmap instance to reopen on same file."""
m = _get_backing_memmap(a)
if m is not None:
# m is a real mmap backed memmap instance, reduce a preserving striding
# information
return _reduce_memmap_backed(a, m)
else:
# Th... | 27,477 |
def load_sparse_csr(filename):
"""Load a saved sparse matrix in csr format. Stolen from above source."""
loader = np.load(filename)
return sparse.csr_matrix((loader['data'], loader['indices'],
loader['indptr']), shape=loader['shape']) | 27,478 |
def admin_unpublish_selected(modeladmin, request, queryset):
"""
Sets all selected items in queryset to not published
"""
queryset.update(admin_published=False) | 27,479 |
def blank(name: Optional[str]) -> Output:
"""Generate a blank `Output` instance."""
return Output(file_suffix=name or _DEFAULT_SUFFIX, variables=dict()) | 27,480 |
def estatistica_regras(regras_pt, regras_lgp):
"""
Contagem das regras morfossintáticas no corpus.
:param regras_pt: Lado português das regras (lista)
:param regras_lgp: Lado LGP das regras (lista)
:return: Dicionário com a frequência de cada regra. Ex: {"(0, 'INT')": 1, "(1, 'CAN')": 1, "(2, 'INT')": 1}
"""
est... | 27,481 |
def read_config():
"""
Reads the configuration info into the cfg dictionary.
:return: A dictionary with the SSH-IPS configuration variables.
"""
CONFIG_FILE = '/etc/ssh-ips/config.json'
try:
with open(CONFIG_FILE, "r") as f:
cfg = json.load(f)
except ValueError as e:
print(str(e))
sys.exit()
return cf... | 27,482 |
def bq_create_dataset(bq_client):
"""Creates the BigQuery dataset.
If the dataset already exists, the existing dataset will be returned.
Dataset will be create in the location specified by DATASET_LOCATION.
Args:
bq_client: BigQuery client
Returns:
BigQuery dataset that will be used to store data... | 27,483 |
def root_node():
"""
Returns DCC scene root node
:return: str
"""
return scene.get_root_node() | 27,484 |
def firsts(things):
"""
FIRSTS list
outputs a list containing the FIRST of each member of the input
list. It is an error if any member of the input list is empty.
(The input itself may be empty, in which case the output is also
empty.) This could be written as::
to firsts :list
... | 27,485 |
def inf_set_mark_code(*args):
"""
inf_set_mark_code(_v=True) -> bool
"""
return _ida_ida.inf_set_mark_code(*args) | 27,486 |
def get_letter(xml):
"""
:param xml:
:return: everything between <bank> tag
"""
try:
left, right = xml.index('<bank '), xml.index('</bank>') + _BANK_OFFSET
return xml[left:right]
except ValueError:
return None | 27,487 |
def stim_align_all_cells(traces, time, new_start):
"""
Make stim-aligned PSTHs from trialwise data (eg. trial x cell x time array). The
advantage of doing it this way (trialwise) is the trace for each cell gets rolled around
to the other side of the array, thus eliminating the need for nan padding.
... | 27,488 |
def set_random_number_seed(seed=5801):
"""Initialize random number generator (RNG).
By default, the RNG is always given the same seed so that simulations are reproducible.
However, if you would like to rerun simulations with different random sequences,
give a new random seed here.
This affects :me... | 27,489 |
def PowercycleNode(opts, args):
"""Remove a node from the cluster.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the name of
the node to be removed
@rtype: int
@return: the desired exit code
"""
node = args[0]
if (not ... | 27,490 |
async def test_async_setup(hass):
"""Test a successful setup with all of the different options."""
with patch(
"homeassistant.components.dynalite.bridge.DynaliteDevices.async_setup",
return_value=True,
):
assert await async_setup_component(
hass,
dynalite.DOMA... | 27,491 |
def collect_data(bids_dir, participant_label, queries, filters=None, bids_validate=True):
"""
Uses pybids to retrieve the input data for a given participant
"""
if isinstance(bids_dir, BIDSLayout):
layout = bids_dir
else:
layout = BIDSLayout(str(bids_dir), validate=bids_validate)
... | 27,492 |
def minimaldescriptives(inlist):
"""this function takes a clean list of data and returns the N, sum, mean
and sum of squares. """
N = 0
sum = 0.0
SS = 0.0
for i in range(len(inlist)):
N = N + 1
sum = sum + inlist[i]
SS = SS + (inlist[i] ** 2)
mean = sum / float(N)
... | 27,493 |
def gen_filelist(infiles, tmpd) :
"""Write all audio files to a temporary text document for ffmpeg
Returns the path of that text document."""
filename = tmpd/"files.txt"
with open(filename, "w") as f:
for file in infiles:
# This part ensures that any ... | 27,494 |
def onpy_register(unit, *args):
"""
Python knows about which built-ins can be imported, due to their registration in the Assembly or at the start of the interpreter.
All modules from the sources listed in PY_SRCS() are registered automatically.
To register the modules from the sources in the SRCS(), yo... | 27,495 |
def _create_tables(driver, create_all, timeout):
"""
create tables
Args:
driver: sqlalchemy driver
create_all (function): create_all function that creates all tables
timeout (int): timeout for transaction
Returns:
None
"""
logger.info('Creating tables (timeout: ... | 27,496 |
def check_envs():
"""Checks environment variables.
The MONGODB_PWD is a needed variable to enable mongodb connection.
Returns:
bool: If all needed environment variables are set.
"""
if not os.environ.get('MONGODB_PWD', False):
return False
return True | 27,497 |
def VMMemoryLower() -> tvm.ir.transform.Pass:
"""Perform memory lowering. Lowers the relax.builtin.alloc_tensor intrinsic to VM intrinsics.
Returns
-------
ret: tvm.ir.transform.Pass
"""
return _ffi_api.VMMemoryLower() | 27,498 |
def subnet_no_ip_space_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:
"""[VPC.4] Subnets should be monitored for available IP address space"""
iso8601Time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
vpc = describe_vpcs(cache=cache)
my... | 27,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.