repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
10gen/mongo-orchestration | mongo_orchestration/server.py | get_app | def get_app():
"""return bottle app that includes all sub-apps"""
from bottle import default_app
default_app.push()
for module in ("mongo_orchestration.apps.servers",
"mongo_orchestration.apps.replica_sets",
"mongo_orchestration.apps.sharded_clusters"):
__im... | python | def get_app():
"""return bottle app that includes all sub-apps"""
from bottle import default_app
default_app.push()
for module in ("mongo_orchestration.apps.servers",
"mongo_orchestration.apps.replica_sets",
"mongo_orchestration.apps.sharded_clusters"):
__im... | [
"def",
"get_app",
"(",
")",
":",
"from",
"bottle",
"import",
"default_app",
"default_app",
".",
"push",
"(",
")",
"for",
"module",
"in",
"(",
"\"mongo_orchestration.apps.servers\"",
",",
"\"mongo_orchestration.apps.replica_sets\"",
",",
"\"mongo_orchestration.apps.sharded... | return bottle app that includes all sub-apps | [
"return",
"bottle",
"app",
"that",
"includes",
"all",
"sub",
"-",
"apps"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/server.py#L103-L112 | train |
10gen/mongo-orchestration | mongo_orchestration/server.py | await_connection | def await_connection(host, port):
"""Wait for the mongo-orchestration server to accept connections."""
for i in range(CONNECT_ATTEMPTS):
try:
conn = socket.create_connection((host, port), CONNECT_TIMEOUT)
conn.close()
return True
except (IOError, socket.error)... | python | def await_connection(host, port):
"""Wait for the mongo-orchestration server to accept connections."""
for i in range(CONNECT_ATTEMPTS):
try:
conn = socket.create_connection((host, port), CONNECT_TIMEOUT)
conn.close()
return True
except (IOError, socket.error)... | [
"def",
"await_connection",
"(",
"host",
",",
"port",
")",
":",
"for",
"i",
"in",
"range",
"(",
"CONNECT_ATTEMPTS",
")",
":",
"try",
":",
"conn",
"=",
"socket",
".",
"create_connection",
"(",
"(",
"host",
",",
"port",
")",
",",
"CONNECT_TIMEOUT",
")",
"... | Wait for the mongo-orchestration server to accept connections. | [
"Wait",
"for",
"the",
"mongo",
"-",
"orchestration",
"server",
"to",
"accept",
"connections",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/server.py#L144-L153 | train |
10gen/mongo-orchestration | mongo_orchestration/servers.py | Server.__init_config_params | def __init_config_params(self, config):
"""Conditionally enable options in the Server's config file."""
if self.version >= (2, 4):
params = config.get('setParameter', {})
# Set enableTestCommands by default but allow enableTestCommands:0.
params.setdefault('enableTest... | python | def __init_config_params(self, config):
"""Conditionally enable options in the Server's config file."""
if self.version >= (2, 4):
params = config.get('setParameter', {})
# Set enableTestCommands by default but allow enableTestCommands:0.
params.setdefault('enableTest... | [
"def",
"__init_config_params",
"(",
"self",
",",
"config",
")",
":",
"if",
"self",
".",
"version",
">=",
"(",
"2",
",",
"4",
")",
":",
"params",
"=",
"config",
".",
"get",
"(",
"'setParameter'",
",",
"{",
"}",
")",
"params",
".",
"setdefault",
"(",
... | Conditionally enable options in the Server's config file. | [
"Conditionally",
"enable",
"options",
"in",
"the",
"Server",
"s",
"config",
"file",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/servers.py#L73-L97 | train |
10gen/mongo-orchestration | mongo_orchestration/servers.py | Server.connection | def connection(self):
"""return authenticated connection"""
c = pymongo.MongoClient(
self.hostname, fsync=True,
socketTimeoutMS=self.socket_timeout, **self.kwargs)
connected(c)
if not self.is_mongos and self.login and not self.restart_required:
db = c[... | python | def connection(self):
"""return authenticated connection"""
c = pymongo.MongoClient(
self.hostname, fsync=True,
socketTimeoutMS=self.socket_timeout, **self.kwargs)
connected(c)
if not self.is_mongos and self.login and not self.restart_required:
db = c[... | [
"def",
"connection",
"(",
"self",
")",
":",
"c",
"=",
"pymongo",
".",
"MongoClient",
"(",
"self",
".",
"hostname",
",",
"fsync",
"=",
"True",
",",
"socketTimeoutMS",
"=",
"self",
".",
"socket_timeout",
",",
"**",
"self",
".",
"kwargs",
")",
"connected",
... | return authenticated connection | [
"return",
"authenticated",
"connection"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/servers.py#L201-L220 | train |
10gen/mongo-orchestration | mongo_orchestration/servers.py | Server.version | def version(self):
"""Get the version of MongoDB that this Server runs as a tuple."""
if not self.__version:
command = (self.name, '--version')
logger.debug(command)
stdout, _ = subprocess.Popen(
command, stdout=subprocess.PIPE).communicate()
... | python | def version(self):
"""Get the version of MongoDB that this Server runs as a tuple."""
if not self.__version:
command = (self.name, '--version')
logger.debug(command)
stdout, _ = subprocess.Popen(
command, stdout=subprocess.PIPE).communicate()
... | [
"def",
"version",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__version",
":",
"command",
"=",
"(",
"self",
".",
"name",
",",
"'--version'",
")",
"logger",
".",
"debug",
"(",
"command",
")",
"stdout",
",",
"_",
"=",
"subprocess",
".",
"Popen",
... | Get the version of MongoDB that this Server runs as a tuple. | [
"Get",
"the",
"version",
"of",
"MongoDB",
"that",
"this",
"Server",
"runs",
"as",
"a",
"tuple",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/servers.py#L223-L238 | train |
10gen/mongo-orchestration | mongo_orchestration/servers.py | Server.run_command | def run_command(self, command, arg=None, is_eval=False):
"""run command on the server
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
return command's result
"""
mode = is_eval and 'eval' or 'co... | python | def run_command(self, command, arg=None, is_eval=False):
"""run command on the server
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
return command's result
"""
mode = is_eval and 'eval' or 'co... | [
"def",
"run_command",
"(",
"self",
",",
"command",
",",
"arg",
"=",
"None",
",",
"is_eval",
"=",
"False",
")",
":",
"mode",
"=",
"is_eval",
"and",
"'eval'",
"or",
"'command'",
"if",
"isinstance",
"(",
"arg",
",",
"tuple",
")",
":",
"name",
",",
"d",
... | run command on the server
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
return command's result | [
"run",
"command",
"on",
"the",
"server"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/servers.py#L259-L277 | train |
10gen/mongo-orchestration | mongo_orchestration/servers.py | Server.info | def info(self):
"""return info about server as dict object"""
proc_info = {"name": self.name,
"params": self.cfg,
"alive": self.is_alive,
"optfile": self.config_path}
if self.is_alive:
proc_info['pid'] = self.proc.pid
... | python | def info(self):
"""return info about server as dict object"""
proc_info = {"name": self.name,
"params": self.cfg,
"alive": self.is_alive,
"optfile": self.config_path}
if self.is_alive:
proc_info['pid'] = self.proc.pid
... | [
"def",
"info",
"(",
"self",
")",
":",
"proc_info",
"=",
"{",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"params\"",
":",
"self",
".",
"cfg",
",",
"\"alive\"",
":",
"self",
".",
"is_alive",
",",
"\"optfile\"",
":",
"self",
".",
"config_path",
"}",
"... | return info about server as dict object | [
"return",
"info",
"about",
"server",
"as",
"dict",
"object"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/servers.py#L283-L313 | train |
10gen/mongo-orchestration | mongo_orchestration/servers.py | Server.start | def start(self, timeout=300):
"""start server
return True of False"""
if self.is_alive:
return True
try:
dbpath = self.cfg.get('dbpath')
if dbpath and self._is_locked:
# repair if needed
logger.info("Performing repair on... | python | def start(self, timeout=300):
"""start server
return True of False"""
if self.is_alive:
return True
try:
dbpath = self.cfg.get('dbpath')
if dbpath and self._is_locked:
# repair if needed
logger.info("Performing repair on... | [
"def",
"start",
"(",
"self",
",",
"timeout",
"=",
"300",
")",
":",
"if",
"self",
".",
"is_alive",
":",
"return",
"True",
"try",
":",
"dbpath",
"=",
"self",
".",
"cfg",
".",
"get",
"(",
"'dbpath'",
")",
"if",
"dbpath",
"and",
"self",
".",
"_is_locke... | start server
return True of False | [
"start",
"server",
"return",
"True",
"of",
"False"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/servers.py#L330-L397 | train |
10gen/mongo-orchestration | mongo_orchestration/servers.py | Server.shutdown | def shutdown(self):
"""Send shutdown command and wait for the process to exit."""
# Return early if this server has already exited.
if not process.proc_alive(self.proc):
return
logger.info("Attempting to connect to %s", self.hostname)
client = self.connection
... | python | def shutdown(self):
"""Send shutdown command and wait for the process to exit."""
# Return early if this server has already exited.
if not process.proc_alive(self.proc):
return
logger.info("Attempting to connect to %s", self.hostname)
client = self.connection
... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"not",
"process",
".",
"proc_alive",
"(",
"self",
".",
"proc",
")",
":",
"return",
"logger",
".",
"info",
"(",
"\"Attempting to connect to %s\"",
",",
"self",
".",
"hostname",
")",
"client",
"=",
"self",
".... | Send shutdown command and wait for the process to exit. | [
"Send",
"shutdown",
"command",
"and",
"wait",
"for",
"the",
"process",
"to",
"exit",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/servers.py#L399-L426 | train |
10gen/mongo-orchestration | mongo_orchestration/container.py | Container.bin_path | def bin_path(self, release=None):
"""Get the bin path for a particular release."""
if release:
for r in self.releases:
if release in r:
return self.releases[r]
raise MongoOrchestrationError("No such release '%s' in %r"
... | python | def bin_path(self, release=None):
"""Get the bin path for a particular release."""
if release:
for r in self.releases:
if release in r:
return self.releases[r]
raise MongoOrchestrationError("No such release '%s' in %r"
... | [
"def",
"bin_path",
"(",
"self",
",",
"release",
"=",
"None",
")",
":",
"if",
"release",
":",
"for",
"r",
"in",
"self",
".",
"releases",
":",
"if",
"release",
"in",
"r",
":",
"return",
"self",
".",
"releases",
"[",
"r",
"]",
"raise",
"MongoOrchestrati... | Get the bin path for a particular release. | [
"Get",
"the",
"bin",
"path",
"for",
"a",
"particular",
"release",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/container.py#L39-L51 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster.__init_configrs | def __init_configrs(self, rs_cfg):
"""Create and start a config replica set."""
# Use 'rs_id' to set the id for consistency, but need to rename
# to 'id' to use with ReplicaSets.create()
rs_cfg['id'] = rs_cfg.pop('rs_id', None)
for member in rs_cfg.setdefault('members', [{}]):
... | python | def __init_configrs(self, rs_cfg):
"""Create and start a config replica set."""
# Use 'rs_id' to set the id for consistency, but need to rename
# to 'id' to use with ReplicaSets.create()
rs_cfg['id'] = rs_cfg.pop('rs_id', None)
for member in rs_cfg.setdefault('members', [{}]):
... | [
"def",
"__init_configrs",
"(",
"self",
",",
"rs_cfg",
")",
":",
"rs_cfg",
"[",
"'id'",
"]",
"=",
"rs_cfg",
".",
"pop",
"(",
"'rs_id'",
",",
"None",
")",
"for",
"member",
"in",
"rs_cfg",
".",
"setdefault",
"(",
"'members'",
",",
"[",
"{",
"}",
"]",
... | Create and start a config replica set. | [
"Create",
"and",
"start",
"a",
"config",
"replica",
"set",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L214-L226 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster.__init_configsvrs | def __init_configsvrs(self, params):
"""create and start config servers"""
self._configsvrs = []
for cfg in params:
# Remove flags that turn on auth.
cfg = self._strip_auth(cfg)
server_id = cfg.pop('server_id', None)
version = cfg.pop('version', se... | python | def __init_configsvrs(self, params):
"""create and start config servers"""
self._configsvrs = []
for cfg in params:
# Remove flags that turn on auth.
cfg = self._strip_auth(cfg)
server_id = cfg.pop('server_id', None)
version = cfg.pop('version', se... | [
"def",
"__init_configsvrs",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"_configsvrs",
"=",
"[",
"]",
"for",
"cfg",
"in",
"params",
":",
"cfg",
"=",
"self",
".",
"_strip_auth",
"(",
"cfg",
")",
"server_id",
"=",
"cfg",
".",
"pop",
"(",
"'serve... | create and start config servers | [
"create",
"and",
"start",
"config",
"servers"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L228-L241 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster.configsvrs | def configsvrs(self):
"""return list of config servers"""
if self.uses_rs_configdb:
rs_id = self._configsvrs[0]
mongodb_uri = ReplicaSets().info(rs_id)['mongodb_uri']
return [{'id': rs_id, 'mongodb_uri': mongodb_uri}]
return [{'id': h_id, 'hostname': Servers()... | python | def configsvrs(self):
"""return list of config servers"""
if self.uses_rs_configdb:
rs_id = self._configsvrs[0]
mongodb_uri = ReplicaSets().info(rs_id)['mongodb_uri']
return [{'id': rs_id, 'mongodb_uri': mongodb_uri}]
return [{'id': h_id, 'hostname': Servers()... | [
"def",
"configsvrs",
"(",
"self",
")",
":",
"if",
"self",
".",
"uses_rs_configdb",
":",
"rs_id",
"=",
"self",
".",
"_configsvrs",
"[",
"0",
"]",
"mongodb_uri",
"=",
"ReplicaSets",
"(",
")",
".",
"info",
"(",
"rs_id",
")",
"[",
"'mongodb_uri'",
"]",
"re... | return list of config servers | [
"return",
"list",
"of",
"config",
"servers"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L247-L254 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster.router | def router(self):
"""return first available router"""
for server in self._routers:
info = Servers().info(server)
if info['procInfo'].get('alive', False):
return {'id': server, 'hostname': Servers().hostname(server)} | python | def router(self):
"""return first available router"""
for server in self._routers:
info = Servers().info(server)
if info['procInfo'].get('alive', False):
return {'id': server, 'hostname': Servers().hostname(server)} | [
"def",
"router",
"(",
"self",
")",
":",
"for",
"server",
"in",
"self",
".",
"_routers",
":",
"info",
"=",
"Servers",
"(",
")",
".",
"info",
"(",
"server",
")",
"if",
"info",
"[",
"'procInfo'",
"]",
".",
"get",
"(",
"'alive'",
",",
"False",
")",
"... | return first available router | [
"return",
"first",
"available",
"router"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L268-L273 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster.router_connections | def router_connections(self):
"""Return a list of MongoClients, one for each mongos."""
clients = []
for server in self._routers:
if Servers().is_alive(server):
client = self.create_connection(Servers().hostname(server))
clients.append(client)
... | python | def router_connections(self):
"""Return a list of MongoClients, one for each mongos."""
clients = []
for server in self._routers:
if Servers().is_alive(server):
client = self.create_connection(Servers().hostname(server))
clients.append(client)
... | [
"def",
"router_connections",
"(",
"self",
")",
":",
"clients",
"=",
"[",
"]",
"for",
"server",
"in",
"self",
".",
"_routers",
":",
"if",
"Servers",
"(",
")",
".",
"is_alive",
"(",
"server",
")",
":",
"client",
"=",
"self",
".",
"create_connection",
"("... | Return a list of MongoClients, one for each mongos. | [
"Return",
"a",
"list",
"of",
"MongoClients",
"one",
"for",
"each",
"mongos",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L321-L328 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster._add | def _add(self, shard_uri, name):
"""execute addShard command"""
return self.router_command("addShard", (shard_uri, {"name": name}), is_eval=False) | python | def _add(self, shard_uri, name):
"""execute addShard command"""
return self.router_command("addShard", (shard_uri, {"name": name}), is_eval=False) | [
"def",
"_add",
"(",
"self",
",",
"shard_uri",
",",
"name",
")",
":",
"return",
"self",
".",
"router_command",
"(",
"\"addShard\"",
",",
"(",
"shard_uri",
",",
"{",
"\"name\"",
":",
"name",
"}",
")",
",",
"is_eval",
"=",
"False",
")"
] | execute addShard command | [
"execute",
"addShard",
"command"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L356-L358 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster.member_add | def member_add(self, member_id=None, params=None):
"""add new member into existing configuration"""
member_id = member_id or str(uuid4())
if self.enable_ipv6:
common.enable_ipv6_repl(params)
if 'members' in params:
# is replica set
for member in params... | python | def member_add(self, member_id=None, params=None):
"""add new member into existing configuration"""
member_id = member_id or str(uuid4())
if self.enable_ipv6:
common.enable_ipv6_repl(params)
if 'members' in params:
# is replica set
for member in params... | [
"def",
"member_add",
"(",
"self",
",",
"member_id",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"member_id",
"=",
"member_id",
"or",
"str",
"(",
"uuid4",
"(",
")",
")",
"if",
"self",
".",
"enable_ipv6",
":",
"common",
".",
"enable_ipv6_repl",
"(... | add new member into existing configuration | [
"add",
"new",
"member",
"into",
"existing",
"configuration"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L360-L400 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster._remove | def _remove(self, shard_name):
"""remove member from configuration"""
result = self.router_command("removeShard", shard_name, is_eval=False)
if result['ok'] == 1 and result['state'] == 'completed':
shard = self._shards.pop(shard_name)
if shard.get('isServer', False):
... | python | def _remove(self, shard_name):
"""remove member from configuration"""
result = self.router_command("removeShard", shard_name, is_eval=False)
if result['ok'] == 1 and result['state'] == 'completed':
shard = self._shards.pop(shard_name)
if shard.get('isServer', False):
... | [
"def",
"_remove",
"(",
"self",
",",
"shard_name",
")",
":",
"result",
"=",
"self",
".",
"router_command",
"(",
"\"removeShard\"",
",",
"shard_name",
",",
"is_eval",
"=",
"False",
")",
"if",
"result",
"[",
"'ok'",
"]",
"==",
"1",
"and",
"result",
"[",
"... | remove member from configuration | [
"remove",
"member",
"from",
"configuration"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L409-L418 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster.reset | def reset(self):
"""Ensure all shards, configs, and routers are running and available."""
# Ensure all shards by calling "reset" on each.
for shard_id in self._shards:
if self._shards[shard_id].get('isReplicaSet'):
singleton = ReplicaSets()
elif self._shar... | python | def reset(self):
"""Ensure all shards, configs, and routers are running and available."""
# Ensure all shards by calling "reset" on each.
for shard_id in self._shards:
if self._shards[shard_id].get('isReplicaSet'):
singleton = ReplicaSets()
elif self._shar... | [
"def",
"reset",
"(",
"self",
")",
":",
"for",
"shard_id",
"in",
"self",
".",
"_shards",
":",
"if",
"self",
".",
"_shards",
"[",
"shard_id",
"]",
".",
"get",
"(",
"'isReplicaSet'",
")",
":",
"singleton",
"=",
"ReplicaSets",
"(",
")",
"elif",
"self",
"... | Ensure all shards, configs, and routers are running and available. | [
"Ensure",
"all",
"shards",
"configs",
"and",
"routers",
"are",
"running",
"and",
"available",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L424-L439 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedCluster.info | def info(self):
"""return info about configuration"""
uri = ','.join(x['hostname'] for x in self.routers)
mongodb_uri = 'mongodb://' + uri
result = {'id': self.id,
'shards': self.members,
'configsvrs': self.configsvrs,
'routers': self... | python | def info(self):
"""return info about configuration"""
uri = ','.join(x['hostname'] for x in self.routers)
mongodb_uri = 'mongodb://' + uri
result = {'id': self.id,
'shards': self.members,
'configsvrs': self.configsvrs,
'routers': self... | [
"def",
"info",
"(",
"self",
")",
":",
"uri",
"=",
"','",
".",
"join",
"(",
"x",
"[",
"'hostname'",
"]",
"for",
"x",
"in",
"self",
".",
"routers",
")",
"mongodb_uri",
"=",
"'mongodb://'",
"+",
"uri",
"result",
"=",
"{",
"'id'",
":",
"self",
".",
"... | return info about configuration | [
"return",
"info",
"about",
"configuration"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L441-L453 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedClusters.router_add | def router_add(self, cluster_id, params):
"""add new router"""
cluster = self._storage[cluster_id]
result = cluster.router_add(params)
self._storage[cluster_id] = cluster
return result | python | def router_add(self, cluster_id, params):
"""add new router"""
cluster = self._storage[cluster_id]
result = cluster.router_add(params)
self._storage[cluster_id] = cluster
return result | [
"def",
"router_add",
"(",
"self",
",",
"cluster_id",
",",
"params",
")",
":",
"cluster",
"=",
"self",
".",
"_storage",
"[",
"cluster_id",
"]",
"result",
"=",
"cluster",
".",
"router_add",
"(",
"params",
")",
"self",
".",
"_storage",
"[",
"cluster_id",
"]... | add new router | [
"add",
"new",
"router"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L533-L538 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedClusters.router_del | def router_del(self, cluster_id, router_id):
"""remove router from the ShardedCluster"""
cluster = self._storage[cluster_id]
result = cluster.router_remove(router_id)
self._storage[cluster_id] = cluster
return result | python | def router_del(self, cluster_id, router_id):
"""remove router from the ShardedCluster"""
cluster = self._storage[cluster_id]
result = cluster.router_remove(router_id)
self._storage[cluster_id] = cluster
return result | [
"def",
"router_del",
"(",
"self",
",",
"cluster_id",
",",
"router_id",
")",
":",
"cluster",
"=",
"self",
".",
"_storage",
"[",
"cluster_id",
"]",
"result",
"=",
"cluster",
".",
"router_remove",
"(",
"router_id",
")",
"self",
".",
"_storage",
"[",
"cluster_... | remove router from the ShardedCluster | [
"remove",
"router",
"from",
"the",
"ShardedCluster"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L540-L545 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedClusters.command | def command(self, cluster_id, command, *args):
"""Call a ShardedCluster method."""
cluster = self._storage[cluster_id]
try:
return getattr(cluster, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ShardedCluster %s"
... | python | def command(self, cluster_id, command, *args):
"""Call a ShardedCluster method."""
cluster = self._storage[cluster_id]
try:
return getattr(cluster, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ShardedCluster %s"
... | [
"def",
"command",
"(",
"self",
",",
"cluster_id",
",",
"command",
",",
"*",
"args",
")",
":",
"cluster",
"=",
"self",
".",
"_storage",
"[",
"cluster_id",
"]",
"try",
":",
"return",
"getattr",
"(",
"cluster",
",",
"command",
")",
"(",
"*",
"args",
")"... | Call a ShardedCluster method. | [
"Call",
"a",
"ShardedCluster",
"method",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L556-L563 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedClusters.member_del | def member_del(self, cluster_id, member_id):
"""remove member from cluster cluster"""
cluster = self._storage[cluster_id]
result = cluster.member_remove(member_id)
self._storage[cluster_id] = cluster
return result | python | def member_del(self, cluster_id, member_id):
"""remove member from cluster cluster"""
cluster = self._storage[cluster_id]
result = cluster.member_remove(member_id)
self._storage[cluster_id] = cluster
return result | [
"def",
"member_del",
"(",
"self",
",",
"cluster_id",
",",
"member_id",
")",
":",
"cluster",
"=",
"self",
".",
"_storage",
"[",
"cluster_id",
"]",
"result",
"=",
"cluster",
".",
"member_remove",
"(",
"member_id",
")",
"self",
".",
"_storage",
"[",
"cluster_... | remove member from cluster cluster | [
"remove",
"member",
"from",
"cluster",
"cluster"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L565-L570 | train |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | ShardedClusters.member_add | def member_add(self, cluster_id, params):
"""add new member into configuration"""
cluster = self._storage[cluster_id]
result = cluster.member_add(params.get('id', None), params.get('shardParams', {}))
self._storage[cluster_id] = cluster
return result | python | def member_add(self, cluster_id, params):
"""add new member into configuration"""
cluster = self._storage[cluster_id]
result = cluster.member_add(params.get('id', None), params.get('shardParams', {}))
self._storage[cluster_id] = cluster
return result | [
"def",
"member_add",
"(",
"self",
",",
"cluster_id",
",",
"params",
")",
":",
"cluster",
"=",
"self",
".",
"_storage",
"[",
"cluster_id",
"]",
"result",
"=",
"cluster",
".",
"member_add",
"(",
"params",
".",
"get",
"(",
"'id'",
",",
"None",
")",
",",
... | add new member into configuration | [
"add",
"new",
"member",
"into",
"configuration"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L572-L577 | train |
vcs-python/vcspull | vcspull/config.py | expand_dir | def expand_dir(_dir, cwd=os.getcwd()):
"""Return path with environmental variables and tilde ~ expanded.
:param _dir:
:type _dir: str
:param cwd: current working dir (for deciphering relative _dir paths)
:type cwd: str
:rtype; str
"""
_dir = os.path.expanduser(os.path.expandvars(_dir))
... | python | def expand_dir(_dir, cwd=os.getcwd()):
"""Return path with environmental variables and tilde ~ expanded.
:param _dir:
:type _dir: str
:param cwd: current working dir (for deciphering relative _dir paths)
:type cwd: str
:rtype; str
"""
_dir = os.path.expanduser(os.path.expandvars(_dir))
... | [
"def",
"expand_dir",
"(",
"_dir",
",",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"_dir",
")",
")",
"if",
"not",
"os",
".",
"path",
"."... | Return path with environmental variables and tilde ~ expanded.
:param _dir:
:type _dir: str
:param cwd: current working dir (for deciphering relative _dir paths)
:type cwd: str
:rtype; str | [
"Return",
"path",
"with",
"environmental",
"variables",
"and",
"tilde",
"~",
"expanded",
"."
] | c1827bf78d2cdebc61d82111c9aa35afd6ea6a25 | https://github.com/vcs-python/vcspull/blob/c1827bf78d2cdebc61d82111c9aa35afd6ea6a25/vcspull/config.py#L26-L38 | train |
vcs-python/vcspull | vcspull/config.py | extract_repos | def extract_repos(config, cwd=os.getcwd()):
"""Return expanded configuration.
end-user configuration permit inline configuration shortcuts, expand to
identical format for parsing.
:param config: the repo config in :py:class:`dict` format.
:type config: dict
:param cwd: current working dir (for... | python | def extract_repos(config, cwd=os.getcwd()):
"""Return expanded configuration.
end-user configuration permit inline configuration shortcuts, expand to
identical format for parsing.
:param config: the repo config in :py:class:`dict` format.
:type config: dict
:param cwd: current working dir (for... | [
"def",
"extract_repos",
"(",
"config",
",",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"configs",
"=",
"[",
"]",
"for",
"directory",
",",
"repos",
"in",
"config",
".",
"items",
"(",
")",
":",
"for",
"repo",
",",
"repo_data",
"in",
"repos"... | Return expanded configuration.
end-user configuration permit inline configuration shortcuts, expand to
identical format for parsing.
:param config: the repo config in :py:class:`dict` format.
:type config: dict
:param cwd: current working dir (for deciphering relative paths)
:type cwd: str
... | [
"Return",
"expanded",
"configuration",
"."
] | c1827bf78d2cdebc61d82111c9aa35afd6ea6a25 | https://github.com/vcs-python/vcspull/blob/c1827bf78d2cdebc61d82111c9aa35afd6ea6a25/vcspull/config.py#L41-L106 | train |
vcs-python/vcspull | vcspull/config.py | find_config_files | def find_config_files(
path=['~/.vcspull'], match=['*'], filetype=['json', 'yaml'], include_home=False
):
"""Return repos from a directory and match. Not recursive.
:param path: list of paths to search
:type path: list
:param match: list of globs to search against
:type match: list
:param f... | python | def find_config_files(
path=['~/.vcspull'], match=['*'], filetype=['json', 'yaml'], include_home=False
):
"""Return repos from a directory and match. Not recursive.
:param path: list of paths to search
:type path: list
:param match: list of globs to search against
:type match: list
:param f... | [
"def",
"find_config_files",
"(",
"path",
"=",
"[",
"'~/.vcspull'",
"]",
",",
"match",
"=",
"[",
"'*'",
"]",
",",
"filetype",
"=",
"[",
"'json'",
",",
"'yaml'",
"]",
",",
"include_home",
"=",
"False",
")",
":",
"configs",
"=",
"[",
"]",
"if",
"include... | Return repos from a directory and match. Not recursive.
:param path: list of paths to search
:type path: list
:param match: list of globs to search against
:type match: list
:param filetype: list of filetypes to search against
:type filetype: list
:param include_home: Include home configura... | [
"Return",
"repos",
"from",
"a",
"directory",
"and",
"match",
".",
"Not",
"recursive",
"."
] | c1827bf78d2cdebc61d82111c9aa35afd6ea6a25 | https://github.com/vcs-python/vcspull/blob/c1827bf78d2cdebc61d82111c9aa35afd6ea6a25/vcspull/config.py#L135-L179 | train |
vcs-python/vcspull | vcspull/config.py | load_configs | def load_configs(files, cwd=os.getcwd()):
"""Return repos from a list of files.
:todo: Validate scheme, check for duplciate destinations, VCS urls
:param files: paths to config file
:type files: list
:param cwd: current path (pass down for :func:`extract_repos`
:type cwd: str
:returns: exp... | python | def load_configs(files, cwd=os.getcwd()):
"""Return repos from a list of files.
:todo: Validate scheme, check for duplciate destinations, VCS urls
:param files: paths to config file
:type files: list
:param cwd: current path (pass down for :func:`extract_repos`
:type cwd: str
:returns: exp... | [
"def",
"load_configs",
"(",
"files",
",",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"repos",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"f",
")",
"conf",
"=",
"kapt... | Return repos from a list of files.
:todo: Validate scheme, check for duplciate destinations, VCS urls
:param files: paths to config file
:type files: list
:param cwd: current path (pass down for :func:`extract_repos`
:type cwd: str
:returns: expanded config dict item
:rtype: list of dict | [
"Return",
"repos",
"from",
"a",
"list",
"of",
"files",
"."
] | c1827bf78d2cdebc61d82111c9aa35afd6ea6a25 | https://github.com/vcs-python/vcspull/blob/c1827bf78d2cdebc61d82111c9aa35afd6ea6a25/vcspull/config.py#L182-L212 | train |
vcs-python/vcspull | vcspull/config.py | detect_duplicate_repos | def detect_duplicate_repos(repos1, repos2):
"""Return duplicate repos dict if repo_dir same and vcs different.
:param repos1: list of repo expanded dicts
:type repos1: list of :py:dict
:param repos2: list of repo expanded dicts
:type repos2: list of :py:dict
:rtype: list of dicts or None
:r... | python | def detect_duplicate_repos(repos1, repos2):
"""Return duplicate repos dict if repo_dir same and vcs different.
:param repos1: list of repo expanded dicts
:type repos1: list of :py:dict
:param repos2: list of repo expanded dicts
:type repos2: list of :py:dict
:rtype: list of dicts or None
:r... | [
"def",
"detect_duplicate_repos",
"(",
"repos1",
",",
"repos2",
")",
":",
"dupes",
"=",
"[",
"]",
"path_dupe_repos",
"=",
"[",
"]",
"curpaths",
"=",
"[",
"r",
"[",
"'repo_dir'",
"]",
"for",
"r",
"in",
"repos1",
"]",
"newpaths",
"=",
"[",
"r",
"[",
"'r... | Return duplicate repos dict if repo_dir same and vcs different.
:param repos1: list of repo expanded dicts
:type repos1: list of :py:dict
:param repos2: list of repo expanded dicts
:type repos2: list of :py:dict
:rtype: list of dicts or None
:returns: Duplicate lists | [
"Return",
"duplicate",
"repos",
"dict",
"if",
"repo_dir",
"same",
"and",
"vcs",
"different",
"."
] | c1827bf78d2cdebc61d82111c9aa35afd6ea6a25 | https://github.com/vcs-python/vcspull/blob/c1827bf78d2cdebc61d82111c9aa35afd6ea6a25/vcspull/config.py#L215-L246 | train |
jschaf/pylint-flask | pylint_flask/__init__.py | copy_node_info | def copy_node_info(src, dest):
"""Copy information from src to dest
Every node in the AST has to have line number information. Get
the information from the old stmt."""
for attr in ['lineno', 'fromlineno', 'tolineno',
'col_offset', 'parent']:
if hasattr(src, attr):
... | python | def copy_node_info(src, dest):
"""Copy information from src to dest
Every node in the AST has to have line number information. Get
the information from the old stmt."""
for attr in ['lineno', 'fromlineno', 'tolineno',
'col_offset', 'parent']:
if hasattr(src, attr):
... | [
"def",
"copy_node_info",
"(",
"src",
",",
"dest",
")",
":",
"for",
"attr",
"in",
"[",
"'lineno'",
",",
"'fromlineno'",
",",
"'tolineno'",
",",
"'col_offset'",
",",
"'parent'",
"]",
":",
"if",
"hasattr",
"(",
"src",
",",
"attr",
")",
":",
"setattr",
"("... | Copy information from src to dest
Every node in the AST has to have line number information. Get
the information from the old stmt. | [
"Copy",
"information",
"from",
"src",
"to",
"dest"
] | 3851d142679facbc60b4755dc7fb5428aafdebe7 | https://github.com/jschaf/pylint-flask/blob/3851d142679facbc60b4755dc7fb5428aafdebe7/pylint_flask/__init__.py#L15-L23 | train |
jschaf/pylint-flask | pylint_flask/__init__.py | make_non_magical_flask_import | def make_non_magical_flask_import(flask_ext_name):
'''Convert a flask.ext.admin into flask_admin.'''
match = re.match(r'flask\.ext\.(.*)', flask_ext_name)
if match is None:
raise LookupError("Module name `{}` doesn't match"
"`flask.ext` style import.")
from_name = match... | python | def make_non_magical_flask_import(flask_ext_name):
'''Convert a flask.ext.admin into flask_admin.'''
match = re.match(r'flask\.ext\.(.*)', flask_ext_name)
if match is None:
raise LookupError("Module name `{}` doesn't match"
"`flask.ext` style import.")
from_name = match... | [
"def",
"make_non_magical_flask_import",
"(",
"flask_ext_name",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'flask\\.ext\\.(.*)'",
",",
"flask_ext_name",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"LookupError",
"(",
"\"Module name `{}` doesn't match\"",
... | Convert a flask.ext.admin into flask_admin. | [
"Convert",
"a",
"flask",
".",
"ext",
".",
"admin",
"into",
"flask_admin",
"."
] | 3851d142679facbc60b4755dc7fb5428aafdebe7 | https://github.com/jschaf/pylint-flask/blob/3851d142679facbc60b4755dc7fb5428aafdebe7/pylint_flask/__init__.py#L36-L44 | train |
jschaf/pylint-flask | pylint_flask/__init__.py | transform_flask_from_import | def transform_flask_from_import(node):
'''Translates a flask.ext from-style import into a non-magical import.
Translates:
from flask.ext import wtf, bcrypt as fcrypt
Into:
import flask_wtf as wtf, flask_bcrypt as fcrypt
'''
new_names = []
# node.names is a list of 2-tuples. Eac... | python | def transform_flask_from_import(node):
'''Translates a flask.ext from-style import into a non-magical import.
Translates:
from flask.ext import wtf, bcrypt as fcrypt
Into:
import flask_wtf as wtf, flask_bcrypt as fcrypt
'''
new_names = []
# node.names is a list of 2-tuples. Eac... | [
"def",
"transform_flask_from_import",
"(",
"node",
")",
":",
"new_names",
"=",
"[",
"]",
"for",
"(",
"name",
",",
"as_name",
")",
"in",
"node",
".",
"names",
":",
"actual_module_name",
"=",
"'flask_{}'",
".",
"format",
"(",
"name",
")",
"new_names",
".",
... | Translates a flask.ext from-style import into a non-magical import.
Translates:
from flask.ext import wtf, bcrypt as fcrypt
Into:
import flask_wtf as wtf, flask_bcrypt as fcrypt | [
"Translates",
"a",
"flask",
".",
"ext",
"from",
"-",
"style",
"import",
"into",
"a",
"non",
"-",
"magical",
"import",
"."
] | 3851d142679facbc60b4755dc7fb5428aafdebe7 | https://github.com/jschaf/pylint-flask/blob/3851d142679facbc60b4755dc7fb5428aafdebe7/pylint_flask/__init__.py#L47-L71 | train |
jschaf/pylint-flask | pylint_flask/__init__.py | transform_flask_from_long | def transform_flask_from_long(node):
'''Translates a flask.ext.wtf from-style import into a non-magical import.
Translates:
from flask.ext.wtf import Form
from flask.ext.admin.model import InlineFormAdmin
Into:
from flask_wtf import Form
from flask_admin.model import InlineF... | python | def transform_flask_from_long(node):
'''Translates a flask.ext.wtf from-style import into a non-magical import.
Translates:
from flask.ext.wtf import Form
from flask.ext.admin.model import InlineFormAdmin
Into:
from flask_wtf import Form
from flask_admin.model import InlineF... | [
"def",
"transform_flask_from_long",
"(",
"node",
")",
":",
"actual_module_name",
"=",
"make_non_magical_flask_import",
"(",
"node",
".",
"modname",
")",
"new_node",
"=",
"nodes",
".",
"ImportFrom",
"(",
"actual_module_name",
",",
"node",
".",
"names",
",",
"node",... | Translates a flask.ext.wtf from-style import into a non-magical import.
Translates:
from flask.ext.wtf import Form
from flask.ext.admin.model import InlineFormAdmin
Into:
from flask_wtf import Form
from flask_admin.model import InlineFormAdmin | [
"Translates",
"a",
"flask",
".",
"ext",
".",
"wtf",
"from",
"-",
"style",
"import",
"into",
"a",
"non",
"-",
"magical",
"import",
"."
] | 3851d142679facbc60b4755dc7fb5428aafdebe7 | https://github.com/jschaf/pylint-flask/blob/3851d142679facbc60b4755dc7fb5428aafdebe7/pylint_flask/__init__.py#L84-L99 | train |
jschaf/pylint-flask | pylint_flask/__init__.py | transform_flask_bare_import | def transform_flask_bare_import(node):
'''Translates a flask.ext.wtf bare import into a non-magical import.
Translates:
import flask.ext.admin as admin
Into:
import flask_admin as admin
'''
new_names = []
for (name, as_name) in node.names:
match = re.match(r'flask\.ext\... | python | def transform_flask_bare_import(node):
'''Translates a flask.ext.wtf bare import into a non-magical import.
Translates:
import flask.ext.admin as admin
Into:
import flask_admin as admin
'''
new_names = []
for (name, as_name) in node.names:
match = re.match(r'flask\.ext\... | [
"def",
"transform_flask_bare_import",
"(",
"node",
")",
":",
"new_names",
"=",
"[",
"]",
"for",
"(",
"name",
",",
"as_name",
")",
"in",
"node",
".",
"names",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'flask\\.ext\\.(.*)'",
",",
"name",
")",
"from_nam... | Translates a flask.ext.wtf bare import into a non-magical import.
Translates:
import flask.ext.admin as admin
Into:
import flask_admin as admin | [
"Translates",
"a",
"flask",
".",
"ext",
".",
"wtf",
"bare",
"import",
"into",
"a",
"non",
"-",
"magical",
"import",
"."
] | 3851d142679facbc60b4755dc7fb5428aafdebe7 | https://github.com/jschaf/pylint-flask/blob/3851d142679facbc60b4755dc7fb5428aafdebe7/pylint_flask/__init__.py#L112-L132 | train |
niolabs/python-xbee | examples/alarm.py | main | def main():
"""
Run through simple demonstration of alarm concept
"""
alarm = XBeeAlarm('/dev/ttyUSB0', '\x56\x78')
routine = SimpleWakeupRoutine(alarm)
from time import sleep
while True:
"""
Run the routine with 10 second delays
"""
try:
print "W... | python | def main():
"""
Run through simple demonstration of alarm concept
"""
alarm = XBeeAlarm('/dev/ttyUSB0', '\x56\x78')
routine = SimpleWakeupRoutine(alarm)
from time import sleep
while True:
"""
Run the routine with 10 second delays
"""
try:
print "W... | [
"def",
"main",
"(",
")",
":",
"alarm",
"=",
"XBeeAlarm",
"(",
"'/dev/ttyUSB0'",
",",
"'\\x56\\x78'",
")",
"routine",
"=",
"SimpleWakeupRoutine",
"(",
"alarm",
")",
"from",
"time",
"import",
"sleep",
"while",
"True",
":",
"try",
":",
"print",
"\"Waiting 5 sec... | Run through simple demonstration of alarm concept | [
"Run",
"through",
"simple",
"demonstration",
"of",
"alarm",
"concept"
] | b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7 | https://github.com/niolabs/python-xbee/blob/b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7/examples/alarm.py#L232-L250 | train |
niolabs/python-xbee | xbee/backend/zigbee.py | ZigBee._parse_IS_at_response | def _parse_IS_at_response(self, packet_info):
"""
If the given packet is a successful remote AT response for an IS
command, parse the parameter field as IO data.
"""
if packet_info['id'] in ('at_response', 'remote_at_response') and \
packet_info['command'].lower()... | python | def _parse_IS_at_response(self, packet_info):
"""
If the given packet is a successful remote AT response for an IS
command, parse the parameter field as IO data.
"""
if packet_info['id'] in ('at_response', 'remote_at_response') and \
packet_info['command'].lower()... | [
"def",
"_parse_IS_at_response",
"(",
"self",
",",
"packet_info",
")",
":",
"if",
"packet_info",
"[",
"'id'",
"]",
"in",
"(",
"'at_response'",
",",
"'remote_at_response'",
")",
"and",
"packet_info",
"[",
"'command'",
"]",
".",
"lower",
"(",
")",
"==",
"b'is'"... | If the given packet is a successful remote AT response for an IS
command, parse the parameter field as IO data. | [
"If",
"the",
"given",
"packet",
"is",
"a",
"successful",
"remote",
"AT",
"response",
"for",
"an",
"IS",
"command",
"parse",
"the",
"parameter",
"field",
"as",
"IO",
"data",
"."
] | b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7 | https://github.com/niolabs/python-xbee/blob/b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7/xbee/backend/zigbee.py#L254-L264 | train |
niolabs/python-xbee | xbee/backend/zigbee.py | ZigBee._parse_ND_at_response | def _parse_ND_at_response(self, packet_info):
"""
If the given packet is a successful AT response for an ND
command, parse the parameter field.
"""
if packet_info['id'] == 'at_response' and \
packet_info['command'].lower() == b'nd' and \
packet_inf... | python | def _parse_ND_at_response(self, packet_info):
"""
If the given packet is a successful AT response for an ND
command, parse the parameter field.
"""
if packet_info['id'] == 'at_response' and \
packet_info['command'].lower() == b'nd' and \
packet_inf... | [
"def",
"_parse_ND_at_response",
"(",
"self",
",",
"packet_info",
")",
":",
"if",
"packet_info",
"[",
"'id'",
"]",
"==",
"'at_response'",
"and",
"packet_info",
"[",
"'command'",
"]",
".",
"lower",
"(",
")",
"==",
"b'nd'",
"and",
"packet_info",
"[",
"'status'"... | If the given packet is a successful AT response for an ND
command, parse the parameter field. | [
"If",
"the",
"given",
"packet",
"is",
"a",
"successful",
"AT",
"response",
"for",
"an",
"ND",
"command",
"parse",
"the",
"parameter",
"field",
"."
] | b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7 | https://github.com/niolabs/python-xbee/blob/b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7/xbee/backend/zigbee.py#L266-L315 | train |
niolabs/python-xbee | examples/serial_example_series_1.py | main | def main():
"""
Sends an API AT command to read the lower-order address bits from
an XBee Series 1 and looks for a response
"""
try:
# Open serial port
ser = serial.Serial('/dev/ttyUSB0', 9600)
# Create XBee Series 1 object
xbee = XBee(ser)
# Send AT packe... | python | def main():
"""
Sends an API AT command to read the lower-order address bits from
an XBee Series 1 and looks for a response
"""
try:
# Open serial port
ser = serial.Serial('/dev/ttyUSB0', 9600)
# Create XBee Series 1 object
xbee = XBee(ser)
# Send AT packe... | [
"def",
"main",
"(",
")",
":",
"try",
":",
"ser",
"=",
"serial",
".",
"Serial",
"(",
"'/dev/ttyUSB0'",
",",
"9600",
")",
"xbee",
"=",
"XBee",
"(",
"ser",
")",
"xbee",
".",
"send",
"(",
"'at'",
",",
"frame_id",
"=",
"'A'",
",",
"command",
"=",
"'DH... | Sends an API AT command to read the lower-order address bits from
an XBee Series 1 and looks for a response | [
"Sends",
"an",
"API",
"AT",
"command",
"to",
"read",
"the",
"lower",
"-",
"order",
"address",
"bits",
"from",
"an",
"XBee",
"Series",
"1",
"and",
"looks",
"for",
"a",
"response"
] | b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7 | https://github.com/niolabs/python-xbee/blob/b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7/examples/serial_example_series_1.py#L14-L58 | train |
niolabs/python-xbee | xbee/python2to3.py | byteToInt | def byteToInt(byte):
"""
byte -> int
Determines whether to use ord() or not to get a byte's value.
"""
if hasattr(byte, 'bit_length'):
# This is already an int
return byte
return ord(byte) if hasattr(byte, 'encode') else byte[0] | python | def byteToInt(byte):
"""
byte -> int
Determines whether to use ord() or not to get a byte's value.
"""
if hasattr(byte, 'bit_length'):
# This is already an int
return byte
return ord(byte) if hasattr(byte, 'encode') else byte[0] | [
"def",
"byteToInt",
"(",
"byte",
")",
":",
"if",
"hasattr",
"(",
"byte",
",",
"'bit_length'",
")",
":",
"return",
"byte",
"return",
"ord",
"(",
"byte",
")",
"if",
"hasattr",
"(",
"byte",
",",
"'encode'",
")",
"else",
"byte",
"[",
"0",
"]"
] | byte -> int
Determines whether to use ord() or not to get a byte's value. | [
"byte",
"-",
">",
"int"
] | b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7 | https://github.com/niolabs/python-xbee/blob/b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7/xbee/python2to3.py#L10-L19 | train |
jwplayer/jwplatform-py | examples/video_conversions_list.py | list_conversions | def list_conversions(api_key, api_secret, video_key, **kwargs):
"""
Function which retrieves a list of a video object's conversions.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWP... | python | def list_conversions(api_key, api_secret, video_key, **kwargs):
"""
Function which retrieves a list of a video object's conversions.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWP... | [
"def",
"list_conversions",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"**",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",
"(",
"\"Querying for video conve... | Function which retrieves a list of a video object's conversions.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
:param kwargs: Arguments conforming to standards found ... | [
"Function",
"which",
"retrieves",
"a",
"list",
"of",
"a",
"video",
"object",
"s",
"conversions",
"."
] | 804950158fa04a6b153fc86acae9a3f97ba3bd75 | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_conversions_list.py#L10-L27 | train |
jwplayer/jwplatform-py | jwplatform/client.py | Client._build_request | def _build_request(self, path, params=None):
"""Build API request"""
_url = '{scheme}://{host}{port}/{version}{path}'.format(
scheme=self._scheme,
host=self._host,
port=':{}'.format(self._port) if self._port != 80 else '',
version=self._api_version,
... | python | def _build_request(self, path, params=None):
"""Build API request"""
_url = '{scheme}://{host}{port}/{version}{path}'.format(
scheme=self._scheme,
host=self._host,
port=':{}'.format(self._port) if self._port != 80 else '',
version=self._api_version,
... | [
"def",
"_build_request",
"(",
"self",
",",
"path",
",",
"params",
"=",
"None",
")",
":",
"_url",
"=",
"'{scheme}://{host}{port}/{version}{path}'",
".",
"format",
"(",
"scheme",
"=",
"self",
".",
"_scheme",
",",
"host",
"=",
"self",
".",
"_host",
",",
"port... | Build API request | [
"Build",
"API",
"request"
] | 804950158fa04a6b153fc86acae9a3f97ba3bd75 | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/jwplatform/client.py#L79-L112 | train |
jwplayer/jwplatform-py | examples/video_singlepart_create.py | create_video | def create_video(api_key, api_secret, local_video_path, api_format='json', **kwargs):
"""
Function which creates new video object via singlefile upload method.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to ... | python | def create_video(api_key, api_secret, local_video_path, api_format='json', **kwargs):
"""
Function which creates new video object via singlefile upload method.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to ... | [
"def",
"create_video",
"(",
"api_key",
",",
"api_secret",
",",
"local_video_path",
",",
"api_format",
"=",
"'json'",
",",
"**",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
... | Function which creates new video object via singlefile upload method.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to media on local machine.
:param api_format: <string> Acceptable values include 'py','xml','json... | [
"Function",
"which",
"creates",
"new",
"video",
"object",
"via",
"singlefile",
"upload",
"method",
"."
] | 804950158fa04a6b153fc86acae9a3f97ba3bd75 | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_singlepart_create.py#L12-L52 | train |
jwplayer/jwplatform-py | examples/video_s3_replace_video.py | replace_video | def replace_video(api_key, api_secret, local_video_path, video_key, **kwargs):
"""
Function which allows to replace the content of an EXISTING video object.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to med... | python | def replace_video(api_key, api_secret, local_video_path, video_key, **kwargs):
"""
Function which allows to replace the content of an EXISTING video object.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to med... | [
"def",
"replace_video",
"(",
"api_key",
",",
"api_secret",
",",
"local_video_path",
",",
"video_key",
",",
"**",
"kwargs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"local_video_path",
")",
"jwplatform_client",
"=",
"jwplatform",
".",... | Function which allows to replace the content of an EXISTING video object.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to media on local machine.
:param video_key: <string> Video's object ID. Can be found within ... | [
"Function",
"which",
"allows",
"to",
"replace",
"the",
"content",
"of",
"an",
"EXISTING",
"video",
"object",
"."
] | 804950158fa04a6b153fc86acae9a3f97ba3bd75 | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_s3_replace_video.py#L14-L57 | train |
jwplayer/jwplatform-py | examples/video_thumbnail_update.py | update_thumbnail | def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs):
"""
Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, us... | python | def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs):
"""
Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, us... | [
"def",
"update_thumbnail",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"position",
"=",
"7.0",
",",
"**",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",... | Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, user may opt to utilize thumbnail_index parameter.
Please eee documentation for further ... | [
"Function",
"which",
"updates",
"the",
"thumbnail",
"for",
"an",
"EXISTING",
"video",
"utilizing",
"position",
"parameter",
".",
"This",
"function",
"is",
"useful",
"for",
"selecting",
"a",
"new",
"thumbnail",
"from",
"with",
"the",
"already",
"existing",
"video... | 804950158fa04a6b153fc86acae9a3f97ba3bd75 | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_thumbnail_update.py#L11-L35 | train |
jwplayer/jwplatform-py | examples/video_thumbnail_update.py | update_thumbnail_via_upload | def update_thumbnail_via_upload(api_key, api_secret, video_key, local_video_image_path='', api_format='json',
**kwargs):
"""
Function which updates the thumbnail for a particular video object with a locally saved image.
:param api_key: <string> JWPlatform api-key
:param ... | python | def update_thumbnail_via_upload(api_key, api_secret, video_key, local_video_image_path='', api_format='json',
**kwargs):
"""
Function which updates the thumbnail for a particular video object with a locally saved image.
:param api_key: <string> JWPlatform api-key
:param ... | [
"def",
"update_thumbnail_via_upload",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"local_video_image_path",
"=",
"''",
",",
"api_format",
"=",
"'json'",
",",
"**",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api... | Function which updates the thumbnail for a particular video object with a locally saved image.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
:param local_video_image_... | [
"Function",
"which",
"updates",
"the",
"thumbnail",
"for",
"a",
"particular",
"video",
"object",
"with",
"a",
"locally",
"saved",
"image",
"."
] | 804950158fa04a6b153fc86acae9a3f97ba3bd75 | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_thumbnail_update.py#L38-L77 | train |
jwplayer/jwplatform-py | examples/video_multipart_create.py | run_upload | def run_upload(video_file_path):
"""
Configures all of the needed upload_parameters and sets up all information pertinent
to the video to be uploaded.
:param video_file_path: <str> the absolute path to the video file
"""
upload_parameters = {
'file_path': video_file_path,
'file... | python | def run_upload(video_file_path):
"""
Configures all of the needed upload_parameters and sets up all information pertinent
to the video to be uploaded.
:param video_file_path: <str> the absolute path to the video file
"""
upload_parameters = {
'file_path': video_file_path,
'file... | [
"def",
"run_upload",
"(",
"video_file_path",
")",
":",
"upload_parameters",
"=",
"{",
"'file_path'",
":",
"video_file_path",
",",
"'file_size'",
":",
"os",
".",
"stat",
"(",
"video_file_path",
")",
".",
"st_size",
",",
"'file_name'",
":",
"os",
".",
"path",
... | Configures all of the needed upload_parameters and sets up all information pertinent
to the video to be uploaded.
:param video_file_path: <str> the absolute path to the video file | [
"Configures",
"all",
"of",
"the",
"needed",
"upload_parameters",
"and",
"sets",
"up",
"all",
"information",
"pertinent",
"to",
"the",
"video",
"to",
"be",
"uploaded",
"."
] | 804950158fa04a6b153fc86acae9a3f97ba3bd75 | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_multipart_create.py#L20-L73 | train |
jwplayer/jwplatform-py | examples/video_list_to_csv.py | make_csv | def make_csv(api_key, api_secret, path_to_csv=None, result_limit=1000, **kwargs):
"""
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param... | python | def make_csv(api_key, api_secret, path_to_csv=None, result_limit=1000, **kwargs):
"""
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param... | [
"def",
"make_csv",
"(",
"api_key",
",",
"api_secret",
",",
"path_to_csv",
"=",
"None",
",",
"result_limit",
"=",
"1000",
",",
"**",
"kwargs",
")",
":",
"path_to_csv",
"=",
"path_to_csv",
"or",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"... | Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param path_to_csv: <string> Local system path to desired CSV. Default will be within current workin... | [
"Function",
"which",
"fetches",
"a",
"video",
"library",
"and",
"writes",
"each",
"video_objects",
"Metadata",
"to",
"CSV",
".",
"Useful",
"for",
"CMS",
"systems",
"."
] | 804950158fa04a6b153fc86acae9a3f97ba3bd75 | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_list_to_csv.py#L13-L73 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha.image | def image(self):
r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is morphed and pased onto CAPTCHA text.
... | python | def image(self):
r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is morphed and pased onto CAPTCHA text.
... | [
"def",
"image",
"(",
"self",
")",
":",
"r",
"text",
"=",
"self",
".",
"text",
"w",
",",
"h",
"=",
"self",
".",
"font",
".",
"getsize",
"(",
"text",
")",
"margin_x",
"=",
"round",
"(",
"self",
".",
"margin_x",
"*",
"w",
"/",
"self",
".",
"w",
... | r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is morphed and pased onto CAPTCHA text.
Additionaly, if self.no... | [
"r",
"Tuple",
"with",
"a",
"CAPTCHA",
"text",
"and",
"a",
"Image",
"object",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L88-L125 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha.bytes | def bytes(self):
r"""
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesIO object)
"""
... | python | def bytes(self):
r"""
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesIO object)
"""
... | [
"def",
"bytes",
"(",
"self",
")",
":",
"r",
"text",
",",
"image",
"=",
"self",
".",
"image",
"bytes",
"=",
"BytesIO",
"(",
")",
"image",
".",
"save",
"(",
"bytes",
",",
"format",
"=",
"self",
".",
"format",
")",
"bytes",
".",
"seek",
"(",
"0",
... | r"""
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesIO object) | [
"r",
"Tuple",
"with",
"a",
"CAPTCHA",
"text",
"and",
"a",
"BytesIO",
"object",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L128-L142 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha.write | def write(self, file):
r"""
Save CAPTCHA image in given filepath.
Property calls self.image and saves image contents in a file,
returning CAPTCHA text and filepath as a tuple.
See: image.
:param file:
Path to file, where CAPTCHA image will be saved.
... | python | def write(self, file):
r"""
Save CAPTCHA image in given filepath.
Property calls self.image and saves image contents in a file,
returning CAPTCHA text and filepath as a tuple.
See: image.
:param file:
Path to file, where CAPTCHA image will be saved.
... | [
"def",
"write",
"(",
"self",
",",
"file",
")",
":",
"r",
"text",
",",
"image",
"=",
"self",
".",
"image",
"image",
".",
"save",
"(",
"file",
",",
"format",
"=",
"self",
".",
"format",
")",
"return",
"(",
"text",
",",
"file",
")"
] | r"""
Save CAPTCHA image in given filepath.
Property calls self.image and saves image contents in a file,
returning CAPTCHA text and filepath as a tuple.
See: image.
:param file:
Path to file, where CAPTCHA image will be saved.
:returns: ``tuple`` (CAPTCHA te... | [
"r",
"Save",
"CAPTCHA",
"image",
"in",
"given",
"filepath",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L144-L158 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha.text | def text(self):
"""Text received from self.source."""
if isinstance(self.source, str):
return self.source
else:
return self.source() | python | def text(self):
"""Text received from self.source."""
if isinstance(self.source, str):
return self.source
else:
return self.source() | [
"def",
"text",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"source",
",",
"str",
")",
":",
"return",
"self",
".",
"source",
"else",
":",
"return",
"self",
".",
"source",
"(",
")"
] | Text received from self.source. | [
"Text",
"received",
"from",
"self",
".",
"source",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L172-L177 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._writeText | def _writeText(self, image, text, pos):
"""Write morphed text in Image object."""
offset = 0
x, y = pos
for c in text:
# Write letter
c_size = self.font.getsize(c)
c_image = Image.new('RGBA', c_size, (0, 0, 0, 0))
c_draw = ImageDraw.Draw(c... | python | def _writeText(self, image, text, pos):
"""Write morphed text in Image object."""
offset = 0
x, y = pos
for c in text:
# Write letter
c_size = self.font.getsize(c)
c_image = Image.new('RGBA', c_size, (0, 0, 0, 0))
c_draw = ImageDraw.Draw(c... | [
"def",
"_writeText",
"(",
"self",
",",
"image",
",",
"text",
",",
"pos",
")",
":",
"offset",
"=",
"0",
"x",
",",
"y",
"=",
"pos",
"for",
"c",
"in",
"text",
":",
"c_size",
"=",
"self",
".",
"font",
".",
"getsize",
"(",
"c",
")",
"c_image",
"=",
... | Write morphed text in Image object. | [
"Write",
"morphed",
"text",
"in",
"Image",
"object",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L267-L284 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._drawLine | def _drawLine(self, image):
"""Draw morphed line in Image object."""
w, h = image.size
w *= 5
h *= 5
l_image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
l_draw = ImageDraw.Draw(l_image)
x1 = int(w * random.uniform(0, 0.1))
y1 = int(h * random.uniform(0, 1)... | python | def _drawLine(self, image):
"""Draw morphed line in Image object."""
w, h = image.size
w *= 5
h *= 5
l_image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
l_draw = ImageDraw.Draw(l_image)
x1 = int(w * random.uniform(0, 0.1))
y1 = int(h * random.uniform(0, 1)... | [
"def",
"_drawLine",
"(",
"self",
",",
"image",
")",
":",
"w",
",",
"h",
"=",
"image",
".",
"size",
"w",
"*=",
"5",
"h",
"*=",
"5",
"l_image",
"=",
"Image",
".",
"new",
"(",
"'RGBA'",
",",
"(",
"w",
",",
"h",
")",
",",
"(",
"0",
",",
"0",
... | Draw morphed line in Image object. | [
"Draw",
"morphed",
"line",
"in",
"Image",
"object",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L286-L312 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._whiteNoise | def _whiteNoise(self, size):
"""Generate white noise and merge it with given Image object."""
if self.noise > 0.003921569: # 1./255.
w, h = size
pixel = (lambda noise: round(255 * random.uniform(1-noise, 1)))
n_image = Image.new('RGB', size, (0, 0, 0, 0))
... | python | def _whiteNoise(self, size):
"""Generate white noise and merge it with given Image object."""
if self.noise > 0.003921569: # 1./255.
w, h = size
pixel = (lambda noise: round(255 * random.uniform(1-noise, 1)))
n_image = Image.new('RGB', size, (0, 0, 0, 0))
... | [
"def",
"_whiteNoise",
"(",
"self",
",",
"size",
")",
":",
"if",
"self",
".",
"noise",
">",
"0.003921569",
":",
"w",
",",
"h",
"=",
"size",
"pixel",
"=",
"(",
"lambda",
"noise",
":",
"round",
"(",
"255",
"*",
"random",
".",
"uniform",
"(",
"1",
"-... | Generate white noise and merge it with given Image object. | [
"Generate",
"white",
"noise",
"and",
"merge",
"it",
"with",
"given",
"Image",
"object",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L314-L327 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._rndLetterTransform | def _rndLetterTransform(self, image):
"""Randomly morph a single character."""
w, h = image.size
dx = w * random.uniform(0.2, 0.7)
dy = h * random.uniform(0.2, 0.7)
x1, y1 = self.__class__._rndPointDisposition(dx, dy)
x2, y2 = self.__class__._rndPointDisposition(dx, dy)... | python | def _rndLetterTransform(self, image):
"""Randomly morph a single character."""
w, h = image.size
dx = w * random.uniform(0.2, 0.7)
dy = h * random.uniform(0.2, 0.7)
x1, y1 = self.__class__._rndPointDisposition(dx, dy)
x2, y2 = self.__class__._rndPointDisposition(dx, dy)... | [
"def",
"_rndLetterTransform",
"(",
"self",
",",
"image",
")",
":",
"w",
",",
"h",
"=",
"image",
".",
"size",
"dx",
"=",
"w",
"*",
"random",
".",
"uniform",
"(",
"0.2",
",",
"0.7",
")",
"dy",
"=",
"h",
"*",
"random",
".",
"uniform",
"(",
"0.2",
... | Randomly morph a single character. | [
"Randomly",
"morph",
"a",
"single",
"character",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L329-L345 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._rndPointDisposition | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | python | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | [
"def",
"_rndPointDisposition",
"(",
"dx",
",",
"dy",
")",
":",
"x",
"=",
"int",
"(",
"random",
".",
"uniform",
"(",
"-",
"dx",
",",
"dx",
")",
")",
"y",
"=",
"int",
"(",
"random",
".",
"uniform",
"(",
"-",
"dy",
",",
"dy",
")",
")",
"return",
... | Return random disposition point. | [
"Return",
"random",
"disposition",
"point",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L363-L367 | train |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._quadPoints | def _quadPoints(size, disp1, disp2):
"""Return points for QUAD transformation."""
w, h = size
x1, y1 = disp1
x2, y2 = disp2
return (
x1, -y1,
-x1, h + y2,
w + x2, h - y2,
w - x2, y1
) | python | def _quadPoints(size, disp1, disp2):
"""Return points for QUAD transformation."""
w, h = size
x1, y1 = disp1
x2, y2 = disp2
return (
x1, -y1,
-x1, h + y2,
w + x2, h - y2,
w - x2, y1
) | [
"def",
"_quadPoints",
"(",
"size",
",",
"disp1",
",",
"disp2",
")",
":",
"w",
",",
"h",
"=",
"size",
"x1",
",",
"y1",
"=",
"disp1",
"x2",
",",
"y2",
"=",
"disp2",
"return",
"(",
"x1",
",",
"-",
"y1",
",",
"-",
"x1",
",",
"h",
"+",
"y2",
","... | Return points for QUAD transformation. | [
"Return",
"points",
"for",
"QUAD",
"transformation",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L370-L381 | train |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/bottle.py | BottlePlugin.path_helper | def path_helper(self, operations, view, **kwargs):
"""Path helper that allows passing a bottle view function."""
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
app = kwargs.get('app', _default_app)
route = self._route_for_view(app, view)
return self.bo... | python | def path_helper(self, operations, view, **kwargs):
"""Path helper that allows passing a bottle view function."""
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
app = kwargs.get('app', _default_app)
route = self._route_for_view(app, view)
return self.bo... | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"view",
",",
"**",
"kwargs",
")",
":",
"operations",
".",
"update",
"(",
"yaml_utils",
".",
"load_operations_from_docstring",
"(",
"view",
".",
"__doc__",
")",
")",
"app",
"=",
"kwargs",
".",
"get"... | Path helper that allows passing a bottle view function. | [
"Path",
"helper",
"that",
"allows",
"passing",
"a",
"bottle",
"view",
"function",
"."
] | 21b0b4135c073d2ada47a4228377e63bc03ac7f9 | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/bottle.py#L56-L61 | train |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/flask.py | FlaskPlugin.path_helper | def path_helper(self, operations, view, app=None, **kwargs):
"""Path helper that allows passing a Flask view function."""
rule = self._rule_for_view(view, app=app)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(vie... | python | def path_helper(self, operations, view, app=None, **kwargs):
"""Path helper that allows passing a Flask view function."""
rule = self._rule_for_view(view, app=app)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(vie... | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"view",
",",
"app",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"rule",
"=",
"self",
".",
"_rule_for_view",
"(",
"view",
",",
"app",
"=",
"app",
")",
"operations",
".",
"update",
"(",
"yaml_u... | Path helper that allows passing a Flask view function. | [
"Path",
"helper",
"that",
"allows",
"passing",
"a",
"Flask",
"view",
"function",
"."
] | 21b0b4135c073d2ada47a4228377e63bc03ac7f9 | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/flask.py#L113-L123 | train |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/tornado.py | TornadoPlugin._operations_from_methods | def _operations_from_methods(handler_class):
"""Generator of operations described in handler's http methods
:param handler_class:
:type handler_class: RequestHandler descendant
"""
for httpmethod in yaml_utils.PATH_KEYS:
method = getattr(handler_class, httpmethod)
... | python | def _operations_from_methods(handler_class):
"""Generator of operations described in handler's http methods
:param handler_class:
:type handler_class: RequestHandler descendant
"""
for httpmethod in yaml_utils.PATH_KEYS:
method = getattr(handler_class, httpmethod)
... | [
"def",
"_operations_from_methods",
"(",
"handler_class",
")",
":",
"for",
"httpmethod",
"in",
"yaml_utils",
".",
"PATH_KEYS",
":",
"method",
"=",
"getattr",
"(",
"handler_class",
",",
"httpmethod",
")",
"operation_data",
"=",
"yaml_utils",
".",
"load_yaml_from_docst... | Generator of operations described in handler's http methods
:param handler_class:
:type handler_class: RequestHandler descendant | [
"Generator",
"of",
"operations",
"described",
"in",
"handler",
"s",
"http",
"methods"
] | 21b0b4135c073d2ada47a4228377e63bc03ac7f9 | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/tornado.py#L45-L56 | train |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/tornado.py | TornadoPlugin.tornadopath2openapi | def tornadopath2openapi(urlspec, method):
"""Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function
"""
if sys.version_info >= (3, 3):
args = list(inspect.sig... | python | def tornadopath2openapi(urlspec, method):
"""Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function
"""
if sys.version_info >= (3, 3):
args = list(inspect.sig... | [
"def",
"tornadopath2openapi",
"(",
"urlspec",
",",
"method",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"3",
")",
":",
"args",
"=",
"list",
"(",
"inspect",
".",
"signature",
"(",
"method",
")",
".",
"parameters",
".",
"keys",
"(... | Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function | [
"Convert",
"Tornado",
"URLSpec",
"to",
"OpenAPI",
"-",
"compliant",
"path",
"."
] | 21b0b4135c073d2ada47a4228377e63bc03ac7f9 | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/tornado.py#L59-L81 | train |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/tornado.py | TornadoPlugin.path_helper | def path_helper(self, operations, urlspec, **kwargs):
"""Path helper that allows passing a Tornado URLSpec or tuple."""
if not isinstance(urlspec, URLSpec):
urlspec = URLSpec(*urlspec)
for operation in self._operations_from_methods(urlspec.handler_class):
operations.updat... | python | def path_helper(self, operations, urlspec, **kwargs):
"""Path helper that allows passing a Tornado URLSpec or tuple."""
if not isinstance(urlspec, URLSpec):
urlspec = URLSpec(*urlspec)
for operation in self._operations_from_methods(urlspec.handler_class):
operations.updat... | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"urlspec",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"urlspec",
",",
"URLSpec",
")",
":",
"urlspec",
"=",
"URLSpec",
"(",
"*",
"urlspec",
")",
"for",
"operation",
"in",
"se... | Path helper that allows passing a Tornado URLSpec or tuple. | [
"Path",
"helper",
"that",
"allows",
"passing",
"a",
"Tornado",
"URLSpec",
"or",
"tuple",
"."
] | 21b0b4135c073d2ada47a4228377e63bc03ac7f9 | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/tornado.py#L92-L104 | train |
onelogin/onelogin-python-sdk | src/onelogin/api/client.py | OneLoginClient.generate_mfa_token | def generate_mfa_token(self, user_id, expires_in=259200, reusable=False):
"""
Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period.
For example, use this token for account recovery.
:param user_id: Id of the user
:type user_id... | python | def generate_mfa_token(self, user_id, expires_in=259200, reusable=False):
"""
Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period.
For example, use this token for account recovery.
:param user_id: Id of the user
:type user_id... | [
"def",
"generate_mfa_token",
"(",
"self",
",",
"user_id",
",",
"expires_in",
"=",
"259200",
",",
"reusable",
"=",
"False",
")",
":",
"self",
".",
"clean_error",
"(",
")",
"try",
":",
"url",
"=",
"self",
".",
"get_url",
"(",
"Constants",
".",
"GENERATE_MF... | Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period.
For example, use this token for account recovery.
:param user_id: Id of the user
:type user_id: int
:param expires_in: Set the duration of the token in seconds.
... | [
"Use",
"to",
"generate",
"a",
"temporary",
"MFA",
"token",
"that",
"can",
"be",
"used",
"in",
"place",
"of",
"other",
"MFA",
"tokens",
"for",
"a",
"set",
"time",
"period",
".",
"For",
"example",
"use",
"this",
"token",
"for",
"account",
"recovery",
"."
] | 2891b2efbd0a94298611f7c9c220a1f32126d339 | https://github.com/onelogin/onelogin-python-sdk/blob/2891b2efbd0a94298611f7c9c220a1f32126d339/src/onelogin/api/client.py#L1039-L1081 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/utils.py | camel_to_snake | def camel_to_snake(camel):
"""Convert camelCase to snake_case."""
ret = []
last_lower = False
for char in camel:
current_upper = char.upper() == char
if current_upper and last_lower:
ret.append("_")
ret.append(char.lower())
else:
ret.append(cha... | python | def camel_to_snake(camel):
"""Convert camelCase to snake_case."""
ret = []
last_lower = False
for char in camel:
current_upper = char.upper() == char
if current_upper and last_lower:
ret.append("_")
ret.append(char.lower())
else:
ret.append(cha... | [
"def",
"camel_to_snake",
"(",
"camel",
")",
":",
"ret",
"=",
"[",
"]",
"last_lower",
"=",
"False",
"for",
"char",
"in",
"camel",
":",
"current_upper",
"=",
"char",
".",
"upper",
"(",
")",
"==",
"char",
"if",
"current_upper",
"and",
"last_lower",
":",
"... | Convert camelCase to snake_case. | [
"Convert",
"camelCase",
"to",
"snake_case",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/utils.py#L69-L81 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | IdGenerator.register_id | def register_id(self, id_string):
"""Register a manually assigned id as used, to avoid collisions.
"""
try:
prefix, count = id_string.rsplit("_", 1)
count = int(count)
except ValueError:
# We don't need to worry about ids that don't match our pattern
... | python | def register_id(self, id_string):
"""Register a manually assigned id as used, to avoid collisions.
"""
try:
prefix, count = id_string.rsplit("_", 1)
count = int(count)
except ValueError:
# We don't need to worry about ids that don't match our pattern
... | [
"def",
"register_id",
"(",
"self",
",",
"id_string",
")",
":",
"try",
":",
"prefix",
",",
"count",
"=",
"id_string",
".",
"rsplit",
"(",
"\"_\"",
",",
"1",
")",
"count",
"=",
"int",
"(",
"count",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",... | Register a manually assigned id as used, to avoid collisions. | [
"Register",
"a",
"manually",
"assigned",
"id",
"as",
"used",
"to",
"avoid",
"collisions",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L35-L46 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | AMDSec.parse | def parse(cls, root):
"""
Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object.
"""
if root.tag != utils.lxmlns("mets") + "amdSec":
raise exceptions.ParseError(
"AMDSec can only parse amdSec elements wit... | python | def parse(cls, root):
"""
Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object.
"""
if root.tag != utils.lxmlns("mets") + "amdSec":
raise exceptions.ParseError(
"AMDSec can only parse amdSec elements wit... | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"if",
"root",
".",
"tag",
"!=",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
"\"amdSec\"",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"AMDSec can only parse amdSec elements with METS namespace.\... | Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object. | [
"Create",
"a",
"new",
"AMDSec",
"by",
"parsing",
"root",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L88-L103 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | AMDSec.serialize | def serialize(self, now=None):
"""
Serialize this amdSec and all children to lxml Element and return it.
:param str now: Default value for CREATED in children if none set
:return: amdSec Element with all children
"""
if self._tree is not None:
return self._tr... | python | def serialize(self, now=None):
"""
Serialize this amdSec and all children to lxml Element and return it.
:param str now: Default value for CREATED in children if none set
:return: amdSec Element with all children
"""
if self._tree is not None:
return self._tr... | [
"def",
"serialize",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"if",
"self",
".",
"_tree",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_tree",
"el",
"=",
"etree",
".",
"Element",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
... | Serialize this amdSec and all children to lxml Element and return it.
:param str now: Default value for CREATED in children if none set
:return: amdSec Element with all children | [
"Serialize",
"this",
"amdSec",
"and",
"all",
"children",
"to",
"lxml",
"Element",
"and",
"return",
"it",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L105-L118 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | AltRecordID.parse | def parse(cls, element):
"""
Create a new AltRecordID by parsing root.
:param element: Element to be parsed into an AltRecordID.
:raises exceptions.ParseError: If element is not a valid altRecordID.
"""
if element.tag != cls.ALT_RECORD_ID_TAG:
raise exception... | python | def parse(cls, element):
"""
Create a new AltRecordID by parsing root.
:param element: Element to be parsed into an AltRecordID.
:raises exceptions.ParseError: If element is not a valid altRecordID.
"""
if element.tag != cls.ALT_RECORD_ID_TAG:
raise exception... | [
"def",
"parse",
"(",
"cls",
",",
"element",
")",
":",
"if",
"element",
".",
"tag",
"!=",
"cls",
".",
"ALT_RECORD_ID_TAG",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"u\"AltRecordID got unexpected tag {}; expected {}\"",
".",
"format",
"(",
"element",
".... | Create a new AltRecordID by parsing root.
:param element: Element to be parsed into an AltRecordID.
:raises exceptions.ParseError: If element is not a valid altRecordID. | [
"Create",
"a",
"new",
"AltRecordID",
"by",
"parsing",
"root",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L142-L156 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | Agent.parse | def parse(cls, element):
"""
Create a new Agent by parsing root.
:param element: Element to be parsed into an Agent.
:raises exceptions.ParseError: If element is not a valid agent.
"""
if element.tag != cls.AGENT_TAG:
raise exceptions.ParseError(
... | python | def parse(cls, element):
"""
Create a new Agent by parsing root.
:param element: Element to be parsed into an Agent.
:raises exceptions.ParseError: If element is not a valid agent.
"""
if element.tag != cls.AGENT_TAG:
raise exceptions.ParseError(
... | [
"def",
"parse",
"(",
"cls",
",",
"element",
")",
":",
"if",
"element",
".",
"tag",
"!=",
"cls",
".",
"AGENT_TAG",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"u\"Agent got unexpected tag {}; expected {}\"",
".",
"format",
"(",
"element",
".",
"tag",
... | Create a new Agent by parsing root.
:param element: Element to be parsed into an Agent.
:raises exceptions.ParseError: If element is not a valid agent. | [
"Create",
"a",
"new",
"Agent",
"by",
"parsing",
"root",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L211-L240 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | SubSection.get_status | def get_status(self):
"""
Returns the STATUS when serializing.
Calculates based on the subsection type and if it's replacing anything.
:returns: None or the STATUS string.
"""
if self.status is not None:
return self.status
if self.subsection == "dmdS... | python | def get_status(self):
"""
Returns the STATUS when serializing.
Calculates based on the subsection type and if it's replacing anything.
:returns: None or the STATUS string.
"""
if self.status is not None:
return self.status
if self.subsection == "dmdS... | [
"def",
"get_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"is",
"not",
"None",
":",
"return",
"self",
".",
"status",
"if",
"self",
".",
"subsection",
"==",
"\"dmdSec\"",
":",
"if",
"self",
".",
"older",
"is",
"None",
":",
"return",
"\"... | Returns the STATUS when serializing.
Calculates based on the subsection type and if it's replacing anything.
:returns: None or the STATUS string. | [
"Returns",
"the",
"STATUS",
"when",
"serializing",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L327-L348 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | SubSection.replace_with | def replace_with(self, new_subsection):
"""
Replace this SubSection with new_subsection.
Replacing SubSection must be the same time. That is, you can only
replace a dmdSec with another dmdSec, or a rightsMD with a rightsMD etc.
:param new_subsection: Updated version of this Su... | python | def replace_with(self, new_subsection):
"""
Replace this SubSection with new_subsection.
Replacing SubSection must be the same time. That is, you can only
replace a dmdSec with another dmdSec, or a rightsMD with a rightsMD etc.
:param new_subsection: Updated version of this Su... | [
"def",
"replace_with",
"(",
"self",
",",
"new_subsection",
")",
":",
"if",
"self",
".",
"subsection",
"!=",
"new_subsection",
".",
"subsection",
":",
"raise",
"exceptions",
".",
"MetsError",
"(",
"\"Must replace a SubSection with one of the same type.\"",
")",
"self",... | Replace this SubSection with new_subsection.
Replacing SubSection must be the same time. That is, you can only
replace a dmdSec with another dmdSec, or a rightsMD with a rightsMD etc.
:param new_subsection: Updated version of this SubSection
:type new_subsection: :class:`SubSection` | [
"Replace",
"this",
"SubSection",
"with",
"new_subsection",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L350-L367 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | SubSection.parse | def parse(cls, root):
"""
Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child o... | python | def parse(cls, root):
"""
Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child o... | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"subsection",
"=",
"root",
".",
"tag",
".",
"replace",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
",",
"\"\"",
",",
"1",
")",
"if",
"subsection",
"not",
"in",
"cls",
".",
"ALLOWED_SUBSECTIONS... | Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child of root is not mdRef or mdWrap. | [
"Create",
"a",
"new",
"SubSection",
"by",
"parsing",
"root",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L370-L400 | train |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | SubSection.serialize | def serialize(self, now=None):
"""
Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children
"""
created = self.created if ... | python | def serialize(self, now=None):
"""
Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children
"""
created = self.created if ... | [
"def",
"serialize",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"created",
"=",
"self",
".",
"created",
"if",
"self",
".",
"created",
"is",
"not",
"None",
"else",
"now",
"el",
"=",
"etree",
".",
"Element",
"(",
"utils",
".",
"lxmlns",
"(",
"\"m... | Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children | [
"Serialize",
"this",
"SubSection",
"and",
"all",
"children",
"to",
"lxml",
"Element",
"and",
"return",
"it",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L402-L418 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _get_el_attributes | def _get_el_attributes(lxml_el, ns=None, nsmap=None):
"""Return the XML attributes of lxml ``Element`` instance lxml_el as a dict
where namespaced attributes are represented via colon-delimiting and using
snake case.
"""
attrs = {}
for attr, val in lxml_el.items():
attr = _to_colon_ns(at... | python | def _get_el_attributes(lxml_el, ns=None, nsmap=None):
"""Return the XML attributes of lxml ``Element`` instance lxml_el as a dict
where namespaced attributes are represented via colon-delimiting and using
snake case.
"""
attrs = {}
for attr, val in lxml_el.items():
attr = _to_colon_ns(at... | [
"def",
"_get_el_attributes",
"(",
"lxml_el",
",",
"ns",
"=",
"None",
",",
"nsmap",
"=",
"None",
")",
":",
"attrs",
"=",
"{",
"}",
"for",
"attr",
",",
"val",
"in",
"lxml_el",
".",
"items",
"(",
")",
":",
"attr",
"=",
"_to_colon_ns",
"(",
"attr",
","... | Return the XML attributes of lxml ``Element`` instance lxml_el as a dict
where namespaced attributes are represented via colon-delimiting and using
snake case. | [
"Return",
"the",
"XML",
"attributes",
"of",
"lxml",
"Element",
"instance",
"lxml_el",
"as",
"a",
"dict",
"where",
"namespaced",
"attributes",
"are",
"represented",
"via",
"colon",
"-",
"delimiting",
"and",
"using",
"snake",
"case",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L662-L671 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _lxml_el_to_data | def _lxml_el_to_data(lxml_el, ns, nsmap, snake=True):
"""Convert an ``lxml._Element`` instance to a Python tuple."""
tag_name = _to_colon_ns(lxml_el.tag, default_ns=ns, nsmap=nsmap)
ret = [tag_name]
attributes = _get_el_attributes(lxml_el, ns=ns, nsmap=nsmap)
if attributes:
ret.append(attrib... | python | def _lxml_el_to_data(lxml_el, ns, nsmap, snake=True):
"""Convert an ``lxml._Element`` instance to a Python tuple."""
tag_name = _to_colon_ns(lxml_el.tag, default_ns=ns, nsmap=nsmap)
ret = [tag_name]
attributes = _get_el_attributes(lxml_el, ns=ns, nsmap=nsmap)
if attributes:
ret.append(attrib... | [
"def",
"_lxml_el_to_data",
"(",
"lxml_el",
",",
"ns",
",",
"nsmap",
",",
"snake",
"=",
"True",
")",
":",
"tag_name",
"=",
"_to_colon_ns",
"(",
"lxml_el",
".",
"tag",
",",
"default_ns",
"=",
"ns",
",",
"nsmap",
"=",
"nsmap",
")",
"ret",
"=",
"[",
"tag... | Convert an ``lxml._Element`` instance to a Python tuple. | [
"Convert",
"an",
"lxml",
".",
"_Element",
"instance",
"to",
"a",
"Python",
"tuple",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L674-L686 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | premis_to_data | def premis_to_data(premis_lxml_el):
"""Transform a PREMIS ``lxml._Element`` instance to a Python tuple."""
premis_version = premis_lxml_el.get("version", utils.PREMIS_VERSION)
nsmap = utils.PREMIS_VERSIONS_MAP[premis_version]["namespaces"]
return _lxml_el_to_data(premis_lxml_el, "premis", nsmap) | python | def premis_to_data(premis_lxml_el):
"""Transform a PREMIS ``lxml._Element`` instance to a Python tuple."""
premis_version = premis_lxml_el.get("version", utils.PREMIS_VERSION)
nsmap = utils.PREMIS_VERSIONS_MAP[premis_version]["namespaces"]
return _lxml_el_to_data(premis_lxml_el, "premis", nsmap) | [
"def",
"premis_to_data",
"(",
"premis_lxml_el",
")",
":",
"premis_version",
"=",
"premis_lxml_el",
".",
"get",
"(",
"\"version\"",
",",
"utils",
".",
"PREMIS_VERSION",
")",
"nsmap",
"=",
"utils",
".",
"PREMIS_VERSIONS_MAP",
"[",
"premis_version",
"]",
"[",
"\"na... | Transform a PREMIS ``lxml._Element`` instance to a Python tuple. | [
"Transform",
"a",
"PREMIS",
"lxml",
".",
"_Element",
"instance",
"to",
"a",
"Python",
"tuple",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L718-L722 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | data_find | def data_find(data, path):
"""Find and return the first element-as-tuple in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elm = [
el
for el in data
if isinstance(el, (tuple, list)) and el[0] == path_parts[0]
... | python | def data_find(data, path):
"""Find and return the first element-as-tuple in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elm = [
el
for el in data
if isinstance(el, (tuple, list)) and el[0] == path_parts[0]
... | [
"def",
"data_find",
"(",
"data",
",",
"path",
")",
":",
"path_parts",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"try",
":",
"sub_elm",
"=",
"[",
"el",
"for",
"el",
"in",
"data",
"if",
"isinstance",
"(",
"el",
",",
"(",
"tuple",
",",
"list",
"... | Find and return the first element-as-tuple in tuple ``data`` using simplified
XPath ``path``. | [
"Find",
"and",
"return",
"the",
"first",
"element",
"-",
"as",
"-",
"tuple",
"in",
"tuple",
"data",
"using",
"simplified",
"XPath",
"path",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L725-L741 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | tuple_to_schema | def tuple_to_schema(tuple_):
"""Convert a tuple representing an XML data structure into a schema tuple
that can be used in the ``.schema`` property of a sub-class of
PREMISElement.
"""
schema = []
for element in tuple_:
if isinstance(element, (tuple, list)):
try:
... | python | def tuple_to_schema(tuple_):
"""Convert a tuple representing an XML data structure into a schema tuple
that can be used in the ``.schema`` property of a sub-class of
PREMISElement.
"""
schema = []
for element in tuple_:
if isinstance(element, (tuple, list)):
try:
... | [
"def",
"tuple_to_schema",
"(",
"tuple_",
")",
":",
"schema",
"=",
"[",
"]",
"for",
"element",
"in",
"tuple_",
":",
"if",
"isinstance",
"(",
"element",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"element",
"[",... | Convert a tuple representing an XML data structure into a schema tuple
that can be used in the ``.schema`` property of a sub-class of
PREMISElement. | [
"Convert",
"a",
"tuple",
"representing",
"an",
"XML",
"data",
"structure",
"into",
"a",
"schema",
"tuple",
"that",
"can",
"be",
"used",
"in",
"the",
".",
"schema",
"property",
"of",
"a",
"sub",
"-",
"class",
"of",
"PREMISElement",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L744-L761 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | generate_element_class | def generate_element_class(tuple_instance):
"""Dynamically create a sub-class of PREMISElement given
``tuple_instance``, which is a tuple representing an XML data structure.
"""
schema = tuple_to_schema(tuple_instance)
def defaults(self):
return {}
def schema_getter(self):
retu... | python | def generate_element_class(tuple_instance):
"""Dynamically create a sub-class of PREMISElement given
``tuple_instance``, which is a tuple representing an XML data structure.
"""
schema = tuple_to_schema(tuple_instance)
def defaults(self):
return {}
def schema_getter(self):
retu... | [
"def",
"generate_element_class",
"(",
"tuple_instance",
")",
":",
"schema",
"=",
"tuple_to_schema",
"(",
"tuple_instance",
")",
"def",
"defaults",
"(",
"self",
")",
":",
"return",
"{",
"}",
"def",
"schema_getter",
"(",
"self",
")",
":",
"return",
"schema",
"... | Dynamically create a sub-class of PREMISElement given
``tuple_instance``, which is a tuple representing an XML data structure. | [
"Dynamically",
"create",
"a",
"sub",
"-",
"class",
"of",
"PREMISElement",
"given",
"tuple_instance",
"which",
"is",
"a",
"tuple",
"representing",
"an",
"XML",
"data",
"structure",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L764-L781 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | data_find_all | def data_find_all(data, path, dyn_cls=False):
"""Find and return all element-as-tuples in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elms = tuple(
el
for el in data
if isinstance(el, (tuple, list)) and el[0] =... | python | def data_find_all(data, path, dyn_cls=False):
"""Find and return all element-as-tuples in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elms = tuple(
el
for el in data
if isinstance(el, (tuple, list)) and el[0] =... | [
"def",
"data_find_all",
"(",
"data",
",",
"path",
",",
"dyn_cls",
"=",
"False",
")",
":",
"path_parts",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"try",
":",
"sub_elms",
"=",
"tuple",
"(",
"el",
"for",
"el",
"in",
"data",
"if",
"isinstance",
"(",... | Find and return all element-as-tuples in tuple ``data`` using simplified
XPath ``path``. | [
"Find",
"and",
"return",
"all",
"element",
"-",
"as",
"-",
"tuples",
"in",
"tuple",
"data",
"using",
"simplified",
"XPath",
"path",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L784-L808 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | data_find_text | def data_find_text(data, path):
"""Return the text value of the element-as-tuple in tuple ``data`` using
simplified XPath ``path``.
"""
el = data_find(data, path)
if not isinstance(el, (list, tuple)):
return None
texts = [child for child in el[1:] if not isinstance(child, (tuple, list, d... | python | def data_find_text(data, path):
"""Return the text value of the element-as-tuple in tuple ``data`` using
simplified XPath ``path``.
"""
el = data_find(data, path)
if not isinstance(el, (list, tuple)):
return None
texts = [child for child in el[1:] if not isinstance(child, (tuple, list, d... | [
"def",
"data_find_text",
"(",
"data",
",",
"path",
")",
":",
"el",
"=",
"data_find",
"(",
"data",
",",
"path",
")",
"if",
"not",
"isinstance",
"(",
"el",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"None",
"texts",
"=",
"[",
"child",
... | Return the text value of the element-as-tuple in tuple ``data`` using
simplified XPath ``path``. | [
"Return",
"the",
"text",
"value",
"of",
"the",
"element",
"-",
"as",
"-",
"tuple",
"in",
"tuple",
"data",
"using",
"simplified",
"XPath",
"path",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L811-L829 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _generate_data | def _generate_data(schema, elements, attributes=None, path=None):
"""Using tree-as-tuple ``schema`` as guide, return a tree-as-tuple ``data``
representing a PREMIS XML element, where the values in dict ``elements`` and
the values in dict ``attributes`` are located in the appropriate locations
in the ``d... | python | def _generate_data(schema, elements, attributes=None, path=None):
"""Using tree-as-tuple ``schema`` as guide, return a tree-as-tuple ``data``
representing a PREMIS XML element, where the values in dict ``elements`` and
the values in dict ``attributes`` are located in the appropriate locations
in the ``d... | [
"def",
"_generate_data",
"(",
"schema",
",",
"elements",
",",
"attributes",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"[",
"]",
"attributes",
"=",
"attributes",
"or",
"{",
"}",
"tag_name",
"=",
"schema",
"[",
"0",
"]... | Using tree-as-tuple ``schema`` as guide, return a tree-as-tuple ``data``
representing a PREMIS XML element, where the values in dict ``elements`` and
the values in dict ``attributes`` are located in the appropriate locations
in the ``data`` tree structure. | [
"Using",
"tree",
"-",
"as",
"-",
"tuple",
"schema",
"as",
"guide",
"return",
"a",
"tree",
"-",
"as",
"-",
"tuple",
"data",
"representing",
"a",
"PREMIS",
"XML",
"element",
"where",
"the",
"values",
"in",
"dict",
"elements",
"and",
"the",
"values",
"in",
... | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L865-L903 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | el_is_empty | def el_is_empty(el):
"""Return ``True`` if tuple ``el`` represents an empty XML element."""
if len(el) == 1 and not isinstance(el[0], (list, tuple)):
return True
subels_are_empty = []
for subel in el:
if isinstance(subel, (list, tuple)):
subels_are_empty.append(el_is_empty(su... | python | def el_is_empty(el):
"""Return ``True`` if tuple ``el`` represents an empty XML element."""
if len(el) == 1 and not isinstance(el[0], (list, tuple)):
return True
subels_are_empty = []
for subel in el:
if isinstance(subel, (list, tuple)):
subels_are_empty.append(el_is_empty(su... | [
"def",
"el_is_empty",
"(",
"el",
")",
":",
"if",
"len",
"(",
"el",
")",
"==",
"1",
"and",
"not",
"isinstance",
"(",
"el",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"True",
"subels_are_empty",
"=",
"[",
"]",
"for",
... | Return ``True`` if tuple ``el`` represents an empty XML element. | [
"Return",
"True",
"if",
"tuple",
"el",
"represents",
"an",
"empty",
"XML",
"element",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L906-L916 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _premis_version_from_data | def _premis_version_from_data(data):
"""Given tuple ``data`` encoding a PREMIS element, attempt to return the
PREMIS version it is using. If none can be found, return the default PREMIS
version.
"""
for child in data:
if isinstance(child, dict):
version = child.get("version")
... | python | def _premis_version_from_data(data):
"""Given tuple ``data`` encoding a PREMIS element, attempt to return the
PREMIS version it is using. If none can be found, return the default PREMIS
version.
"""
for child in data:
if isinstance(child, dict):
version = child.get("version")
... | [
"def",
"_premis_version_from_data",
"(",
"data",
")",
":",
"for",
"child",
"in",
"data",
":",
"if",
"isinstance",
"(",
"child",
",",
"dict",
")",
":",
"version",
"=",
"child",
".",
"get",
"(",
"\"version\"",
")",
"if",
"version",
":",
"return",
"version"... | Given tuple ``data`` encoding a PREMIS element, attempt to return the
PREMIS version it is using. If none can be found, return the default PREMIS
version. | [
"Given",
"tuple",
"data",
"encoding",
"a",
"PREMIS",
"element",
"attempt",
"to",
"return",
"the",
"PREMIS",
"version",
"it",
"is",
"using",
".",
"If",
"none",
"can",
"be",
"found",
"return",
"the",
"default",
"PREMIS",
"version",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L963-L973 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | PREMISEvent.compression_details | def compression_details(self):
"""Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression.
"""
event_type = self.findtext("event_type")
if event_type != "compression":
raise AttributeError(
'... | python | def compression_details(self):
"""Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression.
"""
event_type = self.findtext("event_type")
if event_type != "compression":
raise AttributeError(
'... | [
"def",
"compression_details",
"(",
"self",
")",
":",
"event_type",
"=",
"self",
".",
"findtext",
"(",
"\"event_type\"",
")",
"if",
"event_type",
"!=",
"\"compression\"",
":",
"raise",
"AttributeError",
"(",
"'PREMIS events of type \"{}\" have no compression'",
"\" detai... | Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression. | [
"Return",
"as",
"a",
"3",
"-",
"tuple",
"this",
"PREMIS",
"compression",
"event",
"s",
"program",
"version",
"and",
"algorithm",
"used",
"to",
"perform",
"the",
"compression",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L387-L408 | train |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | PREMISEvent.encryption_details | def encryption_details(self):
"""Return as a 3-tuple, this PREMIS encryption event's program,
version, and key used to perform the encryption.
"""
event_type = self.findtext("event_type")
if event_type != "encryption":
raise AttributeError(
'PREMIS eve... | python | def encryption_details(self):
"""Return as a 3-tuple, this PREMIS encryption event's program,
version, and key used to perform the encryption.
"""
event_type = self.findtext("event_type")
if event_type != "encryption":
raise AttributeError(
'PREMIS eve... | [
"def",
"encryption_details",
"(",
"self",
")",
":",
"event_type",
"=",
"self",
".",
"findtext",
"(",
"\"event_type\"",
")",
"if",
"event_type",
"!=",
"\"encryption\"",
":",
"raise",
"AttributeError",
"(",
"'PREMIS events of type \"{}\" have no encryption'",
"\" details\... | Return as a 3-tuple, this PREMIS encryption event's program,
version, and key used to perform the encryption. | [
"Return",
"as",
"a",
"3",
"-",
"tuple",
"this",
"PREMIS",
"encryption",
"event",
"s",
"program",
"version",
"and",
"key",
"used",
"to",
"perform",
"the",
"encryption",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L431-L449 | train |
artefactual-labs/mets-reader-writer | metsrw/di.py | has_class_methods | def has_class_methods(*class_method_names):
"""Return a test function that, when given a class, returns ``True`` if that
class has all of the class methods in ``class_method_names``. If an object
is passed to the test function, check for the class methods on its
class.
"""
def test(cls):
... | python | def has_class_methods(*class_method_names):
"""Return a test function that, when given a class, returns ``True`` if that
class has all of the class methods in ``class_method_names``. If an object
is passed to the test function, check for the class methods on its
class.
"""
def test(cls):
... | [
"def",
"has_class_methods",
"(",
"*",
"class_method_names",
")",
":",
"def",
"test",
"(",
"cls",
")",
":",
"if",
"not",
"isinstance",
"(",
"cls",
",",
"type",
")",
":",
"cls",
"=",
"type",
"(",
"cls",
")",
"for",
"class_method_name",
"in",
"class_method_... | Return a test function that, when given a class, returns ``True`` if that
class has all of the class methods in ``class_method_names``. If an object
is passed to the test function, check for the class methods on its
class. | [
"Return",
"a",
"test",
"function",
"that",
"when",
"given",
"a",
"class",
"returns",
"True",
"if",
"that",
"class",
"has",
"all",
"of",
"the",
"class",
"methods",
"in",
"class_method_names",
".",
"If",
"an",
"object",
"is",
"passed",
"to",
"the",
"test",
... | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/di.py#L136-L155 | train |
artefactual-labs/mets-reader-writer | metsrw/utils.py | _urlendecode | def _urlendecode(url, func):
"""Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts.
"""
parsed = urlparse(url)
for attr in URL_ENCODABLE_PARTS:
parsed = parsed._replace(**{attr: func(getattr(parsed, attr))})
return urlunparse(parsed) | python | def _urlendecode(url, func):
"""Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts.
"""
parsed = urlparse(url)
for attr in URL_ENCODABLE_PARTS:
parsed = parsed._replace(**{attr: func(getattr(parsed, attr))})
return urlunparse(parsed) | [
"def",
"_urlendecode",
"(",
"url",
",",
"func",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"for",
"attr",
"in",
"URL_ENCODABLE_PARTS",
":",
"parsed",
"=",
"parsed",
".",
"_replace",
"(",
"**",
"{",
"attr",
":",
"func",
"(",
"getattr",
"(",
... | Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts. | [
"Encode",
"or",
"decode",
"url",
"by",
"applying",
"func",
"to",
"all",
"of",
"its",
"URL",
"-",
"encodable",
"parts",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/utils.py#L45-L52 | train |
zmathew/django-backbone | backbone/__init__.py | autodiscover | def autodiscover():
"""
Auto-discover INSTALLED_APPS backbone_api.py modules.
"""
# This code is based off django.contrib.admin.__init__
from django.conf import settings
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
... | python | def autodiscover():
"""
Auto-discover INSTALLED_APPS backbone_api.py modules.
"""
# This code is based off django.contrib.admin.__init__
from django.conf import settings
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
... | [
"def",
"autodiscover",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"try",
":",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"import_module",
"except",
"ImportError",
":",
"from",
"django",
".",
"utils",
".",
"impor... | Auto-discover INSTALLED_APPS backbone_api.py modules. | [
"Auto",
"-",
"discover",
"INSTALLED_APPS",
"backbone_api",
".",
"py",
"modules",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/__init__.py#L16-L41 | train |
zmathew/django-backbone | backbone/sites.py | BackboneSite.register | def register(self, backbone_view_class):
"""
Registers the given backbone view class.
"""
if backbone_view_class not in self._registry:
self._registry.append(backbone_view_class) | python | def register(self, backbone_view_class):
"""
Registers the given backbone view class.
"""
if backbone_view_class not in self._registry:
self._registry.append(backbone_view_class) | [
"def",
"register",
"(",
"self",
",",
"backbone_view_class",
")",
":",
"if",
"backbone_view_class",
"not",
"in",
"self",
".",
"_registry",
":",
"self",
".",
"_registry",
".",
"append",
"(",
"backbone_view_class",
")"
] | Registers the given backbone view class. | [
"Registers",
"the",
"given",
"backbone",
"view",
"class",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/sites.py#L10-L15 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.get | def get(self, request, id=None, **kwargs):
"""
Handles get requests for either the collection or an object detail.
"""
if not self.has_get_permission(request):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
if id:
ob... | python | def get(self, request, id=None, **kwargs):
"""
Handles get requests for either the collection or an object detail.
"""
if not self.has_get_permission(request):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
if id:
ob... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"has_get_permission",
"(",
"request",
")",
":",
"return",
"HttpResponseForbidden",
"(",
"_",
"(",
"'You do not have permission to perf... | Handles get requests for either the collection or an object detail. | [
"Handles",
"get",
"requests",
"for",
"either",
"the",
"collection",
"or",
"an",
"object",
"detail",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L38-L49 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.get_object_detail | def get_object_detail(self, request, obj):
"""
Handles get requests for the details of the given object.
"""
if self.display_detail_fields:
display_fields = self.display_detail_fields
else:
display_fields = self.display_fields
data = self.serializ... | python | def get_object_detail(self, request, obj):
"""
Handles get requests for the details of the given object.
"""
if self.display_detail_fields:
display_fields = self.display_detail_fields
else:
display_fields = self.display_fields
data = self.serializ... | [
"def",
"get_object_detail",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"if",
"self",
".",
"display_detail_fields",
":",
"display_fields",
"=",
"self",
".",
"display_detail_fields",
"else",
":",
"display_fields",
"=",
"self",
".",
"display_fields",
"data"... | Handles get requests for the details of the given object. | [
"Handles",
"get",
"requests",
"for",
"the",
"details",
"of",
"the",
"given",
"object",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L51-L61 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.get_collection | def get_collection(self, request, **kwargs):
"""
Handles get requests for the list of objects.
"""
qs = self.queryset(request, **kwargs)
if self.display_collection_fields:
display_fields = self.display_collection_fields
else:
display_fields = self... | python | def get_collection(self, request, **kwargs):
"""
Handles get requests for the list of objects.
"""
qs = self.queryset(request, **kwargs)
if self.display_collection_fields:
display_fields = self.display_collection_fields
else:
display_fields = self... | [
"def",
"get_collection",
"(",
"self",
",",
"request",
",",
"**",
"kwargs",
")",
":",
"qs",
"=",
"self",
".",
"queryset",
"(",
"request",
",",
"**",
"kwargs",
")",
"if",
"self",
".",
"display_collection_fields",
":",
"display_fields",
"=",
"self",
".",
"d... | Handles get requests for the list of objects. | [
"Handles",
"get",
"requests",
"for",
"the",
"list",
"of",
"objects",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L63-L88 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.post | def post(self, request, id=None, **kwargs):
"""
Handles post requests.
"""
if id:
# No posting to an object detail page
return HttpResponseForbidden()
else:
if not self.has_add_permission(request):
return HttpResponseForbidden(_... | python | def post(self, request, id=None, **kwargs):
"""
Handles post requests.
"""
if id:
# No posting to an object detail page
return HttpResponseForbidden()
else:
if not self.has_add_permission(request):
return HttpResponseForbidden(_... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"id",
":",
"return",
"HttpResponseForbidden",
"(",
")",
"else",
":",
"if",
"not",
"self",
".",
"has_add_permission",
"(",
"request",
")",
":",
"r... | Handles post requests. | [
"Handles",
"post",
"requests",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L90-L101 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.add_object | def add_object(self, request):
"""
Adds an object.
"""
try:
# backbone sends data in the body in json format
# Conditional statement is for backwards compatibility with Django <= 1.3
data = json.loads(request.body if hasattr(request, 'body') else reque... | python | def add_object(self, request):
"""
Adds an object.
"""
try:
# backbone sends data in the body in json format
# Conditional statement is for backwards compatibility with Django <= 1.3
data = json.loads(request.body if hasattr(request, 'body') else reque... | [
"def",
"add_object",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
"if",
"hasattr",
"(",
"request",
",",
"'body'",
")",
"else",
"request",
".",
"raw_post_data",
")",
"except",
"ValueE... | Adds an object. | [
"Adds",
"an",
"object",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L103-L133 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.put | def put(self, request, id=None, **kwargs):
"""
Handles put requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_update_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to pe... | python | def put(self, request, id=None, **kwargs):
"""
Handles put requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_update_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to pe... | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"id",
":",
"obj",
"=",
"get_object_or_404",
"(",
"self",
".",
"queryset",
"(",
"request",
")",
",",
"id",
"=",
"id",
")",
"if",
"not",
"self",... | Handles put requests. | [
"Handles",
"put",
"requests",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L135-L147 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.update_object | def update_object(self, request, obj):
"""
Updates an object.
"""
try:
# backbone sends data in the body in json format
# Conditional statement is for backwards compatibility with Django <= 1.3
data = json.loads(request.body if hasattr(request, 'bo... | python | def update_object(self, request, obj):
"""
Updates an object.
"""
try:
# backbone sends data in the body in json format
# Conditional statement is for backwards compatibility with Django <= 1.3
data = json.loads(request.body if hasattr(request, 'bo... | [
"def",
"update_object",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
"if",
"hasattr",
"(",
"request",
",",
"'body'",
")",
"else",
"request",
".",
"raw_post_data",
")",
... | Updates an object. | [
"Updates",
"an",
"object",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L149-L169 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.get_form_instance | def get_form_instance(self, request, data=None, instance=None):
"""
Returns an instantiated form to be used for adding or editing an object.
The `instance` argument is the model instance (passed only if this form
is going to be used for editing an existing object).
"""
d... | python | def get_form_instance(self, request, data=None, instance=None):
"""
Returns an instantiated form to be used for adding or editing an object.
The `instance` argument is the model instance (passed only if this form
is going to be used for editing an existing object).
"""
d... | [
"def",
"get_form_instance",
"(",
"self",
",",
"request",
",",
"data",
"=",
"None",
",",
"instance",
"=",
"None",
")",
":",
"defaults",
"=",
"{",
"}",
"if",
"self",
".",
"form",
":",
"defaults",
"[",
"'form'",
"]",
"=",
"self",
".",
"form",
"if",
"s... | Returns an instantiated form to be used for adding or editing an object.
The `instance` argument is the model instance (passed only if this form
is going to be used for editing an existing object). | [
"Returns",
"an",
"instantiated",
"form",
"to",
"be",
"used",
"for",
"adding",
"or",
"editing",
"an",
"object",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L171-L183 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.delete | def delete(self, request, id=None):
"""
Handles delete requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_delete_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to perfor... | python | def delete(self, request, id=None):
"""
Handles delete requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_delete_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to perfor... | [
"def",
"delete",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
")",
":",
"if",
"id",
":",
"obj",
"=",
"get_object_or_404",
"(",
"self",
".",
"queryset",
"(",
"request",
")",
",",
"id",
"=",
"id",
")",
"if",
"not",
"self",
".",
"has_delete_pe... | Handles delete requests. | [
"Handles",
"delete",
"requests",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L185-L197 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.