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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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"):
__import__(module)
app = default_app.pop()
return app | 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"):
__import__(module)
app = default_app.pop()
return app | [
"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 | 37,300 |
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):
time.sleep(1)
return False | 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):
time.sleep(1)
return False | [
"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 | 37,301 |
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('enableTestCommands', 1)
# Reduce transactionLifetimeLimitSeconds for faster driver testing.
if self.version >= (4, 1) and not self.is_mongos:
params.setdefault('transactionLifetimeLimitSeconds', 3)
# Increase transaction lock timeout to reduce the chance that tests
# fail with LockTimeout: "Unable to acquire lock {...} within 5ms".
if self.version >= (4, 0) and not self.is_mongos:
params.setdefault('maxTransactionLockRequestTimeoutMillis', 25)
config['setParameter'] = params
compressors = config.get('networkMessageCompressors')
if compressors is None:
if self.version >= (4, 1, 7):
# SERVER-38168 added zstd support in 4.1.7.
config['networkMessageCompressors'] = 'zstd,zlib,snappy,noop'
elif self.version >= (3, 5, 9):
# SERVER-27310 added zlib support in 3.5.9.
config['networkMessageCompressors'] = 'zlib,snappy,noop'
elif self.version >= (3, 4):
config['networkMessageCompressors'] = 'snappy,noop' | 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('enableTestCommands', 1)
# Reduce transactionLifetimeLimitSeconds for faster driver testing.
if self.version >= (4, 1) and not self.is_mongos:
params.setdefault('transactionLifetimeLimitSeconds', 3)
# Increase transaction lock timeout to reduce the chance that tests
# fail with LockTimeout: "Unable to acquire lock {...} within 5ms".
if self.version >= (4, 0) and not self.is_mongos:
params.setdefault('maxTransactionLockRequestTimeoutMillis', 25)
config['setParameter'] = params
compressors = config.get('networkMessageCompressors')
if compressors is None:
if self.version >= (4, 1, 7):
# SERVER-38168 added zstd support in 4.1.7.
config['networkMessageCompressors'] = 'zstd,zlib,snappy,noop'
elif self.version >= (3, 5, 9):
# SERVER-27310 added zlib support in 3.5.9.
config['networkMessageCompressors'] = 'zlib,snappy,noop'
elif self.version >= (3, 4):
config['networkMessageCompressors'] = 'snappy,noop' | [
"def",
"__init_config_params",
"(",
"self",
",",
"config",
")",
":",
"if",
"self",
".",
"version",
">=",
"(",
"2",
",",
"4",
")",
":",
"params",
"=",
"config",
".",
"get",
"(",
"'setParameter'",
",",
"{",
"}",
")",
"# Set enableTestCommands by default but ... | 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 | 37,302 |
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[self.auth_source]
if self.x509_extra_user:
auth_dict = {
'name': DEFAULT_SUBJECT, 'mechanism': 'MONGODB-X509'}
else:
auth_dict = {'name': self.login, 'password': self.password}
try:
db.authenticate(**auth_dict)
except:
logger.exception("Could not authenticate to %s with %r"
% (self.hostname, auth_dict))
raise
return 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[self.auth_source]
if self.x509_extra_user:
auth_dict = {
'name': DEFAULT_SUBJECT, 'mechanism': 'MONGODB-X509'}
else:
auth_dict = {'name': self.login, 'password': self.password}
try:
db.authenticate(**auth_dict)
except:
logger.exception("Could not authenticate to %s with %r"
% (self.hostname, auth_dict))
raise
return c | [
"def",
"connection",
"(",
"self",
")",
":",
"c",
"=",
"pymongo",
".",
"MongoClient",
"(",
"self",
".",
"hostname",
",",
"fsync",
"=",
"True",
",",
"socketTimeoutMS",
"=",
"self",
".",
"socket_timeout",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
"connec... | return authenticated connection | [
"return",
"authenticated",
"connection"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/servers.py#L201-L220 | train | 37,303 |
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()
version_output = str(stdout)
match = re.search(self.version_patt, version_output)
if match is None:
raise ServersError(
'Could not determine version of %s from string: %s'
% (self.name, version_output))
version_string = match.group('version')
self.__version = tuple(map(int, version_string.split('.')))
return self.__version | 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()
version_output = str(stdout)
match = re.search(self.version_patt, version_output)
if match is None:
raise ServersError(
'Could not determine version of %s from string: %s'
% (self.name, version_output))
version_string = match.group('version')
self.__version = tuple(map(int, version_string.split('.')))
return self.__version | [
"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 | 37,304 |
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 'command'
if isinstance(arg, tuple):
name, d = arg
else:
name, d = arg, {}
result = getattr(self.connection.admin, mode)(command, name, **d)
return result | 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 'command'
if isinstance(arg, tuple):
name, d = arg
else:
name, d = arg, {}
result = getattr(self.connection.admin, mode)(command, name, **d)
return result | [
"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 | 37,305 |
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
logger.debug("proc_info: {proc_info}".format(**locals()))
mongodb_uri = ''
server_info = {}
status_info = {}
if self.hostname and self.cfg.get('port', None):
try:
c = self.connection
server_info = c.server_info()
logger.debug("server_info: {server_info}".format(**locals()))
mongodb_uri = 'mongodb://' + self.hostname
status_info = {"primary": c.is_primary, "mongos": c.is_mongos}
logger.debug("status_info: {status_info}".format(**locals()))
except (pymongo.errors.AutoReconnect, pymongo.errors.OperationFailure, pymongo.errors.ConnectionFailure):
server_info = {}
status_info = {}
result = {"mongodb_uri": mongodb_uri, "statuses": status_info,
"serverInfo": server_info, "procInfo": proc_info,
"orchestration": 'servers'}
if self.login:
result['mongodb_auth_uri'] = self.mongodb_auth_uri(self.hostname)
logger.debug("return {result}".format(result=result))
return result | 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
logger.debug("proc_info: {proc_info}".format(**locals()))
mongodb_uri = ''
server_info = {}
status_info = {}
if self.hostname and self.cfg.get('port', None):
try:
c = self.connection
server_info = c.server_info()
logger.debug("server_info: {server_info}".format(**locals()))
mongodb_uri = 'mongodb://' + self.hostname
status_info = {"primary": c.is_primary, "mongos": c.is_mongos}
logger.debug("status_info: {status_info}".format(**locals()))
except (pymongo.errors.AutoReconnect, pymongo.errors.OperationFailure, pymongo.errors.ConnectionFailure):
server_info = {}
status_info = {}
result = {"mongodb_uri": mongodb_uri, "statuses": status_info,
"serverInfo": server_info, "procInfo": proc_info,
"orchestration": 'servers'}
if self.login:
result['mongodb_auth_uri'] = self.mongodb_auth_uri(self.hostname)
logger.debug("return {result}".format(result=result))
return result | [
"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 | 37,306 |
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 locked dbpath %s", dbpath)
process.repair_mongo(self.name, self.cfg['dbpath'])
self.proc, self.hostname = process.mprocess(
self.name, self.config_path, self.cfg.get('port', None),
timeout, self.silence_stdout)
self.pid = self.proc.pid
logger.debug("pid={pid}, hostname={hostname}".format(pid=self.pid, hostname=self.hostname))
self.host = self.hostname.split(':')[0]
self.port = int(self.hostname.split(':')[1])
# Wait for Server to respond to isMaster.
# Only try 6 times, each ConnectionFailure is 30 seconds.
max_attempts = 6
for i in range(max_attempts):
try:
self.run_command('isMaster')
break
except pymongo.errors.ConnectionFailure:
logger.exception('isMaster command failed:')
else:
raise TimeoutError(
"Server did not respond to 'isMaster' after %d attempts."
% max_attempts)
except (OSError, TimeoutError):
logpath = self.cfg.get('logpath')
if logpath:
# Copy the server logs into the mongo-orchestration logs.
logger.error(
"Could not start Server. Please find server log below.\n"
"=====================================================")
with open(logpath) as lp:
logger.error(lp.read())
else:
logger.exception(
'Could not start Server, and no logpath was provided!')
reraise(TimeoutError,
'Could not start Server. '
'Please check server log located in ' +
self.cfg.get('logpath', '<no logpath given>') +
' or the mongo-orchestration log in ' +
LOG_FILE + ' for more details.')
if self.restart_required:
if self.login:
# Add users to the appropriate database.
self._add_users()
self.stop()
# Restart with keyfile and auth.
if self.is_mongos:
self.config_path, self.cfg = self.__init_mongos(self.cfg)
else:
# Add auth options to this Server's config file.
self.config_path, self.cfg = self.__init_mongod(
self.cfg, add_auth=True)
self.restart_required = False
self.start()
return True | 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 locked dbpath %s", dbpath)
process.repair_mongo(self.name, self.cfg['dbpath'])
self.proc, self.hostname = process.mprocess(
self.name, self.config_path, self.cfg.get('port', None),
timeout, self.silence_stdout)
self.pid = self.proc.pid
logger.debug("pid={pid}, hostname={hostname}".format(pid=self.pid, hostname=self.hostname))
self.host = self.hostname.split(':')[0]
self.port = int(self.hostname.split(':')[1])
# Wait for Server to respond to isMaster.
# Only try 6 times, each ConnectionFailure is 30 seconds.
max_attempts = 6
for i in range(max_attempts):
try:
self.run_command('isMaster')
break
except pymongo.errors.ConnectionFailure:
logger.exception('isMaster command failed:')
else:
raise TimeoutError(
"Server did not respond to 'isMaster' after %d attempts."
% max_attempts)
except (OSError, TimeoutError):
logpath = self.cfg.get('logpath')
if logpath:
# Copy the server logs into the mongo-orchestration logs.
logger.error(
"Could not start Server. Please find server log below.\n"
"=====================================================")
with open(logpath) as lp:
logger.error(lp.read())
else:
logger.exception(
'Could not start Server, and no logpath was provided!')
reraise(TimeoutError,
'Could not start Server. '
'Please check server log located in ' +
self.cfg.get('logpath', '<no logpath given>') +
' or the mongo-orchestration log in ' +
LOG_FILE + ' for more details.')
if self.restart_required:
if self.login:
# Add users to the appropriate database.
self._add_users()
self.stop()
# Restart with keyfile and auth.
if self.is_mongos:
self.config_path, self.cfg = self.__init_mongos(self.cfg)
else:
# Add auth options to this Server's config file.
self.config_path, self.cfg = self.__init_mongod(
self.cfg, add_auth=True)
self.restart_required = False
self.start()
return True | [
"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 | 37,307 |
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
# Attempt the shutdown command twice, the first attempt might fail due
# to an election.
attempts = 2
for i in range(attempts):
logger.info("Attempting to send shutdown command to %s",
self.hostname)
try:
client.admin.command("shutdown", force=True)
except ConnectionFailure:
# A shutdown succeeds by closing the connection but a
# connection error does not necessarily mean that the shutdown
# has succeeded.
pass
# Wait for the server to exit otherwise rerun the shutdown command.
try:
return process.wait_mprocess(self.proc, 5)
except TimeoutError as exc:
logger.info("Timed out waiting on process: %s", exc)
continue
raise ServersError("Server %s failed to shutdown after %s attempts" %
(self.hostname, attempts)) | 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
# Attempt the shutdown command twice, the first attempt might fail due
# to an election.
attempts = 2
for i in range(attempts):
logger.info("Attempting to send shutdown command to %s",
self.hostname)
try:
client.admin.command("shutdown", force=True)
except ConnectionFailure:
# A shutdown succeeds by closing the connection but a
# connection error does not necessarily mean that the shutdown
# has succeeded.
pass
# Wait for the server to exit otherwise rerun the shutdown command.
try:
return process.wait_mprocess(self.proc, 5)
except TimeoutError as exc:
logger.info("Timed out waiting on process: %s", exc)
continue
raise ServersError("Server %s failed to shutdown after %s attempts" %
(self.hostname, attempts)) | [
"def",
"shutdown",
"(",
"self",
")",
":",
"# Return early if this server has already exited.",
"if",
"not",
"process",
".",
"proc_alive",
"(",
"self",
".",
"proc",
")",
":",
"return",
"logger",
".",
"info",
"(",
"\"Attempting to connect to %s\"",
",",
"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 | 37,308 |
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"
% (release, self.releases))
if self.default_release:
return self.releases[self.default_release]
if self.releases:
return list(self.releases.values())[0]
return '' | 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"
% (release, self.releases))
if self.default_release:
return self.releases[self.default_release]
if self.releases:
return list(self.releases.values())[0]
return '' | [
"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 | 37,309 |
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', [{}]):
member['procParams'] = self._strip_auth(
member.get('procParams', {}))
member['procParams']['configsvr'] = True
if self.enable_ipv6:
common.enable_ipv6_single(member['procParams'])
rs_cfg['sslParams'] = self.sslParams
self._configsvrs.append(ReplicaSets().create(rs_cfg)) | 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', [{}]):
member['procParams'] = self._strip_auth(
member.get('procParams', {}))
member['procParams']['configsvr'] = True
if self.enable_ipv6:
common.enable_ipv6_single(member['procParams'])
rs_cfg['sslParams'] = self.sslParams
self._configsvrs.append(ReplicaSets().create(rs_cfg)) | [
"def",
"__init_configrs",
"(",
"self",
",",
"rs_cfg",
")",
":",
"# 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... | 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 | 37,310 |
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', self._version)
cfg.update({'configsvr': True})
if self.enable_ipv6:
common.enable_ipv6_single(cfg)
self._configsvrs.append(Servers().create(
'mongod', cfg, sslParams=self.sslParams, autostart=True,
version=version, server_id=server_id)) | 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', self._version)
cfg.update({'configsvr': True})
if self.enable_ipv6:
common.enable_ipv6_single(cfg)
self._configsvrs.append(Servers().create(
'mongod', cfg, sslParams=self.sslParams, autostart=True,
version=version, server_id=server_id)) | [
"def",
"__init_configsvrs",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"_configsvrs",
"=",
"[",
"]",
"for",
"cfg",
"in",
"params",
":",
"# Remove flags that turn on auth.",
"cfg",
"=",
"self",
".",
"_strip_auth",
"(",
"cfg",
")",
"server_id",
"=",
... | 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 | 37,311 |
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().hostname(h_id)}
for h_id in self._configsvrs] | 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().hostname(h_id)}
for h_id in self._configsvrs] | [
"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 | 37,312 |
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 | 37,313 |
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)
return clients | 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)
return clients | [
"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 | 37,314 |
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 | 37,315 |
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['members']:
if not member.get('rsParams', {}).get('arbiterOnly', False):
member.setdefault('procParams', {})['shardsvr'] = True
rs_params = params.copy()
# Turn 'rs_id' -> 'id', to be consistent with 'server_id' below.
rs_params['id'] = rs_params.pop('rs_id', None)
rs_params.update({'sslParams': self.sslParams})
rs_params['version'] = params.pop('version', self._version)
rs_params['members'] = [
self._strip_auth(params) for params in rs_params['members']]
rs_id = ReplicaSets().create(rs_params)
members = ReplicaSets().members(rs_id)
cfgs = rs_id + r"/" + ','.join([item['host'] for item in members])
result = self._add(cfgs, member_id)
if result.get('ok', 0) == 1:
self._shards[result['shardAdded']] = {'isReplicaSet': True, '_id': rs_id}
# return self._shards[result['shardAdded']].copy()
return self.member_info(member_id)
else:
# is single server
params.setdefault('procParams', {})['shardsvr'] = True
params.update({'autostart': True, 'sslParams': self.sslParams})
params = params.copy()
params['procParams'] = self._strip_auth(
params.get('procParams', {}))
params.setdefault('version', self._version)
logger.debug("servers create params: {params}".format(**locals()))
server_id = Servers().create('mongod', **params)
result = self._add(Servers().hostname(server_id), member_id)
if result.get('ok', 0) == 1:
self._shards[result['shardAdded']] = {'isServer': True, '_id': server_id}
return self.member_info(member_id) | 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['members']:
if not member.get('rsParams', {}).get('arbiterOnly', False):
member.setdefault('procParams', {})['shardsvr'] = True
rs_params = params.copy()
# Turn 'rs_id' -> 'id', to be consistent with 'server_id' below.
rs_params['id'] = rs_params.pop('rs_id', None)
rs_params.update({'sslParams': self.sslParams})
rs_params['version'] = params.pop('version', self._version)
rs_params['members'] = [
self._strip_auth(params) for params in rs_params['members']]
rs_id = ReplicaSets().create(rs_params)
members = ReplicaSets().members(rs_id)
cfgs = rs_id + r"/" + ','.join([item['host'] for item in members])
result = self._add(cfgs, member_id)
if result.get('ok', 0) == 1:
self._shards[result['shardAdded']] = {'isReplicaSet': True, '_id': rs_id}
# return self._shards[result['shardAdded']].copy()
return self.member_info(member_id)
else:
# is single server
params.setdefault('procParams', {})['shardsvr'] = True
params.update({'autostart': True, 'sslParams': self.sslParams})
params = params.copy()
params['procParams'] = self._strip_auth(
params.get('procParams', {}))
params.setdefault('version', self._version)
logger.debug("servers create params: {params}".format(**locals()))
server_id = Servers().create('mongod', **params)
result = self._add(Servers().hostname(server_id), member_id)
if result.get('ok', 0) == 1:
self._shards[result['shardAdded']] = {'isServer': True, '_id': server_id}
return self.member_info(member_id) | [
"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 | 37,316 |
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):
Servers().remove(shard['_id'])
if shard.get('isReplicaSet', False):
ReplicaSets().remove(shard['_id'])
return result | 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):
Servers().remove(shard['_id'])
if shard.get('isReplicaSet', False):
ReplicaSets().remove(shard['_id'])
return result | [
"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 | 37,317 |
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._shards[shard_id].get('isServer'):
singleton = Servers()
singleton.command(self._shards[shard_id]['_id'], 'reset')
# Ensure all config servers by calling "reset" on each.
for config_id in self._configsvrs:
self.configdb_singleton.command(config_id, 'reset')
# Ensure all routers by calling "reset" on each.
for router_id in self._routers:
Servers().command(router_id, 'reset')
return self.info() | 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._shards[shard_id].get('isServer'):
singleton = Servers()
singleton.command(self._shards[shard_id]['_id'], 'reset')
# Ensure all config servers by calling "reset" on each.
for config_id in self._configsvrs:
self.configdb_singleton.command(config_id, 'reset')
# Ensure all routers by calling "reset" on each.
for router_id in self._routers:
Servers().command(router_id, 'reset')
return self.info() | [
"def",
"reset",
"(",
"self",
")",
":",
"# Ensure all shards by calling \"reset\" on each.",
"for",
"shard_id",
"in",
"self",
".",
"_shards",
":",
"if",
"self",
".",
"_shards",
"[",
"shard_id",
"]",
".",
"get",
"(",
"'isReplicaSet'",
")",
":",
"singleton",
"=",... | 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 | 37,318 |
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.routers,
'mongodb_uri': mongodb_uri,
'orchestration': 'sharded_clusters'}
if self.login:
result['mongodb_auth_uri'] = self.mongodb_auth_uri(uri)
return result | 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.routers,
'mongodb_uri': mongodb_uri,
'orchestration': 'sharded_clusters'}
if self.login:
result['mongodb_auth_uri'] = self.mongodb_auth_uri(uri)
return result | [
"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 | 37,319 |
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 | 37,320 |
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 | 37,321 |
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"
% (command, cluster_id)) | 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"
% (command, cluster_id)) | [
"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 | 37,322 |
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 | 37,323 |
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 | 37,324 |
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))
if not os.path.isabs(_dir):
_dir = os.path.normpath(os.path.join(cwd, _dir))
return _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))
if not os.path.isabs(_dir):
_dir = os.path.normpath(os.path.join(cwd, _dir))
return _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 | 37,325 |
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 deciphering relative paths)
:type cwd: str
:rtype: list
"""
configs = []
for directory, repos in config.items():
for repo, repo_data in repos.items():
conf = {}
'''
repo_name: http://myrepo.com/repo.git
to
repo_name: { url: 'http://myrepo.com/repo.git' }
also assures the repo is a :py:class:`dict`.
'''
if isinstance(repo_data, string_types):
conf['url'] = repo_data
else:
conf = update_dict(conf, repo_data)
if 'repo' in conf:
if 'url' not in conf:
conf['url'] = conf.pop('repo')
else:
conf.pop('repo', None)
'''
``shell_command_after``: if str, turn to list.
'''
if 'shell_command_after' in conf:
if isinstance(conf['shell_command_after'], string_types):
conf['shell_command_after'] = [conf['shell_command_after']]
if 'name' not in conf:
conf['name'] = repo
if 'parent_dir' not in conf:
conf['parent_dir'] = expand_dir(directory, cwd)
if 'repo_dir' not in conf:
conf['repo_dir'] = expand_dir(
os.path.join(conf['parent_dir'], conf['name']), cwd
)
if 'remotes' in conf:
remotes = []
for remote_name, url in conf['remotes'].items():
remotes.append({'remote_name': remote_name, 'url': url})
conf['remotes'] = sorted(
remotes, key=lambda x: sorted(x.get('remote_name'))
)
configs.append(conf)
return configs | 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 deciphering relative paths)
:type cwd: str
:rtype: list
"""
configs = []
for directory, repos in config.items():
for repo, repo_data in repos.items():
conf = {}
'''
repo_name: http://myrepo.com/repo.git
to
repo_name: { url: 'http://myrepo.com/repo.git' }
also assures the repo is a :py:class:`dict`.
'''
if isinstance(repo_data, string_types):
conf['url'] = repo_data
else:
conf = update_dict(conf, repo_data)
if 'repo' in conf:
if 'url' not in conf:
conf['url'] = conf.pop('repo')
else:
conf.pop('repo', None)
'''
``shell_command_after``: if str, turn to list.
'''
if 'shell_command_after' in conf:
if isinstance(conf['shell_command_after'], string_types):
conf['shell_command_after'] = [conf['shell_command_after']]
if 'name' not in conf:
conf['name'] = repo
if 'parent_dir' not in conf:
conf['parent_dir'] = expand_dir(directory, cwd)
if 'repo_dir' not in conf:
conf['repo_dir'] = expand_dir(
os.path.join(conf['parent_dir'], conf['name']), cwd
)
if 'remotes' in conf:
remotes = []
for remote_name, url in conf['remotes'].items():
remotes.append({'remote_name': remote_name, 'url': url})
conf['remotes'] = sorted(
remotes, key=lambda x: sorted(x.get('remote_name'))
)
configs.append(conf)
return configs | [
"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
:rtype: list | [
"Return",
"expanded",
"configuration",
"."
] | c1827bf78d2cdebc61d82111c9aa35afd6ea6a25 | https://github.com/vcs-python/vcspull/blob/c1827bf78d2cdebc61d82111c9aa35afd6ea6a25/vcspull/config.py#L41-L106 | train | 37,326 |
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 filetype: list of filetypes to search against
:type filetype: list
:param include_home: Include home configuration files
:type include_home: bool
:raises:
- LoadConfigRepoConflict: There are two configs that have same path
and name with different repo urls.
:returns: list of absolute paths to config files.
:rtype: list
"""
configs = []
if include_home is True:
configs.extend(find_home_config_files())
if isinstance(path, list):
for p in path:
configs.extend(find_config_files(p, match, filetype))
return configs
else:
path = os.path.expanduser(path)
if isinstance(match, list):
for m in match:
configs.extend(find_config_files(path, m, filetype))
else:
if isinstance(filetype, list):
for f in filetype:
configs.extend(find_config_files(path, match, f))
else:
match = os.path.join(path, match)
match += ".{filetype}".format(filetype=filetype)
configs = glob.glob(match)
return configs | 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 filetype: list of filetypes to search against
:type filetype: list
:param include_home: Include home configuration files
:type include_home: bool
:raises:
- LoadConfigRepoConflict: There are two configs that have same path
and name with different repo urls.
:returns: list of absolute paths to config files.
:rtype: list
"""
configs = []
if include_home is True:
configs.extend(find_home_config_files())
if isinstance(path, list):
for p in path:
configs.extend(find_config_files(p, match, filetype))
return configs
else:
path = os.path.expanduser(path)
if isinstance(match, list):
for m in match:
configs.extend(find_config_files(path, m, filetype))
else:
if isinstance(filetype, list):
for f in filetype:
configs.extend(find_config_files(path, match, f))
else:
match = os.path.join(path, match)
match += ".{filetype}".format(filetype=filetype)
configs = glob.glob(match)
return configs | [
"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 configuration files
:type include_home: bool
:raises:
- LoadConfigRepoConflict: There are two configs that have same path
and name with different repo urls.
:returns: list of absolute paths to config files.
:rtype: list | [
"Return",
"repos",
"from",
"a",
"directory",
"and",
"match",
".",
"Not",
"recursive",
"."
] | c1827bf78d2cdebc61d82111c9aa35afd6ea6a25 | https://github.com/vcs-python/vcspull/blob/c1827bf78d2cdebc61d82111c9aa35afd6ea6a25/vcspull/config.py#L135-L179 | train | 37,327 |
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: expanded config dict item
:rtype: list of dict
"""
repos = []
for f in files:
_, ext = os.path.splitext(f)
conf = kaptan.Kaptan(handler=ext.lstrip('.')).import_config(f)
newrepos = extract_repos(conf.export('dict'), cwd)
if not repos:
repos.extend(newrepos)
continue
dupes = detect_duplicate_repos(repos, newrepos)
if dupes:
msg = ('repos with same path + different VCS detected!', dupes)
raise exc.VCSPullException(msg)
repos.extend(newrepos)
return repos | 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: expanded config dict item
:rtype: list of dict
"""
repos = []
for f in files:
_, ext = os.path.splitext(f)
conf = kaptan.Kaptan(handler=ext.lstrip('.')).import_config(f)
newrepos = extract_repos(conf.export('dict'), cwd)
if not repos:
repos.extend(newrepos)
continue
dupes = detect_duplicate_repos(repos, newrepos)
if dupes:
msg = ('repos with same path + different VCS detected!', dupes)
raise exc.VCSPullException(msg)
repos.extend(newrepos)
return repos | [
"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 | 37,328 |
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
:returns: Duplicate lists
"""
dupes = []
path_dupe_repos = []
curpaths = [r['repo_dir'] for r in repos1]
newpaths = [r['repo_dir'] for r in repos2]
path_duplicates = list(set(curpaths).intersection(newpaths))
if not path_duplicates:
return None
path_dupe_repos.extend(
[r for r in repos2 if any(r['repo_dir'] == p for p in path_duplicates)]
)
if not path_dupe_repos:
return None
for n in path_dupe_repos:
currepo = next((r for r in repos1 if r['repo_dir'] == n['repo_dir']), None)
if n['url'] != currepo['url']:
dupes += (n, currepo)
return dupes | 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
:returns: Duplicate lists
"""
dupes = []
path_dupe_repos = []
curpaths = [r['repo_dir'] for r in repos1]
newpaths = [r['repo_dir'] for r in repos2]
path_duplicates = list(set(curpaths).intersection(newpaths))
if not path_duplicates:
return None
path_dupe_repos.extend(
[r for r in repos2 if any(r['repo_dir'] == p for p in path_duplicates)]
)
if not path_dupe_repos:
return None
for n in path_dupe_repos:
currepo = next((r for r in repos1 if r['repo_dir'] == n['repo_dir']), None)
if n['url'] != currepo['url']:
dupes += (n, currepo)
return dupes | [
"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 | 37,329 |
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):
setattr(dest, attr, getattr(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):
setattr(dest, attr, getattr(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 | 37,330 |
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.group(1)
actual_module_name = 'flask_{}'.format(from_name)
return actual_module_name | 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.group(1)
actual_module_name = 'flask_{}'.format(from_name)
return actual_module_name | [
"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 | 37,331 |
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. Each tuple consists of (name, as_name).
# So, the import would be represented as:
#
# from flask.ext import wtf as ftw, admin
#
# node.names = [('wtf', 'ftw'), ('admin', None)]
for (name, as_name) in node.names:
actual_module_name = 'flask_{}'.format(name)
new_names.append((actual_module_name, as_name or name))
new_node = nodes.Import()
copy_node_info(node, new_node)
new_node.names = new_names
mark_transformed(new_node)
return new_node | 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. Each tuple consists of (name, as_name).
# So, the import would be represented as:
#
# from flask.ext import wtf as ftw, admin
#
# node.names = [('wtf', 'ftw'), ('admin', None)]
for (name, as_name) in node.names:
actual_module_name = 'flask_{}'.format(name)
new_names.append((actual_module_name, as_name or name))
new_node = nodes.Import()
copy_node_info(node, new_node)
new_node.names = new_names
mark_transformed(new_node)
return new_node | [
"def",
"transform_flask_from_import",
"(",
"node",
")",
":",
"new_names",
"=",
"[",
"]",
"# node.names is a list of 2-tuples. Each tuple consists of (name, as_name).",
"# So, the import would be represented as:",
"#",
"# from flask.ext import wtf as ftw, admin",
"#",
"# node.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 | 37,332 |
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 InlineFormAdmin
'''
actual_module_name = make_non_magical_flask_import(node.modname)
new_node = nodes.ImportFrom(actual_module_name, node.names, node.level)
copy_node_info(node, new_node)
mark_transformed(new_node)
return new_node | 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 InlineFormAdmin
'''
actual_module_name = make_non_magical_flask_import(node.modname)
new_node = nodes.ImportFrom(actual_module_name, node.names, node.level)
copy_node_info(node, new_node)
mark_transformed(new_node)
return new_node | [
"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 | 37,333 |
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\.(.*)', name)
from_name = match.group(1)
actual_module_name = 'flask_{}'.format(from_name)
new_names.append((actual_module_name, as_name))
new_node = nodes.Import()
copy_node_info(node, new_node)
new_node.names = new_names
mark_transformed(new_node)
return new_node | 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\.(.*)', name)
from_name = match.group(1)
actual_module_name = 'flask_{}'.format(from_name)
new_names.append((actual_module_name, as_name))
new_node = nodes.Import()
copy_node_info(node, new_node)
new_node.names = new_names
mark_transformed(new_node)
return new_node | [
"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 | 37,334 |
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 "Waiting 5 seconds..."
sleep(5)
print "Firing"
routine.trigger()
except KeyboardInterrupt:
break | 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 "Waiting 5 seconds..."
sleep(5)
print "Firing"
routine.trigger()
except KeyboardInterrupt:
break | [
"def",
"main",
"(",
")",
":",
"alarm",
"=",
"XBeeAlarm",
"(",
"'/dev/ttyUSB0'",
",",
"'\\x56\\x78'",
")",
"routine",
"=",
"SimpleWakeupRoutine",
"(",
"alarm",
")",
"from",
"time",
"import",
"sleep",
"while",
"True",
":",
"\"\"\"\n Run the routine with 10 se... | 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 | 37,335 |
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() == b'is' and \
packet_info['status'] == b'\x00':
return self._parse_samples(packet_info['parameter'])
else:
return packet_info['parameter'] | 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() == b'is' and \
packet_info['status'] == b'\x00':
return self._parse_samples(packet_info['parameter'])
else:
return packet_info['parameter'] | [
"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 | 37,336 |
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_info['status'] == b'\x00':
result = {}
# Parse each field directly
result['source_addr'] = packet_info['parameter'][0:2]
result['source_addr_long'] = packet_info['parameter'][2:10]
# Parse the null-terminated node identifier field
null_terminator_index = 10
while packet_info['parameter'][null_terminator_index:
null_terminator_index+1] != b'\x00':
null_terminator_index += 1
# Parse each field thereafter directly
result['node_identifier'] = \
packet_info['parameter'][10:null_terminator_index]
result['parent_address'] = \
packet_info['parameter'][null_terminator_index+1:
null_terminator_index+3]
result['device_type'] = \
packet_info['parameter'][null_terminator_index+3:
null_terminator_index+4]
result['status'] = \
packet_info['parameter'][null_terminator_index+4:
null_terminator_index+5]
result['profile_id'] = \
packet_info['parameter'][null_terminator_index+5:
null_terminator_index+7]
result['manufacturer'] = \
packet_info['parameter'][null_terminator_index+7:
null_terminator_index+9]
# Simple check to ensure a good parse
if null_terminator_index+9 != len(packet_info['parameter']):
raise ValueError("Improper ND response length: expected {0}, "
"read {1} bytes".format(
len(packet_info['parameter']),
null_terminator_index+9)
)
return result
else:
return packet_info['parameter'] | 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_info['status'] == b'\x00':
result = {}
# Parse each field directly
result['source_addr'] = packet_info['parameter'][0:2]
result['source_addr_long'] = packet_info['parameter'][2:10]
# Parse the null-terminated node identifier field
null_terminator_index = 10
while packet_info['parameter'][null_terminator_index:
null_terminator_index+1] != b'\x00':
null_terminator_index += 1
# Parse each field thereafter directly
result['node_identifier'] = \
packet_info['parameter'][10:null_terminator_index]
result['parent_address'] = \
packet_info['parameter'][null_terminator_index+1:
null_terminator_index+3]
result['device_type'] = \
packet_info['parameter'][null_terminator_index+3:
null_terminator_index+4]
result['status'] = \
packet_info['parameter'][null_terminator_index+4:
null_terminator_index+5]
result['profile_id'] = \
packet_info['parameter'][null_terminator_index+5:
null_terminator_index+7]
result['manufacturer'] = \
packet_info['parameter'][null_terminator_index+7:
null_terminator_index+9]
# Simple check to ensure a good parse
if null_terminator_index+9 != len(packet_info['parameter']):
raise ValueError("Improper ND response length: expected {0}, "
"read {1} bytes".format(
len(packet_info['parameter']),
null_terminator_index+9)
)
return result
else:
return packet_info['parameter'] | [
"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 | 37,337 |
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 packet
xbee.send('at', frame_id='A', command='DH')
# Wait for response
response = xbee.wait_read_frame()
print response
# Send AT packet
xbee.send('at', frame_id='B', command='DL')
# Wait for response
response = xbee.wait_read_frame()
print response
# Send AT packet
xbee.send('at', frame_id='C', command='MY')
# Wait for response
response = xbee.wait_read_frame()
print response
# Send AT packet
xbee.send('at', frame_id='D', command='CE')
# Wait for response
response = xbee.wait_read_frame()
print response
except KeyboardInterrupt:
pass
finally:
ser.close() | 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 packet
xbee.send('at', frame_id='A', command='DH')
# Wait for response
response = xbee.wait_read_frame()
print response
# Send AT packet
xbee.send('at', frame_id='B', command='DL')
# Wait for response
response = xbee.wait_read_frame()
print response
# Send AT packet
xbee.send('at', frame_id='C', command='MY')
# Wait for response
response = xbee.wait_read_frame()
print response
# Send AT packet
xbee.send('at', frame_id='D', command='CE')
# Wait for response
response = xbee.wait_read_frame()
print response
except KeyboardInterrupt:
pass
finally:
ser.close() | [
"def",
"main",
"(",
")",
":",
"try",
":",
"# Open serial port",
"ser",
"=",
"serial",
".",
"Serial",
"(",
"'/dev/ttyUSB0'",
",",
"9600",
")",
"# Create XBee Series 1 object",
"xbee",
"=",
"XBee",
"(",
"ser",
")",
"# Send AT packet",
"xbee",
".",
"send",
"(",... | 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 | 37,338 |
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'",
")",
":",
"# This is already an int",
"return",
"byte",
"return",
"ord",
"(",
"byte",
")",
"if",
"hasattr",
"(",
"byte",
",",
"'encode'",
")",
"else",
"byte",
"... | 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 | 37,339 |
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 JWPlayer Dashboard.
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/conversions/list.html
:return: <dict> Dict which represents the JSON response.
"""
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Querying for video conversions.")
try:
response = jwplatform_client.videos.conversions.list(video_key=video_key, **kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error querying for video conversions.\n{}".format(e))
sys.exit(e.message)
return response | 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 JWPlayer Dashboard.
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/conversions/list.html
:return: <dict> Dict which represents the JSON response.
"""
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Querying for video conversions.")
try:
response = jwplatform_client.videos.conversions.list(video_key=video_key, **kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error querying for video conversions.\n{}".format(e))
sys.exit(e.message)
return response | [
"def",
"list_conversions",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",
"(",
"\"Querying for video... | 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 @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/conversions/list.html
:return: <dict> Dict which represents the JSON response. | [
"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 | 37,340 |
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,
path=path)
if params is not None:
_params = params.copy()
else:
_params = dict()
# Add required API parameters
_params['api_nonce'] = str(random.randint(0, 999999999)).zfill(9)
_params['api_timestamp'] = int(time.time())
_params['api_key'] = self.__key
_params['api_format'] = 'json'
_params['api_kit'] = 'py-{}{}'.format(
__version__, '-{}'.format(self._agent) if self._agent else '')
# Construct Signature Base String
sbs = '&'.join(['{}={}'.format(
quote((unicode(key).encode('utf-8')), safe='~'),
quote((unicode(value).encode('utf-8')), safe='~')
) for key, value in sorted(_params.items())])
# Add signature to the _params dict
_params['api_signature'] = hashlib.sha1(
'{}{}'.format(sbs, self.__secret).encode('utf-8')).hexdigest()
return _url, _params | 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,
path=path)
if params is not None:
_params = params.copy()
else:
_params = dict()
# Add required API parameters
_params['api_nonce'] = str(random.randint(0, 999999999)).zfill(9)
_params['api_timestamp'] = int(time.time())
_params['api_key'] = self.__key
_params['api_format'] = 'json'
_params['api_kit'] = 'py-{}{}'.format(
__version__, '-{}'.format(self._agent) if self._agent else '')
# Construct Signature Base String
sbs = '&'.join(['{}={}'.format(
quote((unicode(key).encode('utf-8')), safe='~'),
quote((unicode(value).encode('utf-8')), safe='~')
) for key, value in sorted(_params.items())])
# Add signature to the _params dict
_params['api_signature'] = hashlib.sha1(
'{}{}'.format(sbs, self.__secret).encode('utf-8')).hexdigest()
return _url, _params | [
"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 | 37,341 |
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 media on local machine.
:param api_format: <string> Acceptable values include 'py','xml','json',and 'php'
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
:return:
"""
# Setup API client
jwplatform_client = jwplatform.Client(api_key, api_secret)
# Make /videos/create API call
logging.info("Registering new Video-Object")
try:
response = jwplatform_client.videos.create(upload_method='single', **kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error creating a video\n{}".format(e))
logging.info(response)
# Construct base url for upload
upload_url = '{}://{}{}'.format(
response['link']['protocol'],
response['link']['address'],
response['link']['path']
)
# Query parameters for the upload
query_parameters = response['link']['query']
query_parameters['api_format'] = api_format
with open(local_video_path, 'rb') as f:
files = {'file': f}
r = requests.post(upload_url,
params=query_parameters,
files=files)
logging.info('uploading file {} to url {}'.format(local_video_path, r.url))
logging.info('upload response: {}'.format(r.text))
logging.info(r) | 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 media on local machine.
:param api_format: <string> Acceptable values include 'py','xml','json',and 'php'
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
:return:
"""
# Setup API client
jwplatform_client = jwplatform.Client(api_key, api_secret)
# Make /videos/create API call
logging.info("Registering new Video-Object")
try:
response = jwplatform_client.videos.create(upload_method='single', **kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error creating a video\n{}".format(e))
logging.info(response)
# Construct base url for upload
upload_url = '{}://{}{}'.format(
response['link']['protocol'],
response['link']['address'],
response['link']['path']
)
# Query parameters for the upload
query_parameters = response['link']['query']
query_parameters['api_format'] = api_format
with open(local_video_path, 'rb') as f:
files = {'file': f}
r = requests.post(upload_url,
params=query_parameters,
files=files)
logging.info('uploading file {} to url {}'.format(local_video_path, r.url))
logging.info('upload response: {}'.format(r.text))
logging.info(r) | [
"def",
"create_video",
"(",
"api_key",
",",
"api_secret",
",",
"local_video_path",
",",
"api_format",
"=",
"'json'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Setup API client",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret"... | 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',and 'php'
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
:return: | [
"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 | 37,342 |
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 media on local machine.
:param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
:return:
"""
filename = os.path.basename(local_video_path)
# Setup API client
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Updating Video")
try:
response = jwplatform_client.videos.update(
video_key=video_key,
upload_method='s3',
update_file='True',
**kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error updating the video\n{}".format(e))
sys.exit(e.message)
logging.info(response)
# Construct base url for upload
upload_url = '{}://{}{}'.format(
response['link']['protocol'],
response['link']['address'],
response['link']['path']
)
# Query parameters for the upload
query_parameters = response['link']['query']
# HTTP PUT upload using requests
headers = {'Content-Disposition': 'attachment; filename="{}"'.format(filename)}
with open(local_video_path, 'rb') as f:
r = requests.put(upload_url, params=query_parameters, headers=headers, data=f)
logging.info('uploading file {} to url {}'.format(local_video_path, r.url))
logging.info('upload response: {}'.format(r.text))
logging.info(r) | 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 media on local machine.
:param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
:return:
"""
filename = os.path.basename(local_video_path)
# Setup API client
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Updating Video")
try:
response = jwplatform_client.videos.update(
video_key=video_key,
upload_method='s3',
update_file='True',
**kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error updating the video\n{}".format(e))
sys.exit(e.message)
logging.info(response)
# Construct base url for upload
upload_url = '{}://{}{}'.format(
response['link']['protocol'],
response['link']['address'],
response['link']['path']
)
# Query parameters for the upload
query_parameters = response['link']['query']
# HTTP PUT upload using requests
headers = {'Content-Disposition': 'attachment; filename="{}"'.format(filename)}
with open(local_video_path, 'rb') as f:
r = requests.put(upload_url, params=query_parameters, headers=headers, data=f)
logging.info('uploading file {} to url {}'.format(local_video_path, r.url))
logging.info('upload response: {}'.format(r.text))
logging.info(r) | [
"def",
"replace_video",
"(",
"api_key",
",",
"api_secret",
",",
"local_video_path",
",",
"video_key",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"local_video_path",
")",
"# Setup API client",
"jwplatform_client",... | 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 JWPlayer Dashboard.
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
:return: | [
"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 | 37,343 |
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, user may opt to utilize thumbnail_index parameter.
Please eee documentation for further information.
: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 position: <float> Represents seconds into the duration of a video, for thumbnail extraction.
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html
:return: <dict> Dict which represents the JSON response.
"""
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Updating video thumbnail.")
try:
response = jwplatform_client.videos.thumbnails.update(
video_key=video_key,
position=position, # Parameter which specifies seconds into video to extract thumbnail from.
**kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error updating thumbnail.\n{}".format(e))
sys.exit(e.message)
return response | 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, user may opt to utilize thumbnail_index parameter.
Please eee documentation for further information.
: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 position: <float> Represents seconds into the duration of a video, for thumbnail extraction.
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html
:return: <dict> Dict which represents the JSON response.
"""
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Updating video thumbnail.")
try:
response = jwplatform_client.videos.thumbnails.update(
video_key=video_key,
position=position, # Parameter which specifies seconds into video to extract thumbnail from.
**kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error updating thumbnail.\n{}".format(e))
sys.exit(e.message)
return response | [
"def",
"update_thumbnail",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"position",
"=",
"7.0",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"... | 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 information.
: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 position: <float> Represents seconds into the duration of a video, for thumbnail extraction.
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html
:return: <dict> Dict which represents the JSON response. | [
"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 | 37,344 |
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 api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
:param local_video_image_path: <string> Local system path to an image.
:param api_format: <string> REQUIRED Acceptable values include 'py','xml','json',and 'php'
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html
:return: <dict> Dict which represents the JSON response.
"""
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Updating video thumbnail.")
try:
response = jwplatform_client.videos.thumbnails.update(
video_key=video_key,
**kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error updating thumbnail.\n{}".format(e))
sys.exit(e.message)
logging.info(response)
# Construct base url for upload
upload_url = '{}://{}{}'.format(
response['link']['protocol'],
response['link']['address'],
response['link']['path']
)
# Query parameters for the upload
query_parameters = response['link']['query']
query_parameters['api_format'] = api_format
with open(local_video_image_path, 'rb') as f:
files = {'file': f}
r = requests.post(upload_url, params=query_parameters, files=files)
logging.info('uploading file {} to url {}'.format(local_video_image_path, r.url))
logging.info('upload response: {}'.format(r.text)) | 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 api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
:param local_video_image_path: <string> Local system path to an image.
:param api_format: <string> REQUIRED Acceptable values include 'py','xml','json',and 'php'
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html
:return: <dict> Dict which represents the JSON response.
"""
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Updating video thumbnail.")
try:
response = jwplatform_client.videos.thumbnails.update(
video_key=video_key,
**kwargs)
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error updating thumbnail.\n{}".format(e))
sys.exit(e.message)
logging.info(response)
# Construct base url for upload
upload_url = '{}://{}{}'.format(
response['link']['protocol'],
response['link']['address'],
response['link']['path']
)
# Query parameters for the upload
query_parameters = response['link']['query']
query_parameters['api_format'] = api_format
with open(local_video_image_path, 'rb') as f:
files = {'file': f}
r = requests.post(upload_url, params=query_parameters, files=files)
logging.info('uploading file {} to url {}'.format(local_video_image_path, r.url))
logging.info('upload response: {}'.format(r.text)) | [
"def",
"update_thumbnail_via_upload",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"local_video_image_path",
"=",
"''",
",",
"api_format",
"=",
"'json'",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
... | 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_path: <string> Local system path to an image.
:param api_format: <string> REQUIRED Acceptable values include 'py','xml','json',and 'php'
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html
:return: <dict> Dict which represents the JSON response. | [
"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 | 37,345 |
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_size': os.stat(video_file_path).st_size,
'file_name': os.path.basename(video_file_path)
}
try:
# Setup API client
jwplatform_client = Client(JW_API_KEY, JW_API_SECRET)
# Make /videos/create API call with multipart parameter specified
jwplatform_video_create_response = jwplatform_client.videos.create(
upload_method='multipart',
title=upload_parameters['file_name']
)
except JWPlatformError:
logging.exception('An error occurred during the uploader setup. Check that your API keys are properly '
'set up in your environment, and ensure that the video file path exists.')
return
# Construct base url for upload
upload_parameters['upload_url'] = '{protocol}://{address}{path}'.format(**jwplatform_video_create_response['link'])
logging.info('Upload URL to be used: {}'.format(upload_parameters['upload_url']))
upload_parameters['query_parameters'] = jwplatform_video_create_response['link']['query']
upload_parameters['query_parameters']['api_format'] = 'json'
upload_parameters['headers'] = {'X-Session-ID': jwplatform_video_create_response['session_id']}
# The chunk offset will be updated several times during the course of the upload
upload_parameters['chunk_offset'] = 0
# Perform the multipart upload
with open(upload_parameters['file_path'], 'rb') as file_to_upload:
while True:
chunk = file_to_upload.read(BYTES_TO_BUFFER)
if len(chunk) <= 0:
break
try:
upload_chunk(chunk, upload_parameters)
# Log any exceptions that bubbled up
except requests.exceptions.RequestException:
logging.exception('Error posting data, stopping upload...')
break | 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_size': os.stat(video_file_path).st_size,
'file_name': os.path.basename(video_file_path)
}
try:
# Setup API client
jwplatform_client = Client(JW_API_KEY, JW_API_SECRET)
# Make /videos/create API call with multipart parameter specified
jwplatform_video_create_response = jwplatform_client.videos.create(
upload_method='multipart',
title=upload_parameters['file_name']
)
except JWPlatformError:
logging.exception('An error occurred during the uploader setup. Check that your API keys are properly '
'set up in your environment, and ensure that the video file path exists.')
return
# Construct base url for upload
upload_parameters['upload_url'] = '{protocol}://{address}{path}'.format(**jwplatform_video_create_response['link'])
logging.info('Upload URL to be used: {}'.format(upload_parameters['upload_url']))
upload_parameters['query_parameters'] = jwplatform_video_create_response['link']['query']
upload_parameters['query_parameters']['api_format'] = 'json'
upload_parameters['headers'] = {'X-Session-ID': jwplatform_video_create_response['session_id']}
# The chunk offset will be updated several times during the course of the upload
upload_parameters['chunk_offset'] = 0
# Perform the multipart upload
with open(upload_parameters['file_path'], 'rb') as file_to_upload:
while True:
chunk = file_to_upload.read(BYTES_TO_BUFFER)
if len(chunk) <= 0:
break
try:
upload_chunk(chunk, upload_parameters)
# Log any exceptions that bubbled up
except requests.exceptions.RequestException:
logging.exception('Error posting data, stopping upload...')
break | [
"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 | 37,346 |
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 path_to_csv: <string> Local system path to desired CSV. Default will be within current working directory.
:param result_limit: <int> Number of video results returned in response. (Suggested to leave at default of 1000)
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/list.html
:return: <dict> Dict which represents the JSON response.
"""
path_to_csv = path_to_csv or os.path.join(os.getcwd(), 'video_list.csv')
timeout_in_seconds = 2
max_retries = 3
retries = 0
offset = 0
videos = list()
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Querying for video list.")
while True:
try:
response = jwplatform_client.videos.list(result_limit=result_limit,
result_offset=offset,
**kwargs)
except jwplatform.errors.JWPlatformRateLimitExceededError:
logging.error("Encountered rate limiting error. Backing off on request time.")
if retries == max_retries:
raise jwplatform.errors.JWPlatformRateLimitExceededError()
timeout_in_seconds *= timeout_in_seconds # Exponential back off for timeout in seconds. 2->4->8->etc.etc.
retries += 1
time.sleep(timeout_in_seconds)
continue
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error querying for videos list.\n{}".format(e))
raise e
# Reset retry flow-control variables upon a non successful query (AKA not rate limited)
retries = 0
timeout_in_seconds = 2
# Add all fetched video objects to our videos list.
next_videos = response.get('videos', [])
last_query_total = response.get('total', 0)
videos.extend(next_videos)
offset += len(next_videos)
logging.info("Accumulated {} videos.".format(offset))
if offset >= last_query_total: # Condition which defines you've reached the end of the library
break
# Section for writing video library to csv
desired_fields = ['key', 'title', 'description', 'tags', 'date', 'link']
should_write_header = not os.path.isfile(path_to_csv)
with open(path_to_csv, 'a+') as path_to_csv:
# Only write columns to the csv which are specified above. Columns not specified are ignored.
writer = csv.DictWriter(path_to_csv, fieldnames=desired_fields, extrasaction='ignore')
if should_write_header:
writer.writeheader()
writer.writerows(videos) | 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 path_to_csv: <string> Local system path to desired CSV. Default will be within current working directory.
:param result_limit: <int> Number of video results returned in response. (Suggested to leave at default of 1000)
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/list.html
:return: <dict> Dict which represents the JSON response.
"""
path_to_csv = path_to_csv or os.path.join(os.getcwd(), 'video_list.csv')
timeout_in_seconds = 2
max_retries = 3
retries = 0
offset = 0
videos = list()
jwplatform_client = jwplatform.Client(api_key, api_secret)
logging.info("Querying for video list.")
while True:
try:
response = jwplatform_client.videos.list(result_limit=result_limit,
result_offset=offset,
**kwargs)
except jwplatform.errors.JWPlatformRateLimitExceededError:
logging.error("Encountered rate limiting error. Backing off on request time.")
if retries == max_retries:
raise jwplatform.errors.JWPlatformRateLimitExceededError()
timeout_in_seconds *= timeout_in_seconds # Exponential back off for timeout in seconds. 2->4->8->etc.etc.
retries += 1
time.sleep(timeout_in_seconds)
continue
except jwplatform.errors.JWPlatformError as e:
logging.error("Encountered an error querying for videos list.\n{}".format(e))
raise e
# Reset retry flow-control variables upon a non successful query (AKA not rate limited)
retries = 0
timeout_in_seconds = 2
# Add all fetched video objects to our videos list.
next_videos = response.get('videos', [])
last_query_total = response.get('total', 0)
videos.extend(next_videos)
offset += len(next_videos)
logging.info("Accumulated {} videos.".format(offset))
if offset >= last_query_total: # Condition which defines you've reached the end of the library
break
# Section for writing video library to csv
desired_fields = ['key', 'title', 'description', 'tags', 'date', 'link']
should_write_header = not os.path.isfile(path_to_csv)
with open(path_to_csv, 'a+') as path_to_csv:
# Only write columns to the csv which are specified above. Columns not specified are ignored.
writer = csv.DictWriter(path_to_csv, fieldnames=desired_fields, extrasaction='ignore')
if should_write_header:
writer.writeheader()
writer.writerows(videos) | [
"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 working directory.
:param result_limit: <int> Number of video results returned in response. (Suggested to leave at default of 1000)
:param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/list.html
:return: <dict> Dict which represents the JSON response. | [
"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 | 37,347 |
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.
Additionaly, if self.noise > 1/255, a "snowy" image is merged with
CAPTCHA image with a 50/50 ratio.
Property returns a pair containing a string with text in returned
image and image itself.
:returns: ``tuple`` (CAPTCHA text, Image object)
"""
text = self.text
w, h = self.font.getsize(text)
margin_x = round(self.margin_x * w / self.w)
margin_y = round(self.margin_y * h / self.h)
image = Image.new('RGB',
(w + 2*margin_x, h + 2*margin_y),
(255, 255, 255))
# Text
self._writeText(image, text, pos=(margin_x, margin_y))
# Line
self._drawLine(image)
# White noise
noise = self._whiteNoise(image.size)
if noise is not None:
image = Image.blend(image, noise, 0.5)
# Resize
image = image.resize(self.size, resample=self.resample)
return (text, image) | 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.
Additionaly, if self.noise > 1/255, a "snowy" image is merged with
CAPTCHA image with a 50/50 ratio.
Property returns a pair containing a string with text in returned
image and image itself.
:returns: ``tuple`` (CAPTCHA text, Image object)
"""
text = self.text
w, h = self.font.getsize(text)
margin_x = round(self.margin_x * w / self.w)
margin_y = round(self.margin_y * h / self.h)
image = Image.new('RGB',
(w + 2*margin_x, h + 2*margin_y),
(255, 255, 255))
# Text
self._writeText(image, text, pos=(margin_x, margin_y))
# Line
self._drawLine(image)
# White noise
noise = self._whiteNoise(image.size)
if noise is not None:
image = Image.blend(image, noise, 0.5)
# Resize
image = image.resize(self.size, resample=self.resample)
return (text, image) | [
"def",
"image",
"(",
"self",
")",
":",
"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.noise > 1/255, a "snowy" image is merged with
CAPTCHA image with a 50/50 ratio.
Property returns a pair containing a string with text in returned
image and image itself.
:returns: ``tuple`` (CAPTCHA text, Image object) | [
"r",
"Tuple",
"with",
"a",
"CAPTCHA",
"text",
"and",
"a",
"Image",
"object",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L88-L125 | train | 37,348 |
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)
"""
text, image = self.image
bytes = BytesIO()
image.save(bytes, format=self.format)
bytes.seek(0)
return (text, bytes) | 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)
"""
text, image = self.image
bytes = BytesIO()
image.save(bytes, format=self.format)
bytes.seek(0)
return (text, bytes) | [
"def",
"bytes",
"(",
"self",
")",
":",
"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 | 37,349 |
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.
:returns: ``tuple`` (CAPTCHA text, filepath)
"""
text, image = self.image
image.save(file, format=self.format)
return (text, file) | 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.
:returns: ``tuple`` (CAPTCHA text, filepath)
"""
text, image = self.image
image.save(file, format=self.format)
return (text, file) | [
"def",
"write",
"(",
"self",
",",
"file",
")",
":",
"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 text, filepath) | [
"r",
"Save",
"CAPTCHA",
"image",
"in",
"given",
"filepath",
"."
] | 0245f656e6febf34e32b5238196e992929df42c7 | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L144-L158 | train | 37,350 |
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 | 37,351 |
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_image)
c_draw.text((0, 0), c, font=self.font, fill=(0, 0, 0, 255))
# Transform
c_image = self._rndLetterTransform(c_image)
# Paste onto image
image.paste(c_image, (x+offset, y), c_image)
offset += c_size[0] | 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_image)
c_draw.text((0, 0), c, font=self.font, fill=(0, 0, 0, 255))
# Transform
c_image = self._rndLetterTransform(c_image)
# Paste onto image
image.paste(c_image, (x+offset, y), c_image)
offset += c_size[0] | [
"def",
"_writeText",
"(",
"self",
",",
"image",
",",
"text",
",",
"pos",
")",
":",
"offset",
"=",
"0",
"x",
",",
"y",
"=",
"pos",
"for",
"c",
"in",
"text",
":",
"# Write letter",
"c_size",
"=",
"self",
".",
"font",
".",
"getsize",
"(",
"c",
")",
... | 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 | 37,352 |
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))
x2 = int(w * random.uniform(0.9, 1))
y2 = int(h * random.uniform(0, 1))
# Line width modifier was chosen as an educated guess
# based on default image area.
l_width = round((w * h)**0.5 * 2.284e-2)
# Draw
l_draw.line(((x1, y1), (x2, y2)), fill=(0, 0, 0, 255), width=l_width)
# Transform
l_image = self._rndLineTransform(l_image)
l_image = l_image.resize(image.size, resample=self.resample)
# Paste onto image
image.paste(l_image, (0, 0), l_image) | 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))
x2 = int(w * random.uniform(0.9, 1))
y2 = int(h * random.uniform(0, 1))
# Line width modifier was chosen as an educated guess
# based on default image area.
l_width = round((w * h)**0.5 * 2.284e-2)
# Draw
l_draw.line(((x1, y1), (x2, y2)), fill=(0, 0, 0, 255), width=l_width)
# Transform
l_image = self._rndLineTransform(l_image)
l_image = l_image.resize(image.size, resample=self.resample)
# Paste onto image
image.paste(l_image, (0, 0), l_image) | [
"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 | 37,353 |
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))
rnd_grid = map(lambda _: tuple([pixel(self.noise)]) * 3,
[0] * w * h)
n_image.putdata(list(rnd_grid))
return n_image
else:
return None | 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))
rnd_grid = map(lambda _: tuple([pixel(self.noise)]) * 3,
[0] * w * h)
n_image.putdata(list(rnd_grid))
return n_image
else:
return None | [
"def",
"_whiteNoise",
"(",
"self",
",",
"size",
")",
":",
"if",
"self",
".",
"noise",
">",
"0.003921569",
":",
"# 1./255.",
"w",
",",
"h",
"=",
"size",
"pixel",
"=",
"(",
"lambda",
"noise",
":",
"round",
"(",
"255",
"*",
"random",
".",
"uniform",
"... | 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 | 37,354 |
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)
w += abs(x1) + abs(x2)
h += abs(x1) + abs(x2)
quad = self.__class__._quadPoints((w, h), (x1, y1), (x2, y2))
return image.transform(image.size, Image.QUAD,
data=quad, resample=self.resample) | 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)
w += abs(x1) + abs(x2)
h += abs(x1) + abs(x2)
quad = self.__class__._quadPoints((w, h), (x1, y1), (x2, y2))
return image.transform(image.size, Image.QUAD,
data=quad, resample=self.resample) | [
"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 | 37,355 |
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 | 37,356 |
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 | 37,357 |
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.bottle_path_to_openapi(route.rule) | 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.bottle_path_to_openapi(route.rule) | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"view",
",",
"*",
"*",
"kwargs",
")",
":",
"operations",
".",
"update",
"(",
"yaml_utils",
".",
"load_operations_from_docstring",
"(",
"view",
".",
"__doc__",
")",
")",
"app",
"=",
"kwargs",
".",
... | 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 | 37,358 |
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(view.view_class, MethodView):
for method in view.methods:
if method in rule.methods:
method_name = method.lower()
method = getattr(view.view_class, method_name)
operations[method_name] = yaml_utils.load_yaml_from_docstring(method.__doc__)
return self.flaskpath2openapi(rule.rule) | 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(view.view_class, MethodView):
for method in view.methods:
if method in rule.methods:
method_name = method.lower()
method = getattr(view.view_class, method_name)
operations[method_name] = yaml_utils.load_yaml_from_docstring(method.__doc__)
return self.flaskpath2openapi(rule.rule) | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"view",
",",
"app",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"rule",
"=",
"self",
".",
"_rule_for_view",
"(",
"view",
",",
"app",
"=",
"app",
")",
"operations",
".",
"update",
"(",
"... | 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 | 37,359 |
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)
operation_data = yaml_utils.load_yaml_from_docstring(method.__doc__)
if operation_data:
operation = {httpmethod: operation_data}
yield operation | 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)
operation_data = yaml_utils.load_yaml_from_docstring(method.__doc__)
if operation_data:
operation = {httpmethod: operation_data}
yield operation | [
"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 | 37,360 |
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.signature(method).parameters.keys())[1:]
else:
if getattr(method, '__tornado_coroutine__', False):
method = method.__wrapped__
args = inspect.getargspec(method).args[1:]
params = tuple('{{{}}}'.format(arg) for arg in args)
try:
path_tpl = urlspec.matcher._path
except AttributeError: # tornado<4.5
path_tpl = urlspec._path
path = (path_tpl % params)
if path.count('/') > 1:
path = path.rstrip('/?*')
return path | 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.signature(method).parameters.keys())[1:]
else:
if getattr(method, '__tornado_coroutine__', False):
method = method.__wrapped__
args = inspect.getargspec(method).args[1:]
params = tuple('{{{}}}'.format(arg) for arg in args)
try:
path_tpl = urlspec.matcher._path
except AttributeError: # tornado<4.5
path_tpl = urlspec._path
path = (path_tpl % params)
if path.count('/') > 1:
path = path.rstrip('/?*')
return path | [
"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 | 37,361 |
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.update(operation)
if not operations:
raise APISpecError(
'Could not find endpoint for urlspec {0}'.format(urlspec),
)
params_method = getattr(urlspec.handler_class, list(operations.keys())[0])
operations.update(self._extensions_from_handler(urlspec.handler_class))
return self.tornadopath2openapi(urlspec, params_method) | 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.update(operation)
if not operations:
raise APISpecError(
'Could not find endpoint for urlspec {0}'.format(urlspec),
)
params_method = getattr(urlspec.handler_class, list(operations.keys())[0])
operations.update(self._extensions_from_handler(urlspec.handler_class))
return self.tornadopath2openapi(urlspec, params_method) | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"urlspec",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"urlspec",
",",
"URLSpec",
")",
":",
"urlspec",
"=",
"URLSpec",
"(",
"*",
"urlspec",
")",
"for",
"operation",
"in",... | 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 | 37,362 |
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: int
:param expires_in: Set the duration of the token in seconds.
(default: 259200 seconds = 72h) 72 hours is the max value.
:type expires_in: int
:param reusable: Defines if the token reusable. (default: false) If set to true, token can be used for multiple apps, until it expires.
:type reusable: bool
Returns a mfa token
:return: return the object if success
:rtype: MFAToken
See https://developers.onelogin.com/api-docs/1/multi-factor-authentication/generate-mfa-token Generate MFA Token documentation
"""
self.clean_error()
try:
url = self.get_url(Constants.GENERATE_MFA_TOKEN_URL, user_id)
data = {
'expires_in': expires_in,
'reusable': reusable
}
response = self.execute_call('post', url, json=data)
if response.status_code == 201:
json_data = response.json()
if json_data:
return MFAToken(json_data)
else:
self.error = self.extract_status_code_from_response(response)
self.error_description = self.extract_error_message_from_response(response)
except Exception as e:
self.error = 500
self.error_description = e.args[0] | 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: int
:param expires_in: Set the duration of the token in seconds.
(default: 259200 seconds = 72h) 72 hours is the max value.
:type expires_in: int
:param reusable: Defines if the token reusable. (default: false) If set to true, token can be used for multiple apps, until it expires.
:type reusable: bool
Returns a mfa token
:return: return the object if success
:rtype: MFAToken
See https://developers.onelogin.com/api-docs/1/multi-factor-authentication/generate-mfa-token Generate MFA Token documentation
"""
self.clean_error()
try:
url = self.get_url(Constants.GENERATE_MFA_TOKEN_URL, user_id)
data = {
'expires_in': expires_in,
'reusable': reusable
}
response = self.execute_call('post', url, json=data)
if response.status_code == 201:
json_data = response.json()
if json_data:
return MFAToken(json_data)
else:
self.error = self.extract_status_code_from_response(response)
self.error_description = self.extract_error_message_from_response(response)
except Exception as e:
self.error = 500
self.error_description = e.args[0] | [
"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.
(default: 259200 seconds = 72h) 72 hours is the max value.
:type expires_in: int
:param reusable: Defines if the token reusable. (default: false) If set to true, token can be used for multiple apps, until it expires.
:type reusable: bool
Returns a mfa token
:return: return the object if success
:rtype: MFAToken
See https://developers.onelogin.com/api-docs/1/multi-factor-authentication/generate-mfa-token Generate MFA Token documentation | [
"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 | 37,363 |
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(char.lower())
last_lower = not current_upper
return "".join(ret) | 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(char.lower())
last_lower = not current_upper
return "".join(ret) | [
"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 | 37,364 |
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
pass
else:
if prefix == self.prefix:
self.counter = max(count, self.counter) | 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
pass
else:
if prefix == self.prefix:
self.counter = max(count, self.counter) | [
"def",
"register_id",
"(",
"self",
",",
"id_string",
")",
":",
"try",
":",
"prefix",
",",
"count",
"=",
"id_string",
".",
"rsplit",
"(",
"\"_\"",
",",
"1",
")",
"count",
"=",
"int",
"(",
"count",
")",
"except",
"ValueError",
":",
"# We don't need to worr... | 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 | 37,365 |
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 with METS namespace."
)
section_id = root.get("ID")
subsections = []
for child in root:
subsection = SubSection.parse(child)
subsections.append(subsection)
return cls(section_id, subsections) | 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 with METS namespace."
)
section_id = root.get("ID")
subsections = []
for child in root:
subsection = SubSection.parse(child)
subsections.append(subsection)
return cls(section_id, subsections) | [
"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 | 37,366 |
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._tree
el = etree.Element(utils.lxmlns("mets") + self.tag, ID=self.id_string)
self.subsections.sort()
for child in self.subsections:
el.append(child.serialize(now))
return el | 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._tree
el = etree.Element(utils.lxmlns("mets") + self.tag, ID=self.id_string)
self.subsections.sort()
for child in self.subsections:
el.append(child.serialize(now))
return el | [
"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 | 37,367 |
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 exceptions.ParseError(
u"AltRecordID got unexpected tag {}; expected {}".format(
element.tag, cls.ALT_RECORD_ID_TAG
)
)
return cls(element.text, id=element.get(u"ID"), type=element.get(u"TYPE")) | 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 exceptions.ParseError(
u"AltRecordID got unexpected tag {}; expected {}".format(
element.tag, cls.ALT_RECORD_ID_TAG
)
)
return cls(element.text, id=element.get(u"ID"), type=element.get(u"TYPE")) | [
"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 | 37,368 |
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(
u"Agent got unexpected tag {}; expected {}".format(
element.tag, cls.AGENT_TAG
)
)
role = element.get(u"ROLE")
if not role:
raise exceptions.ParseError(u"Agent must have a ROLE attribute.")
if role == u"OTHER":
role = element.get(u"OTHERROLE") or role
agent_type = element.get(u"TYPE")
if agent_type == u"OTHER":
agent_type = element.get(u"OTHERTYPE") or agent_type
agent_id = element.get(u"ID")
try:
name = element.find(cls.NAME_TAG).text
except AttributeError:
name = None
notes = [note.text for note in element.findall(cls.NOTE_TAG)]
return cls(role, id=agent_id, type=agent_type, name=name, notes=notes) | 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(
u"Agent got unexpected tag {}; expected {}".format(
element.tag, cls.AGENT_TAG
)
)
role = element.get(u"ROLE")
if not role:
raise exceptions.ParseError(u"Agent must have a ROLE attribute.")
if role == u"OTHER":
role = element.get(u"OTHERROLE") or role
agent_type = element.get(u"TYPE")
if agent_type == u"OTHER":
agent_type = element.get(u"OTHERTYPE") or agent_type
agent_id = element.get(u"ID")
try:
name = element.find(cls.NAME_TAG).text
except AttributeError:
name = None
notes = [note.text for note in element.findall(cls.NOTE_TAG)]
return cls(role, id=agent_id, type=agent_type, name=name, notes=notes) | [
"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 | 37,369 |
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 == "dmdSec":
if self.older is None:
return "original"
else:
return "updated"
if self.subsection in ("techMD", "rightsMD"):
# TODO how to handle ones where newer has been deleted?
if self.newer is None:
return "current"
else:
return "superseded"
return None | 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 == "dmdSec":
if self.older is None:
return "original"
else:
return "updated"
if self.subsection in ("techMD", "rightsMD"):
# TODO how to handle ones where newer has been deleted?
if self.newer is None:
return "current"
else:
return "superseded"
return None | [
"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 | 37,370 |
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 SubSection
:type new_subsection: :class:`SubSection`
"""
if self.subsection != new_subsection.subsection:
raise exceptions.MetsError(
"Must replace a SubSection with one of the same type."
)
# TODO convert this to a DB so have bidirectonal foreign keys??
self.newer = new_subsection
new_subsection.older = self
self.status = None | 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 SubSection
:type new_subsection: :class:`SubSection`
"""
if self.subsection != new_subsection.subsection:
raise exceptions.MetsError(
"Must replace a SubSection with one of the same type."
)
# TODO convert this to a DB so have bidirectonal foreign keys??
self.newer = new_subsection
new_subsection.older = self
self.status = None | [
"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.\"",
")",
"# TODO... | 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 | 37,371 |
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 of root is not mdRef or mdWrap.
"""
subsection = root.tag.replace(utils.lxmlns("mets"), "", 1)
if subsection not in cls.ALLOWED_SUBSECTIONS:
raise exceptions.ParseError(
"SubSection can only parse elements with tag in %s with METS namespace"
% (cls.ALLOWED_SUBSECTIONS,)
)
section_id = root.get("ID")
created = root.get("CREATED", "")
status = root.get("STATUS", "")
child = root[0]
if child.tag == utils.lxmlns("mets") + "mdWrap":
mdwrap = MDWrap.parse(child)
obj = cls(subsection, mdwrap, section_id)
elif child.tag == utils.lxmlns("mets") + "mdRef":
mdref = MDRef.parse(child)
obj = cls(subsection, mdref, section_id)
else:
raise exceptions.ParseError(
"Child of %s must be mdWrap or mdRef" % subsection
)
obj.created = created
obj.status = status
return obj | 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 of root is not mdRef or mdWrap.
"""
subsection = root.tag.replace(utils.lxmlns("mets"), "", 1)
if subsection not in cls.ALLOWED_SUBSECTIONS:
raise exceptions.ParseError(
"SubSection can only parse elements with tag in %s with METS namespace"
% (cls.ALLOWED_SUBSECTIONS,)
)
section_id = root.get("ID")
created = root.get("CREATED", "")
status = root.get("STATUS", "")
child = root[0]
if child.tag == utils.lxmlns("mets") + "mdWrap":
mdwrap = MDWrap.parse(child)
obj = cls(subsection, mdwrap, section_id)
elif child.tag == utils.lxmlns("mets") + "mdRef":
mdref = MDRef.parse(child)
obj = cls(subsection, mdref, section_id)
else:
raise exceptions.ParseError(
"Child of %s must be mdWrap or mdRef" % subsection
)
obj.created = created
obj.status = status
return obj | [
"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 | 37,372 |
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 self.created is not None else now
el = etree.Element(utils.lxmlns("mets") + self.subsection, ID=self.id_string)
if created: # Don't add CREATED if none was parsed
el.set("CREATED", created)
status = self.get_status()
if status:
el.set("STATUS", status)
if self.contents:
el.append(self.contents.serialize())
return el | 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 self.created is not None else now
el = etree.Element(utils.lxmlns("mets") + self.subsection, ID=self.id_string)
if created: # Don't add CREATED if none was parsed
el.set("CREATED", created)
status = self.get_status()
if status:
el.set("STATUS", status)
if self.contents:
el.append(self.contents.serialize())
return el | [
"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 | 37,373 |
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(attr, default_ns=ns, nsmap=nsmap)
attrs[attr] = val
return attrs | 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(attr, default_ns=ns, nsmap=nsmap)
attrs[attr] = val
return attrs | [
"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 | 37,374 |
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(attributes)
for sub_el in lxml_el:
ret.append(_lxml_el_to_data(sub_el, ns, nsmap, snake=snake))
text = lxml_el.text
if text:
ret.append(text)
return tuple(ret) | 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(attributes)
for sub_el in lxml_el:
ret.append(_lxml_el_to_data(sub_el, ns, nsmap, snake=snake))
text = lxml_el.text
if text:
ret.append(text)
return tuple(ret) | [
"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 | 37,375 |
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 | 37,376 |
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]
][0]
except IndexError:
return None
else:
if len(path_parts) > 1:
return data_find(sub_elm, "/".join(path_parts[1:]))
return sub_elm | 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]
][0]
except IndexError:
return None
else:
if len(path_parts) > 1:
return data_find(sub_elm, "/".join(path_parts[1:]))
return sub_elm | [
"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 | 37,377 |
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:
if isinstance(element[1], six.string_types):
schema.append((element[0],))
else:
schema.append(tuple_to_schema(element))
except IndexError:
schema.append((element[0],))
else:
schema.append(element)
return tuple(schema) | 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:
if isinstance(element[1], six.string_types):
schema.append((element[0],))
else:
schema.append(tuple_to_schema(element))
except IndexError:
schema.append((element[0],))
else:
schema.append(element)
return tuple(schema) | [
"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 | 37,378 |
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):
return schema
new_class_name = "PREMIS{}Element".format(schema[0].capitalize())
return type(
new_class_name,
(PREMISElement,),
{"defaults": property(defaults), "schema": property(schema_getter)},
) | 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):
return schema
new_class_name = "PREMIS{}Element".format(schema[0].capitalize())
return type(
new_class_name,
(PREMISElement,),
{"defaults": property(defaults), "schema": property(schema_getter)},
) | [
"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 | 37,379 |
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] == path_parts[0]
)
except IndexError:
return None
if len(path_parts) > 1:
ret = []
for sub_elm in sub_elms:
for x in data_find_all(sub_elm, "/".join(path_parts[1:])):
ret.append(x)
ret = tuple(ret)
else:
ret = sub_elms
if ret and dyn_cls:
cls = generate_element_class(ret[0])
return tuple(cls(data=tuple_) for tuple_ in ret)
return ret | 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] == path_parts[0]
)
except IndexError:
return None
if len(path_parts) > 1:
ret = []
for sub_elm in sub_elms:
for x in data_find_all(sub_elm, "/".join(path_parts[1:])):
ret.append(x)
ret = tuple(ret)
else:
ret = sub_elms
if ret and dyn_cls:
cls = generate_element_class(ret[0])
return tuple(cls(data=tuple_) for tuple_ in ret)
return ret | [
"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 | 37,380 |
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, dict))]
if not texts:
return None
return " ".join(
[
# How should we deal with decoding errors when `x` is binary?
# For now, we're using the ``strict`` mode. Other options here:
# https://docs.python.org/3/library/functions.html#open.
six.ensure_text(x, encoding="utf-8", errors="strict")
for x in texts
]
) | 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, dict))]
if not texts:
return None
return " ".join(
[
# How should we deal with decoding errors when `x` is binary?
# For now, we're using the ``strict`` mode. Other options here:
# https://docs.python.org/3/library/functions.html#open.
six.ensure_text(x, encoding="utf-8", errors="strict")
for x in texts
]
) | [
"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 | 37,381 |
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 ``data`` tree structure.
"""
path = path or []
attributes = attributes or {}
tag_name = schema[0]
data = [tag_name]
if attributes:
data.append(attributes)
new_path = path[:]
new_path.append(tag_name)
root = new_path[0]
possible_paths = ["__".join(new_path), tag_name]
if root != tag_name and tag_name.startswith(root):
possible_paths.append(tag_name.lstrip(root)[1:])
for possible_path in possible_paths:
val = elements.get(possible_path)
if val:
if isinstance(val, (tuple, list)):
data = tuple(val)
else:
if attributes:
data = (tag_name, attributes, val)
else:
data = (tag_name, val)
return tuple(data)
for subschema in schema[1:]:
subel = _generate_data(subschema, elements, path=new_path)
if (not subel) or (subel == subschema):
continue
if all(map(lambda x: isinstance(x, tuple), subel)):
for subsubel in subel:
data.append(subsubel)
elif not el_is_empty(subel):
data.append(subel)
return tuple(data) | 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 ``data`` tree structure.
"""
path = path or []
attributes = attributes or {}
tag_name = schema[0]
data = [tag_name]
if attributes:
data.append(attributes)
new_path = path[:]
new_path.append(tag_name)
root = new_path[0]
possible_paths = ["__".join(new_path), tag_name]
if root != tag_name and tag_name.startswith(root):
possible_paths.append(tag_name.lstrip(root)[1:])
for possible_path in possible_paths:
val = elements.get(possible_path)
if val:
if isinstance(val, (tuple, list)):
data = tuple(val)
else:
if attributes:
data = (tag_name, attributes, val)
else:
data = (tag_name, val)
return tuple(data)
for subschema in schema[1:]:
subel = _generate_data(subschema, elements, path=new_path)
if (not subel) or (subel == subschema):
continue
if all(map(lambda x: isinstance(x, tuple), subel)):
for subsubel in subel:
data.append(subsubel)
elif not el_is_empty(subel):
data.append(subel)
return tuple(data) | [
"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 | 37,382 |
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(subel))
else:
subels_are_empty.append(not bool(subel))
return all(subels_are_empty) | 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(subel))
else:
subels_are_empty.append(not bool(subel))
return all(subels_are_empty) | [
"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 | 37,383 |
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")
if version:
return version
return utils.PREMIS_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")
if version:
return version
return utils.PREMIS_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 | 37,384 |
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(
'PREMIS events of type "{}" have no compression'
" details".format(event_type)
)
parsed_compression_event_detail = self.parsed_event_detail
compression_program = _get_event_detail_attr(
"program", parsed_compression_event_detail
)
compression_algorithm = _get_event_detail_attr(
"algorithm", parsed_compression_event_detail
)
compression_program_version = _get_event_detail_attr(
"version", parsed_compression_event_detail
)
archive_tool = {"7z": "7-Zip"}.get(compression_program, compression_program)
return compression_algorithm, compression_program_version, archive_tool | 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(
'PREMIS events of type "{}" have no compression'
" details".format(event_type)
)
parsed_compression_event_detail = self.parsed_event_detail
compression_program = _get_event_detail_attr(
"program", parsed_compression_event_detail
)
compression_algorithm = _get_event_detail_attr(
"algorithm", parsed_compression_event_detail
)
compression_program_version = _get_event_detail_attr(
"version", parsed_compression_event_detail
)
archive_tool = {"7z": "7-Zip"}.get(compression_program, compression_program)
return compression_algorithm, compression_program_version, archive_tool | [
"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 | 37,385 |
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 events of type "{}" have no encryption'
" details".format(event_type)
)
parsed_encryption_event_detail = self.parsed_event_detail
encryption_program = _get_event_detail_attr(
"program", parsed_encryption_event_detail
)
encryption_program_version = _get_event_detail_attr(
"version", parsed_encryption_event_detail
)
encryption_key = _get_event_detail_attr("key", parsed_encryption_event_detail)
return encryption_program, encryption_program_version, encryption_key | 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 events of type "{}" have no encryption'
" details".format(event_type)
)
parsed_encryption_event_detail = self.parsed_event_detail
encryption_program = _get_event_detail_attr(
"program", parsed_encryption_event_detail
)
encryption_program_version = _get_event_detail_attr(
"version", parsed_encryption_event_detail
)
encryption_key = _get_event_detail_attr("key", parsed_encryption_event_detail)
return encryption_program, encryption_program_version, encryption_key | [
"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 | 37,386 |
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):
if not isinstance(cls, type):
cls = type(cls)
for class_method_name in class_method_names:
try:
class_method = getattr(cls, class_method_name)
if class_method.__self__ is not cls:
return False
except AttributeError:
return False
return True
return test | 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):
if not isinstance(cls, type):
cls = type(cls)
for class_method_name in class_method_names:
try:
class_method = getattr(cls, class_method_name)
if class_method.__self__ is not cls:
return False
except AttributeError:
return False
return True
return test | [
"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 | 37,387 |
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 | 37,388 |
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:
# Django versions < 1.9
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
from backbone.views import BackboneAPIView # This is to prevent a circular import issue
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's backbone module.
try:
import_module('%s.backbone_api' % app)
except:
# Decide whether to bubble up this error. If the app just
# doesn't have an backbone module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'backbone_api'):
raise | 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:
# Django versions < 1.9
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
from backbone.views import BackboneAPIView # This is to prevent a circular import issue
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's backbone module.
try:
import_module('%s.backbone_api' % app)
except:
# Decide whether to bubble up this error. If the app just
# doesn't have an backbone module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'backbone_api'):
raise | [
"def",
"autodiscover",
"(",
")",
":",
"# 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",
... | 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 | 37,389 |
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 | 37,390 |
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:
obj = get_object_or_404(self.queryset(request, **kwargs), id=id)
return self.get_object_detail(request, obj)
else:
return self.get_collection(request, **kwargs) | 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:
obj = get_object_or_404(self.queryset(request, **kwargs), id=id)
return self.get_object_detail(request, obj)
else:
return self.get_collection(request, **kwargs) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"has_get_permission",
"(",
"request",
")",
":",
"return",
"HttpResponseForbidden",
"(",
"_",
"(",
"'You do not have permission t... | 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 | 37,391 |
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.serialize(obj, ['id'] + list(display_fields))
return HttpResponse(self.json_dumps(data), content_type='application/json') | 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.serialize(obj, ['id'] + list(display_fields))
return HttpResponse(self.json_dumps(data), content_type='application/json') | [
"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 | 37,392 |
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.display_fields
if self.paginate_by is not None:
page = request.GET.get('page', 1)
paginator = Paginator(qs, self.paginate_by)
try:
qs = paginator.page(page).object_list
except PageNotAnInteger:
data = _('Invalid `page` parameter: Not a valid integer.')
return HttpResponseBadRequest(data)
except EmptyPage:
data = _('Invalid `page` parameter: Out of range.')
return HttpResponseBadRequest(data)
data = [
self.serialize(obj, ['id'] + list(display_fields)) for obj in qs
]
return HttpResponse(self.json_dumps(data), content_type='application/json') | 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.display_fields
if self.paginate_by is not None:
page = request.GET.get('page', 1)
paginator = Paginator(qs, self.paginate_by)
try:
qs = paginator.page(page).object_list
except PageNotAnInteger:
data = _('Invalid `page` parameter: Not a valid integer.')
return HttpResponseBadRequest(data)
except EmptyPage:
data = _('Invalid `page` parameter: Out of range.')
return HttpResponseBadRequest(data)
data = [
self.serialize(obj, ['id'] + list(display_fields)) for obj in qs
]
return HttpResponse(self.json_dumps(data), content_type='application/json') | [
"def",
"get_collection",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"qs",
"=",
"self",
".",
"queryset",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"display_collection_fields",
":",
"display_fields",
"=",
"self",... | 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 | 37,393 |
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(_('You do not have permission to perform this action.'))
else:
return self.add_object(request) | 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(_('You do not have permission to perform this action.'))
else:
return self.add_object(request) | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
":",
"# No posting to an object detail page",
"return",
"HttpResponseForbidden",
"(",
")",
"else",
":",
"if",
"not",
"self",
".",
"has_add_pe... | Handles post requests. | [
"Handles",
"post",
"requests",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L90-L101 | train | 37,394 |
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 request.raw_post_data)
except ValueError:
return HttpResponseBadRequest(_('Unable to parse JSON request body.'))
form = self.get_form_instance(request, data=data)
if form.is_valid():
if not self.has_add_permission_for_data(request, form.cleaned_data):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
obj = form.save()
# We return the newly created object's details and a Location header with it's url
response = self.get_object_detail(request, obj)
response.status_code = 201
opts = self.model._meta
url_slug = self.url_slug or (
opts.model_name if hasattr(opts, 'model_name') else opts.module_name
)
url_name = 'backbone:%s_%s_detail' % (self.model._meta.app_label, url_slug)
response['Location'] = reverse(url_name, args=[obj.id])
return response
else:
return HttpResponseBadRequest(self.json_dumps(form.errors), content_type='application/json') | 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 request.raw_post_data)
except ValueError:
return HttpResponseBadRequest(_('Unable to parse JSON request body.'))
form = self.get_form_instance(request, data=data)
if form.is_valid():
if not self.has_add_permission_for_data(request, form.cleaned_data):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
obj = form.save()
# We return the newly created object's details and a Location header with it's url
response = self.get_object_detail(request, obj)
response.status_code = 201
opts = self.model._meta
url_slug = self.url_slug or (
opts.model_name if hasattr(opts, 'model_name') else opts.module_name
)
url_name = 'backbone:%s_%s_detail' % (self.model._meta.app_label, url_slug)
response['Location'] = reverse(url_name, args=[obj.id])
return response
else:
return HttpResponseBadRequest(self.json_dumps(form.errors), content_type='application/json') | [
"def",
"add_object",
"(",
"self",
",",
"request",
")",
":",
"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",
"... | Adds an object. | [
"Adds",
"an",
"object",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L103-L133 | train | 37,395 |
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 perform this action.'))
else:
return self.update_object(request, obj)
else:
# No putting on a collection.
return HttpResponseForbidden() | 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 perform this action.'))
else:
return self.update_object(request, obj)
else:
# No putting on a collection.
return HttpResponseForbidden() | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
":",
"obj",
"=",
"get_object_or_404",
"(",
"self",
".",
"queryset",
"(",
"request",
")",
",",
"id",
"=",
"id",
")",
"if",
"not",
"... | Handles put requests. | [
"Handles",
"put",
"requests",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L135-L147 | train | 37,396 |
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, 'body') else request.raw_post_data)
except ValueError:
return HttpResponseBadRequest(_('Unable to parse JSON request body.'))
form = self.get_form_instance(request, data=data, instance=obj)
if form.is_valid():
if not self.has_update_permission_for_data(request, form.cleaned_data):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
form.save()
# We return the updated object details
return self.get_object_detail(request, obj)
else:
return HttpResponseBadRequest(self.json_dumps(form.errors), content_type='application/json') | 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, 'body') else request.raw_post_data)
except ValueError:
return HttpResponseBadRequest(_('Unable to parse JSON request body.'))
form = self.get_form_instance(request, data=data, instance=obj)
if form.is_valid():
if not self.has_update_permission_for_data(request, form.cleaned_data):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
form.save()
# We return the updated object details
return self.get_object_detail(request, obj)
else:
return HttpResponseBadRequest(self.json_dumps(form.errors), content_type='application/json') | [
"def",
"update_object",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"try",
":",
"# backbone sends data in the body in json format",
"# Conditional statement is for backwards compatibility with Django <= 1.3",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
... | Updates an object. | [
"Updates",
"an",
"object",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L149-L169 | train | 37,397 |
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).
"""
defaults = {}
if self.form:
defaults['form'] = self.form
if self.fields:
defaults['fields'] = self.fields
return modelform_factory(self.model, **defaults)(data=data, instance=instance) | 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).
"""
defaults = {}
if self.form:
defaults['form'] = self.form
if self.fields:
defaults['fields'] = self.fields
return modelform_factory(self.model, **defaults)(data=data, instance=instance) | [
"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 | 37,398 |
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 perform this action.'))
else:
return self.delete_object(request, obj)
else:
# No delete requests allowed on collection view
return HttpResponseForbidden() | 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 perform this action.'))
else:
return self.delete_object(request, obj)
else:
# No delete requests allowed on collection view
return HttpResponseForbidden() | [
"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 | 37,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.