nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cagbal/ros_people_object_detection_tensorflow | 982ffd4a54b8059638f5cd4aa167299c7fc9e61f | src/object_detection/models/faster_rcnn_nas_feature_extractor.py | python | FasterRCNNNASFeatureExtractor.preprocess | (self, resized_inputs) | return (2.0 / 255.0) * resized_inputs - 1.0 | Faster R-CNN with NAS preprocessing.
Maps pixel values to the range [-1, 1].
Args:
resized_inputs: A [batch, height_in, width_in, channels] float32 tensor
representing a batch of images with values between 0 and 255.0.
Returns:
preprocessed_inputs: A [batch, height_out, width_out, channels] float32
tensor representing a batch of images. | Faster R-CNN with NAS preprocessing. | [
"Faster",
"R",
"-",
"CNN",
"with",
"NAS",
"preprocessing",
"."
] | def preprocess(self, resized_inputs):
"""Faster R-CNN with NAS preprocessing.
Maps pixel values to the range [-1, 1].
Args:
resized_inputs: A [batch, height_in, width_in, channels] float32 tensor
representing a batch of images with values between 0 and 255.0.
Returns:
preprocessed_inputs: A [batch, height_out, width_out, channels] float32
tensor representing a batch of images.
"""
return (2.0 / 255.0) * resized_inputs - 1.0 | [
"def",
"preprocess",
"(",
"self",
",",
"resized_inputs",
")",
":",
"return",
"(",
"2.0",
"/",
"255.0",
")",
"*",
"resized_inputs",
"-",
"1.0"
] | https://github.com/cagbal/ros_people_object_detection_tensorflow/blob/982ffd4a54b8059638f5cd4aa167299c7fc9e61f/src/object_detection/models/faster_rcnn_nas_feature_extractor.py#L143-L157 | |
haiwen/seahub | e92fcd44e3e46260597d8faa9347cb8222b8b10d | seahub/auth/views.py | python | password_reset_confirm | (request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html',
token_generator=default_token_generator, set_password_form=SetPasswordForm,
post_reset_redirect=None) | return render(request, template_name, context_instance) | View that checks the hash in a password reset link and presents a
form for entering a new password. | View that checks the hash in a password reset link and presents a
form for entering a new password. | [
"View",
"that",
"checks",
"the",
"hash",
"in",
"a",
"password",
"reset",
"link",
"and",
"presents",
"a",
"form",
"for",
"entering",
"a",
"new",
"password",
"."
] | def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html',
token_generator=default_token_generator, set_password_form=SetPasswordForm,
post_reset_redirect=None):
"""
View that checks the hash in a password reset link and presents a
form for entering a new password.
"""
assert uidb36 is not None and token is not None # checked by URLconf
if post_reset_redirect is None:
post_reset_redirect = reverse('auth_password_reset_complete')
try:
uid_int = base36_to_int(uidb36)
user = User.objects.get(id=uid_int)
except (ValueError, User.DoesNotExist):
user = None
context_instance = {}
if token_generator.check_token(user, token):
context_instance['validlink'] = True
if request.method == 'POST':
form = set_password_form(user, request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(post_reset_redirect)
else:
form = set_password_form(None)
else:
context_instance['validlink'] = False
form = None
context_instance['form'] = form
return render(request, template_name, context_instance) | [
"def",
"password_reset_confirm",
"(",
"request",
",",
"uidb36",
"=",
"None",
",",
"token",
"=",
"None",
",",
"template_name",
"=",
"'registration/password_reset_confirm.html'",
",",
"token_generator",
"=",
"default_token_generator",
",",
"set_password_form",
"=",
"SetPa... | https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/seahub/auth/views.py#L354-L384 | |
smilejay/python | 4fd141161273d3b423544da21c6d1ba720a0b184 | py2018/set_check_localtime.py | python | check_localtime_with_internet | (url) | check local time with internet | check local time with internet | [
"check",
"local",
"time",
"with",
"internet"
] | def check_localtime_with_internet(url):
''' check local time with internet '''
threshold = 2
# use urllib2 in python2; not use requests which need installation
response = urllib2.urlopen(url)
#print response.read()
# 获取http头date部分
ts = response.headers['date']
# 将日期时间字符转化为time
gmt_time = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
# 将GMT时间转换成北京时间
internet_ts = time.mktime(gmt_time)
local_ts = time.mktime(time.gmtime())
if abs(local_ts - internet_ts) <= threshold:
print 'OK. check localtime.'
else:
print 'ERROR! local_ts: %s internet_ts:%s' % (local_ts, internet_ts)
sys.exit(1) | [
"def",
"check_localtime_with_internet",
"(",
"url",
")",
":",
"threshold",
"=",
"2",
"# use urllib2 in python2; not use requests which need installation",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"#print response.read()",
"# 获取http头date部分",
"ts",
"=",
... | https://github.com/smilejay/python/blob/4fd141161273d3b423544da21c6d1ba720a0b184/py2018/set_check_localtime.py#L34-L51 | ||
llSourcell/AI_Artist | 3038c06c2e389b9c919c881c9a169efe2fd7810e | lib/python2.7/site-packages/pip/_vendor/distlib/_backport/sysconfig.py | python | _init_non_posix | (vars) | Initialize the module as appropriate for NT | Initialize the module as appropriate for NT | [
"Initialize",
"the",
"module",
"as",
"appropriate",
"for",
"NT"
] | def _init_non_posix(vars):
"""Initialize the module as appropriate for NT"""
# set basic install directories
vars['LIBDEST'] = get_path('stdlib')
vars['BINLIBDEST'] = get_path('platstdlib')
vars['INCLUDEPY'] = get_path('include')
vars['SO'] = '.pyd'
vars['EXE'] = '.exe'
vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable)) | [
"def",
"_init_non_posix",
"(",
"vars",
")",
":",
"# set basic install directories",
"vars",
"[",
"'LIBDEST'",
"]",
"=",
"get_path",
"(",
"'stdlib'",
")",
"vars",
"[",
"'BINLIBDEST'",
"]",
"=",
"get_path",
"(",
"'platstdlib'",
")",
"vars",
"[",
"'INCLUDEPY'",
"... | https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/sysconfig.py#L372-L381 | ||
pulp/pulp | a0a28d804f997b6f81c391378aff2e4c90183df9 | client_lib/pulp/client/extensions/core.py | python | PulpPrompt.render_section | (self, section, tag=TAG_SECTION) | Prints the given text to the screen, wrapping it in standard Pulp
formatting for a section header.
A section header is meant to be used to separate a large amount of
output into different sections. The text passed to this call will
be separated and highlighted to provide a clear break.
For testing verification, this call will result in one instance of
TAG_SECTION being recorded.
:param section: text to format as a paragraph.
:type section: str | Prints the given text to the screen, wrapping it in standard Pulp
formatting for a section header. | [
"Prints",
"the",
"given",
"text",
"to",
"the",
"screen",
"wrapping",
"it",
"in",
"standard",
"Pulp",
"formatting",
"for",
"a",
"section",
"header",
"."
] | def render_section(self, section, tag=TAG_SECTION):
"""
Prints the given text to the screen, wrapping it in standard Pulp
formatting for a section header.
A section header is meant to be used to separate a large amount of
output into different sections. The text passed to this call will
be separated and highlighted to provide a clear break.
For testing verification, this call will result in one instance of
TAG_SECTION being recorded.
:param section: text to format as a paragraph.
:type section: str
"""
self.write(section, tag=tag)
self.write('-' * len(section))
self.render_spacer() | [
"def",
"render_section",
"(",
"self",
",",
"section",
",",
"tag",
"=",
"TAG_SECTION",
")",
":",
"self",
".",
"write",
"(",
"section",
",",
"tag",
"=",
"tag",
")",
"self",
".",
"write",
"(",
"'-'",
"*",
"len",
"(",
"section",
")",
")",
"self",
".",
... | https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/client_lib/pulp/client/extensions/core.py#L116-L134 | ||
CGATOxford/cgat | 326aad4694bdfae8ddc194171bb5d73911243947 | obsolete/pipeline_proj007.py | python | exportCapseqCpGObsExp | ( infile, outfile ) | Export file of GC content | Export file of GC content | [
"Export",
"file",
"of",
"GC",
"content"
] | def exportCapseqCpGObsExp( infile, outfile ):
'''Export file of GC content '''
# Connect to DB
dbhandle = sqlite3.connect( PARAMS["database"] )
track = P.snip( os.path.basename( infile ), ".replicated.capseq.composition.load" ).replace("-","_").replace(".","_")
# Extract data from db
cc = dbhandle.cursor()
query = '''SELECT c.gene_id, c.CpG_ObsExp, cc.CpG_ObsExp, c3.CpG_ObsExp, c5.CpG_ObsExp
FROM %(track)s_replicated_capseq_composition c
left join %(track)s_replicated_composition_control cc on c.gene_id=cc.gene_id
left join %(track)s_replicated_composition_flanking3 c3 on c.gene_id=c3.gene_id
left join %(track)s_replicated_composition_flanking5 c5 on c.gene_id=c5.gene_id;''' % locals()
cc.execute( query )
# Write to file
outs = open( outfile, "w")
for result in cc:
pre = ""
for r in result:
outs.write("%s%s" % (pre, str(r)) )
pre = "\t"
outs.write("\n")
cc.close()
outs.close() | [
"def",
"exportCapseqCpGObsExp",
"(",
"infile",
",",
"outfile",
")",
":",
"# Connect to DB",
"dbhandle",
"=",
"sqlite3",
".",
"connect",
"(",
"PARAMS",
"[",
"\"database\"",
"]",
")",
"track",
"=",
"P",
".",
"snip",
"(",
"os",
".",
"path",
".",
"basename",
... | https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/obsolete/pipeline_proj007.py#L1362-L1384 | ||
crossbario/crossbar | ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64 | crossbar/network/_backend.py | python | Backend._process_block | (self, w3, block_number, Events) | return cnt | :param w3:
:param block_number:
:param Events:
:return: | [] | def _process_block(self, w3, block_number, Events):
"""
:param w3:
:param block_number:
:param Events:
:return:
"""
cnt = 0
# FIXME: we filter by block, and XBRToken/XBRNetwork contract addresses, but
# there are also dynamically created XBRChannel instances (which fire close events)
filter_params = {
'address': [xbr.xbrtoken.address, xbr.xbrnetwork.address],
'fromBlock': block_number,
'toBlock': block_number,
}
result = w3.eth.getLogs(filter_params)
if result:
for evt in result:
receipt = w3.eth.getTransactionReceipt(evt['transactionHash'])
for Event, handler in Events:
# FIXME: MismatchedABI pops up .. we silence this with errors=web3.logs.DISCARD
if hasattr(web3, 'logs') and web3.logs:
all_res = Event().processReceipt(receipt, errors=web3.logs.DISCARD)
else:
all_res = Event().processReceipt(receipt)
for res in all_res:
self.log.info('{handler} processing block {block_number} / txn {txn} with args {args}',
handler=hl(handler.__name__),
block_number=hlid(block_number),
txn=hlid('0x' + binascii.b2a_hex(evt['transactionHash']).decode()),
args=hlval(res.args))
handler(res.transactionHash, res.blockHash, res.args)
cnt += 1
with self._db.begin(write=True) as txn:
block = cfxdb.xbr.block.Block()
block.timestamp = np.datetime64(time_ns(), 'ns')
block.block_number = block_number
# FIXME
# block.block_hash = bytes()
block.cnt_events = cnt
self._xbr.blocks[txn, pack_uint256(block_number)] = block
if cnt:
self.log.info('Processed blockchain block {block_number}: processed {cnt} XBR events.',
block_number=hlid(block_number),
cnt=hlid(cnt))
else:
self.log.info('Processed blockchain block {block_number}: no XBR events found!',
block_number=hlid(block_number))
return cnt | [
"def",
"_process_block",
"(",
"self",
",",
"w3",
",",
"block_number",
",",
"Events",
")",
":",
"cnt",
"=",
"0",
"# FIXME: we filter by block, and XBRToken/XBRNetwork contract addresses, but",
"# there are also dynamically created XBRChannel instances (which fire close events)",
"fi... | https://github.com/crossbario/crossbar/blob/ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64/crossbar/network/_backend.py#L642-L694 | ||
ilastik/ilastik | 6acd2c554bc517e9c8ddad3623a7aaa2e6970c28 | ilastik/applets/dataExport/dataExportGui.py | python | DataExportGui.handleTableSelectionChange | (self) | Any time the user selects a new item, select the whole row. | Any time the user selects a new item, select the whole row. | [
"Any",
"time",
"the",
"user",
"selects",
"a",
"new",
"item",
"select",
"the",
"whole",
"row",
"."
] | def handleTableSelectionChange(self):
"""
Any time the user selects a new item, select the whole row.
"""
self.selectEntireRow()
self.showSelectedDataset() | [
"def",
"handleTableSelectionChange",
"(",
"self",
")",
":",
"self",
".",
"selectEntireRow",
"(",
")",
"self",
".",
"showSelectedDataset",
"(",
")"
] | https://github.com/ilastik/ilastik/blob/6acd2c554bc517e9c8ddad3623a7aaa2e6970c28/ilastik/applets/dataExport/dataExportGui.py#L350-L355 | ||
JacquesLucke/animation_nodes | b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1 | animation_nodes/nodes/generic/data_input.py | python | DataInputNode.setupSocket | (self, socket) | [] | def setupSocket(self, socket):
socket.display.text = True
socket.text = self.assignedType
socket.defaultDrawType = "PREFER_PROPERTY" | [
"def",
"setupSocket",
"(",
"self",
",",
"socket",
")",
":",
"socket",
".",
"display",
".",
"text",
"=",
"True",
"socket",
".",
"text",
"=",
"self",
".",
"assignedType",
"socket",
".",
"defaultDrawType",
"=",
"\"PREFER_PROPERTY\""
] | https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/generic/data_input.py#L26-L29 | ||||
nianticlabs/footprints | dd660dc5922d05cc9e795953791848df5f4e8801 | footprints/datasets/matterport_dataset.py | python | MatterportDataset.__init__ | (self, raw_data_path, training_data_path, filenames, height, width, no_depth_mask,
is_train=False, **kwargs) | Matterport dataset | Matterport dataset | [
"Matterport",
"dataset"
] | def __init__(self, raw_data_path, training_data_path, filenames, height, width, no_depth_mask,
is_train=False, **kwargs):
""" Matterport dataset """
super().__init__(raw_data_path, training_data_path, filenames, height, width, is_train)
self.no_depth_mask = no_depth_mask
self.process_depth_mask = True
self.footprint_threshold = 0.75 | [
"def",
"__init__",
"(",
"self",
",",
"raw_data_path",
",",
"training_data_path",
",",
"filenames",
",",
"height",
",",
"width",
",",
"no_depth_mask",
",",
"is_train",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(... | https://github.com/nianticlabs/footprints/blob/dd660dc5922d05cc9e795953791848df5f4e8801/footprints/datasets/matterport_dataset.py#L22-L29 | ||
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/CPython/27/Lib/multiprocessing/managers.py | python | BaseManager._finalize_manager | (process, address, authkey, state, _Client) | Shutdown the manager process; will be registered as a finalizer | Shutdown the manager process; will be registered as a finalizer | [
"Shutdown",
"the",
"manager",
"process",
";",
"will",
"be",
"registered",
"as",
"a",
"finalizer"
] | def _finalize_manager(process, address, authkey, state, _Client):
'''
Shutdown the manager process; will be registered as a finalizer
'''
if process.is_alive():
util.info('sending shutdown message to manager')
try:
conn = _Client(address, authkey=authkey)
try:
dispatch(conn, None, 'shutdown')
finally:
conn.close()
except Exception:
pass
process.join(timeout=0.2)
if process.is_alive():
util.info('manager still alive')
if hasattr(process, 'terminate'):
util.info('trying to `terminate()` manager process')
process.terminate()
process.join(timeout=0.1)
if process.is_alive():
util.info('manager still alive after terminate')
state.value = State.SHUTDOWN
try:
del BaseProxy._address_to_local[address]
except KeyError:
pass | [
"def",
"_finalize_manager",
"(",
"process",
",",
"address",
",",
"authkey",
",",
"state",
",",
"_Client",
")",
":",
"if",
"process",
".",
"is_alive",
"(",
")",
":",
"util",
".",
"info",
"(",
"'sending shutdown message to manager'",
")",
"try",
":",
"conn",
... | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/multiprocessing/managers.py#L605-L634 | ||
mit-han-lab/data-efficient-gans | 6858275f08f43a33026844c8c2ac4e703e8a07ba | DiffAugment-stylegan2-pytorch/train.py | python | main | (ctx, outdir, dry_run, **config_kwargs) | Train a GAN using the techniques described in the paper
"Training Generative Adversarial Networks with Limited Data".
Examples:
\b
# Train with custom dataset using 1 GPU.
python train.py --outdir=~/training-runs --data=~/mydataset.zip --gpus=1
\b
# Train class-conditional CIFAR-10 using 2 GPUs.
python train.py --outdir=~/training-runs --data=~/datasets/cifar10.zip \\
--gpus=2 --cfg=cifar --cond=1
\b
# Transfer learn MetFaces from FFHQ using 4 GPUs.
python train.py --outdir=~/training-runs --data=~/datasets/metfaces.zip \\
--gpus=4 --cfg=paper1024 --mirror=1 --resume=ffhq1024 --snap=10
\b
# Reproduce original StyleGAN2 config F.
python train.py --outdir=~/training-runs --data=~/datasets/ffhq.zip \\
--gpus=8 --cfg=stylegan2 --mirror=1 --aug=noaug
\b
Base configs (--cfg):
auto Automatically select reasonable defaults based on resolution
and GPU count. Good starting point for new datasets.
stylegan2 Reproduce results for StyleGAN2 config F at 1024x1024.
paper256 Reproduce results for FFHQ and LSUN Cat at 256x256.
paper512 Reproduce results for BreCaHAD and AFHQ at 512x512.
paper1024 Reproduce results for MetFaces at 1024x1024.
cifar Reproduce results for CIFAR-10 at 32x32.
\b
Transfer learning source networks (--resume):
ffhq256 FFHQ trained at 256x256 resolution.
ffhq512 FFHQ trained at 512x512 resolution.
ffhq1024 FFHQ trained at 1024x1024 resolution.
celebahq256 CelebA-HQ trained at 256x256 resolution.
lsundog256 LSUN Dog trained at 256x256 resolution.
<PATH or URL> Custom network pickle. | Train a GAN using the techniques described in the paper
"Training Generative Adversarial Networks with Limited Data". | [
"Train",
"a",
"GAN",
"using",
"the",
"techniques",
"described",
"in",
"the",
"paper",
"Training",
"Generative",
"Adversarial",
"Networks",
"with",
"Limited",
"Data",
"."
] | def main(ctx, outdir, dry_run, **config_kwargs):
"""Train a GAN using the techniques described in the paper
"Training Generative Adversarial Networks with Limited Data".
Examples:
\b
# Train with custom dataset using 1 GPU.
python train.py --outdir=~/training-runs --data=~/mydataset.zip --gpus=1
\b
# Train class-conditional CIFAR-10 using 2 GPUs.
python train.py --outdir=~/training-runs --data=~/datasets/cifar10.zip \\
--gpus=2 --cfg=cifar --cond=1
\b
# Transfer learn MetFaces from FFHQ using 4 GPUs.
python train.py --outdir=~/training-runs --data=~/datasets/metfaces.zip \\
--gpus=4 --cfg=paper1024 --mirror=1 --resume=ffhq1024 --snap=10
\b
# Reproduce original StyleGAN2 config F.
python train.py --outdir=~/training-runs --data=~/datasets/ffhq.zip \\
--gpus=8 --cfg=stylegan2 --mirror=1 --aug=noaug
\b
Base configs (--cfg):
auto Automatically select reasonable defaults based on resolution
and GPU count. Good starting point for new datasets.
stylegan2 Reproduce results for StyleGAN2 config F at 1024x1024.
paper256 Reproduce results for FFHQ and LSUN Cat at 256x256.
paper512 Reproduce results for BreCaHAD and AFHQ at 512x512.
paper1024 Reproduce results for MetFaces at 1024x1024.
cifar Reproduce results for CIFAR-10 at 32x32.
\b
Transfer learning source networks (--resume):
ffhq256 FFHQ trained at 256x256 resolution.
ffhq512 FFHQ trained at 512x512 resolution.
ffhq1024 FFHQ trained at 1024x1024 resolution.
celebahq256 CelebA-HQ trained at 256x256 resolution.
lsundog256 LSUN Dog trained at 256x256 resolution.
<PATH or URL> Custom network pickle.
"""
dnnlib.util.Logger(should_flush=True)
# Setup training options.
try:
run_desc, args = setup_training_loop_kwargs(**config_kwargs)
except UserError as err:
ctx.fail(err)
# Pick output directory.
prev_run_dirs = []
if os.path.isdir(outdir):
prev_run_dirs = [x for x in os.listdir(outdir) if os.path.isdir(os.path.join(outdir, x))]
prev_run_ids = [re.match(r'^\d+', x) for x in prev_run_dirs]
prev_run_ids = [int(x.group()) for x in prev_run_ids if x is not None]
cur_run_id = max(prev_run_ids, default=-1) + 1
args.run_dir = os.path.join(outdir, f'{cur_run_id:05d}-{run_desc}')
assert not os.path.exists(args.run_dir)
# Print options.
print()
print('Training options:')
print(json.dumps(args, indent=2))
print()
print(f'Output directory: {args.run_dir}')
print(f'Training data: {args.training_set_kwargs.path}')
print(f'Training duration: {args.total_kimg} kimg')
print(f'Number of GPUs: {args.num_gpus}')
print(f'Number of images: {args.training_set_kwargs.max_size}')
print(f'Image resolution: {args.training_set_kwargs.resolution}')
print(f'Conditional model: {args.training_set_kwargs.use_labels}')
print(f'Dataset x-flips: {args.training_set_kwargs.xflip}')
print()
# Dry run?
if dry_run:
print('Dry run; exiting.')
return
# Create output directory.
print('Creating output directory...')
os.makedirs(args.run_dir)
with open(os.path.join(args.run_dir, 'training_options.json'), 'wt') as f:
json.dump(args, f, indent=2)
# Launch processes.
print('Launching processes...')
torch.multiprocessing.set_start_method('spawn')
with tempfile.TemporaryDirectory() as temp_dir:
if args.num_gpus == 1:
subprocess_fn(rank=0, args=args, temp_dir=temp_dir)
else:
torch.multiprocessing.spawn(fn=subprocess_fn, args=(args, temp_dir), nprocs=args.num_gpus) | [
"def",
"main",
"(",
"ctx",
",",
"outdir",
",",
"dry_run",
",",
"*",
"*",
"config_kwargs",
")",
":",
"dnnlib",
".",
"util",
".",
"Logger",
"(",
"should_flush",
"=",
"True",
")",
"# Setup training options.",
"try",
":",
"run_desc",
",",
"args",
"=",
"setup... | https://github.com/mit-han-lab/data-efficient-gans/blob/6858275f08f43a33026844c8c2ac4e703e8a07ba/DiffAugment-stylegan2-pytorch/train.py#L454-L549 | ||
bup/bup | ffa1a813b41d59cb3bdcd96429b9cbb3535e2d88 | lib/bup/shquote.py | python | quotesplit | (line) | return l | Split 'line' into a list of offset,word tuples.
The words are produced after removing doublequotes, singlequotes, and
backslash escapes.
Note that this implementation isn't entirely sh-compatible. It only
dequotes words that *start* with a quote character, that is, bytes like
hello"world"
will not have its quotes removed, while bytes like
hello "world"
will be turned into [(0, 'hello'), (6, 'world')] (ie. quotes removed). | Split 'line' into a list of offset,word tuples. | [
"Split",
"line",
"into",
"a",
"list",
"of",
"offset",
"word",
"tuples",
"."
] | def quotesplit(line):
"""Split 'line' into a list of offset,word tuples.
The words are produced after removing doublequotes, singlequotes, and
backslash escapes.
Note that this implementation isn't entirely sh-compatible. It only
dequotes words that *start* with a quote character, that is, bytes like
hello"world"
will not have its quotes removed, while bytes like
hello "world"
will be turned into [(0, 'hello'), (6, 'world')] (ie. quotes removed).
"""
l = []
try:
for i in _quotesplit(line):
l.append(i)
except QuoteError:
pass
return l | [
"def",
"quotesplit",
"(",
"line",
")",
":",
"l",
"=",
"[",
"]",
"try",
":",
"for",
"i",
"in",
"_quotesplit",
"(",
"line",
")",
":",
"l",
".",
"append",
"(",
"i",
")",
"except",
"QuoteError",
":",
"pass",
"return",
"l"
] | https://github.com/bup/bup/blob/ffa1a813b41d59cb3bdcd96429b9cbb3535e2d88/lib/bup/shquote.py#L53-L72 | |
hatRiot/zarp | 2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad | src/lib/scapy/volatile.py | python | RandomEnumeration.next | (self) | [] | def next(self):
while True:
if self.turns == 0 or (self.i == 0 and self.renewkeys):
self.cnt_key = self.rnd.randint(0,2**self.n-1)
self.sbox = [self.rnd.randint(0,self.fsmask) for k in xrange(self.sbox_size)]
self.turns += 1
while self.i < 2**self.n:
ct = self.i^self.cnt_key
self.i += 1
for k in range(self.rounds): # Unbalanced Feistel Network
lsb = ct & self.fsmask
ct >>= self.fs
lsb ^= self.sbox[ct%self.sbox_size]
ct |= lsb << (self.n-self.fs)
if ct < self.top:
return self.inf+ct
self.i = 0
if not self.forever:
raise StopIteration | [
"def",
"next",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"turns",
"==",
"0",
"or",
"(",
"self",
".",
"i",
"==",
"0",
"and",
"self",
".",
"renewkeys",
")",
":",
"self",
".",
"cnt_key",
"=",
"self",
".",
"rnd",
".",
"randint... | https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/volatile.py#L42-L61 | ||||
etetoolkit/ete | 2b207357dc2a40ccad7bfd8f54964472c72e4726 | ete3/tools/ete_build_lib/utils.py | python | rpath | (fullpath) | Returns relative path of a task file (if possible) | Returns relative path of a task file (if possible) | [
"Returns",
"relative",
"path",
"of",
"a",
"task",
"file",
"(",
"if",
"possible",
")"
] | def rpath(fullpath):
'Returns relative path of a task file (if possible)'
m = re.search("/(tasks/.+)", fullpath)
if m:
return m.groups()[0]
else:
return fullpath | [
"def",
"rpath",
"(",
"fullpath",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"\"/(tasks/.+)\"",
",",
"fullpath",
")",
"if",
"m",
":",
"return",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"else",
":",
"return",
"fullpath"
] | https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/tools/ete_build_lib/utils.py#L200-L206 | ||
matrix-org/synapse | 8e57584a5859a9002759963eb546d523d2498a01 | synapse/module_api/__init__.py | python | ModuleApi.public_room_list_manager | (self) | return self._public_room_list_manager | Allows adding to, removing from and checking the status of rooms in the
public room list.
An instance of synapse.module_api.PublicRoomListManager
Added in Synapse v1.22.0. | Allows adding to, removing from and checking the status of rooms in the
public room list. | [
"Allows",
"adding",
"to",
"removing",
"from",
"and",
"checking",
"the",
"status",
"of",
"rooms",
"in",
"the",
"public",
"room",
"list",
"."
] | def public_room_list_manager(self) -> "PublicRoomListManager":
"""Allows adding to, removing from and checking the status of rooms in the
public room list.
An instance of synapse.module_api.PublicRoomListManager
Added in Synapse v1.22.0.
"""
return self._public_room_list_manager | [
"def",
"public_room_list_manager",
"(",
"self",
")",
"->",
"\"PublicRoomListManager\"",
":",
"return",
"self",
".",
"_public_room_list_manager"
] | https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/module_api/__init__.py#L372-L380 | |
manubot/manubot | 7a2a2df1a803420a15d9aeac712c6640a8b6b388 | manubot/process/requests_cache.py | python | RequestsCache.mkdir | (self) | make directory containing cache file if it doesn't exist | make directory containing cache file if it doesn't exist | [
"make",
"directory",
"containing",
"cache",
"file",
"if",
"it",
"doesn",
"t",
"exist"
] | def mkdir(self):
"""make directory containing cache file if it doesn't exist"""
directory = pathlib.Path(self.path).parent
directory.mkdir(parents=True, exist_ok=True) | [
"def",
"mkdir",
"(",
"self",
")",
":",
"directory",
"=",
"pathlib",
".",
"Path",
"(",
"self",
".",
"path",
")",
".",
"parent",
"directory",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")"
] | https://github.com/manubot/manubot/blob/7a2a2df1a803420a15d9aeac712c6640a8b6b388/manubot/process/requests_cache.py#L13-L16 | ||
Sprytile/Sprytile | 6b68d0069aef5bfed6ab40d1d5a94a3382b41619 | rx/concurrency/mainloopscheduler/twistedscheduler.py | python | TwistedScheduler.schedule_absolute | (self, duetime, action, state=None) | return self.schedule_relative(duetime - self.now, action, state) | Schedules an action to be executed at duetime.
Keyword arguments:
duetime -- {datetime} Absolute time after which to execute the action.
action -- {Function} Action to be executed.
Returns {Disposable} The disposable object used to cancel the scheduled
action (best effort). | Schedules an action to be executed at duetime. | [
"Schedules",
"an",
"action",
"to",
"be",
"executed",
"at",
"duetime",
"."
] | def schedule_absolute(self, duetime, action, state=None):
"""Schedules an action to be executed at duetime.
Keyword arguments:
duetime -- {datetime} Absolute time after which to execute the action.
action -- {Function} Action to be executed.
Returns {Disposable} The disposable object used to cancel the scheduled
action (best effort)."""
duetime = self.to_datetime(duetime)
return self.schedule_relative(duetime - self.now, action, state) | [
"def",
"schedule_absolute",
"(",
"self",
",",
"duetime",
",",
"action",
",",
"state",
"=",
"None",
")",
":",
"duetime",
"=",
"self",
".",
"to_datetime",
"(",
"duetime",
")",
"return",
"self",
".",
"schedule_relative",
"(",
"duetime",
"-",
"self",
".",
"n... | https://github.com/Sprytile/Sprytile/blob/6b68d0069aef5bfed6ab40d1d5a94a3382b41619/rx/concurrency/mainloopscheduler/twistedscheduler.py#L50-L61 | |
rdiff-backup/rdiff-backup | 321e0cd6e5e47d4c158a0172e47ab38240a8b653 | src/rdiff_backup/connection.py | python | LowLevelPipeConnection._putiter | (self, iterator, req_num) | Put an iterator through the pipe | Put an iterator through the pipe | [
"Put",
"an",
"iterator",
"through",
"the",
"pipe"
] | def _putiter(self, iterator, req_num):
"""Put an iterator through the pipe"""
self._write(
"i", self._i2b(VirtualFile.new(iterfile.MiscIterToFile(iterator))),
req_num) | [
"def",
"_putiter",
"(",
"self",
",",
"iterator",
",",
"req_num",
")",
":",
"self",
".",
"_write",
"(",
"\"i\"",
",",
"self",
".",
"_i2b",
"(",
"VirtualFile",
".",
"new",
"(",
"iterfile",
".",
"MiscIterToFile",
"(",
"iterator",
")",
")",
")",
",",
"re... | https://github.com/rdiff-backup/rdiff-backup/blob/321e0cd6e5e47d4c158a0172e47ab38240a8b653/src/rdiff_backup/connection.py#L209-L213 | ||
jmcarpenter2/parfit | 6a6a02608cc99741d5ec15fb8ae569dd6d40c071 | parfit/plot.py | python | plot1DGrid | (scores, paramsToPlot, scoreLabel, vrange) | Makes a line plot of scores, over the parameter to plot
:param scores: A list of scores, estimated using scoreModels
:param paramsToPlot: The parameter to plot, chosen automatically by plotScores
:param scoreLabel: The specified score label (dependent on scoring metric used)
:param vrange: The yrange of the plot | Makes a line plot of scores, over the parameter to plot
:param scores: A list of scores, estimated using scoreModels
:param paramsToPlot: The parameter to plot, chosen automatically by plotScores
:param scoreLabel: The specified score label (dependent on scoring metric used)
:param vrange: The yrange of the plot | [
"Makes",
"a",
"line",
"plot",
"of",
"scores",
"over",
"the",
"parameter",
"to",
"plot",
":",
"param",
"scores",
":",
"A",
"list",
"of",
"scores",
"estimated",
"using",
"scoreModels",
":",
"param",
"paramsToPlot",
":",
"The",
"parameter",
"to",
"plot",
"cho... | def plot1DGrid(scores, paramsToPlot, scoreLabel, vrange):
"""
Makes a line plot of scores, over the parameter to plot
:param scores: A list of scores, estimated using scoreModels
:param paramsToPlot: The parameter to plot, chosen automatically by plotScores
:param scoreLabel: The specified score label (dependent on scoring metric used)
:param vrange: The yrange of the plot
"""
key = list(paramsToPlot.keys())
plt.figure(figsize=(int(round(len(paramsToPlot[key[0]]) / 1.33)), 6))
plt.plot(np.linspace(0, len(paramsToPlot[key[0]]), len(scores)), scores, "-or")
plt.xlabel(key[0])
plt.xticks(np.linspace(0, len(paramsToPlot[key[0]]), len(scores)), paramsToPlot[key[0]])
if scoreLabel is not None:
plt.ylabel(scoreLabel)
else:
plt.ylabel("Score")
if vrange is not None:
plt.ylim(vrange[0], vrange[1])
plt.box(on=False)
plt.show() | [
"def",
"plot1DGrid",
"(",
"scores",
",",
"paramsToPlot",
",",
"scoreLabel",
",",
"vrange",
")",
":",
"key",
"=",
"list",
"(",
"paramsToPlot",
".",
"keys",
"(",
")",
")",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"int",
"(",
"round",
"(",
"len",... | https://github.com/jmcarpenter2/parfit/blob/6a6a02608cc99741d5ec15fb8ae569dd6d40c071/parfit/plot.py#L12-L32 | ||
HuangYG123/CurricularFace | 68c8727fb7cd2243ecbfd7e09c35efc87c6e2de4 | util/verification.py | python | calculate_val_far | (threshold, dist, actual_issame) | return val, far | [] | def calculate_val_far(threshold, dist, actual_issame):
predict_issame = np.less(dist, threshold)
true_accept = np.sum(np.logical_and(predict_issame, actual_issame))
false_accept = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))
n_same = np.sum(actual_issame)
n_diff = np.sum(np.logical_not(actual_issame))
val = float(true_accept) / float(n_same)
far = float(false_accept) / float(n_diff)
return val, far | [
"def",
"calculate_val_far",
"(",
"threshold",
",",
"dist",
",",
"actual_issame",
")",
":",
"predict_issame",
"=",
"np",
".",
"less",
"(",
"dist",
",",
"threshold",
")",
"true_accept",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"logical_and",
"(",
"predict_issa... | https://github.com/HuangYG123/CurricularFace/blob/68c8727fb7cd2243ecbfd7e09c35efc87c6e2de4/util/verification.py#L155-L163 | |||
edfungus/Crouton | ada98b3930192938a48909072b45cb84b945f875 | clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/werkzeug/wrappers.py | python | BaseRequest.host | (self) | return get_host(self.environ, trusted_hosts=self.trusted_hosts) | Just the host including the port if available.
See also: :attr:`trusted_hosts`. | Just the host including the port if available.
See also: :attr:`trusted_hosts`. | [
"Just",
"the",
"host",
"including",
"the",
"port",
"if",
"available",
".",
"See",
"also",
":",
":",
"attr",
":",
"trusted_hosts",
"."
] | def host(self):
"""Just the host including the port if available.
See also: :attr:`trusted_hosts`.
"""
return get_host(self.environ, trusted_hosts=self.trusted_hosts) | [
"def",
"host",
"(",
"self",
")",
":",
"return",
"get_host",
"(",
"self",
".",
"environ",
",",
"trusted_hosts",
"=",
"self",
".",
"trusted_hosts",
")"
] | https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/werkzeug/wrappers.py#L593-L597 | |
morganstanley/treadmill | f18267c665baf6def4374d21170198f63ff1cde4 | lib/python/treadmill/netdev.py | python | dev_conf_proxy_arp_set | (eth, enabled) | Enable Proxy-Arp on the given device
:param ``str`` eth:
The name of the ethernet device.
:param ``bool`` enabled:
Enable or disable the feature. | Enable Proxy-Arp on the given device | [
"Enable",
"Proxy",
"-",
"Arp",
"on",
"the",
"given",
"device"
] | def dev_conf_proxy_arp_set(eth, enabled):
"""Enable Proxy-Arp on the given device
:param ``str`` eth:
The name of the ethernet device.
:param ``bool`` enabled:
Enable or disable the feature.
"""
_proc_sys_write(
_PROC_CONF_PROXY_ARP.format(dev=eth),
int(enabled),
) | [
"def",
"dev_conf_proxy_arp_set",
"(",
"eth",
",",
"enabled",
")",
":",
"_proc_sys_write",
"(",
"_PROC_CONF_PROXY_ARP",
".",
"format",
"(",
"dev",
"=",
"eth",
")",
",",
"int",
"(",
"enabled",
")",
",",
")"
] | https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/netdev.py#L545-L556 | ||
Symbo1/wsltools | 0b6e536fc85c707a1c81f0296c4e91ca835396a1 | wsltools/utils/ipaddr.py | python | IPAddress | (address, version=None) | Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
version: An Integer, 4 or 6. If set, don't try to automatically
determine what the IP address type is. important for things
like IPAddress(1), which could be IPv4, '0.0.0.1', or IPv6,
'::1'.
Returns:
An IPv4Address or IPv6Address object.
Raises:
ValueError: if the string passed isn't either a v4 or a v6
address. | Take an IP string/int and return an object of the correct type. | [
"Take",
"an",
"IP",
"string",
"/",
"int",
"and",
"return",
"an",
"object",
"of",
"the",
"correct",
"type",
"."
] | def IPAddress(address, version=None):
"""Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
version: An Integer, 4 or 6. If set, don't try to automatically
determine what the IP address type is. important for things
like IPAddress(1), which could be IPv4, '0.0.0.1', or IPv6,
'::1'.
Returns:
An IPv4Address or IPv6Address object.
Raises:
ValueError: if the string passed isn't either a v4 or a v6
address.
"""
if version:
if version == 4:
return IPv4Address(address)
elif version == 6:
return IPv6Address(address)
try:
return IPv4Address(address)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Address(address)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
address) | [
"def",
"IPAddress",
"(",
"address",
",",
"version",
"=",
"None",
")",
":",
"if",
"version",
":",
"if",
"version",
"==",
"4",
":",
"return",
"IPv4Address",
"(",
"address",
")",
"elif",
"version",
"==",
"6",
":",
"return",
"IPv6Address",
"(",
"address",
... | https://github.com/Symbo1/wsltools/blob/0b6e536fc85c707a1c81f0296c4e91ca835396a1/wsltools/utils/ipaddr.py#L49-L86 | ||
TDAmeritrade/stumpy | 7c97df98cb4095afae775ab71870d4d5a14776c7 | stumpy/gpu_aamp.py | python | _gpu_aamp | (
T_A_fname,
T_B_fname,
m,
range_stop,
excl_zone,
T_A_subseq_isfinite_fname,
T_B_subseq_isfinite_fname,
T_A_subseq_squared_fname,
T_B_subseq_squared_fname,
QT_fname,
QT_first_fname,
k,
ignore_trivial=True,
range_start=1,
device_id=0,
) | return profile_fname, indices_fname | A Numba CUDA version of AAMP for parallel computation of the non-normalized (i.e.,
without z-normalization) matrix profile, matrix profile indices, left matrix profile
indices, and right matrix profile indices.
Parameters
----------
T_A_fname : str
The file name for the time series or sequence for which to compute
the matrix profile
T_B_fname : str
The file name for the time series or sequence that will be used to annotate T_A.
For every subsequence in T_A, its nearest neighbor in T_B will be recorded.
m : int
Window size
range_stop : int
The index value along T_B for which to stop the matrix profile
calculation. This parameter is here for consistency with the
distributed `stumped` algorithm.
excl_zone : int
The half width for the exclusion zone relative to the current
sliding window
T_A_subseq_isfinite_fname : str
The file name for the boolean array that indicates whether a subsequence in
`T_A` contains a `np.nan`/`np.inf` value (False)
T_B_subseq_isfinite_fname : str
The file name for the boolean array that indicates whether a subsequence in
`T_B` contains a `np.nan`/`np.inf` value (False)
T_A_subseq_squared_fname : str
The file name for the squared subsequences of `T_A`
T_B_subseq_squared_fname : str
The file name for the squared subsequences of `T_B`
QT_fname : str
The file name for the dot product between some query sequence,`Q`,
and time series, `T`
QT_first_fname : str
The file name for the QT for the first window relative to the current
sliding window
k : int
The total number of sliding windows to iterate over
ignore_trivial : bool, default True
Set to `True` if this is a self-join. Otherwise, for AB-join, set this to
`False`. Default is `True`.
range_start : int, default 1
The starting index value along T_B for which to start the matrix
profile calculation. Default is 1.
device_id : int, default 0
The (GPU) device number to use. The default value is `0`.
Returns
-------
profile_fname : str
The file name for the matrix profile
indices_fname : str
The file name for the matrix profile indices. The first column of the
array consists of the matrix profile indices, the second column consists
of the left matrix profile indices, and the third column consists of the
right matrix profile indices.
Notes
-----
`arXiv:1901.05708 \
<https://arxiv.org/pdf/1901.05708.pdf>`__
See Algorithm 1
Note that we have extended this algorithm for AB-joins as well.
`DOI: 10.1109/ICDM.2016.0085 \
<https://www.cs.ucr.edu/~eamonn/STOMP_GPU_final_submission_camera_ready.pdf>`__
See Table II, Figure 5, and Figure 6 | A Numba CUDA version of AAMP for parallel computation of the non-normalized (i.e.,
without z-normalization) matrix profile, matrix profile indices, left matrix profile
indices, and right matrix profile indices. | [
"A",
"Numba",
"CUDA",
"version",
"of",
"AAMP",
"for",
"parallel",
"computation",
"of",
"the",
"non",
"-",
"normalized",
"(",
"i",
".",
"e",
".",
"without",
"z",
"-",
"normalization",
")",
"matrix",
"profile",
"matrix",
"profile",
"indices",
"left",
"matrix... | def _gpu_aamp(
T_A_fname,
T_B_fname,
m,
range_stop,
excl_zone,
T_A_subseq_isfinite_fname,
T_B_subseq_isfinite_fname,
T_A_subseq_squared_fname,
T_B_subseq_squared_fname,
QT_fname,
QT_first_fname,
k,
ignore_trivial=True,
range_start=1,
device_id=0,
):
"""
A Numba CUDA version of AAMP for parallel computation of the non-normalized (i.e.,
without z-normalization) matrix profile, matrix profile indices, left matrix profile
indices, and right matrix profile indices.
Parameters
----------
T_A_fname : str
The file name for the time series or sequence for which to compute
the matrix profile
T_B_fname : str
The file name for the time series or sequence that will be used to annotate T_A.
For every subsequence in T_A, its nearest neighbor in T_B will be recorded.
m : int
Window size
range_stop : int
The index value along T_B for which to stop the matrix profile
calculation. This parameter is here for consistency with the
distributed `stumped` algorithm.
excl_zone : int
The half width for the exclusion zone relative to the current
sliding window
T_A_subseq_isfinite_fname : str
The file name for the boolean array that indicates whether a subsequence in
`T_A` contains a `np.nan`/`np.inf` value (False)
T_B_subseq_isfinite_fname : str
The file name for the boolean array that indicates whether a subsequence in
`T_B` contains a `np.nan`/`np.inf` value (False)
T_A_subseq_squared_fname : str
The file name for the squared subsequences of `T_A`
T_B_subseq_squared_fname : str
The file name for the squared subsequences of `T_B`
QT_fname : str
The file name for the dot product between some query sequence,`Q`,
and time series, `T`
QT_first_fname : str
The file name for the QT for the first window relative to the current
sliding window
k : int
The total number of sliding windows to iterate over
ignore_trivial : bool, default True
Set to `True` if this is a self-join. Otherwise, for AB-join, set this to
`False`. Default is `True`.
range_start : int, default 1
The starting index value along T_B for which to start the matrix
profile calculation. Default is 1.
device_id : int, default 0
The (GPU) device number to use. The default value is `0`.
Returns
-------
profile_fname : str
The file name for the matrix profile
indices_fname : str
The file name for the matrix profile indices. The first column of the
array consists of the matrix profile indices, the second column consists
of the left matrix profile indices, and the third column consists of the
right matrix profile indices.
Notes
-----
`arXiv:1901.05708 \
<https://arxiv.org/pdf/1901.05708.pdf>`__
See Algorithm 1
Note that we have extended this algorithm for AB-joins as well.
`DOI: 10.1109/ICDM.2016.0085 \
<https://www.cs.ucr.edu/~eamonn/STOMP_GPU_final_submission_camera_ready.pdf>`__
See Table II, Figure 5, and Figure 6
"""
threads_per_block = config.STUMPY_THREADS_PER_BLOCK
blocks_per_grid = math.ceil(k / threads_per_block)
T_A = np.load(T_A_fname, allow_pickle=False)
T_B = np.load(T_B_fname, allow_pickle=False)
QT = np.load(QT_fname, allow_pickle=False)
QT_first = np.load(QT_first_fname, allow_pickle=False)
T_A_subseq_isfinite = np.load(T_A_subseq_isfinite_fname, allow_pickle=False)
T_B_subseq_isfinite = np.load(T_B_subseq_isfinite_fname, allow_pickle=False)
T_A_subseq_squared = np.load(T_A_subseq_squared_fname, allow_pickle=False)
T_B_subseq_squared = np.load(T_B_subseq_squared_fname, allow_pickle=False)
with cuda.gpus[device_id]:
device_T_A = cuda.to_device(T_A)
device_T_A_subseq_isfinite = cuda.to_device(T_A_subseq_isfinite)
device_T_A_subseq_squared = cuda.to_device(T_A_subseq_squared)
device_QT_odd = cuda.to_device(QT)
device_QT_even = cuda.to_device(QT)
device_QT_first = cuda.to_device(QT_first)
if ignore_trivial:
device_T_B = device_T_A
device_T_B_subseq_isfinite = device_T_A_subseq_isfinite
device_T_B_subseq_squared = device_T_A_subseq_squared
else:
device_T_B = cuda.to_device(T_B)
device_T_B_subseq_isfinite = cuda.to_device(T_B_subseq_isfinite)
device_T_B_subseq_squared = cuda.to_device(T_B_subseq_squared)
profile = np.full((k, 3), np.inf, dtype=np.float64)
indices = np.full((k, 3), -1, dtype=np.int64)
device_profile = cuda.to_device(profile)
device_indices = cuda.to_device(indices)
_compute_and_update_PI_kernel[blocks_per_grid, threads_per_block](
range_start - 1,
device_T_A,
device_T_B,
m,
device_QT_even,
device_QT_odd,
device_QT_first,
device_T_A_subseq_isfinite,
device_T_B_subseq_isfinite,
device_T_A_subseq_squared,
device_T_B_subseq_squared,
k,
ignore_trivial,
excl_zone,
device_profile,
device_indices,
False,
)
for i in range(range_start, range_stop):
_compute_and_update_PI_kernel[blocks_per_grid, threads_per_block](
i,
device_T_A,
device_T_B,
m,
device_QT_even,
device_QT_odd,
device_QT_first,
device_T_A_subseq_isfinite,
device_T_B_subseq_isfinite,
device_T_A_subseq_squared,
device_T_B_subseq_squared,
k,
ignore_trivial,
excl_zone,
device_profile,
device_indices,
True,
)
profile = device_profile.copy_to_host()
indices = device_indices.copy_to_host()
profile = np.sqrt(profile)
profile_fname = core.array_to_temp_file(profile)
indices_fname = core.array_to_temp_file(indices)
return profile_fname, indices_fname | [
"def",
"_gpu_aamp",
"(",
"T_A_fname",
",",
"T_B_fname",
",",
"m",
",",
"range_stop",
",",
"excl_zone",
",",
"T_A_subseq_isfinite_fname",
",",
"T_B_subseq_isfinite_fname",
",",
"T_A_subseq_squared_fname",
",",
"T_B_subseq_squared_fname",
",",
"QT_fname",
",",
"QT_first_f... | https://github.com/TDAmeritrade/stumpy/blob/7c97df98cb4095afae775ab71870d4d5a14776c7/stumpy/gpu_aamp.py#L170-L356 | |
unknown-horizons/unknown-horizons | 7397fb333006d26c3d9fe796c7bd9cb8c3b43a49 | horizons/world/units/unit.py | python | Unit.draw_health | (self, remove_only=False, auto_remove=False) | Draws the units current health as a healthbar over the unit. | Draws the units current health as a healthbar over the unit. | [
"Draws",
"the",
"units",
"current",
"health",
"as",
"a",
"healthbar",
"over",
"the",
"unit",
"."
] | def draw_health(self, remove_only=False, auto_remove=False):
"""Draws the units current health as a healthbar over the unit."""
if not self.has_component(HealthComponent):
return
render_name = "health_" + str(self.worldid)
renderer = self.session.view.renderer['GenericRenderer']
renderer.removeAll(render_name)
if remove_only or (auto_remove and not self._last_draw_health_call_on_damage):
# only remove on auto_remove if this health was actually displayed as reacton to _on_damage
# else we might remove something that the user still wants
self._health_displayed = False
return
self._last_draw_health_call_on_damage = False
self._health_displayed = True
health_component = self.get_component(HealthComponent)
health = health_component.health
max_health = health_component.max_health
zoom = self.session.view.zoom
height = int(5 * zoom)
width = int(50 * zoom)
y_pos = int(self.health_bar_y * zoom)
relative_x = int((width * health) // max_health - (width // 2))
# mid_node is the coord separating healthy (green) and damaged (red) quads
mid_node_top = fife.RendererNode(self._instance, fife.Point(relative_x, y_pos - height))
mid_node_btm = fife.RendererNode(self._instance, fife.Point(relative_x, y_pos))
left_upper = fife.RendererNode(self._instance, fife.Point(-width // 2, y_pos - height))
right_upper = fife.RendererNode(self._instance, fife.Point(width // 2, y_pos - height))
left_lower = fife.RendererNode(self._instance, fife.Point(-width // 2, y_pos))
right_lower = fife.RendererNode(self._instance, fife.Point(width // 2, y_pos))
if health > 0: # draw healthy part of health bar
renderer.addQuad(render_name,
left_upper,
left_lower,
mid_node_btm,
mid_node_top,
0, 255, 0)
if health < max_health: # draw damaged part
renderer.addQuad(render_name,
mid_node_top,
mid_node_btm,
right_lower,
right_upper,
255, 0, 0) | [
"def",
"draw_health",
"(",
"self",
",",
"remove_only",
"=",
"False",
",",
"auto_remove",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"has_component",
"(",
"HealthComponent",
")",
":",
"return",
"render_name",
"=",
"\"health_\"",
"+",
"str",
"(",
"sel... | https://github.com/unknown-horizons/unknown-horizons/blob/7397fb333006d26c3d9fe796c7bd9cb8c3b43a49/horizons/world/units/unit.py#L125-L169 | ||
dfki-ric/phobos | 63ac5f8496df4d6f0b224878936e8cc45d661854 | phobos/phobossystem.py | python | getBlenderConfigPath | () | return scriptspath | Returns the configuration path for user-specific blender data.
Args:
Returns:
: str -- scripts path | Returns the configuration path for user-specific blender data. | [
"Returns",
"the",
"configuration",
"path",
"for",
"user",
"-",
"specific",
"blender",
"data",
"."
] | def getBlenderConfigPath():
"""Returns the configuration path for user-specific blender data.
Args:
Returns:
: str -- scripts path
"""
if sys.platform == 'linux':
scriptspath = path.normpath(
path.expanduser('~/.config/blender/{0}/config'.format(blenderversion))
)
elif sys.platform == 'darwin':
scriptspath = path.normpath(
path.expanduser(
'~/Library/Application Support/Blender/{0}/config'.format(blenderversion)
)
)
elif sys.platform == 'win32':
scriptspath = path.normpath(
path.expanduser(
'~/AppData/Roaming/Blender Foundation/Blender/{0}/config'.format(blenderversion)
)
)
else:
scriptspath = 'ERROR: {0} not supported,'.format(sys.platform)
return scriptspath | [
"def",
"getBlenderConfigPath",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'linux'",
":",
"scriptspath",
"=",
"path",
".",
"normpath",
"(",
"path",
".",
"expanduser",
"(",
"'~/.config/blender/{0}/config'",
".",
"format",
"(",
"blenderversion",
")",
")"... | https://github.com/dfki-ric/phobos/blob/63ac5f8496df4d6f0b224878936e8cc45d661854/phobos/phobossystem.py#L65-L92 | |
mchristopher/PokemonGo-DesktopMap | ec37575f2776ee7d64456e2a1f6b6b78830b4fe0 | app/pywin/Lib/decimal.py | python | Decimal._divide | (self, other, context) | return ans, ans | Return (self // other, self % other), to context.prec precision.
Assumes that neither self nor other is a NaN, that self is not
infinite and that other is nonzero. | Return (self // other, self % other), to context.prec precision. | [
"Return",
"(",
"self",
"//",
"other",
"self",
"%",
"other",
")",
"to",
"context",
".",
"prec",
"precision",
"."
] | def _divide(self, other, context):
"""Return (self // other, self % other), to context.prec precision.
Assumes that neither self nor other is a NaN, that self is not
infinite and that other is nonzero.
"""
sign = self._sign ^ other._sign
if other._isinfinity():
ideal_exp = self._exp
else:
ideal_exp = min(self._exp, other._exp)
expdiff = self.adjusted() - other.adjusted()
if not self or other._isinfinity() or expdiff <= -2:
return (_dec_from_triple(sign, '0', 0),
self._rescale(ideal_exp, context.rounding))
if expdiff <= context.prec:
op1 = _WorkRep(self)
op2 = _WorkRep(other)
if op1.exp >= op2.exp:
op1.int *= 10**(op1.exp - op2.exp)
else:
op2.int *= 10**(op2.exp - op1.exp)
q, r = divmod(op1.int, op2.int)
if q < 10**context.prec:
return (_dec_from_triple(sign, str(q), 0),
_dec_from_triple(self._sign, str(r), ideal_exp))
# Here the quotient is too large to be representable
ans = context._raise_error(DivisionImpossible,
'quotient too large in //, % or divmod')
return ans, ans | [
"def",
"_divide",
"(",
"self",
",",
"other",
",",
"context",
")",
":",
"sign",
"=",
"self",
".",
"_sign",
"^",
"other",
".",
"_sign",
"if",
"other",
".",
"_isinfinity",
"(",
")",
":",
"ideal_exp",
"=",
"self",
".",
"_exp",
"else",
":",
"ideal_exp",
... | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/decimal.py#L1351-L1382 | |
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/packaging/pyparsing.py | python | ParseElementEnhance.__init__ | (self, expr, savelist=False) | [] | def __init__(self, expr, savelist=False):
super(ParseElementEnhance, self).__init__(savelist)
if isinstance(expr, basestring):
if issubclass(self._literalStringClass, Token):
expr = self._literalStringClass(expr)
else:
expr = self._literalStringClass(Literal(expr))
self.expr = expr
self.strRepr = None
if expr is not None:
self.mayIndexError = expr.mayIndexError
self.mayReturnEmpty = expr.mayReturnEmpty
self.setWhitespaceChars(expr.whiteChars)
self.skipWhitespace = expr.skipWhitespace
self.saveAsList = expr.saveAsList
self.callPreparse = expr.callPreparse
self.ignoreExprs.extend(expr.ignoreExprs) | [
"def",
"__init__",
"(",
"self",
",",
"expr",
",",
"savelist",
"=",
"False",
")",
":",
"super",
"(",
"ParseElementEnhance",
",",
"self",
")",
".",
"__init__",
"(",
"savelist",
")",
"if",
"isinstance",
"(",
"expr",
",",
"basestring",
")",
":",
"if",
"iss... | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/packaging/pyparsing.py#L4442-L4458 | ||||
roclark/sportsipy | c19f545d3376d62ded6304b137dc69238ac620a9 | sportsipy/nfl/boxscore.py | python | Boxscore.away_pass_yards | (self) | return self._away_pass_yards | Returns an ``int`` of the number of passing yards the away team gained. | Returns an ``int`` of the number of passing yards the away team gained. | [
"Returns",
"an",
"int",
"of",
"the",
"number",
"of",
"passing",
"yards",
"the",
"away",
"team",
"gained",
"."
] | def away_pass_yards(self):
"""
Returns an ``int`` of the number of passing yards the away team gained.
"""
return self._away_pass_yards | [
"def",
"away_pass_yards",
"(",
"self",
")",
":",
"return",
"self",
".",
"_away_pass_yards"
] | https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/nfl/boxscore.py#L1129-L1133 | |
PlasmaPy/PlasmaPy | 78d63e341216475ce3318e1409296480407c9019 | plasmapy/simulation/particletracker.py | python | ParticleTracker.test_kinetic_energy | (self) | r"""Test conservation of kinetic energy. | r"""Test conservation of kinetic energy. | [
"r",
"Test",
"conservation",
"of",
"kinetic",
"energy",
"."
] | def test_kinetic_energy(self):
r"""Test conservation of kinetic energy."""
assert np.allclose(
self.kinetic_energy_history,
self.kinetic_energy_history.mean(),
atol=3 * self.kinetic_energy_history.std(),
), "Kinetic energy is not conserved!" | [
"def",
"test_kinetic_energy",
"(",
"self",
")",
":",
"assert",
"np",
".",
"allclose",
"(",
"self",
".",
"kinetic_energy_history",
",",
"self",
".",
"kinetic_energy_history",
".",
"mean",
"(",
")",
",",
"atol",
"=",
"3",
"*",
"self",
".",
"kinetic_energy_hist... | https://github.com/PlasmaPy/PlasmaPy/blob/78d63e341216475ce3318e1409296480407c9019/plasmapy/simulation/particletracker.py#L283-L289 | ||
awslabs/aws-lambda-powertools-python | 0c6ac0fe183476140ee1df55fe9fa1cc20925577 | aws_lambda_powertools/utilities/validation/validator.py | python | validate | (
event: Any,
schema: Dict,
formats: Optional[Dict] = None,
envelope: Optional[str] = None,
jmespath_options: Optional[Dict] = None,
) | Standalone function to validate event data using a JSON Schema
Typically used when you need more control over the validation process.
Parameters
----------
event : Dict
Lambda event to be validated
schema : Dict
JSON Schema to validate incoming event
envelope : Dict
JMESPath expression to filter data against
jmespath_options : Dict
Alternative JMESPath options to be included when filtering expr
formats: Dict
Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool
Example
-------
**Validate event**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict)
return event
**Unwrap event before validating against actual payload - using built-in envelopes**
from aws_lambda_powertools.utilities.validation import validate, envelopes
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST)
return event
**Unwrap event before validating against actual payload - using custom JMESPath expression**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="payload[*].my_data")
return event
**Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="Records[*].powertools_json(body)")
return event
**Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))")
return event
**Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** # noqa: E501
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]")
return event
Raises
------
SchemaValidationError
When schema validation fails against data set
InvalidSchemaFormatError
When JSON schema provided is invalid
InvalidEnvelopeExpressionError
When JMESPath expression to unwrap event is invalid | Standalone function to validate event data using a JSON Schema | [
"Standalone",
"function",
"to",
"validate",
"event",
"data",
"using",
"a",
"JSON",
"Schema"
] | def validate(
event: Any,
schema: Dict,
formats: Optional[Dict] = None,
envelope: Optional[str] = None,
jmespath_options: Optional[Dict] = None,
):
"""Standalone function to validate event data using a JSON Schema
Typically used when you need more control over the validation process.
Parameters
----------
event : Dict
Lambda event to be validated
schema : Dict
JSON Schema to validate incoming event
envelope : Dict
JMESPath expression to filter data against
jmespath_options : Dict
Alternative JMESPath options to be included when filtering expr
formats: Dict
Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool
Example
-------
**Validate event**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict)
return event
**Unwrap event before validating against actual payload - using built-in envelopes**
from aws_lambda_powertools.utilities.validation import validate, envelopes
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST)
return event
**Unwrap event before validating against actual payload - using custom JMESPath expression**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="payload[*].my_data")
return event
**Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="Records[*].powertools_json(body)")
return event
**Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions**
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))")
return event
**Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** # noqa: E501
from aws_lambda_powertools.utilities.validation import validate
def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]")
return event
Raises
------
SchemaValidationError
When schema validation fails against data set
InvalidSchemaFormatError
When JSON schema provided is invalid
InvalidEnvelopeExpressionError
When JMESPath expression to unwrap event is invalid
"""
if envelope:
event = jmespath_utils.extract_data_from_envelope(
data=event, envelope=envelope, jmespath_options=jmespath_options
)
validate_data_against_schema(data=event, schema=schema, formats=formats) | [
"def",
"validate",
"(",
"event",
":",
"Any",
",",
"schema",
":",
"Dict",
",",
"formats",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
",",
"envelope",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"jmespath_options",
":",
"Optional",
"[",
"D... | https://github.com/awslabs/aws-lambda-powertools-python/blob/0c6ac0fe183476140ee1df55fe9fa1cc20925577/aws_lambda_powertools/utilities/validation/validator.py#L138-L227 | ||
ales-tsurko/cells | 4cf7e395cd433762bea70cdc863a346f3a6fe1d0 | packaging/macos/python/lib/python3.7/enum.py | python | Flag._create_pseudo_member_ | (cls, value) | return pseudo_member | Create a composite member iff value contains only members. | Create a composite member iff value contains only members. | [
"Create",
"a",
"composite",
"member",
"iff",
"value",
"contains",
"only",
"members",
"."
] | def _create_pseudo_member_(cls, value):
"""
Create a composite member iff value contains only members.
"""
pseudo_member = cls._value2member_map_.get(value, None)
if pseudo_member is None:
# verify all bits are accounted for
_, extra_flags = _decompose(cls, value)
if extra_flags:
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
# construct a singleton enum pseudo-member
pseudo_member = object.__new__(cls)
pseudo_member._name_ = None
pseudo_member._value_ = value
# use setdefault in case another thread already created a composite
# with this value
pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member)
return pseudo_member | [
"def",
"_create_pseudo_member_",
"(",
"cls",
",",
"value",
")",
":",
"pseudo_member",
"=",
"cls",
".",
"_value2member_map_",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"pseudo_member",
"is",
"None",
":",
"# verify all bits are accounted for",
"_",
",",
... | https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/enum.py#L710-L727 | |
larryhastings/gilectomy | 4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a | Lib/asyncio/transports.py | python | WriteTransport.abort | (self) | Close the transport immediately.
Buffered data will be lost. No more data will be received.
The protocol's connection_lost() method will (eventually) be
called with None as its argument. | Close the transport immediately. | [
"Close",
"the",
"transport",
"immediately",
"."
] | def abort(self):
"""Close the transport immediately.
Buffered data will be lost. No more data will be received.
The protocol's connection_lost() method will (eventually) be
called with None as its argument.
"""
raise NotImplementedError | [
"def",
"abort",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/asyncio/transports.py#L115-L122 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/pygments/lexers/webmisc.py | python | XQueryLexer.pushstate_operator_processing_instruction_callback | (lexer, match, ctx) | [] | def pushstate_operator_processing_instruction_callback(lexer, match, ctx):
yield match.start(), String.Doc, match.group(1)
ctx.stack.append('processing_instruction')
lexer.xquery_parse_state.append('operator')
ctx.pos = match.end() | [
"def",
"pushstate_operator_processing_instruction_callback",
"(",
"lexer",
",",
"match",
",",
"ctx",
")",
":",
"yield",
"match",
".",
"start",
"(",
")",
",",
"String",
".",
"Doc",
",",
"match",
".",
"group",
"(",
"1",
")",
"ctx",
".",
"stack",
".",
"appe... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pygments/lexers/webmisc.py#L218-L222 | ||||
cronyo/cronyo | cd5abab0871b68bf31b18aac934303928130a441 | cronyo/vendor/urllib3/util/timeout.py | python | Timeout._validate_timeout | (cls, value, name) | return value | Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated and casted version of the given value.
:raises ValueError: If it is a numeric value less than or equal to
zero, or the type is not an integer, float, or None. | Check that a timeout attribute is valid. | [
"Check",
"that",
"a",
"timeout",
"attribute",
"is",
"valid",
"."
] | def _validate_timeout(cls, value, name):
""" Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated and casted version of the given value.
:raises ValueError: If it is a numeric value less than or equal to
zero, or the type is not an integer, float, or None.
"""
if value is _Default:
return cls.DEFAULT_TIMEOUT
if value is None or value is cls.DEFAULT_TIMEOUT:
return value
if isinstance(value, bool):
raise ValueError(
"Timeout cannot be a boolean value. It must "
"be an int, float or None."
)
try:
float(value)
except (TypeError, ValueError):
raise ValueError(
"Timeout value %s was %s, but it must be an "
"int, float or None." % (name, value)
)
try:
if value <= 0:
raise ValueError(
"Attempted to set %s timeout to %s, but the "
"timeout cannot be set to a value less "
"than or equal to 0." % (name, value)
)
except TypeError:
# Python 3
raise ValueError(
"Timeout value %s was %s, but it must be an "
"int, float or None." % (name, value)
)
return value | [
"def",
"_validate_timeout",
"(",
"cls",
",",
"value",
",",
"name",
")",
":",
"if",
"value",
"is",
"_Default",
":",
"return",
"cls",
".",
"DEFAULT_TIMEOUT",
"if",
"value",
"is",
"None",
"or",
"value",
"is",
"cls",
".",
"DEFAULT_TIMEOUT",
":",
"return",
"v... | https://github.com/cronyo/cronyo/blob/cd5abab0871b68bf31b18aac934303928130a441/cronyo/vendor/urllib3/util/timeout.py#L110-L153 | |
InQuest/omnibus | 88dbf5d02f87eaa79a1cfc13d403cf854ee44c40 | lib/modules/censys.py | python | Plugin.run | (self) | [] | def run(self):
url = 'https://censys.io/api/v1/view/ipv4/%s' % self.artifact['name']
try:
status, response = get(url, auth=(self.api_key['token'], self.api_key['secret']), headers=self.headers)
if status:
self.artifact['data']['censys'] = response.json()
except Exception as err:
warning('Caught exception in module (%s)' % str(err)) | [
"def",
"run",
"(",
"self",
")",
":",
"url",
"=",
"'https://censys.io/api/v1/view/ipv4/%s'",
"%",
"self",
".",
"artifact",
"[",
"'name'",
"]",
"try",
":",
"status",
",",
"response",
"=",
"get",
"(",
"url",
",",
"auth",
"=",
"(",
"self",
".",
"api_key",
... | https://github.com/InQuest/omnibus/blob/88dbf5d02f87eaa79a1cfc13d403cf854ee44c40/lib/modules/censys.py#L23-L31 | ||||
NervanaSystems/ngraph-python | ac032c83c7152b615a9ad129d54d350f9d6a2986 | ngraph/transformers/base.py | python | set_transformer_factory | (factory) | Sets the Transformer factory used by make_transformer
Arguments:
factory (object): Callable object which generates a Transformer | Sets the Transformer factory used by make_transformer | [
"Sets",
"the",
"Transformer",
"factory",
"used",
"by",
"make_transformer"
] | def set_transformer_factory(factory):
"""
Sets the Transformer factory used by make_transformer
Arguments:
factory (object): Callable object which generates a Transformer
"""
global __transformer_factory
__transformer_factory = factory | [
"def",
"set_transformer_factory",
"(",
"factory",
")",
":",
"global",
"__transformer_factory",
"__transformer_factory",
"=",
"factory"
] | https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/transformers/base.py#L817-L825 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.2/django/core/management/__init__.py | python | execute_manager | (settings_mod, argv=None) | Like execute_from_command_line(), but for use by manage.py, a
project-specific django-admin.py utility. | Like execute_from_command_line(), but for use by manage.py, a
project-specific django-admin.py utility. | [
"Like",
"execute_from_command_line",
"()",
"but",
"for",
"use",
"by",
"manage",
".",
"py",
"a",
"project",
"-",
"specific",
"django",
"-",
"admin",
".",
"py",
"utility",
"."
] | def execute_manager(settings_mod, argv=None):
"""
Like execute_from_command_line(), but for use by manage.py, a
project-specific django-admin.py utility.
"""
setup_environ(settings_mod)
utility = ManagementUtility(argv)
utility.execute() | [
"def",
"execute_manager",
"(",
"settings_mod",
",",
"argv",
"=",
"None",
")",
":",
"setup_environ",
"(",
"settings_mod",
")",
"utility",
"=",
"ManagementUtility",
"(",
"argv",
")",
"utility",
".",
"execute",
"(",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/core/management/__init__.py#L431-L438 | ||
Louis-me/appium | 8ebede253e08c71a00273b2ab8411bf983d01469 | Base/BaseLog.py | python | Log.checkPointNG | (self, driver, caseName, checkPoint) | return self.screenshotNG(driver, caseName) | write the case's checkPoint(NG)
:param driver:
:param caseName:
:param checkPoint:
:return: | write the case's checkPoint(NG)
:param driver:
:param caseName:
:param checkPoint:
:return: | [
"write",
"the",
"case",
"s",
"checkPoint",
"(",
"NG",
")",
":",
"param",
"driver",
":",
":",
"param",
"caseName",
":",
":",
"param",
"checkPoint",
":",
":",
"return",
":"
] | def checkPointNG(self, driver, caseName, checkPoint):
"""write the case's checkPoint(NG)
:param driver:
:param caseName:
:param checkPoint:
:return:
"""
self.checkNo += 1
self.logger.info("[CheckPoint_" + str(self.checkNo) + "]: " + checkPoint + ": NG")
# take shot
return self.screenshotNG(driver, caseName) | [
"def",
"checkPointNG",
"(",
"self",
",",
"driver",
",",
"caseName",
",",
"checkPoint",
")",
":",
"self",
".",
"checkNo",
"+=",
"1",
"self",
".",
"logger",
".",
"info",
"(",
"\"[CheckPoint_\"",
"+",
"str",
"(",
"self",
".",
"checkNo",
")",
"+",
"\"]: \"... | https://github.com/Louis-me/appium/blob/8ebede253e08c71a00273b2ab8411bf983d01469/Base/BaseLog.py#L94-L106 | |
Delta-ML/delta | 31dfebc8f20b7cb282b62f291ff25a87e403cc86 | delta/utils/register.py | python | Register.__setitem__ | (self, key, value) | [] | def __setitem__(self, key, value):
if not callable(value):
raise Exception("Value of a Registry must be a callable.")
if key is None:
key = value.__name__
if key in self._dict:
logging.warning("Key %s already in registry %s." % (key, self._name))
self._dict[key] = value | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"callable",
"(",
"value",
")",
":",
"raise",
"Exception",
"(",
"\"Value of a Registry must be a callable.\"",
")",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"value",
".",... | https://github.com/Delta-ML/delta/blob/31dfebc8f20b7cb282b62f291ff25a87e403cc86/delta/utils/register.py#L31-L38 | ||||
evilhero/mylar | dbee01d7e48e8c717afa01b2de1946c5d0b956cb | lib/requests/sessions.py | python | Session.merge_environment_settings | (self, url, proxies, stream, verify, cert) | return {'verify': verify, 'proxies': proxies, 'stream': stream,
'cert': cert} | Check the environment and merge it with some settings. | Check the environment and merge it with some settings. | [
"Check",
"the",
"environment",
"and",
"merge",
"it",
"with",
"some",
"settings",
"."
] | def merge_environment_settings(self, url, proxies, stream, verify, cert):
"""Check the environment and merge it with some settings."""
# Gather clues from the surrounding environment.
if self.trust_env:
# Set environment's proxies.
env_proxies = get_environ_proxies(url) or {}
for (k, v) in env_proxies.items():
proxies.setdefault(k, v)
# Look for requests environment configuration and be compatible
# with cURL.
if verify is True or verify is None:
verify = (os.environ.get('REQUESTS_CA_BUNDLE') or
os.environ.get('CURL_CA_BUNDLE'))
# Merge all the kwargs.
proxies = merge_setting(proxies, self.proxies)
stream = merge_setting(stream, self.stream)
verify = merge_setting(verify, self.verify)
cert = merge_setting(cert, self.cert)
return {'verify': verify, 'proxies': proxies, 'stream': stream,
'cert': cert} | [
"def",
"merge_environment_settings",
"(",
"self",
",",
"url",
",",
"proxies",
",",
"stream",
",",
"verify",
",",
"cert",
")",
":",
"# Gather clues from the surrounding environment.",
"if",
"self",
".",
"trust_env",
":",
"# Set environment's proxies.",
"env_proxies",
"... | https://github.com/evilhero/mylar/blob/dbee01d7e48e8c717afa01b2de1946c5d0b956cb/lib/requests/sessions.py#L609-L631 | |
giantbranch/python-hacker-code | addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d | 我手敲的代码(中文注释)/chapter11/immlib/immlib.py | python | Debugger.searchOnExecute | (self,buf) | return find | Search string in executable memory.
@param buf: Buffer to search for
@return: A list of address where the string was found on memory | Search string in executable memory. | [
"Search",
"string",
"in",
"executable",
"memory",
"."
] | def searchOnExecute(self,buf):
"""
Search string in executable memory.
@param buf: Buffer to search for
@return: A list of address where the string was found on memory
"""
if not buf:
return []
self.getMemoryPages()
find = []
buf_size = len(buf)
for a in self.MemoryPages.keys():
if (MemoryProtection["PAGE_EXECUTE"] == self.MemoryPages[a].access\
or MemoryProtection["PAGE_EXECUTE_READ"] == self.MemoryPages[a].access\
or MemoryProtection["PAGE_EXECUTE_READWRITE"] == self.MemoryPages[a].access\
or MemoryProtection["PAGE_EXECUTE_WRITECOPY"] == self.MemoryPages[a].access):
mem = self.MemoryPages[a].getMemory()
if not mem:
continue
ndx = 0
while 1:
f = mem[ndx:].find( buf )
if f == -1 : break
find.append( ndx + f + a )
ndx += f + buf_size
return find | [
"def",
"searchOnExecute",
"(",
"self",
",",
"buf",
")",
":",
"if",
"not",
"buf",
":",
"return",
"[",
"]",
"self",
".",
"getMemoryPages",
"(",
")",
"find",
"=",
"[",
"]",
"buf_size",
"=",
"len",
"(",
"buf",
")",
"for",
"a",
"in",
"self",
".",
"Mem... | https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/immlib/immlib.py#L2134-L2160 | |
megvii-model/CrowdDetection | 446f8e688fde679e04c35bd1aa1d4d491646f2eb | model/cascade_emd/train.py | python | run_train | () | [] | def run_train():
parser = argparse.ArgumentParser()
parser.add_argument("--divice_num", "-d", default=-1, type=int, help="total number of gpus for training")
parser.add_argument('--resume_weights', '-r', default=None, type=str)
parser.add_argument('--progressbar', '-p', action='store_true', default=False)
args = parser.parse_args()
train(args) | [
"def",
"run_train",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--divice_num\"",
",",
"\"-d\"",
",",
"default",
"=",
"-",
"1",
",",
"type",
"=",
"int",
",",
"help",
"=",
"\"total numbe... | https://github.com/megvii-model/CrowdDetection/blob/446f8e688fde679e04c35bd1aa1d4d491646f2eb/model/cascade_emd/train.py#L154-L160 | ||||
google/jax | bebe9845a873b3203f8050395255f173ba3bbb71 | jax/interpreters/pxla.py | python | make_sharded_device_array | (
aval: ShapedArray,
sharding_spec: Optional[ShardingSpec],
# Any is for JAX extensions implementing their own buffer.
device_buffers: List[Union[Any, xb.xla_client.Buffer]],
indices: Optional[Tuple[Index, ...]] = None,
) | return _ShardedDeviceArray(aval, sharding_spec, device_buffers, indices) | Returns a ShardedDeviceArray implementation based on arguments.
Returns either a C++ SDA or a Python DeviceArray when the buffers are not
JAX buffers.
Args:
aval: The `ShapedArray` for this array.
sharding_spec: If `None`, assumes a pmap-style ShardedDeviceArrays over the
first dimension.
device_buffers: If a list of Jax `Buffer` objects, a C++ SDA will be
returned (if the version is high enough). Otherwise, a Python object will
be returned, for JAX extensions not implementing the C++ API.
indices: For caching purposes, will be computed if `None`. | Returns a ShardedDeviceArray implementation based on arguments. | [
"Returns",
"a",
"ShardedDeviceArray",
"implementation",
"based",
"on",
"arguments",
"."
] | def make_sharded_device_array(
aval: ShapedArray,
sharding_spec: Optional[ShardingSpec],
# Any is for JAX extensions implementing their own buffer.
device_buffers: List[Union[Any, xb.xla_client.Buffer]],
indices: Optional[Tuple[Index, ...]] = None,
):
"""Returns a ShardedDeviceArray implementation based on arguments.
Returns either a C++ SDA or a Python DeviceArray when the buffers are not
JAX buffers.
Args:
aval: The `ShapedArray` for this array.
sharding_spec: If `None`, assumes a pmap-style ShardedDeviceArrays over the
first dimension.
device_buffers: If a list of Jax `Buffer` objects, a C++ SDA will be
returned (if the version is high enough). Otherwise, a Python object will
be returned, for JAX extensions not implementing the C++ API.
indices: For caching purposes, will be computed if `None`.
"""
if sharding_spec is None:
sharded_aval = aval.update(shape=aval.shape[1:])
sharding_spec = _pmap_sharding_spec(aval.shape[0], aval.shape[0], 1, None,
sharded_aval, 0)
if indices is None:
indices = spec_to_indices(aval.shape, sharding_spec)
if (_USE_CPP_SDA and
(not device_buffers or
isinstance(device_buffers[0], xb.xla_client.Buffer))):
return pmap_lib.ShardedDeviceArray.make(
aval, sharding_spec, device_buffers,
indices, aval.weak_type)
return _ShardedDeviceArray(aval, sharding_spec, device_buffers, indices) | [
"def",
"make_sharded_device_array",
"(",
"aval",
":",
"ShapedArray",
",",
"sharding_spec",
":",
"Optional",
"[",
"ShardingSpec",
"]",
",",
"# Any is for JAX extensions implementing their own buffer.",
"device_buffers",
":",
"List",
"[",
"Union",
"[",
"Any",
",",
"xb",
... | https://github.com/google/jax/blob/bebe9845a873b3203f8050395255f173ba3bbb71/jax/interpreters/pxla.py#L487-L523 | |
nameko/nameko | 17ecee2bcfa90cb0f3a2f3328c5004f48e4e02a3 | nameko/rpc.py | python | Responder.send_response | (self, result, exc_info) | return result, exc_info | [] | def send_response(self, result, exc_info):
error = None
if exc_info is not None:
error = serialize(exc_info[1])
# send response encoded the same way as was the request message
content_type = self.message.properties['content_type']
serializer = kombu.serialization.registry.type_to_name[content_type]
# disaster avoidance serialization check: `result` must be
# serializable, otherwise the container will commit suicide assuming
# unrecoverable errors (and the message will be requeued for another
# victim)
try:
kombu.serialization.dumps(result, serializer)
except Exception:
exc_info = sys.exc_info()
# `error` below is guaranteed to serialize to json
error = serialize(UnserializableValueError(result))
result = None
payload = {'result': result, 'error': error}
routing_key = self.message.properties['reply_to']
correlation_id = self.message.properties.get('correlation_id')
publisher = self.publisher_cls(
self.amqp_uri, ssl=self.ssl, login_method=self.login_method
)
publisher.publish(
payload,
serializer=serializer,
exchange=self.exchange,
routing_key=routing_key,
correlation_id=correlation_id
)
return result, exc_info | [
"def",
"send_response",
"(",
"self",
",",
"result",
",",
"exc_info",
")",
":",
"error",
"=",
"None",
"if",
"exc_info",
"is",
"not",
"None",
":",
"error",
"=",
"serialize",
"(",
"exc_info",
"[",
"1",
"]",
")",
"# send response encoded the same way as was the re... | https://github.com/nameko/nameko/blob/17ecee2bcfa90cb0f3a2f3328c5004f48e4e02a3/nameko/rpc.py#L194-L234 | |||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/idlelib/EditorWindow.py | python | EditorWindow._rmcolorizer | (self) | [] | def _rmcolorizer(self):
if not self.color:
return
self.color.removecolors()
self.per.removefilter(self.color)
self.color = None | [
"def",
"_rmcolorizer",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"color",
":",
"return",
"self",
".",
"color",
".",
"removecolors",
"(",
")",
"self",
".",
"per",
".",
"removefilter",
"(",
"self",
".",
"color",
")",
"self",
".",
"color",
"=",
... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/EditorWindow.py#L696-L701 | ||||
ailabx/ailabx | 4a8c701a3604bbc34157167224588041944ac1a2 | codes/qlib-main/qlib/log.py | python | TimeInspector.log_cost_time | (cls, info="Done") | Get last time mark from stack, calculate time diff with current time, and log time diff and info.
:param info: str
Info that will be log into stdout. | Get last time mark from stack, calculate time diff with current time, and log time diff and info.
:param info: str
Info that will be log into stdout. | [
"Get",
"last",
"time",
"mark",
"from",
"stack",
"calculate",
"time",
"diff",
"with",
"current",
"time",
"and",
"log",
"time",
"diff",
"and",
"info",
".",
":",
"param",
"info",
":",
"str",
"Info",
"that",
"will",
"be",
"log",
"into",
"stdout",
"."
] | def log_cost_time(cls, info="Done"):
"""
Get last time mark from stack, calculate time diff with current time, and log time diff and info.
:param info: str
Info that will be log into stdout.
"""
cost_time = time() - cls.time_marks.pop()
cls.timer_logger.info("Time cost: {0:.3f}s | {1}".format(cost_time, info)) | [
"def",
"log_cost_time",
"(",
"cls",
",",
"info",
"=",
"\"Done\"",
")",
":",
"cost_time",
"=",
"time",
"(",
")",
"-",
"cls",
".",
"time_marks",
".",
"pop",
"(",
")",
"cls",
".",
"timer_logger",
".",
"info",
"(",
"\"Time cost: {0:.3f}s | {1}\"",
".",
"form... | https://github.com/ailabx/ailabx/blob/4a8c701a3604bbc34157167224588041944ac1a2/codes/qlib-main/qlib/log.py#L106-L113 | ||
websocket-client/websocket-client | 81fa70d259ce1609b3fb1bf66c8a9bed81a3f28c | websocket/_app.py | python | WebSocketApp._get_close_args | (self, close_frame) | _get_close_args extracts the close code and reason from the close body
if it exists (RFC6455 says WebSocket Connection Close Code is optional) | _get_close_args extracts the close code and reason from the close body
if it exists (RFC6455 says WebSocket Connection Close Code is optional) | [
"_get_close_args",
"extracts",
"the",
"close",
"code",
"and",
"reason",
"from",
"the",
"close",
"body",
"if",
"it",
"exists",
"(",
"RFC6455",
"says",
"WebSocket",
"Connection",
"Close",
"Code",
"is",
"optional",
")"
] | def _get_close_args(self, close_frame):
"""
_get_close_args extracts the close code and reason from the close body
if it exists (RFC6455 says WebSocket Connection Close Code is optional)
"""
# Need to catch the case where close_frame is None
# Otherwise the following if statement causes an error
if not self.on_close or not close_frame:
return [None, None]
# Extract close frame status code
if close_frame.data and len(close_frame.data) >= 2:
close_status_code = 256 * close_frame.data[0] + close_frame.data[1]
reason = close_frame.data[2:].decode('utf-8')
return [close_status_code, reason]
else:
# Most likely reached this because len(close_frame_data.data) < 2
return [None, None] | [
"def",
"_get_close_args",
"(",
"self",
",",
"close_frame",
")",
":",
"# Need to catch the case where close_frame is None",
"# Otherwise the following if statement causes an error",
"if",
"not",
"self",
".",
"on_close",
"or",
"not",
"close_frame",
":",
"return",
"[",
"None",... | https://github.com/websocket-client/websocket-client/blob/81fa70d259ce1609b3fb1bf66c8a9bed81a3f28c/websocket/_app.py#L385-L402 | ||
HunterMcGushion/hyperparameter_hunter | 28b1d48e01a993818510811b82a677e0a7a232b2 | hyperparameter_hunter/utils/version_utils.py | python | Deprecated._verbose_warning | (self) | Issue :attr:`warning`, bypassing the standard filter that silences DeprecationWarnings | Issue :attr:`warning`, bypassing the standard filter that silences DeprecationWarnings | [
"Issue",
":",
"attr",
":",
"warning",
"bypassing",
"the",
"standard",
"filter",
"that",
"silences",
"DeprecationWarnings"
] | def _verbose_warning(self):
"""Issue :attr:`warning`, bypassing the standard filter that silences DeprecationWarnings"""
if self.do_warn:
simplefilter("always", DeprecatedWarning)
simplefilter("always", UnsupportedWarning)
warn(self.warning, category=DeprecationWarning, stacklevel=4)
simplefilter("default", DeprecatedWarning)
simplefilter("default", UnsupportedWarning) | [
"def",
"_verbose_warning",
"(",
"self",
")",
":",
"if",
"self",
".",
"do_warn",
":",
"simplefilter",
"(",
"\"always\"",
",",
"DeprecatedWarning",
")",
"simplefilter",
"(",
"\"always\"",
",",
"UnsupportedWarning",
")",
"warn",
"(",
"self",
".",
"warning",
",",
... | https://github.com/HunterMcGushion/hyperparameter_hunter/blob/28b1d48e01a993818510811b82a677e0a7a232b2/hyperparameter_hunter/utils/version_utils.py#L408-L415 | ||
marcomusy/vedo | 246bb78a406c4f97fe6f7d2a4d460909c830de87 | vedo/base.py | python | BaseActor.N | (self) | return self.inputdata().GetNumberOfPoints() | Retrieve number of points. Shortcut for `NPoints()`. | Retrieve number of points. Shortcut for `NPoints()`. | [
"Retrieve",
"number",
"of",
"points",
".",
"Shortcut",
"for",
"NPoints",
"()",
"."
] | def N(self):
"""Retrieve number of points. Shortcut for `NPoints()`."""
return self.inputdata().GetNumberOfPoints() | [
"def",
"N",
"(",
"self",
")",
":",
"return",
"self",
".",
"inputdata",
"(",
")",
".",
"GetNumberOfPoints",
"(",
")"
] | https://github.com/marcomusy/vedo/blob/246bb78a406c4f97fe6f7d2a4d460909c830de87/vedo/base.py#L753-L755 | |
caktus/django-treenav | 7329a6a5d74e7388e2079ec73147b9981888e4c5 | treenav/templatetags/treenav_tags.py | python | new_context | (parent_context) | Create new context rather than modifying parent context. | Create new context rather than modifying parent context. | [
"Create",
"new",
"context",
"rather",
"than",
"modifying",
"parent",
"context",
"."
] | def new_context(parent_context):
"""Create new context rather than modifying parent context."""
if "request" in parent_context:
return {"request": parent_context["request"]}
else:
return {} | [
"def",
"new_context",
"(",
"parent_context",
")",
":",
"if",
"\"request\"",
"in",
"parent_context",
":",
"return",
"{",
"\"request\"",
":",
"parent_context",
"[",
"\"request\"",
"]",
"}",
"else",
":",
"return",
"{",
"}"
] | https://github.com/caktus/django-treenav/blob/7329a6a5d74e7388e2079ec73147b9981888e4c5/treenav/templatetags/treenav_tags.py#L49-L54 | ||
makehumancommunity/makehuman | 8006cf2cc851624619485658bb933a4244bbfd7c | makehuman/lib/targets.py | python | Component.finish | (self, path) | Finish component as a leaf in the tree (file). | Finish component as a leaf in the tree (file). | [
"Finish",
"component",
"as",
"a",
"leaf",
"in",
"the",
"tree",
"(",
"file",
")",
"."
] | def finish(self, path):
"""
Finish component as a leaf in the tree (file).
"""
self.path = path
for category in self._categories:
if category not in self.data:
self.data[category] = None | [
"def",
"finish",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"path",
"=",
"path",
"for",
"category",
"in",
"self",
".",
"_categories",
":",
"if",
"category",
"not",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"category",
"]",
"="... | https://github.com/makehumancommunity/makehuman/blob/8006cf2cc851624619485658bb933a4244bbfd7c/makehuman/lib/targets.py#L131-L138 | ||
hwwang55/GraphGAN | 3f1c3f7db6b8b5102eea899659d4c52f64c4288c | src/GraphGAN/graph_gan.py | python | GraphGAN.construct_trees | (self, nodes) | return trees | use BFS algorithm to construct the BFS-trees
Args:
nodes: the list of nodes in the graph
Returns:
trees: dict, root_node_id -> tree, where tree is a dict: node_id -> list: [father, child_0, child_1, ...] | use BFS algorithm to construct the BFS-trees | [
"use",
"BFS",
"algorithm",
"to",
"construct",
"the",
"BFS",
"-",
"trees"
] | def construct_trees(self, nodes):
"""use BFS algorithm to construct the BFS-trees
Args:
nodes: the list of nodes in the graph
Returns:
trees: dict, root_node_id -> tree, where tree is a dict: node_id -> list: [father, child_0, child_1, ...]
"""
trees = {}
for root in tqdm.tqdm(nodes):
trees[root] = {}
trees[root][root] = [root]
used_nodes = set()
queue = collections.deque([root])
while len(queue) > 0:
cur_node = queue.popleft()
used_nodes.add(cur_node)
for sub_node in self.graph[cur_node]:
if sub_node not in used_nodes:
trees[root][cur_node].append(sub_node)
trees[root][sub_node] = [cur_node]
queue.append(sub_node)
used_nodes.add(sub_node)
return trees | [
"def",
"construct_trees",
"(",
"self",
",",
"nodes",
")",
":",
"trees",
"=",
"{",
"}",
"for",
"root",
"in",
"tqdm",
".",
"tqdm",
"(",
"nodes",
")",
":",
"trees",
"[",
"root",
"]",
"=",
"{",
"}",
"trees",
"[",
"root",
"]",
"[",
"root",
"]",
"=",... | https://github.com/hwwang55/GraphGAN/blob/3f1c3f7db6b8b5102eea899659d4c52f64c4288c/src/GraphGAN/graph_gan.py#L84-L108 | |
Dozed12/df-style-worldgen | 937455d54f4b02df9c4b10ae6418f4c932fd97bf | libtcodpy.py | python | Bsp.sethor | (self,value) | [] | def sethor(self,value):
self.p.contents.horizontal = value | [
"def",
"sethor",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"p",
".",
"contents",
".",
"horizontal",
"=",
"value"
] | https://github.com/Dozed12/df-style-worldgen/blob/937455d54f4b02df9c4b10ae6418f4c932fd97bf/libtcodpy.py#L1714-L1715 | ||||
uber/fiber | ad6faf02b8e94dee498990e9fd9c588234666725 | fiber/pool.py | python | ResilientZPool.__init__ | (self, processes=None, initializer=None, initargs=(),
maxtasksperchild=None, cluster=None) | # launch task handler
td = threading.Thread(
target=self._handle_tasks,
args=(
self.taskq,
self._master_sock,
self.active_peer_list,
self._pending_table,
))
td.daemon = True
td._state = RUN
td.start()
self._task_handler = td | # launch task handler
td = threading.Thread(
target=self._handle_tasks,
args=(
self.taskq,
self._master_sock,
self.active_peer_list,
self._pending_table,
))
td.daemon = True
td._state = RUN
td.start()
self._task_handler = td | [
"#",
"launch",
"task",
"handler",
"td",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_handle_tasks",
"args",
"=",
"(",
"self",
".",
"taskq",
"self",
".",
"_master_sock",
"self",
".",
"active_peer_list",
"self",
".",
"_pending_table",
... | def __init__(self, processes=None, initializer=None, initargs=(),
maxtasksperchild=None, cluster=None):
self.active_peer_dict = {}
self.active_peer_list = []
self.peer_lock = threading.Lock()
self.taskq = queue.Queue()
self._pending_table = {}
super(ResilientZPool, self).__init__(
processes=processes,
initializer=initializer,
initargs=initargs,
maxtasksperchild=maxtasksperchild,
cluster=cluster,
master_sock_type="rep")
'''
# launch task handler
td = threading.Thread(
target=self._handle_tasks,
args=(
self.taskq,
self._master_sock,
self.active_peer_list,
self._pending_table,
))
td.daemon = True
td._state = RUN
td.start()
self._task_handler = td
'''
self._pid_to_rid = {} | [
"def",
"__init__",
"(",
"self",
",",
"processes",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"initargs",
"=",
"(",
")",
",",
"maxtasksperchild",
"=",
"None",
",",
"cluster",
"=",
"None",
")",
":",
"self",
".",
"active_peer_dict",
"=",
"{",
"}",... | https://github.com/uber/fiber/blob/ad6faf02b8e94dee498990e9fd9c588234666725/fiber/pool.py#L1437-L1470 | ||
TeamMsgExtractor/msg-extractor | 8a3a0255a7306bdb8073bd8f222d3be5c688080a | extract_msg/message_base.py | python | MessageBase.header | (self) | Returns the message header, if it exists. Otherwise it will generate one. | Returns the message header, if it exists. Otherwise it will generate one. | [
"Returns",
"the",
"message",
"header",
"if",
"it",
"exists",
".",
"Otherwise",
"it",
"will",
"generate",
"one",
"."
] | def header(self):
"""
Returns the message header, if it exists. Otherwise it will generate one.
"""
try:
return self._header
except AttributeError:
headerText = self._getStringStream('__substg1.0_007D')
if headerText is not None:
self._header = EmailParser().parsestr(headerText)
self._header['date'] = self.date
else:
logger.info('Header is empty or was not found. Header will be generated from other streams.')
header = EmailParser().parsestr('')
header.add_header('Date', self.date)
header.add_header('From', self.sender)
header.add_header('To', self.to)
header.add_header('Cc', self.cc)
header.add_header('Message-Id', self.messageId)
# TODO find authentication results outside of header
header.add_header('Authentication-Results', None)
self._header = header
return self._header | [
"def",
"header",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_header",
"except",
"AttributeError",
":",
"headerText",
"=",
"self",
".",
"_getStringStream",
"(",
"'__substg1.0_007D'",
")",
"if",
"headerText",
"is",
"not",
"None",
":",
"self",
... | https://github.com/TeamMsgExtractor/msg-extractor/blob/8a3a0255a7306bdb8073bd8f222d3be5c688080a/extract_msg/message_base.py#L256-L278 | ||
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/cinder/cinder/volume/drivers/xiv.py | python | XIVDriver.create_volume_from_snapshot | (self, volume, snapshot) | return self.xiv_proxy.create_volume_from_snapshot(volume,
snapshot) | Create a volume from a snapshot. | Create a volume from a snapshot. | [
"Create",
"a",
"volume",
"from",
"a",
"snapshot",
"."
] | def create_volume_from_snapshot(self, volume, snapshot):
"""Create a volume from a snapshot."""
return self.xiv_proxy.create_volume_from_snapshot(volume,
snapshot) | [
"def",
"create_volume_from_snapshot",
"(",
"self",
",",
"volume",
",",
"snapshot",
")",
":",
"return",
"self",
".",
"xiv_proxy",
".",
"create_volume_from_snapshot",
"(",
"volume",
",",
"snapshot",
")"
] | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/volume/drivers/xiv.py#L103-L107 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/app_manager/models.py | python | SchedulePhase.id | (self) | return _id + 1 | A Schedule Phase is 1-indexed | A Schedule Phase is 1-indexed | [
"A",
"Schedule",
"Phase",
"is",
"1",
"-",
"indexed"
] | def id(self):
""" A Schedule Phase is 1-indexed """
_id = super(SchedulePhase, self).id
return _id + 1 | [
"def",
"id",
"(",
"self",
")",
":",
"_id",
"=",
"super",
"(",
"SchedulePhase",
",",
"self",
")",
".",
"id",
"return",
"_id",
"+",
"1"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/models.py#L2940-L2943 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/caldav/calendar.py | python | WebDavCalendarData.__init__ | (self, calendar, days, include_all_day, search) | Set up how we are going to search the WebDav calendar. | Set up how we are going to search the WebDav calendar. | [
"Set",
"up",
"how",
"we",
"are",
"going",
"to",
"search",
"the",
"WebDav",
"calendar",
"."
] | def __init__(self, calendar, days, include_all_day, search):
"""Set up how we are going to search the WebDav calendar."""
self.calendar = calendar
self.days = days
self.include_all_day = include_all_day
self.search = search
self.event = None | [
"def",
"__init__",
"(",
"self",
",",
"calendar",
",",
"days",
",",
"include_all_day",
",",
"search",
")",
":",
"self",
".",
"calendar",
"=",
"calendar",
"self",
".",
"days",
"=",
"days",
"self",
".",
"include_all_day",
"=",
"include_all_day",
"self",
".",
... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/caldav/calendar.py#L158-L164 | ||
francisck/DanderSpritz_docs | 86bb7caca5a957147f120b18bb5c31f299914904 | Python/Core/Lib/email/feedparser.py | python | FeedParser.feed | (self, data) | Push more data into the parser. | Push more data into the parser. | [
"Push",
"more",
"data",
"into",
"the",
"parser",
"."
] | def feed(self, data):
"""Push more data into the parser."""
self._input.push(data)
self._call_parse() | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_input",
".",
"push",
"(",
"data",
")",
"self",
".",
"_call_parse",
"(",
")"
] | https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/email/feedparser.py#L124-L127 | ||
benediktschmitt/py-ts3 | 043a6a896169d39464f6f754e2afd300f74eefa5 | ts3/commands.py | python | TS3Commands.customsearch | (self, *, ident, pattern) | return self._return_proxy("customsearch", cparams, uparams, options) | Usage::
customsearch ident={ident} pattern={pattern}
Searches for custom client properties specified by ident and value. The value
parameter can include regular characters and SQL wildcard characters (e.g. %).
Example::
customsearch ident=forum_account pattern=%ScP%
cldbid=2 ident=forum_account value=ScP
error id=0 msg=ok
Example::
>>> ts3cmd.customsearch(ident="forum_account", pattern="%ScP")
... | Usage:: | [
"Usage",
"::"
] | def customsearch(self, *, ident, pattern):
"""
Usage::
customsearch ident={ident} pattern={pattern}
Searches for custom client properties specified by ident and value. The value
parameter can include regular characters and SQL wildcard characters (e.g. %).
Example::
customsearch ident=forum_account pattern=%ScP%
cldbid=2 ident=forum_account value=ScP
error id=0 msg=ok
Example::
>>> ts3cmd.customsearch(ident="forum_account", pattern="%ScP")
...
"""
cparams = OrderedDict()
uparams = list()
options = list()
cparams["ident"] = ident
cparams["pattern"] = pattern
return self._return_proxy("customsearch", cparams, uparams, options) | [
"def",
"customsearch",
"(",
"self",
",",
"*",
",",
"ident",
",",
"pattern",
")",
":",
"cparams",
"=",
"OrderedDict",
"(",
")",
"uparams",
"=",
"list",
"(",
")",
"options",
"=",
"list",
"(",
")",
"cparams",
"[",
"\"ident\"",
"]",
"=",
"ident",
"cparam... | https://github.com/benediktschmitt/py-ts3/blob/043a6a896169d39464f6f754e2afd300f74eefa5/ts3/commands.py#L1718-L1744 | |
missionpinball/mpf | 8e6b74cff4ba06d2fec9445742559c1068b88582 | mpf/core/rgba_color.py | python | RGBAColor.__init__ | (self, color: Union[RGBColor, str, Tuple[int, int, int], Tuple[int, int, int, int], List[int]]) | Initialise RGBA color. | Initialise RGBA color. | [
"Initialise",
"RGBA",
"color",
"."
] | def __init__(self, color: Union[RGBColor, str, Tuple[int, int, int], Tuple[int, int, int, int], List[int]]) -> None:
"""Initialise RGBA color."""
if isinstance(color, (tuple, list)) and len(color) == 4:
self.opacity = color[3] # type: ignore
super().__init__((color[0], color[1], color[2]))
else:
self.opacity = 255
super().__init__(color) | [
"def",
"__init__",
"(",
"self",
",",
"color",
":",
"Union",
"[",
"RGBColor",
",",
"str",
",",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
",",
"int",
"]",
",",
"List",
"[",
"int",
"]",
"... | https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/core/rgba_color.py#L13-L20 | ||
openhatch/oh-mainline | ce29352a034e1223141dcc2f317030bbc3359a51 | vendor/packages/sphinx/sphinx/websupport/__init__.py | python | WebSupport.get_document | (self, docname, username='', moderator=False) | return document | Load and return a document from a pickle. The document will
be a dict object which can be used to render a template::
support = WebSupport(datadir=datadir)
support.get_document('index', username, moderator)
In most cases `docname` will be taken from the request path and
passed directly to this function. In Flask, that would be something
like this::
@app.route('/<path:docname>')
def index(docname):
username = g.user.name if g.user else ''
moderator = g.user.moderator if g.user else False
try:
document = support.get_document(docname, username,
moderator)
except DocumentNotFoundError:
abort(404)
render_template('doc.html', document=document)
The document dict that is returned contains the following items
to be used during template rendering.
* **body**: The main body of the document as HTML
* **sidebar**: The sidebar of the document as HTML
* **relbar**: A div containing links to related documents
* **title**: The title of the document
* **css**: Links to css files used by Sphinx
* **script**: Javascript containing comment options
This raises :class:`~sphinx.websupport.errors.DocumentNotFoundError`
if a document matching `docname` is not found.
:param docname: the name of the document to load. | Load and return a document from a pickle. The document will
be a dict object which can be used to render a template:: | [
"Load",
"and",
"return",
"a",
"document",
"from",
"a",
"pickle",
".",
"The",
"document",
"will",
"be",
"a",
"dict",
"object",
"which",
"can",
"be",
"used",
"to",
"render",
"a",
"template",
"::"
] | def get_document(self, docname, username='', moderator=False):
"""Load and return a document from a pickle. The document will
be a dict object which can be used to render a template::
support = WebSupport(datadir=datadir)
support.get_document('index', username, moderator)
In most cases `docname` will be taken from the request path and
passed directly to this function. In Flask, that would be something
like this::
@app.route('/<path:docname>')
def index(docname):
username = g.user.name if g.user else ''
moderator = g.user.moderator if g.user else False
try:
document = support.get_document(docname, username,
moderator)
except DocumentNotFoundError:
abort(404)
render_template('doc.html', document=document)
The document dict that is returned contains the following items
to be used during template rendering.
* **body**: The main body of the document as HTML
* **sidebar**: The sidebar of the document as HTML
* **relbar**: A div containing links to related documents
* **title**: The title of the document
* **css**: Links to css files used by Sphinx
* **script**: Javascript containing comment options
This raises :class:`~sphinx.websupport.errors.DocumentNotFoundError`
if a document matching `docname` is not found.
:param docname: the name of the document to load.
"""
docpath = path.join(self.datadir, 'pickles', docname)
if path.isdir(docpath):
infilename = docpath + '/index.fpickle'
if not docname:
docname = 'index'
else:
docname += '/index'
else:
infilename = docpath + '.fpickle'
try:
f = open(infilename, 'rb')
except IOError:
raise errors.DocumentNotFoundError(
'The document "%s" could not be found' % docname)
try:
document = pickle.load(f)
finally:
f.close()
comment_opts = self._make_comment_options(username, moderator)
comment_meta = self._make_metadata(
self.storage.get_metadata(docname, moderator))
document['script'] = comment_opts + comment_meta + document['script']
return document | [
"def",
"get_document",
"(",
"self",
",",
"docname",
",",
"username",
"=",
"''",
",",
"moderator",
"=",
"False",
")",
":",
"docpath",
"=",
"path",
".",
"join",
"(",
"self",
".",
"datadir",
",",
"'pickles'",
",",
"docname",
")",
"if",
"path",
".",
"isd... | https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/sphinx/sphinx/websupport/__init__.py#L141-L203 | |
mu-editor/mu | 5a5d7723405db588f67718a63a0ec0ecabebae33 | mu/interface/main.py | python | Window.add_repl | (self, repl_pane, name) | Adds the referenced REPL pane to the application. | Adds the referenced REPL pane to the application. | [
"Adds",
"the",
"referenced",
"REPL",
"pane",
"to",
"the",
"application",
"."
] | def add_repl(self, repl_pane, name):
"""
Adds the referenced REPL pane to the application.
"""
self.repl_pane = repl_pane
self.repl = QDockWidget(_("{} REPL").format(name))
self.repl.setWidget(repl_pane)
self.repl.setFeatures(QDockWidget.DockWidgetMovable)
self.repl.setAllowedAreas(
Qt.BottomDockWidgetArea
| Qt.LeftDockWidgetArea
| Qt.RightDockWidgetArea
)
area = self._repl_area or Qt.BottomDockWidgetArea
self.addDockWidget(area, self.repl)
self.connect_zoom(self.repl_pane)
self.repl_pane.set_theme(self.theme)
self.repl_pane.setFocus() | [
"def",
"add_repl",
"(",
"self",
",",
"repl_pane",
",",
"name",
")",
":",
"self",
".",
"repl_pane",
"=",
"repl_pane",
"self",
".",
"repl",
"=",
"QDockWidget",
"(",
"_",
"(",
"\"{} REPL\"",
")",
".",
"format",
"(",
"name",
")",
")",
"self",
".",
"repl"... | https://github.com/mu-editor/mu/blob/5a5d7723405db588f67718a63a0ec0ecabebae33/mu/interface/main.py#L677-L694 | ||
microsoft/nni | 31f11f51249660930824e888af0d4e022823285c | nni/algorithms/compression/v2/pytorch/utils/pruning.py | python | config_list_canonical | (model: Module, config_list: List[Dict]) | return new_config_list | Split the config by op_names if 'sparsity' or 'sparsity_per_layer' in config,
and set the sub_config['total_sparsity'] = config['sparsity_per_layer'].
And every item in 'op_partial_names' will match corresponding 'op_names' in model,
then convert 'op_partial_names' to 'op_names' in config.
Example::
model = models.resnet18()
config_list = [{'op_types': ['Conv2d'], 'sparsity': 0.8, 'op_partial_names': ['conv1']}]
pruner = L1NormPruner(model, config_list)
pruner.compress()
pruner.show_pruned_weights()
In this process, the config_list will implicitly convert to the following:
[{'op_types': ['Conv2d'], 'sparsity_per_layer': 0.8,
'op_names': ['conv1', 'layer1.0.conv1', 'layer1.1.conv1',
'layer2.0.conv1', 'layer2.1.conv1', 'layer3.0.conv1', 'layer3.1.conv1',
'layer4.0.conv1', 'layer4.1.conv1']}] | Split the config by op_names if 'sparsity' or 'sparsity_per_layer' in config,
and set the sub_config['total_sparsity'] = config['sparsity_per_layer'].
And every item in 'op_partial_names' will match corresponding 'op_names' in model,
then convert 'op_partial_names' to 'op_names' in config. | [
"Split",
"the",
"config",
"by",
"op_names",
"if",
"sparsity",
"or",
"sparsity_per_layer",
"in",
"config",
"and",
"set",
"the",
"sub_config",
"[",
"total_sparsity",
"]",
"=",
"config",
"[",
"sparsity_per_layer",
"]",
".",
"And",
"every",
"item",
"in",
"op_parti... | def config_list_canonical(model: Module, config_list: List[Dict]) -> List[Dict]:
'''
Split the config by op_names if 'sparsity' or 'sparsity_per_layer' in config,
and set the sub_config['total_sparsity'] = config['sparsity_per_layer'].
And every item in 'op_partial_names' will match corresponding 'op_names' in model,
then convert 'op_partial_names' to 'op_names' in config.
Example::
model = models.resnet18()
config_list = [{'op_types': ['Conv2d'], 'sparsity': 0.8, 'op_partial_names': ['conv1']}]
pruner = L1NormPruner(model, config_list)
pruner.compress()
pruner.show_pruned_weights()
In this process, the config_list will implicitly convert to the following:
[{'op_types': ['Conv2d'], 'sparsity_per_layer': 0.8,
'op_names': ['conv1', 'layer1.0.conv1', 'layer1.1.conv1',
'layer2.0.conv1', 'layer2.1.conv1', 'layer3.0.conv1', 'layer3.1.conv1',
'layer4.0.conv1', 'layer4.1.conv1']}]
'''
config_list = deepcopy(config_list)
for config in config_list:
if 'sparsity' in config:
if 'sparsity_per_layer' in config:
raise ValueError("'sparsity' and 'sparsity_per_layer' have the same semantics, can not set both in one config.")
else:
config['sparsity_per_layer'] = config.pop('sparsity')
for config in config_list:
if 'op_types' in config:
if 'default' in config['op_types']:
config['op_types'].remove('default')
config['op_types'].extend(weighted_modules)
for config in config_list:
if 'op_partial_names' in config:
op_names = []
for partial_name in config['op_partial_names']:
for name, _ in model.named_modules():
if partial_name in name:
op_names.append(name)
if 'op_names' in config:
config['op_names'].extend(op_names)
config['op_names'] = list(set(config['op_names']))
else:
config['op_names'] = op_names
config.pop('op_partial_names')
config_list = dedupe_config_list(unfold_config_list(model, config_list))
new_config_list = []
for config in config_list:
if 'sparsity_per_layer' in config:
sparsity_per_layer = config.pop('sparsity_per_layer')
op_names = config.pop('op_names')
for op_name in op_names:
sub_config = deepcopy(config)
sub_config['op_names'] = [op_name]
sub_config['total_sparsity'] = sparsity_per_layer
new_config_list.append(sub_config)
elif 'max_sparsity_per_layer' in config and isinstance(config['max_sparsity_per_layer'], float):
op_names = config.get('op_names', [])
max_sparsity_per_layer = {}
max_sparsity = config['max_sparsity_per_layer']
for op_name in op_names:
max_sparsity_per_layer[op_name] = max_sparsity
config['max_sparsity_per_layer'] = max_sparsity_per_layer
new_config_list.append(config)
else:
new_config_list.append(config)
return new_config_list | [
"def",
"config_list_canonical",
"(",
"model",
":",
"Module",
",",
"config_list",
":",
"List",
"[",
"Dict",
"]",
")",
"->",
"List",
"[",
"Dict",
"]",
":",
"config_list",
"=",
"deepcopy",
"(",
"config_list",
")",
"for",
"config",
"in",
"config_list",
":",
... | https://github.com/microsoft/nni/blob/31f11f51249660930824e888af0d4e022823285c/nni/algorithms/compression/v2/pytorch/utils/pruning.py#L19-L92 | |
shiweibsw/Translation-Tools | 2fbbf902364e557fa7017f9a74a8797b7440c077 | venv/Lib/site-packages/xlwt/Workbook.py | python | Workbook.get_sheet | (self, sheet) | [] | def get_sheet(self, sheet):
if isinstance(sheet, int_types):
return self.__worksheets[sheet]
elif isinstance(sheet, basestring):
sheetnum = self.sheet_index(sheet)
return self.__worksheets[sheetnum]
else:
raise Exception("sheet must be integer or string") | [
"def",
"get_sheet",
"(",
"self",
",",
"sheet",
")",
":",
"if",
"isinstance",
"(",
"sheet",
",",
"int_types",
")",
":",
"return",
"self",
".",
"__worksheets",
"[",
"sheet",
"]",
"elif",
"isinstance",
"(",
"sheet",
",",
"basestring",
")",
":",
"sheetnum",
... | https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/xlwt/Workbook.py#L376-L383 | ||||
ansible/ansible | 4676c08f188fb5dca98df61630c76dba1f0d2d77 | lib/ansible/modules/yum.py | python | YumModule.run | (self) | actually execute the module code backend | actually execute the module code backend | [
"actually",
"execute",
"the",
"module",
"code",
"backend"
] | def run(self):
"""
actually execute the module code backend
"""
if (not HAS_RPM_PYTHON or not HAS_YUM_PYTHON) and sys.executable != '/usr/bin/python' and not has_respawned():
respawn_module('/usr/bin/python')
# end of the line for this process; we'll exit here once the respawned module has completed
error_msgs = []
if not HAS_RPM_PYTHON:
error_msgs.append('The Python 2 bindings for rpm are needed for this module. If you require Python 3 support use the `dnf` Ansible module instead.')
if not HAS_YUM_PYTHON:
error_msgs.append('The Python 2 yum module is needed for this module. If you require Python 3 support use the `dnf` Ansible module instead.')
self.wait_for_lock()
if error_msgs:
self.module.fail_json(msg='. '.join(error_msgs))
# fedora will redirect yum to dnf, which has incompatibilities
# with how this module expects yum to operate. If yum-deprecated
# is available, use that instead to emulate the old behaviors.
if self.module.get_bin_path('yum-deprecated'):
yumbin = self.module.get_bin_path('yum-deprecated')
else:
yumbin = self.module.get_bin_path('yum')
# need debug level 2 to get 'Nothing to do' for groupinstall.
self.yum_basecmd = [yumbin, '-d', '2', '-y']
if self.update_cache and not self.names and not self.list:
rc, stdout, stderr = self.module.run_command(self.yum_basecmd + ['clean', 'expire-cache'])
if rc == 0:
self.module.exit_json(
changed=False,
msg="Cache updated",
rc=rc,
results=[]
)
else:
self.module.exit_json(
changed=False,
msg="Failed to update cache",
rc=rc,
results=[stderr],
)
repoquerybin = self.module.get_bin_path('repoquery', required=False)
if self.install_repoquery and not repoquerybin and not self.module.check_mode:
yum_path = self.module.get_bin_path('yum')
if yum_path:
if self.releasever:
self.module.run_command('%s -y install yum-utils --releasever %s' % (yum_path, self.releasever))
else:
self.module.run_command('%s -y install yum-utils' % yum_path)
repoquerybin = self.module.get_bin_path('repoquery', required=False)
if self.list:
if not repoquerybin:
self.module.fail_json(msg="repoquery is required to use list= with this module. Please install the yum-utils package.")
results = {'results': self.list_stuff(repoquerybin, self.list)}
else:
# If rhn-plugin is installed and no rhn-certificate is available on
# the system then users will see an error message using the yum API.
# Use repoquery in those cases.
repoquery = None
try:
yum_plugins = self.yum_base.plugins._plugins
except AttributeError:
pass
else:
if 'rhnplugin' in yum_plugins:
if repoquerybin:
repoquery = [repoquerybin, '--show-duplicates', '--plugins', '--quiet']
if self.installroot != '/':
repoquery.extend(['--installroot', self.installroot])
if self.disable_excludes:
# repoquery does not support --disableexcludes,
# so make a temp copy of yum.conf and get rid of the 'exclude=' line there
try:
with open('/etc/yum.conf', 'r') as f:
content = f.readlines()
tmp_conf_file = tempfile.NamedTemporaryFile(dir=self.module.tmpdir, delete=False)
self.module.add_cleanup_file(tmp_conf_file.name)
tmp_conf_file.writelines([c for c in content if not c.startswith("exclude=")])
tmp_conf_file.close()
except Exception as e:
self.module.fail_json(msg="Failure setting up repoquery: %s" % to_native(e))
repoquery.extend(['-c', tmp_conf_file.name])
results = self.ensure(repoquery)
if repoquery:
results['msg'] = '%s %s' % (
results.get('msg', ''),
'Warning: Due to potential bad behaviour with rhnplugin and certificates, used slower repoquery calls instead of Yum API.'
)
self.module.exit_json(**results) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"(",
"not",
"HAS_RPM_PYTHON",
"or",
"not",
"HAS_YUM_PYTHON",
")",
"and",
"sys",
".",
"executable",
"!=",
"'/usr/bin/python'",
"and",
"not",
"has_respawned",
"(",
")",
":",
"respawn_module",
"(",
"'/usr/bin/python'",
... | https://github.com/ansible/ansible/blob/4676c08f188fb5dca98df61630c76dba1f0d2d77/lib/ansible/modules/yum.py#L1688-L1792 | ||
santatic/web2attack | 44b6e481a3d56cf0d98073ae0fb69833dda563d9 | w2a/modules/attack/ctf_brute.py | python | Module.run | (self, frmwk, args) | [] | def run(self, frmwk, args):
self.frmwk = frmwk
# self.victim = HTTP(self.options['URL'], timeout = self.advanced_options['TIMEOUT'])
self.victim.storecookie = True
self.verbose = self.options['VERBOSE']
self.userlist = []
self.passlist = []
self.success = []
self.victim.headers.update({'Cookie': self.advanced_options['COOKIE']} if self.advanced_options['COOKIE'] else {})
#######################################
if self.options['USERNAME']:
self.userlist = self.options['USERNAME'].split(',')
else:
self.userlist = read_from_file(full_path(self.options['USERLIST']))
if self.options['PASSWORD']:
self.passlist = self.options['PASSWORD'].split(',')
else:
self.passlist = read_from_file(full_path(self.options['PASSLIST']))
self.lenuser = len(self.userlist)
self.lenpass = len(self.passlist)
###############################################
listthread = []
if len(self.userlist) > 0:
self.temppass = []
for i in range(self.options['THREADS']):
t = Thread(target = self.worker)
listthread.append(t)
t.start()
try:
for t in listthread:
t.join()
except KeyboardInterrupt:
for t in listthread:
if t.isAlive():
t.terminate()
pass
##############################################
self.success = sorted(self.success)
self.frmwk.print_line()
self.frmwk.print_status("List login:\n-----------")
if len(self.success) > 0:
for u, p in self.success:
self.frmwk.print_success('SUCCESS: username: {0:<20} password: {1}'.format(u, p))
self.frmwk.print_status("-----------")
else:
self.frmwk.print_status('Nothing to do!') | [
"def",
"run",
"(",
"self",
",",
"frmwk",
",",
"args",
")",
":",
"self",
".",
"frmwk",
"=",
"frmwk",
"# self.victim\t\t\t\t= HTTP(self.options['URL'], timeout = self.advanced_options['TIMEOUT'])",
"self",
".",
"victim",
".",
"storecookie",
"=",
"True",
"self",
".",
"... | https://github.com/santatic/web2attack/blob/44b6e481a3d56cf0d98073ae0fb69833dda563d9/w2a/modules/attack/ctf_brute.py#L44-L93 | ||||
frappe/frappe | b64cab6867dfd860f10ccaf41a4ec04bc890b583 | frappe/desk/reportview.py | python | scrub_user_tags | (tagcount) | return rlist | rebuild tag list for tags | rebuild tag list for tags | [
"rebuild",
"tag",
"list",
"for",
"tags"
] | def scrub_user_tags(tagcount):
"""rebuild tag list for tags"""
rdict = {}
tagdict = dict(tagcount)
for t in tagdict:
if not t:
continue
alltags = t.split(',')
for tag in alltags:
if tag:
if not tag in rdict:
rdict[tag] = 0
rdict[tag] += tagdict[t]
rlist = []
for tag in rdict:
rlist.append([tag, rdict[tag]])
return rlist | [
"def",
"scrub_user_tags",
"(",
"tagcount",
")",
":",
"rdict",
"=",
"{",
"}",
"tagdict",
"=",
"dict",
"(",
"tagcount",
")",
"for",
"t",
"in",
"tagdict",
":",
"if",
"not",
"t",
":",
"continue",
"alltags",
"=",
"t",
".",
"split",
"(",
"','",
")",
"for... | https://github.com/frappe/frappe/blob/b64cab6867dfd860f10ccaf41a4ec04bc890b583/frappe/desk/reportview.py#L525-L544 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/django/contrib/gis/utils/ogrinspect.py | python | mapping | (data_source, geom_name='geom', layer_key=0, multi_geom=False) | return _mapping | Given a DataSource, generates a dictionary that may be used
for invoking the LayerMapping utility.
Keyword Arguments:
`geom_name` => The name of the geometry field to use for the model.
`layer_key` => The key for specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer.
`multi_geom` => Boolean (default: False) - specify as multigeometry. | Given a DataSource, generates a dictionary that may be used
for invoking the LayerMapping utility. | [
"Given",
"a",
"DataSource",
"generates",
"a",
"dictionary",
"that",
"may",
"be",
"used",
"for",
"invoking",
"the",
"LayerMapping",
"utility",
"."
] | def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False):
"""
Given a DataSource, generates a dictionary that may be used
for invoking the LayerMapping utility.
Keyword Arguments:
`geom_name` => The name of the geometry field to use for the model.
`layer_key` => The key for specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer.
`multi_geom` => Boolean (default: False) - specify as multigeometry.
"""
if isinstance(data_source, six.string_types):
# Instantiating the DataSource from the string.
data_source = DataSource(data_source)
elif isinstance(data_source, DataSource):
pass
else:
raise TypeError('Data source parameter must be a string or a DataSource object.')
# Creating the dictionary.
_mapping = {}
# Generating the field name for each field in the layer.
for field in data_source[layer_key].fields:
mfield = field.lower()
if mfield[-1:] == '_':
mfield += 'field'
_mapping[mfield] = field
gtype = data_source[layer_key].geom_type
if multi_geom:
gtype.to_multi()
_mapping[geom_name] = str(gtype).upper()
return _mapping | [
"def",
"mapping",
"(",
"data_source",
",",
"geom_name",
"=",
"'geom'",
",",
"layer_key",
"=",
"0",
",",
"multi_geom",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data_source",
",",
"six",
".",
"string_types",
")",
":",
"# Instantiating the DataSource fro... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/gis/utils/ogrinspect.py#L15-L50 | |
kirthevasank/nasbot | 3c745dc986be30e3721087c8fa768099032a0802 | nn/nn_constraint_checkers.py | python | NNConstraintChecker._child_constraints_are_satisfied | (self, nn) | Checks if the constraints of the child class are satisfied. | Checks if the constraints of the child class are satisfied. | [
"Checks",
"if",
"the",
"constraints",
"of",
"the",
"child",
"class",
"are",
"satisfied",
"."
] | def _child_constraints_are_satisfied(self, nn):
""" Checks if the constraints of the child class are satisfied. """
raise NotImplementedError('Implement in a child class.') | [
"def",
"_child_constraints_are_satisfied",
"(",
"self",
",",
"nn",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Implement in a child class.'",
")"
] | https://github.com/kirthevasank/nasbot/blob/3c745dc986be30e3721087c8fa768099032a0802/nn/nn_constraint_checkers.py#L77-L79 | ||
Yubico/yubikey-manager | 32914673d1d0004aba820e614ac9a9a640b4d196 | yubikit/core/otp.py | python | _format_frame | (slot, payload) | return payload + struct.pack("<BH", slot, calculate_crc(payload)) + b"\0\0\0" | [] | def _format_frame(slot, payload):
return payload + struct.pack("<BH", slot, calculate_crc(payload)) + b"\0\0\0" | [
"def",
"_format_frame",
"(",
"slot",
",",
"payload",
")",
":",
"return",
"payload",
"+",
"struct",
".",
"pack",
"(",
"\"<BH\"",
",",
"slot",
",",
"calculate_crc",
"(",
"payload",
")",
")",
"+",
"b\"\\0\\0\\0\""
] | https://github.com/Yubico/yubikey-manager/blob/32914673d1d0004aba820e614ac9a9a640b4d196/yubikit/core/otp.py#L115-L116 | |||
kubeflow/pipelines | bea751c9259ff0ae85290f873170aae89284ba8e | components/json/Combine_lists/component.py | python | combine_lists | (
list_1: list = None,
list_2: list = None,
list_3: list = None,
list_4: list = None,
list_5: list = None,
) | return result | Combines multiple JSON arrays into one.
Annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com> | Combines multiple JSON arrays into one. | [
"Combines",
"multiple",
"JSON",
"arrays",
"into",
"one",
"."
] | def combine_lists(
list_1: list = None,
list_2: list = None,
list_3: list = None,
list_4: list = None,
list_5: list = None,
) -> list:
"""Combines multiple JSON arrays into one.
Annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
"""
result = []
for list in [list_1, list_2, list_3, list_4, list_5]:
if list is not None:
result.extend(list)
return result | [
"def",
"combine_lists",
"(",
"list_1",
":",
"list",
"=",
"None",
",",
"list_2",
":",
"list",
"=",
"None",
",",
"list_3",
":",
"list",
"=",
"None",
",",
"list_4",
":",
"list",
"=",
"None",
",",
"list_5",
":",
"list",
"=",
"None",
",",
")",
"->",
"... | https://github.com/kubeflow/pipelines/blob/bea751c9259ff0ae85290f873170aae89284ba8e/components/json/Combine_lists/component.py#L4-L20 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/functions/airy.py | python | FunctionAiryAiPrime.__init__ | (self) | The derivative of the Airy Ai function; see :func:`airy_ai`
for the full documentation.
EXAMPLES::
sage: x, n = var('x n')
sage: airy_ai_prime(x)
airy_ai_prime(x)
sage: airy_ai_prime(0)
-1/3*3^(2/3)/gamma(1/3)
sage: airy_ai_prime(x)._sympy_()
airyaiprime(x) | The derivative of the Airy Ai function; see :func:`airy_ai`
for the full documentation. | [
"The",
"derivative",
"of",
"the",
"Airy",
"Ai",
"function",
";",
"see",
":",
"func",
":",
"airy_ai",
"for",
"the",
"full",
"documentation",
"."
] | def __init__(self):
"""
The derivative of the Airy Ai function; see :func:`airy_ai`
for the full documentation.
EXAMPLES::
sage: x, n = var('x n')
sage: airy_ai_prime(x)
airy_ai_prime(x)
sage: airy_ai_prime(0)
-1/3*3^(2/3)/gamma(1/3)
sage: airy_ai_prime(x)._sympy_()
airyaiprime(x)
"""
BuiltinFunction.__init__(self, 'airy_ai_prime',
latex_name=r"\operatorname{Ai}'",
conversions=dict(mathematica='AiryAiPrime',
maxima='airy_dai',
sympy='airyaiprime',
fricas='airyAiPrime')) | [
"def",
"__init__",
"(",
"self",
")",
":",
"BuiltinFunction",
".",
"__init__",
"(",
"self",
",",
"'airy_ai_prime'",
",",
"latex_name",
"=",
"r\"\\operatorname{Ai}'\"",
",",
"conversions",
"=",
"dict",
"(",
"mathematica",
"=",
"'AiryAiPrime'",
",",
"maxima",
"=",
... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/functions/airy.py#L257-L277 | ||
shaneshixiang/rllabplusplus | 4d55f96ec98e3fe025b7991945e3e6a54fd5449f | rllab/envs/base.py | python | Env.step | (self, action) | Run one timestep of the environment's dynamics. When end of episode
is reached, reset() should be called to reset the environment's internal state.
Input
-----
action : an action provided by the environment
Outputs
-------
(observation, reward, done, info)
observation : agent's observation of the current environment
reward [Float] : amount of reward due to the previous action
done : a boolean, indicating whether the episode has ended
info : a dictionary containing other diagnostic information from the previous action | Run one timestep of the environment's dynamics. When end of episode
is reached, reset() should be called to reset the environment's internal state.
Input
-----
action : an action provided by the environment
Outputs
-------
(observation, reward, done, info)
observation : agent's observation of the current environment
reward [Float] : amount of reward due to the previous action
done : a boolean, indicating whether the episode has ended
info : a dictionary containing other diagnostic information from the previous action | [
"Run",
"one",
"timestep",
"of",
"the",
"environment",
"s",
"dynamics",
".",
"When",
"end",
"of",
"episode",
"is",
"reached",
"reset",
"()",
"should",
"be",
"called",
"to",
"reset",
"the",
"environment",
"s",
"internal",
"state",
".",
"Input",
"-----",
"act... | def step(self, action):
"""
Run one timestep of the environment's dynamics. When end of episode
is reached, reset() should be called to reset the environment's internal state.
Input
-----
action : an action provided by the environment
Outputs
-------
(observation, reward, done, info)
observation : agent's observation of the current environment
reward [Float] : amount of reward due to the previous action
done : a boolean, indicating whether the episode has ended
info : a dictionary containing other diagnostic information from the previous action
"""
raise NotImplementedError | [
"def",
"step",
"(",
"self",
",",
"action",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/shaneshixiang/rllabplusplus/blob/4d55f96ec98e3fe025b7991945e3e6a54fd5449f/rllab/envs/base.py#L7-L22 | ||
simplejson/simplejson | 02221b19672b1b35188080435c7360cd2d6af6fb | simplejson/ordered_dict.py | python | OrderedDict.__eq__ | (self, other) | return dict.__eq__(self, other) | [] | def __eq__(self, other):
if isinstance(other, OrderedDict):
return len(self)==len(other) and \
all(p==q for p, q in zip(self.items(), other.items()))
return dict.__eq__(self, other) | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"OrderedDict",
")",
":",
"return",
"len",
"(",
"self",
")",
"==",
"len",
"(",
"other",
")",
"and",
"all",
"(",
"p",
"==",
"q",
"for",
"p",
",",
"q",
"i... | https://github.com/simplejson/simplejson/blob/02221b19672b1b35188080435c7360cd2d6af6fb/simplejson/ordered_dict.py#L96-L100 | |||
twitter/zktraffic | 82db04d9aafa13f694d4f5c7265069db42c0307c | zktraffic/stats/accumulators.py | python | PerIPStatsAccumulator.update_request_stats | (self, request) | [] | def update_request_stats(self, request):
self._update_request_stats(self.get_path(request, request.ip), request) | [
"def",
"update_request_stats",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"_update_request_stats",
"(",
"self",
".",
"get_path",
"(",
"request",
",",
"request",
".",
"ip",
")",
",",
"request",
")"
] | https://github.com/twitter/zktraffic/blob/82db04d9aafa13f694d4f5c7265069db42c0307c/zktraffic/stats/accumulators.py#L135-L136 | ||||
eirannejad/pyRevit | 49c0b7eb54eb343458ce1365425e6552d0c47d44 | site-packages/werkzeug/wrappers.py | python | _run_wsgi_app | (*args) | return _run_wsgi_app(*args) | This function replaces itself to ensure that the test module is not
imported unless required. DO NOT USE! | This function replaces itself to ensure that the test module is not
imported unless required. DO NOT USE! | [
"This",
"function",
"replaces",
"itself",
"to",
"ensure",
"that",
"the",
"test",
"module",
"is",
"not",
"imported",
"unless",
"required",
".",
"DO",
"NOT",
"USE!"
] | def _run_wsgi_app(*args):
"""This function replaces itself to ensure that the test module is not
imported unless required. DO NOT USE!
"""
global _run_wsgi_app
from werkzeug.test import run_wsgi_app as _run_wsgi_app
return _run_wsgi_app(*args) | [
"def",
"_run_wsgi_app",
"(",
"*",
"args",
")",
":",
"global",
"_run_wsgi_app",
"from",
"werkzeug",
".",
"test",
"import",
"run_wsgi_app",
"as",
"_run_wsgi_app",
"return",
"_run_wsgi_app",
"(",
"*",
"args",
")"
] | https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/werkzeug/wrappers.py#L51-L57 | |
HymanLiuTS/flaskTs | 286648286976e85d9b9a5873632331efcafe0b21 | flasky/lib/python2.7/site-packages/flask_script/commands.py | python | Shell.run | (self, no_ipython, no_bpython) | Runs the shell. If no_bpython is False or use_bpython is True, then
a BPython shell is run (if installed). Else, if no_ipython is False or
use_python is True then a IPython shell is run (if installed). | Runs the shell. If no_bpython is False or use_bpython is True, then
a BPython shell is run (if installed). Else, if no_ipython is False or
use_python is True then a IPython shell is run (if installed). | [
"Runs",
"the",
"shell",
".",
"If",
"no_bpython",
"is",
"False",
"or",
"use_bpython",
"is",
"True",
"then",
"a",
"BPython",
"shell",
"is",
"run",
"(",
"if",
"installed",
")",
".",
"Else",
"if",
"no_ipython",
"is",
"False",
"or",
"use_python",
"is",
"True"... | def run(self, no_ipython, no_bpython):
"""
Runs the shell. If no_bpython is False or use_bpython is True, then
a BPython shell is run (if installed). Else, if no_ipython is False or
use_python is True then a IPython shell is run (if installed).
"""
context = self.get_context()
if not no_bpython:
# Try BPython
try:
from bpython import embed
embed(banner=self.banner, locals_=context)
return
except ImportError:
pass
if not no_ipython:
# Try IPython
try:
try:
# 0.10.x
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed(banner=self.banner)
ipshell(global_ns=dict(), local_ns=context)
except ImportError:
# 0.12+
from IPython import embed
embed(banner1=self.banner, user_ns=context)
return
except ImportError:
pass
# Use basic python shell
code.interact(self.banner, local=context) | [
"def",
"run",
"(",
"self",
",",
"no_ipython",
",",
"no_bpython",
")",
":",
"context",
"=",
"self",
".",
"get_context",
"(",
")",
"if",
"not",
"no_bpython",
":",
"# Try BPython",
"try",
":",
"from",
"bpython",
"import",
"embed",
"embed",
"(",
"banner",
"=... | https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/flask_script/commands.py#L277-L312 | ||
deepset-ai/haystack | 79fdda8a7cf393d774803608a4874f2a6e63cf6f | haystack/pipelines/base.py | python | Pipeline.load_from_yaml | (cls, path: Path, pipeline_name: Optional[str] = None, overwrite_with_env_variables: bool = True) | return pipeline | Load Pipeline from a YAML file defining the individual components and how they're tied together to form
a Pipeline. A single YAML can declare multiple Pipelines, in which case an explicit `pipeline_name` must
be passed.
Here's a sample configuration:
```yaml
| version: '0.8'
|
| components: # define all the building-blocks for Pipeline
| - name: MyReader # custom-name for the component; helpful for visualization & debugging
| type: FARMReader # Haystack Class name for the component
| params:
| no_ans_boost: -10
| model_name_or_path: deepset/roberta-base-squad2
| - name: MyESRetriever
| type: ElasticsearchRetriever
| params:
| document_store: MyDocumentStore # params can reference other components defined in the YAML
| custom_query: null
| - name: MyDocumentStore
| type: ElasticsearchDocumentStore
| params:
| index: haystack_test
|
| pipelines: # multiple Pipelines can be defined using the components from above
| - name: my_query_pipeline # a simple extractive-qa Pipeline
| nodes:
| - name: MyESRetriever
| inputs: [Query]
| - name: MyReader
| inputs: [MyESRetriever]
```
:param path: path of the YAML file.
:param pipeline_name: if the YAML contains multiple pipelines, the pipeline_name to load must be set.
:param overwrite_with_env_variables: Overwrite the YAML configuration with environment variables. For example,
to change index name param for an ElasticsearchDocumentStore, an env
variable 'MYDOCSTORE_PARAMS_INDEX=documents-2021' can be set. Note that an
`_` sign must be used to specify nested hierarchical properties. | Load Pipeline from a YAML file defining the individual components and how they're tied together to form
a Pipeline. A single YAML can declare multiple Pipelines, in which case an explicit `pipeline_name` must
be passed. | [
"Load",
"Pipeline",
"from",
"a",
"YAML",
"file",
"defining",
"the",
"individual",
"components",
"and",
"how",
"they",
"re",
"tied",
"together",
"to",
"form",
"a",
"Pipeline",
".",
"A",
"single",
"YAML",
"can",
"declare",
"multiple",
"Pipelines",
"in",
"which... | def load_from_yaml(cls, path: Path, pipeline_name: Optional[str] = None, overwrite_with_env_variables: bool = True):
"""
Load Pipeline from a YAML file defining the individual components and how they're tied together to form
a Pipeline. A single YAML can declare multiple Pipelines, in which case an explicit `pipeline_name` must
be passed.
Here's a sample configuration:
```yaml
| version: '0.8'
|
| components: # define all the building-blocks for Pipeline
| - name: MyReader # custom-name for the component; helpful for visualization & debugging
| type: FARMReader # Haystack Class name for the component
| params:
| no_ans_boost: -10
| model_name_or_path: deepset/roberta-base-squad2
| - name: MyESRetriever
| type: ElasticsearchRetriever
| params:
| document_store: MyDocumentStore # params can reference other components defined in the YAML
| custom_query: null
| - name: MyDocumentStore
| type: ElasticsearchDocumentStore
| params:
| index: haystack_test
|
| pipelines: # multiple Pipelines can be defined using the components from above
| - name: my_query_pipeline # a simple extractive-qa Pipeline
| nodes:
| - name: MyESRetriever
| inputs: [Query]
| - name: MyReader
| inputs: [MyESRetriever]
```
:param path: path of the YAML file.
:param pipeline_name: if the YAML contains multiple pipelines, the pipeline_name to load must be set.
:param overwrite_with_env_variables: Overwrite the YAML configuration with environment variables. For example,
to change index name param for an ElasticsearchDocumentStore, an env
variable 'MYDOCSTORE_PARAMS_INDEX=documents-2021' can be set. Note that an
`_` sign must be used to specify nested hierarchical properties.
"""
data, pipeline_config, definitions = cls._read_yaml(
path=path, pipeline_name=pipeline_name, overwrite_with_env_variables=overwrite_with_env_variables
)
pipeline = cls()
components: dict = {} # instances of component objects.
for node_config in pipeline_config["nodes"]:
name = node_config["name"]
component = cls._load_or_get_component(name=name, definitions=definitions, components=components)
pipeline.add_node(component=component, name=node_config["name"], inputs=node_config.get("inputs", []))
return pipeline | [
"def",
"load_from_yaml",
"(",
"cls",
",",
"path",
":",
"Path",
",",
"pipeline_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"overwrite_with_env_variables",
":",
"bool",
"=",
"True",
")",
":",
"data",
",",
"pipeline_config",
",",
"definitions",
... | https://github.com/deepset-ai/haystack/blob/79fdda8a7cf393d774803608a4874f2a6e63cf6f/haystack/pipelines/base.py#L587-L642 | |
ParmEd/ParmEd | cd763f2e83c98ba9e51676f6dbebf0eebfd5157e | parmed/tools/parmed_cmd.py | python | ParmedCmd.do_shell | (self, line) | Support the limited interpreter | Support the limited interpreter | [
"Support",
"the",
"limited",
"interpreter"
] | def do_shell(self, line):
""" Support the limited interpreter """
if not self.interpreter:
raise InterpreterError("Interpreter not enabled! Use '-e' to enable")
line = str(line)
if line.strip() == '!':
self._python_shell()
else:
globals_ = dict(amber_prmtop=self.parm)
globals_.update(globals())
try:
exec(line.strip(), globals_)
except Exception as err:
self.stdout.write(f"{type(err).__name__}: {err}\n") | [
"def",
"do_shell",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"self",
".",
"interpreter",
":",
"raise",
"InterpreterError",
"(",
"\"Interpreter not enabled! Use '-e' to enable\"",
")",
"line",
"=",
"str",
"(",
"line",
")",
"if",
"line",
".",
"strip",
"... | https://github.com/ParmEd/ParmEd/blob/cd763f2e83c98ba9e51676f6dbebf0eebfd5157e/parmed/tools/parmed_cmd.py#L261-L274 | ||
QCoDeS/Qcodes | 3cda2cef44812e2aa4672781f2423bf5f816f9f9 | qcodes/instrument_drivers/stahl/stahl.py | python | Stahl.parse_idn_string | (idn_string: str) | return {
name: converter(value)
for (name, converter), value in zip(converters.items(), result.groups())
} | Return:
dict: The dict contains the following keys "model",
"serial_number", "voltage_range","n_channels", "output_type" | Return:
dict: The dict contains the following keys "model",
"serial_number", "voltage_range","n_channels", "output_type" | [
"Return",
":",
"dict",
":",
"The",
"dict",
"contains",
"the",
"following",
"keys",
"model",
"serial_number",
"voltage_range",
"n_channels",
"output_type"
] | def parse_idn_string(idn_string: str) -> Dict[str, Any]:
"""
Return:
dict: The dict contains the following keys "model",
"serial_number", "voltage_range","n_channels", "output_type"
"""
result = re.search(
r"(HV|BS)(\d{3}) (\d{3}) (\d{2}) ([buqsm])",
idn_string
)
if result is None:
raise RuntimeError(
"Unexpected instrument response. Perhaps the model of the "
"instrument does not match the drivers expectation or a "
"firmware upgrade has taken place. Please get in touch "
"with a QCoDeS core developer"
)
converters: Dict[str, Callable[..., Any]] = OrderedDict({
"model": str,
"serial_number": str,
"voltage_range": float,
"n_channels": int,
"output_type": {
"b": "bipolar",
"u": "unipolar",
"q": "quadrupole",
"s": "steerer",
"m": "bipolar milivolt"
}.get
})
return {
name: converter(value)
for (name, converter), value in zip(converters.items(), result.groups())
} | [
"def",
"parse_idn_string",
"(",
"idn_string",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"result",
"=",
"re",
".",
"search",
"(",
"r\"(HV|BS)(\\d{3}) (\\d{3}) (\\d{2}) ([buqsm])\"",
",",
"idn_string",
")",
"if",
"result",
"is",
"None",
... | https://github.com/QCoDeS/Qcodes/blob/3cda2cef44812e2aa4672781f2423bf5f816f9f9/qcodes/instrument_drivers/stahl/stahl.py#L200-L236 | |
lsbardel/python-stdnet | 78db5320bdedc3f28c5e4f38cda13a4469e35db7 | stdnet/odm/fields.py | python | SymbolField.get_encoder | (self, params) | return encoders.Default(self.charset) | [] | def get_encoder(self, params):
return encoders.Default(self.charset) | [
"def",
"get_encoder",
"(",
"self",
",",
"params",
")",
":",
"return",
"encoders",
".",
"Default",
"(",
"self",
".",
"charset",
")"
] | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/fields.py#L492-L493 | |||
adobe/brackets-shell | c180d7ea812759ba50d25ab0685434c345343008 | gyp/pylib/gyp/generator/make.py | python | MakefileWriter.WritePchTargets | (self, pch_commands) | Writes make rules to compile prefix headers. | Writes make rules to compile prefix headers. | [
"Writes",
"make",
"rules",
"to",
"compile",
"prefix",
"headers",
"."
] | def WritePchTargets(self, pch_commands):
"""Writes make rules to compile prefix headers."""
if not pch_commands:
return
for gch, lang_flag, lang, input in pch_commands:
extra_flags = {
'c': '$(CFLAGS_C_$(BUILDTYPE))',
'cc': '$(CFLAGS_CC_$(BUILDTYPE))',
'm': '$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))',
'mm': '$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))',
}[lang]
var_name = {
'c': 'GYP_PCH_CFLAGS',
'cc': 'GYP_PCH_CXXFLAGS',
'm': 'GYP_PCH_OBJCFLAGS',
'mm': 'GYP_PCH_OBJCXXFLAGS',
}[lang]
self.WriteLn("%s: %s := %s " % (gch, var_name, lang_flag) +
"$(DEFS_$(BUILDTYPE)) "
"$(INCS_$(BUILDTYPE)) "
"$(CFLAGS_$(BUILDTYPE)) " +
extra_flags)
self.WriteLn('%s: %s FORCE_DO_CMD' % (gch, input))
self.WriteLn('\t@$(call do_cmd,pch_%s,1)' % lang)
self.WriteLn('')
assert ' ' not in gch, (
"Spaces in gch filenames not supported (%s)" % gch)
self.WriteLn('all_deps += %s' % gch)
self.WriteLn('') | [
"def",
"WritePchTargets",
"(",
"self",
",",
"pch_commands",
")",
":",
"if",
"not",
"pch_commands",
":",
"return",
"for",
"gch",
",",
"lang_flag",
",",
"lang",
",",
"input",
"in",
"pch_commands",
":",
"extra_flags",
"=",
"{",
"'c'",
":",
"'$(CFLAGS_C_$(BUILDT... | https://github.com/adobe/brackets-shell/blob/c180d7ea812759ba50d25ab0685434c345343008/gyp/pylib/gyp/generator/make.py#L1293-L1323 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/dotenv/parser.py | python | Position.advance | (self, string: str) | [] | def advance(self, string: str) -> None:
self.chars += len(string)
self.line += len(re.findall(_newline, string)) | [
"def",
"advance",
"(",
"self",
",",
"string",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"chars",
"+=",
"len",
"(",
"string",
")",
"self",
".",
"line",
"+=",
"len",
"(",
"re",
".",
"findall",
"(",
"_newline",
",",
"string",
")",
")"
] | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/dotenv/parser.py#L60-L62 | ||||
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/Exabeam/Integrations/Exabeam/Exabeam.py | python | Client.delete_watchlist_request | (self, watchlist_id: str = None) | Args:
watchlist_id: watchlist id | Args:
watchlist_id: watchlist id | [
"Args",
":",
"watchlist_id",
":",
"watchlist",
"id"
] | def delete_watchlist_request(self, watchlist_id: str = None):
"""
Args:
watchlist_id: watchlist id
"""
self._http_request('DELETE', url_suffix=f'/uba/api/watchlist/{watchlist_id}/') | [
"def",
"delete_watchlist_request",
"(",
"self",
",",
"watchlist_id",
":",
"str",
"=",
"None",
")",
":",
"self",
".",
"_http_request",
"(",
"'DELETE'",
",",
"url_suffix",
"=",
"f'/uba/api/watchlist/{watchlist_id}/'",
")"
] | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Exabeam/Integrations/Exabeam/Exabeam.py#L130-L136 | ||
largelymfs/topical_word_embeddings | 1ae3d15d0afcd3fcd39cc81eec4ad9463413a9f6 | TWE-2/gensim/models/lsimodel.py | python | LsiModel.__getitem__ | (self, bow, scaled=False, chunksize=512) | return result | Return latent representation, as a list of (topic_id, topic_value) 2-tuples.
This is done by folding input document into the latent topic space. | Return latent representation, as a list of (topic_id, topic_value) 2-tuples. | [
"Return",
"latent",
"representation",
"as",
"a",
"list",
"of",
"(",
"topic_id",
"topic_value",
")",
"2",
"-",
"tuples",
"."
] | def __getitem__(self, bow, scaled=False, chunksize=512):
"""
Return latent representation, as a list of (topic_id, topic_value) 2-tuples.
This is done by folding input document into the latent topic space.
"""
assert self.projection.u is not None, "decomposition not initialized yet"
# if the input vector is in fact a corpus, return a transformed corpus as a result
is_corpus, bow = utils.is_corpus(bow)
if is_corpus and chunksize:
# by default, transform `chunksize` documents at once, when called as `lsi[corpus]`.
# this chunking is completely transparent to the user, but it speeds
# up internal computations (one mat * mat multiplication, instead of
# `chunksize` smaller mat * vec multiplications).
return self._apply(bow, chunksize=chunksize)
if not is_corpus:
bow = [bow]
# convert input to scipy.sparse CSC, then do "sparse * dense = dense" multiplication
vec = matutils.corpus2csc(bow, num_terms=self.num_terms, dtype=self.projection.u.dtype)
topic_dist = (vec.T * self.projection.u[:, :self.num_topics]).T # (x^T * u).T = u^-1 * x
# # convert input to dense, then do dense * dense multiplication
# # ± same performance as above (BLAS dense * dense is better optimized than scipy.sparse), but consumes more memory
# vec = matutils.corpus2dense(bow, num_terms=self.num_terms, num_docs=len(bow))
# topic_dist = numpy.dot(self.projection.u[:, :self.num_topics].T, vec)
# # use numpy's advanced indexing to simulate sparse * dense
# # ± same speed again
# u = self.projection.u[:, :self.num_topics]
# topic_dist = numpy.empty((u.shape[1], len(bow)), dtype=u.dtype)
# for vecno, vec in enumerate(bow):
# indices, data = zip(*vec) if vec else ([], [])
# topic_dist[:, vecno] = numpy.dot(u.take(indices, axis=0).T, numpy.array(data, dtype=u.dtype))
if scaled:
topic_dist = (1.0 / self.projection.s[:self.num_topics]) * topic_dist # s^-1 * u^-1 * x
# convert a numpy array to gensim sparse vector = tuples of (feature_id, feature_weight),
# with no zero weights.
if not is_corpus:
# lsi[single_document]
result = matutils.full2sparse(topic_dist.flat)
else:
# lsi[chunk of documents]
result = matutils.Dense2Corpus(topic_dist)
return result | [
"def",
"__getitem__",
"(",
"self",
",",
"bow",
",",
"scaled",
"=",
"False",
",",
"chunksize",
"=",
"512",
")",
":",
"assert",
"self",
".",
"projection",
".",
"u",
"is",
"not",
"None",
",",
"\"decomposition not initialized yet\"",
"# if the input vector is in fac... | https://github.com/largelymfs/topical_word_embeddings/blob/1ae3d15d0afcd3fcd39cc81eec4ad9463413a9f6/TWE-2/gensim/models/lsimodel.py#L415-L463 | |
EtienneCmb/visbrain | b599038e095919dc193b12d5e502d127de7d03c9 | visbrain/io/download.py | python | get_data_url | (name, astype) | Get filename and url to a file.
Parameters
----------
name : string
Name of the file.
astype : string
Type of the file to download.
Returns
-------
url : string
Url to the file to download. | Get filename and url to a file. | [
"Get",
"filename",
"and",
"url",
"to",
"a",
"file",
"."
] | def get_data_url(name, astype):
"""Get filename and url to a file.
Parameters
----------
name : string
Name of the file.
astype : string
Type of the file to download.
Returns
-------
url : string
Url to the file to download.
"""
# Get path to data_url.txt :
urls = load_config_json(get_data_url_path())[astype]
# Try to get the file :
try:
url_to_download = urls[name]
if not bool(url_to_download.find('dl=1') + 1):
warn("The dropbox url should contains 'dl=1'.")
return urls[name]
except:
raise IOError(name + " not in the default path list of files.") | [
"def",
"get_data_url",
"(",
"name",
",",
"astype",
")",
":",
"# Get path to data_url.txt :",
"urls",
"=",
"load_config_json",
"(",
"get_data_url_path",
"(",
")",
")",
"[",
"astype",
"]",
"# Try to get the file :",
"try",
":",
"url_to_download",
"=",
"urls",
"[",
... | https://github.com/EtienneCmb/visbrain/blob/b599038e095919dc193b12d5e502d127de7d03c9/visbrain/io/download.py#L19-L43 | ||
Azure/azure-devops-cli-extension | 11334cd55806bef0b99c3bee5a438eed71e44037 | azure-devops/azext_devops/devops_sdk/v6_0/feed/feed_client.py | python | FeedClient.get_feed_permissions | (self, feed_id, project=None, include_ids=None, exclude_inherited_permissions=None, identity_descriptor=None, include_deleted_feeds=None) | return self._deserialize('[FeedPermission]', self._unwrap_collection(response)) | GetFeedPermissions.
[Preview API] Get the permissions for a feed.
:param str feed_id: Name or Id of the feed.
:param str project: Project ID or project name
:param bool include_ids: True to include user Ids in the response. Default is false.
:param bool exclude_inherited_permissions: True to only return explicitly set permissions on the feed. Default is false.
:param str identity_descriptor: Filter permissions to the provided identity.
:param bool include_deleted_feeds: If includeDeletedFeeds is true, then feedId must be specified by name and not by Guid.
:rtype: [FeedPermission] | GetFeedPermissions.
[Preview API] Get the permissions for a feed.
:param str feed_id: Name or Id of the feed.
:param str project: Project ID or project name
:param bool include_ids: True to include user Ids in the response. Default is false.
:param bool exclude_inherited_permissions: True to only return explicitly set permissions on the feed. Default is false.
:param str identity_descriptor: Filter permissions to the provided identity.
:param bool include_deleted_feeds: If includeDeletedFeeds is true, then feedId must be specified by name and not by Guid.
:rtype: [FeedPermission] | [
"GetFeedPermissions",
".",
"[",
"Preview",
"API",
"]",
"Get",
"the",
"permissions",
"for",
"a",
"feed",
".",
":",
"param",
"str",
"feed_id",
":",
"Name",
"or",
"Id",
"of",
"the",
"feed",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
... | def get_feed_permissions(self, feed_id, project=None, include_ids=None, exclude_inherited_permissions=None, identity_descriptor=None, include_deleted_feeds=None):
"""GetFeedPermissions.
[Preview API] Get the permissions for a feed.
:param str feed_id: Name or Id of the feed.
:param str project: Project ID or project name
:param bool include_ids: True to include user Ids in the response. Default is false.
:param bool exclude_inherited_permissions: True to only return explicitly set permissions on the feed. Default is false.
:param str identity_descriptor: Filter permissions to the provided identity.
:param bool include_deleted_feeds: If includeDeletedFeeds is true, then feedId must be specified by name and not by Guid.
:rtype: [FeedPermission]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if feed_id is not None:
route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
query_parameters = {}
if include_ids is not None:
query_parameters['includeIds'] = self._serialize.query('include_ids', include_ids, 'bool')
if exclude_inherited_permissions is not None:
query_parameters['excludeInheritedPermissions'] = self._serialize.query('exclude_inherited_permissions', exclude_inherited_permissions, 'bool')
if identity_descriptor is not None:
query_parameters['identityDescriptor'] = self._serialize.query('identity_descriptor', identity_descriptor, 'str')
if include_deleted_feeds is not None:
query_parameters['includeDeletedFeeds'] = self._serialize.query('include_deleted_feeds', include_deleted_feeds, 'bool')
response = self._send(http_method='GET',
location_id='be8c1476-86a7-44ed-b19d-aec0e9275cd8',
version='6.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[FeedPermission]', self._unwrap_collection(response)) | [
"def",
"get_feed_permissions",
"(",
"self",
",",
"feed_id",
",",
"project",
"=",
"None",
",",
"include_ids",
"=",
"None",
",",
"exclude_inherited_permissions",
"=",
"None",
",",
"identity_descriptor",
"=",
"None",
",",
"include_deleted_feeds",
"=",
"None",
")",
... | https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/feed/feed_client.py#L428-L458 | |
edfungus/Crouton | ada98b3930192938a48909072b45cb84b945f875 | clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/_vendor/packaging/version.py | python | parse | (version) | Parse the given version string and return either a :class:`Version` object
or a :class:`LegacyVersion` object depending on if the given version is
a valid PEP 440 version or a legacy version. | Parse the given version string and return either a :class:`Version` object
or a :class:`LegacyVersion` object depending on if the given version is
a valid PEP 440 version or a legacy version. | [
"Parse",
"the",
"given",
"version",
"string",
"and",
"return",
"either",
"a",
":",
"class",
":",
"Version",
"object",
"or",
"a",
":",
"class",
":",
"LegacyVersion",
"object",
"depending",
"on",
"if",
"the",
"given",
"version",
"is",
"a",
"valid",
"PEP",
... | def parse(version):
"""
Parse the given version string and return either a :class:`Version` object
or a :class:`LegacyVersion` object depending on if the given version is
a valid PEP 440 version or a legacy version.
"""
try:
return Version(version)
except InvalidVersion:
return LegacyVersion(version) | [
"def",
"parse",
"(",
"version",
")",
":",
"try",
":",
"return",
"Version",
"(",
"version",
")",
"except",
"InvalidVersion",
":",
"return",
"LegacyVersion",
"(",
"version",
")"
] | https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/_vendor/packaging/version.py#L34-L43 | ||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/ex-submodules/dimagi/utils/retry.py | python | retry_on | (
*errors,
should_retry=lambda err: True,
delays=(0.1, 1, 2, 4, 8),
) | return retry_decorator | Make a decorator to retry function on any of the given errors
Retry up to 5 times with exponential backoff. Raise the last
received error if all calls fail.
:param *errors: One or more errors (exception classes) to catch and retry.
:param should_retry: Optional function taking one argument, an
exception instance, that returns true to signal a retry and false
to signal that the error should be re-raised.
:param delays: A list of delays given in seconds.
:returns: a decorator to be applied to functions that should be
retried if they raise one of the given errors. | Make a decorator to retry function on any of the given errors | [
"Make",
"a",
"decorator",
"to",
"retry",
"function",
"on",
"any",
"of",
"the",
"given",
"errors"
] | def retry_on(
*errors,
should_retry=lambda err: True,
delays=(0.1, 1, 2, 4, 8),
):
"""Make a decorator to retry function on any of the given errors
Retry up to 5 times with exponential backoff. Raise the last
received error if all calls fail.
:param *errors: One or more errors (exception classes) to catch and retry.
:param should_retry: Optional function taking one argument, an
exception instance, that returns true to signal a retry and false
to signal that the error should be re-raised.
:param delays: A list of delays given in seconds.
:returns: a decorator to be applied to functions that should be
retried if they raise one of the given errors.
"""
errors = tuple(errors)
def retry_decorator(func):
@wraps(func)
def retry(*args, **kw):
for delay in chain(delays, [None]):
try:
return func(*args, **kw)
except errors as err:
if delay is None or not should_retry(err):
raise
sleep(delay)
return retry
return retry_decorator | [
"def",
"retry_on",
"(",
"*",
"errors",
",",
"should_retry",
"=",
"lambda",
"err",
":",
"True",
",",
"delays",
"=",
"(",
"0.1",
",",
"1",
",",
"2",
",",
"4",
",",
"8",
")",
",",
")",
":",
"errors",
"=",
"tuple",
"(",
"errors",
")",
"def",
"retry... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/ex-submodules/dimagi/utils/retry.py#L6-L37 | |
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/models/v1_persistent_volume_status.py | python | V1PersistentVolumeStatus.__ne__ | (self, other) | return not self == other | Returns true if both objects are not equal | Returns true if both objects are not equal | [
"Returns",
"true",
"if",
"both",
"objects",
"are",
"not",
"equal"
] | def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other | [
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"return",
"not",
"self",
"==",
"other"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_persistent_volume_status.py#L165-L169 | |
phantomcyber/playbooks | 9e850ecc44cb98c5dde53784744213a1ed5799bd | symantec_ioc_data_enhancement.py | python | get_report_callback | (action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None) | return | [] | def get_report_callback(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None):
phantom.debug('get_report_callback() called')
reversinglabs_file_rep(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
lookup_url_1(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
domain_reputation_1(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
ip_reputation(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
virustotal_file_reputation(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
google_url_reputation(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
deepsight_url_reputation(action=action, success=success, container=container, results=results, handle=handle, custom_function=custom_function)
return | [
"def",
"get_report_callback",
"(",
"action",
"=",
"None",
",",
"success",
"=",
"None",
",",
"container",
"=",
"None",
",",
"results",
"=",
"None",
",",
"handle",
"=",
"None",
",",
"filtered_artifacts",
"=",
"None",
",",
"filtered_results",
"=",
"None",
","... | https://github.com/phantomcyber/playbooks/blob/9e850ecc44cb98c5dde53784744213a1ed5799bd/symantec_ioc_data_enhancement.py#L253-L264 | |||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/data/processors/glue.py | python | QnliProcessor.get_train_examples | (self, data_dir) | return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") | [
"def",
"get_train_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"return",
"self",
".",
"_create_examples",
"(",
"self",
".",
"_read_tsv",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"train.tsv\"",
")",
")",
",",
"\"train\"",
")"
] | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/data/processors/glue.py#L486-L488 | |
tdda/tdda | 79bd8b8352c18312354ba47eee6d70c7631bcba3 | tdda/constraints/extension.py | python | BaseConstraintCalculator.find_rexes | (self, colname, values=None) | Generate a list of regular expressions that cover all of
the patterns found in the (string) column. | Generate a list of regular expressions that cover all of
the patterns found in the (string) column. | [
"Generate",
"a",
"list",
"of",
"regular",
"expressions",
"that",
"cover",
"all",
"of",
"the",
"patterns",
"found",
"in",
"the",
"(",
"string",
")",
"column",
"."
] | def find_rexes(self, colname, values=None):
"""
Generate a list of regular expressions that cover all of
the patterns found in the (string) column.
"""
raise NotImplementedError('find_rexes') | [
"def",
"find_rexes",
"(",
"self",
",",
"colname",
",",
"values",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'find_rexes'",
")"
] | https://github.com/tdda/tdda/blob/79bd8b8352c18312354ba47eee6d70c7631bcba3/tdda/constraints/extension.py#L330-L335 | ||
materialsproject/pymatgen | 8128f3062a334a2edd240e4062b5b9bdd1ae6f58 | pymatgen/io/wannier90.py | python | Unk.__init__ | (self, ik: int, data: np.ndarray) | Initialize Unk class.
Args:
ik (int): index of the kpoint UNK file is for
data (np.ndarray): data from the UNK file that has shape (nbnd,
ngx, ngy, ngz) or (nbnd, 2, ngx, ngy, ngz) if noncollinear | Initialize Unk class. | [
"Initialize",
"Unk",
"class",
"."
] | def __init__(self, ik: int, data: np.ndarray) -> None:
"""
Initialize Unk class.
Args:
ik (int): index of the kpoint UNK file is for
data (np.ndarray): data from the UNK file that has shape (nbnd,
ngx, ngy, ngz) or (nbnd, 2, ngx, ngy, ngz) if noncollinear
"""
self.ik = ik
self.data = data | [
"def",
"__init__",
"(",
"self",
",",
"ik",
":",
"int",
",",
"data",
":",
"np",
".",
"ndarray",
")",
"->",
"None",
":",
"self",
".",
"ik",
"=",
"ik",
"self",
".",
"data",
"=",
"data"
] | https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/io/wannier90.py#L56-L66 | ||
haiwen/seahub | e92fcd44e3e46260597d8faa9347cb8222b8b10d | seahub/two_factor/models/phone.py | python | PhoneDevice.__eq__ | (self, other) | return self.number == other.number \
and self.method == other.method \
and self.key == other.key | [] | def __eq__(self, other):
if not isinstance(other, PhoneDevice):
return False
return self.number == other.number \
and self.method == other.method \
and self.key == other.key | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"PhoneDevice",
")",
":",
"return",
"False",
"return",
"self",
".",
"number",
"==",
"other",
".",
"number",
"and",
"self",
".",
"method",
"==",
"other",
... | https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/seahub/two_factor/models/phone.py#L41-L46 | |||
edfungus/Crouton | ada98b3930192938a48909072b45cb84b945f875 | clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py | python | iteritems | (d) | return iter(getattr(d, _iteritems)()) | Return an iterator over the (key, value) pairs of a dictionary. | Return an iterator over the (key, value) pairs of a dictionary. | [
"Return",
"an",
"iterator",
"over",
"the",
"(",
"key",
"value",
")",
"pairs",
"of",
"a",
"dictionary",
"."
] | def iteritems(d):
"""Return an iterator over the (key, value) pairs of a dictionary."""
return iter(getattr(d, _iteritems)()) | [
"def",
"iteritems",
"(",
"d",
")",
":",
"return",
"iter",
"(",
"getattr",
"(",
"d",
",",
"_iteritems",
")",
"(",
")",
")"
] | https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py#L271-L273 | |
SethMMorton/natsort | 9616d2909899e1a47735c6fcdb6fa84d08c03206 | natsort/__main__.py | python | check_filters | (filters: Optional[NumPairIter]) | Execute range_check for every element of an iterable.
Parameters
----------
filters : iterable
The collection of filters to check. Each element
must be a two-element tuple of floats or ints.
Returns
-------
The input as-is, or None if it evaluates to False.
Raises
------
ValueError
Low is greater than or equal to high for any element. | Execute range_check for every element of an iterable. | [
"Execute",
"range_check",
"for",
"every",
"element",
"of",
"an",
"iterable",
"."
] | def check_filters(filters: Optional[NumPairIter]) -> Optional[List[NumPair]]:
"""
Execute range_check for every element of an iterable.
Parameters
----------
filters : iterable
The collection of filters to check. Each element
must be a two-element tuple of floats or ints.
Returns
-------
The input as-is, or None if it evaluates to False.
Raises
------
ValueError
Low is greater than or equal to high for any element.
"""
if not filters:
return None
try:
return [range_check(f[0], f[1]) for f in filters]
except ValueError as err:
raise ValueError("Error in --filter: " + str(err)) | [
"def",
"check_filters",
"(",
"filters",
":",
"Optional",
"[",
"NumPairIter",
"]",
")",
"->",
"Optional",
"[",
"List",
"[",
"NumPair",
"]",
"]",
":",
"if",
"not",
"filters",
":",
"return",
"None",
"try",
":",
"return",
"[",
"range_check",
"(",
"f",
"[",... | https://github.com/SethMMorton/natsort/blob/9616d2909899e1a47735c6fcdb6fa84d08c03206/natsort/__main__.py#L209-L234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.