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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
openai/imitation | 8a2ed905e2ac54bda0f71e5ee364e90568e6d031 | scripts/vis_mj.py | python | main | () | [] | def main():
np.set_printoptions(suppress=True, precision=5, linewidth=1000)
parser = argparse.ArgumentParser()
# MDP options
parser.add_argument('policy', type=str)
parser.add_argument('--eval_only', action='store_true')
parser.add_argument('--max_traj_len', type=int, default=None) # only used for saving
parser.add_argument('--out', type=str, default=None)
parser.add_argument('--count', type=int, default=None)
parser.add_argument('--deterministic', action='store_true')
args = parser.parse_args()
# Load the saved state
policy_file, policy_key = util.split_h5_name(args.policy)
print 'Loading policy parameters from %s in %s' % (policy_key, policy_file)
with h5py.File(policy_file, 'r') as f:
train_args = json.loads(f.attrs['args'])
dset = f[policy_key]
import pprint
pprint.pprint(dict(dset.attrs))
# Initialize the MDP
env_name = train_args['env_name']
print 'Loading environment', env_name
mdp = rlgymenv.RLGymMDP(env_name)
util.header('MDP observation space, action space sizes: %d, %d\n' % (mdp.obs_space.dim, mdp.action_space.storage_size))
if args.max_traj_len is None:
args.max_traj_len = mdp.env_spec.timestep_limit
util.header('Max traj len is {}'.format(args.max_traj_len))
# Initialize the policy and load its parameters
enable_obsnorm = bool(train_args['enable_obsnorm']) if 'enable_obsnorm' in train_args else train_args['obsnorm_mode'] != 'none'
if isinstance(mdp.action_space, policyopt.ContinuousSpace):
policy_cfg = rl.GaussianPolicyConfig(
hidden_spec=train_args['policy_hidden_spec'],
min_stdev=0.,
init_logstdev=0.,
enable_obsnorm=enable_obsnorm)
policy = rl.GaussianPolicy(policy_cfg, mdp.obs_space, mdp.action_space, 'GaussianPolicy')
else:
policy_cfg = rl.GibbsPolicyConfig(
hidden_spec=train_args['policy_hidden_spec'],
enable_obsnorm=enable_obsnorm)
policy = rl.GibbsPolicy(policy_cfg, mdp.obs_space, mdp.action_space, 'GibbsPolicy')
policy.load_h5(policy_file, policy_key)
if args.eval_only:
n = 50
print 'Evaluating based on {} trajs'.format(n)
if False:
eval_trajbatch = mdp.sim_mp(
policy_fn=lambda obs_B_Do: policy.sample_actions(obs_B_Do, args.deterministic),
obsfeat_fn=lambda obs:obs,
cfg=policyopt.SimConfig(
min_num_trajs=n, min_total_sa=-1,
batch_size=None, max_traj_len=args.max_traj_len))
returns = eval_trajbatch.r.padded(fill=0.).sum(axis=1)
avgr = eval_trajbatch.r.stacked.mean()
lengths = np.array([len(traj) for traj in eval_trajbatch])
ent = policy._compute_actiondist_entropy(eval_trajbatch.adist.stacked).mean()
print 'ret: {} +/- {}'.format(returns.mean(), returns.std())
print 'avgr: {}'.format(avgr)
print 'len: {} +/- {}'.format(lengths.mean(), lengths.std())
print 'ent: {}'.format(ent)
print returns
else:
returns = []
lengths = []
sim = mdp.new_sim()
for i_traj in xrange(n):
print i_traj, n
sim.reset()
totalr = 0.
l = 0
while not sim.done:
a = policy.sample_actions(sim.obs[None,:], bool(args.deterministic))[0][0,:]
r = sim.step(a)
totalr += r
l += 1
returns.append(totalr)
lengths.append(l)
import IPython; IPython.embed()
elif args.out is not None:
# Sample trajs and write to file
print 'Saving traj samples to file: {}'.format(args.out)
assert not os.path.exists(args.out)
assert args.count > 0
# Simulate to create a trajectory batch
util.header('Sampling {} trajectories of maximum length {}'.format(args.count, args.max_traj_len))
trajs = []
for i in tqdm.trange(args.count):
trajs.append(mdp.sim_single(
lambda obs: policy.sample_actions(obs, args.deterministic),
lambda obs: obs,
args.max_traj_len))
trajbatch = policyopt.TrajBatch.FromTrajs(trajs)
print
print 'Average return:', trajbatch.r.padded(fill=0.).sum(axis=1).mean()
# Save the trajs to a file
with h5py.File(args.out, 'w') as f:
def write(name, a):
# chunks of 128 trajs each
f.create_dataset(name, data=a, chunks=(min(128, a.shape[0]),)+a.shape[1:], compression='gzip', compression_opts=9)
# Right-padded trajectory data
write('obs_B_T_Do', trajbatch.obs.padded(fill=0.))
write('a_B_T_Da', trajbatch.a.padded(fill=0.))
write('r_B_T', trajbatch.r.padded(fill=0.))
# Trajectory lengths
write('len_B', np.array([len(traj) for traj in trajbatch], dtype=np.int32))
# Also save args to this script
argstr = json.dumps(vars(args), separators=(',', ':'), indent=2)
f.attrs['args'] = argstr
else:
# Animate
sim = mdp.new_sim()
raw_obs, normalized_obs = [], []
while True:
sim.reset()
totalr = 0.
steps = 0
while not sim.done:
raw_obs.append(sim.obs[None,:])
normalized_obs.append(policy.compute_internal_normalized_obsfeat(sim.obs[None,:]))
a = policy.sample_actions(sim.obs[None,:], args.deterministic)[0][0,:]
r = sim.step(a)
totalr += r
steps += 1
sim.draw()
if steps % 1000 == 0:
tmpraw = np.concatenate(raw_obs, axis=0)
tmpnormed = np.concatenate(normalized_obs, axis=0)
print 'raw mean, raw std, normed mean, normed std'
print np.stack([tmpraw.mean(0), tmpraw.std(0), tmpnormed.mean(0), tmpnormed.std(0)])
print 'Steps: %d, return: %.5f' % (steps, totalr) | [
"def",
"main",
"(",
")",
":",
"np",
".",
"set_printoptions",
"(",
"suppress",
"=",
"True",
",",
"precision",
"=",
"5",
",",
"linewidth",
"=",
"1000",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# MDP options",
"parser",
".",
"add_ar... | https://github.com/openai/imitation/blob/8a2ed905e2ac54bda0f71e5ee364e90568e6d031/scripts/vis_mj.py#L13-L158 | ||||
nlloyd/SubliminalCollaborator | 5c619e17ddbe8acb9eea8996ec038169ddcd50a1 | libs/twisted/words/protocols/jabber/client.py | python | XMPPAuthenticator.associateWithStream | (self, xs) | Register with the XML stream.
Populates stream's list of initializers, along with their
requiredness. This list is used by
L{ConnectAuthenticator.initializeStream} to perform the initalization
steps. | Register with the XML stream. | [
"Register",
"with",
"the",
"XML",
"stream",
"."
] | def associateWithStream(self, xs):
"""
Register with the XML stream.
Populates stream's list of initializers, along with their
requiredness. This list is used by
L{ConnectAuthenticator.initializeStream} to perform the initalization
steps.
"""
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [CheckVersionInitializer(xs)]
inits = [ (xmlstream.TLSInitiatingInitializer, False),
(sasl.SASLInitiatingInitializer, True),
(BindInitializer, False),
(SessionInitializer, False),
]
for initClass, required in inits:
init = initClass(xs)
init.required = required
xs.initializers.append(init) | [
"def",
"associateWithStream",
"(",
"self",
",",
"xs",
")",
":",
"xmlstream",
".",
"ConnectAuthenticator",
".",
"associateWithStream",
"(",
"self",
",",
"xs",
")",
"xs",
".",
"initializers",
"=",
"[",
"CheckVersionInitializer",
"(",
"xs",
")",
"]",
"inits",
"... | https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/words/protocols/jabber/client.py#L347-L368 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/sqlalchemy/ext/automap.py | python | automap_base | (declarative_base=None, **kw) | return type(
Base.__name__,
(AutomapBase, Base,),
{"__abstract__": True, "classes": util.Properties({})}
) | Produce a declarative automap base.
This function produces a new base class that is a product of the
:class:`.AutomapBase` class as well a declarative base produced by
:func:`.declarative.declarative_base`.
All parameters other than ``declarative_base`` are keyword arguments
that are passed directly to the :func:`.declarative.declarative_base`
function.
:param declarative_base: an existing class produced by
:func:`.declarative.declarative_base`. When this is passed, the function
no longer invokes :func:`.declarative.declarative_base` itself, and all
other keyword arguments are ignored.
:param \**kw: keyword arguments are passed along to
:func:`.declarative.declarative_base`. | Produce a declarative automap base. | [
"Produce",
"a",
"declarative",
"automap",
"base",
"."
] | def automap_base(declarative_base=None, **kw):
"""Produce a declarative automap base.
This function produces a new base class that is a product of the
:class:`.AutomapBase` class as well a declarative base produced by
:func:`.declarative.declarative_base`.
All parameters other than ``declarative_base`` are keyword arguments
that are passed directly to the :func:`.declarative.declarative_base`
function.
:param declarative_base: an existing class produced by
:func:`.declarative.declarative_base`. When this is passed, the function
no longer invokes :func:`.declarative.declarative_base` itself, and all
other keyword arguments are ignored.
:param \**kw: keyword arguments are passed along to
:func:`.declarative.declarative_base`.
"""
if declarative_base is None:
Base = _declarative_base(**kw)
else:
Base = declarative_base
return type(
Base.__name__,
(AutomapBase, Base,),
{"__abstract__": True, "classes": util.Properties({})}
) | [
"def",
"automap_base",
"(",
"declarative_base",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"declarative_base",
"is",
"None",
":",
"Base",
"=",
"_declarative_base",
"(",
"*",
"*",
"kw",
")",
"else",
":",
"Base",
"=",
"declarative_base",
"return",
"... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/sqlalchemy/ext/automap.py#L794-L823 | |
golismero/golismero | 7d605b937e241f51c1ca4f47b20f755eeefb9d76 | thirdparty_libs/nltk/internals.py | python | config_java | (bin=None, options=None, verbose=True) | Configure nltk's java interface, by letting nltk know where it can
find the Java binary, and what extra options (if any) should be
passed to Java when it is run.
:param bin: The full path to the Java binary. If not specified,
then nltk will search the system for a Java binary; and if
one is not found, it will raise a ``LookupError`` exception.
:type bin: str
:param options: A list of options that should be passed to the
Java binary when it is called. A common value is
``'-Xmx512m'``, which tells Java binary to increase
the maximum heap size to 512 megabytes. If no options are
specified, then do not modify the options list.
:type options: list(str) | Configure nltk's java interface, by letting nltk know where it can
find the Java binary, and what extra options (if any) should be
passed to Java when it is run. | [
"Configure",
"nltk",
"s",
"java",
"interface",
"by",
"letting",
"nltk",
"know",
"where",
"it",
"can",
"find",
"the",
"Java",
"binary",
"and",
"what",
"extra",
"options",
"(",
"if",
"any",
")",
"should",
"be",
"passed",
"to",
"Java",
"when",
"it",
"is",
... | def config_java(bin=None, options=None, verbose=True):
"""
Configure nltk's java interface, by letting nltk know where it can
find the Java binary, and what extra options (if any) should be
passed to Java when it is run.
:param bin: The full path to the Java binary. If not specified,
then nltk will search the system for a Java binary; and if
one is not found, it will raise a ``LookupError`` exception.
:type bin: str
:param options: A list of options that should be passed to the
Java binary when it is called. A common value is
``'-Xmx512m'``, which tells Java binary to increase
the maximum heap size to 512 megabytes. If no options are
specified, then do not modify the options list.
:type options: list(str)
"""
global _java_bin, _java_options
_java_bin = find_binary('java', bin, env_vars=['JAVAHOME', 'JAVA_HOME'], verbose=verbose)
if options is not None:
if isinstance(options, basestring):
options = options.split()
_java_options = list(options) | [
"def",
"config_java",
"(",
"bin",
"=",
"None",
",",
"options",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"global",
"_java_bin",
",",
"_java_options",
"_java_bin",
"=",
"find_binary",
"(",
"'java'",
",",
"bin",
",",
"env_vars",
"=",
"[",
"'JAVAH... | https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/nltk/internals.py#L72-L95 | ||
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | tokumx/datadog_checks/tokumx/vendor/pymongo/message.py | python | _do_batched_insert | (collection_name, docs, check_keys,
safe, last_error_args, continue_on_error, opts,
ctx) | Insert `docs` using multiple batches. | Insert `docs` using multiple batches. | [
"Insert",
"docs",
"using",
"multiple",
"batches",
"."
] | def _do_batched_insert(collection_name, docs, check_keys,
safe, last_error_args, continue_on_error, opts,
ctx):
"""Insert `docs` using multiple batches.
"""
def _insert_message(insert_message, send_safe):
"""Build the insert message with header and GLE.
"""
request_id, final_message = __pack_message(2002, insert_message)
if send_safe:
request_id, error_message, _ = __last_error(collection_name,
last_error_args)
final_message += error_message
return request_id, final_message
send_safe = safe or not continue_on_error
last_error = None
data = StringIO()
data.write(struct.pack("<i", int(continue_on_error)))
data.write(bson._make_c_string(collection_name))
message_length = begin_loc = data.tell()
has_docs = False
to_send = []
for doc in docs:
encoded = bson.BSON.encode(doc, check_keys, opts)
encoded_length = len(encoded)
too_large = (encoded_length > ctx.max_bson_size)
message_length += encoded_length
if message_length < ctx.max_message_size and not too_large:
data.write(encoded)
to_send.append(doc)
has_docs = True
continue
if has_docs:
# We have enough data, send this message.
try:
request_id, msg = _insert_message(data.getvalue(), send_safe)
ctx.legacy_write(request_id, msg, 0, send_safe, to_send)
# Exception type could be OperationFailure or a subtype
# (e.g. DuplicateKeyError)
except OperationFailure as exc:
# Like it says, continue on error...
if continue_on_error:
# Store exception details to re-raise after the final batch.
last_error = exc
# With unacknowledged writes just return at the first error.
elif not safe:
return
# With acknowledged writes raise immediately.
else:
raise
if too_large:
_raise_document_too_large(
"insert", encoded_length, ctx.max_bson_size)
message_length = begin_loc + encoded_length
data.seek(begin_loc)
data.truncate()
data.write(encoded)
to_send = [doc]
if not has_docs:
raise InvalidOperation("cannot do an empty bulk insert")
request_id, msg = _insert_message(data.getvalue(), safe)
ctx.legacy_write(request_id, msg, 0, safe, to_send)
# Re-raise any exception stored due to continue_on_error
if last_error is not None:
raise last_error | [
"def",
"_do_batched_insert",
"(",
"collection_name",
",",
"docs",
",",
"check_keys",
",",
"safe",
",",
"last_error_args",
",",
"continue_on_error",
",",
"opts",
",",
"ctx",
")",
":",
"def",
"_insert_message",
"(",
"insert_message",
",",
"send_safe",
")",
":",
... | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/tokumx/datadog_checks/tokumx/vendor/pymongo/message.py#L629-L701 | ||
Kronuz/esprima-python | 809cb6e257b1d3d5b0d23f2bca7976e21f02fc3d | esprima/parser.py | python | Parser.collectComments | (self) | [] | def collectComments(self):
if not self.config.comment:
self.scanner.scanComments()
else:
comments = self.scanner.scanComments()
if comments:
for e in comments:
if e.multiLine:
node = Node.BlockComment(self.scanner.source[e.slice[0]:e.slice[1]])
else:
node = Node.LineComment(self.scanner.source[e.slice[0]:e.slice[1]])
if self.config.range:
node.range = e.range
if self.config.loc:
node.loc = e.loc
if self.delegate:
metadata = SourceLocation(
start=Position(
line=e.loc.start.line,
column=e.loc.start.column,
offset=e.range[0],
),
end=Position(
line=e.loc.end.line,
column=e.loc.end.column,
offset=e.range[1],
)
)
new_node = self.delegate(node, metadata)
if new_node is not None:
node = new_node | [
"def",
"collectComments",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"config",
".",
"comment",
":",
"self",
".",
"scanner",
".",
"scanComments",
"(",
")",
"else",
":",
"comments",
"=",
"self",
".",
"scanner",
".",
"scanComments",
"(",
")",
"if",
... | https://github.com/Kronuz/esprima-python/blob/809cb6e257b1d3d5b0d23f2bca7976e21f02fc3d/esprima/parser.py#L242-L272 | ||||
keiffster/program-y | 8c99b56f8c32f01a7b9887b5daae9465619d0385 | src/programy/config/programy.py | python | ProgramyConfiguration.__init__ | (self, client_configuration) | [] | def __init__(self, client_configuration):
self._client_config = client_configuration | [
"def",
"__init__",
"(",
"self",
",",
"client_configuration",
")",
":",
"self",
".",
"_client_config",
"=",
"client_configuration"
] | https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/config/programy.py#L22-L23 | ||||
CedricGuillemet/Imogen | ee417b42747ed5b46cb11b02ef0c3630000085b3 | bin/Lib/tarfile.py | python | TarFile.chmod | (self, tarinfo, targetpath) | Set file permissions of targetpath according to tarinfo. | Set file permissions of targetpath according to tarinfo. | [
"Set",
"file",
"permissions",
"of",
"targetpath",
"according",
"to",
"tarinfo",
"."
] | def chmod(self, tarinfo, targetpath):
"""Set file permissions of targetpath according to tarinfo.
"""
if hasattr(os, 'chmod'):
try:
os.chmod(targetpath, tarinfo.mode)
except OSError:
raise ExtractError("could not change mode") | [
"def",
"chmod",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"hasattr",
"(",
"os",
",",
"'chmod'",
")",
":",
"try",
":",
"os",
".",
"chmod",
"(",
"targetpath",
",",
"tarinfo",
".",
"mode",
")",
"except",
"OSError",
":",
"raise",
... | https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/tarfile.py#L2248-L2255 | ||
sametmax/Django--an-app-at-a-time | 99eddf12ead76e6dfbeb09ce0bae61e282e22f8a | ignore_this_directory/django/views/generic/edit.py | python | ProcessFormView.get | (self, request, *args, **kwargs) | return self.render_to_response(self.get_context_data()) | Handle GET requests: instantiate a blank version of the form. | Handle GET requests: instantiate a blank version of the form. | [
"Handle",
"GET",
"requests",
":",
"instantiate",
"a",
"blank",
"version",
"of",
"the",
"form",
"."
] | def get(self, request, *args, **kwargs):
"""Handle GET requests: instantiate a blank version of the form."""
return self.render_to_response(self.get_context_data()) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"render_to_response",
"(",
"self",
".",
"get_context_data",
"(",
")",
")"
] | https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/views/generic/edit.py#L131-L133 | |
explosion/srsly | 8617ecc099d1f34a60117b5287bef5424ea2c837 | srsly/ruamel_yaml/util.py | python | configobj_walker | (cfg) | walks over a ConfigObj (INI file with comments) generating
corresponding YAML output (including comments | walks over a ConfigObj (INI file with comments) generating
corresponding YAML output (including comments | [
"walks",
"over",
"a",
"ConfigObj",
"(",
"INI",
"file",
"with",
"comments",
")",
"generating",
"corresponding",
"YAML",
"output",
"(",
"including",
"comments"
] | def configobj_walker(cfg):
# type: (Any) -> Any
"""
walks over a ConfigObj (INI file with comments) generating
corresponding YAML output (including comments
"""
from configobj import ConfigObj # type: ignore
assert isinstance(cfg, ConfigObj)
for c in cfg.initial_comment:
if c.strip():
yield c
for s in _walk_section(cfg):
if s.strip():
yield s
for c in cfg.final_comment:
if c.strip():
yield c | [
"def",
"configobj_walker",
"(",
"cfg",
")",
":",
"# type: (Any) -> Any",
"from",
"configobj",
"import",
"ConfigObj",
"# type: ignore",
"assert",
"isinstance",
"(",
"cfg",
",",
"ConfigObj",
")",
"for",
"c",
"in",
"cfg",
".",
"initial_comment",
":",
"if",
"c",
"... | https://github.com/explosion/srsly/blob/8617ecc099d1f34a60117b5287bef5424ea2c837/srsly/ruamel_yaml/util.py#L123-L140 | ||
openSUSE/osc | 5c2e1b039a16334880e7ebe4a33baafe0f2d5e20 | osc/conf.py | python | get_config | (override_conffile=None,
override_apiurl=None,
override_debug=None,
override_http_debug=None,
override_http_full_debug=None,
override_traceback=None,
override_post_mortem=None,
override_no_keyring=None,
override_no_gnome_keyring=None,
override_verbose=None) | do the actual work (see module documentation) | do the actual work (see module documentation) | [
"do",
"the",
"actual",
"work",
"(",
"see",
"module",
"documentation",
")"
] | def get_config(override_conffile=None,
override_apiurl=None,
override_debug=None,
override_http_debug=None,
override_http_full_debug=None,
override_traceback=None,
override_post_mortem=None,
override_no_keyring=None,
override_no_gnome_keyring=None,
override_verbose=None):
"""do the actual work (see module documentation)"""
global config
if not override_conffile:
conffile = identify_conf()
else:
conffile = override_conffile
conffile = os.path.expanduser(conffile)
if not os.path.exists(conffile):
raise oscerr.NoConfigfile(conffile, \
account_not_configured_text % conffile)
# okay, we made sure that oscrc exists
# make sure it is not world readable, it may contain a password.
conffile_stat = os.stat(conffile)
if conffile_stat.st_mode != 0o600:
try:
os.chmod(conffile, 0o600)
except OSError as e:
if e.errno == errno.EROFS:
print('Warning: file \'%s\' may have an insecure mode.', conffile)
else:
raise e
cp = get_configParser(conffile)
if not cp.has_section('general'):
# FIXME: it might be sufficient to just assume defaults?
msg = config_incomplete_text % conffile
msg += new_conf_template % DEFAULTS
raise oscerr.ConfigError(msg, conffile)
config = dict(cp.items('general', raw=1))
config['conffile'] = conffile
typed_opts = ((boolean_opts, cp.getboolean), (integer_opts, cp.getint))
for opts, meth in typed_opts:
for opt in opts:
try:
config[opt] = meth('general', opt)
except ValueError as e:
msg = 'cannot parse \'%s\' setting: %s' % (opt, str(e))
raise oscerr.ConfigError(msg, conffile)
config['packagecachedir'] = os.path.expanduser(config['packagecachedir'])
config['exclude_glob'] = config['exclude_glob'].split()
re_clist = re.compile('[, ]+')
config['extra-pkgs'] = [i.strip() for i in re_clist.split(config['extra-pkgs'].strip()) if i]
# collect the usernames, passwords and additional options for each api host
api_host_options = {}
# Regexp to split extra http headers into a dictionary
# the text to be matched looks essentially looks this:
# "Attribute1: value1, Attribute2: value2, ..."
# there may be arbitray leading and intermitting whitespace.
# the following regexp does _not_ support quoted commas within the value.
http_header_regexp = re.compile(r"\s*(.*?)\s*:\s*(.*?)\s*(?:,\s*|\Z)")
# override values which we were called with
# This needs to be done before processing API sections as it might be already used there
if override_no_keyring:
config['use_keyring'] = False
if override_no_gnome_keyring:
config['gnome_keyring'] = False
aliases = {}
for url in [x for x in cp.sections() if x != 'general']:
# backward compatiblity
scheme, host, path = parse_apisrv_url(config.get('scheme', 'https'), url)
apiurl = urljoin(scheme, host, path)
creds_mgr = _get_credentials_manager(url, cp)
# if the deprecated gnomekeyring is used we should use the apiurl instead of url
# (that's what the old code did), but this makes things more complex
# (also, it is very unlikely that url and apiurl differ)
user = _extract_user_compat(cp, url, creds_mgr)
if user is None:
raise oscerr.ConfigMissingCredentialsError('No user found in section %s' % url, conffile, url)
password = creds_mgr.get_password(url, user)
if password is None:
raise oscerr.ConfigMissingCredentialsError('No password found in section %s' % url, conffile, url)
if cp.has_option(url, 'http_headers'):
http_headers = cp.get(url, 'http_headers')
http_headers = http_header_regexp.findall(http_headers)
else:
http_headers = []
if cp.has_option(url, 'aliases'):
for i in cp.get(url, 'aliases').split(','):
key = i.strip()
if key == '':
continue
if key in aliases:
msg = 'duplicate alias entry: \'%s\' is already used for another apiurl' % key
raise oscerr.ConfigError(msg, conffile)
aliases[key] = url
entry = {'user': user,
'pass': password,
'http_headers': http_headers}
api_host_options[apiurl] = APIHostOptionsEntry(entry)
optional = ('realname', 'email', 'sslcertck', 'cafile', 'capath')
for key in optional:
if cp.has_option(url, key):
if key == 'sslcertck':
api_host_options[apiurl][key] = cp.getboolean(url, key)
else:
api_host_options[apiurl][key] = cp.get(url, key)
if cp.has_option(url, 'build-root', proper=True):
api_host_options[apiurl]['build-root'] = cp.get(url, 'build-root', raw=True)
if not 'sslcertck' in api_host_options[apiurl]:
api_host_options[apiurl]['sslcertck'] = True
if scheme == 'http':
api_host_options[apiurl]['sslcertck'] = False
if cp.has_option(url, 'trusted_prj'):
api_host_options[apiurl]['trusted_prj'] = cp.get(url, 'trusted_prj').split(' ')
else:
api_host_options[apiurl]['trusted_prj'] = []
# add the auth data we collected to the config dict
config['api_host_options'] = api_host_options
config['apiurl_aliases'] = aliases
apiurl = aliases.get(config['apiurl'], config['apiurl'])
config['apiurl'] = urljoin(*parse_apisrv_url(None, apiurl))
# backward compatibility
if 'apisrv' in config:
apisrv = config['apisrv'].lstrip('http://')
apisrv = apisrv.lstrip('https://')
scheme = config.get('scheme', 'https')
config['apiurl'] = urljoin(scheme, apisrv)
if 'apisrc' in config or 'scheme' in config:
print('Warning: Use of the \'scheme\' or \'apisrv\' in oscrc is deprecated!\n' \
'Warning: See README for migration details.', file=sys.stderr)
if 'build_platform' in config:
print('Warning: Use of \'build_platform\' config option is deprecated! (use \'build_repository\' instead)', file=sys.stderr)
config['build_repository'] = config['build_platform']
if config['plaintext_passwd']:
print('The \'plaintext_passwd\' option is deprecated and will be ignored', file=sys.stderr)
config['verbose'] = int(config['verbose'])
# override values which we were called with
if override_verbose:
config['verbose'] = override_verbose + 1
if override_debug:
config['debug'] = override_debug
if override_http_debug:
config['http_debug'] = override_http_debug
if override_http_full_debug:
config['http_debug'] = override_http_full_debug or config['http_debug']
config['http_full_debug'] = override_http_full_debug
if override_traceback:
config['traceback'] = override_traceback
if override_post_mortem:
config['post_mortem'] = override_post_mortem
if override_apiurl:
apiurl = aliases.get(override_apiurl, override_apiurl)
# check if apiurl is a valid url
config['apiurl'] = urljoin(*parse_apisrv_url(None, apiurl))
# XXX unless config['user'] goes away (and is replaced with a handy function, or
# config becomes an object, even better), set the global 'user' here as well,
# provided that there _are_ credentials for the chosen apiurl:
try:
config['user'] = get_apiurl_usr(config['apiurl'])
except oscerr.ConfigMissingApiurl as e:
e.msg = config_missing_apiurl_text % config['apiurl']
e.file = conffile
raise e
# finally, initialize urllib2 for to use the credentials for Basic Authentication
init_basicauth(config, os.stat(conffile).st_mtime) | [
"def",
"get_config",
"(",
"override_conffile",
"=",
"None",
",",
"override_apiurl",
"=",
"None",
",",
"override_debug",
"=",
"None",
",",
"override_http_debug",
"=",
"None",
",",
"override_http_full_debug",
"=",
"None",
",",
"override_traceback",
"=",
"None",
",",... | https://github.com/openSUSE/osc/blob/5c2e1b039a16334880e7ebe4a33baafe0f2d5e20/osc/conf.py#L886-L1075 | ||
mchristopher/PokemonGo-DesktopMap | ec37575f2776ee7d64456e2a1f6b6b78830b4fe0 | app/pywin/Lib/calendar.py | python | Calendar.itermonthdates | (self, year, month) | Return an iterator for one month. The iterator will yield datetime.date
values and will always iterate through complete weeks, so it will yield
dates outside the specified month. | Return an iterator for one month. The iterator will yield datetime.date
values and will always iterate through complete weeks, so it will yield
dates outside the specified month. | [
"Return",
"an",
"iterator",
"for",
"one",
"month",
".",
"The",
"iterator",
"will",
"yield",
"datetime",
".",
"date",
"values",
"and",
"will",
"always",
"iterate",
"through",
"complete",
"weeks",
"so",
"it",
"will",
"yield",
"dates",
"outside",
"the",
"specif... | def itermonthdates(self, year, month):
"""
Return an iterator for one month. The iterator will yield datetime.date
values and will always iterate through complete weeks, so it will yield
dates outside the specified month.
"""
date = datetime.date(year, month, 1)
# Go back to the beginning of the week
days = (date.weekday() - self.firstweekday) % 7
date -= datetime.timedelta(days=days)
oneday = datetime.timedelta(days=1)
while True:
yield date
try:
date += oneday
except OverflowError:
# Adding one day could fail after datetime.MAXYEAR
break
if date.month != month and date.weekday() == self.firstweekday:
break | [
"def",
"itermonthdates",
"(",
"self",
",",
"year",
",",
"month",
")",
":",
"date",
"=",
"datetime",
".",
"date",
"(",
"year",
",",
"month",
",",
"1",
")",
"# Go back to the beginning of the week",
"days",
"=",
"(",
"date",
".",
"weekday",
"(",
")",
"-",
... | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/calendar.py#L151-L170 | ||
cal-pratt/SheetVision | f1ce1c9c97d5c922aa95b9120152f9c62fab829d | MIDIUtil-0.89/MIDIUtil-0.89/src/midiutil/MidiFile.py | python | MIDIFile.close | (self) | Close the MIDIFile for further writing.
To close the File for events, we must close the tracks, adjust the time to be
zero-origined, and have the tracks write to their MIDI Stream data structure. | Close the MIDIFile for further writing.
To close the File for events, we must close the tracks, adjust the time to be
zero-origined, and have the tracks write to their MIDI Stream data structure. | [
"Close",
"the",
"MIDIFile",
"for",
"further",
"writing",
".",
"To",
"close",
"the",
"File",
"for",
"events",
"we",
"must",
"close",
"the",
"tracks",
"adjust",
"the",
"time",
"to",
"be",
"zero",
"-",
"origined",
"and",
"have",
"the",
"tracks",
"write",
"t... | def close(self):
'''Close the MIDIFile for further writing.
To close the File for events, we must close the tracks, adjust the time to be
zero-origined, and have the tracks write to their MIDI Stream data structure.
'''
if self.closed == True:
return
for i in range(0,self.numTracks):
self.tracks[i].closeTrack()
# We want things like program changes to come before notes when they are at the
# same time, so we sort the MIDI events by their ordinality
self.tracks[i].MIDIEventList.sort()
origin = self.findOrigin()
for i in range(0,self.numTracks):
self.tracks[i].adjustTime(origin)
self.tracks[i].writeMIDIStream()
self.closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
"==",
"True",
":",
"return",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"numTracks",
")",
":",
"self",
".",
"tracks",
"[",
"i",
"]",
".",
"closeTrack",
"(",
")",
"#... | https://github.com/cal-pratt/SheetVision/blob/f1ce1c9c97d5c922aa95b9120152f9c62fab829d/MIDIUtil-0.89/MIDIUtil-0.89/src/midiutil/MidiFile.py#L922-L944 | ||
gnome-terminator/terminator | ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1 | terminatorlib/notebook.py | python | Notebook.__init__ | (self, window) | Class initialiser | Class initialiser | [
"Class",
"initialiser"
] | def __init__(self, window):
"""Class initialiser"""
if isinstance(window.get_child(), Gtk.Notebook):
err('There is already a Notebook at the top of this window')
raise(ValueError)
Container.__init__(self)
GObject.GObject.__init__(self)
self.terminator = Terminator()
self.window = window
GObject.type_register(Notebook)
self.register_signals(Notebook)
self.connect('switch-page', self.deferred_on_tab_switch)
self.connect('scroll-event', self.on_scroll_event)
self.connect('create-window', self.create_window_detach)
self.configure()
self.set_can_focus(False)
child = window.get_child()
window.remove(child)
window.add(self)
window_last_active_term = window.last_active_term
self.newtab(widget=child)
if window_last_active_term:
self.set_last_active_term(window_last_active_term)
window.last_active_term = None
self.show_all() | [
"def",
"__init__",
"(",
"self",
",",
"window",
")",
":",
"if",
"isinstance",
"(",
"window",
".",
"get_child",
"(",
")",
",",
"Gtk",
".",
"Notebook",
")",
":",
"err",
"(",
"'There is already a Notebook at the top of this window'",
")",
"raise",
"(",
"ValueError... | https://github.com/gnome-terminator/terminator/blob/ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1/terminatorlib/notebook.py#L26-L54 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/pytz/tzinfo.py | python | StaticTzInfo.tzname | (self, dt, is_dst=None) | return self._tzname | See datetime.tzinfo.tzname
is_dst is ignored for StaticTzInfo, and exists only to
retain compatibility with DstTzInfo. | See datetime.tzinfo.tzname | [
"See",
"datetime",
".",
"tzinfo",
".",
"tzname"
] | def tzname(self, dt, is_dst=None):
'''See datetime.tzinfo.tzname
is_dst is ignored for StaticTzInfo, and exists only to
retain compatibility with DstTzInfo.
'''
return self._tzname | [
"def",
"tzname",
"(",
"self",
",",
"dt",
",",
"is_dst",
"=",
"None",
")",
":",
"return",
"self",
".",
"_tzname"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/pytz/tzinfo.py#L97-L103 | |
IronLanguages/ironpython2 | 51fdedeeda15727717fb8268a805f71b06c0b9f1 | Src/StdLib/Lib/site-packages/win32com/decimal_23.py | python | Decimal.__rmod__ | (self, other, context=None) | return other.__mod__(self, context=context) | Swaps self/other and returns __mod__. | Swaps self/other and returns __mod__. | [
"Swaps",
"self",
"/",
"other",
"and",
"returns",
"__mod__",
"."
] | def __rmod__(self, other, context=None):
"""Swaps self/other and returns __mod__."""
other = _convert_other(other)
return other.__mod__(self, context=context) | [
"def",
"__rmod__",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
")",
"return",
"other",
".",
"__mod__",
"(",
"self",
",",
"context",
"=",
"context",
")"
] | https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/site-packages/win32com/decimal_23.py#L1329-L1332 | |
angr/angr | 4b04d56ace135018083d36d9083805be8146688b | angr/knowledge_plugins/sync/sync_controller.py | python | SyncController.connected | (self) | return self.client is not None | [] | def connected(self):
return self.client is not None | [
"def",
"connected",
"(",
"self",
")",
":",
"return",
"self",
".",
"client",
"is",
"not",
"None"
] | https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/knowledge_plugins/sync/sync_controller.py#L111-L112 | |||
deepchem/deepchem | 054eb4b2b082e3df8e1a8e77f36a52137ae6e375 | deepchem/models/chemnet_layers.py | python | InceptionResnetA._build_layer_components | (self) | Builds the layers components and set _layers attribute. | Builds the layers components and set _layers attribute. | [
"Builds",
"the",
"layers",
"components",
"and",
"set",
"_layers",
"attribute",
"."
] | def _build_layer_components(self):
"""Builds the layers components and set _layers attribute."""
self.conv_block1 = [
Conv2D(
self.num_filters,
kernel_size=(1, 1),
strides=1,
padding="same",
activation=tf.nn.relu)
]
self.conv_block2 = [
Conv2D(
filters=self.num_filters,
kernel_size=(1, 1),
strides=1,
activation=tf.nn.relu,
padding="same")
]
self.conv_block2.append(
Conv2D(
filters=self.num_filters,
kernel_size=(3, 3),
strides=1,
activation=tf.nn.relu,
padding="same"))
self.conv_block3 = [
Conv2D(
filters=self.num_filters,
kernel_size=1,
strides=1,
activation=tf.nn.relu,
padding="same")
]
self.conv_block3.append(
Conv2D(
filters=int(self.num_filters * 1.5),
kernel_size=(3, 3),
strides=1,
activation=tf.nn.relu,
padding="same"))
self.conv_block3.append(
Conv2D(
filters=self.num_filters * 2,
kernel_size=(3, 3),
strides=1,
activation=tf.nn.relu,
padding="same"))
self.conv_block4 = [
Conv2D(
filters=self.input_dim,
kernel_size=(1, 1),
strides=1,
padding="same")
]
self.concat_layer = Concatenate()
self.add_layer = Add()
self.activation_layer = ReLU()
self._layers = self.conv_block1 + self.conv_block2 + self.conv_block3 + self.conv_block4
self._layers.extend(
[self.concat_layer, self.add_layer, self.activation_layer]) | [
"def",
"_build_layer_components",
"(",
"self",
")",
":",
"self",
".",
"conv_block1",
"=",
"[",
"Conv2D",
"(",
"self",
".",
"num_filters",
",",
"kernel_size",
"=",
"(",
"1",
",",
"1",
")",
",",
"strides",
"=",
"1",
",",
"padding",
"=",
"\"same\"",
",",
... | https://github.com/deepchem/deepchem/blob/054eb4b2b082e3df8e1a8e77f36a52137ae6e375/deepchem/models/chemnet_layers.py#L76-L142 | ||
retresco/Spyder | 9a2de6ec4c25d4dc85802305d5675a52c3ebb750 | src/spyder/processor/stripsessions.py | python | StripSessionIds.__call__ | (self, curi) | return curi | Main method stripping the session stuff from the query string. | Main method stripping the session stuff from the query string. | [
"Main",
"method",
"stripping",
"the",
"session",
"stuff",
"from",
"the",
"query",
"string",
"."
] | def __call__(self, curi):
"""
Main method stripping the session stuff from the query string.
"""
if CURI_EXTRACTED_URLS not in curi.optional_vars:
return curi
urls = []
for raw_url in curi.optional_vars[CURI_EXTRACTED_URLS].split('\n'):
urls.append(self._remove_session_ids(raw_url))
curi.optional_vars[CURI_EXTRACTED_URLS] = "\n".join(urls)
return curi | [
"def",
"__call__",
"(",
"self",
",",
"curi",
")",
":",
"if",
"CURI_EXTRACTED_URLS",
"not",
"in",
"curi",
".",
"optional_vars",
":",
"return",
"curi",
"urls",
"=",
"[",
"]",
"for",
"raw_url",
"in",
"curi",
".",
"optional_vars",
"[",
"CURI_EXTRACTED_URLS",
"... | https://github.com/retresco/Spyder/blob/9a2de6ec4c25d4dc85802305d5675a52c3ebb750/src/spyder/processor/stripsessions.py#L46-L58 | |
openlabs/magento | 903c02db6ea2404d1e2013a7f0951a621c80fd80 | magento/catalog.py | python | Product.getSpecialPrice | (self, product, store_view=None) | return self.call(
'catalog_product.getSpecialPrice', [product, store_view]
) | Get product special price data
:param product: ID or SKU of product
:param store_view: ID or Code of Store view
:return: Dictionary | Get product special price data | [
"Get",
"product",
"special",
"price",
"data"
] | def getSpecialPrice(self, product, store_view=None):
"""
Get product special price data
:param product: ID or SKU of product
:param store_view: ID or Code of Store view
:return: Dictionary
"""
return self.call(
'catalog_product.getSpecialPrice', [product, store_view]
) | [
"def",
"getSpecialPrice",
"(",
"self",
",",
"product",
",",
"store_view",
"=",
"None",
")",
":",
"return",
"self",
".",
"call",
"(",
"'catalog_product.getSpecialPrice'",
",",
"[",
"product",
",",
"store_view",
"]",
")"
] | https://github.com/openlabs/magento/blob/903c02db6ea2404d1e2013a7f0951a621c80fd80/magento/catalog.py#L317-L328 | |
gratipay/gratipay.com | dc4e953a8a5b96908e2f3ea7f8fef779217ba2b6 | gratipay/models/payment_for_open_source.py | python | PaymentForOpenSource.from_id | (cls, id, cursor=None) | return (cursor or cls.db).one("""
SELECT pfos.*::payments_for_open_source
FROM payments_for_open_source pfos
WHERE id = %s
""", (id,)) | Take an id and return an object. | Take an id and return an object. | [
"Take",
"an",
"id",
"and",
"return",
"an",
"object",
"."
] | def from_id(cls, id, cursor=None):
"""Take an id and return an object.
"""
return (cursor or cls.db).one("""
SELECT pfos.*::payments_for_open_source
FROM payments_for_open_source pfos
WHERE id = %s
""", (id,)) | [
"def",
"from_id",
"(",
"cls",
",",
"id",
",",
"cursor",
"=",
"None",
")",
":",
"return",
"(",
"cursor",
"or",
"cls",
".",
"db",
")",
".",
"one",
"(",
"\"\"\"\n SELECT pfos.*::payments_for_open_source\n FROM payments_for_open_source pfos\n ... | https://github.com/gratipay/gratipay.com/blob/dc4e953a8a5b96908e2f3ea7f8fef779217ba2b6/gratipay/models/payment_for_open_source.py#L40-L47 | |
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/imaplib.py | python | IMAP4.sort | (self, sort_criteria, charset, *search_criteria) | return self._untagged_response(typ, dat, name) | IMAP4rev1 extension SORT command.
(typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...) | IMAP4rev1 extension SORT command. | [
"IMAP4rev1",
"extension",
"SORT",
"command",
"."
] | def sort(self, sort_criteria, charset, *search_criteria):
"""IMAP4rev1 extension SORT command.
(typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
"""
name = 'SORT'
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unimplemented extension command: %s' % name)
if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
sort_criteria = '(%s)' % sort_criteria
typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
return self._untagged_response(typ, dat, name) | [
"def",
"sort",
"(",
"self",
",",
"sort_criteria",
",",
"charset",
",",
"*",
"search_criteria",
")",
":",
"name",
"=",
"'SORT'",
"#if not name in self.capabilities: # Let the server decide!",
"# raise self.error('unimplemented extension command: %s' % name)",
"if",
"(... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/imaplib.py#L701-L712 | |
limodou/ulipad | 4c7d590234f39cac80bb1d36dca095b646e287fb | modules/scriptils.py | python | newtab | (win) | return win.document | r'''Creates a new tab, returning a reference to the enclosed document
object. | r'''Creates a new tab, returning a reference to the enclosed document
object. | [
"r",
"Creates",
"a",
"new",
"tab",
"returning",
"a",
"reference",
"to",
"the",
"enclosed",
"document",
"object",
"."
] | def newtab(win):
r'''Creates a new tab, returning a reference to the enclosed document
object.
'''
win.editctrl.new()
return win.document | [
"def",
"newtab",
"(",
"win",
")",
":",
"win",
".",
"editctrl",
".",
"new",
"(",
")",
"return",
"win",
".",
"document"
] | https://github.com/limodou/ulipad/blob/4c7d590234f39cac80bb1d36dca095b646e287fb/modules/scriptils.py#L52-L57 | |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | 5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e | tensorflow_dl_models/research/lfads/distributions.py | python | DiagonalGaussian.__init__ | (self, batch_size, z_size, mean, logvar) | Create a diagonal gaussian distribution.
Args:
batch_size: The size of the batch, i.e. 0th dim in 2D tensor of samples.
z_size: The dimension of the distribution, i.e. 1st dim in 2D tensor.
mean: The N-D mean of the distribution.
logvar: The N-D log variance of the diagonal distribution. | Create a diagonal gaussian distribution. | [
"Create",
"a",
"diagonal",
"gaussian",
"distribution",
"."
] | def __init__(self, batch_size, z_size, mean, logvar):
"""Create a diagonal gaussian distribution.
Args:
batch_size: The size of the batch, i.e. 0th dim in 2D tensor of samples.
z_size: The dimension of the distribution, i.e. 1st dim in 2D tensor.
mean: The N-D mean of the distribution.
logvar: The N-D log variance of the diagonal distribution.
"""
size__xz = [None, z_size]
self.mean = mean # bxn already
self.logvar = logvar # bxn already
self.noise = noise = tf.random_normal(tf.shape(logvar))
self.sample = mean + tf.exp(0.5 * logvar) * noise
mean.set_shape(size__xz)
logvar.set_shape(size__xz)
self.sample.set_shape(size__xz) | [
"def",
"__init__",
"(",
"self",
",",
"batch_size",
",",
"z_size",
",",
"mean",
",",
"logvar",
")",
":",
"size__xz",
"=",
"[",
"None",
",",
"z_size",
"]",
"self",
".",
"mean",
"=",
"mean",
"# bxn already",
"self",
".",
"logvar",
"=",
"logvar",
"# bxn al... | https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/lfads/distributions.py#L96-L112 | ||
itailang/SampleNet | 442459abc54f9e14f0966a169a094a98febd32eb | registration/src/qdataset.py | python | QuaternionTransform.wxyz_to_xyzw | (q) | return q | [] | def wxyz_to_xyzw(q):
q = q[..., [1, 2, 3, 0]]
return q | [
"def",
"wxyz_to_xyzw",
"(",
"q",
")",
":",
"q",
"=",
"q",
"[",
"...",
",",
"[",
"1",
",",
"2",
",",
"3",
",",
"0",
"]",
"]",
"return",
"q"
] | https://github.com/itailang/SampleNet/blob/442459abc54f9e14f0966a169a094a98febd32eb/registration/src/qdataset.py#L53-L55 | |||
dagwieers/mrepo | a55cbc737d8bade92070d38e4dbb9a24be4b477f | up2date_client/config.py | python | UuidConfig.__init__ | (self) | [] | def __init__(self):
ConfigFile.__init__(self)
self.fileName = "/etc/sysconfig/rhn/up2date-uuid" | [
"def",
"__init__",
"(",
"self",
")",
":",
"ConfigFile",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"fileName",
"=",
"\"/etc/sysconfig/rhn/up2date-uuid\""
] | https://github.com/dagwieers/mrepo/blob/a55cbc737d8bade92070d38e4dbb9a24be4b477f/up2date_client/config.py#L305-L307 | ||||
klen/Flask-Foundation | d154886a8a4358a3bfb99d189a6401e422fea416 | migrate/env.py | python | run_migrations_offline | () | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | Run migrations in 'offline' mode. | [
"Run",
"migrations",
"in",
"offline",
"mode",
"."
] | def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations() | [
"def",
"run_migrations_offline",
"(",
")",
":",
"url",
"=",
"config",
".",
"get_main_option",
"(",
"\"sqlalchemy.url\"",
")",
"context",
".",
"configure",
"(",
"url",
"=",
"url",
")",
"with",
"context",
".",
"begin_transaction",
"(",
")",
":",
"context",
"."... | https://github.com/klen/Flask-Foundation/blob/d154886a8a4358a3bfb99d189a6401e422fea416/migrate/env.py#L25-L41 | ||
kpe/bert-for-tf2 | 55f6a6fd5d8ea14f96ee19938b7a1bf0cb26aaea | bert/tokenization/albert_tokenization.py | python | BasicTokenizer._run_strip_accents | (self, text) | return "".join(output) | Strips accents from a piece of text. | Strips accents from a piece of text. | [
"Strips",
"accents",
"from",
"a",
"piece",
"of",
"text",
"."
] | def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output) | [
"def",
"_run_strip_accents",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"unicodedata",
".",
"normalize",
"(",
"\"NFD\"",
",",
"text",
")",
"output",
"=",
"[",
"]",
"for",
"char",
"in",
"text",
":",
"cat",
"=",
"unicodedata",
".",
"category",
"(",... | https://github.com/kpe/bert-for-tf2/blob/55f6a6fd5d8ea14f96ee19938b7a1bf0cb26aaea/bert/tokenization/albert_tokenization.py#L336-L345 | |
nvaccess/nvda | 20d5a25dced4da34338197f0ef6546270ebca5d0 | source/NVDAObjects/UIA/spartanEdge.py | python | EdgeHTMLRoot._isIframe | (self) | return False | Override, the root node is never an iFrame | Override, the root node is never an iFrame | [
"Override",
"the",
"root",
"node",
"is",
"never",
"an",
"iFrame"
] | def _isIframe(self):
"""Override, the root node is never an iFrame"""
return False | [
"def",
"_isIframe",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/NVDAObjects/UIA/spartanEdge.py#L405-L407 | |
sunpy/sunpy | 528579df0a4c938c133bd08971ba75c131b189a7 | sunpy/coordinates/sun.py | python | _sun_north_angle_to_z | (frame) | return Angle(angle) | Return the angle between solar north and the Z axis of the provided frame's coordinate system
and observation time. | Return the angle between solar north and the Z axis of the provided frame's coordinate system
and observation time. | [
"Return",
"the",
"angle",
"between",
"solar",
"north",
"and",
"the",
"Z",
"axis",
"of",
"the",
"provided",
"frame",
"s",
"coordinate",
"system",
"and",
"observation",
"time",
"."
] | def _sun_north_angle_to_z(frame):
"""
Return the angle between solar north and the Z axis of the provided frame's coordinate system
and observation time.
"""
# Find the Sun center in HGS at the frame's observation time(s)
sun_center_repr = SphericalRepresentation(0*u.deg, 0*u.deg, 0*u.km)
# The representation is repeated for as many times as are in obstime prior to transformation
sun_center = SkyCoord(sun_center_repr._apply('repeat', frame.obstime.size),
frame=HeliographicStonyhurst, obstime=frame.obstime)
# Find the Sun north pole in HGS at the frame's observation time(s)
sun_north_repr = SphericalRepresentation(0*u.deg, 90*u.deg, constants.radius)
# The representation is repeated for as many times as are in obstime prior to transformation
sun_north = SkyCoord(sun_north_repr._apply('repeat', frame.obstime.size),
frame=HeliographicStonyhurst, obstime=frame.obstime)
# Find the Sun center and Sun north in the frame's coordinate system
sky_normal = sun_center.transform_to(frame).data.to_cartesian()
sun_north = sun_north.transform_to(frame).data.to_cartesian()
# Use cross products to obtain the sky projections of the two vectors (rotated by 90 deg)
sun_north_in_sky = sun_north.cross(sky_normal)
z_in_sky = CartesianRepresentation(0, 0, 1).cross(sky_normal)
# Normalize directional vectors
sky_normal /= sky_normal.norm()
sun_north_in_sky /= sun_north_in_sky.norm()
z_in_sky /= z_in_sky.norm()
# Calculate the signed angle between the two projected vectors
cos_theta = sun_north_in_sky.dot(z_in_sky)
sin_theta = sun_north_in_sky.cross(z_in_sky).dot(sky_normal)
angle = np.arctan2(sin_theta, cos_theta).to('deg')
# If there is only one time, this function's output should be scalar rather than array
if angle.size == 1:
angle = angle[0]
return Angle(angle) | [
"def",
"_sun_north_angle_to_z",
"(",
"frame",
")",
":",
"# Find the Sun center in HGS at the frame's observation time(s)",
"sun_center_repr",
"=",
"SphericalRepresentation",
"(",
"0",
"*",
"u",
".",
"deg",
",",
"0",
"*",
"u",
".",
"deg",
",",
"0",
"*",
"u",
".",
... | https://github.com/sunpy/sunpy/blob/528579df0a4c938c133bd08971ba75c131b189a7/sunpy/coordinates/sun.py#L683-L722 | |
neubig/nn4nlp-code | 970d91a51664b3d91a9822b61cd76abea20218cb | 14-semparsing/ucca/ucca/evaluation.py | python | Scores.__init__ | (self, evaluator_results) | :param evaluator_results: dict: eval_type -> EvaluatorResults | :param evaluator_results: dict: eval_type -> EvaluatorResults | [
":",
"param",
"evaluator_results",
":",
"dict",
":",
"eval_type",
"-",
">",
"EvaluatorResults"
] | def __init__(self, evaluator_results):
"""
:param evaluator_results: dict: eval_type -> EvaluatorResults
"""
self.evaluators = dict(evaluator_results) | [
"def",
"__init__",
"(",
"self",
",",
"evaluator_results",
")",
":",
"self",
".",
"evaluators",
"=",
"dict",
"(",
"evaluator_results",
")"
] | https://github.com/neubig/nn4nlp-code/blob/970d91a51664b3d91a9822b61cd76abea20218cb/14-semparsing/ucca/ucca/evaluation.py#L183-L187 | ||
stratosphereips/StratosphereLinuxIPS | 985ac0f141dd71fe9c6faa8307bcf95a3754951d | modules/virustotal/virustotal.py | python | Module.set_vt_data_in_IPInfo | (self, ip, cached_data) | Function to set VirusTotal data of the IP in the IPInfo.
It also sets asn data if it is unknown or does not exist.
It also set passive dns retrieved from VirusTotal. | Function to set VirusTotal data of the IP in the IPInfo.
It also sets asn data if it is unknown or does not exist.
It also set passive dns retrieved from VirusTotal. | [
"Function",
"to",
"set",
"VirusTotal",
"data",
"of",
"the",
"IP",
"in",
"the",
"IPInfo",
".",
"It",
"also",
"sets",
"asn",
"data",
"if",
"it",
"is",
"unknown",
"or",
"does",
"not",
"exist",
".",
"It",
"also",
"set",
"passive",
"dns",
"retrieved",
"from... | def set_vt_data_in_IPInfo(self, ip, cached_data):
"""
Function to set VirusTotal data of the IP in the IPInfo.
It also sets asn data if it is unknown or does not exist.
It also set passive dns retrieved from VirusTotal.
"""
vt_scores, passive_dns, as_owner = self.get_ip_vt_data(ip)
ts = time.time()
vtdata = {"URL": vt_scores[0],
"down_file": vt_scores[1],
"ref_file": vt_scores[2],
"com_file": vt_scores[3],
"timestamp": ts}
data = {}
data["VirusTotal"] = vtdata
# Add asn if it is unknown or not in the IP info
if cached_data and ('asn' not in cached_data or cached_data['asn']['asnorg'] == 'Unknown'):
data['asn'] = {'asnorg': as_owner,
'timestamp': ts}
__database__.setInfoForIPs(ip, data)
__database__.set_passive_dns(ip, passive_dns) | [
"def",
"set_vt_data_in_IPInfo",
"(",
"self",
",",
"ip",
",",
"cached_data",
")",
":",
"vt_scores",
",",
"passive_dns",
",",
"as_owner",
"=",
"self",
".",
"get_ip_vt_data",
"(",
"ip",
")",
"ts",
"=",
"time",
".",
"time",
"(",
")",
"vtdata",
"=",
"{",
"\... | https://github.com/stratosphereips/StratosphereLinuxIPS/blob/985ac0f141dd71fe9c6faa8307bcf95a3754951d/modules/virustotal/virustotal.py#L116-L138 | ||
Lonero-Team/Decentralized-Internet | 3cb157834fcc19ff8c2316e66bf07b103c137068 | packages/p2lara/src/storages/bigchaindb/backend/query.py | python | store_metadatas | (connection, metadata) | Write a list of metadata to metadata table.
Args:
metadata (list): list of metadata.
Returns:
The result of the operation. | Write a list of metadata to metadata table. | [
"Write",
"a",
"list",
"of",
"metadata",
"to",
"metadata",
"table",
"."
] | def store_metadatas(connection, metadata):
"""Write a list of metadata to metadata table.
Args:
metadata (list): list of metadata.
Returns:
The result of the operation.
"""
raise NotImplementedError | [
"def",
"store_metadatas",
"(",
"connection",
",",
"metadata",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/Lonero-Team/Decentralized-Internet/blob/3cb157834fcc19ff8c2316e66bf07b103c137068/packages/p2lara/src/storages/bigchaindb/backend/query.py#L41-L51 | ||
bernwang/latte | b30ea4ee95efdbf52a274f504cb9920c5695acf9 | app/Mask_RCNN/model.py | python | identity_block | (input_tensor, kernel_size, filters, stage, block,
use_bias=True) | return x | The identity_block is the block that has no conv layer at shortcut
# Arguments
input_tensor: input tensor
kernel_size: defualt 3, the kernel size of middle conv layer at main path
filters: list of integers, the nb_filters of 3 conv layer at main path
stage: integer, current stage label, used for generating layer names
block: 'a','b'..., current block label, used for generating layer names | The identity_block is the block that has no conv layer at shortcut
# Arguments
input_tensor: input tensor
kernel_size: defualt 3, the kernel size of middle conv layer at main path
filters: list of integers, the nb_filters of 3 conv layer at main path
stage: integer, current stage label, used for generating layer names
block: 'a','b'..., current block label, used for generating layer names | [
"The",
"identity_block",
"is",
"the",
"block",
"that",
"has",
"no",
"conv",
"layer",
"at",
"shortcut",
"#",
"Arguments",
"input_tensor",
":",
"input",
"tensor",
"kernel_size",
":",
"defualt",
"3",
"the",
"kernel",
"size",
"of",
"middle",
"conv",
"layer",
"at... | def identity_block(input_tensor, kernel_size, filters, stage, block,
use_bias=True):
"""The identity_block is the block that has no conv layer at shortcut
# Arguments
input_tensor: input tensor
kernel_size: defualt 3, the kernel size of middle conv layer at main path
filters: list of integers, the nb_filters of 3 conv layer at main path
stage: integer, current stage label, used for generating layer names
block: 'a','b'..., current block label, used for generating layer names
"""
nb_filter1, nb_filter2, nb_filter3 = filters
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
x = KL.Conv2D(nb_filter1, (1, 1), name=conv_name_base + '2a',
use_bias=use_bias)(input_tensor)
x = BatchNorm(axis=3, name=bn_name_base + '2a')(x)
x = KL.Activation('relu')(x)
x = KL.Conv2D(nb_filter2, (kernel_size, kernel_size), padding='same',
name=conv_name_base + '2b', use_bias=use_bias)(x)
x = BatchNorm(axis=3, name=bn_name_base + '2b')(x)
x = KL.Activation('relu')(x)
x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base + '2c',
use_bias=use_bias)(x)
x = BatchNorm(axis=3, name=bn_name_base + '2c')(x)
x = KL.Add()([x, input_tensor])
x = KL.Activation('relu', name='res' + str(stage) + block + '_out')(x)
return x | [
"def",
"identity_block",
"(",
"input_tensor",
",",
"kernel_size",
",",
"filters",
",",
"stage",
",",
"block",
",",
"use_bias",
"=",
"True",
")",
":",
"nb_filter1",
",",
"nb_filter2",
",",
"nb_filter3",
"=",
"filters",
"conv_name_base",
"=",
"'res'",
"+",
"st... | https://github.com/bernwang/latte/blob/b30ea4ee95efdbf52a274f504cb9920c5695acf9/app/Mask_RCNN/model.py#L76-L106 | |
NVIDIA/NeMo | 5b0c0b4dec12d87d3cd960846de4105309ce938e | nemo/collections/tts/modules/melgan_modules.py | python | ResidualStack.__init__ | (
self,
nonlinear_activation: torch.nn.Module,
kernel_size: int,
channels: int,
dilation: int = 1,
bias: bool = True,
) | Initialize ResidualStack module.
Args:
kernel_size (int): Kernel size of dilation convolution layer.
channels (int): Number of channels of convolution layers.
dilation (int): Dilation factor.
bias (bool): Whether to add bias parameter in convolution layers.
nonlinear_activation (torch.nn.Module): Activation function. | Initialize ResidualStack module.
Args:
kernel_size (int): Kernel size of dilation convolution layer.
channels (int): Number of channels of convolution layers.
dilation (int): Dilation factor.
bias (bool): Whether to add bias parameter in convolution layers.
nonlinear_activation (torch.nn.Module): Activation function. | [
"Initialize",
"ResidualStack",
"module",
".",
"Args",
":",
"kernel_size",
"(",
"int",
")",
":",
"Kernel",
"size",
"of",
"dilation",
"convolution",
"layer",
".",
"channels",
"(",
"int",
")",
":",
"Number",
"of",
"channels",
"of",
"convolution",
"layers",
".",... | def __init__(
self,
nonlinear_activation: torch.nn.Module,
kernel_size: int,
channels: int,
dilation: int = 1,
bias: bool = True,
):
"""Initialize ResidualStack module.
Args:
kernel_size (int): Kernel size of dilation convolution layer.
channels (int): Number of channels of convolution layers.
dilation (int): Dilation factor.
bias (bool): Whether to add bias parameter in convolution layers.
nonlinear_activation (torch.nn.Module): Activation function.
"""
super().__init__()
# defile residual stack part
assert (kernel_size - 1) % 2 == 0, "Not support even number kernel size."
self.stack = torch.nn.Sequential(
nonlinear_activation,
torch.nn.ReflectionPad1d((kernel_size - 1) // 2 * dilation),
torch.nn.Conv1d(channels, channels, kernel_size, dilation=dilation, bias=bias),
nonlinear_activation,
torch.nn.Conv1d(channels, channels, 1, bias=bias),
)
# defile extra layer for skip connection
self.skip_layer = torch.nn.Conv1d(channels, channels, 1, bias=bias) | [
"def",
"__init__",
"(",
"self",
",",
"nonlinear_activation",
":",
"torch",
".",
"nn",
".",
"Module",
",",
"kernel_size",
":",
"int",
",",
"channels",
":",
"int",
",",
"dilation",
":",
"int",
"=",
"1",
",",
"bias",
":",
"bool",
"=",
"True",
",",
")",
... | https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/tts/modules/melgan_modules.py#L60-L89 | ||
eirannejad/pyRevit | 49c0b7eb54eb343458ce1365425e6552d0c47d44 | site-packages/sqlalchemy/sql/elements.py | python | WithinGroup.over | (self, partition_by=None, order_by=None) | return Over(self, partition_by=partition_by, order_by=order_by) | Produce an OVER clause against this :class:`.WithinGroup`
construct.
This function has the same signature as that of
:meth:`.FunctionElement.over`. | Produce an OVER clause against this :class:`.WithinGroup`
construct. | [
"Produce",
"an",
"OVER",
"clause",
"against",
"this",
":",
"class",
":",
".",
"WithinGroup",
"construct",
"."
] | def over(self, partition_by=None, order_by=None):
"""Produce an OVER clause against this :class:`.WithinGroup`
construct.
This function has the same signature as that of
:meth:`.FunctionElement.over`.
"""
return Over(self, partition_by=partition_by, order_by=order_by) | [
"def",
"over",
"(",
"self",
",",
"partition_by",
"=",
"None",
",",
"order_by",
"=",
"None",
")",
":",
"return",
"Over",
"(",
"self",
",",
"partition_by",
"=",
"partition_by",
",",
"order_by",
"=",
"order_by",
")"
] | https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sqlalchemy/sql/elements.py#L3336-L3344 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/sympy/polys/galoistools.py | python | gf_degree | (f) | return len(f) - 1 | Return the leading degree of ``f``.
Examples
========
>>> from sympy.polys.galoistools import gf_degree
>>> gf_degree([1, 1, 2, 0])
3
>>> gf_degree([])
-1 | Return the leading degree of ``f``. | [
"Return",
"the",
"leading",
"degree",
"of",
"f",
"."
] | def gf_degree(f):
"""
Return the leading degree of ``f``.
Examples
========
>>> from sympy.polys.galoistools import gf_degree
>>> gf_degree([1, 1, 2, 0])
3
>>> gf_degree([])
-1
"""
return len(f) - 1 | [
"def",
"gf_degree",
"(",
"f",
")",
":",
"return",
"len",
"(",
"f",
")",
"-",
"1"
] | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/polys/galoistools.py#L135-L150 | |
fabioz/PyDev.Debugger | 0f8c02a010fe5690405da1dd30ed72326191ce63 | _pydev_imps/_pydev_SocketServer.py | python | TCPServer.server_close | (self) | Called to clean-up the server.
May be overridden. | Called to clean-up the server. | [
"Called",
"to",
"clean",
"-",
"up",
"the",
"server",
"."
] | def server_close(self):
"""Called to clean-up the server.
May be overridden.
"""
self.socket.close() | [
"def",
"server_close",
"(",
"self",
")",
":",
"self",
".",
"socket",
".",
"close",
"(",
")"
] | https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/_pydev_imps/_pydev_SocketServer.py#L430-L436 | ||
python-diamond/Diamond | 7000e16cfdf4508ed9291fc4b3800592557b2431 | src/collectors/postgres/postgres.py | python | PostgresqlCollector._connect | (self, database=None) | return conn | Connect to given database | Connect to given database | [
"Connect",
"to",
"given",
"database"
] | def _connect(self, database=None):
"""
Connect to given database
"""
conn_args = {
'host': self.config['host'],
'user': self.config['user'],
'password': self.config['password'],
'port': self.config['port'],
'sslmode': self.config['sslmode'],
}
if database:
conn_args['database'] = database
else:
conn_args['database'] = 'postgres'
# libpq will use ~/.pgpass only if no password supplied
if self.config['password_provider'] == 'pgpass':
del conn_args['password']
try:
conn = psycopg2.connect(**conn_args)
except Exception as e:
self.log.error(e)
raise e
# Avoid using transactions, set isolation level to autocommit
conn.set_isolation_level(0)
return conn | [
"def",
"_connect",
"(",
"self",
",",
"database",
"=",
"None",
")",
":",
"conn_args",
"=",
"{",
"'host'",
":",
"self",
".",
"config",
"[",
"'host'",
"]",
",",
"'user'",
":",
"self",
".",
"config",
"[",
"'user'",
"]",
",",
"'password'",
":",
"self",
... | https://github.com/python-diamond/Diamond/blob/7000e16cfdf4508ed9291fc4b3800592557b2431/src/collectors/postgres/postgres.py#L150-L179 | |
Instagram/LibCST | 13370227703fe3171e94c57bdd7977f3af696b73 | libcst/_typed_visitor.py | python | CSTTypedTransformerFunctions.leave_Imaginary | (
self, original_node: "Imaginary", updated_node: "Imaginary"
) | return updated_node | [] | def leave_Imaginary(
self, original_node: "Imaginary", updated_node: "Imaginary"
) -> "BaseExpression":
return updated_node | [
"def",
"leave_Imaginary",
"(",
"self",
",",
"original_node",
":",
"\"Imaginary\"",
",",
"updated_node",
":",
"\"Imaginary\"",
")",
"->",
"\"BaseExpression\"",
":",
"return",
"updated_node"
] | https://github.com/Instagram/LibCST/blob/13370227703fe3171e94c57bdd7977f3af696b73/libcst/_typed_visitor.py#L6565-L6568 | |||
dbrattli/OSlash | c271c7633daf9d72393b419cfc9229e427e6a42a | oslash/reader.py | python | Reader.__init__ | (self, fn: Callable[[TEnv], TSource]) | Initialize a new reader. | Initialize a new reader. | [
"Initialize",
"a",
"new",
"reader",
"."
] | def __init__(self, fn: Callable[[TEnv], TSource]) -> None:
"""Initialize a new reader."""
self.fn = fn | [
"def",
"__init__",
"(",
"self",
",",
"fn",
":",
"Callable",
"[",
"[",
"TEnv",
"]",
",",
"TSource",
"]",
")",
"->",
"None",
":",
"self",
".",
"fn",
"=",
"fn"
] | https://github.com/dbrattli/OSlash/blob/c271c7633daf9d72393b419cfc9229e427e6a42a/oslash/reader.py#L26-L29 | ||
NervanaSystems/ngraph-python | ac032c83c7152b615a9ad129d54d350f9d6a2986 | ngraph/op_graph/op_graph.py | python | Op.scalar_op | (self) | return self | Returns the scalar op version of this op. Will be overridden by subclasses | Returns the scalar op version of this op. Will be overridden by subclasses | [
"Returns",
"the",
"scalar",
"op",
"version",
"of",
"this",
"op",
".",
"Will",
"be",
"overridden",
"by",
"subclasses"
] | def scalar_op(self):
"""
Returns the scalar op version of this op. Will be overridden by subclasses
"""
if not self.is_scalar:
raise ValueError()
return self | [
"def",
"scalar_op",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_scalar",
":",
"raise",
"ValueError",
"(",
")",
"return",
"self"
] | https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/op_graph/op_graph.py#L518-L524 | |
ClusterLabs/pcs | 1f225199e02c8d20456bb386f4c913c3ff21ac78 | pcs/daemon/app/session.py | python | Mixin.session_auth_user | (self, username, password, sign_rejection=True) | Make user authorization and refresh storage.
bool sing_rejection -- flag according to which will be decided whether
to manipulate with session in storage in case of failed
authorization. It allows not to touch session for ajax calls when
authorization fails. It keeps previous behavior and should be
reviewed. | Make user authorization and refresh storage. | [
"Make",
"user",
"authorization",
"and",
"refresh",
"storage",
"."
] | async def session_auth_user(self, username, password, sign_rejection=True):
"""
Make user authorization and refresh storage.
bool sing_rejection -- flag according to which will be decided whether
to manipulate with session in storage in case of failed
authorization. It allows not to touch session for ajax calls when
authorization fails. It keeps previous behavior and should be
reviewed.
"""
# initialize session since it should be used without `init_session`
self.__session = self.__storage.provide(self.__sid_from_client)
self.__refresh_auth(
await authorize_user(username, password),
sign_rejection=sign_rejection,
) | [
"async",
"def",
"session_auth_user",
"(",
"self",
",",
"username",
",",
"password",
",",
"sign_rejection",
"=",
"True",
")",
":",
"# initialize session since it should be used without `init_session`",
"self",
".",
"__session",
"=",
"self",
".",
"__storage",
".",
"prov... | https://github.com/ClusterLabs/pcs/blob/1f225199e02c8d20456bb386f4c913c3ff21ac78/pcs/daemon/app/session.py#L29-L44 | ||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/South-0.7.3-py2.7.egg/south/db/generic.py | python | DatabaseOperations.rollback_transactions_dry_run | (self) | Rolls back all pending_transactions during this dry run. | Rolls back all pending_transactions during this dry run. | [
"Rolls",
"back",
"all",
"pending_transactions",
"during",
"this",
"dry",
"run",
"."
] | def rollback_transactions_dry_run(self):
"""
Rolls back all pending_transactions during this dry run.
"""
if not self.dry_run:
return
while self.pending_transactions > 0:
self.rollback_transaction()
if transaction.is_dirty():
# Force an exception, if we're still in a dirty transaction.
# This means we are missing a COMMIT/ROLLBACK.
transaction.leave_transaction_management() | [
"def",
"rollback_transactions_dry_run",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"dry_run",
":",
"return",
"while",
"self",
".",
"pending_transactions",
">",
"0",
":",
"self",
".",
"rollback_transaction",
"(",
")",
"if",
"transaction",
".",
"is_dirty",... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/South-0.7.3-py2.7.egg/south/db/generic.py#L778-L789 | ||
nuxeo/FunkLoad | 8a3a44c20398098d03197baeef27a4177858df1b | src/funkload/ReportStats.py | python | PageStat.add | (self, thread, step, date, result, duration, rtype) | Add a new response to stat. | Add a new response to stat. | [
"Add",
"a",
"new",
"response",
"to",
"stat",
"."
] | def add(self, thread, step, date, result, duration, rtype):
"""Add a new response to stat."""
thread = self.threads.setdefault(thread, {'count': 0,
'pages': {}})
if str(rtype) in ('post', 'get', 'xmlrpc', 'put', 'delete', 'head'):
new_page = True
else:
new_page = False
if new_page:
thread['count'] += 1
self.count += 1
if not thread['count']:
# don't take into account request that belongs to a staging up page
return
stat = thread['pages'].setdefault(thread['count'],
SinglePageStat(step))
stat.addResponse(date, result, duration)
self.apdex.add(float(duration))
self.finalized = False | [
"def",
"add",
"(",
"self",
",",
"thread",
",",
"step",
",",
"date",
",",
"result",
",",
"duration",
",",
"rtype",
")",
":",
"thread",
"=",
"self",
".",
"threads",
".",
"setdefault",
"(",
"thread",
",",
"{",
"'count'",
":",
"0",
",",
"'pages'",
":",... | https://github.com/nuxeo/FunkLoad/blob/8a3a44c20398098d03197baeef27a4177858df1b/src/funkload/ReportStats.py#L209-L227 | ||
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-darwin/x64/cryptography/hazmat/primitives/padding.py | python | ANSIX923.unpadder | (self) | return _ANSIX923UnpaddingContext(self.block_size) | [] | def unpadder(self):
return _ANSIX923UnpaddingContext(self.block_size) | [
"def",
"unpadder",
"(",
"self",
")",
":",
"return",
"_ANSIX923UnpaddingContext",
"(",
"self",
".",
"block_size",
")"
] | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/cryptography/hazmat/primitives/padding.py#L159-L160 | |||
partyrobotics/bartendro | 99070c609a480d5be9d523325d13deb4116b7707 | ui/bartendro/global_lock.py | python | BartendroGlobalLock.lock_bartendro | (self) | return True | Call this function before making a drink or doing anything that where two users' action may conflict.
This function will return True if the lock was granted, of False is someone else has already locked
Bartendro. | Call this function before making a drink or doing anything that where two users' action may conflict.
This function will return True if the lock was granted, of False is someone else has already locked
Bartendro. | [
"Call",
"this",
"function",
"before",
"making",
"a",
"drink",
"or",
"doing",
"anything",
"that",
"where",
"two",
"users",
"action",
"may",
"conflict",
".",
"This",
"function",
"will",
"return",
"True",
"if",
"the",
"lock",
"was",
"granted",
"of",
"False",
... | def lock_bartendro(self):
"""Call this function before making a drink or doing anything that where two users' action may conflict.
This function will return True if the lock was granted, of False is someone else has already locked
Bartendro."""
# If we're not running inside uwsgi, then don't try to use the lock
if not have_uwsgi: return True
uwsgi.lock()
is_locked = uwsgi.sharedarea_read8(0, 0)
if is_locked:
uwsgi.unlock()
return False
uwsgi.sharedarea_write8(0, 0, 1)
uwsgi.unlock()
return True | [
"def",
"lock_bartendro",
"(",
"self",
")",
":",
"# If we're not running inside uwsgi, then don't try to use the lock",
"if",
"not",
"have_uwsgi",
":",
"return",
"True",
"uwsgi",
".",
"lock",
"(",
")",
"is_locked",
"=",
"uwsgi",
".",
"sharedarea_read8",
"(",
"0",
","... | https://github.com/partyrobotics/bartendro/blob/99070c609a480d5be9d523325d13deb4116b7707/ui/bartendro/global_lock.py#L31-L47 | |
EmuKit/emukit | cdcb0d070d7f1c5585260266160722b636786859 | emukit/examples/preferential_batch_bayesian_optimization/pbbo/inferences/ep_batch_comparison.py | python | sqrtm_block | (M: np.ndarray, y: List[Tuple[int, float]], yc: List[List[Tuple[int, int]]]) | return Msqrtm | Returns a square root of a positive definite matrix
:param M: A positive definite block matrix
:param y: Observations indicating where we have a diagonal element
:param yc: Comparisons indicating where we have a block diagonal element
:return: Squarte root of M | Returns a square root of a positive definite matrix
:param M: A positive definite block matrix
:param y: Observations indicating where we have a diagonal element
:param yc: Comparisons indicating where we have a block diagonal element
:return: Squarte root of M | [
"Returns",
"a",
"square",
"root",
"of",
"a",
"positive",
"definite",
"matrix",
":",
"param",
"M",
":",
"A",
"positive",
"definite",
"block",
"matrix",
":",
"param",
"y",
":",
"Observations",
"indicating",
"where",
"we",
"have",
"a",
"diagonal",
"element",
... | def sqrtm_block(M: np.ndarray, y: List[Tuple[int, float]], yc: List[List[Tuple[int, int]]]) -> np.ndarray:
"""
Returns a square root of a positive definite matrix
:param M: A positive definite block matrix
:param y: Observations indicating where we have a diagonal element
:param yc: Comparisons indicating where we have a block diagonal element
:return: Squarte root of M
"""
Msqrtm = np.zeros(M.shape)
if(len(y)>0):
for yi, yval in y:
Msqrtm[yi,yi] = np.sqrt(M[yi,yi])
if(len(yc)>0):
for ycb in yc:
loc_inds_winners, loc_inds_loosers = [ycb[k][0] for k in range(len(ycb))], [ycb[k][1] for k in range(len(ycb))]
batch = np.sort(np.unique(loc_inds_winners + loc_inds_loosers))
Msqrtm[np.ix_(batch,batch)] = posdef_sqrtm(M[np.ix_(batch,batch)])
return Msqrtm | [
"def",
"sqrtm_block",
"(",
"M",
":",
"np",
".",
"ndarray",
",",
"y",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"float",
"]",
"]",
",",
"yc",
":",
"List",
"[",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
")",
"->",
"np",
"... | https://github.com/EmuKit/emukit/blob/cdcb0d070d7f1c5585260266160722b636786859/emukit/examples/preferential_batch_bayesian_optimization/pbbo/inferences/ep_batch_comparison.py#L40-L57 | |
1012598167/flask_mongodb_game | 60c7e0351586656ec38f851592886338e50b4110 | python_flask/venv/Lib/site-packages/pymongo/uri_parser.py | python | _parse_options | (opts, delim) | return options | Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion, and the use of a unicode options string. | Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion, and the use of a unicode options string. | [
"Helper",
"method",
"for",
"split_options",
"which",
"creates",
"the",
"options",
"dict",
".",
"Also",
"handles",
"the",
"creation",
"of",
"a",
"list",
"for",
"the",
"URI",
"tag_sets",
"/",
"readpreferencetags",
"portion",
"and",
"the",
"use",
"of",
"a",
"un... | def _parse_options(opts, delim):
"""Helper method for split_options which creates the options dict.
Also handles the creation of a list for the URI tag_sets/
readpreferencetags portion, and the use of a unicode options string."""
options = _CaseInsensitiveDictionary()
for uriopt in opts.split(delim):
key, value = uriopt.split("=")
if key.lower() == 'readpreferencetags':
options.setdefault(key, []).append(value)
else:
if key in options:
warnings.warn("Duplicate URI option '%s'." % (key,))
options[key] = unquote_plus(value)
return options | [
"def",
"_parse_options",
"(",
"opts",
",",
"delim",
")",
":",
"options",
"=",
"_CaseInsensitiveDictionary",
"(",
")",
"for",
"uriopt",
"in",
"opts",
".",
"split",
"(",
"delim",
")",
":",
"key",
",",
"value",
"=",
"uriopt",
".",
"split",
"(",
"\"=\"",
"... | https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pymongo/uri_parser.py#L137-L151 | |
jython/frozen-mirror | b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99 | lib-python/2.7/multiprocessing/pool.py | python | Pool.imap_unordered | (self, func, iterable, chunksize=1) | Like `imap()` method but ordering of results is arbitrary | Like `imap()` method but ordering of results is arbitrary | [
"Like",
"imap",
"()",
"method",
"but",
"ordering",
"of",
"results",
"is",
"arbitrary"
] | def imap_unordered(self, func, iterable, chunksize=1):
'''
Like `imap()` method but ordering of results is arbitrary
'''
assert self._state == RUN
if chunksize == 1:
result = IMapUnorderedIterator(self._cache)
self._taskqueue.put((((result._job, i, func, (x,), {})
for i, x in enumerate(iterable)), result._set_length))
return result
else:
assert chunksize > 1
task_batches = Pool._get_tasks(func, iterable, chunksize)
result = IMapUnorderedIterator(self._cache)
self._taskqueue.put((((result._job, i, mapstar, (x,), {})
for i, x in enumerate(task_batches)), result._set_length))
return (item for chunk in result for item in chunk) | [
"def",
"imap_unordered",
"(",
"self",
",",
"func",
",",
"iterable",
",",
"chunksize",
"=",
"1",
")",
":",
"assert",
"self",
".",
"_state",
"==",
"RUN",
"if",
"chunksize",
"==",
"1",
":",
"result",
"=",
"IMapUnorderedIterator",
"(",
"self",
".",
"_cache",... | https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/multiprocessing/pool.py#L271-L287 | ||
allenai/allennlp-models | b6923c362095a82829646912353425143f757143 | allennlp_models/coref/metrics/conll_coref_scores.py | python | Scorer.ceafe | (clusters, gold_clusters) | return similarity, len(clusters), similarity, len(gold_clusters) | Computes the Constrained Entity-Alignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters.
<https://www.semanticscholar.org/paper/On-Coreference-Resolution-Performance-Metrics-Luo/de133c1f22d0dfe12539e25dda70f28672459b99> | Computes the Constrained Entity-Alignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters. | [
"Computes",
"the",
"Constrained",
"Entity",
"-",
"Alignment",
"F",
"-",
"Measure",
"(",
"CEAF",
")",
"for",
"evaluating",
"coreference",
".",
"Gold",
"and",
"predicted",
"mentions",
"are",
"aligned",
"into",
"clusterings",
"which",
"maximise",
"a",
"metric",
"... | def ceafe(clusters, gold_clusters):
"""
Computes the Constrained Entity-Alignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters.
<https://www.semanticscholar.org/paper/On-Coreference-Resolution-Performance-Metrics-Luo/de133c1f22d0dfe12539e25dda70f28672459b99>
"""
clusters = [cluster for cluster in clusters if len(cluster) != 1]
scores = np.zeros((len(gold_clusters), len(clusters)))
for i, gold_cluster in enumerate(gold_clusters):
for j, cluster in enumerate(clusters):
scores[i, j] = Scorer.phi4(gold_cluster, cluster)
row, col = linear_sum_assignment(-scores)
similarity = sum(scores[row, col])
return similarity, len(clusters), similarity, len(gold_clusters) | [
"def",
"ceafe",
"(",
"clusters",
",",
"gold_clusters",
")",
":",
"clusters",
"=",
"[",
"cluster",
"for",
"cluster",
"in",
"clusters",
"if",
"len",
"(",
"cluster",
")",
"!=",
"1",
"]",
"scores",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"gold_clu... | https://github.com/allenai/allennlp-models/blob/b6923c362095a82829646912353425143f757143/allennlp_models/coref/metrics/conll_coref_scores.py#L237-L252 | |
reviewboard/reviewboard | 7395902e4c181bcd1d633f61105012ffb1d18e1b | reviewboard/datagrids/sidebar.py | python | SidebarNavItem.get_url | (self) | Return the URL for the item.
If :py:attr:`url` is set, that URL will be returned directly.
If :py:attr:`url_name` is set instead, it will be resolved relative
to any Local Site that might be accessed and used as the URL. Note that
the URL can't require any parameters.
If not explicit URL or name is provided, the current page is used along
with query parameters built from :py:attr:`view_id` and
:py:attr:`view_args`.
Returns:
unicode:
The URL to navigate to when clicked. | Return the URL for the item. | [
"Return",
"the",
"URL",
"for",
"the",
"item",
"."
] | def get_url(self):
"""Return the URL for the item.
If :py:attr:`url` is set, that URL will be returned directly.
If :py:attr:`url_name` is set instead, it will be resolved relative
to any Local Site that might be accessed and used as the URL. Note that
the URL can't require any parameters.
If not explicit URL or name is provided, the current page is used along
with query parameters built from :py:attr:`view_id` and
:py:attr:`view_args`.
Returns:
unicode:
The URL to navigate to when clicked.
"""
if self.url:
return self.url
elif self.url_name:
return local_site_reverse(self.url_name,
request=self.datagrid.request)
else:
return super(SidebarNavItem, self).get_url() | [
"def",
"get_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"url",
":",
"return",
"self",
".",
"url",
"elif",
"self",
".",
"url_name",
":",
"return",
"local_site_reverse",
"(",
"self",
".",
"url_name",
",",
"request",
"=",
"self",
".",
"datagrid",
".",... | https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/datagrids/sidebar.py#L303-L326 | ||
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | numba/cpython/setobj.py | python | set_add | (context, builder, sig, args) | return context.get_dummy_value() | [] | def set_add(context, builder, sig, args):
inst = SetInstance(context, builder, sig.args[0], args[0])
item = args[1]
inst.add(item)
return context.get_dummy_value() | [
"def",
"set_add",
"(",
"context",
",",
"builder",
",",
"sig",
",",
"args",
")",
":",
"inst",
"=",
"SetInstance",
"(",
"context",
",",
"builder",
",",
"sig",
".",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"0",
"]",
")",
"item",
"=",
"args",
"[",
... | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cpython/setobj.py#L1230-L1235 | |||
InvestmentSystems/static-frame | 0b19d6969bf6c17fb0599871aca79eb3b52cf2ed | static_frame/core/node_dt.py | python | InterfaceDatetime.is_month_start | (self) | return self._blocks_to_container(blocks()) | Return Boolean indicators if the day is the month start. | Return Boolean indicators if the day is the month start. | [
"Return",
"Boolean",
"indicators",
"if",
"the",
"day",
"is",
"the",
"month",
"start",
"."
] | def is_month_start(self) -> TContainer:
'''Return Boolean indicators if the day is the month start.
'''
def blocks() -> tp.Iterator[np.ndarray]:
for block in self._blocks:
self._validate_dtype_non_str(block.dtype, exclude=self.DT64_EXCLUDE_YEAR_MONTH)
# astype object dtypes to day too
if block.dtype != DT64_DAY:
block = block.astype(DT64_DAY)
array = block == block.astype(DT64_MONTH).astype(DT64_DAY)
array.flags.writeable = False
yield array
return self._blocks_to_container(blocks()) | [
"def",
"is_month_start",
"(",
"self",
")",
"->",
"TContainer",
":",
"def",
"blocks",
"(",
")",
"->",
"tp",
".",
"Iterator",
"[",
"np",
".",
"ndarray",
"]",
":",
"for",
"block",
"in",
"self",
".",
"_blocks",
":",
"self",
".",
"_validate_dtype_non_str",
... | https://github.com/InvestmentSystems/static-frame/blob/0b19d6969bf6c17fb0599871aca79eb3b52cf2ed/static_frame/core/node_dt.py#L350-L364 | |
ahmetb/kubectl-aliases | 4440d32d636dc9aade0c5cbbf627e003f04cf939 | generate_aliases.py | python | diff | (a, b) | return list(set(a) - set(b)) | [] | def diff(a, b):
return list(set(a) - set(b)) | [
"def",
"diff",
"(",
"a",
",",
"b",
")",
":",
"return",
"list",
"(",
"set",
"(",
"a",
")",
"-",
"set",
"(",
"b",
")",
")"
] | https://github.com/ahmetb/kubectl-aliases/blob/4440d32d636dc9aade0c5cbbf627e003f04cf939/generate_aliases.py#L190-L191 | |||
jankrepl/deepdow | eb6c85845c45f89e0743b8e8c29ddb69cb78da4f | deepdow/layers/collapse.py | python | AttentionCollapse.forward | (self, x) | return torch.stack(res_list, dim=0) | Perform forward pass.
Parameters
----------
x : torch.Tensor
Tensor of shape `(n_samples, n_channels, lookback, n_assets)`.
Returns
-------
torch.Tensor
Tensor of shape `(n_samples, n_channels, n_assets)`. | Perform forward pass. | [
"Perform",
"forward",
"pass",
"."
] | def forward(self, x):
"""Perform forward pass.
Parameters
----------
x : torch.Tensor
Tensor of shape `(n_samples, n_channels, lookback, n_assets)`.
Returns
-------
torch.Tensor
Tensor of shape `(n_samples, n_channels, n_assets)`.
"""
n_samples, n_channels, lookback, n_assets = x.shape
res_list = []
for i in range(n_samples):
inp_single = x[i].permute(2, 1, 0) # n_assets, lookback, n_channels
tformed = self.affine(inp_single) # n_assets, lookback, n_channels
w = self.context_vector(tformed) # n_assets, lookback, 1
scaled_w = torch.nn.functional.softmax(w, dim=1) # n_assets, lookback, 1
weighted_sum = (inp_single * scaled_w).mean(dim=1) # n_assets, n_channels
res_list.append(weighted_sum.permute(1, 0)) # n_channels, n_assets
return torch.stack(res_list, dim=0) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"n_samples",
",",
"n_channels",
",",
"lookback",
",",
"n_assets",
"=",
"x",
".",
"shape",
"res_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n_samples",
")",
":",
"inp_single",
"=",
"x",
"... | https://github.com/jankrepl/deepdow/blob/eb6c85845c45f89e0743b8e8c29ddb69cb78da4f/deepdow/layers/collapse.py#L30-L55 | |
carrierlxk/COSNet | 549109db0d60b69fd4f70b400bd48a12d6c83ea7 | train_iteration_conf.py | python | adjust_learning_rate | (optimizer, i_iter, epoch, max_iter) | return lr | Sets the learning rate to the initial LR divided by 5 at 60th, 120th and 160th epochs | Sets the learning rate to the initial LR divided by 5 at 60th, 120th and 160th epochs | [
"Sets",
"the",
"learning",
"rate",
"to",
"the",
"initial",
"LR",
"divided",
"by",
"5",
"at",
"60th",
"120th",
"and",
"160th",
"epochs"
] | def adjust_learning_rate(optimizer, i_iter, epoch, max_iter):
"""Sets the learning rate to the initial LR divided by 5 at 60th, 120th and 160th epochs"""
lr = lr_poly(args.learning_rate, i_iter, max_iter, args.power, epoch)
optimizer.param_groups[0]['lr'] = lr
if i_iter%3 ==0:
optimizer.param_groups[0]['lr'] = lr
optimizer.param_groups[1]['lr'] = 0
else:
optimizer.param_groups[0]['lr'] = 0.01*lr
optimizer.param_groups[1]['lr'] = lr * 10
return lr | [
"def",
"adjust_learning_rate",
"(",
"optimizer",
",",
"i_iter",
",",
"epoch",
",",
"max_iter",
")",
":",
"lr",
"=",
"lr_poly",
"(",
"args",
".",
"learning_rate",
",",
"i_iter",
",",
"max_iter",
",",
"args",
".",
"power",
",",
"epoch",
")",
"optimizer",
"... | https://github.com/carrierlxk/COSNet/blob/549109db0d60b69fd4f70b400bd48a12d6c83ea7/train_iteration_conf.py#L133-L145 | |
unias/docklet | 70c089a6a5bb186dc3f898127af84d79b4dfab2d | src/utils/log.py | python | RedirectLogger.__init__ | (self, logger, level) | Needs a logger and a logger level. | Needs a logger and a logger level. | [
"Needs",
"a",
"logger",
"and",
"a",
"logger",
"level",
"."
] | def __init__(self, logger, level):
"""Needs a logger and a logger level."""
self.logger = logger
self.level = level | [
"def",
"__init__",
"(",
"self",
",",
"logger",
",",
"level",
")",
":",
"self",
".",
"logger",
"=",
"logger",
"self",
".",
"level",
"=",
"level"
] | https://github.com/unias/docklet/blob/70c089a6a5bb186dc3f898127af84d79b4dfab2d/src/utils/log.py#L56-L59 | ||
IJDykeman/wangTiles | 7c1ee2095ebdf7f72bce07d94c6484915d5cae8b | experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pip/util.py | python | splitext | (path) | return base, ext | Like os.path.splitext, but take off .tar too | Like os.path.splitext, but take off .tar too | [
"Like",
"os",
".",
"path",
".",
"splitext",
"but",
"take",
"off",
".",
"tar",
"too"
] | def splitext(path):
"""Like os.path.splitext, but take off .tar too"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext | [
"def",
"splitext",
"(",
"path",
")",
":",
"base",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"path",
")",
"if",
"base",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.tar'",
")",
":",
"ext",
"=",
"base",
"[",
"-",
"4",
":",
"]",
"+",... | https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv/lib/python2.7/site-packages/pip/util.py#L279-L285 | |
JetBrains/python-skeletons | 95ad24b666e475998e5d1cc02ed53a2188036167 | __builtin__.py | python | long.__mul__ | (self, y) | return 0 | Product of x and y.
:type y: numbers.Number
:rtype: long | Product of x and y. | [
"Product",
"of",
"x",
"and",
"y",
"."
] | def __mul__(self, y):
"""Product of x and y.
:type y: numbers.Number
:rtype: long
"""
return 0 | [
"def",
"__mul__",
"(",
"self",
",",
"y",
")",
":",
"return",
"0"
] | https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/__builtin__.py#L737-L743 | |
smart-mobile-software/gitstack | d9fee8f414f202143eb6e620529e8e5539a2af56 | python/Lib/site-packages/django/contrib/gis/geos/mutable_list.py | python | ListMixin.append | (self, val) | Standard list append method | Standard list append method | [
"Standard",
"list",
"append",
"method"
] | def append(self, val):
"Standard list append method"
self[len(self):] = [val] | [
"def",
"append",
"(",
"self",
",",
"val",
")",
":",
"self",
"[",
"len",
"(",
"self",
")",
":",
"]",
"=",
"[",
"val",
"]"
] | https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/contrib/gis/geos/mutable_list.py#L177-L179 | ||
albertz/music-player | d23586f5bf657cbaea8147223be7814d117ae73d | mac/pyobjc-framework-Quartz/Examples/PDFKit/PDFKitViewer/MyPDFDocument.py | python | MyPDFDocument.loadDataRepresentation_ofType_ | (self, data, aType) | return True | [] | def loadDataRepresentation_ofType_(self, data, aType):
return True | [
"def",
"loadDataRepresentation_ofType_",
"(",
"self",
",",
"data",
",",
"aType",
")",
":",
"return",
"True"
] | https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-framework-Quartz/Examples/PDFKit/PDFKitViewer/MyPDFDocument.py#L78-L79 | |||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/google/appengine/api/app_identity/app_identity_service_pb.py | python | _SigningService_ClientBaseStub.SignForApp | (self, request, rpc=None, callback=None, response=None) | return self._MakeCall(rpc,
self._full_name_SignForApp,
'SignForApp',
request,
response,
callback,
self._protorpc_SignForApp) | Make a SignForApp RPC call.
Args:
request: a SignForAppRequest instance.
rpc: Optional RPC instance to use for the call.
callback: Optional final callback. Will be called as
callback(rpc, result) when the rpc completes. If None, the
call is synchronous.
response: Optional ProtocolMessage to be filled in with response.
Returns:
The SignForAppResponse if callback is None. Otherwise, returns None. | Make a SignForApp RPC call. | [
"Make",
"a",
"SignForApp",
"RPC",
"call",
"."
] | def SignForApp(self, request, rpc=None, callback=None, response=None):
"""Make a SignForApp RPC call.
Args:
request: a SignForAppRequest instance.
rpc: Optional RPC instance to use for the call.
callback: Optional final callback. Will be called as
callback(rpc, result) when the rpc completes. If None, the
call is synchronous.
response: Optional ProtocolMessage to be filled in with response.
Returns:
The SignForAppResponse if callback is None. Otherwise, returns None.
"""
if response is None:
response = SignForAppResponse
return self._MakeCall(rpc,
self._full_name_SignForApp,
'SignForApp',
request,
response,
callback,
self._protorpc_SignForApp) | [
"def",
"SignForApp",
"(",
"self",
",",
"request",
",",
"rpc",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"response",
"=",
"None",
")",
":",
"if",
"response",
"is",
"None",
":",
"response",
"=",
"SignForAppResponse",
"return",
"self",
".",
"_MakeCall... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/app_identity/app_identity_service_pb.py#L1765-L1788 | |
Nuitka/Nuitka | 39262276993757fa4e299f497654065600453fc9 | nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Tool/intelc.py | python | get_version_from_list | (v, vlist) | See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way. | See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way. | [
"See",
"if",
"we",
"can",
"match",
"v",
"(",
"string",
")",
"in",
"vlist",
"(",
"list",
"of",
"strings",
")",
"Linux",
"has",
"to",
"match",
"in",
"a",
"fuzzy",
"way",
"."
] | def get_version_from_list(v, vlist):
"""See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way."""
if is_windows:
# Simple case, just find it in the list
if v in vlist: return v
else: return None
else:
# Fuzzy match: normalize version number first, but still return
# original non-normalized form.
fuzz = 0.001
for vi in vlist:
if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz:
return vi
# Not found
return None | [
"def",
"get_version_from_list",
"(",
"v",
",",
"vlist",
")",
":",
"if",
"is_windows",
":",
"# Simple case, just find it in the list",
"if",
"v",
"in",
"vlist",
":",
"return",
"v",
"else",
":",
"return",
"None",
"else",
":",
"# Fuzzy match: normalize version number f... | https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Tool/intelc.py#L116-L131 | ||
pillone/usntssearch | 24b5e5bc4b6af2589d95121c4d523dc58cb34273 | NZBmegasearch/werkzeug/wrappers.py | python | BaseResponse.get_wsgi_response | (self, environ) | return app_iter, self.status, headers.to_list() | Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the request
method in the WSGI environment is ``'HEAD'`` the response will
be empty and only the headers and status code will be present.
.. versionadded:: 0.6
:param environ: the WSGI environment of the request.
:return: an ``(app_iter, status, headers)`` tuple. | Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the request
method in the WSGI environment is ``'HEAD'`` the response will
be empty and only the headers and status code will be present. | [
"Returns",
"the",
"final",
"WSGI",
"response",
"as",
"tuple",
".",
"The",
"first",
"item",
"in",
"the",
"tuple",
"is",
"the",
"application",
"iterator",
"the",
"second",
"the",
"status",
"and",
"the",
"third",
"the",
"list",
"of",
"headers",
".",
"The",
... | def get_wsgi_response(self, environ):
"""Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the request
method in the WSGI environment is ``'HEAD'`` the response will
be empty and only the headers and status code will be present.
.. versionadded:: 0.6
:param environ: the WSGI environment of the request.
:return: an ``(app_iter, status, headers)`` tuple.
"""
# XXX: code for backwards compatibility with custom fix_headers
# methods.
if self.fix_headers.func_code is not \
BaseResponse.fix_headers.func_code:
if __debug__:
from warnings import warn
warn(DeprecationWarning('fix_headers changed behavior in 0.6 '
'and is now called get_wsgi_headers. '
'See documentation for more details.'),
stacklevel=2)
self.fix_headers(environ)
headers = self.headers
else:
headers = self.get_wsgi_headers(environ)
app_iter = self.get_app_iter(environ)
return app_iter, self.status, headers.to_list() | [
"def",
"get_wsgi_response",
"(",
"self",
",",
"environ",
")",
":",
"# XXX: code for backwards compatibility with custom fix_headers",
"# methods.",
"if",
"self",
".",
"fix_headers",
".",
"func_code",
"is",
"not",
"BaseResponse",
".",
"fix_headers",
".",
"func_code",
":"... | https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/werkzeug/wrappers.py#L1044-L1072 | |
msg-systems/holmes-extractor | fc536f32a5cd02a53d1c32f771adc14227d09f38 | holmes_extractor/parsing.py | python | HolmesDictionary.get_label_of_dependency_with_child_index | (self, index) | return None | [] | def get_label_of_dependency_with_child_index(self, index):
for dependency in self.children:
if dependency.child_index == index:
return dependency.label
return None | [
"def",
"get_label_of_dependency_with_child_index",
"(",
"self",
",",
"index",
")",
":",
"for",
"dependency",
"in",
"self",
".",
"children",
":",
"if",
"dependency",
".",
"child_index",
"==",
"index",
":",
"return",
"dependency",
".",
"label",
"return",
"None"
] | https://github.com/msg-systems/holmes-extractor/blob/fc536f32a5cd02a53d1c32f771adc14227d09f38/holmes_extractor/parsing.py#L338-L342 | |||
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/bs4/builder/__init__.py | python | HTMLTreeBuilder.set_up_substitutions | (self, tag) | return (meta_encoding is not None) | [] | def set_up_substitutions(self, tag):
# We are only interested in <meta> tags
if tag.name != 'meta':
return False
http_equiv = tag.get('http-equiv')
content = tag.get('content')
charset = tag.get('charset')
# We are interested in <meta> tags that say what encoding the
# document was originally in. This means HTML 5-style <meta>
# tags that provide the "charset" attribute. It also means
# HTML 4-style <meta> tags that provide the "content"
# attribute and have "http-equiv" set to "content-type".
#
# In both cases we will replace the value of the appropriate
# attribute with a standin object that can take on any
# encoding.
meta_encoding = None
if charset is not None:
# HTML 5 style:
# <meta charset="utf8">
meta_encoding = charset
tag['charset'] = CharsetMetaAttributeValue(charset)
elif (content is not None and http_equiv is not None
and http_equiv.lower() == 'content-type'):
# HTML 4 style:
# <meta http-equiv="content-type" content="text/html; charset=utf8">
tag['content'] = ContentMetaAttributeValue(content)
return (meta_encoding is not None) | [
"def",
"set_up_substitutions",
"(",
"self",
",",
"tag",
")",
":",
"# We are only interested in <meta> tags",
"if",
"tag",
".",
"name",
"!=",
"'meta'",
":",
"return",
"False",
"http_equiv",
"=",
"tag",
".",
"get",
"(",
"'http-equiv'",
")",
"content",
"=",
"tag"... | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/bs4/builder/__init__.py#L258-L289 | |||
xtiankisutsa/MARA_Framework | ac4ac88bfd38f33ae8780a606ed09ab97177c562 | tools/androwarn/androwarn/util/util.py | python | search_field | (x, field_name) | return [] | @param x : a VMAnalysis instance
@param field_name : a regexp for the field name
@rtype : a list of classes' paths | [] | def search_field(x, field_name) :
"""
@param x : a VMAnalysis instance
@param field_name : a regexp for the field name
@rtype : a list of classes' paths
"""
for f, _ in x.tainted_variables.get_fields() :
field_info = f.get_info()
if field_name in field_info :
return f
return [] | [
"def",
"search_field",
"(",
"x",
",",
"field_name",
")",
":",
"for",
"f",
",",
"_",
"in",
"x",
".",
"tainted_variables",
".",
"get_fields",
"(",
")",
":",
"field_info",
"=",
"f",
".",
"get_info",
"(",
")",
"if",
"field_name",
"in",
"field_info",
":",
... | https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/androwarn/androwarn/util/util.py#L164-L175 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Tools/ccbench/ccbench.py | python | bandwidth_client | (addr, packet_size, duration) | [] | def bandwidth_client(addr, packet_size, duration):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", 0))
local_addr = sock.getsockname()
_time = time.time
_sleep = time.sleep
def _send_chunk(msg):
_sendto(sock, ("%r#%s\n" % (local_addr, msg)).rjust(packet_size), addr)
# We give the parent some time to be ready.
_sleep(1.0)
try:
start_time = _time()
end_time = start_time + duration * 2.0
i = 0
while _time() < end_time:
_send_chunk(str(i))
s = _recv(sock, packet_size)
assert len(s) == packet_size
i += 1
_send_chunk(BW_END)
finally:
sock.close() | [
"def",
"bandwidth_client",
"(",
"addr",
",",
"packet_size",
",",
"duration",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"sock",
".",
"bind",
"(",
"(",
"\"127.0.0.1\"",
",",
"0",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/ccbench/ccbench.py#L403-L424 | ||||
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-linux/x64/tornado/http1connection.py | python | _GzipMessageDelegate.finish | (self) | return self._delegate.finish() | [] | def finish(self) -> None:
if self._decompressor is not None:
tail = self._decompressor.flush()
if tail:
# The tail should always be empty: decompress returned
# all that it can in data_received and the only
# purpose of the flush call is to detect errors such
# as truncated input. If we did legitimately get a new
# chunk at this point we'd need to change the
# interface to make finish() a coroutine.
raise ValueError(
"decompressor.flush returned data; possile truncated input"
)
return self._delegate.finish() | [
"def",
"finish",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_decompressor",
"is",
"not",
"None",
":",
"tail",
"=",
"self",
".",
"_decompressor",
".",
"flush",
"(",
")",
"if",
"tail",
":",
"# The tail should always be empty: decompress returned",
... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/tornado/http1connection.py#L743-L756 | |||
chenguanyou/weixin_YiQi | ad86ed8061f4f5fa88b6600a9b0809e5bb3bfd08 | backend/Yiqi/Yiqi/utils/weixin_util/weixin/lib/WXBizMsgCrypt.py | python | Prpcrypt.decrypt | (self, text, appid) | return 0, xml_content | 对解密后的明文进行补位删除
@param text: 密文
@return: 删除填充补位后的明文 | 对解密后的明文进行补位删除 | [
"对解密后的明文进行补位删除"
] | def decrypt(self, text, appid):
"""对解密后的明文进行补位删除
@param text: 密文
@return: 删除填充补位后的明文
"""
try:
cryptor = AES.new(self.key, self.mode, self.key[:16])
# 使用BASE64对密文进行解码,然后AES-CBC解密
plain_text = cryptor.decrypt(base64.b64decode(text))
except Exception:
return WXBizMsgCrypt_DecryptAES_Error, None
try:
if not isinstance(plain_text[-1], int):
pad = ord(plain_text[-1])
else:
pad = plain_text[-1]
# 去掉补位字符串
# pkcs7 = PKCS7Encoder()
# plain_text = pkcs7.encode(plain_text)
# 去除16位随机字符串
content = plain_text[16:-pad]
xml_len = socket.ntohl(struct.unpack(b"I", content[:4])[0])
xml_content = content[4:xml_len+4]
from_appid = smart_bytes(content[xml_len+4:])
except Exception:
return WXBizMsgCrypt_IllegalBuffer, None
if from_appid != smart_bytes(appid):
return WXBizMsgCrypt_ValidateAppid_Error, None
return 0, xml_content | [
"def",
"decrypt",
"(",
"self",
",",
"text",
",",
"appid",
")",
":",
"try",
":",
"cryptor",
"=",
"AES",
".",
"new",
"(",
"self",
".",
"key",
",",
"self",
".",
"mode",
",",
"self",
".",
"key",
"[",
":",
"16",
"]",
")",
"# 使用BASE64对密文进行解码,然后AES-CBC解密"... | https://github.com/chenguanyou/weixin_YiQi/blob/ad86ed8061f4f5fa88b6600a9b0809e5bb3bfd08/backend/Yiqi/Yiqi/utils/weixin_util/weixin/lib/WXBizMsgCrypt.py#L161-L189 | |
GiulioRossetti/cdlib | b2c6311b99725bb2b029556f531d244a2af14a2a | cdlib/algorithms/internal/CONGA.py | python | max_split_betweenness | (G, dic) | return vMax, vNum, vSpl | Given a dictionary of vertices and their pair betweenness scores, uses the greedy
algorithm discussed in the CONGA paper to find a (hopefully) near-optimal split.
Returns a 3-tuple (vMax, vNum, vSpl) where vMax is the max split betweenness,
vNum is the vertex with said split betweenness, and vSpl is a list of which
vertices are on each side of the optimal split. | Given a dictionary of vertices and their pair betweenness scores, uses the greedy
algorithm discussed in the CONGA paper to find a (hopefully) near-optimal split.
Returns a 3-tuple (vMax, vNum, vSpl) where vMax is the max split betweenness,
vNum is the vertex with said split betweenness, and vSpl is a list of which
vertices are on each side of the optimal split. | [
"Given",
"a",
"dictionary",
"of",
"vertices",
"and",
"their",
"pair",
"betweenness",
"scores",
"uses",
"the",
"greedy",
"algorithm",
"discussed",
"in",
"the",
"CONGA",
"paper",
"to",
"find",
"a",
"(",
"hopefully",
")",
"near",
"-",
"optimal",
"split",
".",
... | def max_split_betweenness(G, dic):
"""
Given a dictionary of vertices and their pair betweenness scores, uses the greedy
algorithm discussed in the CONGA paper to find a (hopefully) near-optimal split.
Returns a 3-tuple (vMax, vNum, vSpl) where vMax is the max split betweenness,
vNum is the vertex with said split betweenness, and vSpl is a list of which
vertices are on each side of the optimal split.
"""
vMax = 0
# for every vertex of interest, we want to figure out the maximum score achievable
# by splitting the vertices in various ways, and return that optimal split
for v in dic:
clique = create_clique(G, v, dic[v])
# initialize a list on how we will map the neighbors to the collapsing matrix
vMap = [[ve] for ve in G.neighbors(v)]
# we want to keep collapsing the matrix until we have a 2x2 matrix and its
# score. Then we want to remove index j from our vMap list and concatenate
# it with the vMap[i]. This begins building a way of keeping track of how
# we are splitting the vertex and its neighbors
while clique.size > 4:
i, j, clique = reduce_matrix(clique)
vMap[i] += vMap.pop(j)
if clique[0, 1] >= vMax:
vMax = clique[0, 1]
vNum = v
vSpl = vMap
return vMax, vNum, vSpl | [
"def",
"max_split_betweenness",
"(",
"G",
",",
"dic",
")",
":",
"vMax",
"=",
"0",
"# for every vertex of interest, we want to figure out the maximum score achievable",
"# by splitting the vertices in various ways, and return that optimal split",
"for",
"v",
"in",
"dic",
":",
"cli... | https://github.com/GiulioRossetti/cdlib/blob/b2c6311b99725bb2b029556f531d244a2af14a2a/cdlib/algorithms/internal/CONGA.py#L477-L505 | |
microsoft/msticpy | 2a401444ee529114004f496f4c0376ff25b5268a | msticpy/data/azure_blob_storage.py | python | AzureBlobStorage.blobs | (self, container_name: str) | return _parse_returned_items(blobs) if blobs else None | Get a list of blobs in a container.
Parameters
----------
container_name : str
The name of the container to get blobs from.
Returns
-------
pd.DataFrame
Details of the blobs. | Get a list of blobs in a container. | [
"Get",
"a",
"list",
"of",
"blobs",
"in",
"a",
"container",
"."
] | def blobs(self, container_name: str) -> Optional[pd.DataFrame]:
"""
Get a list of blobs in a container.
Parameters
----------
container_name : str
The name of the container to get blobs from.
Returns
-------
pd.DataFrame
Details of the blobs.
"""
container_client = self.abs_client.get_container_client(container_name) # type: ignore
blobs = list(container_client.list_blobs())
return _parse_returned_items(blobs) if blobs else None | [
"def",
"blobs",
"(",
"self",
",",
"container_name",
":",
"str",
")",
"->",
"Optional",
"[",
"pd",
".",
"DataFrame",
"]",
":",
"container_client",
"=",
"self",
".",
"abs_client",
".",
"get_container_client",
"(",
"container_name",
")",
"# type: ignore",
"blobs"... | https://github.com/microsoft/msticpy/blob/2a401444ee529114004f496f4c0376ff25b5268a/msticpy/data/azure_blob_storage.py#L104-L121 | |
ProjectQ-Framework/ProjectQ | 0d32c1610ba4e9aefd7f19eb52dadb4fbe5f9005 | projectq/cengines/_twodmapper.py | python | GridMapper.is_available | (self, cmd) | return num_qubits <= 2 | Only allow 1 or two qubit gates. | Only allow 1 or two qubit gates. | [
"Only",
"allow",
"1",
"or",
"two",
"qubit",
"gates",
"."
] | def is_available(self, cmd):
"""Only allow 1 or two qubit gates."""
num_qubits = 0
for qureg in cmd.all_qubits:
num_qubits += len(qureg)
return num_qubits <= 2 | [
"def",
"is_available",
"(",
"self",
",",
"cmd",
")",
":",
"num_qubits",
"=",
"0",
"for",
"qureg",
"in",
"cmd",
".",
"all_qubits",
":",
"num_qubits",
"+=",
"len",
"(",
"qureg",
")",
"return",
"num_qubits",
"<=",
"2"
] | https://github.com/ProjectQ-Framework/ProjectQ/blob/0d32c1610ba4e9aefd7f19eb52dadb4fbe5f9005/projectq/cengines/_twodmapper.py#L175-L180 | |
lektor/lektor-archive | d2ab208c756b1e7092b2056108571719abd8d6cd | lektor/db.py | python | Image.format | (self) | return Undefined('The format of the image could not be determined.') | Returns the format of the image. | Returns the format of the image. | [
"Returns",
"the",
"format",
"of",
"the",
"image",
"."
] | def format(self):
"""Returns the format of the image."""
rv = self._get_image_info()[0]
if rv is not None:
return rv
return Undefined('The format of the image could not be determined.') | [
"def",
"format",
"(",
"self",
")",
":",
"rv",
"=",
"self",
".",
"_get_image_info",
"(",
")",
"[",
"0",
"]",
"if",
"rv",
"is",
"not",
"None",
":",
"return",
"rv",
"return",
"Undefined",
"(",
"'The format of the image could not be determined.'",
")"
] | https://github.com/lektor/lektor-archive/blob/d2ab208c756b1e7092b2056108571719abd8d6cd/lektor/db.py#L582-L587 | |
Jack-Cherish/python-spider | 0d3b56b3ec179cac93155fc14cec815b3c963083 | baiwan/baiwan.py | python | BaiWan.search | (self, question, alternative_answers) | [] | def search(self, question, alternative_answers):
print(question)
print(alternative_answers)
infos = {"word":question}
# 调用百度接口
url = self.baidu + 'lm=0&rn=10&pn=0&fr=search&ie=gbk&' + urllib.parse.urlencode(infos, encoding='GB2312')
print(url)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36',
}
sess = requests.Session()
req = sess.get(url = url, headers=headers, verify=False)
req.encoding = 'gbk'
# print(req.text)
bf = BeautifulSoup(req.text, 'lxml')
answers = bf.find_all('dd',class_='dd answer')
for answer in answers:
print(answer.text)
# 推荐答案
recommend = ''
if alternative_answers != []:
best = []
print('\n')
for answer in answers:
# print(answer.text)
for each_answer in alternative_answers:
if each_answer in answer.text:
best.append(each_answer)
print(each_answer,end=' ')
# print(answer.text)
print('\n')
break
statistics = {}
for each in best:
if each not in statistics.keys():
statistics[each] = 1
else:
statistics[each] += 1
errors = ['没有', '不是', '不对', '不正确','错误','不包括','不包含','不在','错']
error_list = list(map(lambda x: x in question, errors))
print(error_list)
if sum(error_list) >= 1:
for each_answer in alternative_answers:
if each_answer not in statistics.items():
recommend = each_answer
print('推荐答案:', recommend)
break
elif statistics != {}:
recommend = sorted(statistics.items(), key=lambda e:e[1], reverse=True)[0][0]
print('推荐答案:', recommend)
# 写入文件
with open('file.txt', 'w') as f:
f.write('问题:' + question)
f.write('\n')
f.write('*' * 50)
f.write('\n')
if alternative_answers != []:
f.write('选项:')
for i in range(len(alternative_answers)):
f.write(alternative_answers[i])
f.write(' ')
f.write('\n')
f.write('*' * 50)
f.write('\n')
f.write('参考答案:\n')
for answer in answers:
f.write(answer.text)
f.write('\n')
f.write('*' * 50)
f.write('\n')
if recommend != '':
f.write('最终答案请自行斟酌!\t')
f.write('推荐答案:' + sorted(statistics.items(), key=lambda e:e[1], reverse=True)[0][0]) | [
"def",
"search",
"(",
"self",
",",
"question",
",",
"alternative_answers",
")",
":",
"print",
"(",
"question",
")",
"print",
"(",
"alternative_answers",
")",
"infos",
"=",
"{",
"\"word\"",
":",
"question",
"}",
"# 调用百度接口",
"url",
"=",
"self",
".",
"baidu",... | https://github.com/Jack-Cherish/python-spider/blob/0d3b56b3ec179cac93155fc14cec815b3c963083/baiwan/baiwan.py#L91-L164 | ||||
realpython/book2-exercises | cde325eac8e6d8cff2316601c2e5b36bb46af7d0 | web2py-rest/gluon/cache.py | python | CacheAbstract.__call__ | (self, key, f,
time_expire=DEFAULT_TIME_EXPIRE) | Tries to retrieve the value corresponding to `key` from the cache if the
object exists and if it did not expire, else it calls the function `f`
and stores the output in the cache corresponding to `key`. It always
returns the function that is returned.
Args:
key(str): the key of the object to be stored or retrieved
f(function): the function whose output is to be cached.
If `f` is `None` the cache is cleared.
time_expire(int): expiration of the cache in seconds.
It's used to compare the current time with the time
when the requested object was last saved in cache. It does not
affect future requests. Setting `time_expire` to 0 or negative
value forces the cache to refresh. | Tries to retrieve the value corresponding to `key` from the cache if the
object exists and if it did not expire, else it calls the function `f`
and stores the output in the cache corresponding to `key`. It always
returns the function that is returned. | [
"Tries",
"to",
"retrieve",
"the",
"value",
"corresponding",
"to",
"key",
"from",
"the",
"cache",
"if",
"the",
"object",
"exists",
"and",
"if",
"it",
"did",
"not",
"expire",
"else",
"it",
"calls",
"the",
"function",
"f",
"and",
"stores",
"the",
"output",
... | def __call__(self, key, f,
time_expire=DEFAULT_TIME_EXPIRE):
"""
Tries to retrieve the value corresponding to `key` from the cache if the
object exists and if it did not expire, else it calls the function `f`
and stores the output in the cache corresponding to `key`. It always
returns the function that is returned.
Args:
key(str): the key of the object to be stored or retrieved
f(function): the function whose output is to be cached.
If `f` is `None` the cache is cleared.
time_expire(int): expiration of the cache in seconds.
It's used to compare the current time with the time
when the requested object was last saved in cache. It does not
affect future requests. Setting `time_expire` to 0 or negative
value forces the cache to refresh.
"""
raise NotImplementedError | [
"def",
"__call__",
"(",
"self",
",",
"key",
",",
"f",
",",
"time_expire",
"=",
"DEFAULT_TIME_EXPIRE",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py-rest/gluon/cache.py#L115-L135 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/vilfo/__init__.py | python | VilfoRouterData.async_update | (self) | Update data using calls to VilfoClient library. | Update data using calls to VilfoClient library. | [
"Update",
"data",
"using",
"calls",
"to",
"VilfoClient",
"library",
"."
] | async def async_update(self):
"""Update data using calls to VilfoClient library."""
try:
data = await self.hass.async_add_executor_job(self._fetch_data)
self.firmware_version = data["board_information"]["version"]
self.data[ATTR_BOOT_TIME] = data["board_information"]["bootTime"]
self.data[ATTR_LOAD] = data["load"]
self.available = True
except VilfoException as error:
if not self._unavailable_logged:
_LOGGER.error(
"Could not fetch data from %s, error: %s", self.host, error
)
self._unavailable_logged = True
self.available = False
return
if self.available and self._unavailable_logged:
_LOGGER.info("Vilfo Router %s is available again", self.host)
self._unavailable_logged = False | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_fetch_data",
")",
"self",
".",
"firmware_version",
"=",
"data",
"[",
"\"board_information\"",
"]"... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/vilfo/__init__.py#L87-L108 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/reportlab/pdfgen/pathobject.py | python | PDFPathObject.close | (self) | draws a line back to where it started | draws a line back to where it started | [
"draws",
"a",
"line",
"back",
"to",
"where",
"it",
"started"
] | def close(self):
"draws a line back to where it started"
self._code_append('h') | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_code_append",
"(",
"'h'",
")"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/reportlab/pdfgen/pathobject.py#L125-L127 | ||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/blobs/interface.py | python | AbstractBlobDB.size | (self, key) | Gets the size of a stored blob in bytes. This may be different from the raw
content length if the blob was compressed.
:param key: Blob key.
:returns: The number of bytes of a blob | Gets the size of a stored blob in bytes. This may be different from the raw
content length if the blob was compressed. | [
"Gets",
"the",
"size",
"of",
"a",
"stored",
"blob",
"in",
"bytes",
".",
"This",
"may",
"be",
"different",
"from",
"the",
"raw",
"content",
"length",
"if",
"the",
"blob",
"was",
"compressed",
"."
] | def size(self, key):
"""Gets the size of a stored blob in bytes. This may be different from the raw
content length if the blob was compressed.
:param key: Blob key.
:returns: The number of bytes of a blob
"""
raise NotImplementedError | [
"def",
"size",
"(",
"self",
",",
"key",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/blobs/interface.py#L96-L103 | ||
spotify/luigi | c3b66f4a5fa7eaa52f9a72eb6704b1049035c789 | luigi/contrib/hadoop.py | python | fetch_task_failures | (tracking_url) | return '\n'.join(error_text) | Uses mechanize to fetch the actual task logs from the task tracker.
This is highly opportunistic, and we might not succeed.
So we set a low timeout and hope it works.
If it does not, it's not the end of the world.
TODO: Yarn has a REST API that we should probably use instead:
http://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-site/WebServicesIntro.html | Uses mechanize to fetch the actual task logs from the task tracker. | [
"Uses",
"mechanize",
"to",
"fetch",
"the",
"actual",
"task",
"logs",
"from",
"the",
"task",
"tracker",
"."
] | def fetch_task_failures(tracking_url):
"""
Uses mechanize to fetch the actual task logs from the task tracker.
This is highly opportunistic, and we might not succeed.
So we set a low timeout and hope it works.
If it does not, it's not the end of the world.
TODO: Yarn has a REST API that we should probably use instead:
http://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-site/WebServicesIntro.html
"""
import mechanize
timeout = 3.0
failures_url = tracking_url.replace('jobdetails.jsp', 'jobfailures.jsp') + '&cause=failed'
logger.debug('Fetching data from %s', failures_url)
b = mechanize.Browser()
b.open(failures_url, timeout=timeout)
links = list(b.links(text_regex='Last 4KB')) # For some reason text_regex='All' doesn't work... no idea why
links = random.sample(links, min(10, len(links))) # Fetch a random subset of all failed tasks, so not to be biased towards the early fails
error_text = []
for link in links:
task_url = link.url.replace('&start=-4097', '&start=-100000') # Increase the offset
logger.debug('Fetching data from %s', task_url)
b2 = mechanize.Browser()
try:
r = b2.open(task_url, timeout=timeout)
data = r.read()
except Exception as e:
logger.debug('Error fetching data from %s: %s', task_url, e)
continue
# Try to get the hex-encoded traceback back from the output
for exc in re.findall(r'luigi-exc-hex=[0-9a-f]+', data):
error_text.append('---------- %s:' % task_url)
error_text.append(exc.split('=')[-1].decode('hex'))
return '\n'.join(error_text) | [
"def",
"fetch_task_failures",
"(",
"tracking_url",
")",
":",
"import",
"mechanize",
"timeout",
"=",
"3.0",
"failures_url",
"=",
"tracking_url",
".",
"replace",
"(",
"'jobdetails.jsp'",
",",
"'jobfailures.jsp'",
")",
"+",
"'&cause=failed'",
"logger",
".",
"debug",
... | https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/luigi/contrib/hadoop.py#L347-L382 | |
dwadden/dygiepp | 8faac5711489d4f5fb1189f8344c8ffb5548d2cb | scripts/data/genia/genia_xml_to_inline_sutd.py | python | Span.__init__ | (self, start, end) | Span object represents any span with start and end indices | Span object represents any span with start and end indices | [
"Span",
"object",
"represents",
"any",
"span",
"with",
"start",
"and",
"end",
"indices"
] | def __init__(self, start, end):
'''Span object represents any span with start and end indices'''
self.start = start
self.end = end | [
"def",
"__init__",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"self",
".",
"start",
"=",
"start",
"self",
".",
"end",
"=",
"end"
] | https://github.com/dwadden/dygiepp/blob/8faac5711489d4f5fb1189f8344c8ffb5548d2cb/scripts/data/genia/genia_xml_to_inline_sutd.py#L54-L57 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/python-chess-0.1.0/chess/__init__.py | python | Bitboard.set_fen | (self, fen) | Parses a FEN and sets the position from it.
:raises ValueError: If the FEN string is invalid. | Parses a FEN and sets the position from it. | [
"Parses",
"a",
"FEN",
"and",
"sets",
"the",
"position",
"from",
"it",
"."
] | def set_fen(self, fen):
"""
Parses a FEN and sets the position from it.
:raises ValueError: If the FEN string is invalid.
"""
# Ensure there are six parts.
parts = fen.split()
if len(parts) != 6:
raise ValueError("A FEN string should consist of 6 parts.")
# Ensure the board part is valid.
rows = parts[0].split("/")
if len(rows) != 8:
raise ValueError("Expected 8 rows in position part of FEN.")
# Validate each row.
for row in rows:
field_sum = 0
previous_was_digit = False
for c in row:
if c in ["1", "2", "3", "4", "5", "6", "7", "8"]:
if previous_was_digit:
raise ValueError("Two subsequent digits in position part of FEN.")
field_sum += int(c)
previous_was_digit = True
elif c.lower() in ["p", "n", "b", "r", "q", "k"]:
field_sum += 1
previous_was_digit = False
else:
raise ValueError("Invalid character in position part of FEN.")
if field_sum != 8:
raise ValueError("Expected 8 columns per row in position part of FEN.")
# Check that the turn part is valid.
if not parts[1] in ["w", "b"]:
raise ValueError("Expected w or b for turn part of FEN.")
# Check that the castling part is valid.
# if not FEN_CASTLING_REGEX.match(parts[2]):
# raise ValueError("Invalid castling part in FEN.")
# Check that the en-passant part is valid.
if parts[3] != "-":
if parts[1] == "w":
if rank_index(SQUARE_NAMES.index(parts[3])) != 5:
raise ValueError("Expected en-passant square to be on sixth rank.")
else:
if rank_index(SQUARE_NAMES.index(parts[3])) != 2:
raise ValueError("Expected en-passant square to be on third rank.")
# Check that the half move part is valid.
if int(parts[4]) < 0:
raise ValueError("Half moves can not be negative.")
# Check that the ply part is valid.
if int(parts[5]) <= 0:
raise ValueError("Ply must be positive.")
# Clear board.
self.pawns = BB_VOID
self.knights = BB_VOID
self.bishops = BB_VOID
self.rooks = BB_VOID
self.queens = BB_VOID
self.kings = BB_VOID
self.occupied_co = [ BB_VOID, BB_VOID ]
self.occupied = BB_VOID
self.occupied_l90 = BB_VOID
self.occupied_r45 = BB_VOID
self.occupied_l45 = BB_VOID
self.king_squares = [ E1, E8 ]
self.half_move_stack = [] #collections.deque()
self.captured_piece_stack = [] #collections.deque()
self.castling_right_stack = [] #collections.deque()
self.ep_square_stack = [] #collections.deque()
self.move_stack = [] #collections.deque()
# Put pieces on the board.
square_index = 0
for c in parts[0]:
if c in ["1", "2", "3", "4", "5", "6", "7", "8"]:
square_index += int(c)
elif c.lower() in ["p", "n", "b", "r", "q", "k"]:
self.set_piece_at(SQUARES_180[square_index], Piece.from_symbol(c))
square_index += 1
# Set the turn.
if parts[1] == "w":
self.turn = WHITE
else:
self.turn = BLACK
# Set castling flags.
self.castling_rights = CASTLING_NONE
if "K" in parts[2]:
self.castling_rights |= CASTLING_WHITE_KINGSIDE
if "Q" in parts[2]:
self.castling_rights |= CASTLING_WHITE_QUEENSIDE
if "k" in parts[2]:
self.castling_rights |= CASTLING_BLACK_KINGSIDE
if "q" in parts[2]:
self.castling_rights |= CASTLING_BLACK_QUEENSIDE
# Set the en-passant square.
if parts[3] == "-":
self.ep_square = 0
else:
self.ep_square = SQUARE_NAMES.index(parts[3])
# Set the mover counters.
self.half_moves = int(parts[4])
self.ply = int(parts[5]) | [
"def",
"set_fen",
"(",
"self",
",",
"fen",
")",
":",
"# Ensure there are six parts.",
"parts",
"=",
"fen",
".",
"split",
"(",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"6",
":",
"raise",
"ValueError",
"(",
"\"A FEN string should consist of 6 parts.\"",
")",
... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/python-chess-0.1.0/chess/__init__.py#L1903-L2017 | ||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/importlib/metadata/_meta.py | python | SimplePath.parent | (self) | [] | def parent(self) -> 'SimplePath':
... | [
"def",
"parent",
"(",
"self",
")",
"->",
"'SimplePath'",
":",
"..."
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/importlib/metadata/_meta.py#L43-L44 | ||||
veusz/veusz | 5a1e2af5f24df0eb2a2842be51f2997c4999c7fb | veusz/dataimport/defn_hdf5.py | python | OperationDataImportHDF5.textDataToDataset | (self, name, dread) | return ds | Convert textual data to a veusz dataset. | Convert textual data to a veusz dataset. | [
"Convert",
"textual",
"data",
"to",
"a",
"veusz",
"dataset",
"."
] | def textDataToDataset(self, name, dread):
"""Convert textual data to a veusz dataset."""
data = dread.data
if ( (self.params.convert_datetime and
dread.origname in self.params.convert_datetime) or
"vsz_convert_datetime" in dread.options ):
try:
fmt = self.params.convert_datetime[dread.origname]
except (TypeError, KeyError):
fmt = dread.options["vsz_convert_datetime"]
if fmt.strip() == 'iso':
fmt = 'YYYY-MM-DD|T|hh:mm:ss'
try:
datere = re.compile(utils.dateStrToRegularExpression(fmt))
except Exception:
raise base.ImportingError(
_("Could not interpret date-time syntax '%s'") % fmt)
dout = N.empty(len(data), dtype=N.float64)
for i, ditem in enumerate(data):
ditem = bconv(ditem)
try:
match = datere.match(ditem)
val = utils.dateREMatchToDate(match)
except ValueError:
val = N.nan
dout[i] = val
ds = datasets.DatasetDateTime(dout)
else:
# unfortunately byte strings are returned in py3
tdata = [bconv(d) for d in dread.data]
# standard text dataset
ds = datasets.DatasetText(tdata)
return ds | [
"def",
"textDataToDataset",
"(",
"self",
",",
"name",
",",
"dread",
")",
":",
"data",
"=",
"dread",
".",
"data",
"if",
"(",
"(",
"self",
".",
"params",
".",
"convert_datetime",
"and",
"dread",
".",
"origname",
"in",
"self",
".",
"params",
".",
"convert... | https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/dataimport/defn_hdf5.py#L333-L375 | |
PaddlePaddle/Research | 2da0bd6c72d60e9df403aff23a7802779561c4a1 | NLP/ACL2019-DuConv/generative_paddle/tools/eval.py | python | calc_bleu | (pair_list) | return [bleu1, bleu2] | calc_bleu | calc_bleu | [
"calc_bleu"
] | def calc_bleu(pair_list):
"""
calc_bleu
"""
bp = calc_bp(pair_list)
cover_rate1 = calc_cover_rate(pair_list, 1)
cover_rate2 = calc_cover_rate(pair_list, 2)
cover_rate3 = calc_cover_rate(pair_list, 3)
bleu1 = 0
bleu2 = 0
bleu3 = 0
if cover_rate1 > 0:
bleu1 = bp * math.exp(math.log(cover_rate1))
if cover_rate2 > 0:
bleu2 = bp * math.exp((math.log(cover_rate1) + math.log(cover_rate2)) / 2)
if cover_rate3 > 0:
bleu3 = bp * math.exp((math.log(cover_rate1) + math.log(cover_rate2) + math.log(cover_rate3)) / 3)
return [bleu1, bleu2] | [
"def",
"calc_bleu",
"(",
"pair_list",
")",
":",
"bp",
"=",
"calc_bp",
"(",
"pair_list",
")",
"cover_rate1",
"=",
"calc_cover_rate",
"(",
"pair_list",
",",
"1",
")",
"cover_rate2",
"=",
"calc_cover_rate",
"(",
"pair_list",
",",
"2",
")",
"cover_rate3",
"=",
... | https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/NLP/ACL2019-DuConv/generative_paddle/tools/eval.py#L90-L107 | |
wonderworks-software/PyFlow | 57e2c858933bf63890d769d985396dfad0fca0f0 | PyFlow/UI/Widgets/QtSliders.py | python | uiTick.__init__ | (self, raw_tick, parent=None) | :param raw_tick: Input Core Tick
:type raw_tick: :obj:`PyFlow.Core.structs.Tick`
:param parent: Parent QWidget
:type parent: QtWidgets.QWidget, optional | :param raw_tick: Input Core Tick
:type raw_tick: :obj:`PyFlow.Core.structs.Tick`
:param parent: Parent QWidget
:type parent: QtWidgets.QWidget, optional | [
":",
"param",
"raw_tick",
":",
"Input",
"Core",
"Tick",
":",
"type",
"raw_tick",
":",
":",
"obj",
":",
"PyFlow",
".",
"Core",
".",
"structs",
".",
"Tick",
":",
"param",
"parent",
":",
"Parent",
"QWidget",
":",
"type",
"parent",
":",
"QtWidgets",
".",
... | def __init__(self, raw_tick, parent=None):
"""
:param raw_tick: Input Core Tick
:type raw_tick: :obj:`PyFlow.Core.structs.Tick`
:param parent: Parent QWidget
:type parent: QtWidgets.QWidget, optional
"""
super(uiTick, self).__init__(parent)
self.setAcceptHoverEvents(True)
self._width = 6
self._height = 6
self.hovered = False
self.setFlag(QtWidgets.QGraphicsWidget.ItemIsMovable)
self.setFlag(QtWidgets.QGraphicsWidget.ItemIsFocusable)
self.setFlag(QtWidgets.QGraphicsWidget.ItemIsSelectable, True)
self.setFlag(QtWidgets.QGraphicsWidget.ItemSendsGeometryChanges)
self._rawTick = raw_tick
self._color = QtGui.QColor(0) | [
"def",
"__init__",
"(",
"self",
",",
"raw_tick",
",",
"parent",
"=",
"None",
")",
":",
"super",
"(",
"uiTick",
",",
"self",
")",
".",
"__init__",
"(",
"parent",
")",
"self",
".",
"setAcceptHoverEvents",
"(",
"True",
")",
"self",
".",
"_width",
"=",
"... | https://github.com/wonderworks-software/PyFlow/blob/57e2c858933bf63890d769d985396dfad0fca0f0/PyFlow/UI/Widgets/QtSliders.py#L1037-L1054 | ||
openai/mujoco-worldgen | 39f52b1b47aed499925a6a214b58bdbdb4e2f75e | mujoco_worldgen/env.py | python | Env.__init__ | (self,
get_sim,
get_obs=flatten_get_obs,
get_reward=zero_get_reward,
get_info=empty_get_info,
get_diverged=false_get_diverged,
set_action=ctrl_set_action,
action_space=None,
horizon=100,
start_seed=None,
deterministic_mode=False) | Env is a Gym environment subclass tuned for robotics learning
research.
Args:
- get_sim (callable): a callable that returns an MjSim.
- get_obs (callable): callable with an MjSim object as the sole
argument and should return observations.
- set_action (callable): callable which takes an MjSim object and
updates its data and buffer directly.
- get_reward (callable): callable which takes an MjSim object and
returns a scalar reward.
- get_info (callable): callable which takes an MjSim object and
returns info (dictionary).
- get_diverged (callable): callable which takes an MjSim object
and returns a (bool, float) tuple. First value is True if
simulator diverged and second value is the reward at divergence.
- action_space: a space of allowed actions or a two-tuple of a ranges
if number of actions is unknown until the simulation is instantiated
- horizon (int): horizon of environment (i.e. max number of steps).
- start_seed (int or string): seed for random state generator (None for random seed).
Strings will be hashed. A non-None value implies deterministic_mode=True.
This argument allows us to run a deterministic series of goals/randomizations
for a given policy. Then applying the same seed to another policy will allow the
comparison of results more accurately. The reason a string is allowed is so
that we can more easily find and share seeds that are farther from 0,
which is the default starting point for deterministic_mode, and thus have
more likelihood of getting a performant sequence of goals. | Env is a Gym environment subclass tuned for robotics learning
research. | [
"Env",
"is",
"a",
"Gym",
"environment",
"subclass",
"tuned",
"for",
"robotics",
"learning",
"research",
"."
] | def __init__(self,
get_sim,
get_obs=flatten_get_obs,
get_reward=zero_get_reward,
get_info=empty_get_info,
get_diverged=false_get_diverged,
set_action=ctrl_set_action,
action_space=None,
horizon=100,
start_seed=None,
deterministic_mode=False):
"""
Env is a Gym environment subclass tuned for robotics learning
research.
Args:
- get_sim (callable): a callable that returns an MjSim.
- get_obs (callable): callable with an MjSim object as the sole
argument and should return observations.
- set_action (callable): callable which takes an MjSim object and
updates its data and buffer directly.
- get_reward (callable): callable which takes an MjSim object and
returns a scalar reward.
- get_info (callable): callable which takes an MjSim object and
returns info (dictionary).
- get_diverged (callable): callable which takes an MjSim object
and returns a (bool, float) tuple. First value is True if
simulator diverged and second value is the reward at divergence.
- action_space: a space of allowed actions or a two-tuple of a ranges
if number of actions is unknown until the simulation is instantiated
- horizon (int): horizon of environment (i.e. max number of steps).
- start_seed (int or string): seed for random state generator (None for random seed).
Strings will be hashed. A non-None value implies deterministic_mode=True.
This argument allows us to run a deterministic series of goals/randomizations
for a given policy. Then applying the same seed to another policy will allow the
comparison of results more accurately. The reason a string is allowed is so
that we can more easily find and share seeds that are farther from 0,
which is the default starting point for deterministic_mode, and thus have
more likelihood of getting a performant sequence of goals.
"""
if (horizon is not None) and not isinstance(horizon, int):
raise TypeError('horizon must be an int')
self.get_sim = enforce_is_callable(get_sim, (
'get_sim should be callable and should return an MjSim object'))
self.get_obs = enforce_is_callable(get_obs, (
'get_obs should be callable with an MjSim object as the sole '
'argument and should return observations'))
self.set_action = enforce_is_callable(set_action, (
'set_action should be a callable which takes an MjSim object and '
'updates its data and buffer directly'))
self.get_reward = enforce_is_callable(get_reward, (
'get_reward should be a callable which takes an MjSim object and '
'returns a scalar reward'))
self.get_info = enforce_is_callable(get_info, (
'get_info should be a callable which takes an MjSim object and '
'returns a dictionary'))
self.get_diverged = enforce_is_callable(get_diverged, (
'get_diverged should be a callable which takes an MjSim object '
'and returns a (bool, float) tuple. First value is whether '
'simulator is diverged (or done) and second value is the reward at '
'that time.'))
self.sim = None
self.horizon = horizon
self.t = None
self.deterministic_mode = deterministic_mode
# Numpy Random State
if isinstance(start_seed, str):
start_seed = int(hashlib.sha1(start_seed.encode()).hexdigest(), 16) % (2**32)
self.deterministic_mode = True
elif isinstance(start_seed, int):
self.deterministic_mode = True
else:
start_seed = 0 if self.deterministic_mode else np.random.randint(2**32)
self._random_state = np.random.RandomState(start_seed)
# Seed that will be used on next _reset()
self._next_seed = start_seed
# Seed that was used in last _reset()
self._current_seed = None
# For rendering
self.viewer = None
# These are required by Gym
self._action_space = action_space
self._observation_space = None
self._spec = Spec(max_episode_steps=horizon, timestep_limit=horizon)
self._name = None | [
"def",
"__init__",
"(",
"self",
",",
"get_sim",
",",
"get_obs",
"=",
"flatten_get_obs",
",",
"get_reward",
"=",
"zero_get_reward",
",",
"get_info",
"=",
"empty_get_info",
",",
"get_diverged",
"=",
"false_get_diverged",
",",
"set_action",
"=",
"ctrl_set_action",
",... | https://github.com/openai/mujoco-worldgen/blob/39f52b1b47aed499925a6a214b58bdbdb4e2f75e/mujoco_worldgen/env.py#L28-L117 | ||
dagster-io/dagster | b27d569d5fcf1072543533a0c763815d96f90b8f | python_modules/dagster/dagster/core/definitions/config.py | python | ConfigMapping.resolve_from_unvalidated_config | (self, config: Any) | return self.config_fn(outer_config) | Validates config against outer config schema, and calls mapping against validated config. | Validates config against outer config schema, and calls mapping against validated config. | [
"Validates",
"config",
"against",
"outer",
"config",
"schema",
"and",
"calls",
"mapping",
"against",
"validated",
"config",
"."
] | def resolve_from_unvalidated_config(self, config: Any) -> Any:
"""Validates config against outer config schema, and calls mapping against validated config."""
receive_processed_config_values = check.opt_bool_param(
self.receive_processed_config_values, "receive_processed_config_values", default=True
)
if receive_processed_config_values:
outer_evr = process_config(
self.config_schema.config_type,
config,
)
else:
outer_evr = validate_config(
self.config_schema.config_type,
config,
)
if not outer_evr.success:
raise DagsterInvalidConfigError(
"Error in config mapping ",
outer_evr.errors,
config,
)
outer_config = outer_evr.value
if not receive_processed_config_values:
outer_config = resolve_defaults(
cast(ConfigType, self.config_schema.config_type),
outer_config,
).value
return self.config_fn(outer_config) | [
"def",
"resolve_from_unvalidated_config",
"(",
"self",
",",
"config",
":",
"Any",
")",
"->",
"Any",
":",
"receive_processed_config_values",
"=",
"check",
".",
"opt_bool_param",
"(",
"self",
".",
"receive_processed_config_values",
",",
"\"receive_processed_config_values\""... | https://github.com/dagster-io/dagster/blob/b27d569d5fcf1072543533a0c763815d96f90b8f/python_modules/dagster/dagster/core/definitions/config.py#L67-L97 | |
DrSleep/tensorflow-deeplab-resnet | 066023c033624e6c8154340e06e8fbad4f702bdf | train.py | python | get_arguments | () | return parser.parse_args() | Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments. | Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments. | [
"Parse",
"all",
"the",
"arguments",
"provided",
"from",
"the",
"CLI",
".",
"Returns",
":",
"A",
"list",
"of",
"parsed",
"arguments",
"."
] | def get_arguments():
"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="DeepLab-ResNet Network")
parser.add_argument("--batch-size", type=int, default=BATCH_SIZE,
help="Number of images sent to the network in one step.")
parser.add_argument("--data-dir", type=str, default=DATA_DIRECTORY,
help="Path to the directory containing the PASCAL VOC dataset.")
parser.add_argument("--data-list", type=str, default=DATA_LIST_PATH,
help="Path to the file listing the images in the dataset.")
parser.add_argument("--ignore-label", type=int, default=IGNORE_LABEL,
help="The index of the label to ignore during the training.")
parser.add_argument("--input-size", type=str, default=INPUT_SIZE,
help="Comma-separated string with height and width of images.")
parser.add_argument("--is-training", action="store_true",
help="Whether to updates the running means and variances during the training.")
parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE,
help="Base learning rate for training with polynomial decay.")
parser.add_argument("--momentum", type=float, default=MOMENTUM,
help="Momentum component of the optimiser.")
parser.add_argument("--not-restore-last", action="store_true",
help="Whether to not restore last (FC) layers.")
parser.add_argument("--num-classes", type=int, default=NUM_CLASSES,
help="Number of classes to predict (including background).")
parser.add_argument("--num-steps", type=int, default=NUM_STEPS,
help="Number of training steps.")
parser.add_argument("--power", type=float, default=POWER,
help="Decay parameter to compute the learning rate.")
parser.add_argument("--random-mirror", action="store_true",
help="Whether to randomly mirror the inputs during the training.")
parser.add_argument("--random-scale", action="store_true",
help="Whether to randomly scale the inputs during the training.")
parser.add_argument("--random-seed", type=int, default=RANDOM_SEED,
help="Random seed to have reproducible results.")
parser.add_argument("--restore-from", type=str, default=RESTORE_FROM,
help="Where restore model parameters from.")
parser.add_argument("--save-num-images", type=int, default=SAVE_NUM_IMAGES,
help="How many images to save.")
parser.add_argument("--save-pred-every", type=int, default=SAVE_PRED_EVERY,
help="Save summaries and checkpoint every often.")
parser.add_argument("--snapshot-dir", type=str, default=SNAPSHOT_DIR,
help="Where to save snapshots of the model.")
parser.add_argument("--weight-decay", type=float, default=WEIGHT_DECAY,
help="Regularisation parameter for L2-loss.")
return parser.parse_args() | [
"def",
"get_arguments",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"DeepLab-ResNet Network\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--batch-size\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"BATCH_SIZE... | https://github.com/DrSleep/tensorflow-deeplab-resnet/blob/066023c033624e6c8154340e06e8fbad4f702bdf/train.py#L41-L88 | |
oracle/oci-python-sdk | 3c1604e4e212008fb6718e2f68cdb5ef71fd5793 | src/oci/artifacts/artifacts_client.py | python | ArtifactsClient.remove_container_version | (self, image_id, remove_container_version_details, **kwargs) | Remove version from container image.
:param str image_id: (required)
The `OCID`__ of the container image.
Example: `ocid1.containerimage.oc1..exampleuniqueID`
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param oci.artifacts.models.RemoveContainerVersionDetails remove_container_version_details: (required)
Remove version details.
:param str if_match: (optional)
For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match`
parameter to the value of the etag from a previous GET or POST response for that resource. The resource
will be updated or deleted only if the etag you provide matches the resource's current etag value.
:param str opc_request_id: (optional)
Unique identifier for the request.
If you need to contact Oracle about a particular request, please provide the request ID.
:param str opc_retry_token: (optional)
A token that uniquely identifies a request so it can be retried in case of a timeout or
server error without risk of executing that same action again. Retry tokens expire after 24
hours, but can be invalidated before then due to conflicting operations (for example, if a resource
has been deleted and purged from the system, then a retry of the original creation request
may be rejected).
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:return: A :class:`~oci.response.Response` object with data of type :class:`~oci.artifacts.models.ContainerImage`
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/artifacts/remove_container_version.py.html>`__ to see an example of how to use remove_container_version API. | Remove version from container image. | [
"Remove",
"version",
"from",
"container",
"image",
"."
] | def remove_container_version(self, image_id, remove_container_version_details, **kwargs):
"""
Remove version from container image.
:param str image_id: (required)
The `OCID`__ of the container image.
Example: `ocid1.containerimage.oc1..exampleuniqueID`
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param oci.artifacts.models.RemoveContainerVersionDetails remove_container_version_details: (required)
Remove version details.
:param str if_match: (optional)
For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match`
parameter to the value of the etag from a previous GET or POST response for that resource. The resource
will be updated or deleted only if the etag you provide matches the resource's current etag value.
:param str opc_request_id: (optional)
Unique identifier for the request.
If you need to contact Oracle about a particular request, please provide the request ID.
:param str opc_retry_token: (optional)
A token that uniquely identifies a request so it can be retried in case of a timeout or
server error without risk of executing that same action again. Retry tokens expire after 24
hours, but can be invalidated before then due to conflicting operations (for example, if a resource
has been deleted and purged from the system, then a retry of the original creation request
may be rejected).
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:return: A :class:`~oci.response.Response` object with data of type :class:`~oci.artifacts.models.ContainerImage`
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/artifacts/remove_container_version.py.html>`__ to see an example of how to use remove_container_version API.
"""
resource_path = "/container/images/{imageId}/actions/removeVersion"
method = "POST"
# Don't accept unknown kwargs
expected_kwargs = [
"retry_strategy",
"if_match",
"opc_request_id",
"opc_retry_token"
]
extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"remove_container_version got unknown kwargs: {!r}".format(extra_kwargs))
path_params = {
"imageId": image_id
}
path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing}
for (k, v) in six.iteritems(path_params):
if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0):
raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k))
header_params = {
"accept": "application/json",
"content-type": "application/json",
"if-match": kwargs.get("if_match", missing),
"opc-request-id": kwargs.get("opc_request_id", missing),
"opc-retry-token": kwargs.get("opc_retry_token", missing)
}
header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None}
retry_strategy = self.base_client.get_preferred_retry_strategy(
operation_retry_strategy=kwargs.get('retry_strategy'),
client_retry_strategy=self.retry_strategy
)
if retry_strategy:
if not isinstance(retry_strategy, retry.NoneRetryStrategy):
self.base_client.add_opc_retry_token_if_needed(header_params)
self.base_client.add_opc_client_retries_header(header_params)
retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback)
return retry_strategy.make_retrying_call(
self.base_client.call_api,
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params,
body=remove_container_version_details,
response_type="ContainerImage")
else:
return self.base_client.call_api(
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params,
body=remove_container_version_details,
response_type="ContainerImage") | [
"def",
"remove_container_version",
"(",
"self",
",",
"image_id",
",",
"remove_container_version_details",
",",
"*",
"*",
"kwargs",
")",
":",
"resource_path",
"=",
"\"/container/images/{imageId}/actions/removeVersion\"",
"method",
"=",
"\"POST\"",
"# Don't accept unknown kwarg... | https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/artifacts/artifacts_client.py#L2574-L2678 | ||
etianen/django-watson | 077c336dd430a0eb397efecb2bf57867149a8d78 | watson/backends.py | python | PostgresSearchBackend.do_install | (self) | Executes the PostgreSQL specific SQL code to install django-watson. | Executes the PostgreSQL specific SQL code to install django-watson. | [
"Executes",
"the",
"PostgreSQL",
"specific",
"SQL",
"code",
"to",
"install",
"django",
"-",
"watson",
"."
] | def do_install(self):
"""Executes the PostgreSQL specific SQL code to install django-watson."""
connection = connections[router.db_for_write(SearchEntry)]
connection.cursor().execute("""
-- Ensure that plpgsql is installed.
CREATE OR REPLACE FUNCTION make_plpgsql() RETURNS VOID LANGUAGE SQL AS
$$
CREATE LANGUAGE plpgsql;
$$;
SELECT
CASE
WHEN EXISTS(
SELECT 1
FROM pg_catalog.pg_language
WHERE lanname='plpgsql'
)
THEN NULL
ELSE make_plpgsql() END;
DROP FUNCTION make_plpgsql();
-- Create the search index.
ALTER TABLE watson_searchentry ADD COLUMN search_tsv tsvector NOT NULL;
CREATE INDEX watson_searchentry_search_tsv ON watson_searchentry USING gin(search_tsv);
-- Create the trigger function.
CREATE OR REPLACE FUNCTION watson_searchentry_trigger_handler() RETURNS trigger AS $$
begin
new.search_tsv :=
setweight(to_tsvector('{search_config}', coalesce(new.title, '')), 'A') ||
setweight(to_tsvector('{search_config}', coalesce(new.description, '')), 'C') ||
setweight(to_tsvector('{search_config}', coalesce(new.content, '')), 'D');
return new;
end
$$ LANGUAGE plpgsql;
CREATE TRIGGER watson_searchentry_trigger BEFORE INSERT OR UPDATE
ON watson_searchentry FOR EACH ROW EXECUTE PROCEDURE watson_searchentry_trigger_handler();
""".format(
search_config=self.search_config
)) | [
"def",
"do_install",
"(",
"self",
")",
":",
"connection",
"=",
"connections",
"[",
"router",
".",
"db_for_write",
"(",
"SearchEntry",
")",
"]",
"connection",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"\"\"\"\n -- Ensure that plpgsql is installed.\n ... | https://github.com/etianen/django-watson/blob/077c336dd430a0eb397efecb2bf57867149a8d78/watson/backends.py#L198-L237 | ||
c0rv4x/project-black | 2d3df00ba1b1453c99ec5a247793a74e11adba2a | black/workers/dirsearch/dirsearch_ext/thirdparty/requests/packages/urllib3/util/url.py | python | Url.request_uri | (self) | return uri | Absolute path including the query string. | Absolute path including the query string. | [
"Absolute",
"path",
"including",
"the",
"query",
"string",
"."
] | def request_uri(self):
"""Absolute path including the query string."""
uri = self.path or '/'
if self.query is not None:
uri += '?' + self.query
return uri | [
"def",
"request_uri",
"(",
"self",
")",
":",
"uri",
"=",
"self",
".",
"path",
"or",
"'/'",
"if",
"self",
".",
"query",
"is",
"not",
"None",
":",
"uri",
"+=",
"'?'",
"+",
"self",
".",
"query",
"return",
"uri"
] | https://github.com/c0rv4x/project-black/blob/2d3df00ba1b1453c99ec5a247793a74e11adba2a/black/workers/dirsearch/dirsearch_ext/thirdparty/requests/packages/urllib3/util/url.py#L29-L36 | |
hatRiot/zarp | 2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad | src/modules/sniffer/http_sniffer.py | python | http_sniffer.__init__ | (self) | [] | def __init__(self):
super(http_sniffer, self).__init__('HTTP Sniffer')
self.sessions = {}
self.config.update({"verb":Zoption(type = "int",
value = 1,
required = False,
display = "Output verbosity",
opts = ['Site Only', 'Request String',
'Request and Payload',
'Session IDs', 'Custom Regex'
]),
"regex":Zoption(type = "regex",
value = None,
required = False,
display = "Regex for level 5 verbosity"),
'port':Zoption(type = "int",
value = 80,
required = False,
display = "Port to sniff on")
})
self.info = """
The HTTP sniffer is a fairly robust sniffer module that
supports various methods of parsing up data, including:
[*] Site Only
This level will only parse out the website/host in
the packet's request.
[*] Request string
This will parse out and store the entire request string.
[*] Request and Payload
Included in this level from the last is the actual
payload of the request.
[*] Session ID
Still a work in progress, but this will attempt to
parse out MOST standard session ID variables. This
will store them in a pretty table that you can drag up
when viewing the module.
[*] Custom regex
This allows the user to insert a custom regex string,
in Python form, that will then parse and display
matches.""" | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"http_sniffer",
",",
"self",
")",
".",
"__init__",
"(",
"'HTTP Sniffer'",
")",
"self",
".",
"sessions",
"=",
"{",
"}",
"self",
".",
"config",
".",
"update",
"(",
"{",
"\"verb\"",
":",
"Zoption",
... | https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/modules/sniffer/http_sniffer.py#L11-L50 | ||||
tracim/tracim | a0e9746fde5a4c45b4e0f0bfa2caf9522b8c4e21 | backend/official_plugins/tracim_backend_child_removal/__init__.py | python | ChildRemovalPlugin.on_user_role_in_workspace_deleted | (
self, role: UserRoleInWorkspace, context: TracimContext
) | Remove the user from all child spaces | Remove the user from all child spaces | [
"Remove",
"the",
"user",
"from",
"all",
"child",
"spaces"
] | def on_user_role_in_workspace_deleted(
self, role: UserRoleInWorkspace, context: TracimContext
) -> None:
"""
Remove the user from all child spaces
"""
user = role.user
parent_workspace = role.workspace
rapi = RoleApi(session=context.dbsession, config=context.app_config, current_user=None)
for workspace in parent_workspace.recursive_children:
try:
rapi.delete_one(
user_id=user.user_id, workspace_id=workspace.workspace_id, flush=False,
)
except UserRoleNotFound:
pass | [
"def",
"on_user_role_in_workspace_deleted",
"(",
"self",
",",
"role",
":",
"UserRoleInWorkspace",
",",
"context",
":",
"TracimContext",
")",
"->",
"None",
":",
"user",
"=",
"role",
".",
"user",
"parent_workspace",
"=",
"role",
".",
"workspace",
"rapi",
"=",
"R... | https://github.com/tracim/tracim/blob/a0e9746fde5a4c45b4e0f0bfa2caf9522b8c4e21/backend/official_plugins/tracim_backend_child_removal/__init__.py#L19-L34 | ||
bethesirius/ChosunTruck | 889644385ce57f971ec2921f006fbb0a167e6f1e | linux/tensorbox/pymouse/windows.py | python | PyMouseEvent.run | (self) | [] | def run(self):
self.hm.MouseAll = self._action
self.hm.HookMouse()
while self.state:
sleep(0.01)
pythoncom.PumpWaitingMessages() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"hm",
".",
"MouseAll",
"=",
"self",
".",
"_action",
"self",
".",
"hm",
".",
"HookMouse",
"(",
")",
"while",
"self",
".",
"state",
":",
"sleep",
"(",
"0.01",
")",
"pythoncom",
".",
"PumpWaitingMessages... | https://github.com/bethesirius/ChosunTruck/blob/889644385ce57f971ec2921f006fbb0a167e6f1e/linux/tensorbox/pymouse/windows.py#L99-L104 | ||||
lazylibrarian/LazyLibrarian | ae3c14e9db9328ce81765e094ab2a14ed7155624 | lib/pythontwitter/__init__.py | python | DirectMessage.NewFromJsonDict | (data) | return DirectMessage(created_at=data.get('created_at', None),
recipient_id=data.get('recipient_id', None),
sender_id=data.get('sender_id', None),
text=data.get('text', None),
sender_screen_name=data.get('sender_screen_name', None),
id=data.get('id', None),
recipient_screen_name=data.get('recipient_screen_name', None)) | Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.DirectMessage instance | Create a new instance based on a JSON dict. | [
"Create",
"a",
"new",
"instance",
"based",
"on",
"a",
"JSON",
"dict",
"."
] | def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.DirectMessage instance
'''
return DirectMessage(created_at=data.get('created_at', None),
recipient_id=data.get('recipient_id', None),
sender_id=data.get('sender_id', None),
text=data.get('text', None),
sender_screen_name=data.get('sender_screen_name', None),
id=data.get('id', None),
recipient_screen_name=data.get('recipient_screen_name', None)) | [
"def",
"NewFromJsonDict",
"(",
"data",
")",
":",
"return",
"DirectMessage",
"(",
"created_at",
"=",
"data",
".",
"get",
"(",
"'created_at'",
",",
"None",
")",
",",
"recipient_id",
"=",
"data",
".",
"get",
"(",
"'recipient_id'",
",",
"None",
")",
",",
"se... | https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/lib/pythontwitter/__init__.py#L2158-L2174 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/opentherm_gw/climate.py | python | OpenThermClimate.preset_modes | (self) | return [] | Available preset modes to set. | Available preset modes to set. | [
"Available",
"preset",
"modes",
"to",
"set",
"."
] | def preset_modes(self):
"""Available preset modes to set."""
return [] | [
"def",
"preset_modes",
"(",
"self",
")",
":",
"return",
"[",
"]"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/opentherm_gw/climate.py#L268-L270 | |
ryankiros/skip-thoughts | 6661cad40664b6c251cac1dad779986eb332c26a | dataset_handler.py | python | shuffle_data | (X, L, seed=1234) | return (X, L) | Shuffle the data | Shuffle the data | [
"Shuffle",
"the",
"data"
] | def shuffle_data(X, L, seed=1234):
"""
Shuffle the data
"""
prng = RandomState(seed)
inds = np.arange(len(X))
prng.shuffle(inds)
X = [X[i] for i in inds]
L = L[inds]
return (X, L) | [
"def",
"shuffle_data",
"(",
"X",
",",
"L",
",",
"seed",
"=",
"1234",
")",
":",
"prng",
"=",
"RandomState",
"(",
"seed",
")",
"inds",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"X",
")",
")",
"prng",
".",
"shuffle",
"(",
"inds",
")",
"X",
"=",
... | https://github.com/ryankiros/skip-thoughts/blob/6661cad40664b6c251cac1dad779986eb332c26a/dataset_handler.py#L105-L114 | |
sqlalchemy/alembic | 85152025ddba1dbeb51b467f40eb36b795d2ca37 | alembic/script/revision.py | python | RevisionMap._collect_downgrade_revisions | (
self,
upper: _RevisionIdentifierType,
target: _RevisionIdentifierType,
inclusive: bool,
implicit_base: bool,
assert_relative_length: bool,
) | return downgrade_revisions, heads | Compute the set of current revisions specified by :upper, and the
downgrade target specified by :target. Return all dependents of target
which are currently active.
:inclusive=True includes the target revision in the set | Compute the set of current revisions specified by :upper, and the
downgrade target specified by :target. Return all dependents of target
which are currently active. | [
"Compute",
"the",
"set",
"of",
"current",
"revisions",
"specified",
"by",
":",
"upper",
"and",
"the",
"downgrade",
"target",
"specified",
"by",
":",
"target",
".",
"Return",
"all",
"dependents",
"of",
"target",
"which",
"are",
"currently",
"active",
"."
] | def _collect_downgrade_revisions(
self,
upper: _RevisionIdentifierType,
target: _RevisionIdentifierType,
inclusive: bool,
implicit_base: bool,
assert_relative_length: bool,
) -> Any:
"""
Compute the set of current revisions specified by :upper, and the
downgrade target specified by :target. Return all dependents of target
which are currently active.
:inclusive=True includes the target revision in the set
"""
branch_label, target_revision = self._parse_downgrade_target(
current_revisions=upper,
target=target,
assert_relative_length=assert_relative_length,
)
if target_revision == "base":
target_revision = None
assert target_revision is None or isinstance(target_revision, Revision)
# Find candidates to drop.
if target_revision is None:
# Downgrading back to base: find all tree roots.
roots = [
rev
for rev in self._revision_map.values()
if rev is not None and rev.down_revision is None
]
elif inclusive:
# inclusive implies target revision should also be dropped
roots = [target_revision]
else:
# Downgrading to fixed target: find all direct children.
roots = list(self.get_revisions(target_revision.nextrev))
if branch_label and len(roots) > 1:
# Need to filter roots.
ancestors = {
rev.revision
for rev in self._get_ancestor_nodes(
[self._resolve_branch(branch_label)],
include_dependencies=False,
)
}
# Intersection gives the root revisions we are trying to
# rollback with the downgrade.
roots = list(
self.get_revisions(
{rev.revision for rev in roots}.intersection(ancestors)
)
)
# Ensure we didn't throw everything away when filtering branches.
if len(roots) == 0:
raise RevisionError(
"Not a valid downgrade target from current heads"
)
heads = self.get_revisions(upper)
# Aim is to drop :branch_revision; to do so we also need to drop its
# descendents and anything dependent on it.
downgrade_revisions = set(
self._get_descendant_nodes(
roots,
include_dependencies=True,
omit_immediate_dependencies=False,
)
)
active_revisions = set(
self._get_ancestor_nodes(heads, include_dependencies=True)
)
# Emit revisions to drop in reverse topological sorted order.
downgrade_revisions.intersection_update(active_revisions)
if implicit_base:
# Wind other branches back to base.
downgrade_revisions.update(
active_revisions.difference(self._get_ancestor_nodes(roots))
)
if (
target_revision is not None
and not downgrade_revisions
and target_revision not in heads
):
# Empty intersection: target revs are not present.
raise RangeNotAncestorError("Nothing to drop", upper)
return downgrade_revisions, heads | [
"def",
"_collect_downgrade_revisions",
"(",
"self",
",",
"upper",
":",
"_RevisionIdentifierType",
",",
"target",
":",
"_RevisionIdentifierType",
",",
"inclusive",
":",
"bool",
",",
"implicit_base",
":",
"bool",
",",
"assert_relative_length",
":",
"bool",
",",
")",
... | https://github.com/sqlalchemy/alembic/blob/85152025ddba1dbeb51b467f40eb36b795d2ca37/alembic/script/revision.py#L1272-L1368 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.