content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_mint_studies_response(xml_raw) -> List[MintStudy]:
"""Parse the xml response to a MINT find DICOM studies call
Raises
------
DICOMTrolleyError
If parsing fails
"""
try:
studies = ElementTree.fromstring(xml_raw).findall(
MintStudy.xml_element
)
e... | 25,900 |
def lookup_no_interp(x, dx, xi, y, dy, yi):
"""
Return the indices for the closest values for a look-up table
Choose the closest point in the grid
x ... range of x values
xi ... interpolation value on x-axis
dx ... grid width of x ( dx = x[1]-x[0])
(same for y)
re... | 25,901 |
def index_xml(directory, db):
"""
Index a list of XML files of publication information.
"""
xml.index_directory(directory, db) | 25,902 |
def advertisement_data_complete_builder(list_of_ad_entries):
"""
Generate a finalized advertisement data value from a list of AD entries that can be passed
to the BLEConnectionManager to set the advertisement data that is sent during advertising.
:param list_of_ad_entries: List of AD entries (can be bu... | 25,903 |
def process_vocab_table(vocab,
vocab_size,
vocab_threshold,
vocab_lookup,
unk,
pad):
"""process vocab table"""
default_vocab = [unk, pad]
if unk in vocab:
del vocab[unk]
i... | 25,904 |
def get_mag_msg(stamp, mag):
"""
Get magnetometer measurement as ROS sensor_msgs::MagneticField
"""
# init:
mag_msg = MagneticField()
# a. set header:
mag_msg.header.stamp = stamp
mag_msg.header.frame_id = '/imu_link'
# b. mag:
(
mag_msg.magnetic_field.x,
mag_ms... | 25,905 |
async def UserMeAPI(
current_user: User = Depends(User.getCurrentUser),
):
"""
現在ログイン中のユーザーアカウントの情報を取得する。<br>
JWT エンコードされたアクセストークンがリクエストの Authorization: Bearer に設定されていないとアクセスできない。
"""
# 一番よく使う API なので、リクエスト時に twitter_accounts テーブルに仮のアカウントデータが残っていたらすべて消しておく
## Twitter 連携では途中で連携をキャンセルした場合に仮のア... | 25,906 |
def process_resolvers(context, template=templates.DEFAULT_TEMPLATE):
"""
Perform second stage path resolution based on template rules
Args:
session (TreeNode): The session node to search within
context (dict): The context to perform path resolution on
template (Template): The templa... | 25,907 |
def test_unsupported_version_with_number():
"""
Test the decorator when supplying a non existing version with a number.
"""
with raises(InvalidVersionException):
your_function_nr.v3() | 25,908 |
def midpt(pt1, pt2):
""" Get the midpoint for two arbitrary points in space. """
return rg.Point3d((pt1[0] + pt2[0])/2, (pt1[1] + pt2[1])/2, (pt1[2] + pt2[2])/2 ) | 25,909 |
def dark_current_jh_task(det_name):
"""JH version of single sensor execution of the dark current task."""
from collections import defaultdict
from astropy.io import fits
import siteUtils
from bot_eo_analyses import make_file_prefix, glob_pattern,\
get_amplifier_gains, bias_filename, dark_cur... | 25,910 |
def change_title(mri):
""" Change Title
Change title of current MRI window. """
ui = mri.ui
txt, state = ui.dlgs.dialog_input("Input new title name.",
"", ui.frame.getTitle())
if state:
ui.frame.setTitle(txt) | 25,911 |
def get_sid_list (video_source_filename):
"""This returns a list of subtitle ids in the source video file.
TODO: Also extract ID_SID_nnn_LANG to associate language. Not all DVDs include this.
"""
cmd = "mplayer '%s' -vo null -ao null -frames 0 -identify" % video_source_filename
(command_output, exit... | 25,912 |
def test_default_not_required():
"""Values with a default are not required"""
v = Value(KEY, default='s')
assert v.required is False | 25,913 |
def load_dir(path):
"""Get an iterable of PySource from the given directory."""
for root, subdirs, files in os.walk(abspath(path)):
files = (abspath(os.path.join(root, fname)) for fname in files)
files = (fname for fname in files if fname.endswith('.py'))
for file_name in files:
... | 25,914 |
def test_backup(tmpdir, monkeypatch, name, existing_files, expected):
"""
Ensure the DeferredFileWriter backs up existing files correctly, and at the
correct moment
"""
monkeypatch.chdir(tmpdir)
for idx, file in enumerate(existing_files):
with open(file, 'w') as handle:
handl... | 25,915 |
def test_1_10_15_distribution():
"""
Test connector using Apache Airflow 1.10.15 built distribution.
"""
apc = AirflowPackageCatalogConnector(AIRFLOW_SUPPORTED_FILE_TYPES)
# get catalog entries for the specified distribution
ces = apc.get_catalog_entries({"airflow_package_download_url": AIRFLOW_... | 25,916 |
def main() -> None:
"""impost0r.py main function"""
parser = argparse.ArgumentParser(prog=PROGNAME)
parser.add_argument('--verbose', '-v', action='count', default=0)
parser.add_argument('--version', action='version', version='%(prog)s v' + VERSION)
args = parser.parse_args()
if args.verbose == ... | 25,917 |
def tweetnacl_crypto_box_open(max_messagelength=256):
"""
max_messagelength: maximum length of the message, in bytes.
i.e., the symbolic execution will not consider messages longer than max_messagelength
"""
proj = tweetnaclProject()
state = funcEntryState(proj, "crypto_box_curve25519xsalsa2... | 25,918 |
def balanced_parentheses_checker(symbol_string):
"""Verify that a set of parentheses is balanced."""
opening_symbols = '{[('
closing_symbols = '}])'
opening_symbols_stack = data_structures.Stack()
symbol_count = len(symbol_string)
counter = 0
while counter < symbol_count:
current_... | 25,919 |
def _wrap_outcoming(
store_cls: type, wrapped_method: str, trans_func: Optional[callable] = None
):
"""Output-transforming wrapping of the wrapped_method of store_cls.
The transformation is given by trans_func, which could be a one (trans_func(x)
or two (trans_func(self, x)) argument function.
... | 25,920 |
def quantize(x):
"""convert a float in [0,1] to an int in [0,255]"""
y = math.floor(x*255)
return y if y<256 else 255 | 25,921 |
def initialize_logger(prefix):
"""
Initialization of logging subsystem. Two logging handlers are brought up:
'fh' which logs to a log file and 'ch' which logs to standard output.
:param prefix: prefix that is added to the filename
:return logger: return a logger instance
"""
logger = loggi... | 25,922 |
def plex_test_cmd(bot, trigger):
"""Test if your configured options can reach Plex."""
plex = plex_test(bot, trigger)
if plex is None:
return
else:
bot.reply("Plex connection test successful.") | 25,923 |
def interpolate(x,
x_data,
y_data,
left_slope=0.0,
right_slope=0.0,
dtype=None,
name=None):
"""Performs linear interpolation for supplied points.
Given a set of knots whose x- and y- coordinates are in `x_data` and `y_d... | 25,924 |
def login(token_path: str) -> Optional[Credentials]:
"""
Trigger the authentication so that we can store a new token.pickle.
"""
flow = InstalledAppFlow.from_client_secrets_file(
'gcal/credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next ru... | 25,925 |
def get_auth_token(context, scope):
"""
Get a token from the auth service to allow access to a service
:param context: context of the test
:return: the token
"""
secret = get_client_secret(context)
data = {
'grant_type': 'client_credentials',
'scope': scope
}
respons... | 25,926 |
def getDefaultFontFamily():
"""Returns the default font family of the application"""
return qt.QApplication.instance().font().family() | 25,927 |
def result(a, b, operator):
"""This function return result"""
lambda_ops = {
"+": (lambda x,y: x+y),
"-": (lambda x,y: x-y),
"*": (lambda x,y: x*y),
"/": (lambda x,y: x/y),
"//": (lambda x,y: x//y),
"%": (lambda x,y: x%y),
}
r = False
error = ''
... | 25,928 |
def batched_nms(boxes, scores, idxs, nms_cfg, class_agnostic=False):
"""Performs non-maximum suppression in a batched fashion.
Modified from https://github.com/pytorch/vision/blob
/505cd6957711af790211896d32b40291bea1bc21/torchvision/ops/boxes.py#L39.
In order to perform NMS independently per class, we... | 25,929 |
def get_deconv_filter(f_shape):
"""
reference: https://github.com/MarvinTeichmann/tensorflow-fcn
"""
width = f_shape[0]
heigh = f_shape[0]
f = ceil(width/2.0)
c = (2 * f - 1 - f % 2) / (2.0 * f)
bilinear = np.zeros([f_shape[0], f_shape[1]])
for x in range(width):
for y in range... | 25,930 |
def twitter_split_handle_from_txt(tweet):
"""
Looks for RT @twitterhandle: or just @twitterhandle in the beginning of the tweet.
The handle is split off and returned as two separate strings.
:param tweet: (str)
The tweet text to split.
:return: (str, str)
twitter_handle, rest_of_t... | 25,931 |
def points(piece_list):
"""Calculating point differential for the given board state"""
# Args: (1) piece list
# Returns: differential (white points - black points)
# The points are calculated via the standard chess value system:
# Pawn = 1, King = 3, Bishop = 3, Rook = 5, Queen = 9
# King = 100 (arbitrarily la... | 25,932 |
def grid_sampler(x, grid, name=None):
"""
:alias_main: paddle.nn.functional.grid_sampler
:alias: paddle.nn.functional.grid_sampler,paddle.nn.functional.vision.grid_sampler
:old_api: paddle.fluid.layers.grid_sampler
This operation samples input X by using bilinear interpolation based on
flow field gri... | 25,933 |
def _write_results(proto, xid=None):
"""Writes the prediction, ground truth, and representation to disk."""
key, s = proto
p = results_pb2.Results.FromString(s)
if xid is None:
dir_out = FLAGS.input_dir + '/extracted/' + key + '/'
else:
dir_out = FLAGS.input_dir + '/extracted/XID%i/%s/' % (xid,... | 25,934 |
def fpack (filename):
"""fpack fits images; skip fits tables"""
try:
# fits check if extension is .fits and not an LDAC fits file
if filename.split('.')[-1] == 'fits' and '_ldac.fits' not in filename:
header = read_hdulist(filename, get_data=False, get_header=True,
... | 25,935 |
def SpecSwitch(spec_id):
"""
Create hotkey function that switches hotkey spec.
:param spec_id: Hotkey spec ID or index.
:return: Hotkey function.
"""
# Create hotkey function that switches hotkey spec
func = partial(spec_switch, spec_id)
# Add `call in main thread` tag
func = tag_... | 25,936 |
async def eliminate(ctx):
"""GM Only: Eliminate a country"""
if ctx.message.author == gm:
with session_scope() as session:
command, country = ctx.message.content.split(" ")
row = session.query(Movelist).filter(Movelist.country == country).one_or_none()
if row is None:... | 25,937 |
def get_package_version() -> str:
"""Returns the package version."""
metadata = importlib_metadata.metadata(PACKAGE_NAME) # type: ignore
version = metadata["Version"]
return version | 25,938 |
def safe_name(dbname):
"""Returns a database name with non letter, digit, _ characters removed."""
char_list = [c for c in dbname if c.isalnum() or c == '_']
return "".join(char_list) | 25,939 |
def _parse_mro(mro_file_name):
"""Parse an MRO file into python objects."""
# A few helpful pyparsing constants
EQUALS, SEMI, LBRACE, RBRACE, LPAREN, RPAREN = map(pp.Suppress, '=;{}()')
mro_label = pp.Word(pp.alphanums + '_')
mro_modifier = pp.oneOf(["in", "out", "src"])
mro_type = pp.oneOf([
... | 25,940 |
def remove_privilege(self, server, timeout=20):
"""Check that we can remove privilege from a role used
in the external user directory configuration.
"""
node = self.context.node
uid = getuid()
message = "DB::Exception: {user}: Not enough privileges."
exitcode = 241
self.context.ldap_nod... | 25,941 |
def tabulate_stats(stats: rl_common.Stats) -> str:
"""Pretty-prints the statistics in `stats` in a table."""
res = []
for (env_name, (reward_type, reward_path)), vs in stats.items():
for seed, (x, _log_dir) in enumerate(vs):
row = {
"env_name": env_name,
"... | 25,942 |
def test_html_blacklist_dialog():
"""The dialog element is a user-interactive area for performing."""
check_html_output_does_not_contain_tag("""
<p><b>Note:</b> The dialog tag is not supported in Edge.</p>
<p>January <dialog open>This is an open dialog window</dialog></p>
<p>Februar... | 25,943 |
def LLR_binom(k, n, p0, EPS=1E-15):
""" Log likelihood ratio test statistic for the single binomial pdf.
Args:
k : number of counts (numpy array)
n : number of trials
p0 : null hypothesis parameter value
Returns:
individual log-likelihood ratio values
"""
phat = ... | 25,944 |
def concatenate_shifts(shifts):
""" Take the shifts, which are relative to the previous shift,
and sum them up so that all of them are relative to the first."""
# the first shift is 0,0,0
for i in range(2, len(shifts)): # we start at the third
s0 = shifts[i-1]
s1 = shifts[i]
s1.x += s0.x
s1.y +=... | 25,945 |
def users(user_id=None, serialize=True):
"""
The method returns users in a json responses. The json is hashed to increase security.
:param serialize: Serialize helps indicate the format of the response
:param user_id: user id intended to be searched
:return: Json format or plain text depending in ... | 25,946 |
def course_units_my(user):
"""
Get all course units assign to a teacher available persisted in DB
:return: tuple with
- Course units data
- list of success messages
- list of error messages
"""
success = []
data = set([attendance.course_unit for attendance in
... | 25,947 |
def warning(msg: str,
logger: Union[logging.Logger, str] = None,
*args, **kwargs):
""" Log to a given or default logger (if available) with 'WARNING' level.
Args:
msg: message to log.
logger: logger instance or logger name. If not set, default logger
is used ... | 25,948 |
def get_world_size():
"""TODO Add missing docstring."""
if not is_dist_avail_and_initialized():
return 1
return dist.get_world_size() | 25,949 |
def get_namenode_setting(namenode):
"""Function for getting the namenode in input as parameter setting from the configuration file.
Parameters
----------
namenode --> str, the namenode for which you want to get the setting info
Returns
-------
conf['namenodes_setting'][namenode] --... | 25,950 |
def cds(identity: str, sequence: str, **kwargs) -> Tuple[sbol3.Component, sbol3.Sequence]:
"""Creates a Coding Sequence (CDS) Component and its Sequence.
:param identity: The identity of the Component. The identity of Sequence is also identity with the suffix '_seq'.
:param sequence: The DNA sequence of th... | 25,951 |
def all_scenes():
"""List all scenes
Returns:
list of Scene objects
"""
global _scene_json
if _scene_json is None:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "scenes.json")) as fh:
_scene_json = json.loads(fh.read())
ret = []
for s in _scene_json:
ret.append(Sc... | 25,952 |
def calc_innovation(xEst, PEst, y, LMid):
"""
Compute innovation and Kalman gain elements
"""
# Compute predicted observation from state
lm = get_landmark_position_from_state(xEst, LMid)
delta = lm - xEst[0:2]
q = (delta.T @ delta)[0, 0]
y_angle = math.atan2(delta[1, 0], delta[0, 0]) - ... | 25,953 |
def next_key(basekey: str, keys: dict[str, Any]) -> str:
"""Returns the next unused key for basekey in the supplied dictionary.
The first try is `basekey`, followed by `basekey-2`, `basekey-3`, etc
until a free one is found.
"""
if basekey not in keys:
return basekey
i = 2
while f"{... | 25,954 |
def load_mmio_overhead_elimination_map(yaml_path):
"""
Load a previously dumped mmio overhead elimination map
"""
with open(yaml_path, "r") as yaml_file:
res = yaml.safe_load(yaml_file.read())
res_map = {
'overall': res[0]['overall'],
'per_model': res[1]['per_model'],
}
... | 25,955 |
def execute(pagename, request):
""" Handle "action=diff"
checking for either a "rev=formerrevision" parameter
or rev1 and rev2 parameters
"""
if not request.user.may.read(pagename):
Page(request, pagename).send_page()
return
try:
date = request.values['date']
... | 25,956 |
def SetBmaskName(enum_id, bmask, name):
"""
Set bitmask name (only for bitfields)
@param enum_id: id of enum
@param bmask: bitmask of the constant
@param name: name of bitmask
@return: 1-ok, 0-failed
"""
return idaapi.set_bmask_name(enum_id, bmask, name) | 25,957 |
def angle_to(x: int, y: int) -> int:
"""Return angle for given vector pointing from orign (0,0), adjusted for north=0"""
#xt,yt = y,x
#rad = math.atan2(yt,xt)
rad = math.atan2(x,y)
if rad < 0.0:
rad = math.pi + (math.pi + rad)
return rad | 25,958 |
def sp_args():
"""Apply quirks for `subprocess.Popen` to have standard behavior in PyInstaller-frozen windows binary.
Returns
-------
dict[str, str or bool or None]
The additional arguments for `subprocess` calls.
"""
if sys.platform.startswith('win32'):
# Prevent Windows from... | 25,959 |
def adj(triples, num_nodes, num_rels, cuda=False, vertical=True):
"""
Computes a sparse adjacency matrix for the given graph (the adjacency matrices of all
relations are stacked vertically).
:param edges: List representing the triples
:param i2r: list of relations
:param i2n: list of nodes... | 25,960 |
def join_b2_path(b2_dir, b2_name):
"""
Like os.path.join, but for B2 file names where the root directory is called ''.
:param b2_dir: a directory path
:type b2_dir: str
:param b2_name: a file name
:type b2_name: str
"""
if b2_dir == '':
return b2_name
else:
return b2... | 25,961 |
def actual_line_flux(wavelength,flux, center=None,pass_it=True):
"""Measure actual line flux:
parameters
----------
wavelength: float array
flux: float array
center: float
wavelength to center plot on
output parameters
-----------------
flux in line integrated over ... | 25,962 |
def _too_many_contigs(ref_file):
"""Check for more contigs than the maximum samblaster deduplication supports.
"""
max_contigs = 32768
return len(list(ref.file_contigs(ref_file))) >= max_contigs | 25,963 |
def read(ctx, file):
"""
Display records in human-readable form
:param ctx: shared context
:param file: record to be displayed
"""
frames = rdpcap(file)
for frame in frames:
show_hex(frame)
frame[ZWaveReq].show()
print '\n' | 25,964 |
def survival_regression_metric(metric, outcomes_train, outcomes_test,
predictions, times):
"""Compute metrics to assess survival model performance.
Parameters
-----------
metric: string
Measure used to assess the survival regression model performance.
Options include:... | 25,965 |
def check_line_length(fn, lines):
"""Check for line length; this checker is not run by default."""
for lno, line in enumerate(lines):
if len(line) > 81:
# don't complain about tables, links and function signatures
if line.lstrip()[0] not in '+|' and \
'http://' not... | 25,966 |
def _get_all_valid_corners(img_arr, crop_size, l_thresh, corner_thresh):
"""Get all valid corners for random cropping"""
valid_pix = img_arr >= l_thresh
kernel = np.ones((crop_size, crop_size))
conv = signal.correlate2d(valid_pix, kernel, mode='valid')
return conv > (corner_thresh * crop_size ** ... | 25,967 |
async def test_get_method_raises_an_error_without_lti13_private_key(
make_mock_request_handler,
):
"""
Is an environment error raised if the LTI13_PRIVATE_KEY env var is not set
after calling the handler's method?
"""
handler = make_mock_request_handler(RequestHandler)
config_handler = LTI13... | 25,968 |
def remove_dup(a):
""" remove duplicates using extra array """
res = []
count = 0
for i in range(0, len(a)-1):
if a[i] != a[i+1]:
res.append(a[i])
count = count + 1
res.append(a[len(a)-1])
print('Total count of unique elements: {}'.format(count + 1))
return ... | 25,969 |
def mjd2crnum(mjd):
"""
Converts MJD to Carrington Rotation number
Mathew Owens, 16/10/20
"""
return 1750 + ((mjd-45871.41)/27.2753) | 25,970 |
def poly_print_simple(poly,pretty=False):
"""Show the polynomial in descending form as it would be written"""
# Get the degree of the polynomial in case it is in non-normal form
d = poly.degree()
if d == -1:
return f"0"
out = ""
# Step through the ascending list of co... | 25,971 |
def download_junit(db, threads, client_class):
"""Download junit results for builds without them."""
logging.info('Downloading JUnit artifacts.')
sys.stdout.flush()
builds_to_grab = db.get_builds_missing_junit()
pool = None
if threads > 1:
pool = multiprocessing.pool.ThreadPool(
... | 25,972 |
def parse_file_():
"""
Retrieves the parsed information by specifying the file, the timestamp and latitude + longitude. Don't forget
to encode the plus sign '+' = %2B!
Example: GET /parse/data/ecmwf/an-2017-09-14.grib?timestamp=2017-09-16T15:21:20%2B00:00&lat=48.398400&lon=9.591550
:param fileName:... | 25,973 |
def make_model(drc_csv: str, sat_tables: list, sector_info_csv: str,
ia_tables=None, units_csv='', compartments_csv='',
locations_csv='') -> model.Model:
"""
Creates a full EE-IO model with all information required for calculations,
JSON-LD export, validation, etc.
:param ... | 25,974 |
def newNXentry(parent, name):
"""Create new NXentry group.
Args:
parent (h5py.File or h5py.Group): hdf5 file handle or group
group (str): group name without extension (str)
Returns:
hdf5.Group: new NXentry group
"""
grp = parent.create_group(name)
grp.attrs["NX_class"]... | 25,975 |
def list_files(path: str, excluded: List[str]) -> Iterable[str]:
"""List relative file paths inside the given path."""
excluded = {os.path.abspath(x) for x in excluded}
for root, dirs, files in os.walk(path):
abs_root = os.path.abspath(root)
for d in list(dirs):
if os.path.join(a... | 25,976 |
def _build_europe_gas_day_tzinfo():
"""
Build the Europe/Gas_Day based on the CET time.
:raises ValueError: When something is wrong with the CET/CEST definition
"""
zone = 'Europe/Gas_Day'
transitions = _get_transitions()
transition_info_cet = _get_transition_info_cet()
difference_sec ... | 25,977 |
def prepare_variants_relations_data(
queryset: "QuerySet",
fields: Set[str],
attribute_ids: Optional[List[int]],
warehouse_ids: Optional[List[int]],
) -> Dict[int, Dict[str, str]]:
"""Prepare data about variants relation fields for given queryset.
It return dict where key is a product pk, value... | 25,978 |
def vnorm(velocity, window_size):
"""
Normalize velocity with latest window data.
- Note that std is not divided. Only subtract mean
- data should have dimension 3.
"""
v = velocity
N = v.shape[1]
if v.dim() != 3:
print("velocity's dim must be 3 for batch operation")... | 25,979 |
def valid_collate_fn(data):
"""Build mini-batch tensors from a list of (image, caption) tuples.
Args:
data: list of (image, caption) tuple.
- image: torch tensor of shape (3, 256, 256).
- caption: torch tensor of shape (?); variable length.
Returns:
images: torch ten... | 25,980 |
def parse_statement(tokens):
"""
statement:
| 'while' statement_list 'do' statement_list 'end'
| 'while' statement_list 'do' 'end'
| 'if' if_body
| num_literal
| string_literal
| builtin
| identifier
"""
if tokens.consume_maybe("while"):
condition = parse_... | 25,981 |
def test_positive_enrich_observe_observables_relationships(
module_headers, observable, observable_type):
""" Perform testing for enrich observe observables endpoint to get
relationships for observable Qualys module
ID: CCTRI-798-bcb33509-c153-4436-93c3-7345e7704b9d
Steps:
1. Send requ... | 25,982 |
def vector_to_pytree_fun(func):
"""Make a pytree -> pytree function from a vector -> vector function."""
def wrapper(state):
return func(Vector(state)).pytree
return wrapper | 25,983 |
def _write_exif_data(
self,
filepath,
use_albums_as_keywords=False,
use_persons_as_keywords=False,
keyword_template=None,
description_template=None,
ignore_date_modified=False,
):
""" write exif data to image file at filepath
Args:
filepath: full path to the image file
... | 25,984 |
def test_convertOrbitalElements_hyperbolic():
"""
Read the test dataset for cartesian and keplerian states for each hyperbolic orbit target at each T0.
Using THOR convert the cartesian states to keplerian states, and convert the keplerian states
to cartesian states. Then compare how well the converted s... | 25,985 |
def _filter_contacts(people_filter, maillist_filter, qs, values):
"""Helper for filtering based on subclassed contacts.
Runs the filter on separately on each subclass (field defined by argument,
the same values are used), then filters the queryset to only keep items
that have matching.
"""
peop... | 25,986 |
def build_uvprojx_element_various_controls(xml_sub_element, xml_tag):
"""
Modify and update UVPROJX various control element
"""
tree = ET.parse(DLG_UVPROJX_NAME)
root = tree.getroot()
updated_data = ""
if (CLEAN_PROJ_ENV == True):
updated_data = DLG_DEFAULT_INCLUDE_PATHS
else:
... | 25,987 |
def viz_property(statement, properties):
"""Create properties for graphviz element"""
if not properties:
return statement + ";";
return statement + "[{}];".format(" ".join(properties)) | 25,988 |
def create_fsl_fnirt_nonlinear_reg(name='fsl_fnirt_nonlinear_reg'):
"""
Performs non-linear registration of an input file to a reference file
using FSL FNIRT.
Parameters
----------
name : string, optional
Name of the workflow.
Returns
-------
nonlinear_register : nipype.pip... | 25,989 |
def _subspace_plot(
inputs, output, *, input_names, output_name, scatter_args=None,
histogram_args=None, min_output=None, max_output=None
):
"""
Do actual plotting
"""
if scatter_args is None:
scatter_args = {}
if histogram_args is None:
histogram_args = {}
if min_output ... | 25,990 |
def preload_template(fname, comment='#'):
"""Preloads a template from a file relative to the calling Python file."""
comment = comment.strip()
if not os.path.isabs(fname):
previous_frame = inspect.currentframe().f_back
caller_fname, _, _, _, _ = inspect.getframeinfo(previous_frame)
... | 25,991 |
def detect_windows_needs_driver(sd, print_reason=False):
"""detect if Windows user needs to install driver for a supported device"""
need_to_install_driver = False
if sd:
system = platform.system()
#print(f'in detect_windows_needs_driver system:{system}')
if system == "Windows":
... | 25,992 |
async def test_non_cachable_zero_ttl(cache: Cache) -> None:
"""
We shouldn't bother caching if the cache TTL is zero.
"""
cache.ttl = 0
scope: Scope = {
"type": "http",
"method": "GET",
"path": "/path",
"headers": [],
}
request = Request(scope)
response = ... | 25,993 |
def compute_footprint(sequence, utilization):
"""
compute the cache footprint
"""
# compute the buffer utilization per stencil
print(r"\ compute the cache footprint of the individual stencils")
for high, stencil in enumerate(sequence):
print("f%" + str(high) + " >= " + str(utilization[st... | 25,994 |
def unload_plugin(name, category=None):
""" remove single plugin
Parameters
----------
name : str
plugin name
category : str
plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {... | 25,995 |
def install_microcode_filter(*args):
"""
install_microcode_filter(filter, install=True)
register/unregister non-standard microcode generator
@param filter: - microcode generator object (C++: microcode_filter_t
*)
@param install: - TRUE - register the object, FALSE - unregister (C++:
... | 25,996 |
def get_marvel_character_embed(attribution_text, result):
"""Parses a given JSON object that contains a result of a Marvel
character and turns it into an Embed
:param attribution_text: The attributions to give to Marvel for using the API
:param result: A JSON object of a Marvel API call result
:r... | 25,997 |
def get_or_create_dfp_targeting_key(name, key_type='FREEFORM'):
"""
Get or create a custom targeting key by name.
Args:
name (str)
Returns:
an integer: the ID of the targeting key
"""
key_id = dfp.get_custom_targeting.get_key_id_by_name(name)
if key_id is None:
key_id = dfp.create_custom_targ... | 25,998 |
def positive(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in positive")
return Array._new(np.positive(x... | 25,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.