本文整理汇总了Python中functools.partial方法的典型用法代码示例。如果您正苦于以下问题:Python functools.partial方法的具体用法?Python functools.partial怎么用?Python functools.partial使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类functools
的用法示例。
在下文中一共展示了functools.partial方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_plugins
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def load_plugins():
here = os.path.abspath(os.path.dirname(__file__))
get_path = partial(os.path.join, here)
plugin_dir = get_path('plugins')
plugin_base = PluginBase(
package='wafw00f.plugins', searchpath=[plugin_dir]
)
plugin_source = plugin_base.make_plugin_source(
searchpath=[plugin_dir], persist=True
)
plugin_dict = {}
for plugin_name in plugin_source.list_plugins():
plugin_dict[plugin_name] = plugin_source.load_plugin(plugin_name)
return plugin_dict
示例2: tasks
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def tasks(args):
list_clusters = clients.ecs.get_paginator("list_clusters")
list_tasks = clients.ecs.get_paginator("list_tasks")
def list_tasks_worker(worker_args):
cluster, status = worker_args
return cluster, status, list(paginate(list_tasks, cluster=cluster, desiredStatus=status))
def describe_tasks_worker(t, cluster=None):
return clients.ecs.describe_tasks(cluster=cluster, tasks=t)["tasks"] if t else []
task_descs = []
if args.clusters is None:
args.clusters = [__name__.replace(".", "_")] if args.tasks else list(paginate(list_clusters))
if args.tasks:
task_descs = describe_tasks_worker(args.tasks, cluster=args.clusters[0])
else:
with ThreadPoolExecutor() as executor:
for cluster, status, tasks in executor.map(list_tasks_worker, product(args.clusters, args.desired_status)):
worker = partial(describe_tasks_worker, cluster=cluster)
descs = executor.map(worker, (tasks[pos:pos + 100] for pos in range(0, len(tasks), 100)))
task_descs += sum(descs, [])
page_output(tabulate(task_descs, args))
示例3: get_arg_serializer
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def get_arg_serializer(arg_type):
if isinstance(arg_type, GraphQLNonNull):
return get_arg_serializer(arg_type.of_type)
if isinstance(arg_type, GraphQLInputField):
return get_arg_serializer(arg_type.type)
if isinstance(arg_type, GraphQLInputObjectType):
serializers = {k: get_arg_serializer(v) for k, v in arg_type.fields.items()}
return lambda value: ObjectValueNode(
fields=FrozenList(
ObjectFieldNode(name=NameNode(value=k), value=serializers[k](v))
for k, v in value.items()
)
)
if isinstance(arg_type, GraphQLList):
inner_serializer = get_arg_serializer(arg_type.of_type)
return partial(serialize_list, inner_serializer)
if isinstance(arg_type, GraphQLEnumType):
return lambda value: EnumValueNode(value=arg_type.serialize(value))
return lambda value: ast_from_value(arg_type.serialize(value), arg_type)
示例4: subscribe
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def subscribe(self, channel, callback=None, priority=None):
"""Add the given callback at the given channel (if not present).
If callback is None, return a partial suitable for decorating
the callback.
"""
if callback is None:
return functools.partial(
self.subscribe,
channel,
priority=priority,
)
ch_listeners = self.listeners.setdefault(channel, set())
ch_listeners.add(callback)
if priority is None:
priority = getattr(callback, 'priority', 50)
self._priorities[(channel, callback)] = priority
示例5: multi_apply
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def multi_apply(func, *args, **kwargs):
"""Apply function to a list of arguments.
Note:
This function applies the ``func`` to multiple inputs and
map the multiple outputs of the ``func`` into different
list. Each list contains the same type of outputs corresponding
to different inputs.
Args:
func (Function): A function that will be applied to a list of
arguments
Returns:
tuple(list): A tuple containing multiple list, each list contains
a kind of returned results by the function
"""
pfunc = partial(func, **kwargs) if kwargs else func
map_results = map(pfunc, *args)
return tuple(map(list, zip(*map_results)))
示例6: fprop
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def fprop(self, x, **kwargs):
del kwargs
my_conv = functools.partial(tf.layers.conv2d,
kernel_size=3,
strides=2,
padding='valid',
activation=tf.nn.relu,
kernel_initializer=HeReLuNormalInitializer)
my_dense = functools.partial(
tf.layers.dense, kernel_initializer=HeReLuNormalInitializer)
with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
for depth in [96, 256, 384, 384, 256]:
x = my_conv(x, depth)
y = tf.layers.flatten(x)
y = my_dense(y, 4096, tf.nn.relu)
y = fc7 = my_dense(y, 4096, tf.nn.relu)
y = my_dense(y, 1000)
return {'fc7': fc7,
self.O_LOGITS: y,
self.O_PROBS: tf.nn.softmax(logits=y)}
示例7: run
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def run(self):
self.monitor.start()
notifier = poll.Poll.for_events(
(self.monitor, 'r'), (self._stop_event.source, 'r'))
while True:
for file_descriptor, event in eintr_retry_call(notifier.poll):
if file_descriptor == self._stop_event.source.fileno():
# in case of a stop event, close our pipe side, and
# return from the thread
self._stop_event.source.close()
return
elif file_descriptor == self.monitor.fileno() and event == 'r':
read_device = partial(eintr_retry_call, self.monitor.poll, timeout=0)
for device in iter(read_device, None):
self._callback(device)
else:
raise EnvironmentError('Observed monitor hung up')
示例8: _create_evaluation_spec
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def _create_evaluation_spec(params, audio_adapter, audio_path):
""" Setup eval spec evaluating ever n seconds
:param params: TF params to build spec from.
:returns: Built evaluation spec.
"""
input_fn = partial(
get_validation_dataset,
params,
audio_adapter,
audio_path)
evaluation_spec = tf.estimator.EvalSpec(
input_fn=input_fn,
steps=None,
throttle_secs=params['throttle_secs'])
return evaluation_spec
示例9: __init__
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def __init__(self, learning_rate, max_iteration_steps, seed=None):
"""Initializes a `Generator` that builds `SimpleCNNs`.
Args:
learning_rate: The float learning rate to use.
max_iteration_steps: The number of steps per iteration.
seed: The random seed.
Returns:
An instance of `Generator`.
"""
self._seed = seed
self._cnn_builder_fn = functools.partial(
SimpleCNNBuilder,
learning_rate=learning_rate,
max_iteration_steps=max_iteration_steps)
示例10: __init__
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def __init__(self, input_shape, num_hidden,
h2h_kernel=(3, 3), h2h_dilate=(1, 1),
i2h_kernel=(3, 3), i2h_stride=(1, 1),
i2h_pad=(1, 1), i2h_dilate=(1, 1),
i2h_weight_initializer=None, h2h_weight_initializer=None,
i2h_bias_initializer='zeros', h2h_bias_initializer='zeros',
activation=functools.partial(symbol.LeakyReLU, act_type='leaky', slope=0.2),
prefix='ConvRNN_', params=None, conv_layout='NCHW'):
super(ConvRNNCell, self).__init__(input_shape=input_shape, num_hidden=num_hidden,
h2h_kernel=h2h_kernel, h2h_dilate=h2h_dilate,
i2h_kernel=i2h_kernel, i2h_stride=i2h_stride,
i2h_pad=i2h_pad, i2h_dilate=i2h_dilate,
i2h_weight_initializer=i2h_weight_initializer,
h2h_weight_initializer=h2h_weight_initializer,
i2h_bias_initializer=i2h_bias_initializer,
h2h_bias_initializer=h2h_bias_initializer,
activation=activation, prefix=prefix,
params=params, conv_layout=conv_layout)
示例11: main
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def main(unused_argv):
assert FLAGS.checkpoint_dir, '`checkpoint_dir` is missing.'
assert FLAGS.eval_dir, '`eval_dir` is missing.'
if FLAGS.pipeline_config_path:
model_config, eval_config, input_config = get_configs_from_pipeline_file()
else:
model_config, eval_config, input_config = get_configs_from_multiple_files()
model_fn = functools.partial(
model_builder.build,
model_config=model_config,
is_training=False)
create_input_dict_fn = functools.partial(
input_reader_builder.build,
input_config)
label_map = label_map_util.load_labelmap(input_config.label_map_path)
max_num_classes = max([item.id for item in label_map.item])
categories = label_map_util.convert_label_map_to_categories(
label_map, max_num_classes)
evaluator.evaluate(create_input_dict_fn, model_fn, eval_config, categories,
FLAGS.checkpoint_dir, FLAGS.eval_dir)
示例12: _build_randomization_function_dict
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def _build_randomization_function_dict(self, env):
func_dict = {}
func_dict["mass"] = functools.partial(
self._randomize_masses, minitaur=env.minitaur)
func_dict["inertia"] = functools.partial(
self._randomize_inertia, minitaur=env.minitaur)
func_dict["latency"] = functools.partial(
self._randomize_latency, minitaur=env.minitaur)
func_dict["joint friction"] = functools.partial(
self._randomize_joint_friction, minitaur=env.minitaur)
func_dict["motor friction"] = functools.partial(
self._randomize_motor_friction, minitaur=env.minitaur)
func_dict["restitution"] = functools.partial(
self._randomize_contact_restitution, minitaur=env.minitaur)
func_dict["lateral friction"] = functools.partial(
self._randomize_contact_friction, minitaur=env.minitaur)
func_dict["battery"] = functools.partial(
self._randomize_battery_level, minitaur=env.minitaur)
func_dict["motor strength"] = functools.partial(
self._randomize_motor_strength, minitaur=env.minitaur)
# Settinmg control step needs access to the environment.
func_dict["control step"] = functools.partial(
self._randomize_control_step, env=env)
return func_dict
示例13: step
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def step(self, action, blocking=True):
"""Step the environment.
Args:
action: The action to apply to the environment.
blocking: Whether to wait for the result.
Returns:
Transition tuple when blocking, otherwise callable that returns the
transition tuple.
"""
self._conn.send((self._ACTION, action))
if blocking:
return self._receive(self._TRANSITION)
else:
return functools.partial(self._receive, self._TRANSITION)
示例14: load_textset
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def load_textset(n_jobs, use_gpu, pin_memory, corpus, text):
# Text tokenizer
tokenizer = load_text_encoder(**text)
# Dataset
tr_set, dv_set, tr_loader_bs, dv_loader_bs, data_msg = create_textset(
tokenizer, **corpus)
collect_tr = partial(collect_text_batch, mode='train')
collect_dv = partial(collect_text_batch, mode='dev')
# Dataloader (Text data stored in RAM, no need num_workers)
tr_set = DataLoader(tr_set, batch_size=tr_loader_bs, shuffle=True, drop_last=True, collate_fn=collect_tr,
num_workers=0, pin_memory=use_gpu)
dv_set = DataLoader(dv_set, batch_size=dv_loader_bs, shuffle=False, drop_last=False, collate_fn=collect_dv,
num_workers=0, pin_memory=pin_memory)
# Messages to show
data_msg.append('I/O spec. | Token type = {}\t| Vocab size = {}'
.format(tokenizer.token_type, tokenizer.vocab_size))
return tr_set, dv_set, tokenizer.vocab_size, tokenizer, data_msg
示例15: set_alert_callback
# 需要导入模块: import functools [as 别名]
# 或者: from functools import partial [as 别名]
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callback):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
#Not working
#def get_clipboard(self):
# return self.http.post("/wda/getPasteboard").value
# Not working
#def siri_activate(self, text):
# self.http.post("/wda/siri/activate", {"text": text})