sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def get_members_in_state(self, state):
"""return all members of replica set in specific state"""
members = self.run_command(command='replSetGetStatus', is_eval=False)['members']
return [member['name'] for member in members if member['state'] == state] | return all members of replica set in specific state | entailment |
def _authenticate_client(self, client):
"""Authenticate the client if necessary."""
if self.login and not self.restart_required:
try:
db = client[self.auth_source]
if self.x509_extra_user:
db.authenticate(
DEFAULT_SU... | Authenticate the client if necessary. | entailment |
def connection(self, hostname=None, read_preference=pymongo.ReadPreference.PRIMARY, timeout=300):
"""return MongoReplicaSetClient object if hostname specified
return MongoClient object if hostname doesn't specified
Args:
hostname - connection uri
read_preference - default... | return MongoReplicaSetClient object if hostname specified
return MongoClient object if hostname doesn't specified
Args:
hostname - connection uri
read_preference - default PRIMARY
timeout - specify how long, in seconds, a command can take before server times out. | entailment |
def secondaries(self):
"""return list of secondaries members"""
return [
{
"_id": self.host2id(member),
"host": member,
"server_id": self._servers.host_to_server_id(member)
}
for member in self.get_members_in_state(2)
... | return list of secondaries members | entailment |
def arbiters(self):
"""return list of arbiters"""
return [
{
"_id": self.host2id(member),
"host": member,
"server_id": self._servers.host_to_server_id(member)
}
for member in self.get_members_in_state(7)
] | return list of arbiters | entailment |
def hidden(self):
"""return list of hidden members"""
members = [self.member_info(item["_id"]) for item in self.members()]
result = []
for member in members:
if member['rsInfo'].get('hidden'):
server_id = member['server_id']
result.append({
... | return list of hidden members | entailment |
def passives(self):
"""return list of passive servers"""
servers = self.run_command('ismaster').get('passives', [])
return [member for member in self.members() if member['host'] in servers] | return list of passive servers | entailment |
def wait_while_reachable(self, servers, timeout=60):
"""wait while all servers be reachable
Args:
servers - list of servers
"""
t_start = time.time()
while True:
try:
for server in servers:
# TODO: use state code to chec... | wait while all servers be reachable
Args:
servers - list of servers | entailment |
def waiting_member_state(self, timeout=300):
"""Wait for all RS members to be in an acceptable state."""
t_start = time.time()
while not self.check_member_state():
if time.time() - t_start > timeout:
return False
time.sleep(0.1)
return True | Wait for all RS members to be in an acceptable state. | entailment |
def waiting_config_state(self, timeout=300):
"""waiting while real state equal config state
Args:
timeout - specify how long, in seconds, a command can take before server times out.
return True if operation success otherwise False
"""
t_start = time.time()
wh... | waiting while real state equal config state
Args:
timeout - specify how long, in seconds, a command can take before server times out.
return True if operation success otherwise False | entailment |
def check_member_state(self):
"""Verify that all RS members have an acceptable state."""
bad_states = (0, 3, 4, 5, 6, 9)
try:
rs_status = self.run_command('replSetGetStatus')
bad_members = [member for member in rs_status['members']
if member['st... | Verify that all RS members have an acceptable state. | entailment |
def check_config_state(self):
"""Return True if real state equal config state otherwise False."""
config = self.config
self.update_server_map(config)
for member in config['members']:
cfg_member_info = self.default_params.copy()
cfg_member_info.update(member)
... | Return True if real state equal config state otherwise False. | entailment |
def restart(self, timeout=300, config_callback=None):
"""Restart each member of the replica set."""
for member_id in self.server_map:
host = self.server_map[member_id]
server_id = self._servers.host_to_server_id(host)
server = self._servers._storage[server_id]
... | Restart each member of the replica set. | entailment |
def set_settings(self, releases=None, default_release=None):
"""set path to storage"""
super(ReplicaSets, self).set_settings(releases, default_release)
Servers().set_settings(releases, default_release) | set path to storage | entailment |
def create(self, rs_params):
"""create new replica set
Args:
rs_params - replica set configuration
Return repl_id which can use to take the replica set
"""
repl_id = rs_params.get('id', None)
if repl_id is not None and repl_id in self:
raise Replica... | create new replica set
Args:
rs_params - replica set configuration
Return repl_id which can use to take the replica set | entailment |
def primary(self, repl_id):
"""find and return primary hostname
Args:
repl_id - replica set identity
"""
repl = self[repl_id]
primary = repl.primary()
return repl.member_info(repl.host2id(primary)) | find and return primary hostname
Args:
repl_id - replica set identity | entailment |
def remove(self, repl_id):
"""remove replica set with kill members
Args:
repl_id - replica set identity
return True if operation success otherwise False
"""
repl = self._storage.pop(repl_id)
repl.cleanup()
del(repl) | remove replica set with kill members
Args:
repl_id - replica set identity
return True if operation success otherwise False | entailment |
def command(self, rs_id, command, *args):
"""Call a ReplicaSet method."""
rs = self._storage[rs_id]
try:
return getattr(rs, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ReplicaSet %s"
% (comma... | Call a ReplicaSet method. | entailment |
def member_del(self, repl_id, member_id):
"""remove member from replica set (reconfig replica)
Args:
repl_id - replica set identity
member_id - member index
"""
repl = self[repl_id]
result = repl.member_del(member_id)
self[repl_id] = repl
r... | remove member from replica set (reconfig replica)
Args:
repl_id - replica set identity
member_id - member index | entailment |
def member_add(self, repl_id, params):
"""create instance and add it to existing replcia
Args:
repl_id - replica set identity
params - member params
return True if operation success otherwise False
"""
repl = self[repl_id]
member_id = repl.repl_me... | create instance and add it to existing replcia
Args:
repl_id - replica set identity
params - member params
return True if operation success otherwise False | entailment |
def member_command(self, repl_id, member_id, command):
"""apply command(start, stop, restart) to the member of replica set
Args:
repl_id - replica set identity
member_id - member index
command - command: start, stop, restart
return True if operation success o... | apply command(start, stop, restart) to the member of replica set
Args:
repl_id - replica set identity
member_id - member index
command - command: start, stop, restart
return True if operation success otherwise False | entailment |
def member_update(self, repl_id, member_id, params):
"""apply new params to replica set member
Args:
repl_id - replica set identity
member_id - member index
params - new member's params
return True if operation success otherwise False
"""
repl... | apply new params to replica set member
Args:
repl_id - replica set identity
member_id - member index
params - new member's params
return True if operation success otherwise False | entailment |
def key_file(self):
"""Get the path to the key file containig our auth key, or None."""
if self.auth_key:
key_file_path = os.path.join(orchestration_mkdtemp(), 'key')
with open(key_file_path, 'w') as fd:
fd.write(self.auth_key)
os.chmod(key_file_path, ... | Get the path to the key file containig our auth key, or None. | entailment |
def _strip_auth(self, proc_params):
"""Remove options from parameters that cause auth to be enabled."""
params = proc_params.copy()
params.pop("auth", None)
params.pop("clusterAuthMode", None)
return params | Remove options from parameters that cause auth to be enabled. | entailment |
def mongodb_auth_uri(self, hosts):
"""Get a connection string with all info necessary to authenticate."""
parts = ['mongodb://']
if self.login:
parts.append(self.login)
if self.password:
parts.append(':' + self.password)
parts.append('@')
... | Get a connection string with all info necessary to authenticate. | entailment |
def _add_users(self, db, mongo_version):
"""Add given user, and extra x509 user if necessary."""
if self.x509_extra_user:
# Build dict of kwargs to pass to add_user.
auth_dict = {
'name': DEFAULT_SUBJECT,
'roles': self._user_roles(db.client)
... | Add given user, and extra x509 user if necessary. | entailment |
def base_link(rel, self_rel=False):
"""Helper for getting a link document under the API root, given a rel."""
link = _BASE_LINKS[rel].copy()
link['rel'] = 'self' if self_rel else rel
return link | Helper for getting a link document under the API root, given a rel. | entailment |
def all_base_links(rel_to=None):
"""Get a list of all links to be included to base (/) API requests."""
links = [
base_link('get-releases'),
base_link('service'),
server_link('get-servers'),
server_link('add-server'),
replica_set_link('add-replica-set'),
replica_s... | Get a list of all links to be included to base (/) API requests. | entailment |
def server_link(rel, server_id=None, self_rel=False):
"""Helper for getting a Server link document, given a rel."""
servers_href = '/v1/servers'
link = _SERVER_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | Helper for getting a Server link document, given a rel. | entailment |
def all_server_links(server_id, rel_to=None):
"""Get a list of all links to be included with Servers."""
return [
server_link(rel, server_id, self_rel=(rel == rel_to))
for rel in ('delete-server', 'get-server-info', 'server-command')
] | Get a list of all links to be included with Servers. | entailment |
def replica_set_link(rel, repl_id=None, member_id=None, self_rel=False):
"""Helper for getting a ReplicaSet link document, given a rel."""
repls_href = '/v1/replica_sets'
link = _REPLICA_SET_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
... | Helper for getting a ReplicaSet link document, given a rel. | entailment |
def all_replica_set_links(rs_id, rel_to=None):
"""Get a list of all links to be included with replica sets."""
return [
replica_set_link(rel, rs_id, self_rel=(rel == rel_to))
for rel in (
'get-replica-set-info',
'delete-replica-set', 'replica-set-command',
'ge... | Get a list of all links to be included with replica sets. | entailment |
def sharded_cluster_link(rel, cluster_id=None,
shard_id=None, router_id=None, self_rel=False):
"""Helper for getting a ShardedCluster link document, given a rel."""
clusters_href = '/v1/sharded_clusters'
link = _SHARDED_CLUSTER_LINKS[rel].copy()
link['href'] = link['href'].forma... | Helper for getting a ShardedCluster link document, given a rel. | entailment |
def all_sharded_cluster_links(cluster_id, shard_id=None,
router_id=None, rel_to=None):
"""Get a list of all links to be included with ShardedClusters."""
return [
sharded_cluster_link(rel, cluster_id, shard_id, router_id,
self_rel=(rel == rel_to... | Get a list of all links to be included with ShardedClusters. | entailment |
def cleanup_storage(*args):
"""Clean up processes after SIGTERM or SIGINT is received."""
ShardedClusters().cleanup()
ReplicaSets().cleanup()
Servers().cleanup()
sys.exit(0) | Clean up processes after SIGTERM or SIGINT is received. | entailment |
def read_env():
"""return command-line arguments"""
parser = argparse.ArgumentParser(description='mongo-orchestration server')
parser.add_argument('-f', '--config',
action='store', default=None, type=str, dest='config')
parser.add_argument('-e', '--env',
a... | return command-line arguments | entailment |
def setup(releases, default_release):
"""setup storages"""
from mongo_orchestration import set_releases, cleanup_storage
set_releases(releases, default_release)
signal.signal(signal.SIGTERM, cleanup_storage)
signal.signal(signal.SIGINT, cleanup_storage) | setup storages | entailment |
def get_app():
"""return bottle app that includes all sub-apps"""
from bottle import default_app
default_app.push()
for module in ("mongo_orchestration.apps.servers",
"mongo_orchestration.apps.replica_sets",
"mongo_orchestration.apps.sharded_clusters"):
__im... | return bottle app that includes all sub-apps | entailment |
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)... | Wait for the mongo-orchestration server to accept connections. | entailment |
def __init_config_params(self, config):
"""Conditionally enable options in the Server's config file."""
if self.version >= (2, 4):
params = config.get('setParameter', {})
# Set enableTestCommands by default but allow enableTestCommands:0.
params.setdefault('enableTest... | Conditionally enable options in the Server's config file. | entailment |
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[... | return authenticated connection | entailment |
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()
... | Get the version of MongoDB that this Server runs as a tuple. | entailment |
def run_command(self, command, arg=None, is_eval=False):
"""run command on the server
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
return command's result
"""
mode = is_eval and 'eval' or 'co... | run command on the server
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
return command's result | entailment |
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
... | return info about server as dict object | entailment |
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... | start server
return True of False | entailment |
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
... | Send shutdown command and wait for the process to exit. | entailment |
def stop(self):
"""stop server"""
try:
self.shutdown()
except (PyMongoError, ServersError) as exc:
logger.info("Killing %s with signal, shutdown command failed: %r",
self.name, exc)
return process.kill_mprocess(self.proc) | stop server | entailment |
def restart(self, timeout=300, config_callback=None):
"""restart server: stop() and start()
return status of start command
"""
self.stop()
if config_callback:
self.cfg = config_callback(self.cfg.copy())
self.config_path = process.write_config(self.cfg)
... | restart server: stop() and start()
return status of start command | entailment |
def create(self, name, procParams, sslParams={},
auth_key=None, login=None, password=None,
auth_source='admin', timeout=300, autostart=True,
server_id=None, version=None):
"""create new server
Args:
name - process name or path
procParams... | create new server
Args:
name - process name or path
procParams - dictionary with specific params for instance
auth_key - authorization key
login - username for the admin collection
password - password
timeout - specify how long, in seconds, a c... | entailment |
def remove(self, server_id):
"""remove server and data stuff
Args:
server_id - server identity
"""
server = self._storage.pop(server_id)
server.stop()
server.cleanup() | remove server and data stuff
Args:
server_id - server identity | entailment |
def command(self, server_id, command, *args):
"""run command
Args:
server_id - server identity
command - command which apply to server
"""
server = self._storage[server_id]
try:
if args:
result = getattr(server, command)(*args)
... | run command
Args:
server_id - server identity
command - command which apply to server | entailment |
def info(self, server_id):
"""return dicionary object with info about server
Args:
server_id - server identity
"""
result = self._storage[server_id].info()
result['id'] = server_id
return result | return dicionary object with info about server
Args:
server_id - server identity | entailment |
def set_settings(self, releases=None, default_release=None):
"""set path to storage"""
if (self._storage is None or
getattr(self, 'releases', {}) != releases or
getattr(self, 'default_release', '') != default_release):
self._storage = {}
self.relea... | set path to storage | entailment |
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"
... | Get the bin path for a particular release. | entailment |
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', [{}]):
... | Create and start a config replica set. | entailment |
def __init_configsvrs(self, params):
"""create and start config servers"""
self._configsvrs = []
for cfg in params:
# Remove flags that turn on auth.
cfg = self._strip_auth(cfg)
server_id = cfg.pop('server_id', None)
version = cfg.pop('version', se... | create and start config servers | entailment |
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()... | return list of config servers | entailment |
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)} | return first available router | entailment |
def router_add(self, params):
"""add new router (mongos) into existing configuration"""
if self.uses_rs_configdb:
# Replica set configdb.
rs_id = self._configsvrs[0]
config_members = ReplicaSets().members(rs_id)
configdb = '%s/%s' % (
rs_id... | add new router (mongos) into existing configuration | entailment |
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 a list of MongoClients, one for each mongos. | entailment |
def router_remove(self, router_id):
"""remove """
result = Servers().remove(router_id)
del self._routers[ self._routers.index(router_id) ]
return { "ok": 1, "routers": self._routers } | remove | entailment |
def _add(self, shard_uri, name):
"""execute addShard command"""
return self.router_command("addShard", (shard_uri, {"name": name}), is_eval=False) | execute addShard command | entailment |
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... | add new member into existing configuration | entailment |
def member_info(self, member_id):
"""return info about member"""
info = self._shards[member_id].copy()
info['id'] = member_id
info['tags'] = self.tags.get(member_id, list())
return info | return info about member | entailment |
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):
... | remove member from configuration | entailment |
def reset(self):
"""Ensure all shards, configs, and routers are running and available."""
# Ensure all shards by calling "reset" on each.
for shard_id in self._shards:
if self._shards[shard_id].get('isReplicaSet'):
singleton = ReplicaSets()
elif self._shar... | Ensure all shards, configs, and routers are running and available. | entailment |
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... | return info about configuration | entailment |
def cleanup(self):
"""cleanup configuration: stop and remove all servers"""
for _id, shard in self._shards.items():
if shard.get('isServer', False):
Servers().remove(shard['_id'])
if shard.get('isReplicaSet', False):
ReplicaSets().remove(shard['_id... | cleanup configuration: stop and remove all servers | entailment |
def set_settings(self, releases=None, default_release=None):
"""set path to storage"""
super(ShardedClusters, self).set_settings(releases, default_release)
ReplicaSets().set_settings(releases, default_release) | set path to storage | entailment |
def create(self, params):
"""create new ShardedCluster
Args:
params - dictionary with specific params for instance
Return cluster_id
where cluster_id - id which can use to take the cluster from servers collection
"""
sh_id = params.get('id', str(uuid4()))
... | create new ShardedCluster
Args:
params - dictionary with specific params for instance
Return cluster_id
where cluster_id - id which can use to take the cluster from servers collection | entailment |
def remove(self, cluster_id):
"""remove cluster and data stuff
Args:
cluster_id - cluster identity
"""
cluster = self._storage.pop(cluster_id)
cluster.cleanup() | remove cluster and data stuff
Args:
cluster_id - cluster identity | entailment |
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 | add new router | entailment |
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 | remove router from the ShardedCluster | entailment |
def member_info(self, cluster_id, member_id):
"""return info about member"""
cluster = self._storage[cluster_id]
return cluster.member_info(member_id) | return info about member | entailment |
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"
... | Call a ShardedCluster method. | entailment |
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 | remove member from cluster cluster | entailment |
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 | add new member into configuration | entailment |
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))
... | 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 | entailment |
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... | 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
... | entailment |
def find_home_config_files(filetype=['json', 'yaml']):
"""Return configs of ``.vcspull.{yaml,json}`` in user's home directory."""
configs = []
yaml_config = os.path.expanduser('~/.vcspull.yaml')
has_yaml_config = os.path.exists(yaml_config)
json_config = os.path.expanduser('~/.vcspull.json')
ha... | Return configs of ``.vcspull.{yaml,json}`` in user's home directory. | entailment |
def find_config_files(
path=['~/.vcspull'], match=['*'], filetype=['json', 'yaml'], include_home=False
):
"""Return repos from a directory and match. Not recursive.
:param path: list of paths to search
:type path: list
:param match: list of globs to search against
:type match: list
:param f... | Return repos from a directory and match. Not recursive.
:param path: list of paths to search
:type path: list
:param match: list of globs to search against
:type match: list
:param filetype: list of filetypes to search against
:type filetype: list
:param include_home: Include home configura... | entailment |
def load_configs(files, cwd=os.getcwd()):
"""Return repos from a list of files.
:todo: Validate scheme, check for duplciate destinations, VCS urls
:param files: paths to config file
:type files: list
:param cwd: current path (pass down for :func:`extract_repos`
:type cwd: str
:returns: exp... | 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 | entailment |
def detect_duplicate_repos(repos1, repos2):
"""Return duplicate repos dict if repo_dir same and vcs different.
:param repos1: list of repo expanded dicts
:type repos1: list of :py:dict
:param repos2: list of repo expanded dicts
:type repos2: list of :py:dict
:rtype: list of dicts or None
:r... | 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 | entailment |
def in_dir(config_dir=CONFIG_DIR, extensions=['.yml', '.yaml', '.json']):
"""Return a list of configs in ``config_dir``.
:param config_dir: directory to search
:type config_dir: str
:param extensions: filetypes to check (e.g. ``['.yaml', '.json']``).
:type extensions: list
:rtype: list
"""... | Return a list of configs in ``config_dir``.
:param config_dir: directory to search
:type config_dir: str
:param extensions: filetypes to check (e.g. ``['.yaml', '.json']``).
:type extensions: list
:rtype: list | entailment |
def filter_repos(config, repo_dir=None, vcs_url=None, name=None):
"""Return a :py:obj:`list` list of repos from (expanded) config file.
repo_dir, vcs_url and name all support fnmatch.
:param config: the expanded repo config in :py:class:`dict` format.
:type config: dict
:param repo_dir: directory ... | Return a :py:obj:`list` list of repos from (expanded) config file.
repo_dir, vcs_url and name all support fnmatch.
:param config: the expanded repo config in :py:class:`dict` format.
:type config: dict
:param repo_dir: directory of checkout location, fnmatch pattern supported
:type repo_dir: str o... | entailment |
def setup_logger(log=None, level='INFO'):
"""Setup logging for CLI use.
:param log: instance of logger
:type log: :py:class:`Logger`
"""
if not log:
log = logging.getLogger()
if not log.handlers:
channel = logging.StreamHandler()
channel.setFormatter(DebugLogFormatter()... | Setup logging for CLI use.
:param log: instance of logger
:type log: :py:class:`Logger` | entailment |
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):
... | Copy information from src to dest
Every node in the AST has to have line number information. Get
the information from the old stmt. | entailment |
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... | Convert a flask.ext.admin into flask_admin. | entailment |
def transform_flask_from_import(node):
'''Translates a flask.ext from-style import into a non-magical import.
Translates:
from flask.ext import wtf, bcrypt as fcrypt
Into:
import flask_wtf as wtf, flask_bcrypt as fcrypt
'''
new_names = []
# node.names is a list of 2-tuples. Eac... | 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 | entailment |
def transform_flask_from_long(node):
'''Translates a flask.ext.wtf from-style import into a non-magical import.
Translates:
from flask.ext.wtf import Form
from flask.ext.admin.model import InlineFormAdmin
Into:
from flask_wtf import Form
from flask_admin.model import InlineF... | 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 | entailment |
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\... | 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 | entailment |
def _write(self, data):
"""
_write: binary data -> None
Packages the given binary data in an API frame and writes the
result to the serial port
"""
frame = APIFrame(data, self._escaped).output()
self.serial.write(frame) | _write: binary data -> None
Packages the given binary data in an API frame and writes the
result to the serial port | entailment |
def _build_command(self, cmd, **kwargs):
"""
_build_command: string (binary data) ... -> binary data
_build_command will construct a command packet according to the
specified command's specification in api_commands. It will expect
named arguments for all fields other than those ... | _build_command: string (binary data) ... -> binary data
_build_command will construct a command packet according to the
specified command's specification in api_commands. It will expect
named arguments for all fields other than those with a default
value or a length of 'None'.
... | entailment |
def _split_response(self, data):
"""
_split_response: binary data -> {'id':str,
'param':binary data,
...}
_split_response takes a data packet received from an XBee device
and converts it into a dictionary.... | _split_response: binary data -> {'id':str,
'param':binary data,
...}
_split_response takes a data packet received from an XBee device
and converts it into a dictionary. This dictionary provides
names for each segm... | entailment |
def _parse_samples_header(self, io_bytes):
"""
_parse_samples_header: binary data in XBee IO data format ->
(int, [int ...], [int ...], int, int)
_parse_samples_header will read the first three bytes of the
binary data given and will return the number of samples ... | _parse_samples_header: binary data in XBee IO data format ->
(int, [int ...], [int ...], int, int)
_parse_samples_header will read the first three bytes of the
binary data given and will return the number of samples which
follow, a list of enabled digital inputs, a list ... | entailment |
def _parse_samples(self, io_bytes):
"""
_parse_samples: binary data in XBee IO data format ->
[ {"dio-0":True,
"dio-1":False,
"adc-0":100"}, ...]
_parse_samples reads binary data from an XBee device in the IO
... | _parse_samples: binary data in XBee IO data format ->
[ {"dio-0":True,
"dio-1":False,
"adc-0":100"}, ...]
_parse_samples reads binary data from an XBee device in the IO
data format specified by the API. It will then return a
... | entailment |
def send(self, cmd, **kwargs):
"""
send: string param=binary data ... -> None
When send is called with the proper arguments, an API command
will be written to the serial port for this XBee device
containing the proper instructions and data.
This method must be called wi... | send: string param=binary data ... -> None
When send is called with the proper arguments, an API command
will be written to the serial port for this XBee device
containing the proper instructions and data.
This method must be called with named arguments in accordance
with the a... | entailment |
def main():
"""
Run through simple demonstration of alarm concept
"""
alarm = XBeeAlarm('/dev/ttyUSB0', '\x56\x78')
routine = SimpleWakeupRoutine(alarm)
from time import sleep
while True:
"""
Run the routine with 10 second delays
"""
try:
print "W... | Run through simple demonstration of alarm concept | entailment |
def _reset(self):
"""
reset: None -> None
Resets the remote XBee device to a standard configuration
"""
# Analog pin 0
self.hw.remote_at(
dest_addr=self.remote_addr,
command='D0',
parameter='\x02')
# Disengage remote LED, buzz... | reset: None -> None
Resets the remote XBee device to a standard configuration | entailment |
def _set_LED(self, status):
"""
_set_LED: boolean -> None
Sets the status of the remote LED
"""
# DIO pin 1 (LED), active low
self.hw.remote_at(
dest_addr=self.remote_addr,
command='D1',
parameter='\x04' if status else '\x05') | _set_LED: boolean -> None
Sets the status of the remote LED | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.